2 Django projects on one IIS server under the same domain name Posted: 15 Nov 2021 11:06 AM PST My goal is to create a dev environment for a Django project that I inherited. It is hosted on an IIS server and there is currently only a production environment server-side, which is being used by the clients at my university. I want to have a copy of the entire site that I can use for testing purposes. This copy would also use a separate database, which is a copy of the current database with some added tables. My initial thought was to have another branch of the git repo in the wwwroot folder, something like this: wwwroot/prod/django_project_files_here wwwroot/dev/django_project_files_here Both of these would hopefully use the same domain name, but use different urls and views in their respective urls.py and views.py files. For example, app.uniname.edu/home would tap the production version, whereas app.uniname.edu/dev-home would tap the dev version. All of the urls in the prod version would have a similar dev version with "dev" added to the url. I thought I had this all set up, but all of the urls in the second/dev version were 404s. This leads me to believe that the server is not actually using the second copy of the Django application. Granted, I'm not sure that this is a good approach in the first place. But I don't want to mess with the production environment any more than I have to since it is live and used daily. Any and all thoughts would be useful. I am totally new to Django, so the more detail the better! Thank you! |
Convert an ArrayList to Xml on a file Posted: 15 Nov 2021 11:06 AM PST I have to convert an ArrayList to XML and save it on a file but it continue to give me this error with debugging information: Exception in thread main com.thoughtworks.xstream.converters.ConversionException: No converter available ------Debugging information--------- message : No converter available type : istat.ArrayData converter : com.thoughtworks.xstream.converters.reflection.SerializableConverter message[1] : Unable to make private void java.util.ArrayList.readObject(java.io.ObjectInputStream) throws java.io.IOException,java.lang.ClassNotFoundException accessible: module java.base does not "opens java.util" to unnamed module @ec756bd converter[1] : com.thoughtworks.xstream.converters.reflection.ReflectionConverter message[2] : Unable to make field protected transient intjava.util.AbstractList.modCount accessible: module java.base does not opens java.util to unnamed module @ec756bd at com.thoughtworks.xstream.core.DefaultConverterLookup.lookupConverterForType(DefaultConverterLookup.java:88) at com.thoughtworks.xstream.XStream$1.lookupConverterForType(XStream.java:472) at com.thoughtworks.xstream.core.TreeMarshaller.convertAnother(TreeMarshaller.java:48) at com.thoughtworks.xstream.core.TreeMarshaller.convertAnother(TreeMarshaller.java:43) at com.thoughtworks.xstream.core.TreeMarshaller.start(TreeMarshaller.java:82) at com.thoughtworks.xstream.core.AbstractTreeMarshallingStrategy.marshal(AbstractTreeMarshallingStrategy.java:37) at com.thoughtworks.xstream.XStream.marshal(XStream.java:1243) at com.thoughtworks.xstream.XStream.marshal(XStream.java:1232) at com.thoughtworks.xstream.XStream.toXML(XStream.java:1205) at com.thoughtworks.xstream.XStream.toXML(XStream.java:1192) at istat.Running.arrayToXML(Running.java:57) at istat.Running.main(Running.java:73) in particular I have to transform a CSV file into an ArrayList, but my only problem is when I get to the part of converting to XML. This is the main class: package istat; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.StaxDriver; public class Running { private ArrayData list; public ArrayData readFileArray(File f) { FileInputStream fis = null; InputStreamReader isr = null; BufferedReader br = null; try { fis = new FileInputStream(f.getPath()); isr = new InputStreamReader(fis); br = new BufferedReader(isr); list= new ArrayData(); String line = ""; while((line = br.readLine()) != null){ String[] array=line.split(","); if(array[0].equals("groupAge")) { } else { if(array.length==3) { Dati d = new Dati(array[0], array[1], array[2]); list.add(d); } } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return list; } public void arrayToXML() { XStream xstream = new XStream(new StaxDriver()); String xml = xstream.toXML(list); FileWriter fw = null; try { fw = new FileWriter(new File("ArrayList.xml")); fw.write(xml); }catch(Exception e) { e.printStackTrace(); } } public static void main(String[] args) { Running r = new Running(); File f = new File("PersonalComputer.csv"); r.readFileArray(f); r.arrayToXML(); } } I use Eclipse IDE with jdk-17_windows-x64_bin, if it is useful. |
Is itpossible to download files from Docker Volume via Docker Desktop application? Posted: 15 Nov 2021 11:04 AM PST I have created a docker volume as the following: docker create volume test_volume I run my container as the following: docker run --rm -v test_volume:/data collect_symbols:1.0 ... where (in the container) I can access the test_volume via /data . And when my container runs, I save a symbols.csv file as the following in a python script: df.to_csv("/data/symbols.csv", index=False) My container is not a Web server so it just runs a task and then it ends. Then I go to my Docker Desktop application, and go to the Volumes section. I select the test_volume Docker volume, and I see the symbols.csv file there, which is good. On the right hand side of the screen, there are 2 options: "Save As" and "Delete" . (See below image.) Then I click on Save As to check the content of the file, it asks me where to save the file, I pick a location in my local computer and click on Save. But the application throws the following error at this point: It says Cannot destructure property 'filePath' of '(intermediate value)' as it is undefined. Am I doing something wrong here? Or is it not possible to get the file from a Docker volume in this way? If it is the case, what is the purpose of Save As button? |
rjsf with typescript, how can I access formData and event in the onSubmit handler Posted: 15 Nov 2021 11:04 AM PST I am trying to submit a form using a react json schema form. I need to have access to the event object in order to to e.preventDefault(). I am quite new to typescript and cant seem to find the way to access 'event' with typescript. Without typescript it would simply be like this. const onSubmit = ({formData}, e) => console.log("Data submitted: ", formData); ReactDOM.render(( <Form schema={schema} onSubmit={onSubmit} /> ), document.getElementById("app")); Any help on how I can do this would be appreciated. |
Future.delayed execution Posted: 15 Nov 2021 11:06 AM PST Got some example. void main() { A a = A(); transform(a); print(a.str + ' sync'); } Future<void> transform(A a) async { await Future.delayed(Duration(seconds: 3), () => a.str = 'B'); print(a.str + ' async'); } class A { String str = 'A'; } And output: A sync B async And next example void main() { A a = A(); transform(a); print(a.str + ' sync'); } Future<void> transform(A a) async { Function f = () { a.str = 'B'; }; await Future.delayed(Duration(seconds: 3), f()); print(a.str + ' async'); } class A { String str = 'A'; } With output: B sync B async Am i right thinking that f() is executed but just not returned in the second case, so i've got the a.str value modified imidiatly and returned later? Or what the right answer? |
i echoed a form and ajax code to save that particular form using php but what ever i select it saves only the first row data Posted: 15 Nov 2021 11:05 AM PST **This is the page i am working with having issue.The data from the first row of table is getting saved even if i click the save button for below rows.Is there any solution or suggestions for the same. <table> <tr> <th>BED</th> <th>NAME</th> <th>RBS<br>Serum Electrolytes<br>RFT</th> <th>CBC</th> <th>PT,APTT,INR</th> <th>LFT</th> <th>Urine <br>Electrolytes</th> <th>Serum & <br>Urine<br> OSMOLALITY</th> <th>Procalcitonine</th> <th>TFT</th> <th>LIPID<br>Profile</th> <th>Ammonia <br>& Phosphate</th> <th>ACTION</th> </tr> <?php include'connection.php'; $sql = "SELECT id,fname,mname, lname,uhid,bednumber FROM patientlist WHERE status='active' ORDER BY `bednumber` ASC"; $result = mysqli_query($link, $sql); if (mysqli_num_rows($result) > 0) { // output data of each row while($row = mysqli_fetch_assoc($result)) { $id=$row["id"]; $fname=$row["fname"]; $mname=$row["mname"]; $lname=$row["lname"]; $uhid=$row["uhid"]; $bednumber=$row["bednumber"]; $spacer=' '; $name=$fname.$spacer.$mname.$spacer.$lname; echo" <tr> <form> <input type='hidden' name='id' id='id' value='$id'> <input type='hidden' name='fname' id='fname' value='$fname'> <input type='hidden' name='mname' id='mname' value='$mname'> <input type='hidden' name='lname' id='lname' value='$lname'> <input type='hidden' name='uhid' id='uhid' value='$uhid'> <input type='hidden' name='bednumber' id='bednumber' value='$bednumber'> <td>$bednumber</td> <td>$name</td> <td><input type='checkbox' name='rbs' id='rbs' value='RBS,SE,RFT' checked></td> <td><input type='checkbox' name='cbc' id='cbc' value='CBC' ></td> <td><input type='checkbox' name='pt' id='pt' value='PT,APTT,INR' ></td> <td><input type='checkbox' name='lft' id='lft' value='LFT' ></td> <td><input type='checkbox' name='ue' id='ue' value='URINE ELECTROLYTES' ></td> <td><input type='checkbox' name='osmo' id='osmo' value='SERUM & URINE OSMOLALITY' ></td> <td><input type='checkbox' name='procal' id='procal' value='PROCALCITONINE' ></td> <td><input type='checkbox' name='tft' id='tft' value='TFT' ></td> <td><input type='checkbox' name='lipid' id='lipid' value='LIPID PROFILE' ></td> <td><input type='checkbox' name='ammo' id='ammo' value='AMMONIA & PHOSPHATE' ></td> <td> <input id='$id' type='button' class='btn-submit' value='Save' ><input type='reset'></td> </form> </tr> <script> $(document).ready(function() { $('#$id').click(function() { var id = $('#id').val(); var fname = $('#fname').val(); var mname = $('#mname').val(); var lname = $('#lname').val(); var uhid = $('#uhid').val(); var bednumber = $('#bednumber').val(); var rbs = $('#rbs').val(); var cbc = $('#cbc').val(); var pt = $('#pt').val(); var lft = $('#lft').val(); var ue = $('#ue').val(); var osmo = $('#osmo').val(); var procal = $('#procal').val(); var tft = $('#tft').val(); var lipid = $('#lipid').val(); var ammo = $('#ammo').val(); if(id==''||uhid==''||bednumber=='') { alert('Form render error.Demographics return empty.'); return false; } $.ajax({ type: 'POST', url: 'labbookformhandler.php', data: { id: id, fname: fname, mname: mname, lname: lname, uhid: uhid, bednumber: bednumber, rbs: rbs, cbc: cbc, pt: pt, lft: lft, ue: ue, osmo: osmo, procal: procal, tft: tft, lipid: lipid, ammo: ammo }, cache: false, success: function(data) { alert(data); }, error: function(xhr, status, error) { console.error(xhr); } }); }); }); </script> "; } } My goal is to save each row data seperately for that particular save button provided at the end of each row.I tried my maximum.I am not a professional.I am doing it as a hobby.Kindly give me a suggestion so that i can correct it and learn something new. |
PHP JSON decode multiple polygon [duplicate] Posted: 15 Nov 2021 11:04 AM PST I'm having trouble decoding my json, also it seems to be a problem when there is more than one "polygon" inside this is my code so far right now it does not show anything <?php $str = '{"type":"FeatureCollection","features":[{"type":"Feature","properties":{},"geometry":{"type":"Polygon","coordinates":[[[9.78281,54.923985],[9.80341,54.901586],[9.819803,54.901981],[9.83551,54.908396],[9.825897,54.91481],[9.822721,54.927142],[9.807186,54.927931],[9.792767,54.926797],[9.78281,54.923985]]]}},{"type":"Feature","properties":{},"geometry":{"type":"Polygon","coordinates":[[[9.914474,54.930298],[9.901085,54.912343],[9.849243,54.912146],[9.846497,54.928917],[9.890785,54.946865],[9.930267,54.937399],[9.914474,54.930298]]]}}]} '; $polygon = json_decode($str); foreach($polygon->polygon->geometry->coordinates[0] as $coordinates) { echo $coordinates[0].' , '.$coordinates[1].'<br>'; } ?> I want it to display all coordinates for each polygon inside my json |
Fix for "fatal: Authentication failed for" Posted: 15 Nov 2021 11:04 AM PST A lot of us are currently having the issue where we aren't able to push changes to GitHub anymore and getting a fatal: Authentication failed for error. This is because the newest version of VS Code (1.62.2) introduced this bug. |
How can I get the last object in this JSON array? Posted: 15 Nov 2021 11:05 AM PST I'm trying to use player data from a football stats API, but I can't seem to get data for the current season (which can be found in the last object in the array). For some reason I'm only getting data for the third index (code below). .then(data => { //BIO const bio = data['data'][0] const nameValue = bio['fullname'] const imageValue = bio['image_path'] const teamValue = bio['team']['data']['name'] const countryValue = bio['nationality'] const birthdateValue = bio['birthdate'] const heightValue = bio['height'] const positionValue = bio['position']['data']['name'] //STATS const stats = bio['stats']['data']['data'.length - 1] const appearancesValue = stats['appearences'] Here is an image of the JSON data I am trying to access. In this instance I should be getting data from [4] but I'm getting it from [3]. I'm quite inexperienced so I feel like I must be making a silly mistake somewhere! Appreciate any help. |
Stripping characters from a string Posted: 15 Nov 2021 11:04 AM PST I know this probably has an easy solution but I've been looking for ages and found nothing. I know you can strip out white spaces from a string. For example: abc = (" hello everyone ") cba = abc.strip() print (cba) # output would be "hello everyone" with no spaces either side However, is it possible to strip characters out of a string? my first initial guess was: eee = ("hello everyone") rrr = eee.strip(l) In which I was hoping for the output to be "heo world", but I was met with an error instead I have also tried replacing. strip with: remove But still, no luck. Thanks for listening, have a nice day. |
Copying string into set<string> in lowercase? Posted: 15 Nov 2021 11:06 AM PST I have the following small and easy code: int main(int argc, char *argv[]) { std::vector<std::string> in; std::set<std::string> out; in.push_back("Hi"); in.push_back("Dear"); in.push_back("Buddy"); for (const auto& item : in) { *** std::transform(item.begin(),item.end(),item.begin(), ::tolower); *** out.insert(item); } return 0; } I'd like to copy all items of in into out . However, with an in-place lowercase conversion, preferrably without an extra temporary variable. So this is the required content of out at the end: hi dear buddy Please note, const auto& item is fixed, meaning I can't remove the const requirement (this is part of a bigger library, here is over-simplified for demo). How should I do this? (If I remove the "const" modifier, it works, but if modifications are not allowed on item , how can I still insert the item into the set, while also transforming it to lowercase?) |
I need to save tailwind.config.js file for my changes to apply Posted: 15 Nov 2021 11:04 AM PST UPDATE I think vs code bugged out when i updated and saved the scripts in the package.json file, i saved the package.json again and restarted the site and now the problem is gone. i am facing this issue with tailwind css, basically when i apply a classname to an item i need to go to the tailwind.config.js file and save it for my changes to apply, for example, if i put a text-6xl i need to go to my tailwind.config.js file and save it for my changes to apply, now, if i change the classname on that item to text-5xl , the styling will reset and i need to save the tailwind.config.js file again for my changes to apply. This is really frustrating. Here is my code: index.js import React from "react"; import ReactDOM from "react-dom"; import "./index.css"; import App from "./App"; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById("root") ); app.js import React from "react"; import Navbar from "./components/navbar"; function App() { return ( <div className="App"> <Navbar /> </div> ); } export default App; tailwind.config.js module.exports = { purge: ["./src/**/*.{js,jsx,ts,tsx}", "./public/index.html"], darkMode: false, // or 'media' or 'class' theme: { extend: { fontFamily: { poppins: "'Poppins', sans-serif", }, }, }, variants: { extend: {}, }, plugins: [], }; navbar.jsx import React from "react"; const Navbar = () => { return ( <React.Fragment> {/* The Item I Was Talking About... */} <h1 className="text-6xl text-blue-500">Navbar</h1> </React.Fragment> ); }; export default Navbar; index.css /* ./src/index.css */ @tailwind base; @tailwind components; @tailwind utilities; |
Pandas Fill Values Interpolation Posted: 15 Nov 2021 11:04 AM PST I have a pandas frame (df_temperature) composed of {timestamp: temperature} values Time Stamp || Temperature 1/1/2021 01:01:05|| 28 1/1/2021 01:02:05|| 27.9 1/1/2021 01:03:05|| 28 1/1/2021 01:04:05|| 27.8 1/1/2021 01:05:05|| 28.1 . . 31/12/2021 01:05:05|| 3 And I have another data frame (df) that contains a date column. The date value is not exactly similar. Time Stamp || dataCol1 || dataCol2|| dataCol2 1/1/2021 01:01:25|| 558 || 552 || 368 1/1/2021 01:07:05|| 255.9 || 452 || 368 1/1/2021 01:08:05|| 278 || 952 || 358 1/1/2021 01:10:05|| 568 || 562 || 868 1/1/2021 01:20:05|| 281 || 567 || 378 . . 31/12/2021 08:05:05|| 3 || 552 || 368 Now I need to get the temperature given the data frame of df_temp, how can I do that? If I will do that manually I will plot a continuous graph for time vs temperature, then, I will pick the missing value this way. |
Adding functions to string class in c++ Posted: 15 Nov 2021 11:06 AM PST I am using the up to date compiler for gcc. Therefore my code can execute to_String() and stoi() but unfortunately the platform that I am trying to compile my code in has a much previous one and I want to add these two functions into the string class therefore I can use them in my code without any problem.This is one of each example of the errors I get. Cabinet.cpp:93:25: error: 'to_string' was not declared in this scope cout << to_string(id) << " not found"<<endl; LabOrganizer.cpp: In member function 'void LabOrganizer::findClosest(int, int, int)': LabOrganizer.cpp:294:38: error: 'stoi' was not declared in this scope cc = stoi(arr1[i].substr(1,1))-1; |
Oracle : how to subtract two dates and get seconds of the result Posted: 15 Nov 2021 11:05 AM PST I have created oracle NVL function which would subtract start and end time column (Datatype is Date) and give the result However I am not getting correct output as I am unable to ceil to highest value For eg - Start time- 9:13:07 End time -9:13:18 Actual Output - 10 seconds Expected Output- 11 seconds I think ceil function will resolve the issue, but I do not know how/where to add that Query NVL(TO_CHAR(opa.start_time,'YYYY/MM/DD HH24:MI:SS'),' ')"Start Time", NVL(TO_CHAR(opa.end_time,'YYYY/MM/DD HH24:MI:SS'),' ')"End Time", NVL(dbms_lob.substr(oprm.message,4000),' ') AS "Messages", NVL(REGEXP_SUBSTR (CAST(opa.end_time AS TIMESTAMP) - CAST(opa.start_time AS TIMESTAMP), '\d{2}:\d{2}:\d{2}'),' ') AS duration |
New web hosting breaks webcam that worked with old web hosting Posted: 15 Nov 2021 11:05 AM PST I have a hobby weather website that I recently moved from HostGator web hosting to Hostinger web hosting. Everything works well at the new host with the exception of my webcam. The cam page on the website uses a script that pulls a static image from my camera, displays it, and then updates it every 1 seconds... this worked very well with the old hosting and fails with the new hosting. I'm a complete dunce when it comes to coding and don't know how to fix this issue. I do suspect however that the issue is the way SSL is forced for everything on my new host. The URL the script is pulling from my camera is: http://172.100.163.136/webcapture.jpg?command=snap&channel=1&user=viewer&password That URL works in a browser as http but not https Here's the script I'm using: <script type="text/javascript"> // <![CDATA[ var refreshrate = 1; // seconds between refresh var image = "http://172.100.163.136/webcapture.jpg?command=snap&channel=1&user=viewer&password"; // image name var imgwidth = 665; // image width var imgheight = 374; // image height var imgalt = "WebCam Image"; var imgtitle = "header=[WebCam Image] body=[WebCam Image Automatically Updated Every 1-2 Seconds] delay=[500]"; function refresh() { document.images["pic"].src = image + "?" + new Date(); setTimeout('refresh()', refreshrate * 500); } document.write('<img src="' + image + '" alt="' + imgalt + '" title="' + imgtitle + '" name="pic" id="pic" width="' + imgwidth + '" height="' + imgheight + '" style="border:1px dashed gray;"/>'); if(document.images)window.onload=refresh; // ]]> </script> Does anyone have an idea on how to fix this? |
Having trouble with the array address in C? Posted: 15 Nov 2021 11:05 AM PST I create a dynamic array name listProduct, now I want to read data from file and insert to this array. But I have some trouble with parse array to function, I know I parse wrong address :( but I can not solve this problem. Some one can help me(I spent 3 hours on it, but it didn't work).Thanks for all in main() int main(int argc, char** argv) { struct Product* listProduct = (struct Product*) malloc(sizeof(struct Product) * 1); printf("address of listProduct in main: %d \n", &listProduct); int length = 0; char fileName[] = "products.txt"; length = readDataFromFile(&listProduct,length,fileName); printf("address of listProduct in main after insert \n: %d \n", &listProduct); printf("length in main %d \n", length); printf("start for in main \n"); int i; for(i =0; i < length; i++){ printf("%s \n", listProduct[i].tenSanPham); } printf("end for in main \n"); return 0; } in readFile function int readDataFromFile(struct Product* listProduct,int length, char fileName[]){ printf("address of listProduct in readData: %d \n", (*listProduct)); FILE *fp; char buff[1024]; struct Product product; fp = fopen(fileName, "r"); while(fgets(buff, 255, (FILE*)fp) != NULL){ product = convertStringToProduct(buff); printf("IN readData: %s \n", product.tenSanPham); insertProduct(product, &(*listProduct), length); length++; } fclose(fp); int i ; printf("\n\ncheck value in listProduct after insert\n"); for(i = 0; i < length; i++){ printf("IN FOREACH readData: %s \n", listProduct[i].tenSanPham); } printf("read done \n"); return length; } in insert function void insertProduct(struct Product product, struct Product** listProduct, int length) { printf("addres of listProduct in insert %d \n", (*listProduct)); printf("Product In Insert: %s \n", product.tenSanPham); *listProduct = (struct Product*) realloc(listProduct, sizeof(struct Product) * (length+1)); (*listProduct)[length] = product; printf("Get product inserted: %s length: %d \n", (*listProduct)[length].tenSanPham, length); printf("insert done!\n"); } console: address of listProduct in main: 6487568 address of listProduct in readData: 6486368 IN readData: FOOD 1 addres of listProduct in insert 1905632 Product In Insert: FOOD 1 -------------------------------- Process exited after 0.5239 seconds with return value 3221226356 Press any key to continue . . . |
Stop flex child from expanding, when it overflows add scroll bar [duplicate] Posted: 15 Nov 2021 11:05 AM PST I have a website that looks something like this: https://codepen.io/Username123T/pen/GRvwmoq <div class="Nav"></div> <div class="Content"> <div class="Sidebar"> <div class="Card"> </div> </div> <div class="Input"></div> </div> </div> .App { background-color: black; display: flex; flex-direction: column; flex: 1; } .Content { display: flex; flex: 1; background-color: turquoise; } .Nav { flex: 1; } .Sidebar { flex: 1; background-color: thistle; display: flex; } .Card { margin: 3vh; flex: 1; background-color: blue; overflow: auto; } .Input { background-color: violet; flex: 1; } body { height: 100vh; display: flex; flex-direction: row; } And when i add Content that is bigger than the box, it should add a Scroll bar. But instead it just expands like this: https://codepen.io/Username123T/pen/PoKxmGW <div class="Nav"></div> <div class="Content"> <div class="Sidebar"> <div class="Card"> <p>d</p> <p>d</p> <p>d</p> <p>d</p> <p>d</p> <p>d</p> <p>d</p> <p>d</p> <p>d</p> <p>d</p> <p>d</p> <p>d</p> </div> </div> <div class="Input"></div> </div> I would prefer not to set a max-height, or only if it is relativ to its parent (Sidebar). Any help is welcome, thanks in advance. I took a look at One flex/grid item sets the size limit for siblings But i am not quite sure how this is supposed to help me. I added flex-basis: 0px; flex-grow: 1; https://codepen.io/Username123T/pen/oNeQevd to the sibling (Input) but it doesnt do anything... Did i miss anything? |
how to get value from 1 side of 1 to n with condition on n side of relation in ef core Posted: 15 Nov 2021 11:06 AM PST i have two classes like below class order { int Id; List<Payment> Paymants; } class Payment { int Id; string Token; int OrderId; Order Order; } and i use ef core code first approach. tokens are unique and want to get related order from DB by token related to it. I've tried var order = _dbContext.Orders .Include(i=>i.Payments) .SingleAsync(b=>b.Payments.Contains(c=>c.vandarToken == Token)); But it didn't work. |
How to combine data by two-year intervals in R Posted: 15 Nov 2021 11:04 AM PST I want to create a new column in the data frame that categorizes length in two-year intervals by region and I am stumped on how. I included sample data below with years 2010, 2011, 2012, 2013, 2014, 2015, and 2019. I want to: - Find the first year in each region.
- Set the year as a starting point for two-year intervals in each region.
- If the region has data available for both years in the interval, label the two-year interval as "year1 - year2" in the new column.
- If not, leave the year as is in the new column.
I think step 1 could use min and steps 3-4 could use if_else but I am not sure how to execute step 2. Thank you! df <- data.frame(matrix(nrow=500, ncol=0)) set.seed(1) df$region <- sample(c("North", "Central", "South"), size = nrow(df), replace = TRUE) df$year <- sample(c("2010", "2011", "2012", "2013", "2014", "2015", "2019"), size = nrow(df), replace = TRUE) df$length <- sample(1:100, size = nrow(df), replace=TRUE) |
Autoloading of classes of a local TYPO3 extension Posted: 15 Nov 2021 11:05 AM PST In my following composer.json I am requiring extensions, which are in the same Git repository as the whole project. So I add in the repositories section and later I do composer req vendor/site_package:@dev in order to require my local extension. Now I realized, that some classes of the extension are not autoloaded. Do I need to additional add the autoload part as shown below in the composer.json of the project? { "name": "site-package", "description": "Base composer.json", "repositories": [ { "type": "path", "url": "./packages/*" } ], "require": { "typo3/cms-backend": "^10.4", "typo3/cms-belog": "^10.4", "typo3/cms-beuser": "^10.4", "typo3/cms-core": "^10.4", ... "vendor/site_package": "@dev", "georgringer/news": "^8", ... }, "autoload": { "classmap": [ "public/typo3conf/ext/site_package/Classes" ], "psr-4": { "Vendor\\SitePackage\\": "public/typo3conf/ext/site_package/Classes" } }, "extra": { "typo3/cms": { "root-dir": "public", "web-dir": "public" } }, "config": { "vendor-dir": "vendor", "bin-dir": "bin" }, "scripts": { "typo3-cms-scripts": [ "typo3cms install:generatepackagestates", "typo3cms install:fixfolderstructure" ], "post-autoload-dump": [ "@typo3-cms-scripts" ] } } In ext:site_package I have the following autoload section as well: "autoload": { "psr-4": { "Vendor\\SitePackage\\": "Classes", } }, Do I need both? Why? |
Test freezes after applying bypass for browser tab issue Posted: 15 Nov 2021 11:04 AM PST Due to cypress inability to access browser tab, I have to use one of recommended bypasses: my test changes target attribute of the link from target: "_blank" to target: "_self" . After clicking the link the target page is open in the same tab as expected, but the test freezes without any notification and stops working. The browser window can't be closed by clicking "X" button. The test can be interrupted with Stop button of the Test runner only. Is there any solution for this issue? I need to add something important to this question: it looks like the reason is that after the page is open and verified by the test, the next test following it tries to navigate back to the page from where the previous test was redirected to the target page and this cy.visit() command freezes this test. Visually there is no any navigation occurred. |
Cannot use "type":"module" in Node 14 on shared server Posted: 15 Nov 2021 11:05 AM PST I'm trying to setup my nodejs app in a node environment on namecheap's shared hosting. Their server uses node version 14.18.1 and when I try to run the app, I get this error: internal/modules/cjs/loader.js:1102 throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath); ^ Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /home/*****/test2/index.js require() of ES modules is not supported. require() of /home/*****/test2/index.js from /usr/local/lsws/fcgi-bin/lsnode.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules. Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /home/*****/test2/package.json. I was able to reproduce this error with this simple express app: import express from "express"; const app = express(); const PORT = process.env.PORT || 8000; app.get("/", (req, res) => { res.send("Hello world"); }); app.listen(PORT, () => console.log(`Server is running on PORT ${PORT}`)); and the following package.json { "name": "test", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "type": "module", "author": "", "license": "ISC", "dependencies": { "express": "^4.17.1" } } if I run the same app without "type":"module" and use require(express), it works. In my local machine, using the same node version, I can run both es6 and non es6 version without any errors. What am I missing? Thank you |
PHP - Testing array for multiple conditions Posted: 15 Nov 2021 11:05 AM PST I have a multidimensional array that is filtered resulting in an array: $arr_sublineitems[$lineitem_data[$j]['SubLineItems'][$k]['SubLineItemId']]=[ 'VendorId' => $lineitem_data[$j]['SubLineItems'][$k]['VendorId'], 'Quantity' => $lineitem_data[$j]['SubLineItems'][$k]['Quantity'], 'SellPrice' => $lineitem_data[$j]['SubLineItems'][$k]['SellPrice'], 'FreightSell' => $lineitem_data[$j]['SubLineItems'][$k]['FreightSell'], 'NetPrice' => $lineitem_data[$j]['SubLineItems'][$k]['NetPrice'], 'FreightNet' => $lineitem_data[$j]['SubLineItems'][$k]['FreightNet'], 'Taxable' => $lineitem_data[$j]['SubLineItems'][$k]['Taxable'], 'ProjectId' => $project_id, 'Total_Sell' => ($lineitem_data[$j]['SubLineItems'][$k]['SellPrice'] * $lineitem_data[$j]['SubLineItems'][$k]['Quantity']) Within the resulting array, I need to aggregate Total_Sell based on taxable/non-taxable and >0 or <0 (i.e. a charge or a credit) by vendor prior to moving to database. Each vendor could meet all four possible conditions if they have multiple items in $arr_sublineitems so I'm thinking to parse $arr_sublineitems into 4 arrays using the VendorId as key for the new arrays: $arr_sublineitem_taxable, $arr_sublineitems_nontaxable, $arr_sublineitems_taxable_credit and $arr_sublineitems_nontaxable_credit. Each vendor could have a row in one or more of the parsed arrays, but only one row per array. If tried this with foreach and multiple if/else but I need to exit when a condition is met and the values from $arr_sublineitems is added to one of the parsed arrays... I cannot figure out how to make this happen using break/continue or a switch statement... My current code is: foreach($arr_sublineitems as $key => $item){ if($item['Total_Sell'] > 0 && $item['Taxable']){ if(!isset($arr_sublineitems[$item]['VendorId'])){ $arr_sublineitems_taxable[$item]['VendorId'] = array('FreightSell' => $item['FreightSell'], 'Total_Sell' => $item['VendorId']['Total_Sell'] ); }else{ $arr_sublineitems_taxable[$item]['VendorId']['Total_Sell']+= $item['Total_Sell']; } } if($item['Total_Sell'] > 0 && !($item['Taxable'])){ if(!isset($arr_sublineitems[$key]['VendorId'])){ $arr_sublineitems_nontaxable[$key]['VendorId'] = array('FreightSell' => $item['FreightSell'], 'Total_Sell' => $item['Total_Sell']); }else{ $arr_sublineitems_nontaxable[$key]['VendorId']['Total_Sell']+= $item['Total_Sell']; } } if($item['Total_Sell'] < 0 && $item['Taxable']){ if(!isset($arr_sublineitems[$key])){ $arr_sublineitems_taxable_credit[$key] = array('FreightSell' => $item['FreightSell'], 'Total_Sell_Credit' => $item['Total_Sell']); }else{ $arr_sublineitems_nottaxable_credit[$key]['Total_Sell_Credit']+= $item['Total_Sell_Credit']; } } if($item['Total_Sell'] < 0 && !($item['Taxable'])){ if(!isset($arr_sublineitems[$key])){ $arr_sublineitems_taxable_credit[$key] = array('FreightSell' => $item['FreightSell'], 'Total_Sell_Credit' => $item['Total_Sell']); }else{ $arr_sublineitems_nottaxable_credit[$key]['Total_Sell_Credit']+= $item['Total_Sell_Credit']; } } } I have edited my code to this:``` foreach($arr_sublineitems as $key => $item) { $vendor_id = $item['VendorId']; if (!array_key_exists($vendor_id, $arr_vendor_totals)) { if ($item['Taxable'] && $item['Total_Sell'] > 0) { $arr_vendor_totals[$vendor_id] = array('FreightSell' => $item['FreightSell'], 'Total_Taxable' => $item['Total_Sell']); } elseif ($item['Taxable'] && $item['Total_Sell'] < 0) { $arr_vendor_totals[$vendor_id]['Total_Credit_Taxable'] = array('FreightSell' => $item['FreightSell'], 'Total_Taxable' => $item['Total_Sell']); } elseif (!$item['Taxable'] && $item['Total_Sell'] > 0) { $arr_vendor_totals[$vendor_id]['Total_NonTaxable'] = array('FreightSell' => $item['FreightSell'], 'Total_Taxable' => $item['Total_Sell']); } elseif (!$item['Taxable'] && $item['Total_Sell'] < 0) { $arr_vendor_totals[$vendor_id]['Total_Credit_NonTaxable'] = array('FreightSell' => $item['FreightSell'], 'Total_Taxable' => $item['Total_Sell']); } continue; } if (array_key_exists($vendor_id, $arr_vendor_totals)){ if ($item['Taxable'] && $item['Total_Sell'] > 0) { $arr_vendor_totals[$vendor_id]['Total_Taxable'] += $item['Total_Sell']; } elseif ($item['Taxable'] && $item['Total_Sell'] < 0) { $arr_vendor_totals[$vendor_id]['Total_Credit_Taxable'] += $item['Total_Credit_Taxable']; } elseif (!$item['Taxable'] && $item['Total_Sell'] > 0) { $arr_vendor_totals[$vendor_id]['Total_NonTaxable'] += $item['Total_NonTaxable']; } elseif (!$item['Taxable'] && $item['Total_Sell'] < 0) { $arr_vendor_totals[$vendor_id]['Total_Credit_NonTaxable'] += $item['Total_Credit_NonTaxable']; } } }``` Thank you for looking at this... I'm going to look at @Riggs Folly's solution also. |
Sending emails using next.js API after creating a user ERR_HTTP_HEADERS_SENT Posted: 15 Nov 2021 11:06 AM PST I'm currently creating users using the next.js API, however, I now want to send emails using sendgrid. I have this setup, however, I get the following event - compiled successfully in 661 ms (254 modules) Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at new NodeError (internal/errors.js:322:7) at ServerResponse.setHeader (_http_outgoing.js:561:11) at DevServer.renderError (/Users/ellisbrookes/Documents/Ellis-Developement/node_modules/next/dist/server/next-server.js:1628:17) at DevServer.run (/Users/ellisbrookes/Documents/Ellis-Developement/node_modules/next/dist/server/dev/next-dev-server.js:431:35) at runMicrotasks (<anonymous>) at processTicksAndRejections (internal/process/task_queues.js:95:5) at async DevServer.handleRequest (/Users/ellisbrookes/Documents/Ellis-Developement/node_modules/next/dist/server/next-server.js:305:20) { code: 'ERR_HTTP_HEADERS_SENT' } error - Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client error - uncaughtException: Error [ERR_STREAM_WRITE_AFTER_END]: write after end The user is being created and the email is being sent, however, I'm not sure why I'm getting this error. Here is what I have form wise in terms of the onSubmit api call const res = await fetch('/api/auth/register', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) and here is what I have in the api/auth/register file import connectDB from '../../../lib/mongodb' import bcrypt from 'bcrypt' import User from '../../../models/user' const mail = require('@sendgrid/mail'); mail.setApiKey(process.env.SENDGRID_API_KEY); const handler = async (req, res) => { // check if user exists in the database already const emailExists = await User.findOne({ email: req.body.email }) if (emailExists) return res.status(400).send("Email already exists") // hash password const salt = await bcrypt.genSalt(10) const hash = await bcrypt.hash(req.body.password, salt) var user = new User({ firstname: req.body.firstname, lastname: req.body.lastname, username: req.body.username, email: req.body.email, password: hash }) try { user = await user.save(); res.send({ user: user._id }) } catch { res.status(400).send(err) } // nodemailer const message = ` First Name: ${req.body.firstname}\r\n Last Name: ${req.body.lastname}\r\n Username: ${req.body.username}\r\n Email: ${req.body.email} `; const data = { to: `${req.body.email}`, from: 'Ellis Development <hello@ebrookes.dev>', subject: `Welcome ${req.body.firstname} ${req.body.lastname} to Ellis Development`, text: message, html: message.replace(/\r\n/g, '<br />') }; await mail.send(data); res.status(200).json({ status: 'OK' }); } export default connectDB(handler) As mentioned before the user is being created and the email is being sent, but not sure why I'm getting the ERR_HEADERS error. |
Record has Long.MIN_VALUE timestamp (= no timestamp marker). Is the time characteristic set to 'ProcessingTime' Posted: 15 Nov 2021 11:05 AM PST I have following topology env.setTimeCharacteristic(TimeCharacteristic.EventTime); DataStream<Event> eventSource = env.addSource(createEventSource(kafkaTopic, kafkaBroker)) .assignTimestampANdWatermarks(WatermarksStrategy .<Event>forBoundedOutOfOrderness(Duration.ofSecond(20))) .keyBy((event)->event.getId().toString()); eventSource.window(TumblingEventTimeWindows.of(Time.seconds(20)) .process(new MyProcessWindowFunction()) .name("TESTING"); public static class MyProcessWindowFunction extends ProcessWindowFunction<Event,Event, String, TimeWindow> { @Override public void process(String key, Context context, Iterable<Event> input, Collector<Event> out) { logger.info("currentTime = {}, currentWatermark = {} ",context.currentProcessingTime(), context.currentWatermark()); long count = 0; for( Event in : input) { count++; out.collect(in); } logger.info(" count = {}",count); } } public static FlinkKafkaConsumer<Event> createEventSource(String topic, String broker) { Properties prop = new Properties(); prop.setProperty("bootstrap.servers",broker); prop.setproperty("group.id", "flinkPOCtest"); FlinkKafkaConsumer<Event> kafkaConsumer = new FlinkKafkaConsumer<>(topic, new AvroDeserializer<Event>(Event.class), prop); return kafkaConsumer; } Adding env.setTimeCharacteristic(TimeCharacteristic.EventTime); Along with calling assignTimestampANdWatermarks on stream did solve the problem reported in earlier post where I was getting Record has Long.MIN_VALUE timestamp (= no timestamp marker). Is the time characteristic set to 'ProcessingTime' |
In dpc++ malloc_shared can we share a buffer between 2 gpus Posted: 15 Nov 2021 11:05 AM PST In sycl/dpc++ malloc_shared I am aware that it is possible to create a buffer which could be shared between the host and a single gpu with the below function. void* malloc_shared(size_t num_bytes, const sycl::device& dev, const sycl::context& ctxt); or int *data = malloc_shared<int>(N, q); I wanted to know if something existed that could possibly share the same data/buffer across multiple gpus? Something like the below int *data = malloc_shared<int>(N, q1,q2); |
Terminal will not open in Visual Studio Code Posted: 15 Nov 2021 11:05 AM PST OS is linux. Opening the terminal produces this error: The terminal process failed to launch: Path to shell executable "bash" is not a file of a symlink. The path to bash is correct in settings.json and the $PATH variable. This is Visual Studio Code version 1.57.1. rolling back to an earlier version fixes the issue, so I made a bug report. |
Main process exited code=exited status=203/exec Posted: 15 Nov 2021 11:06 AM PST I followed a flask+uwsgi+nginx tutorial like this. However it comes with error: Warning: The unit file, source configuration file or drop-ins of myproject.service changed on disk. Run 'systemctl daem-reload' to reload units> ● myproject.service - uWSGI instance to serve myproject Loaded: loaded (/etc/systemd/system/myproject.service; enabled; vendor preset: disabled) Active: failed (Result: exit-code) since Tue 2020-05-05 18:26:18 AEST; 20min ago Main PID: 38304 (code=exited, status=203/EXEC) May 05 18:26:18 ip-10-86-162-214.ap-southeast-2.compute.internal systemd[1]: Started uWSGI instance to serve myproject。 May 05 18:26:18 ip-10-86-162-214.ap-southeast-2.compute.internal systemd[1]: myproject.service: Main process exited code=exited status=203/exec May 05 18:26:18 ip-10-86-162-214.ap-southeast-2.compute.internal systemd[1]: myproject.service: Failed with result 'exit-code'. /etc/systemd/system/myproject.service [Unit] Description=uWSGI instance to serve myproject After=network.target [Service] User=rh WorkingDirectory=/home/rh/myproject Environment="PATH=/home/rh/myproject/myprojectenv/bin" ExecStart=/home/rh/myproject/myprojectenv/bin/uwsgi --ini myproject.ini [Install] WantedBy=multi-user.target The "rh" is the user I used. |
How can I write this query using TypeORM createQueryBuilder? Posted: 15 Nov 2021 11:06 AM PST I want to write this raw query using the TypeORM createQueryBuilder . How can I achieve this? SELECT * FROM Location l INNER JOIN LocationType t ON l.TypeId = t.Id LEFT JOIN Location p ON l.ParentId = p.Id LEFT JOIN (SELECT locationId, SUM(Units) TotalUnits FROM ItemInventory GROUP BY LocationId) qty ON l.Id = qty.LocationId` |
No comments:
Post a Comment