qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,317,356
<p>I have defined a parameter called CODE.</p> <p>CODE is a list of strings, for instance 'Car', 'Bike', 'Boat' and so on.</p> <p>I need to execute SQL Querys that have the following pattern:</p> <pre><code>Select * from Table when CODE=Car </code></pre> <p>Or</p> <pre><code>Select * from Table when CODE=Bike </code></pre> <p>and so on.</p> <p>Is it posible to use the parameter directly in the Query?</p> <p>Like somenthing thike the following:</p> <pre><code>Select * from Table when CODE = Parameter CODE? </code></pre> <p>Edit:</p> <p>Im using Python to make the Query. Variable CODE comes from a colomn of a DataFrame as it follows:</p> <pre><code>import pandas as pd import pyodbc CODE=Table1['CODE'] dbconnection=pyodbc.connect('Driver={SQL Server};' 'Server=XXXX,1234;' 'Database=AAAA;' 'Trusted_Connection=yes;') sql=&quot;SELECT * FROM DATABASE WHERE CODE = 'Bike'&quot; Selection=pd.read_sql(sql,dbconnection) </code></pre>
[ { "answer_id": 74317385, "author": "George", "author_id": 20345563, "author_profile": "https://Stackoverflow.com/users/20345563", "pm_score": 3, "selected": true, "text": "AND" }, { "answer_id": 74321541, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 0, "selected": false, "text": "=INDEX(IF(B2:B=\"\",,IF((B2:B=TRUE)*(D2:D>50), (E2:E*0.85), E2:E))\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11789082/" ]
74,317,378
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#myElement { width: 50px; height: 300px; background: linear-gradient(0deg, #4a94cd, #fe49a6); display: flex; flex-direction: column; justify-content: space-evenly; } #myBar { width: 100%; height: 10px; background: #000; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="myElement"&gt; &lt;div id="myBar"&gt;&lt;/div&gt; &lt;div id="myBar"&gt;&lt;/div&gt; &lt;div id="myBar"&gt;&lt;/div&gt; &lt;div id="myBar"&gt;&lt;/div&gt; &lt;div id="myBar"&gt;&lt;/div&gt; &lt;div id="myBar"&gt;&lt;/div&gt; &lt;div id="myBar"&gt;&lt;/div&gt; &lt;div id="myBar"&gt;&lt;/div&gt; &lt;div id="myBar"&gt;&lt;/div&gt; &lt;div id="myBar"&gt;&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>How can I make the black part transparent to show the background behind,The background won't always be white,maybe a picture,The color part is a gradient of the whole</p>
[ { "answer_id": 74317385, "author": "George", "author_id": 20345563, "author_profile": "https://Stackoverflow.com/users/20345563", "pm_score": 3, "selected": true, "text": "AND" }, { "answer_id": 74321541, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 0, "selected": false, "text": "=INDEX(IF(B2:B=\"\",,IF((B2:B=TRUE)*(D2:D>50), (E2:E*0.85), E2:E))\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19312839/" ]
74,317,383
<p>I have <code>setLocale</code> function like below that I wrote in main.java file.</p> <p>How can I get the current <code>Locale</code> in the <code>setLocale</code> function?</p> <p>I use the <code>Locale</code> value to be able to include an &quot;if-else&quot; condition in another java file. This mean, I have 2 tables of data, when the language in <code>setLocale</code> function is English, I will select the table for English, and when I choose another language, I will select the table for that language.</p> <pre><code>// main.java public void setLocale(String lang) { Locale myLocale = new Locale(lang); Resources res = getResources(); DisplayMetrics dm = res.getDisplayMetrics(); Configuration conf = res.getConfiguration(); conf.locale = myLocale; res.updateConfiguration(conf, dm); Intent refresh = new Intent(this, MainActivity2.class); finish(); startActivity(refresh); } </code></pre>
[ { "answer_id": 74317514, "author": "Annamalai Palanikumar", "author_id": 6784846, "author_profile": "https://Stackoverflow.com/users/6784846", "pm_score": 0, "selected": false, "text": "public Locale getLocale() {\n return getResources().getConfiguration().locale;\n}\n" }, { "answer_id": 74324560, "author": "BigBeef", "author_id": 20304512, "author_profile": "https://Stackoverflow.com/users/20304512", "pm_score": 1, "selected": false, "text": "if (getLocale().getLanguage().equals(new Locale(\"en\").getLanguage())) {\n // do something here\n}\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20379528/" ]
74,317,387
<p>I want to sum all elements in a matrix <code>A</code> with dimension <code>n</code> times <code>n</code>. The matrix is symmetric and has 0s on the diagonal. The fastest way to do so that I have found is simply <code>sum(A)</code>. However this seems wasteful since it doesn't use the fact that I only need to calculate the lower triangle of the matrix. However, <code>sum(tril(A, -1))</code> is significantly slower, and <code>sum(A[i, j] for i = 1:n-1 for j = i+1:n)</code> even more so. Is there a more efficient way to sum the matrix?</p> <p>Edit: The solution by @AboAmmar performs well. Here is code (with summing the diagonal separately, something that can be removed if there is only zeros on the diagonal) to compare:</p> <pre><code>using BenchmarkTools using LinearAlgebra function sum_triu(A) m, n = size(A) @assert m == n s = zero(eltype(A)) for j = 2:n @simd for i = 1:j-1 s += @inbounds A[i,j] end end s *= 2 for i = 1:n s += A[i, i] end return s end N = 1000 A = Symmetric(rand(0:9,N,N)) A -= diagm(diag(A)) @btime sum(A) @btime 2 * sum(tril(A)) @btime sum_triu(A) </code></pre>
[ { "answer_id": 74317579, "author": "Sundar R", "author_id": 8127, "author_profile": "https://Stackoverflow.com/users/8127", "pm_score": 1, "selected": false, "text": "2 * sum(LowerTriangular(A))\n" }, { "answer_id": 74318954, "author": "AboAmmar", "author_id": 3943170, "author_profile": "https://Stackoverflow.com/users/3943170", "pm_score": 3, "selected": true, "text": "sum" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4182596/" ]
74,317,392
<p>I have an array. As far as I know array keys are integers in javascript.</p> <pre class="lang-js prettyprint-override"><code>const array1 = ['a', 'b', 'c']; </code></pre> <p>When I get and log keys I get an array of integers.</p> <pre class="lang-js prettyprint-override"><code>console.log([...array1.keys()]); // Outputs=&gt; [0, 1, 2] </code></pre> <p>But in a for...in loop keys are string. But why and is there a way to type cast for integer keys?</p> <pre class="lang-js prettyprint-override"><code>for (const key in array1) { console.log(&quot;Type of key &quot;+key+&quot; is &quot;+ typeof key); } /* outputs: Type of key 0 is string Type of key 1 is string Type of key 2 is string */ </code></pre>
[ { "answer_id": 74317487, "author": "Felix Kling", "author_id": 218196, "author_profile": "https://Stackoverflow.com/users/218196", "pm_score": 3, "selected": true, "text": "Number" }, { "answer_id": 74317508, "author": "Lakruwan Pathirage", "author_id": 12383492, "author_profile": "https://Stackoverflow.com/users/12383492", "pm_score": 1, "selected": false, "text": "parseInt()" }, { "answer_id": 74317649, "author": "Shreyansh Gupta", "author_id": 18046485, "author_profile": "https://Stackoverflow.com/users/18046485", "pm_score": 1, "selected": false, "text": "//actually the for in loop is used for objects , as the key in objects is always assigned as string whether you put a string or not\n\nconst obj = {a:1,b:2}\nfor (key in obj){\n console.log('typeof ',key,' is ',typeof key)\n console.log('valueof ',key,' is ',obj[key])\n}\n \n// Now because you used array the keys are indexes of the array so there for 0, 1, 2 .. and so on are logged as string not integers \n \n //to solve this problem\n \nconst array = ['a','b','c']\n\n//1. one can use the for each loop and used the index in the parameter\n\narray.forEach((elem,index) => {\n console.log(elem,' ',index)\n});\n\nconsole.log(`2. use a for range loop`)\n\nfor (let i = 0; i < array.length; i++) {\n console.log(array[i],i)\n}\n\n//3. using the same for key loop convert the key into index\n\nfor (const key in array) {\n console.log(\"Type of key \"+Number(key)+\" is \"+ typeof Number(key));\n }" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2572967/" ]
74,317,445
<p>I'm trying to select several 1000 rows from a remote database (where I can change nothing). I have (string) IDs to filter the needed data rows but I'm having performance issues.</p> <p>Using a simple sql select I can retrieve the data in ~4 s. `</p> <pre><code>SELECT myid, column2 FROM view1@remotedb WHERE myid IN ( '1', '2', '3' ) </code></pre> <p>`</p> <p>Since I need to select several thousand rows I'm using a local database for the IDs to select. `</p> <pre><code>SELECT /*+DRIVING_SITE(V1)*/ myid, column2 FROM view1@remotedb v1, localdb t1 WHERE v1.myid = t1.myid; </code></pre> <p>` Unfortunately even for only 3 IDs in t1 the execution time increases to 3 min. Using driving_site or not makes no difference. Is there a way to increase the performance?</p>
[ { "answer_id": 74317518, "author": "sankar", "author_id": 4017098, "author_profile": "https://Stackoverflow.com/users/4017098", "pm_score": 0, "selected": false, "text": "SELECT\n myid,\n column2\nFROM\n view1@remotedb\nWHERE\n myid IN ( SELECT myid from localdb)\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11290225/" ]
74,317,473
<p><a href="https://en.wikipedia.org/wiki/Context_switch" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Context_switch</a></p> <blockquote> <p>In computing, a context switch is the process of storing the state of a process or thread, so that it can be restored and resume execution at a later point, and then restoring a different, previously saved, state.[1] This allows multiple processes to share a single central processing unit (CPU), and is an essential feature of a multitasking operating system.</p> <p>The precise meaning of the phrase &quot;context switch&quot; varies. In a multitasking context, it refers to the process of storing the system state for one task, so that task can be paused and another task resumed. A context switch can also occur as the result of an interrupt, such as when a task needs to access disk storage, freeing up CPU time for other tasks. Some operating systems also require a context switch to move between user mode and kernel mode tasks. The process of context switching can have a negative impact on system performance.[2]: 28</p> </blockquote> <p><strong>and the second question 2):</strong></p> <p>If I understand correctly, <strong>on a single-core processor ONLY ONE thread can be executed AT A TIME</strong> (that's why context switching is INEVITABLE), so there is virtual parallelism.</p> <p><strong>So, is it completely SAFE not to use locks (like mutex, etc) to access shared resources (variables) on single-core processors (there are almost no such processors nowadays but take it as a &quot;theoretical&quot; question)? Thanks</strong></p>
[ { "answer_id": 74318038, "author": "Dan Getz", "author_id": 3004881, "author_profile": "https://Stackoverflow.com/users/3004881", "pm_score": 2, "selected": false, "text": "read variable\nmutate value\nwrite result back to variable\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19551894/" ]
74,317,484
<p>I am building a DevOps pipeline through yaml file which triggers a build for PR. Structure below:</p> <pre><code>pr: - dev2 stages: - stage: PR condition: and(eq(variables['Build.Reason'], 'PullRequest') displayName: prBuild jobs: - job: DowndSecureFile </code></pre> <p>if i raise a PR for the first time to the <strong>dev2</strong> branch from another branch ex: <strong>dev3</strong> it triggers.</p> <p>Another build fails to trigger in this case: If the PR is not yet merged: and I have made additional commit to <strong>dev3</strong> then build is <strong>skipped</strong> for the PR I understand this is due to this condition where Build.Reason changes to CI:</p> <pre><code> condition: eq(variables['Build.Reason'], 'PullRequest') </code></pre> <p>But I am trying to do, that if a pr is still open and if i put additional commits to the PR branch <strong>dev3</strong>, i need to trigger a build again for that PR. Is there any suitable condition for that? or</p> <p><strong>Update:</strong></p> <p>I am using github enterprise, for the repository, no Azure Repos is used here.</p> <p>should i do something else?</p> <p>Can anyone help me here? Thanks.</p>
[ { "answer_id": 74318038, "author": "Dan Getz", "author_id": 3004881, "author_profile": "https://Stackoverflow.com/users/3004881", "pm_score": 2, "selected": false, "text": "read variable\nmutate value\nwrite result back to variable\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20263192/" ]
74,317,495
<p>In linux to create nested folders, irrespective of the intermediate folders exist or not can be done using the below command.</p> <pre><code>mkdir -p /home/user/some_non_existing_folder1/some_non_existing_folder2/somefolder </code></pre> <p>Similar to this i want to create a nested folder structure in S3 and place my files there later</p> <p>how can i do this using <code>aws cli</code></p>
[ { "answer_id": 74318038, "author": "Dan Getz", "author_id": 3004881, "author_profile": "https://Stackoverflow.com/users/3004881", "pm_score": 2, "selected": false, "text": "read variable\nmutate value\nwrite result back to variable\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2897115/" ]
74,317,496
<p>Is it possible to have one line assignments in structs as an example:</p> <pre><code>pub struct Pipe { texture: Texture2D, x: f32, y: f32, } </code></pre> <p>Instead have something like</p> <pre><code>pub struct Pipe { texture: Texture2D, (x, y): (f32, f32) } </code></pre> <p>Also an approach like this is not what I want, because I want to access the variable like Pipe.pos.x or Pipe.x instead of pipe.pos.0:</p> <pre><code>pub struct Pipe { texture: Texture2D, pos: (f32, f32) } </code></pre>
[ { "answer_id": 74317932, "author": "Oussama Gammoudi", "author_id": 3978243, "author_profile": "https://Stackoverflow.com/users/3978243", "pm_score": 0, "selected": false, "text": "pub struct Pipe {\n texture: Texture2D,\n pos: (f32, f32),\n}\n\nlet pipe = Pipe {\n texture: new_texture, \n pos: (10.5, 24.0),\n};\n\nprintln!(\"x position is {}\", pipe.pos.0);\nprintln!(\"y position is {}\", pipe.pos.1);\n\n// to access using x and y you can create a trait\ntrait XYAccessor {\n fn x(&self) -> f32\n fn y(&self) -> f32\n}\n\n// implement trait for the tuple\nimpl XYAccessor for (f32,f32) {\n fn x(&self) -> f32 {\n self.0\n }\n fn y(&self) -> f32 {\n self.1\n }\n}\n\n// then you can use .x() and .y()\nprintln!(\"x position is {}\", pipe.pos.x());\nprintln!(\"y position is {}\", pipe.pos.y());\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18784628/" ]
74,317,498
<p>Be the following DataFrame in pandas.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>country</th> <th>ctry</th> <th>city</th> <th>cty</th> <th>other</th> <th>important</th> <th>other_important</th> <th>other_1</th> </tr> </thead> <tbody> <tr> <td>France</td> <td>France</td> <td>París</td> <td>París</td> <td>blue</td> <td>019210</td> <td>0011119</td> <td>red</td> </tr> <tr> <td>Spain</td> <td>Spain</td> <td>Madrid</td> <td>Barcelona</td> <td>blue</td> <td>1211</td> <td>0019210</td> <td>blue</td> </tr> <tr> <td>Germany</td> <td>Spain</td> <td>Barcelona</td> <td>Barcelona</td> <td>white</td> <td>019210</td> <td>1212</td> <td>red</td> </tr> <tr> <td>France</td> <td>UK</td> <td>Bourdeux</td> <td>London</td> <td>blue</td> <td>019210</td> <td>91021</td> <td>red</td> </tr> </tbody> </table> </div> <p>I have to fill with NaN the information of the unimportant columns (other) in case <code>country != ctry || city != cty</code>. Dataframe result:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>country</th> <th>ctry</th> <th>city</th> <th>cty</th> <th>other</th> <th>important</th> <th>other_important</th> <th>other_1</th> </tr> </thead> <tbody> <tr> <td>France</td> <td>France</td> <td>París</td> <td>París</td> <td>blue</td> <td>019210</td> <td>0011119</td> <td>red</td> </tr> <tr> <td>Spain</td> <td>Spain</td> <td>Madrid</td> <td>Barcelona</td> <td>NaN</td> <td>1211</td> <td>0019210</td> <td>NaN</td> </tr> <tr> <td>Germany</td> <td>Spain</td> <td>Barcelona</td> <td>Barcelona</td> <td>NaN</td> <td>019210</td> <td>1212</td> <td>NaN</td> </tr> <tr> <td>France</td> <td>UK</td> <td>Bourdeux</td> <td>London</td> <td>NaN</td> <td>019210</td> <td>91021</td> <td>NaN</td> </tr> </tbody> </table> </div> <p>Finally I delete the country and city columns.</p> <pre><code> df = df.drop(['country', 'city'], axis=1) </code></pre> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ctry</th> <th>cty</th> <th>other</th> <th>important</th> <th>other_important</th> <th>other_1</th> </tr> </thead> <tbody> <tr> <td>France</td> <td>París</td> <td>blue</td> <td>019210</td> <td>0011119</td> <td>red</td> </tr> <tr> <td>Spain</td> <td>Barcelona</td> <td>NaN</td> <td>1211</td> <td>0019210</td> <td>NaN</td> </tr> <tr> <td>Spain</td> <td>Barcelona</td> <td>NaN</td> <td>019210</td> <td>1212</td> <td>NaN</td> </tr> <tr> <td>UK</td> <td>London</td> <td>NaN</td> <td>019210</td> <td>91021</td> <td>NaN</td> </tr> </tbody> </table> </div> <p>I would be grateful if the columns that I want to leave as NaN, could be indicated in a string vector with the name of each one. <code>['other', 'other_1']</code></p>
[ { "answer_id": 74317522, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 2, "selected": true, "text": "DataFrame.loc" }, { "answer_id": 74317560, "author": "Naveed", "author_id": 3494754, "author_profile": "https://Stackoverflow.com/users/3494754", "pm_score": 0, "selected": false, "text": "# list of columns\ncols=['other', 'other_1']\n\n# use mask to make NaN when condition is met\ndf[cols] = df[cols].mask(df['country'].ne(df['ctry']) | df['city'].ne(df['cty']))\n\n# drop columns\ndf = df.drop(['country', 'city'], axis=1)\ndf\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18396935/" ]
74,317,543
<p>I have a dataframe that's very large (let's say 8 rows by 10,000 columns) that is filled with strings. I want to convert each unique string to a number and replace it with it.</p> <p>For example, if I had a dataframe:</p> <pre><code> X1 X2 X3 1 cat mouse rabbit 2 dog cat, dog dog </code></pre> <p>I'd like to convert it to:</p> <pre><code> X1 X2 X3 1 1 2 3 2 4 5 4 </code></pre> <p>Note the combined label of &quot;cat,dog&quot; gets its own unique number. The actual numbering of each string is irrelevant as I'm doing this for an inter-rater reliability calculation.</p> <p>Short of me getting all the unique elements, assigning them a number and replacing is there a more elegant way to do this?</p> <p>Also, if a value in an element is blank, eg &quot;&quot;, it should be converted to an NA in the numeric DF.</p>
[ { "answer_id": 74317601, "author": "Maël", "author_id": 13460602, "author_profile": "https://Stackoverflow.com/users/13460602", "pm_score": 4, "selected": true, "text": "match" }, { "answer_id": 74317633, "author": "Robert Hacken", "author_id": 2094893, "author_profile": "https://Stackoverflow.com/users/2094893", "pm_score": 1, "selected": false, "text": "factor" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1357015/" ]
74,317,567
<p>I need to create a comments board for an assignment that takes user inputs and displays them below the input field in a comments section, This is where I have gotten to but I am not sure how to finish off the script so that the inputted data is displayed</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function sendMessage() { let emailjs = email.value; email.value = "" let handlejs = handle.value; handle.value = "" let messagejs = message.value; message.value = "" let userobject = { emailjs, handlejs, messagejs }; let array = []; array.push(userobject); comments.innerHTML = 'this is the bit I need help with'; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"&gt; &lt;meta http-equiv="X-UA-Compatible" content="ie=edge"&gt; &lt;title&gt;Comment section&lt;/title&gt; &lt;link rel="stylesheet" href="style.css"&gt; &lt;script src="code.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="alert"&gt; Your message has been sent&lt;/div&gt; &lt;h1&gt; Spartak Swinford FC - Comment Section&lt;/h1&gt; &lt;form id="contactform" action="#"&gt; &lt;fieldset&gt; &lt;legend&gt;Message&lt;/legend&gt; &lt;span&gt;Email : &lt;/span&gt;&lt;input type="text" id="email" placeholder="Email"&gt;&lt;br&gt; &lt;span&gt;Handle: &lt;/span&gt;&lt;input type="text" id="handle" placeholder="Handle"&gt;&lt;br&gt; &lt;span style="position: absolute;"&gt;&lt;/span&gt; &lt;textarea name="message" id="message" cols="50" rows="8"&gt;Enter your message...&lt;/textarea&gt; &lt;br&gt; &lt;button id="btn" type="button" onclick="sendMessage()"&gt;Post&lt;/button&gt; &lt;div id="clientSideContent"&gt;&lt;/div&gt; &lt;/fieldset&gt; &lt;/form&gt; &lt;h1&gt;Comments&lt;/h1&gt; &lt;div id="comments"&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74317819, "author": "Ankit", "author_id": 19757319, "author_profile": "https://Stackoverflow.com/users/19757319", "pm_score": 0, "selected": false, "text": "li" }, { "answer_id": 74318701, "author": "Mr. Polywhirl", "author_id": 1762224, "author_profile": "https://Stackoverflow.com/users/1762224", "pm_score": 1, "selected": false, "text": "<form id=\"contactform\" onSubmit=\"postComment(event, this)\" autocomplete=\"off\">\n <!-- form items -->\n <button type=\"submit\">Post</button>\n</form>\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20256918/" ]
74,317,614
<p>Stateless Widget</p> <pre><code>CustomButton.build( label: 'login', onPressed: () { presenter.login(context,username,password); }, ); </code></pre> <p>Presenter class (where we have all the logic)</p> <pre><code>class Presenter { Future&lt;void&gt; login(BuildContext context,String username, String password) async { showDialog(context); var result = await authenticate(username,password); int type = await getUserType(result); Navigator.pop(context); // to hide progress dialog if(type == 1){ Navigator.pushReplacementNamed(context, 'a'); }else if(type == 2){ Navigator.pushReplacementNamed(context, 'b'); } } Future&lt;int&gt; getUserType(User user) async { //.. some await function return type; } } </code></pre> <p>Now we are getting <strong>Do not use BuildContexts across async gaps.</strong> lint error on our presenter wile hiding the dialog and screen navigation.</p> <p>What is the best way to fix this lint.</p>
[ { "answer_id": 74317819, "author": "Ankit", "author_id": 19757319, "author_profile": "https://Stackoverflow.com/users/19757319", "pm_score": 0, "selected": false, "text": "li" }, { "answer_id": 74318701, "author": "Mr. Polywhirl", "author_id": 1762224, "author_profile": "https://Stackoverflow.com/users/1762224", "pm_score": 1, "selected": false, "text": "<form id=\"contactform\" onSubmit=\"postComment(event, this)\" autocomplete=\"off\">\n <!-- form items -->\n <button type=\"submit\">Post</button>\n</form>\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4646166/" ]
74,317,616
<p>In a form, I'm forming a string with java script and collecting it's result into a SQLite table the state of 12 checkboxes, under a string of binary values like &quot;000011111100&quot; .</p> <pre><code>&lt;script&gt; const checkboxes = [...document.querySelectorAll('input[type=checkbox]')]; function RegMD() { document.getElementById(&quot;mounths&quot;).textContent = checkboxes.reduce((a, b) =&gt; a + (b.checked ? 1 : 0), &quot;&quot;); document.getElementById(&quot;results&quot;).innerHTML = document.getElementById(&quot;mounths&quot;).innerHTML; } &lt;/script&gt; </code></pre> <p>After the string is formed is sent through POST method into a SQLite table. Calling back this value is also simple because I can echo it with a PHP script (more or less like this)</p> <pre><code>&lt;?php try { $conn = new PDO('sqlite:db/MyDatabase.db'); $conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn-&gt;prepare(&quot;SELECT months FROM MyTable where MyID='this_value'&quot;); $stmt-&gt;execute(); $data = $stmt-&gt;fetchcolumn(PDO::FETCH_ASSOC); if ( !empty($data) ) { echo $data['mounths']; } } else { echo &quot;Record missing!&quot;; } } catch(PDOException $e) { echo &quot;Error: &quot; . $e-&gt;getMessage(); } $conn = null; ?&gt; </code></pre> <p>This value is not needed to be visible, I can hide it or not echo it at all. But I want to use it in a different way. When I recall this value, I want it to break it into it's individual values of &quot;0&quot; and &quot;1&quot; and according to these values, I want to color 12 DIVs (or table cells) into some predefined colors:</p> <pre><code>$color1 = red; $color2 = white; </code></pre> <p>I know that for reaching my goal, I should do something like from here, and somehow adapting it: <a href="https://stackoverflow.com/questions/43030312/change-row-background-color-based-on-cell-value">Change Row background color based on cell value</a></p> <pre><code> $data( function(value){ if(value == &quot;0&quot;){ html += '&lt;div style=&quot;background-color: red;&quot;&gt;'+some_content+'&lt;/div&gt;'; } else{ html += '&lt;div style=&quot;background-color: white;&quot;&gt;'+some_content+'&lt;/div&gt;'; } }); </code></pre> <p>I found some similar questions (coloring and splitting) in these articles, but nothing I could apply just by myself: <a href="https://stackoverflow.com/questions/49744802/php-display-different-image-based-on-mysql-row-result">PHP - Display different image based on mysql row result</a> <a href="https://stackoverflow.com/questions/59406804/split-into-different-rows-based-on-condition">Split into different rows based on condition</a> <a href="https://stackoverflow.com/questions/51176415/sql-split-row-into-multiple-based-on-month">SQL - Split Row into multiple based on month</a> <a href="https://stackoverflow.com/questions/47221519/different-color-of-row-based-on-result-in-php">different color of row based on result in PHP</a> <a href="https://stackoverflow.com/questions/21616535/split-sql-rows-array-into-multiple-arrays-based-on-date">Split SQL rows array into multiple arrays based on date</a> <a href="https://stackoverflow.com/questions/56873423/split-a-div-background-color-based-on-index-in-ng-repeat">Split a div background color based on $index in ng-repeat</a></p> <p>Can you help me to achieve something like this: <a href="https://i.stack.imgur.com/ZFe44.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZFe44.png" alt="mounths of the year" /></a> starting from the step where I recall the string value from the database (database column name &quot;mounths&quot;) ?</p> <pre><code>&lt;p hidden&gt;&lt;?php echo $data['mounths']; ?&gt;&lt;/p&gt; </code></pre> <p>If hiding the result is not necessary is even better.</p>
[ { "answer_id": 74317819, "author": "Ankit", "author_id": 19757319, "author_profile": "https://Stackoverflow.com/users/19757319", "pm_score": 0, "selected": false, "text": "li" }, { "answer_id": 74318701, "author": "Mr. Polywhirl", "author_id": 1762224, "author_profile": "https://Stackoverflow.com/users/1762224", "pm_score": 1, "selected": false, "text": "<form id=\"contactform\" onSubmit=\"postComment(event, this)\" autocomplete=\"off\">\n <!-- form items -->\n <button type=\"submit\">Post</button>\n</form>\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20144069/" ]
74,317,629
<p>I have a requirement where I have to keep the button to be disabled initially and enable it only when the length of my input is 10.</p> <pre><code>&lt;div class=&quot;form-group&quot;&gt; &lt;label for=&quot;MSISDN_Value&quot; class=&quot;m-r-10&quot;&gt;MSISDN:&lt;/label&gt; &lt;input type=&quot;number&quot; onkeyPress=&quot;if(this.value.length === 10) return false;&quot; [(ngModel)]=&quot;MSISDN_Value&quot; id=&quot;MSISDN_Value&quot; name=&quot;MSISDN_Value&quot; class=&quot;form-control display-inline-block width70p m-b-5&quot;&gt; &lt;/div&gt; &lt;div class=&quot;form-group&quot;&gt; &lt;button class=&quot;btn btn-primary m-l-65&quot; type=&quot;submit&quot; [disabled]=&quot;true&quot;&gt;Search&lt;/button&gt; &lt;/div&gt; </code></pre> <p>I tried <code>[disabled] = &quot;MSISDN_Value.length !== 10&quot;</code> but it did not work, there are many solutions that disable buttons, but I couldn't find any solution which enables buttons in Angular5.</p>
[ { "answer_id": 74317819, "author": "Ankit", "author_id": 19757319, "author_profile": "https://Stackoverflow.com/users/19757319", "pm_score": 0, "selected": false, "text": "li" }, { "answer_id": 74318701, "author": "Mr. Polywhirl", "author_id": 1762224, "author_profile": "https://Stackoverflow.com/users/1762224", "pm_score": 1, "selected": false, "text": "<form id=\"contactform\" onSubmit=\"postComment(event, this)\" autocomplete=\"off\">\n <!-- form items -->\n <button type=\"submit\">Post</button>\n</form>\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13542280/" ]
74,317,635
<p>I just started studying front-end development and I'm struggling with a node.js error. Typing 'npm start' in my VSCode terminal used to work fine for simple tutorial projects with just an index.html, script.js, and style.css file. (without a package.json file)</p> <p>However after trying out React for the first time, 'npm start' now doesn't work anymore in my other non-React projects. At first it was giving me an error that it was missing the package.json (which it didn't need before?) but after trying to fix it with help of googling I now got to a point where it's giving me the error: Missing script: &quot;start&quot;.</p> <p>How can I run node without creating package.json files for every small tutorial project I've made previously, or without turning them into React apps? Also why is this happening? Did installing React-native create dependencies of some sort?</p> <p>Thanks in advance!</p> <p>I already tried reinstalling node.js and tried different versions. Also tried deleting package-lock.json. It still works for React apps, just not with simpler native javascript apps.</p>
[ { "answer_id": 74317674, "author": "node_modules", "author_id": 6060964, "author_profile": "https://Stackoverflow.com/users/6060964", "pm_score": 2, "selected": true, "text": "package.json" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20416915/" ]
74,317,647
<p>I have some data attributes on buttons that I need to send as content to a div when those buttons are clicked. A part of my code until now is this:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function getDiscount() { var buttons = document.querySelectorAll(".form-button"); buttons.forEach(function(item, index) { item.addEventListener('click', function() { var discount = getDiscount(this); }); }); function getDiscount(clicked_element) { var val = clicked_element.getAttribute("data-discount"); return val; } };</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="discount__Topics"&gt; &lt;div&gt;&lt;strong class="discount-amount"&gt;50&lt;/strong&gt;%&lt;/div&gt; &lt;div class="offers"&gt; &lt;button class="form-button" data-discount="38"&gt;Offer 1&lt;/button&gt; &lt;button class="form-button" data-discount="50"&gt;Offer 2&lt;/button&gt; &lt;button class="form-button" data-discount="22"&gt;Offer 3&lt;/button&gt; &lt;button class="form-button" data-discount="88"&gt;Offer 4&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="discount__Topics"&gt; &lt;div&gt;&lt;strong class="discount-amount"&gt;60&lt;/strong&gt;%&lt;/div&gt; &lt;div class="offers"&gt; &lt;button class="form-button" data-discount="12"&gt;Offer 1&lt;/button&gt; &lt;button class="form-button" data-discount="32"&gt;Offer 2&lt;/button&gt; &lt;button class="form-button" data-discount="44"&gt;Offer 3&lt;/button&gt; &lt;button class="form-button" data-discount="55"&gt;Offer 4&lt;/button&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>I'm just not seeing how to change the html with attribute when it's clicked and how to have two sets of buttons or more on the same page.</p> <p>Hope someone can help. Many thanks</p> <p>UPDATE: Now the code is running properly but im having troubles with getting multiples div's with multiple buttons working. I've created a for.Each wic logs my div correctly but im not beeing able to have the working properly.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var discounters = document.querySelectorAll(".discount__Topics"); discounters.forEach((index) =&gt; { console.log(index) var buttons = document.querySelectorAll(".form-button"); buttons.forEach(function (item) { item.addEventListener('click', function(){ var discount = getDiscount(this); let span = document.querySelector('.discount-amount') span.innerHTML = '&lt;strong&gt;' + discount+ '&lt;/strong&gt;' }); }); function getDiscount(clicked_element) { var val = clicked_element.getAttribute("data-discount"); return val; } });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="discount__Topics"&gt; &lt;div&gt;&lt;strong class="discount-amount"&gt;38&lt;/strong&gt;%&lt;/div&gt; &lt;div class="offers"&gt; &lt;button class="form-button" data-discount="38"&gt;Offer 1&lt;/button&gt; &lt;button class="form-button" data-discount="50"&gt;Offer 2&lt;/button&gt; &lt;button class="form-button" data-discount="22"&gt;Offer 3&lt;/button&gt; &lt;button class="form-button" data-discount="88"&gt;Offer 4&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="discount__Topics"&gt; &lt;div&gt;&lt;strong class="discount-amount"&gt;12&lt;/strong&gt;%&lt;/div&gt; &lt;div class="offers"&gt; &lt;button class="form-button" data-discount="12"&gt;Offer 1&lt;/button&gt; &lt;button class="form-button" data-discount="32"&gt;Offer 2&lt;/button&gt; &lt;button class="form-button" data-discount="44"&gt;Offer 3&lt;/button&gt; &lt;button class="form-button" data-discount="55"&gt;Offer 4&lt;/button&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74317705, "author": "flyingfox", "author_id": 3176419, "author_profile": "https://Stackoverflow.com/users/3176419", "pm_score": 4, "selected": true, "text": "getDiscount" }, { "answer_id": 74317882, "author": "Robin Stut", "author_id": 14366546, "author_profile": "https://Stackoverflow.com/users/14366546", "pm_score": 0, "selected": false, "text": "var buttons = document.querySelectorAll(\".form-button\");\nvar discountRef = document.querySelector(\".discount-amount\");\n\nfunction setDiscount(pointerEvent) {\n // get the clicked button from the pointerEvent\n var discount = pointerEvent.target.dataset.discount\n\n // add the discount to <span class=\"discount-amount\"></span>\n discountRef.innerText = discount\n}\n\nbuttons.forEach(function (item) {\n item.addEventListener('click', setDiscount);\n});\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14185251/" ]
74,317,676
<p>I try to fill dropdown menu items from API JSON. I have <code>myList</code> in code. Sometimes, this list is empty and sometimes list has data.</p> <p>If <code>myList</code> has data there is no problem. I am having trouble when <code>myList</code> is empty. How can I solve this?</p> <p>My model class:</p> <pre><code>Login loginFromJson(String str) =&gt; Login.fromJson(json.decode(str)); String loginToJson(Login data) =&gt; json.encode(data.toJson()); class Login { Login({ required this.token, required this.callListDto, }); String token; List&lt;CallListDto&gt; callListDto; factory Login.fromJson(Map&lt;String, dynamic&gt; json) =&gt; Login( token: json[&quot;token&quot;], callListDto: List&lt;CallListDto&gt;.from( json[&quot;callListDto&quot;].map((x) =&gt; CallListDto.fromJson(x))), ); Map&lt;String, dynamic&gt; toJson() =&gt; { &quot;token&quot;: token, &quot;callListDto&quot;: List&lt;dynamic&gt;.from(callListDto.map((x) =&gt; x.toJson())), }; } class CallListDto { CallListDto({ required this.callId, required this.stationCode, required this.callType, }); int callId; String stationCode; int callType; factory CallListDto.fromJson(Map&lt;String, dynamic&gt; json) =&gt; CallListDto( callId: json[&quot;callID&quot;], stationCode: json[&quot;stationCode&quot;], callType: json[&quot;callType&quot;], ); Map&lt;String, dynamic&gt; toJson() =&gt; { &quot;callID&quot;: callId, &quot;stationCode&quot;: stationCode, &quot;callType&quot;: callType, }; } </code></pre> <p>My dropdown UI:</p> <pre><code>items: _loginController.loginList[0].myList .where((p0) =&gt; p0.callType == 1) .map( (item) =&gt; DropdownMenuItem&lt;String&gt;( value: item.callId.toString(), child: Text( item.callId.toString(), style: GoogleFonts.ptSansNarrow( textStyle: TextStyle( fontSize: 25, fontWeight: FontWeight.w600, color: Colors.black.withOpacity(.8)), ), ), ), ) .toList(), </code></pre>
[ { "answer_id": 74317705, "author": "flyingfox", "author_id": 3176419, "author_profile": "https://Stackoverflow.com/users/3176419", "pm_score": 4, "selected": true, "text": "getDiscount" }, { "answer_id": 74317882, "author": "Robin Stut", "author_id": 14366546, "author_profile": "https://Stackoverflow.com/users/14366546", "pm_score": 0, "selected": false, "text": "var buttons = document.querySelectorAll(\".form-button\");\nvar discountRef = document.querySelector(\".discount-amount\");\n\nfunction setDiscount(pointerEvent) {\n // get the clicked button from the pointerEvent\n var discount = pointerEvent.target.dataset.discount\n\n // add the discount to <span class=\"discount-amount\"></span>\n discountRef.innerText = discount\n}\n\nbuttons.forEach(function (item) {\n item.addEventListener('click', setDiscount);\n});\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1928396/" ]
74,317,702
<p>The title is a bit lengthy, but it's best explained by an example:</p> <p>Suppose we have the following functions in C++:</p> <pre class="lang-cpp prettyprint-override"><code>void SomeFunction(int num) { //1 } void SomeFunction(int&amp; num) { //2 } void SomeFunction(const int&amp; num) { //3 } void SomeFunction(const int num) { //4 } </code></pre> <p>All of these are called the same way:</p> <pre><code>SomeFunction(5); </code></pre> <p>or</p> <pre><code>int x = 5; SomeFunction(x); </code></pre> <p>When I tried to compile the code, it rightfully says <code>more than one instance of overloaded function &quot;SomeFunction&quot; matches the argument</code></p> <p>My question is: Is there a way to tell the compiler which function I meant to call?</p> <p>I asked my lecturer if it was possible, and she tried something along</p> <pre><code>SomeFunction&lt; /*some text which I don't remember*/ &gt;(x); </code></pre> <p>But it didn't work and she asked me to find out and tell her.</p> <p>I also encounter this post: <a href="https://stackoverflow.com/questions/15905749/how-to-define-two-functions-with-the-same-name-and-parameters-if-one-of-them-ha">How to define two functions with the same name and parameters, if one of them has a reference?</a> And it seems that 1 and 2 can't be written together, but what about 3 and 4? Can either one of those be called specifically?</p>
[ { "answer_id": 74317884, "author": "pptaszni", "author_id": 4165552, "author_profile": "https://Stackoverflow.com/users/4165552", "pm_score": 0, "selected": false, "text": " static_cast<void(*)(int)>(SomeFunction)(i);\n static_cast<void(*)(int&)>(SomeFunction)(i);\n static_cast<void(*)(const int&)>(SomeFunction)(i);\n" }, { "answer_id": 74317905, "author": "fabian", "author_id": 2991525, "author_profile": "https://Stackoverflow.com/users/2991525", "pm_score": 2, "selected": true, "text": "template<class Arg>\nvoid Call(void f(Arg), Arg arg)\n{\n f(arg);\n}\n\n// Driver Program to test above functions\nint main()\n{\n int i;\n Call<int>(SomeFunction, 1);\n Call<int&>(SomeFunction, i);\n Call<const int&>(SomeFunction, 1);\n}\n" }, { "answer_id": 74318010, "author": "Nelfeal", "author_id": 3854570, "author_profile": "https://Stackoverflow.com/users/3854570", "pm_score": 0, "selected": false, "text": "SomeFunction" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4584801/" ]
74,317,725
<p>I have the following numpy array</p> <pre><code>import numpy as np arr = np.array([1,1,1,2,2,2,3,3,2,2,2,1,1,1,2,2]) </code></pre> <p>I split this array into parts, where each part has the same value <strong>consequently</strong> using <a href="https://stackoverflow.com/questions/7352684/how-to-find-the-groups-of-consecutive-elements-in-a-numpy-array">this question</a></p> <pre><code>def consecutive(data, stepsize=1): return np.split(data, np.where(np.diff(data) != stepsize)[0]+1) consecutive(arr, stepsize=0) </code></pre> <p>which yields</p> <pre><code>[array([1, 1, 1]), array([2, 2, 2]), array([3, 3]), array([2, 2, 2]), array([1, 1, 1]), array([2, 2])] </code></pre> <p>I would like, for every sub-part above, if its (unique) element has appeared before, to add to this sub-part <code>0.001 * times_of_appearences_before_that</code></p> <p>I tried this:</p> <pre><code>arr_f = [] times_appeared_dict = dict(zip([str(l) for l in list(np.unique(arr))], [-1]*len(list(np.unique(arr))))) # dictionary which will count the times of appearences for sub_arr in consecutive(arr, stepsize=0): arr_f.append(sub_arr) arr_f_tmp = np.concatenate(arr_f).ravel() if np.unique(sub_arr) in arr_f_tmp: times_appeared_dict[str(np.unique(sub_arr)[0])] = times_appeared_dict[str(np.unique(sub_arr)[0])] + 1 # then add the 0.0001 to the elements, starting from the end arr_ff = [] for sub_arr in reversed(consecutive(arr, stepsize=0)): sub_arr_f = sub_arr + 0.0001*times_appeared_dict[str(np.unique(sub_arr)[0])] times_appeared_dict[str(np.unique(sub_arr)[0])] = times_appeared_dict[str(np.unique(sub_arr)[0])] - 1 arr_ff.append(sub_arr_f) arr_ff = np.concatenate(arr_ff).ravel() # revert the order back to initial arr_fff = [] for sub_arr in reversed(consecutive(arr_ff, stepsize=0)): arr_fff.append(sub_arr) arr_fff = np.concatenate(arr_fff).ravel() arr_fff </code></pre> <p>which yields</p> <pre><code>array([1. , 1. , 1. , 2. , 2. , 2. , 3. , 3. , 2.0001, 2.0001, 2.0001, 1.0001, 1.0001, 1.0001, 2.0002, 2.0002]) </code></pre> <p>which is the correct result. I was wondering if there is a smarter way to do that (avoiding all these loops etc)</p>
[ { "answer_id": 74319589, "author": "chrslg", "author_id": 20037042, "author_profile": "https://Stackoverflow.com/users/20037042", "pm_score": 3, "selected": true, "text": "times_appeared_dict = dict(zip([str(l) for l in list(np.unique(arr))], [-1]*len(list(np.unique(arr))))) # dictionary which will count the times of appearences\n# As Ahmed said, no need to use str(l) as key here. l is a better key, and we spare a `str`\ntimes_appeared_dict = dict(zip([l for l in list(np.unique(arr))], [-1]*len(list(np.unique(arr)))))\n# Also `np.unique(arr)` is iterable. No need to iterate list(np.unique(arr))\ntimes_appeared_dict = dict(zip([l for l in np.unique(arr)], [-1]*len(np.unique(arr))))\n# Since you use np.unique(arr) 2 times, let compute it once only\nlistUniq=np.unique(arr)\ntimes_appeared_dict = dict(zip([l for l in listUniq], [-1]*len(listUniq)))\n# [l for l in aList] is just aList\ntimes_appeared_dict = dict(zip(listUniq, [-1]*len(listUniq)))\n" }, { "answer_id": 74319597, "author": "amirhm", "author_id": 4529589, "author_profile": "https://Stackoverflow.com/users/4529589", "pm_score": 1, "selected": false, "text": "splits = consecutive(arr, stepsize=0)\nl2 = np.array(list(map(lambda x: (x[0], len(x)) , splits)), dtype=float)\na, b = l2[:,0], l2[:,1]\n\nfor val in np.unique(a):\n idx = np.where(a == val)[0]\n a[idx] = val + np.arange(len(idx)) * 0.001\n\nout = np.array([val for val, l in zip(a, b) for i in range(int(l))])\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5868293/" ]
74,317,726
<p>I have a button, <code>onClick</code> of that button I want to make a <code>POST</code> call with some data user has filled in an input field, stored in state, and then redirect the user to another page.</p> <p>My current code looks like this, but I get an error:</p> <blockquote> <p><em>React Hook &quot;usePost&quot; is called in function &quot;onAccept&quot; which is neither a React function component or a custom React Hook function</em></p> </blockquote> <p>And the code doesn't work. I have created my own hook for <code>POST</code> calls.</p> <p>What might a way to make the desired functionality work?</p> <p>What I'm after is the ability to make a POST call and redirect.</p> <p>Simplified example:</p> <pre><code>// my function const onAccept = () =&gt; { const { data, loading, error } = usePost( &quot;MY_URL&quot;, { DATA: MY_DATA } ); if (data &amp;&amp; !error) { navigate(`/`); } }; // return &lt;button onClick={() =&gt; onAccept()} </code></pre>
[ { "answer_id": 74319589, "author": "chrslg", "author_id": 20037042, "author_profile": "https://Stackoverflow.com/users/20037042", "pm_score": 3, "selected": true, "text": "times_appeared_dict = dict(zip([str(l) for l in list(np.unique(arr))], [-1]*len(list(np.unique(arr))))) # dictionary which will count the times of appearences\n# As Ahmed said, no need to use str(l) as key here. l is a better key, and we spare a `str`\ntimes_appeared_dict = dict(zip([l for l in list(np.unique(arr))], [-1]*len(list(np.unique(arr)))))\n# Also `np.unique(arr)` is iterable. No need to iterate list(np.unique(arr))\ntimes_appeared_dict = dict(zip([l for l in np.unique(arr)], [-1]*len(np.unique(arr))))\n# Since you use np.unique(arr) 2 times, let compute it once only\nlistUniq=np.unique(arr)\ntimes_appeared_dict = dict(zip([l for l in listUniq], [-1]*len(listUniq)))\n# [l for l in aList] is just aList\ntimes_appeared_dict = dict(zip(listUniq, [-1]*len(listUniq)))\n" }, { "answer_id": 74319597, "author": "amirhm", "author_id": 4529589, "author_profile": "https://Stackoverflow.com/users/4529589", "pm_score": 1, "selected": false, "text": "splits = consecutive(arr, stepsize=0)\nl2 = np.array(list(map(lambda x: (x[0], len(x)) , splits)), dtype=float)\na, b = l2[:,0], l2[:,1]\n\nfor val in np.unique(a):\n idx = np.where(a == val)[0]\n a[idx] = val + np.arange(len(idx)) * 0.001\n\nout = np.array([val for val, l in zip(a, b) for i in range(int(l))])\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4942596/" ]
74,317,727
<p>I try to fetch data from a mySQL database using Axios to set the initial values of a form input generated with vue.js-formulate.</p> <p>Here is my script where I want to set the initial value of &quot;question1&quot;:</p> <pre><code>new Vue({ el: '#app', created() { this.fetchData(); }, data: { row: &quot;&quot;, values: { question1: this.row[&quot;answerq1&quot;], } }, methods: { fetchData() { axios.get('retrieve.php') .then(function (response) { this.row = response.data; // Checking output in Console: console.log(this.row[&quot;answerq1&quot;]); }); }, } }) </code></pre> <p>The fetchData() function is working as expected, this.row[&quot;answerq1&quot;] prints the expected string. However, access this value in the data part produces the error &quot;this.row is undefined&quot;. I'm guessing it has something to do with the lifecycle of the created() hook but I can't figure it out.</p>
[ { "answer_id": 74319589, "author": "chrslg", "author_id": 20037042, "author_profile": "https://Stackoverflow.com/users/20037042", "pm_score": 3, "selected": true, "text": "times_appeared_dict = dict(zip([str(l) for l in list(np.unique(arr))], [-1]*len(list(np.unique(arr))))) # dictionary which will count the times of appearences\n# As Ahmed said, no need to use str(l) as key here. l is a better key, and we spare a `str`\ntimes_appeared_dict = dict(zip([l for l in list(np.unique(arr))], [-1]*len(list(np.unique(arr)))))\n# Also `np.unique(arr)` is iterable. No need to iterate list(np.unique(arr))\ntimes_appeared_dict = dict(zip([l for l in np.unique(arr)], [-1]*len(np.unique(arr))))\n# Since you use np.unique(arr) 2 times, let compute it once only\nlistUniq=np.unique(arr)\ntimes_appeared_dict = dict(zip([l for l in listUniq], [-1]*len(listUniq)))\n# [l for l in aList] is just aList\ntimes_appeared_dict = dict(zip(listUniq, [-1]*len(listUniq)))\n" }, { "answer_id": 74319597, "author": "amirhm", "author_id": 4529589, "author_profile": "https://Stackoverflow.com/users/4529589", "pm_score": 1, "selected": false, "text": "splits = consecutive(arr, stepsize=0)\nl2 = np.array(list(map(lambda x: (x[0], len(x)) , splits)), dtype=float)\na, b = l2[:,0], l2[:,1]\n\nfor val in np.unique(a):\n idx = np.where(a == val)[0]\n a[idx] = val + np.arange(len(idx)) * 0.001\n\nout = np.array([val for val, l in zip(a, b) for i in range(int(l))])\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15171287/" ]
74,317,751
<p>I am trying to find out if there is the same number of occurrences <code>&quot;dog&quot;</code> and &quot;cat&quot; are in the given <code>String</code>.</p> <p>It should return <code>true</code> if they are equal, or <code>false</code> otherwise. How can I find out this <strong>without</strong> <code>while</code>, <code>for</code> etc. loops?</p> <p>This is my current process</p> <pre><code>class Main { public static boolean catsDogs(String s) { String cat = &quot;cat&quot;; String dog = &quot;dog&quot;; if (s.contains(cat) &amp;&amp; s.contains(dog)) { return true; } return false; } public static void main(String[] args) { boolean r = catsDogs(&quot;catdog&quot;); System.out.println(r); // =&gt; true System.out.println(catsDogs(&quot;catcat&quot;)); // =&gt; false System.out.println(catsDogs(&quot;1cat1cadodog&quot;)); // =&gt; true } } </code></pre>
[ { "answer_id": 74318054, "author": "67af7af3-67f3-48bf-98c5-d9155c", "author_id": 17856705, "author_profile": "https://Stackoverflow.com/users/17856705", "pm_score": 2, "selected": false, "text": "public static boolean catsDogs(String s) {\n Pattern pCat = Pattern.compile(\"cat\");\n Pattern pDog = Pattern.compile(\"dog\");\n Matcher mCat = pCat.matcher(s);\n Matcher mDog = pDog.matcher(s);\n return (mCat.results().count() == mDog.results().count());\n}\n" }, { "answer_id": 74318572, "author": "Melron", "author_id": 8920328, "author_profile": "https://Stackoverflow.com/users/8920328", "pm_score": 2, "selected": true, "text": "public static boolean catsDogs(String s) {\n return count(s,\"cat\") == count(s,\"dog\");\n}\n\npublic static int count(String s, String catOrDog) {\n return (s.length() - s.replace(catOrDog, \"\").length()) / catOrDog.length();\n}\n\npublic static void main(String[] args) {\n boolean r = catsDogs(\"catdog\");\n System.out.println(r); // => true\n System.out.println(catsDogs(\"catcat\")); // => false\n System.out.println(catsDogs(\"1cat1cadodog\")); // => true\n}\n" }, { "answer_id": 74318805, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 1, "selected": false, "text": "Matcher.result()" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20387799/" ]
74,317,812
<p>I have two tables:</p> <pre><code>product(id, reference, name) order(id, productId, date, quantity) </code></pre> <p>Every order has one or many products. The order table can have many lines of the same product. I need to select the 5 best seller products for today in the order table. I try this join to select the products of every order on today.</p> <pre class="lang-cs prettyprint-override"><code>from order in orders where order.date == DateTime.Today join product in products on product.Id equals order.productId select new {product.name, product.quantity, product.Id}; </code></pre> <p>Now I have a list of products sold on today, which can have multiple lines of the same products. So I tried this to add the quantity of the repeated product:</p> <pre class="lang-cs prettyprint-override"><code>for (int i = 1; i &lt;= productList.ToArray().Count(); i++) { foreach (var product in productList) { if (productList.Contains(product)) quantite += product.Quantite; else quantite = product.Quantite; </code></pre> <p>I didn't find a solution how to get the top 5 articles!</p>
[ { "answer_id": 74318127, "author": "jdweng", "author_id": 5015238, "author_profile": "https://Stackoverflow.com/users/5015238", "pm_score": 2, "selected": false, "text": "var results = (from order in orders on order.date equals DateTime.Today\n join product in products on product.Id equals order.productId\n select new {name = product.name, quantity = order.quantity, id = product.Id})\n .GroupBy(x => x.id)\n .Select(x => new { name = x.First().name, id = x.Key, totalQuantity = x.Sum(y => y.quantity)}\n .OrderByDescending(x => x.totalQuantity)\n .Take(5)\n .ToList();\n" }, { "answer_id": 74319272, "author": "Stefanov.sm", "author_id": 2302032, "author_profile": "https://Stackoverflow.com/users/2302032", "pm_score": 2, "selected": false, "text": "select * from \n(\n select p.id, p.name, sum(o.quantity) qty \n from \"order\" as o \n inner join product as p on o.productid = p.id\n where o.date = current_date\n group by p.id -- and p.name if p.id is not primary key\n) as t\norder by qty desc\nlimit 5;\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11450029/" ]
74,317,853
<p>I have spent way more time on this than any human should, I been through at least 30 solutions on Stack before posting this, as I know it is a VERY common issue. So I apologize for making my own post but I truly cannot get it working.</p> <p>My code is below:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code> &lt;div style="width: 100%"&gt; &lt;div style="width: 70%; float: left;"&gt; &lt;mat-form-field appearance="standard" &gt; &lt;mat-label&gt;Filter Table Data&lt;/mat-label&gt; &lt;input matInput [(ngModel)]="filter" (keyup)="applyFilter($event)"&gt; &lt;/mat-form-field&gt; &lt;/div&gt; &lt;div style="width: 30%; float: right;"&gt; &lt;button stye="display: flex; flex-direction: column; align-items: center;" mat-raised-button (click)="clearFilter(1)" &gt; Clear Filter &lt;/button&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>This is how it displays on my site:</p> <p><a href="https://i.stack.imgur.com/RMCPo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RMCPo.png" alt="enter image description here" /></a></p> <p>Any ideas on how I can get it working to be vertically aligned?</p> <p><strong>End result goal:</strong> the button (&quot;Clear Filter&quot;) shown in the image needs to be vertically aligned, currently it shows at the top of the div.</p>
[ { "answer_id": 74317957, "author": "Parth M. Dave", "author_id": 12119351, "author_profile": "https://Stackoverflow.com/users/12119351", "pm_score": 0, "selected": false, "text": "<div style=\"width: 100%;display: flex;\n align-items: center;\n justify-content: center;\">\n <div style=\"width: 70%; float: left;\">\n <mat-form-field appearance=\"standard\" >\n <mat-label>Filter Table Data</mat-label>\n <input matInput [(ngModel)]=\"filter\" (keyup)=\"applyFilter($event)\" >\n </mat-form-field>\n </div>\n <div style=\"width: 30%;float: right;display: flex;\n align-items: center;\n justify-content: center;\">\n <button\n mat-raised-button (click)=\"clearFilter(1)\" >\n Clear Filter \n </button>\n </div>\n </div>" }, { "answer_id": 74317979, "author": "Jovana", "author_id": 11365465, "author_profile": "https://Stackoverflow.com/users/11365465", "pm_score": 2, "selected": true, "text": "float" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9599098/" ]
74,317,862
<p>I am trying to convert the date I have got using the <code>GETDATE()</code> function into <code>YY-MON-DD</code> format such as <code>04 Nov 2022</code>. I have used <code>TO_VARCHAR()</code> to convert into the date returned by the <code>GETDATE()</code> into a string. The output is correct till the <code>TO_VARCHAR()</code> is used i.e. <code>SELECT TO_VARCHAR(GET_DATE, 'DD-MON-YY')</code> returns the desired format.</p> <p>When I try to wrap it around <code>TO_DATE()</code> function; the date format changes into <code>2022-11-04</code>.</p> <pre><code>SELECT TO_DATE(TO_CHAR(GETDATE(), 'DD-MON-YY'), 'DD-MON-YY') </code></pre> <p>How can I resolve the problem and correct the format!?</p>
[ { "answer_id": 74317957, "author": "Parth M. Dave", "author_id": 12119351, "author_profile": "https://Stackoverflow.com/users/12119351", "pm_score": 0, "selected": false, "text": "<div style=\"width: 100%;display: flex;\n align-items: center;\n justify-content: center;\">\n <div style=\"width: 70%; float: left;\">\n <mat-form-field appearance=\"standard\" >\n <mat-label>Filter Table Data</mat-label>\n <input matInput [(ngModel)]=\"filter\" (keyup)=\"applyFilter($event)\" >\n </mat-form-field>\n </div>\n <div style=\"width: 30%;float: right;display: flex;\n align-items: center;\n justify-content: center;\">\n <button\n mat-raised-button (click)=\"clearFilter(1)\" >\n Clear Filter \n </button>\n </div>\n </div>" }, { "answer_id": 74317979, "author": "Jovana", "author_id": 11365465, "author_profile": "https://Stackoverflow.com/users/11365465", "pm_score": 2, "selected": true, "text": "float" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20417885/" ]
74,317,867
<p>I am trying to get user input into a text file on different lines. The user input is stored in a list then the list is appended. I realize you are not suppose to use quotes since that will act as your own input. How could I go about using the user input?</p> <pre><code>def userfile(): text = [] s1 = input(&quot;Enter sentence #1 &quot;) s1 = input(&quot;Enter sentence #2 &quot;) text.append(s1) userfile = open(os.path.join(sys.path[0], &quot;sample2.txt&quot;), &quot;w&quot;) lines = ['s1\n', 's1\n'] userfile.writelines(lines) userfile.close() newfile = open(os.path.join(sys.path[0],&quot;sample2.txt&quot;), &quot;r&quot;) print(newfile.read()) def main(): #txtfile() userfile() if __name__ == &quot;__main__&quot;: main() </code></pre>
[ { "answer_id": 74317918, "author": "Raphael", "author_id": 9173710, "author_profile": "https://Stackoverflow.com/users/9173710", "pm_score": 1, "selected": false, "text": "userfile()" }, { "answer_id": 74317942, "author": "batelme", "author_id": 7916316, "author_profile": "https://Stackoverflow.com/users/7916316", "pm_score": 0, "selected": false, "text": "lines = [s1+'\\n', s1+'\\n']" }, { "answer_id": 74318652, "author": "user99999", "author_id": 20070120, "author_profile": "https://Stackoverflow.com/users/20070120", "pm_score": 0, "selected": false, "text": "userfile()" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15235615/" ]
74,317,897
<p>I have a DateTime string like below:</p> <pre class="lang-js prettyprint-override"><code>&quot;11/20/2022 19.00&quot; </code></pre> <p>I just want to delete the spaces until the end, how do I do that?</p> <p>I'm expecting the below output:</p> <pre class="lang-js prettyprint-override"><code>&quot;11/20/2022&quot; </code></pre>
[ { "answer_id": 74317918, "author": "Raphael", "author_id": 9173710, "author_profile": "https://Stackoverflow.com/users/9173710", "pm_score": 1, "selected": false, "text": "userfile()" }, { "answer_id": 74317942, "author": "batelme", "author_id": 7916316, "author_profile": "https://Stackoverflow.com/users/7916316", "pm_score": 0, "selected": false, "text": "lines = [s1+'\\n', s1+'\\n']" }, { "answer_id": 74318652, "author": "user99999", "author_id": 20070120, "author_profile": "https://Stackoverflow.com/users/20070120", "pm_score": 0, "selected": false, "text": "userfile()" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20278389/" ]
74,317,936
<p>As title says, I would like to send emails with my gmail account writing some java code. I have found many code examples, but none of them is working for me</p> <p>I was looking a this one: <a href="https://stackoverflow.com/questions/46663/how-can-i-send-an-email-by-java-application-using-gmail-yahoo-or-hotmail/47452#47452">How can I send an email by Java application using GMail, Yahoo, or Hotmail?</a></p> <p>I have tried the code posted as answer, but I get this exception:</p> <pre><code>javax.mail.MessagingException: Can't send command to SMTP host; nested exception is: javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate) at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:1717) at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:1704) at com.sun.mail.smtp.SMTPTransport.ehlo(SMTPTransport.java:1088) at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:468) at javax.mail.Service.connect(Service.java:291) at javax.mail.Service.connect(Service.java:172) ... </code></pre> <p>The code is this:</p> <pre><code>public class GmailTest { private static String USER_NAME = &quot;*****&quot;; // GMail user name (just the part before &quot;@gmail.com&quot;) private static String PASSWORD = &quot;********&quot;; // GMail password private static String RECIPIENT = &quot;random.address@gmail.com&quot;; public static void main(String[] args) { String from = USER_NAME; String pass = PASSWORD; String[] to = { RECIPIENT }; // list of recipient email addresses String subject = &quot;Java send mail example&quot;; String body = &quot;Welcome to JavaMail!&quot;; sendFromGMail(from, pass, to, subject, body); } private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) { Properties props = System.getProperties(); String host = &quot;smtp.gmail.com&quot;; props.put(&quot;mail.smtp.starttls.enable&quot;, &quot;true&quot;); props.put(&quot;mail.smtp.host&quot;, host); props.put(&quot;mail.smtp.user&quot;, from); props.put(&quot;mail.smtp.password&quot;, pass); props.put(&quot;mail.smtp.port&quot;, &quot;587&quot;); props.put(&quot;mail.smtp.auth&quot;, &quot;true&quot;); Session session = Session.getDefaultInstance(props); MimeMessage message = new MimeMessage(session); try { message.setFrom(new InternetAddress(from)); InternetAddress[] toAddress = new InternetAddress[to.length]; // To get the array of addresses for( int i = 0; i &lt; to.length; i++ ) { toAddress[i] = new InternetAddress(to[i]); } for( int i = 0; i &lt; toAddress.length; i++) { message.addRecipient(Message.RecipientType.TO, toAddress[i]); } message.setSubject(subject); message.setText(body); Transport transport = session.getTransport(&quot;smtp&quot;); transport.connect(host, from, pass); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (Exception e) { e.printStackTrace(); } } } </code></pre> <p>Should this work in 2022 or did something change? Why am I getting that exception?</p>
[ { "answer_id": 74317918, "author": "Raphael", "author_id": 9173710, "author_profile": "https://Stackoverflow.com/users/9173710", "pm_score": 1, "selected": false, "text": "userfile()" }, { "answer_id": 74317942, "author": "batelme", "author_id": 7916316, "author_profile": "https://Stackoverflow.com/users/7916316", "pm_score": 0, "selected": false, "text": "lines = [s1+'\\n', s1+'\\n']" }, { "answer_id": 74318652, "author": "user99999", "author_id": 20070120, "author_profile": "https://Stackoverflow.com/users/20070120", "pm_score": 0, "selected": false, "text": "userfile()" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/465588/" ]
74,317,958
<p>I need to trim the 'My Pet' column inside the query string. How can that be done?</p> <pre><code># Note that one cat literal has a trailing space. testDF = pd.DataFrame([{&quot;My Pet&quot;:&quot;cat &quot;, &quot;Cost&quot;:&quot;$10 &quot;, &quot;Weight&quot;:&quot;10 pounds&quot;, &quot;Name&quot;:&quot;Violet&quot;}, {&quot;My Pet&quot;:&quot;cat&quot;, &quot;Cost&quot;:&quot;$10 &quot;, &quot;Weight&quot;:&quot;15 pounds&quot;, &quot;Name&quot;:&quot;Sirius&quot;}, {&quot;My Pet&quot;:&quot;dog&quot;, &quot;Cost&quot;:&quot;$0 &quot;, &quot;Weight&quot;:&quot;50 pounds&quot;, &quot;Name&quot;:&quot;Sam&quot;}, {&quot;My Pet&quot;:&quot;turtle&quot;, &quot;Cost&quot;:&quot;$5 &quot;, &quot;Weight&quot;:&quot;20 ounces&quot;, &quot;Name&quot;:&quot;Tommy&quot;}, ]) # We try to filter on cat. catDF = testDF.query(&quot;`My Pet` == 'cat'&quot;) # This yields only one row because one cat cell has a trailing space catDF.head() </code></pre> <p>Output is only one row but I would like to get both rows with cat in them</p> <pre><code> My Pet Cost Weight Name 1 cat $10 15 pounds Sirius </code></pre>
[ { "answer_id": 74318017, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 2, "selected": true, "text": "Series.str.strip" }, { "answer_id": 74318022, "author": "Matteo Zanoni", "author_id": 13384774, "author_profile": "https://Stackoverflow.com/users/13384774", "pm_score": 0, "selected": false, "text": "Series.str.strip" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1169091/" ]
74,317,961
<p>I have an application where we have a button in index.html. So just wanted to navigate from index.html to another razor page which is in PAGES folder called</p> <pre><code>dashboard.razor </code></pre> <p>I am newbie to blazor applications,please help.</p>
[ { "answer_id": 74319449, "author": "Lex", "author_id": 548997, "author_profile": "https://Stackoverflow.com/users/548997", "pm_score": 1, "selected": false, "text": "NavigationManager" }, { "answer_id": 74325586, "author": "AlirezaK", "author_id": 4444757, "author_profile": "https://Stackoverflow.com/users/4444757", "pm_score": 0, "selected": false, "text": "dashboard.razor" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2355408/" ]
74,317,968
<p>I created a function that returns a new url at random, in a given amount of time from an object. I then tried to export the function so that I am able to consume the url in another React file but It's like it's not working. can anybody help out.</p> <p>``</p> <pre><code>JS FILE //create a function that will display random images every five or more seconds const imageObject = { one: 'https://static.nike.com/a/images/f_auto/dpr_1.0,cs_srgb/w_1253,c_limit/a6c38705-dd40-43f8-a1ca-9ba62db12896/nike-just-do-it.jpg', two: 'https://static.nike.com/a/images/f_auto/dpr_1.0,cs_srgb/w_1253,c_limit/30afe174-1232-4fa5-8bd2-c8d5c4140ea7/nike-just-do-it.jpg', three: 'https://static.nike.com/a/images/f_auto/dpr_1.0,cs_srgb/w_1253,c_limit/abdc6ff0-7743-4d16-8022-b006b5b5cd2e/nike-just-do-it.jpg', four: 'https://static.nike.com/a/images/f_auto/dpr_1.0,cs_srgb/w_621,c_limit/aa52dbcb-437f-40d7-aba8-485b9166c0da/nike-just-do-it.jpg', five: 'https://static.nike.com/a/images/f_auto/dpr_1.0,cs_srgb/w_621,c_limit/35590940-95bc-4360-aaf0-3b4f2b690913/nike-just-do-it.png', six: 'https://www.newbalance.com/dw/image/v2/AAGI_PRD/on/demandware.static/-/Library-Sites-NBUS-NBCA/default/dw803b3a09/images/page-designer/2022/october_3/14428_Comp_J5_Image.jpg', seven: 'https://www.newbalance.com/dw/image/v2/AAGI_PRD/on/demandware.static/-/Library-Sites-NBUS-NBCA/default/dwc2463d13/images/page-designer/2022/october_3/14430_Comp_E_Image1.jpg?sw=808&amp;sfrm=jpg', eight: 'https://www.newbalance.com/dw/image/v2/AAGI_PRD/on/demandware.static/-/Library-Sites-NBUS-NBCA/default/dwe8369510/images/page-designer/2022/october_2/14437_Comp_E1_Image1.jpg?sw=808&amp;sfrm=jpg', nine: 'https://media.gucci.com/content/GiantEditorialStandard_1366x1643/1666791903/GiantEditorialStandard_HAHAHA-Harry-Styles_001_Default.jpg', ten: 'https://static.nike.com/a/images/f_auto/dpr_1.0,cs_srgb/w_621,c_limit/142b1b85-a20a-46e5-8d4d-8b2c3467d9c3/nike-just-do-it.jpg' } const DisplayImages = () =&gt; { setInterval(() =&gt; { const myImageArray = Object.keys(imageObject); const randomNumber = Math.floor(Math.random() * myImageArray.length); const randomImage = myImageArray[randomNumber]; console.log(imageObject[randomImage]); }, 1000); } export default DisplayImages; </code></pre> <p>React file(tried to simplify)</p> <p>import React from 'react'; import DisplayImages from './images.js';</p> <p>function Images() { return( ); }</p> <p>``</p> <p>Images are not displaying on the page. What did i do wrong</p>
[ { "answer_id": 74318184, "author": "Getabalew Tesfaye", "author_id": 18007080, "author_profile": "https://Stackoverflow.com/users/18007080", "pm_score": 1, "selected": false, "text": " const myImageArray = [\"one\", \"two\" , \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\"]\n" }, { "answer_id": 74319229, "author": "Nijat Mursali", "author_id": 10489887, "author_profile": "https://Stackoverflow.com/users/10489887", "pm_score": 0, "selected": false, "text": "useState" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14743938/" ]
74,317,970
<p>I have 2 files which look like this.</p> <p>file-A</p> <pre><code>Red Green Blue Yellow </code></pre> <p>file-B</p> <pre><code>Car Bus Van Bike </code></pre> <p>I have to write content of them to <code>file-C</code> by following the <strong>defined variable</strong>. (Every time file-A and file-B line count will be equal)</p> <p>expected output:</p> <pre><code>Red Car Green Bus Green Blue Blue Blue Yellow </code></pre> <p>This is what I tried (I must follow this way)</p> <pre><code>mycolor=&quot;file-A&quot; myvehicle=$(cat file-B) while read -r color do for vehicle in $myvehicle do echo $color $vehicle echo $color $vehicle $color echo $color $color $color echo $color done done &lt;$mycolor &gt; file-C </code></pre> <p>then output I got</p> <pre><code>Red Car Red Car Red Red Red Red Red Red Bus Red Bus Red Red Red Red Red Red Van Red Van Red Red Red Red Red Red Bike Red Bike Red Red Red Red Red Green Car Green Car Green Green Green Green Green Green Bus Green Bus Green Green Green Green Green Green Van Green Van Green Green Green Green Green Green Bike Green Bike Green Green Green Green Green Blue Car Blue Car Blue Blue Blue Blue Blue Blue Bus Blue Bus Blue Blue Blue Blue Blue Blue Van Blue Van Blue Blue Blue Blue Blue Blue Bike Blue Bike Blue Blue Blue Blue Blue Yellow Car Yellow Car Yellow Yellow Yellow Yellow Yellow Yellow Bus Yellow Bus Yellow Yellow Yellow Yellow Yellow Yellow Van Yellow Van Yellow Yellow Yellow Yellow Yellow Yellow Bike Yellow Bike Yellow Yellow Yellow Yellow Yellow </code></pre> <p>Can someone help me to figure out this? Thanks in advance!</p> <p>Note: I am not allowed to use jq or other languages as JavaScript, Python etc.</p>
[ { "answer_id": 74318184, "author": "Getabalew Tesfaye", "author_id": 18007080, "author_profile": "https://Stackoverflow.com/users/18007080", "pm_score": 1, "selected": false, "text": " const myImageArray = [\"one\", \"two\" , \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\"]\n" }, { "answer_id": 74319229, "author": "Nijat Mursali", "author_id": 10489887, "author_profile": "https://Stackoverflow.com/users/10489887", "pm_score": 0, "selected": false, "text": "useState" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11312762/" ]
74,317,978
<p>Im trying out next js 13 and I got some error I cant fix. My code:</p> <pre><code>import { useRouter } from 'next/navigation'; async function getCheckoutInfo() { const router = useRouter(); if (router.isReady) { console.log('Router query:', router.query); } else { console.log('Router is not ready yet') } return 'test'; } export default async function CheckoutPage() { const info = await getCheckoutInfo(); return( &lt;div&gt; &lt;h1&gt;Checkout &lt;/h1&gt; &lt;p&gt;{info}&lt;/p&gt; &lt;/div&gt; ) } </code></pre> <p>My error msg:</p> <pre><code>Unhandled Runtime Error Error: Cannot read properties of null (reading 'useContext') Call Stack Object.useContext webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/react/cjs/react.shared-subset.development.js (1428:31) useRouter webpack-internal:///(sc_server)/./node_modules/next/dist/client/components/navigation.js (91:32) </code></pre> <p>What's wrong here? To me, it looks like useRouter doesn't work as intended. Previously I used useEffect() which worked fine but with nextjs 13 you don't need to do this I suppose: <a href="https://beta.nextjs.org/docs/api-reference/use-router" rel="nofollow noreferrer">https://beta.nextjs.org/docs/api-reference/use-router</a></p> <p>Thanks in advance for solving this mystery for me.</p>
[ { "answer_id": 74318322, "author": "Sarath Adhithya", "author_id": 18233081, "author_profile": "https://Stackoverflow.com/users/18233081", "pm_score": 0, "selected": false, "text": "useRouter()" }, { "answer_id": 74330051, "author": "nifCody", "author_id": 2672566, "author_profile": "https://Stackoverflow.com/users/2672566", "pm_score": 2, "selected": false, "text": "router.push\nrouter.replace\nrouter.refresh()\nrouter.prefetch\nrouter.back()\nrouter.forward()\n" }, { "answer_id": 74442234, "author": "Mirado Andria", "author_id": 10143236, "author_profile": "https://Stackoverflow.com/users/10143236", "pm_score": 0, "selected": false, "text": "'use client';\n\nimport { useRouter } from 'next/navigation';\n\n//... rest of the code\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16176943/" ]
74,317,983
<p>I have got this error</p> <p>TypeError: string indices must be integers</p> <p>I am try to call this function</p> <pre><code>def encrypt(): text = input(&quot;Type your message:\n&quot;).lower() for i in alphabet: if i == text[range(len(text)]: print(i) alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] encrypt() </code></pre> <p>I have got this error</p> <p><code>TypeError: string indices must be integers</code></p> <p>any help plz</p>
[ { "answer_id": 74318322, "author": "Sarath Adhithya", "author_id": 18233081, "author_profile": "https://Stackoverflow.com/users/18233081", "pm_score": 0, "selected": false, "text": "useRouter()" }, { "answer_id": 74330051, "author": "nifCody", "author_id": 2672566, "author_profile": "https://Stackoverflow.com/users/2672566", "pm_score": 2, "selected": false, "text": "router.push\nrouter.replace\nrouter.refresh()\nrouter.prefetch\nrouter.back()\nrouter.forward()\n" }, { "answer_id": 74442234, "author": "Mirado Andria", "author_id": 10143236, "author_profile": "https://Stackoverflow.com/users/10143236", "pm_score": 0, "selected": false, "text": "'use client';\n\nimport { useRouter } from 'next/navigation';\n\n//... rest of the code\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74317983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20304483/" ]
74,318,006
<p><a href="https://i.stack.imgur.com/oOm75.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oOm75.png" alt="" /></a> I have this components</p> <p><a href="https://i.stack.imgur.com/LVpaz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LVpaz.png" alt="" /></a> and i have this code as the if sentence.</p> <p>I have the same method in other project that works, can anyone help?</p> <p><a href="https://i.stack.imgur.com/7rHo6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7rHo6.png" alt=" " /></a> it should only render the first one as addnewchat hte others ones should be avatars, if i take of the &quot;!&quot; only renders the avatars.</p>
[ { "answer_id": 74318322, "author": "Sarath Adhithya", "author_id": 18233081, "author_profile": "https://Stackoverflow.com/users/18233081", "pm_score": 0, "selected": false, "text": "useRouter()" }, { "answer_id": 74330051, "author": "nifCody", "author_id": 2672566, "author_profile": "https://Stackoverflow.com/users/2672566", "pm_score": 2, "selected": false, "text": "router.push\nrouter.replace\nrouter.refresh()\nrouter.prefetch\nrouter.back()\nrouter.forward()\n" }, { "answer_id": 74442234, "author": "Mirado Andria", "author_id": 10143236, "author_profile": "https://Stackoverflow.com/users/10143236", "pm_score": 0, "selected": false, "text": "'use client';\n\nimport { useRouter } from 'next/navigation';\n\n//... rest of the code\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20418013/" ]
74,318,019
<p>I am trying to connect my django app to postgres but it gives the following error.</p> <pre><code>connection to server at &quot;127.0.0.1&quot;, port 5432 failed: FATAL: database &quot;testDB&quot; does not exist </code></pre> <p>the postgres server is running I have checked it also restarted the server still I get the same error</p> <p>my database settings.</p> <pre><code> DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'testDB', 'USER': 'postgres', 'PASSWORD': 'xxxxx', 'HOST': '127.0.0.1', 'PORT': '5432', } } </code></pre> <p>I tried to check if the server is running and it is running, also restarted the server but still the same error.</p>
[ { "answer_id": 74319473, "author": "Anton", "author_id": 6621510, "author_profile": "https://Stackoverflow.com/users/6621510", "pm_score": 2, "selected": true, "text": "database \"testDB\" does not exist" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19384362/" ]
74,318,061
<p>I want to change the name of a file. The source filename is changing all the time. The produced name mus be fixed. Here is mij script:</p> <pre><code>&lt;?php $directory = '/public_html/Weercam/FI9853EP_00626EA2E6A9/snap/'; foreach (glob($directory.&quot;*.jpg&quot;) as $filename) { $file = realpath($filename); rename($file, str_replace(&quot;.jpg&quot;,&quot;test.gif&quot;,$file)); } ?&gt; </code></pre> <p>It works. BUT the name shoud be only test.gif. Now it makes the name like: abcdefghtest.gif</p> <p>I tried to use the script on the server. It works fine, onle the outcoming name is wrong</p>
[ { "answer_id": 74319473, "author": "Anton", "author_id": 6621510, "author_profile": "https://Stackoverflow.com/users/6621510", "pm_score": 2, "selected": true, "text": "database \"testDB\" does not exist" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20417871/" ]
74,318,062
<p>I created a Json Server Database like this:</p> <pre><code>&quot;Time&quot;: [ { &quot;id&quot;:1, &quot;name&quot;: [ { &quot;id&quot;:1, &quot;checkin&quot;: [ { &quot;id&quot;:1, &quot;date&quot;:&quot;123&quot;, &quot;time&quot;:&quot;123&quot; }, { &quot;id&quot;:2, &quot;date&quot;:&quot;123&quot;, &quot;time&quot;:&quot;123&quot; } ] }, { &quot;id&quot;:2, &quot;checkout&quot;: [ { &quot;id&quot;:1, &quot;date&quot;:&quot;123&quot;, &quot;time&quot;:&quot;123&quot; } ] } ] } ] </code></pre> <p>I don't want to get the entire Database and go through it. I just want to tell the Database where exactly my Object is and have it returned.</p> <p>How would I call the call for example the first Check-in Object?</p> <p>I use the Angular HttpClient like this:</p> <pre><code>this.http.get(endpoint, JSON.stringify(time), this.httpOptions)) </code></pre> <p>So I need the Exact Endpoint in a format like: endpoint/id/id or similar</p> <p>I imagined it like this: endpoint/time/1/1 <br> With output:</p> <pre><code>[ { &quot;id&quot;:1, &quot;date&quot;:&quot;123&quot;, &quot;time&quot;:&quot;123&quot; } ] </code></pre> <p>If this is not possible please tell me anyways.</p> <p>PS: The question from <a href="https://stackoverflow.com/questions/50295925/how-to-access-nested-resources-in-json-server">this thread</a> is essentially the same as mine. Also the JSON documentation doesn't real help either, it just says you need custom routes for multilayer JSON strings but not how to implement these routes.</p>
[ { "answer_id": 74319473, "author": "Anton", "author_id": 6621510, "author_profile": "https://Stackoverflow.com/users/6621510", "pm_score": 2, "selected": true, "text": "database \"testDB\" does not exist" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20291198/" ]
74,318,075
<p>Just a tought came in mind till now i have make maps of strings and vectors Like this <code>map&lt;int,int&gt; m; map &lt;int,vector&lt;int&gt;&gt; m; map &lt;string,vector&lt;int&gt;&gt; m;</code> and various combinations are possible with other data types also.</p> <p>But what will happen If I do <code>map &lt;vector&lt;int&gt;,vector&lt;int&gt;&gt; m; or map &lt;vector&lt;int&gt;,vector&lt;vector&lt;int&gt;&gt;&gt; m;</code> etc.</p> <p>I was solving a question leetcode in which this format could be helpfull <a href="https://leetcode.com/contest/biweekly-contest-90/problems/odd-string-difference/" rel="nofollow noreferrer">https://leetcode.com/contest/biweekly-contest-90/problems/odd-string-difference/</a> I tried like this</p> <pre><code>class Solution { public: string oddString(vector&lt;string&gt;&amp; words) { map &lt;vector&lt;int&gt;,vector&lt;string&gt;&gt; m; for(auto i:words) { // m[{int(i[0]-i[1]), int(i[1]-i[2])}].push_back(i); vector&lt;int&gt; v; for(int j=1;j&lt;i.size();j++) { v.push_back(int(i[j]-i[j-1])); } } for(auto i:m) { if(i.second.size() ==1) { return i.second[0]; } } return &quot;&quot;; } }; </code></pre>
[ { "answer_id": 74318245, "author": "Fareanor", "author_id": 11455384, "author_profile": "https://Stackoverflow.com/users/11455384", "pm_score": 3, "selected": true, "text": "std::vector<int>" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14388733/" ]
74,318,100
<p>I am newbie with Pyqt and need help with setting setData on QAbstractTableModel with QSqlRelationalTableModel table model</p> <p>I have this simple code and I dont now how to implement setData function. I can't set value to field. I'm getting TypeError: 'QSqlRelationalTableModel' object is not subscriptable error.</p> <p>Also, how to perform calculatation on column (eg. Total column)?</p> <pre><code> from pyexpat import model import sys from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import Qt from PyQt5.QtWidgets import (QApplication, QGridLayout, QHeaderView, QMessageBox, QTableView, QMainWindow, QWidget) from PyQt5.QtSql import QSqlDatabase, QSqlRelationalTableModel, QSqlTableModel from PyQt5.QtSql import QSqlRelation, QSqlRelationalDelegate from PyQt5 import QtCore from PyQt5.QtCore import QAbstractTableModel, QModelIndex, QRect, Qt from datetime import date from time import strftime from numpy import record class MyTableModel(QtCore.QAbstractTableModel): def __init__(self, model): super().__init__() self._model = model # Create the data method def data(self, index, role): value = self._model.record(index.row()).value(index.column()) if role == Qt.ItemDataRole.DisplayRole: if isinstance(value, int) and index.column() == 0: return f'# {value}' if isinstance(value, int) and index.column() == 1: # Format the currency value return &quot;${: ,.2f}&quot;.format(value) if role == Qt.EditRole: return self._model[index.row()][index.column()] return value if role == Qt.ItemDataRole.DecorationRole: if isinstance(value, int) and index.column() == 0: return QtGui.QIcon('data/icons/hashtag_icon.png') if isinstance(value, str) and index.column() == 9: return QtGui.QIcon('data/icons/calendar.png') # Create the headerData method def headerData(self, section: int, orientation: Qt.Orientation, role: int): if role == Qt.ItemDataRole.DisplayRole and orientation == Qt.Orientation.Horizontal: return self._model.headerData(section, orientation, role=role) # Create the rowCount method def rowCount(self, parent: QModelIndex) -&gt; int: return self._model.rowCount() # Create the columnCount method def columnCount(self, parent: QModelIndex) -&gt; int: return self._model.columnCount() def setData(self, index, value, role): if not index.isValid(): return False if role == Qt.EditRole: self._model[index.row()][index.column()]=value self.dataChanged.emit(index, index,) return True return False def flags(self, index): return Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsEditable # Inherit from QMainWindow class MainWindow(QMainWindow): def __init__(self, parent=None): super().__init__(parent) # Set the window title self.setWindowTitle('QTable Example') self.window_width, self.window_height = 1000, 700 self.setMinimumSize(self.window_width, self.window_height) # Create the model model = QSqlRelationalTableModel(self) # Set the table to display model.setTable('obracundetails') model.setEditStrategy(QSqlRelationalTableModel.EditStrategy.OnFieldChange) # Set relations for related columns to be displayed #model.setRelation(1, QSqlRelation('products', 'ProductID', 'Price')) model.setRelation(8, QSqlRelation('asortiman', 'asortiman_id', 'naziv')) model.setRelation(9, QSqlRelation('obracunmain', 'obracunmain_id', 'datum')) #model.setHeaderData(0, Qt.Horizontal, &quot;ID&quot;) model.select() # Setup the view # Create the view = a table widget presentation_model = MyTableModel(model) view = QTableView(self) # Set the data model for table widget #view.setModel(model) view.setModel(presentation_model) # Adjust column widths to their content view.resizeColumnsToContents() # Add the widget to main window self.setCentralWidget(view) # Type hint for return value def createConnection() -&gt; bool: # SQLite type database connection instance con = QSqlDatabase.addDatabase('QSQLITE') # Connect to the database file con.setDatabaseName('havana.sqlite3') # Show message box when there is a connection issue if not con.open(): QMessageBox.critical( None, 'QTableView Example - Error!', 'Database Error: %s' % con.lastError().databaseText(), ) return False return True if __name__ == &quot;__main__&quot;: app = QApplication(sys.argv) if not createConnection(): sys.exit(1) form = MainWindow() form.show() app.exec() </code></pre> <p>Thanks in advance</p>
[ { "answer_id": 74318245, "author": "Fareanor", "author_id": 11455384, "author_profile": "https://Stackoverflow.com/users/11455384", "pm_score": 3, "selected": true, "text": "std::vector<int>" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14694614/" ]
74,318,106
<p>I am building a blog using React and Material UI. I have added a TinyMCE rich text field on my add posts page. The Tiny form is correctly storing the data as HTML into the JSON file; but when I try rendering a specific blog post I am getting the unformatted text with all the HTML tags. How to I turn this data into plain, formatted text(paragraphs, lists, accents) without displaying the HTML tags?</p> <p>This is the Tiny editor code:</p> <pre><code>&lt;Editor init={{ plugins: 'link image code', toolbar: 'undo redo | bold italic | alignleft aligncenter alignright | code' }} value={body} onChange={(e) =&gt; setBody(e.target.getContent())} /&gt; </code></pre> <p>This is what is displaying in the JSON file, and on the front-end of my post page:</p> <pre><code>&lt;p style=&quot;margin: 0px 0px 15px; padding: 0px; text-align: justify; color: rgb(0, 0, 0); font-family: 'Open Sans', Arial, sans-serif; font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;&quot; data-mce-style=&quot;margin: 0px 0px 15px; padding: 0px; text-align: justify; color: rgb(0, 0, 0); font-family: 'Open Sans', Arial, sans-serif; font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;&quot;&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. </code></pre> <p>I tried using this but it didn't seem to do anything:</p> <pre><code>.getContent({ format: 'text' }) </code></pre> <p>I have checked the docs but they confused me further. I am hoping to be able to do this without another npm package.</p>
[ { "answer_id": 74318245, "author": "Fareanor", "author_id": 11455384, "author_profile": "https://Stackoverflow.com/users/11455384", "pm_score": 3, "selected": true, "text": "std::vector<int>" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12441586/" ]
74,318,108
<p>Using yq (or any other tool), how can I return the full YAML path of an arbitrary line number ?</p> <p>e.g. with this file :</p> <pre class="lang-yaml prettyprint-override"><code>a: b: c: &quot;foo&quot; d: | abc def </code></pre> <p>I want to get the full path of line 2; it should yield: <code>a.b.c</code>. Line 0 ? <code>a</code>, Line 4 ? <code>a.d</code> (multiline support), etc.</p> <p>Any idea how I could achieve that?</p> <p>Thanks</p>
[ { "answer_id": 74318842, "author": "0stone0", "author_id": 5625547, "author_profile": "https://Stackoverflow.com/users/5625547", "pm_score": 0, "selected": false, "text": "line" }, { "answer_id": 74318860, "author": "jpseng", "author_id": 16332641, "author_profile": "https://Stackoverflow.com/users/16332641", "pm_score": 1, "selected": false, "text": "input_line_number" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1891989/" ]
74,318,121
<p>My project file structure is like this,</p> <pre><code>project/src/test/myscript.py project/src/utils/file_utils.py </code></pre> <p>When I run <code>myscript.py</code>, which has <code>from utils import file_utils</code>, it gave me error:</p> <blockquote> <p>ModuleNotFoundError: No module named 'utils'</p> </blockquote> <p>Previously in Pycharm IDE I did not get this type of error (maybe due to _ init _.py), the subdirs of the same parent dir could be detected. But not sure for VSCode, is there something I need to add for specifying the file structure? And I opened the folder <code>project </code>as my VSCode workspace (not sure if where I open the workspace matters)</p> <p>I tried adding:</p> <ol> <li>in the <code>/project/.vscode/launch.json</code></li> </ol> <pre><code>&quot;cwd&quot;: &quot;${workspaceFolder}/src&quot; </code></pre> <ol start="2"> <li>or in the begining of <code>myscript.py</code></li> </ol> <pre><code>import sys import os src_path = os.path.dirname(os.path.abspath('/project/src/')) sys.path.insert(0, src_path) </code></pre> <p>But none of them works. Does anyone have any insights? Thank you very much!</p>
[ { "answer_id": 74318263, "author": "João Bonfim", "author_id": 20381775, "author_profile": "https://Stackoverflow.com/users/20381775", "pm_score": 0, "selected": false, "text": "__init__.py" }, { "answer_id": 74318373, "author": "The Lazy Graybeard", "author_id": 9608497, "author_profile": "https://Stackoverflow.com/users/9608497", "pm_score": 3, "selected": true, "text": ">>> cat /project/.env\nPYTHONPATH=/project/src/\n>>>\n" }, { "answer_id": 74341169, "author": "MingJie-MSFT", "author_id": 18359438, "author_profile": "https://Stackoverflow.com/users/18359438", "pm_score": -1, "selected": false, "text": "from src.utils import file_utils\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20417812/" ]
74,318,140
<p>The time is given in string for eg &quot;23:20&quot;. However in my function I need to compare times for which I gotta convert these to time format</p> <p>I tried strptime() and it works with 12 hour format for eg when I enter &quot;12:00PM&quot;</p>
[ { "answer_id": 74318237, "author": "Aarav Shah", "author_id": 20243803, "author_profile": "https://Stackoverflow.com/users/20243803", "pm_score": 1, "selected": false, "text": " from datetime import datetime\n m2 = '1:35 PM'\n in_time = datetime.strptime(m2, \"%I:%M %p\")\n out_time = datetime.strftime(in_time, \"%H:%M\")\n print(out_time)\n 13:35\n" }, { "answer_id": 74318418, "author": "Matteo Zanoni", "author_id": 13384774, "author_profile": "https://Stackoverflow.com/users/13384774", "pm_score": 1, "selected": true, "text": "datetime.time" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20418070/" ]
74,318,158
<p>I have a matrix, and i don't know the size, because the matrix was created from a dataframe. I have 2 arrays, min_cols and max_cols, first one is for each minimum from each column, and same with the max_cols.<br /> I want to recalculate each element from the columns, with this formula:</p> <blockquote> <p>Element[line][column] = Element - min_cols[column]/ (max_cols[column] - min_cols [column])</p> <p>(Element - min_cols) means that we substract the value from array min_cols that is on element's column position, from the element, and like that for each element on that column.</p> </blockquote> <blockquote> <p>Tehnically i have to substract from each element, the minimum from element's column. EX: I have my element on second column, i have to substract the minimum from second column, from my element. Element = Element - min_cols[1] (minimum from second position)</p> </blockquote> <p>The problem is i want to use a numpy function, and i don't know how to work with this.</p> <p>Or, I have to scale a matrix, between range [0,1]</p>
[ { "answer_id": 74318237, "author": "Aarav Shah", "author_id": 20243803, "author_profile": "https://Stackoverflow.com/users/20243803", "pm_score": 1, "selected": false, "text": " from datetime import datetime\n m2 = '1:35 PM'\n in_time = datetime.strptime(m2, \"%I:%M %p\")\n out_time = datetime.strftime(in_time, \"%H:%M\")\n print(out_time)\n 13:35\n" }, { "answer_id": 74318418, "author": "Matteo Zanoni", "author_id": 13384774, "author_profile": "https://Stackoverflow.com/users/13384774", "pm_score": 1, "selected": true, "text": "datetime.time" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19715327/" ]
74,318,163
<p>I am trying to write few regex . I am testing my regex on below link <a href="https://www.regextester.com/" rel="nofollow noreferrer">https://www.regextester.com/</a></p> <p><strong>Case 1</strong></p> <p>1.regex: <strong>/flow</strong></p> <p><strong>Testing string</strong> : <a href="https://example.com/flow" rel="nofollow noreferrer">https://example.com/flow</a></p> <p><strong>Testing result</strong> : correct same as expected (selected after domain) <a href="https://i.stack.imgur.com/6fiGU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6fiGU.png" alt="enter image description here" /></a></p> <p><strong>case 2</strong></p> <ol> <li><strong>/_next/.</strong>*</li> </ol> <p><strong>Testing string</strong>: <a href="https://example.com/_next/static/css/96c1d677121f4c49.css" rel="nofollow noreferrer">https://example.com/_next/static/css/96c1d677121f4c49.css</a></p> <p><strong>Testing result</strong> : correct same as expected (selected after domain) <a href="https://i.stack.imgur.com/7xKdy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7xKdy.png" alt="enter image description here" /></a></p> <p><strong>Case 3</strong>:</p> <ol start="2"> <li>regex: <strong>/(.+.(css|js))</strong> <strong>Testing string</strong>: <a href="https://example.com/96c1d677121f4c49.css" rel="nofollow noreferrer">https://example.com/96c1d677121f4c49.css</a></li> </ol> <p><strong>Testing result</strong> : NOT correct(it is selecting everything domain + match element)</p> <p><a href="https://i.stack.imgur.com/6T5S5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6T5S5.png" alt="enter image description here" /></a></p> <p><strong>Expected output</strong> : ONLY select <strong>&quot;96c1d677121f4c49.css&quot;</strong> NOT domain</p> <p>any way to fix this bug ?</p>
[ { "answer_id": 74318237, "author": "Aarav Shah", "author_id": 20243803, "author_profile": "https://Stackoverflow.com/users/20243803", "pm_score": 1, "selected": false, "text": " from datetime import datetime\n m2 = '1:35 PM'\n in_time = datetime.strptime(m2, \"%I:%M %p\")\n out_time = datetime.strftime(in_time, \"%H:%M\")\n print(out_time)\n 13:35\n" }, { "answer_id": 74318418, "author": "Matteo Zanoni", "author_id": 13384774, "author_profile": "https://Stackoverflow.com/users/13384774", "pm_score": 1, "selected": true, "text": "datetime.time" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19883277/" ]
74,318,190
<p>I am trying to create an azure function app with two http trigger functions in it with open API specs, but both using same route but with different parameters.</p> <p>Requirement to fetch some templates from Database. first way is when customer provides id, another way when customer provides name</p> <p>Here is my function looks like</p> <pre><code>[FunctionName(&quot;GetTemplateById&quot;)] [OpenApiOperation(operationId: &quot;Get-Template&quot;, tags: new[] { &quot;Get-Template&quot; })] [OpenApiParameter(name: &quot;id&quot;, In = ParameterLocation.Query, Required = true, Description = &quot;template id&quot;)] [OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: &quot;application/json&quot;, bodyType: typeof(JObject), Description = &quot;The OK response&quot;)] [OpenApiResponseWithoutBody(statusCode: HttpStatusCode.Unauthorized, Summary = &quot;Unauthorized Access&quot;, Description = &quot;Unauthorized Access.&quot;)] public async Task&lt;IActionResult&gt; GetTemplateById( [HttpTrigger(AuthorizationLevel.Anonymous, &quot;get&quot;, Route = &quot;template&quot;)] HttpRequest req) { //some code using id parameter return new ObjectResult(response); } </code></pre> <p>But I need another function where to fetch template by template name instead of ID. But how can I make it with the same route, but different parameter. I am not thinking about a solution where both parameters in single function and making both optional. Any other workaround?</p>
[ { "answer_id": 74365490, "author": "Nicolas Boisvert", "author_id": 912299, "author_profile": "https://Stackoverflow.com/users/912299", "pm_score": 1, "selected": false, "text": "http://yourApi/templates/{templateid}\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/954093/" ]
74,318,195
<p>I am working on a dataframe that has a category of challenges for a class. I need to be able to identify them as either being 'linux','window' or 'primer' based. I have created a dictionary as so:</p> <pre><code>import pandas as pd topic_keywords_dict = { 'Linux': { 'identification':['linux'], 'topic': [ 'bash','boot','process','auditing' ]}, 'Windows': { 'identification':['windows','memory'], 'topic': [ 'boot','process','artifacts','memory','active_directory','sysinternal' ]}, 'Primer': { 'identification':['primer'], 'topic': [ 'kernel','CLI','registry','process','NTFS','boot','auditing','security','active_directory','networking','surveys' ]} } </code></pre> <p>and I have a dataframe that looks like this:</p> <pre><code>challenge_count_df = pd.DataFrame({'Challenge': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'], 'Count' : [32, 22, 40, 12, 10, 60, 32, 22, 44, 90], 'Value' : [&quot;0&quot;,&quot;5&quot;,&quot;10&quot;,&quot;15&quot;,&quot;5&quot;,&quot;10&quot;,&quot;5&quot;,&quot;10&quot;,&quot;15&quot;,&quot;10&quot;], 'Category' : ['linux_bash','primer_02','windows_active_directory','basic_linux','linux_kitty','alpha_primer','windows_auditing','linux_logging', 'linux', 'primer']}) </code></pre> <p>which would give me something like this:</p> <pre><code>&gt;&gt;&gt; challenge_count_df Challenge Count Value Category 0 A 32 0 linux_bash 1 B 22 5 primer_02 2 C 40 10 windows_active_directory 3 D 12 15 basic_linux 4 E 10 5 linux_kitty 5 F 60 10 alpha_primer 6 G 32 5 windows_auditing 7 H 22 10 linux_logging 8 I 44 15 linux 9 J 90 10 primer </code></pre> <p>I was thinking of using something like this:</p> <pre><code>challenge_count_df[challenge_count_df['Category'].contains('|'.join(topic_keywords_dict[dict_key]['identification']))] </code></pre> <p>and maybe putting it in a form of applying lambda with the method above</p> <pre><code>challenge_count_df['key_dict'] = challenge_count_df['Category'].apply(lambda x: key_dict if x .contains('|'.join(topic_keywords_dict[dict_key]['identification'])) for key_dict in topic_keywords_dict) </code></pre> <p>but I'm thinking I'm doing the for loop inside the lambda wrong...can someone please help me understand what I'm doing wrong?</p> <p>--------------------EDIT-----------------</p> <p>The expected outcome would look like this:</p> <pre><code>&gt;&gt;&gt; challenge_count_df Challenge Count Value Category key_dict 0 A 32 0 linux_bash linux 1 B 22 5 primer_02 primer 2 C 40 10 windows_active_directory windows 3 D 12 15 basic_linux linux 4 E 10 5 linux_kitty linux 5 F 60 10 alpha_primer primer 6 G 32 5 windows_auditing windows 7 H 22 10 linux_logging linux 8 I 44 15 linux linux 9 J 90 10 primer primer </code></pre>
[ { "answer_id": 74365490, "author": "Nicolas Boisvert", "author_id": 912299, "author_profile": "https://Stackoverflow.com/users/912299", "pm_score": 1, "selected": false, "text": "http://yourApi/templates/{templateid}\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5669565/" ]
74,318,209
<p>Given I have the following configuration:</p> <pre class="lang-js prettyprint-override"><code>let config = { &quot;requests&quot;: [ { &quot;resource&quot;: &quot;foo&quot;, &quot;interval&quot;: 1000 }, { &quot;resource&quot;: &quot;bar&quot;, &quot;interval&quot;: 500 }, { &quot;resource&quot;: &quot;baz&quot;, &quot;interval&quot;: 3000 }, { &quot;resource&quot;: &quot;qux&quot;, &quot;interval&quot;: 500 }, { &quot;resource&quot;: &quot;zot&quot;, &quot;interval&quot;: 500 }, ], // other configs... } </code></pre> <p>I need to make a recursive setTimeout calls where I check what resources should be requested from a server at a given call and make the request to the server.</p> <p>For example, considering the array above:</p> <p>After 500ms, since it's the smallest interval, I have to make a request and pass array of <code>['bar', 'qux', 'zot']</code>. After another 500ms, and since it's already 1000ms, the array should be <code>['bar', 'qux', 'zot', 'foo']</code>. After another 500 it should be again <code>['bar', 'qux', 'zot']</code>. When reaches 3000 - <code>['bar', 'qux', 'zot', 'foo', 'baz']</code>, and so on...</p> <p>The configuration itself is coming from a server when the app starts and it's a black box to me. Meaning I can't know exactly what intervals may be configured and how many of them are there. Here I made them increase by 500ms for convenience only (though I think I might make it a technical requirement to the back-end guys, lets assume I can't).</p> <p>I'm not sure how to tackle this problem. I thought maybe I should store an array of required intervals and do something with that array. Perhaps store a current request as an object with timestamp and interval. Something like that:</p> <pre class="lang-js prettyprint-override"><code>const { requests } = config let intervals = new Set() for (let obj of requests) { intervals.add(obj.interval) } intervals = Array.from(intervals).sort((a, b) =&gt; a - b) //[500, 1000, 3000] let currentRequest const makeRequest = resources =&gt; { // send request to server with given resources array // init the next request by calling initRequest again } const initRequest = () =&gt; { const interval = 500 // just for example, the actual interval should be determind here const resources = [] // Here I should determine what should be the requested resources setTimeout(() =&gt; { makeRequest(resources) }, interval) } initRequest() </code></pre> <p>But I'm not sure about the logic here. How can this be done? Any ideas, please?</p>
[ { "answer_id": 74318483, "author": "Dr. Vortex", "author_id": 17637456, "author_profile": "https://Stackoverflow.com/users/17637456", "pm_score": 0, "selected": false, "text": "initRequests = () => {\n let i = -1;\n const resources = [];\n const timeoutHandler = () => {\n if(i < intervals.length){\n setTimeout(timeoutHandler, intervals[++i]);\n }\n }\n timeoutHandler();\n}\n\n" }, { "answer_id": 74318983, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 3, "selected": true, "text": "upcoming" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1231619/" ]
74,318,222
<p>I am trying to grow on a bookstore project mentioned in the book titled</p> <blockquote> <p>Django for Professionals by Vincent</p> </blockquote> <p>As I try to grow on it my <code>requirements.txt</code> has grown to</p> <pre><code>asgiref==3.5.2 Django==4.0.4 psycopg2-binary==2.9.3 sqlparse==0.4.2 django-crispy-forms==1.14.0 crispy-bootstrap5==0.6 django-allauth==0.50.0 </code></pre> <p>with my <code>Dockerfile</code> as</p> <pre><code>FROM python:3.8-slim-bullseye # set environment variables ENV PIP_DISABLE_PIP_VERSION_CHECK 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # # Set working directory WORKDIR /code # # Installing python dependencies COPY ./requirements.txt . RUN pip install -r requirements.txt </code></pre> <p>and my <code>docker-compose.yml</code> as</p> <pre><code># Mentioning which format of dockerfile version: &quot;3.9&quot; # services or nicknamed the container services: # web service for the web web: # you should use the --build flag for every node package added build: . # Add additional commands for webpack to 'watch for changes and bundle it to production' command: python manage.py runserver 0.0.0.0:8000 volumes: - type: bind source: . target: /code ports: - &quot;8000:8000&quot; depends_on: - db environment: - &quot;DJANGO_SECRET_KEY=django-insecure-m#x2vcrd_2un!9b4la%^)ou&amp;hcib&amp;nc9fvqn0s23z%i1e5))6&amp;&quot; - &quot;DJANGO_DEBUG=True&quot; # postgreSQL database server being constructed alongside db: image: postgres:13 # volumes: - postgres_data:/var/lib/postgresql/data/ # unsure of what this environment means. environment: - &quot;POSTGRES_HOST_AUTH_METHOD=trust&quot; # Volumes set up volumes: postgres_data: </code></pre> <hr /> <p>I have been unable to run migrations or create a super user. The primary reasoning that I see is that the <code>relation doesn't exist</code>.</p> <p>Attempting to debug it, the following is a list of tables in my postgres database.</p> <pre><code>root@a8988e22cd23:/# psql -U postgres psql (13.8 (Debian 13.8-1.pgdg110+1)) Type &quot;help&quot; for help. postgres=# \dt List of relations Schema | Name | Type | Owner --------+-------------------+-------+---------- public | django_migrations | table | postgres (1 row) </code></pre> <hr /> <p>The error that I see is from the python command</p> <pre><code>P:\StockWhiz&gt; docker compose exec web python manage.py migrate Operations to perform: Apply all migrations: account, admin, auth, contenttypes, sessions, sites, socialaccount Running migrations: Applying account.0001_initial...Traceback (most recent call last): File &quot;/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py&quot;, line 89, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation &quot;accounts_customuser&quot; does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File &quot;manage.py&quot;, line 22, in &lt;module&gt; main() File &quot;manage.py&quot;, line 18, in main execute_from_command_line(sys.argv) File &quot;/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py&quot;, line 446, in execute_from_command_line utility.execute() File &quot;/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py&quot;, line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File &quot;/usr/local/lib/python3.8/site-packages/django/core/management/base.py&quot;, line 414, in run_from_argv self.execute(*args, **cmd_options) File &quot;/usr/local/lib/python3.8/site-packages/django/core/management/base.py&quot;, line 460, in execute output = self.handle(*args, **options) File &quot;/usr/local/lib/python3.8/site-packages/django/core/management/base.py&quot;, line 98, in wrapped res = handle_func(*args, **kwargs) File &quot;/usr/local/lib/python3.8/site-packages/django/core/management/commands/migrate.py&quot;, line 290, in handle post_migrate_state = executor.migrate( File &quot;/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py&quot;, line 89, in _execute return self.cursor.execute(sql, params) File &quot;/usr/local/lib/python3.8/site-packages/django/db/utils.py&quot;, line 91, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File &quot;/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py&quot;, line 89, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation &quot;accounts_customuser&quot; does not exist </code></pre> <p>error from the compose console:</p> <pre><code>stockwhiz-db-1 | 2022-11-04 13:36:40.562 UTC [36] ERROR: relation &quot;accounts_customuser&quot; does not exist &quot;, &quot;accounts_customuser&quot;.&quot;password&quot;, &quot;accounts_customuser&quot;.&quot;last_login&quot;, &quot;accounts_customuser&quot;.&quot;is_superuser&quot;, &quot;accounts_customuser&quot;.&quot;username&quot;, &quot;accounts_customuser&quot;.&quot;first_name&quot;, &quot;accounts_customuser&quot;.&quot;last_name&quot;, &quot;accounts_customuser&quot;.&quot;email&quot;, &quot;accounts_customuser&quot;.&quot;is_staff&quot;, &quot;accounts_customuser&quot;.&quot;is_active&quot;, &quot;accounts_customuser&quot;.&quot;date_joined&quot; FROM &quot;accounts_customuser&quot; WHERE &quot;accounts_customuser&quot;.&quot;username&quot; = 'admin' LIMIT 21 stockwhiz-db-1 | 2022-11-04 13:38:26.019 UTC [41] ERROR: relation &quot;accounts_customuser&quot; does not existstockwhiz-db-1 | 2022-11-04 13:38:26.019 UTC [41] STATEMENT: ALTER TABLE &quot;account_emailaddress&quot; ADD CONSTRAINT &quot;account_emailaddress_user_id_2c513194_fk_accounts_customuser_id&quot; FOREIGN KEY (&quot;user_id&quot;) REFERENCES &quot;accounts_customuser&quot; (&quot;id&quot;) DEFERRABLE INITIALLY DEFERRED </code></pre> <hr /> <p>Could you please direct me towards a solution.</p>
[ { "answer_id": 74321571, "author": "MajorPig", "author_id": 17779866, "author_profile": "https://Stackoverflow.com/users/17779866", "pm_score": 1, "selected": false, "text": "makemigrations" }, { "answer_id": 74325689, "author": "Savakar Rohan", "author_id": 12379923, "author_profile": "https://Stackoverflow.com/users/12379923", "pm_score": 0, "selected": false, "text": "migrations" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12379923/" ]
74,318,223
<p>I have a SQL Code which i am trying to Convert into Pyspark? The SQL Query looks like this: I need to Concatenate '0' at starting of 'ADDRESS_HOME' if the below Query Conditions Satisfies.</p> <pre><code> UPDATE STUDENT_DATA SET STUDENT_DATA.ADDRESS_HOME = &quot;0&quot; &amp; [STUDENT_DATA].ADDRESS_HOME WHERE (((STUDENT_DATA.STATE_ABB)=&quot;TURIN&quot; Or (STUDENT_DATA.STATE_ABB)=&quot;RUSH&quot; Or (STUDENT_DATA.STATE_ABB)=&quot;MEXIC&quot; Or (STUDENT_DATA.STATE_ABB)=&quot;VINTA&quot;) AND ((Len([ADDRESS_HOME])) &lt; &quot;5&quot;)); </code></pre> <p>Thank you in Advance for your responses</p> <pre><code># +---+---------------+---------+ # | ID|ADDRESS_HOME | STATE_ABB| # +---+---------------+---------+ # | 1| 7645 |RUSH | # | 2| 98364 |MEXIC | # | 3| 2980 |TURIN | # | 4| 6728 |VINTA | # | 5| 128 |VINTA | EXPECTED OUTPUT # +---+---------------+---------+ # | ID|ADDRESS_HOME | STATE_ABB| # +---+---------------+---------+ # | 1| 07645 |RUSH | # | 2| 98364 |MEXIC | # | 3| 02980 |TURIN | # | 4| 06728 |VINTA | # | 5| 0128 |VINTA | </code></pre>
[ { "answer_id": 74320658, "author": "OdiumPura", "author_id": 16459035, "author_profile": "https://Stackoverflow.com/users/16459035", "pm_score": 1, "selected": false, "text": "df = df.filter(\n (f.col(\"STATE_ABB\").isin(f.lit(\"TURIN\"), f.lit(\"RUSH\"), f.lit(\"TURIN\"), f.lit(\"VINTA\")) &\n (f.len(\"ADDRESS_HOME\") < 5)\n ).withColumn(\n \"ADDRESS_HOME_CONCAT\",\n f.concat(f.lit(\"0\"),f.col(\"ADDRESS_HOME\"))\n ).alias(\"df_filtered\").join(\n df.alias(\"original_df\"),\n on=f.col(\"original_df.Id\") == f.col(\"df_filtered.Id\")\n how='left'\n ).withColumn(\n \"FINAL_ADDRESS\",\n f.coalesce(f.col(\"df_filtered.ADDRESS_HOME_CONCAT\"), f.col(\"original_df.ADDRESS_HOME\")\n ).select(\n f.col(\"original_df.Id\").alias(\"Id\"),\n f.col(\"FINAL_ADDRESS\").alias(\"ADDRESS_HOME\"),\n f.col(\"original_df.STATE_ABB\").alias(\"STATE_ABB\")\n )\n" }, { "answer_id": 74320669, "author": "Emma", "author_id": 2956135, "author_profile": "https://Stackoverflow.com/users/2956135", "pm_score": 3, "selected": true, "text": "lpad" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20216373/" ]
74,318,225
<p>I have two arrays, one with the original data, and another one that contains the same entries but in a new order.</p> <p>How can I sort the original array so that only items nominated in the new order array are moved?</p> <p>Original Array:</p> <pre><code>[ ['tabelle_mannschaft' =&gt; 'SV Winter'], ['tabelle_mannschaft' =&gt; 'Mannschaft 7'], ['tabelle_mannschaft' =&gt; 'TSV HORIZONT'], ['tabelle_mannschaft' =&gt; 'Mannschaft 8'], ] </code></pre> <p>New order array:</p> <pre><code>[ ['tabelle_mannschaft' =&gt; 'TSV HORIZONT'], ['tabelle_mannschaft' =&gt; 'Mannschaft 7'], ] </code></pre> <p>So in the case above as result I need the original array but with items [1] and [2] switched.</p> <p>Desired result:</p> <pre><code>[ ['tabelle_mannschaft' =&gt; 'SV Winter'], ['tabelle_mannschaft' =&gt; 'TSV HORIZONT'], ['tabelle_mannschaft' =&gt; 'Mannschaft 7'], ['tabelle_mannschaft' =&gt; 'Mannschaft 8'], ] </code></pre> <p>For clarity, both arrays can contain much more then 2 or 3 entries.</p>
[ { "answer_id": 74320658, "author": "OdiumPura", "author_id": 16459035, "author_profile": "https://Stackoverflow.com/users/16459035", "pm_score": 1, "selected": false, "text": "df = df.filter(\n (f.col(\"STATE_ABB\").isin(f.lit(\"TURIN\"), f.lit(\"RUSH\"), f.lit(\"TURIN\"), f.lit(\"VINTA\")) &\n (f.len(\"ADDRESS_HOME\") < 5)\n ).withColumn(\n \"ADDRESS_HOME_CONCAT\",\n f.concat(f.lit(\"0\"),f.col(\"ADDRESS_HOME\"))\n ).alias(\"df_filtered\").join(\n df.alias(\"original_df\"),\n on=f.col(\"original_df.Id\") == f.col(\"df_filtered.Id\")\n how='left'\n ).withColumn(\n \"FINAL_ADDRESS\",\n f.coalesce(f.col(\"df_filtered.ADDRESS_HOME_CONCAT\"), f.col(\"original_df.ADDRESS_HOME\")\n ).select(\n f.col(\"original_df.Id\").alias(\"Id\"),\n f.col(\"FINAL_ADDRESS\").alias(\"ADDRESS_HOME\"),\n f.col(\"original_df.STATE_ABB\").alias(\"STATE_ABB\")\n )\n" }, { "answer_id": 74320669, "author": "Emma", "author_id": 2956135, "author_profile": "https://Stackoverflow.com/users/2956135", "pm_score": 3, "selected": true, "text": "lpad" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14454384/" ]
74,318,252
<p>Is there an Excel formula I can write in Excel to separate a combination of numbers and text from a cell?</p> <p>col A is how the data is formatted, cols b - i are how I need them to be:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>col A</th> <th>col b</th> <th>col c</th> <th>col d</th> <th>col e</th> <th>col f</th> <th>col g</th> <th>col h</th> <th>col i</th> </tr> </thead> <tbody> <tr> <td>1EA/1PK/16BX/124CA</td> <td>1</td> <td>EA</td> <td>1</td> <td>PK</td> <td>16</td> <td>BX</td> <td>124</td> <td>CA</td> </tr> <tr> <td>1EA/6CA</td> <td>1</td> <td>EA</td> <td>6</td> <td>CS</td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> </div>
[ { "answer_id": 74318918, "author": "JvdV", "author_id": 9758194, "author_profile": "https://Stackoverflow.com/users/9758194", "pm_score": 3, "selected": true, "text": "B1" }, { "answer_id": 74319655, "author": "P.b", "author_id": 12634230, "author_profile": "https://Stackoverflow.com/users/12634230", "pm_score": 2, "selected": false, "text": "=LET(number,TEXTSPLIT(A1,CHAR(SEQUENCE(1,26,65)),,1),\n text,TEXTSPLIT(A1,SEQUENCE(1,10,0),,1),\n spill,TOROW(VSTACK(number,text),,1),\n remove,SUBSTITUTE(spill,\"/\",\"\"),\nIFERROR(--remove,remove))\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15432491/" ]
74,318,261
<p>In Python, I often find myself implementing the same pattern: count the number of &quot;valid&quot; iterations while processing within a loop, where an &quot;invalid&quot; iteration is skipped over with a continue statement. I use the continue statement instead of <code>if-else</code> blocks to improve readability. Essentially, I do the following:</p> <pre><code>count = 0 for item in collection: do_something_1(item) if not evaluate_some_condition(item): continue count += 1 do_something_2(item) return count </code></pre> <p>There are several nifty tricks one can use to implement similar patterns in a Pythonic manner. For example, <code>enumerate</code>, <code>continue</code>, <code>break</code>, <code>for-else</code>, and <code>while-else</code> come to mind. I am looking for a Pythonic construct to implement the scenario described above.</p> <p>This works (below) but would require the <code>evaluate_some_condition</code> function be executed twice for every element, which can sometimes be unacceptable (it is also less readable in my opinion):</p> <pre><code>count = sum(1 for item in collection if not evaluate_some_condition(item)) for item in collection: do_something_1(item) if not evaluate_some_condition(item): continue do_something_2(item) return count </code></pre> <p>Some construct like the below would be ideal:</p> <pre><code>for count, item in uninterrupted_enumerate(collection): do_something_1(item) if not evaluate_some_condition(item): continue do_something_2(item) return count </code></pre> <p>Any ideas of a built-in Python feature, third-party feature, or future plans to include such a feature?</p>
[ { "answer_id": 74318357, "author": "Bastian Venthur", "author_id": 2881414, "author_profile": "https://Stackoverflow.com/users/2881414", "pm_score": 1, "selected": false, "text": "count = 0\nfor item in collection:\n do_something_1(item)\n if not evaluate_some_condition(item):\n continue\n count += 1\n do_something_2(item)\nreturn count\n" }, { "answer_id": 74318729, "author": "AGN Gazer", "author_id": 8033585, "author_profile": "https://Stackoverflow.com/users/8033585", "pm_score": 0, "selected": false, "text": "class Doer2:\n def __init__(self):\n self.count = 0\n def __call__(self, item):\n self.count += 1\n # put here the code from 'do_something_2()'\n ....\n" }, { "answer_id": 74330166, "author": "Luke Kurlandski", "author_id": 13386085, "author_profile": "https://Stackoverflow.com/users/13386085", "pm_score": 0, "selected": false, "text": "from typing import Callable\n\n\ndef do_something_1(item) -> None:\n ...\n\n\ndef do_something_2(item) -> None:\n ...\n\n\ndef evaluate_some_condition(item: int) -> bool:\n return item % 2 == 0\n\n\ndef count_complete_iterations(\n process_item: Callable[..., bool]\n) -> Callable[..., int]:\n count = 0\n def wrapper(*args, **kwargs) -> int:\n nonlocal count\n if process_item(*args, **kwargs):\n count += 1\n return count\n return wrapper\n\n\n@count_complete_iterations\ndef process_int(item: int) -> bool:\n do_something_1(item)\n if not evaluate_some_condition(item):\n return False\n do_something_2(item)\n return True\n\n\ncollection = range(10)\nfor item in collection:\n count = process_int(item)\nprint(count) # Prints 5\n\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13386085/" ]
74,318,278
<p>I tried to sort an object that contains other objects and arrays in it E.g</p> <pre><code>let object = { '2573': { results: [ { &quot;rooms&quot;: { &quot;price&quot;: 1500 }, }, { &quot;rooms&quot;: { &quot;price&quot;: 1700 }, } ], }, '2574': { results: [ { &quot;rooms&quot;: { &quot;price&quot;: 1800 }, }, { &quot;rooms&quot;: { &quot;price&quot;: 1900 }, } ], }, '2575': { results: [ { &quot;rooms&quot;: { &quot;price&quot;: 1850 }, }, { &quot;rooms&quot;: { &quot;price&quot;: 1200 }, } ], } } </code></pre> <p>I don't really understand how I could sort this object In the first phase, I should clearly access the first key, after accessing the rooms array and then filtering according to the prices found in each rooms object Is this possible?</p> <p>I tried something like this</p> <pre><code>object.sort((a, b) =&gt; Object.keys(a)[0] - Object.keys(b)[0]); </code></pre> <p>But I clearly do not reach the necessary objects to be able to do this filtering</p> <p>So is it possible to sort by the prices of all the rooms in the object?</p> <p>results ascending sort</p> <pre><code>let object = { '2574': { results: [ { &quot;rooms&quot;: { &quot;price&quot;: 1200 }, { &quot;rooms&quot;: { &quot;price&quot;: 1850 }, } } ], }, '2573': { results: [ { &quot;rooms&quot;: { &quot;price&quot;: 1500 }, }, { &quot;rooms&quot;: { &quot;price&quot;: 1700 }, } ], }, '2574': { results: [ { &quot;rooms&quot;: { &quot;price&quot;: 1800 }, }, { &quot;rooms&quot;: { &quot;price&quot;: 1900 }, } ], } } </code></pre>
[ { "answer_id": 74318588, "author": "Rickard Elimää", "author_id": 5526624, "author_profile": "https://Stackoverflow.com/users/5526624", "pm_score": 1, "selected": false, "text": "let object={2573:{results:[{rooms:{price:1500}},{rooms:{price:1700}}]},2574:{results:[{rooms:{price:1800}},{rooms:{price:1900}}]},2575:{results:[{rooms:{price:1850}},{rooms:{price:1200}}]}};\n\nconst sortResults = (obj) => {\n for (key in obj) {\n obj[key].results.sort((a, b) => {\n return a.rooms.price - b.rooms.price;\n });\n }\n \n return obj;\n}\n\nconsole.log( sortResults(object) );" }, { "answer_id": 74318622, "author": "Mohammad Fareed Alam", "author_id": 12829775, "author_profile": "https://Stackoverflow.com/users/12829775", "pm_score": 0, "selected": false, "text": "for(let i in a){\n let element = a[i];\n element.results.sort((el1, el2) => el1.rooms.prices - el2.rooms.prices)\n}\nconsole.log(a);\n" }, { "answer_id": 74318878, "author": "Shreyansh Gupta", "author_id": 18046485, "author_profile": "https://Stackoverflow.com/users/18046485", "pm_score": 0, "selected": false, "text": "// this is the actual function that will do the job\nfunction sortNestedObject(o) {\n return Object.keys(o).reduce((p,c)=>({...p,[c]:{results:object[c].results.sort((a,b)=>a.rooms.price-b.rooms.price)}}),{})\n }\n const object = {\n \"2573\": {\n \"results\": [\n {\n \"rooms\": {\n \"price\": 1700\n }\n },\n {\n \"rooms\": {\n \"price\": 1500\n }\n }\n ]\n },\n \"2574\": {\n \"results\": [\n {\n \"rooms\": {\n \"price\": 1800\n }\n },\n {\n \"rooms\": {\n \"price\": 1900\n }\n }\n ]\n },\n \"2575\": {\n \"results\": [\n {\n \"rooms\": {\n \"price\": 1850\n }\n },\n {\n \"rooms\": {\n \"price\": 1200\n }\n }\n ]\n }\n }\n\n\n const sorted = sortNestedObject(object)\n console.log(sorted)" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20350508/" ]
74,318,331
<p>When I run on chrome on the computer, everything is ok, but on an Android device, there is a bug while clicking a material button on the app.</p> <p><strong>Expected results</strong>: When clicking on the button, the function must do a calculus about the total order discount or add 5000 to the total if some kind of articles are selected.</p> <p><strong>Actual results</strong>: While the function is on top the Navigator switching page in the button onPressed part, nothing appear when clicking on it (the button do not lead to the concerned page). In other side, when the function is down to the Navigator switching page, the function is not implemented (like there is not a certain function there).</p> <p>I have try many type of putting this function on the onPressed part of the button, and many other type of button but the same result.</p> <p><strong>A minimal complete reproductible code sample</strong></p> <p><em>The main.dart</em></p> <pre><code>import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'minimal_cart_bill.dart'; import 'minimal_cart_controller.dart'; void main() { runApp(const MyApp()); } //Stateless du MaterialApp // ignore: must_be_immutable class MyApp extends StatelessWidget { // final bool showHome; const MyApp({Key? key}) : super(key: key); static const String title = &quot;Eclat d'Afrik&quot;; // final userr = UserPreferences.myUser; @override Widget build(BuildContext context) { return MaterialApp( title: title, home: MinimalReproductible(), // home: showHome ? const AuthPage() : OnBrodingPage(), ); } } class MinimalReproductible extends StatelessWidget { MinimalReproductible({super.key}); final minimalController = Get.find&lt;MinimalCartController&gt;(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Bill Generator')), body: MaterialButton( onPressed: () { minimalController.realIfSuExpress(); Navigator.of(context).push( MaterialPageRoute(builder: (builder) =&gt; const MinimalCartBill())); }, color: const Color(0xFF5ACC80), height: 55.0, child: const Text( &quot;GENERATE MY BILL&quot;, style: TextStyle( fontWeight: FontWeight.bold, fontSize: 14.0, color: Colors.black, ), ), ), ); } } </code></pre> <p><em>The minimal_cart_controller.dart</em></p> <pre><code>// ignore: depend_on_referenced_packagesimport 'package:get/get.dart'; class MinimalCartController extends GetxController { var realTotal = 0.0;var globalsom = 3000.0;var ifCinqMilles = 5000.0;var totalOfArticles = 2.0;var theRemiseTwenty = 0.0;var theRemiseTen = 0.0; void realIfSuExpress() {realTotal = globalsom + ifCinqMilles;if (totalOfArticles &gt; 20) {theRemiseTwenty = (globalsom * 20) / 100;}if (totalOfArticles &gt; 9 &amp;&amp; totalOfArticles &lt; 20) {theRemiseTen = (globalsom * 15) / 100;}}} </code></pre> <p><em>The minimal_cart_bill.dart</em></p> <pre><code>import 'package:flutter/material.dart'; class MinimalCartBill extends StatelessWidget { const MinimalCartBill({super.key}); @override Widget build(BuildContext context) {return Scaffold(appBar: AppBar(title: const Text('Welcome Page')),body: const Padding(padding: EdgeInsets.all(.0),child: Text (&quot;Welcome !&quot;,style: TextStyle(fontWeight: FontWeight.bold,fontSize: 14.0,color: Colors.black,),),),);}} </code></pre> <p><strong>Logs</strong></p> <ul> <li><p>Flutter run --verbose <a href="https://github.com/flutter/flutter/files/9924282/my.flutter.run.verbose.txt" rel="nofollow noreferrer">my flutter run verbose.txt</a></p> </li> <li><p>Flutter Analyse</p> </li> </ul> <p>Analyzing afrikeclat...</p> <p>0 issue found. (ran in 548.3s)</p> <ul> <li>Flutter Doctor</li> </ul> <p>[√] Flutter (Channel stable, 3.3.3, on Microsoft Windows [version 10.0.19044.2130], locale fr-FR) • Flutter version 3.3.3 on channel stable at C:\Users\Asus\flutter • Upstream repository <a href="https://github.com/flutter/flutter.git" rel="nofollow noreferrer">https://github.com/flutter/flutter.git</a> • Framework revision 18a827f393 (5 weeks ago), 2022-09-28 10:03:14 -0700 • Engine revision 5c984c26eb • Dart version 2.18.2 • DevTools version 2.15.0</p> <p>Checking Android licenses is taking an unexpectedly long time...[√] Android toolchain - develop for Android devices (Android SDK version 33.0.0) • Android SDK at C:\Users\Asus\AppData\Local\Android\sdk • Platform android-TiramisuPrivacySandbox, build-tools 33.0.0 • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866) • All Android licenses accepted.</p> <p>[√] Chrome - develop for the web • Chrome at C:\Program Files (x86)\Google\Chrome\Application\chrome.exe</p> <p>[√] Visual Studio - develop for Windows (Visual Studio Community 2022 17.2.6) • Visual Studio at C:\Program Files\Microsoft Visual Studio\2022\Community • Visual Studio Community 2022 version 17.2.32630.192 • Windows 10 SDK version 10.0.19041.0</p> <p>[√] Android Studio (version 2021.3) • Android Studio at C:\Program Files\Android\Android Studio • Flutter plugin can be installed from: <a href="https://plugins.jetbrains.com/plugin/9212-flutter" rel="nofollow noreferrer">https://plugins.jetbrains.com/plugin/9212-flutter</a> • Dart plugin can be installed from: <a href="https://plugins.jetbrains.com/plugin/6351-dart" rel="nofollow noreferrer">https://plugins.jetbrains.com/plugin/6351-dart</a> • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)</p> <p>[√] VS Code (version 1.72.2) • VS Code at C:\Users\Asus\AppData\Local\Programs\Microsoft VS Code • Flutter extension version 3.50.0</p> <p>[√] Connected device (3 available) • Windows (desktop) • windows • windows-x64 • Microsoft Windows [version 10.0.19044.2130] • Chrome (web) • chrome • web-javascript • Google Chrome 107.0.5304.87 • Edge (web) • edge • web-javascript • Microsoft Edge 106.0.1370.37</p> <p>[√] HTTP Host Availability • All required HTTP hosts are available</p> <p>• No issues found!</p>
[ { "answer_id": 74318588, "author": "Rickard Elimää", "author_id": 5526624, "author_profile": "https://Stackoverflow.com/users/5526624", "pm_score": 1, "selected": false, "text": "let object={2573:{results:[{rooms:{price:1500}},{rooms:{price:1700}}]},2574:{results:[{rooms:{price:1800}},{rooms:{price:1900}}]},2575:{results:[{rooms:{price:1850}},{rooms:{price:1200}}]}};\n\nconst sortResults = (obj) => {\n for (key in obj) {\n obj[key].results.sort((a, b) => {\n return a.rooms.price - b.rooms.price;\n });\n }\n \n return obj;\n}\n\nconsole.log( sortResults(object) );" }, { "answer_id": 74318622, "author": "Mohammad Fareed Alam", "author_id": 12829775, "author_profile": "https://Stackoverflow.com/users/12829775", "pm_score": 0, "selected": false, "text": "for(let i in a){\n let element = a[i];\n element.results.sort((el1, el2) => el1.rooms.prices - el2.rooms.prices)\n}\nconsole.log(a);\n" }, { "answer_id": 74318878, "author": "Shreyansh Gupta", "author_id": 18046485, "author_profile": "https://Stackoverflow.com/users/18046485", "pm_score": 0, "selected": false, "text": "// this is the actual function that will do the job\nfunction sortNestedObject(o) {\n return Object.keys(o).reduce((p,c)=>({...p,[c]:{results:object[c].results.sort((a,b)=>a.rooms.price-b.rooms.price)}}),{})\n }\n const object = {\n \"2573\": {\n \"results\": [\n {\n \"rooms\": {\n \"price\": 1700\n }\n },\n {\n \"rooms\": {\n \"price\": 1500\n }\n }\n ]\n },\n \"2574\": {\n \"results\": [\n {\n \"rooms\": {\n \"price\": 1800\n }\n },\n {\n \"rooms\": {\n \"price\": 1900\n }\n }\n ]\n },\n \"2575\": {\n \"results\": [\n {\n \"rooms\": {\n \"price\": 1850\n }\n },\n {\n \"rooms\": {\n \"price\": 1200\n }\n }\n ]\n }\n }\n\n\n const sorted = sortNestedObject(object)\n console.log(sorted)" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19640643/" ]
74,318,333
<p>I am trying to create an edit function for updating a task that was previously written.</p> <p>I have tried this so far but apparently the prompt is only for the browser. Would this even work? What are alternatives to create the prompt for react native?</p> <pre><code> const taskUpdate = (index) =&gt; { const newItemsCopy = [...taskItems]; const item = newItemsCopy[index]; let newItem = prompt(`Update ${item.task}?`, item.task); let todoObj = { todo: newItem, complete: false }; newItemsCopy.splice(index, 1, todoObj); if (newItem === null || newItem === &quot;&quot;) { return; } else { item.task = newItem; } setTaskItems(newTodoItems); } </code></pre> <p><a href="https://pastebin.com/yaRejwUq" rel="nofollow noreferrer">Full Code</a></p>
[ { "answer_id": 74318588, "author": "Rickard Elimää", "author_id": 5526624, "author_profile": "https://Stackoverflow.com/users/5526624", "pm_score": 1, "selected": false, "text": "let object={2573:{results:[{rooms:{price:1500}},{rooms:{price:1700}}]},2574:{results:[{rooms:{price:1800}},{rooms:{price:1900}}]},2575:{results:[{rooms:{price:1850}},{rooms:{price:1200}}]}};\n\nconst sortResults = (obj) => {\n for (key in obj) {\n obj[key].results.sort((a, b) => {\n return a.rooms.price - b.rooms.price;\n });\n }\n \n return obj;\n}\n\nconsole.log( sortResults(object) );" }, { "answer_id": 74318622, "author": "Mohammad Fareed Alam", "author_id": 12829775, "author_profile": "https://Stackoverflow.com/users/12829775", "pm_score": 0, "selected": false, "text": "for(let i in a){\n let element = a[i];\n element.results.sort((el1, el2) => el1.rooms.prices - el2.rooms.prices)\n}\nconsole.log(a);\n" }, { "answer_id": 74318878, "author": "Shreyansh Gupta", "author_id": 18046485, "author_profile": "https://Stackoverflow.com/users/18046485", "pm_score": 0, "selected": false, "text": "// this is the actual function that will do the job\nfunction sortNestedObject(o) {\n return Object.keys(o).reduce((p,c)=>({...p,[c]:{results:object[c].results.sort((a,b)=>a.rooms.price-b.rooms.price)}}),{})\n }\n const object = {\n \"2573\": {\n \"results\": [\n {\n \"rooms\": {\n \"price\": 1700\n }\n },\n {\n \"rooms\": {\n \"price\": 1500\n }\n }\n ]\n },\n \"2574\": {\n \"results\": [\n {\n \"rooms\": {\n \"price\": 1800\n }\n },\n {\n \"rooms\": {\n \"price\": 1900\n }\n }\n ]\n },\n \"2575\": {\n \"results\": [\n {\n \"rooms\": {\n \"price\": 1850\n }\n },\n {\n \"rooms\": {\n \"price\": 1200\n }\n }\n ]\n }\n }\n\n\n const sorted = sortNestedObject(object)\n console.log(sorted)" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17313643/" ]
74,318,341
<p>So I had a job interview two days ago and they used coderPad.io for it, which is pretty common for job interviews. As a matter of fact, I have another job interview coming up that uses coderPad as well, so I really need to ask this question.</p> <p>Essentially what happened was that my algorithm was written correctly. My interviewer told me so. However, the hash map was not working and we started debugging until the interviewer got tired and ended the interview right there. I then received a rejection email a day later. The interviewer did however narrow it down to the insert function on the hash map. We tried different ways of inserting and it still did now work.</p> <p>I had to write an algorithm that needed for me to find the frequency for every integer element in a vector. However, when I had print the contents of the hash map, the frequency is always 1 for each element when it is not supposed to be 1 for each element. This had cost me the interview process to continue. I have recreated the algorithm on coderPad just now and the same issue is occurring. Here is the code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;unordered_map&gt; #include &lt;vector&gt; using namespace std; // To execute C++, please define &quot;int main()&quot; class hashMapTester { public: hashMapTester() { } unordered_map&lt;int, int&gt; collectMap(vector&lt;int&gt;&amp; arr) { unordered_map&lt;int, int&gt; map; for (long unsigned int i = 0; i &lt; arr.size(); i++) { if (map.find(arr[i]) != map.end()) { auto freq = map.find(arr[i])-&gt;second; freq++; map.insert(pair&lt;int, int&gt; (arr[i], freq)); } else { map.insert(pair&lt;int, int&gt;(arr[i], 1)); } } return map; } void printMap(unordered_map&lt;int, int&gt; map, vector&lt;int&gt;&amp; arr) { for (const auto&amp; iter : map) { cout &lt;&lt; iter.second &lt;&lt; endl; } } }; int main() { vector&lt;int&gt; arr = {1, 2, 2, 3 , 4 , 4, 4}; hashMapTester hM; unordered_map&lt;int, int&gt; map = hM.collectMap(arr); hM.printMap(map, arr); return 0; } </code></pre> <p>Why is the frequency portion of the map always outputting 1 when it is not supposed to ? I am stuck on this and I really need to understand why. When I use this algorithm on LeetCode or on another compiler, it works, but not on CoderPad. Can anyone please help me out ? What do I need to do to make it work on CoderPad ?</p>
[ { "answer_id": 74318460, "author": "Nelfeal", "author_id": 3854570, "author_profile": "https://Stackoverflow.com/users/3854570", "pm_score": 0, "selected": false, "text": "operator[]" }, { "answer_id": 74318507, "author": "MarkB", "author_id": 17841694, "author_profile": "https://Stackoverflow.com/users/17841694", "pm_score": 2, "selected": true, "text": "insert" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18093841/" ]
74,318,352
<p>I am building an app with Swift and SwiftUI. In MainViewModel I have a function who call Api for fetching JSON from url and deserialize it. this is made under async/await protocol. the problem is the next, I have received from xcode the next comment : &quot;Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive(on:)) on model updates.&quot; in this part of de code :</p> <pre><code>func getCountries() async throws{ countries = try await MainViewModel.countriesApi.fetchCountries() ?? [] } </code></pre> <p>who calls this one:</p> <pre><code>func fetchCountries() async throws -&gt; [Country]? { guard let url = URL(string: CountryUrl.countriesJSON.rawValue ) else { print(&quot;Invalid URL&quot;) return nil } let urlRequest = URLRequest(url: url) do { let (json, _) = try await URLSession.shared.data(for: urlRequest) if let decodedResponse = try? JSONDecoder().decode([Country].self, from: json) { debugPrint(&quot;return decodeResponse&quot;) return decodedResponse } } catch { debugPrint(&quot;error data&quot;) } return nil } </code></pre> <p>I would like to know if somebody knows how I can fix it</p>
[ { "answer_id": 74318451, "author": "Mr Developer", "author_id": 20384561, "author_profile": "https://Stackoverflow.com/users/20384561", "pm_score": 0, "selected": false, "text": "@MainActor" }, { "answer_id": 74318973, "author": "Joakim Danielson", "author_id": 9223839, "author_profile": "https://Stackoverflow.com/users/9223839", "pm_score": 3, "selected": true, "text": "func getCountries() async throws{ \n let fetchedData = try await MainViewModel.countriesApi.fetchCountries()\n await MainActor.run {\n countries = fetchedData ?? []\n }\n}\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18292838/" ]
74,318,353
<p>i have tried to get user group name as value in auth/me URL, but it returns only objectId of group. How to get the group name instead of objectId.</p> <p>In my manifest i have added</p> <p>&quot;groupMembershipClaims&quot;: &quot;SecurityGroup&quot;</p> <p>optional claims also added</p> <p>i don't have any onpremises AD connect I need the manifest configuration to get the group name in auth/me url</p>
[ { "answer_id": 74318451, "author": "Mr Developer", "author_id": 20384561, "author_profile": "https://Stackoverflow.com/users/20384561", "pm_score": 0, "selected": false, "text": "@MainActor" }, { "answer_id": 74318973, "author": "Joakim Danielson", "author_id": 9223839, "author_profile": "https://Stackoverflow.com/users/9223839", "pm_score": 3, "selected": true, "text": "func getCountries() async throws{ \n let fetchedData = try await MainViewModel.countriesApi.fetchCountries()\n await MainActor.run {\n countries = fetchedData ?? []\n }\n}\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19679562/" ]
74,318,361
<p>I have 2 columns in my google sheet - Time, and some Ids</p> <p><a href="https://i.stack.imgur.com/pBdqk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pBdqk.png" alt="enter image description here" /></a></p> <p>My aim is to calculate the number of ids reported in an hour. For example, from this image we can tell from 10AM to 11AM - 4 ids, and from 11AM to 12PM - 5 ids. I want to come up with a <strong>QUERY Function ONLY</strong> that helps me do so, and group the number of IDs hour-wise. Any help would be much appreciated.</p>
[ { "answer_id": 74318451, "author": "Mr Developer", "author_id": 20384561, "author_profile": "https://Stackoverflow.com/users/20384561", "pm_score": 0, "selected": false, "text": "@MainActor" }, { "answer_id": 74318973, "author": "Joakim Danielson", "author_id": 9223839, "author_profile": "https://Stackoverflow.com/users/9223839", "pm_score": 3, "selected": true, "text": "func getCountries() async throws{ \n let fetchedData = try await MainViewModel.countriesApi.fetchCountries()\n await MainActor.run {\n countries = fetchedData ?? []\n }\n}\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19082958/" ]
74,318,365
<p>I see a lot of same questions with mine, but none of them worked for me. So I am trying to navigate to the url after successful subscribing, but it is not navigating to url instead it is again redirecting to beginning.</p> <pre><code>private moveToOverview(): void { this.userService.reloadUser().subscribe(() =&gt; { this.router.navigate(['/wallet'])}); } </code></pre> <p>If I console the data <code>.subscribe((data) =&gt; {console.log(data); // and then navigate to the url})</code>, it is logging the data but not navigating.</p>
[ { "answer_id": 74318451, "author": "Mr Developer", "author_id": 20384561, "author_profile": "https://Stackoverflow.com/users/20384561", "pm_score": 0, "selected": false, "text": "@MainActor" }, { "answer_id": 74318973, "author": "Joakim Danielson", "author_id": 9223839, "author_profile": "https://Stackoverflow.com/users/9223839", "pm_score": 3, "selected": true, "text": "func getCountries() async throws{ \n let fetchedData = try await MainViewModel.countriesApi.fetchCountries()\n await MainActor.run {\n countries = fetchedData ?? []\n }\n}\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15148870/" ]
74,318,369
<p>I have a data frame and i am creating bins with pd.qcut as following:</p> <pre><code>us_counties['bins'] = pd.qcut(us_counties['economic connectedness'], q=10,precision=2) </code></pre> <p>The bins are:</p> <pre><code>us_counties.bins.cat.categories IntervalIndex([(0.27999999999999997, 0.58], (0.58, 0.67], (0.67, 0.72], (0.72, 0.76], (0.76, 0.81], (0.81, 0.85], (0.85, 0.9], (0.9, 0.97], (0.97, 1.06], (1.06, 1.36]], dtype='interval[float64, right]') </code></pre> <p>I want to change their format so the first bin is &lt;0.58, the medium ones 0.67-0.72 and the last one &gt;1.06.</p> <p>I managed to make the format of the medium ones with the following command:</p> <pre><code>us_counties.bins.cat.categories = [f'{i.left} - {i.right}' for i in us_counties.bins.cat.categories] </code></pre> <p>How can I change the first and last one, so that I end with bins that look like:</p> <pre><code>['&lt;0.58','0.58 - 0.67',....,'0.97 - 1.06','&gt;1.06'] </code></pre>
[ { "answer_id": 74318757, "author": "hsaltan", "author_id": 10905535, "author_profile": "https://Stackoverflow.com/users/10905535", "pm_score": 0, "selected": false, "text": "qcut" }, { "answer_id": 74323701, "author": "Vincent Rupp", "author_id": 4024409, "author_profile": "https://Stackoverflow.com/users/4024409", "pm_score": 3, "selected": true, "text": "mybinlabels = [f'{i.left} - {i.right}' for i in us_counties.bins.cat.categories]\nmybinlabels[0] = [\"<\"+str(i.right) for i in [us_counties.bins.cat.categories[0]]]\nmybinlabels[-1] = [\">\"+str(i.left) for i in [us_counties.bins.cat.categories[-1]]]\nus_counties.bins.cat.categories = mybinlabels\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5826233/" ]
74,318,372
<p>Sample table (customer) have the following data,</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: right;">RecID</th> <th style="text-align: center;">createdDate</th> <th>UserID</th> <th style="text-align: right;">ROWNUMBER</th> <th style="text-align: center;">toCount</th> </tr> </thead> <tbody> <tr> <td style="text-align: right;">1</td> <td style="text-align: center;">10-25-2022</td> <td>User01</td> <td style="text-align: right;">1</td> <td style="text-align: center;">true</td> </tr> <tr> <td style="text-align: right;">2</td> <td style="text-align: center;">10-14-2022</td> <td>User01</td> <td style="text-align: right;">2</td> <td style="text-align: center;">true</td> </tr> <tr> <td style="text-align: right;">3</td> <td style="text-align: center;">01-25-2020</td> <td>User01</td> <td style="text-align: right;">3</td> <td style="text-align: center;">true</td> </tr> <tr> <td style="text-align: right;">4</td> <td style="text-align: center;">10-19-2022</td> <td>User02</td> <td style="text-align: right;">1</td> <td style="text-align: center;">true</td> </tr> </tbody> </table> </div> <p>As per below query, will get the similar customer with rowNumber(). Think the problem is the the comparison of data set with createdDate.</p> <pre class="lang-sql prettyprint-override"><code>select RecID, createdDate, UserID, row_number() over (partition by UserID order by UserID) as &quot;ROWNUMBER&quot;, toCount from ( select *, (case when datediff(day, lag(createdDate,50,createdDate) over (partition by UserID order by UserID), createdDate) &lt;= 1 then 'true' else 'false' end) as toCount from customer ) t </code></pre> <p>The problem: All users should receive a flag (count), who had not registered in the last 50 days. like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: right;">RecID</th> <th style="text-align: center;">createdDate</th> <th>UserID</th> <th style="text-align: right;">ROWNUMBER</th> <th style="text-align: center;">toCount</th> </tr> </thead> <tbody> <tr> <td style="text-align: right;">1</td> <td style="text-align: center;">10-25-2022</td> <td>User01</td> <td style="text-align: right;">1</td> <td style="text-align: center;">false</td> </tr> <tr> <td style="text-align: right;">2</td> <td style="text-align: center;">10-14-2022</td> <td>User01</td> <td style="text-align: right;">2</td> <td style="text-align: center;">true</td> </tr> <tr> <td style="text-align: right;">3</td> <td style="text-align: center;">01-25-2020</td> <td>User01</td> <td style="text-align: right;">3</td> <td style="text-align: center;">true</td> </tr> <tr> <td style="text-align: right;">4</td> <td style="text-align: center;">10-19-2022</td> <td>User02</td> <td style="text-align: right;">1</td> <td style="text-align: center;">true</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74318757, "author": "hsaltan", "author_id": 10905535, "author_profile": "https://Stackoverflow.com/users/10905535", "pm_score": 0, "selected": false, "text": "qcut" }, { "answer_id": 74323701, "author": "Vincent Rupp", "author_id": 4024409, "author_profile": "https://Stackoverflow.com/users/4024409", "pm_score": 3, "selected": true, "text": "mybinlabels = [f'{i.left} - {i.right}' for i in us_counties.bins.cat.categories]\nmybinlabels[0] = [\"<\"+str(i.right) for i in [us_counties.bins.cat.categories[0]]]\nmybinlabels[-1] = [\">\"+str(i.left) for i in [us_counties.bins.cat.categories[-1]]]\nus_counties.bins.cat.categories = mybinlabels\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4691159/" ]
74,318,375
<p>I have a horizontally centered column of Flex items ordered from 1 to 5 that are aligned from the top of the container like this:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body, html { height: 100%; position: relative; margin: 0; padding: 0; } .container { display: inline-flex; flex-wrap: wrap; flex-direction: column; align-items: flex-end; align-content: center; width: 100%; height: 100%; background: pink; } .item { margin: 1px; width: 30px; height: 30px; background: green; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class=container&gt;&lt;div class=item&gt;1&lt;/div&gt;&lt;div class=item&gt;2&lt;/div&gt;&lt;div class=item&gt;3&lt;/div&gt;&lt;div class=item&gt;4&lt;/div&gt;&lt;div class=item&gt;5&lt;/div&gt;&lt;/div&gt;</code></pre> </div> </div> </p> <p>I would like to let it aligned by the bottom of the container instead. I manage to do it with <code>flex-direction: column-reverse;</code> like in the next Snippet:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body, html { height: 100%; position: relative; margin: 0; padding: 0; } .container { display: inline-flex; flex-wrap: wrap; flex-direction: column-reverse; align-items: flex-end; align-content: center; width: 100%; height: 100%; background: pink; } .item { margin: 1px; width: 30px; height: 30px; background: green; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class=container&gt;&lt;div class=item&gt;1&lt;/div&gt;&lt;div class=item&gt;2&lt;/div&gt;&lt;div class=item&gt;3&lt;/div&gt;&lt;div class=item&gt;4&lt;/div&gt;&lt;div class=item&gt;5&lt;/div&gt;&lt;/div&gt;</code></pre> </div> </div> </p> <p>However, as you see, the items get out of order! <strong>Is there a way to let a flex column on the bottom without reversing the items order using CSS?</strong> I tried every Flex property that I know so far without success.</p>
[ { "answer_id": 74318757, "author": "hsaltan", "author_id": 10905535, "author_profile": "https://Stackoverflow.com/users/10905535", "pm_score": 0, "selected": false, "text": "qcut" }, { "answer_id": 74323701, "author": "Vincent Rupp", "author_id": 4024409, "author_profile": "https://Stackoverflow.com/users/4024409", "pm_score": 3, "selected": true, "text": "mybinlabels = [f'{i.left} - {i.right}' for i in us_counties.bins.cat.categories]\nmybinlabels[0] = [\"<\"+str(i.right) for i in [us_counties.bins.cat.categories[0]]]\nmybinlabels[-1] = [\">\"+str(i.left) for i in [us_counties.bins.cat.categories[-1]]]\nus_counties.bins.cat.categories = mybinlabels\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5875416/" ]
74,318,475
<p>I'm using &quot;Web scraper apify&quot; to scrap some data from a website. The goal is to get all the texts in H2 and return an array of them. My problem is when I returned the array. This one is not correct and not usable because it separates all the letters of the different scrapped texts.</p> <p>I tried to write this code (javascript and jquery including):</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function pageFunction() { const results = [] $('h2').map(function() { results.push($(this).text()); }); return results; } console.log(pageFunction());</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;h2&gt;Heading One&lt;/h2&gt; &lt;h2&gt;Heading Two&lt;/h2&gt; &lt;h2&gt;Heading Three&lt;/h2&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <p>And I have this result when I export in JSON</p> <pre><code>[{ &quot;0&quot;: &quot;M&quot;, &quot;1&quot;: &quot;u&quot;, &quot;2&quot;: &quot;t&quot;, &quot;3&quot;: &quot;i&quot;, &quot;4&quot;: &quot;n&quot;, &quot;5&quot;: &quot;y&quot; }, { &quot;0&quot;: &quot;G&quot;, &quot;1&quot;: &quot;r&quot;, &quot;2&quot;: &quot;o&quot;, &quot;3&quot;: &quot;w&quot;, &quot;4&quot;: &quot;S&quot;, &quot;5&quot;: &quot;u&quot;, &quot;6&quot;: &quot;m&quot;, &quot;7&quot;: &quot;o&quot; }, { &quot;0&quot;: &quot;C&quot;, &quot;1&quot;: &quot;u&quot;, &quot;2&quot;: &quot;s&quot;, &quot;3&quot;: &quot;t&quot;, &quot;4&quot;: &quot;o&quot;, &quot;5&quot;: &quot;m&quot;, &quot;6&quot;: &quot;e&quot;, &quot;7&quot;: &quot;r&quot;, &quot;8&quot;: &quot;.&quot;, &quot;9&quot;: &quot;i&quot;, &quot;10&quot;: &quot;o&quot; }] </code></pre> <p>I would like something like</p> <pre><code> [{ &quot;tool&quot;: &quot;Mutiny&quot; }, { &quot;tool&quot;: &quot;Growsumo&quot; }, { &quot;tool&quot;:&quot;customer.io&quot; }] </code></pre>
[ { "answer_id": 74318757, "author": "hsaltan", "author_id": 10905535, "author_profile": "https://Stackoverflow.com/users/10905535", "pm_score": 0, "selected": false, "text": "qcut" }, { "answer_id": 74323701, "author": "Vincent Rupp", "author_id": 4024409, "author_profile": "https://Stackoverflow.com/users/4024409", "pm_score": 3, "selected": true, "text": "mybinlabels = [f'{i.left} - {i.right}' for i in us_counties.bins.cat.categories]\nmybinlabels[0] = [\"<\"+str(i.right) for i in [us_counties.bins.cat.categories[0]]]\nmybinlabels[-1] = [\">\"+str(i.left) for i in [us_counties.bins.cat.categories[-1]]]\nus_counties.bins.cat.categories = mybinlabels\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20418105/" ]
74,318,498
<p>Joining two tables and grouping, we're trying to get the sum of a user's value but only include a user's value once if that user is represented in a grouping multiple times.</p> <p>Some sample tables:</p> <p><code>user</code> table:</p> <pre class="lang-bash prettyprint-override"><code>| id | net_worth | ------------------ | 1 | 100 | | 2 | 1000 | </code></pre> <p><code>visit</code> table:</p> <pre class="lang-bash prettyprint-override"><code>| id | location | user_id | ----------------------------- | 1 | mcdonalds | 1 | | 2 | mcdonalds | 1 | | 3 | mcdonalds | 2 | | 4 | subway | 1 | </code></pre> <p>We want to find the total net worth of users visiting each location. User <code>1</code> visited McDonalds twice, but we don't want to double count their net worth. Ideally we can use a <code>SUM</code> but only add in the net worth value if that user hasn't already been counted for at that location. Something like this:</p> <pre><code>-- NOTE: Hypothetical query SELECT location, SUM(CASE WHEN DISTINCT user.id then user.net_worth ELSE 0 END) as total_net_worth FROM visit JOIN user on user.id = visit.user_id GROUP BY 1; </code></pre> <p>The ideal output being:</p> <pre class="lang-bash prettyprint-override"><code>| location | total_net_worth | ------------------------------- | mcdonalds | 1100 | | subway | 100 | </code></pre> <p>This particular database is Redshift/PostgreSQL, but it would be interesting if there is a generic SQL solution. Is something like the above possible?</p>
[ { "answer_id": 74318630, "author": "a_horse_with_no_name", "author_id": 330315, "author_profile": "https://Stackoverflow.com/users/330315", "pm_score": 0, "selected": false, "text": "select v.location, sum(u.net_worth)\nfrom \"user\" u\n join (\n select location, user_id, \n row_number() over (partition by location, user_id) as rn\n from visit\n order by user_id, location, id\n ) v on v.user_id = u.id and v.rn = 1\ngroup by v.location;\n" }, { "answer_id": 74318642, "author": "sankar", "author_id": 4017098, "author_profile": "https://Stackoverflow.com/users/4017098", "pm_score": 0, "selected": false, "text": "SELECT v.location, SUM(u.net_worth)\nFROM (SELECT location, user_id FROM visit GROUP BY location, user_id) v\n JOIN user u on u.id = v.user_id\nGROUP BY v.location;\n" }, { "answer_id": 74318646, "author": "Thorsten Kettner", "author_id": 2270762, "author_profile": "https://Stackoverflow.com/users/2270762", "pm_score": 2, "selected": true, "text": "SELECT\n v.location,\n SUM(u.net_worth) as total_net_worth\nFROM (SELECT DISTINCT location, user_id FROM visit) v\nJOIN user u on u.id = v.user_id\nGROUP BY v.location\nORDER BY v.location;\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2595659/" ]
74,318,501
<p>I want to have a number that halves until it reaches 1, then it should return a count of how many times it halved. example:</p> <p>halve(4) 2</p> <p>halve(11) 3</p> <p>since 4/2 = 2 and 2/2= 1, hence it halved twice before reaching 1, and this is what I want it to return but my code isn't working, why? Can a modification be made ?</p> <p>Here's my code</p> <p>Python</p> <pre><code>def halve(n): i = 0 for i in range(n,1): if float(i/2) &gt;=1: i+=1 return i </code></pre> <p>Thanks,</p>
[ { "answer_id": 74318540, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 1, "selected": false, "text": "import math\n\ndef halve(n):\n return math.floor(math.log(n, 2))\n" }, { "answer_id": 74318666, "author": "matszwecja", "author_id": 9296093, "author_profile": "https://Stackoverflow.com/users/9296093", "pm_score": 0, "selected": false, "text": "if" }, { "answer_id": 74318683, "author": "John Gordon", "author_id": 494134, "author_profile": "https://Stackoverflow.com/users/494134", "pm_score": 0, "selected": false, "text": "while" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20214604/" ]
74,318,512
<p>I run a query on python to get hourly price data from an API, using the get function:</p> <pre><code>result = (requests.get(url_prices, headers=headers, params={'SpotKey':'1','Fields':'hours','FromDate':'2016-05-05','ToDate':'2016-12-05','Currency':'eur','SortType':'ascending'}).json()) </code></pre> <p>where 'SpotKey' identifies the item I want to retrieve from the API, in this example '1' is hourly price timeseries (the other parameters are self explanatory).</p> <p>The result from the query is:</p> <pre><code>{'SpotKey': '1', 'SpotName': 'APX', 'Denomination': 'eur/mwh', 'Elements': [{'Date': '2016-05-05T00:00:00.0000000', 'TimeSpans': [{'TimeSpan': '00:00-01:00', 'Value': 23.69}, {'TimeSpan': '01:00-02:00', 'Value': 21.86}, {'TimeSpan': '02:00-03:00', 'Value': 21.26}, {'TimeSpan': '03:00-04:00', 'Value': 20.26}, {'TimeSpan': '04:00-05:00', 'Value': 19.79}, {'TimeSpan': '05:00-06:00', 'Value': 19.79}, ... {'TimeSpan': '19:00-20:00', 'Value': 57.52}, {'TimeSpan': '20:00-21:00', 'Value': 49.4}, {'TimeSpan': '21:00-22:00', 'Value': 42.23}, {'TimeSpan': '22:00-23:00', 'Value': 34.99}, {'TimeSpan': '23:00-24:00', 'Value': 33.51}]}]} </code></pre> <p>where 'Elements' is the relevant list containing the timeseries, structured as nested dictionaries of 'Date' keys and 'TimeSpans' keys.</p> <p>Each 'TimeSpans' keys contains other nested dictionaries for each hour of the day, with a 'TimeSpan' key for the hour and a 'Value' key for the price.</p> <p>I would like to transform it to a dataframe like:</p> <pre><code>Datetime eur/mwh 2016-05-05 00:00:00 23.69 2016-05-05 01:00:00 21.86 2016-05-05 02:00:00 21.26 2016-05-05 03:00:00 20.26 2016-05-05 04:00:00 19.79 ... ... 2016-12-05 19:00:00 57.52 2016-12-05 20:00:00 49.40 2016-12-05 21:00:00 42.23 2016-12-05 22:00:00 34.99 2016-12-05 23:00:00 33.51 </code></pre> <p>For the time being I managed to do so doing:</p> <pre><code>df = pd.concat([pd.DataFrame(x) for x in result['Elements']]) df['Date'] = pd.to_datetime(df['Date'] + ' ' + [x['TimeSpan'][:5] for x in df['TimeSpans']], errors='coerce') df[result['Denomination']] = [x['Value'] for x in df['TimeSpans']] df = df.set_index(df['Date'], drop=True).drop(columns=['Date','TimeSpans']) df = df[~df.index.isnull()] </code></pre> <p>I did so because the daylight-saving-time is replacing the 'TimeSpan' hourly values with 'dts' string, giving ParseDate errors when creating the datetime index. Since I will request data very frequently and potentially for different granularities (e.g. half-hourly), is there a better / quicker / standard way to shape so many nested dictionaries into a dataframe with the format I look for, that allows to avoid the parsing date error for daylight-saving-time changes?</p> <p>thank you in advance, cheers.</p>
[ { "answer_id": 74348126, "author": "pwoolvett", "author_id": 7814595, "author_profile": "https://Stackoverflow.com/users/7814595", "pm_score": 3, "selected": true, "text": "Date" }, { "answer_id": 74363251, "author": "maxxel_", "author_id": 17575465, "author_profile": "https://Stackoverflow.com/users/17575465", "pm_score": 2, "selected": false, "text": "df = pd.DataFrame()\ncols = ['Datetime', 'eur/mwh']\n\n# concat days together to one df\nfor day in results['Elements']:\n # chunk represents a day worth of data to concat\n chunk = []\n date = pd.to_datetime(day['Date'])\n for pair in day['TimeSpans']:\n # hour offset is just the first 2 characters of TimeSpan\n offset = pd.DateOffset(hours=int(pair['TimeSpan'][:1])\n value = pair['Value']\n chunk.append([(date + offset), value])\n \n # concat day-chunk to df\n df = pd.concat([df, pd.DataFrame(chunk, columns=cols)]\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10190983/" ]
74,318,516
<p>Hi Hopefully somebody can help as i am missing something in my code.</p> <p>I am trying to loop through a dynamic row from the last knowing value to the new values, then add these new values as a column headr in starting in row 3.</p> <p>I have the first portion and can get the new values to paste into next blank column. the issue is i can't work out how to offset to the next empty cell. rather than pasting all new values into the same cell.</p> <pre><code>Sub Testnewname() Dim Nw2 As Integer Dim c As Long Dim D As Long Dim Lcol1 As Long Dim Lrow2 As Long Lcol1 = Cells(3, Columns.Count).End(xlToLeft).Column '' Find last column available in row 3 Lrow2 = Cells(Rows.Count, 10).End(xlUp).Row ''Find last row where new info is put via a table defined by names =UNIQUE(Table1[[#Data],[Company]],FALSE,FALSE) Nw2 = Sheets(&quot;Cost Table&quot;).Range(&quot;$H$10&quot;).Value ''value of the old number of cells used to start from in loop c = Lcol1 + 1 ''allocate a varable to last column + 1 For D = Nw2 To Lrow2 ''for d (i) from cell 19 to last cell Cells(D, 10).Copy 'copy cell value Cells(3, c).PasteSpecial xlPasteValues ''this is where is would of thought pasteinto last column whichit does. What seems to happen is id doesnt move to next column when it reloops Next D ''would of expected that when it goes onto next loop that the C (Lcol+1) would recalculate ThisWorkbook.Worksheets(&quot;Cost Table&quot;).Range(&quot;H11&quot;).Copy ThisWorkbook.Worksheets(&quot;Cost Table&quot;).Range(&quot;H10&quot;).PasteSpecial Paste:=xlPasteValues ' takes the value from a CountA function in H11 and pastes into H10 to update the last place a cell value was prior to running macro and updates Nw2 for running the macro again Application.CutCopyMode = False End Sub </code></pre> <p>I have tried to add in a Second loop for the column but this does nothing</p> <pre><code>For C = Lcol to Lcol + 1 For D = Nw2 To Lrow2 Cells(D, 10).Copy Cells(3, c).PasteSpecial xlPasteValues Next D Next C </code></pre> <p>Any help greatly appreciated</p> <p>cheers</p>
[ { "answer_id": 74348126, "author": "pwoolvett", "author_id": 7814595, "author_profile": "https://Stackoverflow.com/users/7814595", "pm_score": 3, "selected": true, "text": "Date" }, { "answer_id": 74363251, "author": "maxxel_", "author_id": 17575465, "author_profile": "https://Stackoverflow.com/users/17575465", "pm_score": 2, "selected": false, "text": "df = pd.DataFrame()\ncols = ['Datetime', 'eur/mwh']\n\n# concat days together to one df\nfor day in results['Elements']:\n # chunk represents a day worth of data to concat\n chunk = []\n date = pd.to_datetime(day['Date'])\n for pair in day['TimeSpans']:\n # hour offset is just the first 2 characters of TimeSpan\n offset = pd.DateOffset(hours=int(pair['TimeSpan'][:1])\n value = pair['Value']\n chunk.append([(date + offset), value])\n \n # concat day-chunk to df\n df = pd.concat([df, pd.DataFrame(chunk, columns=cols)]\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9209543/" ]
74,318,519
<p>I'm trying to assess if an Oximeter plugged in via USB is correctly collecting heart rate data. I am using the Systole package, and some pre-writtend code sourced here (Scroll down to Recording PPG Signal :<a href="https://embodied-computation-group.github.io/systole/auto_examples/Recording/plot_RecordingPPG.html#sphx-glr-auto-examples-recording-plot-recordingppg-py" rel="nofollow noreferrer">Recording PPG Signal code</a></p> <p>I am having 2 errors, the first is:SerialException: could not open port 'COM4': PermissionError(13, 'Access is denied.', None, 5)</p> <p>And the second is:TypeError: plot_raw() got an unexpected keyword argument 'show_heart_rate'</p> <p>The script I am trying to run:</p> <pre><code>from systole.recording import Oximeter #Option for usin a simulated device, which I am not doing from systole import serialSim # Use a USB device import serial ser = serial.Serial(&quot;COM4&quot;) # Use this line for USB recording </code></pre> <p>#Plotting</p> <pre><code>oxi = Oximeter(serial=ser).setup().read(duration=10) oxi.plot_raw(show_heart_rate=True, figsize=(13, 8)) </code></pre> <p>Below is my desired output:</p> <p><a href="https://i.stack.imgur.com/rozi8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rozi8.png" alt="Desired output" /></a></p>
[ { "answer_id": 74348126, "author": "pwoolvett", "author_id": 7814595, "author_profile": "https://Stackoverflow.com/users/7814595", "pm_score": 3, "selected": true, "text": "Date" }, { "answer_id": 74363251, "author": "maxxel_", "author_id": 17575465, "author_profile": "https://Stackoverflow.com/users/17575465", "pm_score": 2, "selected": false, "text": "df = pd.DataFrame()\ncols = ['Datetime', 'eur/mwh']\n\n# concat days together to one df\nfor day in results['Elements']:\n # chunk represents a day worth of data to concat\n chunk = []\n date = pd.to_datetime(day['Date'])\n for pair in day['TimeSpans']:\n # hour offset is just the first 2 characters of TimeSpan\n offset = pd.DateOffset(hours=int(pair['TimeSpan'][:1])\n value = pair['Value']\n chunk.append([(date + offset), value])\n \n # concat day-chunk to df\n df = pd.concat([df, pd.DataFrame(chunk, columns=cols)]\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18542744/" ]
74,318,521
<p>I have an iOS/wOS app that launched last year. Now I want to add complications to it and use the new way of doing complications with WidgetKit. I have everything in place up to the point where I'm supposed to read the data from Health to display it, where it fails with <code>Missing com.apple.developer.healthkit entitlement</code>.</p> <p>This is the new extension I've added</p> <p><a href="https://i.stack.imgur.com/TPUAA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TPUAA.png" alt="enter image description here" /></a></p> <p>It's embedded in the WatchKit app NOT in the WatchKit Extension and I've added permission to read health data directly in the <code>info.plist</code> for the extension</p> <p><a href="https://i.stack.imgur.com/56JoC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/56JoC.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/NvtOD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NvtOD.png" alt="enter image description here" /></a></p> <p>I pull the data from the <code>TimelineProvider</code> protocol method</p> <pre><code> func getTimeline(in context: Context, completion: @escaping (Timeline&lt;Entry&gt;) -&gt; ()) { let currentDate = Date() var entries: [WorkoutEntry] = [] ComplicationHealthManager.loadPreviousWorkouts { workout in let workoutEntry = WorkoutEntry(date: currentDate, workout: workout) entries.append(workoutEntry) let timeline = Timeline(entries: entries, policy: .after(currentDate)) completion(timeline) } } </code></pre> <p>with the help of a small manager class</p> <pre><code>class ComplicationHealthManager: ObservableObject { static func loadPreviousWorkouts(completion: @escaping (HKWorkout?) -&gt; Void) { let healthStore: HKHealthStore = HKHealthStore() let workoutPredicate = HKQuery.predicateForWorkouts(with: .traditionalStrengthTraining) let compound = NSCompoundPredicate(andPredicateWithSubpredicates: [workoutPredicate]) let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false) let query = HKSampleQuery( sampleType: .workoutType(), predicate: compound, limit: 0, sortDescriptors: [sortDescriptor]) { (query, samples, error) in guard let samples = samples as? [HKWorkout], error == nil else { completion(nil) return } let calendar = Calendar.current let todaysSamples = samples.filter{ calendar.isDateInToday($0.endDate) }.last completion(todaysSamples) } healthStore.execute(query) } } </code></pre> <p>The issue is in the closure for the health query where it returns with no workouts but an error stating</p> <pre><code>Error Domain=com.apple.healthkit Code=4 &quot;Missing com.apple.developer.healthkit entitlement.&quot; UserInfo={NSLocalizedDescription=Missing com.apple.developer.healthkit entitlement.} </code></pre> <p>The problem here is I don't understand where and how to add an entitlement for the complication extension or the WatchKit app, as none of them have the option for health. I have a health entitlements set for the iPhone app and the WatchKit Extension.</p> <p><a href="https://i.stack.imgur.com/rlT71.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rlT71.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74324472, "author": "psolanki", "author_id": 5386319, "author_profile": "https://Stackoverflow.com/users/5386319", "pm_score": 0, "selected": false, "text": "<key>com.apple.developer.healthkit</key>\n<true/>\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2984775/" ]
74,318,525
<p>I need a different format of strings to convert to &quot;DD.MM.YYYY&quot;.</p> <p><code>&quot;Thu, 3 Nov 2022 06:00:00 +0100&quot;</code> has to be changed to <code>&quot;03.11.2022&quot;</code></p> <p>and</p> <p><code>&quot;01.11.2022 20:00:00&quot;</code> to <code>&quot;01.11.2022&quot;</code>.</p> <p>All the formats are in <code>String</code>.</p> <p>I tried doing</p> <pre class="lang-java prettyprint-override"><code>String pattern=&quot;DD.MM.YYYY&quot;; DateTimeFormatter formatter=DateTimeFormatter.ofPattern(pattern); new SimpleDateFormat(pattern).parse(&quot;01.11.2022 20:00:00&quot;) </code></pre> <p>I have also tried doing the following</p> <pre class="lang-java prettyprint-override"><code>java.time.LocalDateTime.parse( item.getStartdatum(), DateTimeFormatter.ofPattern( &quot;DDMMYYYY&quot; ) ).format( DateTimeFormatter.ofPattern(&quot;DD.MM.YYYY&quot;) ) </code></pre> <p>But got the error :</p> <pre><code>Exception in thread &quot;main&quot; java.time.format.DateTimeParseException: Text 'Sun, 30 Oct 2022 00:30:00 +0200' could not be parsed at index 0 </code></pre> <p>I tried doing the following as well</p> <pre class="lang-java prettyprint-override"><code>String pattern=&quot;DD.MM.YYYY&quot;; DateFormat format = new SimpleDateFormat(pattern); Date date = format.parse(01.11.2022 20:00:00); </code></pre> <p>However, I am not getting the correct output. How can I get my desired result?</p>
[ { "answer_id": 74324472, "author": "psolanki", "author_id": 5386319, "author_profile": "https://Stackoverflow.com/users/5386319", "pm_score": 0, "selected": false, "text": "<key>com.apple.developer.healthkit</key>\n<true/>\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11660873/" ]
74,318,559
<p>I have some divs and if i hover them I want an popup to show. I have six divs and six popups to show but not all at once instead only one per one.</p> <p>The first function works fine but then the other do not work how can I move them all to one snippet?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script&gt; document.addEventListener('DOMContentLoaded', function() { let elements = document.querySelectorAll('#Mitarbeiter1Punkt'); let popupposts = ['647']; elements.forEach(function(e, i) { e.addEventListener('mouseenter', function() { elementorProFrontend.modules.popup.showPopup({ id: popupposts[i] }); }); e.addEventListener('mouseleave', function(event) { jQuery('body').click(); }); }); }); document.addEventListener('DOMContentLoaded', function() { let elements = document.querySelectorAll('#Mitarbeiter2Punkt'); let popupposts = ['656']; elements.forEach(function(e, i) { e.addEventListener('mouseenter', function() { elementorProFrontend.modules.popup.showPopup({ id: popupposts[i] }); }); e.addEventListener('mouseleave', function(event) { jQuery('body').click(); }); }); }); &lt;/script&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74318993, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 1, "selected": false, "text": "document.addEventListener('DOMContentLoaded', function() {\n\n let popupMap = [{\n div: '#Mitarbeiter1Punkt',\n popup: 647\n },\n {\n div: '#Mitarbeiter2Punkt',\n popup: 646\n }\n ];\n\n popupMap.forEach(({div, popup}) => {\n let e = document.querySelector(div);\n e.addEventListener('mouseenter', () => elementorProFrontend.modules.popup.showPopup(popup));\n e.addEventListener('mouseleave', () => jQuery('body').click());\n });\n});" }, { "answer_id": 74319188, "author": "freedomn-m", "author_id": 2181514, "author_profile": "https://Stackoverflow.com/users/2181514", "pm_score": 1, "selected": false, "text": "$(\".punkt\").on(\"mouseenter\", function() {\n var id = $(this).data(\"popup-id\");\n $(\".popup[data-popup-id='\" + id + \"']\").show();\n});\n$(\".punkt\").on(\"mouseleave\", function() {\n var id = $(this).data(\"popup-id\");\n $(\".popup[data-popup-id='\" + id + \"']\").hide();\n});" }, { "answer_id": 74345409, "author": "oli venöl", "author_id": 11233039, "author_profile": "https://Stackoverflow.com/users/11233039", "pm_score": 1, "selected": true, "text": "<script>\ndocument.addEventListener('DOMContentLoaded', function() {\n let elements = document.querySelectorAll( '.mitarbeiterPunkt' );\n let popupposts = [ '647', '656', '660', '664', '664', '668', '672']; \n\n elements.forEach(function(e,i){\n e.addEventListener( 'mouseenter', function(){\n elementorProFrontend.modules.popup.showPopup( { id: popupposts[i] } );\n } );\n\n e.addEventListener( 'mouseleave', function(event){\n jQuery('body').click();\n });\n });\n});\n</script>" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11233039/" ]
74,318,570
<p>I have example data as follows:</p> <pre><code>library(data.table) dat &lt;- fread(&quot;q1 q2 ...1 ..2 q3..1 ..1 NA response other else response other 1 4 NA NA 1 NA&quot;) </code></pre> <p>I wanted to filter out all columns that are automatically named when reading in an Excel file with missing column names, which have names like <code>..x</code>. I thought that the following piece of code would work:</p> <pre><code>grepl(&quot;\\.+&quot;, names(dat)) [1] FALSE FALSE TRUE TRUE TRUE TRUE </code></pre> <p>But it also filters out columns which have a similar structure as column <code>q3..1</code>.</p> <p>Although I do not know why the <code>..x</code> part is added to such a column (because it was not empty), I would like to adapt the <code>grepl</code> code, so that the outcome is <code>TRUE</code>, unless the structure is ONLY <code>..x</code>.</p> <p>How should I do this?</p> <p>Desired output:</p> <pre><code>grepl(&quot;\\.+&quot;, names(dat)) [1] FALSE FALSE TRUE TRUE FALSE TRUE </code></pre>
[ { "answer_id": 74318603, "author": "Maël", "author_id": 13460602, "author_profile": "https://Stackoverflow.com/users/13460602", "pm_score": 3, "selected": true, "text": "^" }, { "answer_id": 74319080, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 0, "selected": false, "text": "library(dplyr)\ndat %>% \n select(matches('^[^.]+$'))\n q1 q2\n <int> <char>\n1: NA response\n2: 1 4\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8071608/" ]
74,318,573
<p>I have an example object which is mixed of lists and dicts:</p> <pre><code>{ &quot;field_1&quot; : &quot;aaa&quot;, &quot;field_2&quot;: [ { &quot;name&quot; : &quot;bbb&quot;, ..... &quot;field_4&quot; : &quot;ccc&quot;, &quot;field_need_to_filter&quot; : False, }, { &quot;name&quot; : &quot;ddd&quot;, ..... &quot;details&quot;: [ { &quot;name&quot; : &quot;eee&quot;, .... &quot;details&quot; : [ { &quot;name&quot;: &quot;fff&quot;, ..... &quot;field_10&quot;: { &quot;field_11&quot;: &quot;rrr&quot;, ... &quot;details&quot;: [ { &quot;name&quot;: &quot;xxx&quot;, ... &quot;field_need_to_filter&quot;: True, }, { &quot;name&quot;: &quot;yyy&quot;, ... &quot;field_need_to_filter&quot;: True, }, { &quot;field_13&quot;: &quot;zzz&quot;, ... &quot;field_need_to_filter&quot;: False, } ] } }, ]}]} ] } </code></pre> <p>I'd like to iterate this dictionary and add all the corresponding fields for <code>name</code> where <code>field_need_to_filter</code> is <code>True</code>, so for this example, expected output would be: <code>[&quot;ddd.eee.fff.xxx&quot;, &quot;ddd.eee.fff.yyy&quot;]</code>. I've been looking at this for too long and my brain stops working now, any help would be appreciated. Thanks.</p>
[ { "answer_id": 74321201, "author": "Swifty", "author_id": 20267366, "author_profile": "https://Stackoverflow.com/users/20267366", "pm_score": 2, "selected": true, "text": "mydict = {\n \"field_1\" : \"aaa\",\n \"field_2\": [\n {\n \"name\" : \"bbb\",\n\n \"field_4\" : \"ccc\",\n \"field_need_to_filter\" : False,\n },\n\n {\n \"name\" : \"ddd\",\n\n \"details\": [\n {\n \"name\" : \"eee\",\n\n \"details\" : [\n {\n \"name\": \"fff\",\n\n \"field_10\": {\n \"field_11\": \"rrr\",\n\n \"details\": [\n {\n \"name\": \"xxx\",\n\n \"field_need_to_filter\": True,\n },\n {\n \"name\": \"yyy\",\n\n \"field_need_to_filter\": True,\n },\n {\n \"field_13\": \"zzz\",\n\n \"field_need_to_filter\": False,\n }\n ]\n }\n },\n\n\n ]}]}\n\n ]\n}\n\ndef filter_paths(thing, path=''):\n if type(thing) == dict:\n # if this dict has a name, log it\n if thing.get(\"name\"):\n path += ('.' if path else '') + thing[\"name\"]\n # if this dict has \"...filter\": True, we've reached an end point, and return the path\n if thing.get(\"field_need_to_filter\") and thing[\"field_need_to_filter\"]:\n return [path]\n # else we delve deeper\n result = []\n for key in thing:\n result += [deep_path for deep_path in filter_paths(thing[key], path)]\n return result\n \n # if the current object is a list, we simply delve deeper\n elif type(thing) == list:\n result = []\n for element in thing:\n result += [deep_path for deep_path in filter_paths(element, path)]\n return result\n\n # We've reached a dead-end, so we return an empty list\n else:\n return []\n \nfilter_paths(mydict)\n# Out[204]: ['ddd.eee.fff.xxx', 'ddd.eee.fff.yyy']\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10581944/" ]
74,318,665
<p>[![import &quot;django.shortcuts&quot; could not be resolved from sauce Pylance(reportMissingModuleSoucre)</p> <pre><code>from django.shortcuts import render # Create your views here. def get_home(request): return render(request,'home.html') </code></pre> <p>i didnt try anything,i need some help</p>
[ { "answer_id": 74321201, "author": "Swifty", "author_id": 20267366, "author_profile": "https://Stackoverflow.com/users/20267366", "pm_score": 2, "selected": true, "text": "mydict = {\n \"field_1\" : \"aaa\",\n \"field_2\": [\n {\n \"name\" : \"bbb\",\n\n \"field_4\" : \"ccc\",\n \"field_need_to_filter\" : False,\n },\n\n {\n \"name\" : \"ddd\",\n\n \"details\": [\n {\n \"name\" : \"eee\",\n\n \"details\" : [\n {\n \"name\": \"fff\",\n\n \"field_10\": {\n \"field_11\": \"rrr\",\n\n \"details\": [\n {\n \"name\": \"xxx\",\n\n \"field_need_to_filter\": True,\n },\n {\n \"name\": \"yyy\",\n\n \"field_need_to_filter\": True,\n },\n {\n \"field_13\": \"zzz\",\n\n \"field_need_to_filter\": False,\n }\n ]\n }\n },\n\n\n ]}]}\n\n ]\n}\n\ndef filter_paths(thing, path=''):\n if type(thing) == dict:\n # if this dict has a name, log it\n if thing.get(\"name\"):\n path += ('.' if path else '') + thing[\"name\"]\n # if this dict has \"...filter\": True, we've reached an end point, and return the path\n if thing.get(\"field_need_to_filter\") and thing[\"field_need_to_filter\"]:\n return [path]\n # else we delve deeper\n result = []\n for key in thing:\n result += [deep_path for deep_path in filter_paths(thing[key], path)]\n return result\n \n # if the current object is a list, we simply delve deeper\n elif type(thing) == list:\n result = []\n for element in thing:\n result += [deep_path for deep_path in filter_paths(element, path)]\n return result\n\n # We've reached a dead-end, so we return an empty list\n else:\n return []\n \nfilter_paths(mydict)\n# Out[204]: ['ddd.eee.fff.xxx', 'ddd.eee.fff.yyy']\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20418399/" ]
74,318,682
<p>I am facing the following issue while trying to pass a value from an HTML form <code>&lt;input&gt;</code> element to the form's <code>action</code> attribute and send it to the FastAPI server.</p> <p>This is how the Jinja2 (HTML) template is loaded:</p> <pre class="lang-py prettyprint-override"><code># Test TEMPLATES @app.get(&quot;/test&quot;,response_class=HTMLResponse) async def read_item(request: Request): return templates.TemplateResponse(&quot;index.html&quot;, {&quot;request&quot;: request}) </code></pre> <p>My HTML form:</p> <pre><code>&lt;form action=&quot;/disableSubCategory/{{subCatName}}&quot;&gt; &lt;label for=&quot;subCatName&quot;&gt;SubCategory:&lt;/label&gt;&lt;br&gt; &lt;input type=&quot;text&quot; id=&quot;subCatName&quot; name=&quot;subCatName&quot; value=&quot;&quot;&gt;&lt;br&gt; &lt;input type=&quot;submit&quot; value=&quot;Disable&quot;&gt; &lt;/form&gt; </code></pre> <p>My FastAPI endpoint to be called in the form action:</p> <pre class="lang-py prettyprint-override"><code># Disable SubCategory @app.get(&quot;/disableSubCategory/{subCatName}&quot;) async def deactivateSubCategory(subCatName: str): disableSubCategory(subCatName) return {&quot;message&quot;: &quot;SubCategory [&quot; + subCatName + &quot;] Disabled&quot;} </code></pre> <p>The error I get:</p> <pre><code>&quot;GET /disableSubCategory/?subCatName=Barber HTTP/1.1&quot; 404 Not Found </code></pre> <p>What I am trying to achieve is the following FastAPI call:</p> <pre><code>/disableSubCategory/{subCatName} ==&gt; &quot;/disableSubCategory/Barber&quot; </code></pre> <p>Anyone who could help me understand what I am doing wrong?</p> <p>Thanks. Leo</p>
[ { "answer_id": 74321201, "author": "Swifty", "author_id": 20267366, "author_profile": "https://Stackoverflow.com/users/20267366", "pm_score": 2, "selected": true, "text": "mydict = {\n \"field_1\" : \"aaa\",\n \"field_2\": [\n {\n \"name\" : \"bbb\",\n\n \"field_4\" : \"ccc\",\n \"field_need_to_filter\" : False,\n },\n\n {\n \"name\" : \"ddd\",\n\n \"details\": [\n {\n \"name\" : \"eee\",\n\n \"details\" : [\n {\n \"name\": \"fff\",\n\n \"field_10\": {\n \"field_11\": \"rrr\",\n\n \"details\": [\n {\n \"name\": \"xxx\",\n\n \"field_need_to_filter\": True,\n },\n {\n \"name\": \"yyy\",\n\n \"field_need_to_filter\": True,\n },\n {\n \"field_13\": \"zzz\",\n\n \"field_need_to_filter\": False,\n }\n ]\n }\n },\n\n\n ]}]}\n\n ]\n}\n\ndef filter_paths(thing, path=''):\n if type(thing) == dict:\n # if this dict has a name, log it\n if thing.get(\"name\"):\n path += ('.' if path else '') + thing[\"name\"]\n # if this dict has \"...filter\": True, we've reached an end point, and return the path\n if thing.get(\"field_need_to_filter\") and thing[\"field_need_to_filter\"]:\n return [path]\n # else we delve deeper\n result = []\n for key in thing:\n result += [deep_path for deep_path in filter_paths(thing[key], path)]\n return result\n \n # if the current object is a list, we simply delve deeper\n elif type(thing) == list:\n result = []\n for element in thing:\n result += [deep_path for deep_path in filter_paths(element, path)]\n return result\n\n # We've reached a dead-end, so we return an empty list\n else:\n return []\n \nfilter_paths(mydict)\n# Out[204]: ['ddd.eee.fff.xxx', 'ddd.eee.fff.yyy']\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20418391/" ]
74,318,721
<p>I am currently optimizing a piece of C code with a lot of loops and adding/multiplying two-dimensional float vectors. The code is so slow that I cannot process my data in real time on ARM Cortex-M or even ARM Cortex-A in low CPU mode. I am close to being quick enough on Cortex-A. But on cortex-M... I will need to run this code in a lot of different architectures environments.</p> <p>This is the first time I need to optimize deeply an algorithm to be real-time. I found a lot of papers/articles about loop optimization and vectorization to help me in this task. I am also exploring multi-architecture solution as library OpenBlas.</p> <p>The problem is that my two ARM environments are quite painful. Iterating, rebuilding, deploying the code and measuring the performance is a quite slow process.</p> <p>Any advice to help me to accelerate the process?</p> <ul> <li>Do I must target cross-target optimization first? Specific target optimization?</li> <li>Is it a good idea to iterate on my x86 host and test my optimization on my target later? I am afraid that the best optimization only works for a specific architecture.</li> <li>Can I use perhaps an emulator like QEMU to iterate more quickly? Does it make sense?</li> <li>Is it the best method to analyze the assembler code without running it to check the result of optimization and improvement in the performance? I try to run some minor modifications and compare the result of GCC -S. The output is changing a lot.</li> </ul>
[ { "answer_id": 74321201, "author": "Swifty", "author_id": 20267366, "author_profile": "https://Stackoverflow.com/users/20267366", "pm_score": 2, "selected": true, "text": "mydict = {\n \"field_1\" : \"aaa\",\n \"field_2\": [\n {\n \"name\" : \"bbb\",\n\n \"field_4\" : \"ccc\",\n \"field_need_to_filter\" : False,\n },\n\n {\n \"name\" : \"ddd\",\n\n \"details\": [\n {\n \"name\" : \"eee\",\n\n \"details\" : [\n {\n \"name\": \"fff\",\n\n \"field_10\": {\n \"field_11\": \"rrr\",\n\n \"details\": [\n {\n \"name\": \"xxx\",\n\n \"field_need_to_filter\": True,\n },\n {\n \"name\": \"yyy\",\n\n \"field_need_to_filter\": True,\n },\n {\n \"field_13\": \"zzz\",\n\n \"field_need_to_filter\": False,\n }\n ]\n }\n },\n\n\n ]}]}\n\n ]\n}\n\ndef filter_paths(thing, path=''):\n if type(thing) == dict:\n # if this dict has a name, log it\n if thing.get(\"name\"):\n path += ('.' if path else '') + thing[\"name\"]\n # if this dict has \"...filter\": True, we've reached an end point, and return the path\n if thing.get(\"field_need_to_filter\") and thing[\"field_need_to_filter\"]:\n return [path]\n # else we delve deeper\n result = []\n for key in thing:\n result += [deep_path for deep_path in filter_paths(thing[key], path)]\n return result\n \n # if the current object is a list, we simply delve deeper\n elif type(thing) == list:\n result = []\n for element in thing:\n result += [deep_path for deep_path in filter_paths(element, path)]\n return result\n\n # We've reached a dead-end, so we return an empty list\n else:\n return []\n \nfilter_paths(mydict)\n# Out[204]: ['ddd.eee.fff.xxx', 'ddd.eee.fff.yyy']\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1919173/" ]
74,318,732
<p><a href="https://i.stack.imgur.com/ui4tK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ui4tK.png" alt="enter image description here" /></a>Unknown spacing coming again and again in <code>.content &gt; div</code>, sometimes at the top and sometimes at the bottom. I tried many ways but nothing worked for me.</p> <p>How can I remove the unknown spacing from <code>div</code>?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.content { position: absolute; width: 100%; height: 100%; margin-bottom: 10px; padding: 5px 2px 30px 2px; background-color: #f5f5f5; overflow: scroll; overflow-x: hidden; } .content&gt;div { width: 100%; background-color: white; border: 1px solid black; border-right: none; margin-bottom: 5px; position: relative; } .content&gt;div&gt;div:nth-child(1) { width: calc(100% - 5px); padding: 2px; background-color: #aaaaaa; color: white; } .content&gt;div&gt;*:nth-child(2) { width: calc(100% - 5px); padding: 5px; word-break: break-word; } .content&gt;div&gt;div:nth-child(3) { cursor: pointer; user-select: none; height: 100%; width: 5px; bottom: 0; right: 0; position: absolute; background-color: #87ceeb; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="content"&gt; &lt;div&gt; &lt;div&gt;H1 heading&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;/div&gt; &lt;div&gt; &lt;div&gt;H1 heading&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;/div&gt; &lt;div&gt; &lt;div&gt;H1 heading&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;/div&gt; &lt;div&gt; &lt;div&gt;H1 heading&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;/div&gt; &lt;div&gt; &lt;div&gt;H1 heading&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;/div&gt; &lt;div&gt; &lt;div&gt;H1 heading&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>[![enter image description here]</p>
[ { "answer_id": 74321201, "author": "Swifty", "author_id": 20267366, "author_profile": "https://Stackoverflow.com/users/20267366", "pm_score": 2, "selected": true, "text": "mydict = {\n \"field_1\" : \"aaa\",\n \"field_2\": [\n {\n \"name\" : \"bbb\",\n\n \"field_4\" : \"ccc\",\n \"field_need_to_filter\" : False,\n },\n\n {\n \"name\" : \"ddd\",\n\n \"details\": [\n {\n \"name\" : \"eee\",\n\n \"details\" : [\n {\n \"name\": \"fff\",\n\n \"field_10\": {\n \"field_11\": \"rrr\",\n\n \"details\": [\n {\n \"name\": \"xxx\",\n\n \"field_need_to_filter\": True,\n },\n {\n \"name\": \"yyy\",\n\n \"field_need_to_filter\": True,\n },\n {\n \"field_13\": \"zzz\",\n\n \"field_need_to_filter\": False,\n }\n ]\n }\n },\n\n\n ]}]}\n\n ]\n}\n\ndef filter_paths(thing, path=''):\n if type(thing) == dict:\n # if this dict has a name, log it\n if thing.get(\"name\"):\n path += ('.' if path else '') + thing[\"name\"]\n # if this dict has \"...filter\": True, we've reached an end point, and return the path\n if thing.get(\"field_need_to_filter\") and thing[\"field_need_to_filter\"]:\n return [path]\n # else we delve deeper\n result = []\n for key in thing:\n result += [deep_path for deep_path in filter_paths(thing[key], path)]\n return result\n \n # if the current object is a list, we simply delve deeper\n elif type(thing) == list:\n result = []\n for element in thing:\n result += [deep_path for deep_path in filter_paths(element, path)]\n return result\n\n # We've reached a dead-end, so we return an empty list\n else:\n return []\n \nfilter_paths(mydict)\n# Out[204]: ['ddd.eee.fff.xxx', 'ddd.eee.fff.yyy']\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19802999/" ]
74,318,753
<p>I have a table which has a large amount of variable data with the <code>key</code> field in particular that has, at the time of writing 14 variants. The structure is as below:</p> <pre class="lang-sql prettyprint-override"><code>CREATE TABLE `device_data` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `device_id` bigint(20) unsigned NOT NULL, `serialized` tinyint(1) NOT NULL DEFAULT 0, `system` tinyint(1) NOT NULL DEFAULT 0, `key` varchar(60) COLLATE utf8mb4_unicode_ci NOT NULL, `value` longtext COLLATE utf8mb4_unicode_ci NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `unique_device_data_key` (`device_id`,`key`), CONSTRAINT `device_data_device_id_foreign` FOREIGN KEY (`device_id`) REFERENCES `devices` (`id`) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; </code></pre> <p>The table holds about 80,000 records which demonstrates that there is a large amount of repetition for the value of the <code>key</code> field. The problem with this is that if the key value is <code>key_name_here</code> and it's repeated 30,000 times, that's 13 bytes for every row * 30,000.</p> <p>I understand that I could create an enum column but the system itself is very dynamic and subject to change. It's not faesable to create a new enum value for the <code>key</code> every time.</p> <p>So my question here, would it make sense to add an index to the <code>key</code> field, in the hope this would reduce overall data consumption and benefit performance or would this simply be detremental to performance?</p> <p>It's worth adding that in 99% of cases we'd already be filtering down based on the <code>device_id</code> column, which makes me suspect this would just be entirely detrimental.</p> <p>Thanks in advance, Chris.</p>
[ { "answer_id": 74321201, "author": "Swifty", "author_id": 20267366, "author_profile": "https://Stackoverflow.com/users/20267366", "pm_score": 2, "selected": true, "text": "mydict = {\n \"field_1\" : \"aaa\",\n \"field_2\": [\n {\n \"name\" : \"bbb\",\n\n \"field_4\" : \"ccc\",\n \"field_need_to_filter\" : False,\n },\n\n {\n \"name\" : \"ddd\",\n\n \"details\": [\n {\n \"name\" : \"eee\",\n\n \"details\" : [\n {\n \"name\": \"fff\",\n\n \"field_10\": {\n \"field_11\": \"rrr\",\n\n \"details\": [\n {\n \"name\": \"xxx\",\n\n \"field_need_to_filter\": True,\n },\n {\n \"name\": \"yyy\",\n\n \"field_need_to_filter\": True,\n },\n {\n \"field_13\": \"zzz\",\n\n \"field_need_to_filter\": False,\n }\n ]\n }\n },\n\n\n ]}]}\n\n ]\n}\n\ndef filter_paths(thing, path=''):\n if type(thing) == dict:\n # if this dict has a name, log it\n if thing.get(\"name\"):\n path += ('.' if path else '') + thing[\"name\"]\n # if this dict has \"...filter\": True, we've reached an end point, and return the path\n if thing.get(\"field_need_to_filter\") and thing[\"field_need_to_filter\"]:\n return [path]\n # else we delve deeper\n result = []\n for key in thing:\n result += [deep_path for deep_path in filter_paths(thing[key], path)]\n return result\n \n # if the current object is a list, we simply delve deeper\n elif type(thing) == list:\n result = []\n for element in thing:\n result += [deep_path for deep_path in filter_paths(element, path)]\n return result\n\n # We've reached a dead-end, so we return an empty list\n else:\n return []\n \nfilter_paths(mydict)\n# Out[204]: ['ddd.eee.fff.xxx', 'ddd.eee.fff.yyy']\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/504487/" ]
74,318,756
<p>For a website internationalization project, I have a Google Sheets with countries and languages that we would like to offer within that country.</p> <p>Shortened sample sheet: <a href="https://docs.google.com/spreadsheets/d/1JNftjuEy97KeHfEH80bwl6H-40nNohPQrnQ-W_lzDZA/" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/1JNftjuEy97KeHfEH80bwl6H-40nNohPQrnQ-W_lzDZA/</a> The actual matrix is much bigger.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>en</th> <th>de</th> <th>fr</th> </tr> </thead> <tbody> <tr> <td>US</td> <td>1</td> <td></td> <td></td> </tr> <tr> <td>DE</td> <td>1</td> <td>2</td> <td></td> </tr> <tr> <td>FR</td> <td>2</td> <td></td> <td>1</td> </tr> </tbody> </table> </div> <p>The numbers determine the order in which the languages should be offered in the country's language menu.</p> <p>Now, I would like to use a formula to extract a list of required locales.</p> <p>Such as: US-en,DE-en,DE-de,FR-fr,FR-en</p> <p>The table keeps on changing, so a formula would be preferred to a one-time solution.</p>
[ { "answer_id": 74321201, "author": "Swifty", "author_id": 20267366, "author_profile": "https://Stackoverflow.com/users/20267366", "pm_score": 2, "selected": true, "text": "mydict = {\n \"field_1\" : \"aaa\",\n \"field_2\": [\n {\n \"name\" : \"bbb\",\n\n \"field_4\" : \"ccc\",\n \"field_need_to_filter\" : False,\n },\n\n {\n \"name\" : \"ddd\",\n\n \"details\": [\n {\n \"name\" : \"eee\",\n\n \"details\" : [\n {\n \"name\": \"fff\",\n\n \"field_10\": {\n \"field_11\": \"rrr\",\n\n \"details\": [\n {\n \"name\": \"xxx\",\n\n \"field_need_to_filter\": True,\n },\n {\n \"name\": \"yyy\",\n\n \"field_need_to_filter\": True,\n },\n {\n \"field_13\": \"zzz\",\n\n \"field_need_to_filter\": False,\n }\n ]\n }\n },\n\n\n ]}]}\n\n ]\n}\n\ndef filter_paths(thing, path=''):\n if type(thing) == dict:\n # if this dict has a name, log it\n if thing.get(\"name\"):\n path += ('.' if path else '') + thing[\"name\"]\n # if this dict has \"...filter\": True, we've reached an end point, and return the path\n if thing.get(\"field_need_to_filter\") and thing[\"field_need_to_filter\"]:\n return [path]\n # else we delve deeper\n result = []\n for key in thing:\n result += [deep_path for deep_path in filter_paths(thing[key], path)]\n return result\n \n # if the current object is a list, we simply delve deeper\n elif type(thing) == list:\n result = []\n for element in thing:\n result += [deep_path for deep_path in filter_paths(element, path)]\n return result\n\n # We've reached a dead-end, so we return an empty list\n else:\n return []\n \nfilter_paths(mydict)\n# Out[204]: ['ddd.eee.fff.xxx', 'ddd.eee.fff.yyy']\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/595438/" ]
74,318,794
<p>I am getting this error while performing migration between postgresql single server and flexible server:</p> <pre><code>Data migration could not be started for one or more of the DBSets. Error details: PGv2RestoreError: PG Restore failed for database 'postgres' with exit code '1' and error message 'error: could not execute query: ERROR: permission denied to create &quot;pg_catalog.hypopg_list_indexes&quot;'. </code></pre> <p>Which quite clearly states that user which is performing migration dosen't have right to perform some operations with creating extensio in pg_catalog. The problem is that in Azure i CAN NOT have superuser, so it seems like there is no way to perform this operation. Every step is done using azure platform and in compilance with guides below. Also it looks like problem lies with hypopg extension, which is enabled on both databases.</p> <p>guides: <a href="https://learn.microsoft.com/en-us/azure/postgresql/migrate/how-to-migrate-single-to-flexible-portal" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/azure/postgresql/migrate/how-to-migrate-single-to-flexible-portal</a> <a href="https://learn.microsoft.com/en-us/azure/postgresql/migrate/concepts-single-to-flexible" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/azure/postgresql/migrate/concepts-single-to-flexible</a> <a href="https://learn.microsoft.com/en-us/azure/postgresql/migrate/concepts-single-to-flexible#migration-prerequisites" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/azure/postgresql/migrate/concepts-single-to-flexible#migration-prerequisites</a></p>
[ { "answer_id": 74319673, "author": "Laurenz Albe", "author_id": 6464308, "author_profile": "https://Stackoverflow.com/users/6464308", "pm_score": 0, "selected": false, "text": "pg_catalog" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9494334/" ]
74,318,800
<p>I need help for my project. I try to inject Entity Manager inside my service (SendInBlueService) call with messenger, but DependencyInjection can't find doctrine.orm.entity_manager.</p> <p>My test route</p> <pre><code>#[Route('api/testSendInBlue', name: 'testsendinblue')] public function testMessenger(AsyncMethodService $asyncMethodService): Response { $asyncMethodService-&gt;async_low_priority( SendInBlueService::class, 'confirmationMail', [ $this-&gt;getUser()-&gt;getId() ] ); return new Response('Test OK'); } </code></pre> <p>My AsyncMethodService</p> <pre><code>&lt;?php namespace App\Service\Messenger; use Symfony\Component\Messenger\MessageBusInterface; class AsyncMethodService { private MessageBusInterface $messageBus; public function __construct(MessageBusInterface $messageBus) { $this-&gt;messageBus = $messageBus; } public function async_low_priority(string $serviceName, string $methodName,array $params = []) { $this-&gt;messageBus-&gt;dispatch(new ServiceMethodCallMessageLowPriority( $serviceName, $methodName, $params ) ); } public function async_medium_priority(string $serviceName, string $methodName,array $params = []) { $this-&gt;messageBus-&gt;dispatch(new ServiceMethodCallMessageMediumPriority( $serviceName, $methodName, $params ) ); } public function async_high_priority(string $serviceName, string $methodName,array $params = []) { $this-&gt;messageBus-&gt;dispatch(new ServiceMethodCallMessageHighPriority( $serviceName, $methodName, $params )); } } </code></pre> <p>My ServiceMethodCallMessageLowPriority exactly same for High and Medium</p> <pre><code>&lt;?php namespace App\Service\Messenger; class ServiceMethodCallMessageLowPriority extends ServiceMethodCallMessage { } </code></pre> <p>My ServiceMethodCallMessage</p> <pre><code>&lt;?php namespace App\Service\Messenger; class ServiceMethodCallMessage { private string $serviceName; private string $methodName; private array $params; public function __construct(string $serviceName, string $methodName, array $params = []) { $this-&gt;serviceName = $serviceName; $this-&gt;methodName = $methodName; $this-&gt;params = $params; } /** * @return string */ public function getServiceName(): string { return $this-&gt;serviceName; } /** * @return string */ public function getMethodName(): string { return $this-&gt;methodName; } /** * @return array */ public function getParams(): array { return $this-&gt;params; } } </code></pre> <p>My MessengerHandle</p> <pre><code>&lt;?php namespace App\Service\Messenger; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Messenger\Attribute\AsMessageHandler; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; #[AsMessageHandler] class ServiceMethodCallHandler extends AbstractController { private string $path; public function __construct(string $path) { $this-&gt;path = $path; } public function __invoke( ServiceMethodCallMessageLowPriority | ServiceMethodCallMessageMediumPriority | ServiceMethodCallMessageHighPriority $message ) { $containerBuilder = new ContainerBuilder(); $loader = new YamlFileLoader($containerBuilder, new FileLocator($this-&gt;path)); $loader-&gt;load('services.yaml'); $callable = [ $containerBuilder-&gt;get($message-&gt;getServiceName()), $message-&gt;getMethodName() ]; call_user_func_array($callable,$message-&gt;getParams()); } } </code></pre> <p>My Service Send In Blue</p> <pre><code>&lt;?php namespace App\Service; use App\Entity\User; use Doctrine\ORM\EntityManagerInterface; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; class SendInBlueService { private string $SEND_IN_BLUE_API_KEY; private EntityManagerInterface $entityManager; public function __construct( string $SEND_IN_BLUE_API_KEY, EntityManagerInterface $entityManager ) { $this-&gt;SEND_IN_BLUE_API_KEY = $SEND_IN_BLUE_API_KEY; $this-&gt;entityManager = $entityManager; } public function confirmationMail(int $userId) { dd($this-&gt;entityManager); $user = $this-&gt;entityManager-&gt;getRepository(User::class)-&gt;find($userId); dd($user); } } </code></pre> <p>My config/services.yaml</p> <pre><code>parameters: SEND_IN_BLUE_API_KEY: '%env(SEND_IN_BLUE_API_KEY)%' services: # default configuration for services in *this* file _defaults: autowire: true # Automatically injects dependencies in your services. autoconfigure: true # Automatically registers your services as commands, event subscribers, etc. App\: resource: '../src/' exclude: - '../src/Entity/' - '../src/Kernel.php' - '../src/DependencyInjection/' # Messenger Declaration Service App\Service\Messenger\ServiceMethodCallHandler: arguments: ['%kernel.project_dir%/config'] App\Service\SendInBlueService: class: App\Service\SendInBlueService arguments: ['%env(SEND_IN_BLUE_API_KEY)%','@doctrine.orm.entity_manager'] </code></pre> <p>And for finish my error:</p> <p><a href="https://i.stack.imgur.com/dQ36Q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dQ36Q.png" alt="enter image description here" /></a></p> <p>I try get EntityManager with ContainerBuilder inside my service, But i have a same error.</p> <p>I think i have a problem because messenger use other kernel instance, and inside this instance, the DependencyInjection don't have load all bundles.</p> <p>If someone has an idea. Thanks you</p>
[ { "answer_id": 74319673, "author": "Laurenz Albe", "author_id": 6464308, "author_profile": "https://Stackoverflow.com/users/6464308", "pm_score": 0, "selected": false, "text": "pg_catalog" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18628733/" ]
74,318,815
<p>We are using IIS 10 I have a user that wants their site and subsites to show the full URL path when browsing. For example, if you go to mysite.domain.com/ or mysite.domain.com/subsite/ it will show you mysite.domain/file.html or mysite.domain.com/subsite/file.html in the URL Is there a way in IIS to tell it to show the full path or append the file somehow?</p> <p>The reasoning for this within Google Analytics there getting reports for both sites and just want the mysite.domain.com/file.html and not mysite.domain.com/ I think the main files there concerned about are the index.html files being seen in URL.</p> <p>I know a little about URL Rewrite rules but by far no expert for sure but I can't figure out if this is possible or not. Thanks, any advice.</p> <p>We are using IIS 10</p> <p>I tried to basic redirect rule in URL rewrite, but I am not sure if that it what I am really asking for.</p>
[ { "answer_id": 74319673, "author": "Laurenz Albe", "author_id": 6464308, "author_profile": "https://Stackoverflow.com/users/6464308", "pm_score": 0, "selected": false, "text": "pg_catalog" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20364737/" ]
74,318,824
<p>I want to draw a random card from a deck and validates that it's always unique. I'm using the cardGenerator() recursive function to do that. If the random card picked has been shown then it calls itself again. Need a work around or if any of yall got a better logic please let me know.</p> <pre><code>import java.util.ArrayList; import java.util.Random; public class App { static ArrayList&lt;Integer[]&gt; deck = new ArrayList&lt;&gt;(); static ArrayList&lt;Integer[]&gt; dealer = new ArrayList&lt;&gt;(); static Integer[] cardGenerator() throws Exception{ Random random = new Random(); Integer[] card = {0, 0}; Integer num = random.nextInt(13); Integer shape = random.nextInt(4); Integer[] deckSet = deck.get(num); if(deckSet[shape] == 1){ deckSet[shape] = 0; deck.set(num, deckSet); card[0] = num; card[1] = shape; return card; } else return cardGenerator(); } public static void main(String[] args) throws Exception { Integer[] deckSet = {1, 1, 1, 1}; for(int i = 0; i &lt; 13; i++){ deck.add(deckSet); } dealer.add(cardGenerator()); dealer.add(cardGenerator()); dealer.add(cardGenerator()); dealer.add(cardGenerator()); dealer.add(cardGenerator()); } } </code></pre> <p>expecting for dealer to store 5 unique cards, but java.lang.StackOverflowError occured on the cardGenerator function.</p>
[ { "answer_id": 74318917, "author": "kmeh", "author_id": 20178298, "author_profile": "https://Stackoverflow.com/users/20178298", "pm_score": 0, "selected": false, "text": " for(int i = 0; i < 13; i++){\n Integer[] deckSet = {1, 1, 1, 1}; // Moved inside\n deck.add(deckSet);\n }\n" }, { "answer_id": 74319265, "author": "Thomas Kläger", "author_id": 5646962, "author_profile": "https://Stackoverflow.com/users/5646962", "pm_score": 1, "selected": false, "text": "deckSet" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20418428/" ]
74,318,838
<p>i want to dispatch an action after state Change in an useEffect</p> <pre><code>React.useEffect(() =&gt; { let timer = setInterval(() =&gt; { setCurrTime(activeCallTime()); /** @todo:dispatch currtime action **/ }, 1000); return () =&gt; clearInterval(timer); }, [props.startTime]); </code></pre>
[ { "answer_id": 74318917, "author": "kmeh", "author_id": 20178298, "author_profile": "https://Stackoverflow.com/users/20178298", "pm_score": 0, "selected": false, "text": " for(int i = 0; i < 13; i++){\n Integer[] deckSet = {1, 1, 1, 1}; // Moved inside\n deck.add(deckSet);\n }\n" }, { "answer_id": 74319265, "author": "Thomas Kläger", "author_id": 5646962, "author_profile": "https://Stackoverflow.com/users/5646962", "pm_score": 1, "selected": false, "text": "deckSet" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11051396/" ]
74,318,853
<p>I have a chrome MV3 extension that has the following manifest.json:</p> <pre><code>{ &quot;manifest_version&quot;: 3, &quot;permissions&quot;: [ &quot;scripting&quot;, &quot;tabs&quot; ], &quot;host_permissions&quot;: [&quot;&lt;all_urls&gt;&quot;] } </code></pre> <p>When I install the extension and have existing tabs, I am unable to execute scripts on those existing tabs:</p> <pre><code>chrome.scripting.executeScript({ target: {tabId: 1305686273}, func: function(){ console.log('hi'); } }); </code></pre> <p>I get this error in my background service worker script:</p> <blockquote> <p>Cannot access contents of the page. Extension manifest must request permission to access the respective host.</p> </blockquote> <p>My understanding is that the <code>tabs</code> permission lets me query all tabs without user gesture, and the <code>&quot;host_permissions&quot;: [&quot;&lt;all_urls&gt;&quot;]</code> should let me execute scripts on all tabs without user gesture.</p> <p>Am I wrong, or is there something missing to allow scripting on pages without user gesture?</p> <p>P.S. running <code>chrome.tabs.get(1305686273).then(console.log)</code> works as expected.</p>
[ { "answer_id": 74319499, "author": "d-_-b", "author_id": 1166285, "author_profile": "https://Stackoverflow.com/users/1166285", "pm_score": 1, "selected": false, "text": "chrome.scripting" }, { "answer_id": 74319860, "author": "Thomas Mueller", "author_id": 19840875, "author_profile": "https://Stackoverflow.com/users/19840875", "pm_score": 0, "selected": false, "text": "{\n \"name\": \"executeScript\",\n \"version\": \"1.0.0\",\n \"manifest_version\": 3,\n \"background\": {\n \"service_worker\": \"background.js\"\n }, \n \"host_permissions\": [\"<all_urls>\"],\n \"permissions\": [\n \"scripting\",\n \"tabs\"\n ]\n}\n" }, { "answer_id": 74323928, "author": "Norio Yamamoto", "author_id": 20074043, "author_profile": "https://Stackoverflow.com/users/20074043", "pm_score": 0, "selected": false, "text": "{\n \"manifest_version\": 3,\n \"name\": \"hoge\",\n \"version\": \"1.0\",\n \"permissions\": [\n \"scripting\"\n ],\n \"host_permissions\": [\n \"<all_urls>\"\n ],\n \"background\": {\n \"service_worker\": \"background.js\"\n }\n}\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1166285/" ]
74,318,894
<p>I have a list where users can dynamically add items. The list looks like this :</p> <pre><code> [{author: Tsubasa Yamaguchi, created: 24 Juin 2017, total_chapter: 34, genre: seinen, pic: https://www.nautiljon.com/images/more/03/72/278427.jpg, title: Blue Period}, {author: Tsubasa Yamaguchi, created: 24 Juin 2017, total_chapter: 34, genre: seinen, pic: https://www.nautiljon.com/images/more/03/72/278427.jpg, title: Blue Period}] </code></pre> <p>I don't want any duplicates in this list because I display items in a listView. I've tried the method of <code>list.toSet().toList()</code> but for some reason, I have the same result. I think it's because of the format or my items '<code>{}</code>'.</p> <p>Any suggestion?</p> <p>This is how I obtain my list :</p> <pre><code>FirebaseFirestore firestore = FirebaseFirestore.instance; List favMangasListTitle = []; List detailledMangaList = []; String title = ''; String read_chapter = ''; Future&lt;List&gt; getFavMangas() async { var value = await firestore.collection(&quot;users/${user.uid}/fav_mangas&quot;).get(); final favMangasGetter = value.docs.map((doc) =&gt; doc.data()).toList(); favMangasListTitle.clear(); detailledMangaList.clear(); for (var i in favMangasGetter) { title = i['title']; read_chapter = i['read_chapter']; favMangasListTitle.add(title); } await Future.forEach(favMangasListTitle, (i) async { final mangas = await firestore.collection('mangas').where('title', isEqualTo: i).get(); final receivedMangaDetailled = mangas.docs.map((doc) =&gt; doc.data()).toList(); detailledMangaList.addAll(receivedMangaDetailled); }); var test = detailledMangaList.toSet().toList(); print(test); return detailledMangaList; } </code></pre>
[ { "answer_id": 74319499, "author": "d-_-b", "author_id": 1166285, "author_profile": "https://Stackoverflow.com/users/1166285", "pm_score": 1, "selected": false, "text": "chrome.scripting" }, { "answer_id": 74319860, "author": "Thomas Mueller", "author_id": 19840875, "author_profile": "https://Stackoverflow.com/users/19840875", "pm_score": 0, "selected": false, "text": "{\n \"name\": \"executeScript\",\n \"version\": \"1.0.0\",\n \"manifest_version\": 3,\n \"background\": {\n \"service_worker\": \"background.js\"\n }, \n \"host_permissions\": [\"<all_urls>\"],\n \"permissions\": [\n \"scripting\",\n \"tabs\"\n ]\n}\n" }, { "answer_id": 74323928, "author": "Norio Yamamoto", "author_id": 20074043, "author_profile": "https://Stackoverflow.com/users/20074043", "pm_score": 0, "selected": false, "text": "{\n \"manifest_version\": 3,\n \"name\": \"hoge\",\n \"version\": \"1.0\",\n \"permissions\": [\n \"scripting\"\n ],\n \"host_permissions\": [\n \"<all_urls>\"\n ],\n \"background\": {\n \"service_worker\": \"background.js\"\n }\n}\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19904553/" ]
74,318,945
<p>I'm trying to take the first column from my file (all rows except header) and delete text to the left of a colon character but I get a 400 error from VBA. I don't know what's wrong with this code.</p> <p>As an example A2 (and subsequent cells in the A column) look like this: <a href="https://i.stack.imgur.com/c2SxJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c2SxJ.png" alt="enter image description here" /></a></p> <pre><code>Sub cleanLoginTime() Dim cell As Range Dim MyRange As Range Dim tmp As String LastRow = Cells(Rows.Count, 1).End(xlUp) Set MyRange = ActiveSheet.Range(&quot;A2:A&quot; &amp; LastRow) 'this is your range of data For Each cell In MyRange.Cells tmp = cell.Value 'output n - 1 characters from the right cell.Value = Right(tmp, Len(tmp) - 21) Next End Sub </code></pre>
[ { "answer_id": 74320228, "author": "dcromley", "author_id": 3361377, "author_profile": "https://Stackoverflow.com/users/3361377", "pm_score": 0, "selected": false, "text": "lastrow = Cells(Rows.Count, 1).End(xlUp).row\n" }, { "answer_id": 74320848, "author": "VBasic2008", "author_id": 9814069, "author_profile": "https://Stackoverflow.com/users/9814069", "pm_score": 2, "selected": true, "text": "Sub CleanLoginTime()\n \n Const FindString As String = \":\"\n \n Dim FindStringLength As Long: FindStringLength = Len(FindString)\n \n Dim ws As Worksheet: Set ws = ActiveSheet ' improve!\n Dim rg As Range\n Set rg = ws.Range(\"A2\", ws.Cells(ws.Rows.Count, \"A\").End(xlUp))\n \n Dim cell As Range\n Dim FindStringPosition As Long\n Dim CellString As String\n \n For Each cell In rg.Cells\n CellString = CStr(cell.Value)\n FindStringPosition = InStr(CellString, FindString)\n If FindStringPosition > 0 Then ' string found\n cell.Value = Right(CellString, Len(CellString) _\n - FindStringPosition - FindStringLength + 1)\n 'Else ' string not found; do nothing\n End If\n Next cell\n\nEnd Sub\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2800956/" ]
74,318,955
<p>Because we need to have the ability to schedule email delivery, we have migrated to using Sidekiq to send emails with the <code>deliver_later</code> method. Under the old regime that used <code>deliver_now</code>, our testing could use</p> <pre><code>ActionMailer::Base.deliveries[index] </code></pre> <p>to inspect the recipient, subject, body, attachments, etc...</p> <p>For testing purposes, is there an equivalent mechanism to inspect the contents of queued email when using Sidekiq and <code>deliver_later</code>?</p>
[ { "answer_id": 74320228, "author": "dcromley", "author_id": 3361377, "author_profile": "https://Stackoverflow.com/users/3361377", "pm_score": 0, "selected": false, "text": "lastrow = Cells(Rows.Count, 1).End(xlUp).row\n" }, { "answer_id": 74320848, "author": "VBasic2008", "author_id": 9814069, "author_profile": "https://Stackoverflow.com/users/9814069", "pm_score": 2, "selected": true, "text": "Sub CleanLoginTime()\n \n Const FindString As String = \":\"\n \n Dim FindStringLength As Long: FindStringLength = Len(FindString)\n \n Dim ws As Worksheet: Set ws = ActiveSheet ' improve!\n Dim rg As Range\n Set rg = ws.Range(\"A2\", ws.Cells(ws.Rows.Count, \"A\").End(xlUp))\n \n Dim cell As Range\n Dim FindStringPosition As Long\n Dim CellString As String\n \n For Each cell In rg.Cells\n CellString = CStr(cell.Value)\n FindStringPosition = InStr(CellString, FindString)\n If FindStringPosition > 0 Then ' string found\n cell.Value = Right(CellString, Len(CellString) _\n - FindStringPosition - FindStringLength + 1)\n 'Else ' string not found; do nothing\n End If\n Next cell\n\nEnd Sub\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74318955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4959100/" ]
74,319,014
<p>Need help creating a string method in java without the use of arrays. The method takes what the user typed in as a string and passes it to the new string method. Or a whole sentence and converting it into the pig latin version of it.</p> <p>Ex. the word typed in apple is shown again with quotes around it followed by in Pig Latin is apple-way</p> <pre><code>This program will convert an English word into Pig Latin. Please enter a word ==&gt; apple &quot;apple&quot; in Pig Latin is &quot;apple-way&quot; </code></pre>
[ { "answer_id": 74320228, "author": "dcromley", "author_id": 3361377, "author_profile": "https://Stackoverflow.com/users/3361377", "pm_score": 0, "selected": false, "text": "lastrow = Cells(Rows.Count, 1).End(xlUp).row\n" }, { "answer_id": 74320848, "author": "VBasic2008", "author_id": 9814069, "author_profile": "https://Stackoverflow.com/users/9814069", "pm_score": 2, "selected": true, "text": "Sub CleanLoginTime()\n \n Const FindString As String = \":\"\n \n Dim FindStringLength As Long: FindStringLength = Len(FindString)\n \n Dim ws As Worksheet: Set ws = ActiveSheet ' improve!\n Dim rg As Range\n Set rg = ws.Range(\"A2\", ws.Cells(ws.Rows.Count, \"A\").End(xlUp))\n \n Dim cell As Range\n Dim FindStringPosition As Long\n Dim CellString As String\n \n For Each cell In rg.Cells\n CellString = CStr(cell.Value)\n FindStringPosition = InStr(CellString, FindString)\n If FindStringPosition > 0 Then ' string found\n cell.Value = Right(CellString, Len(CellString) _\n - FindStringPosition - FindStringLength + 1)\n 'Else ' string not found; do nothing\n End If\n Next cell\n\nEnd Sub\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74319014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20417482/" ]
74,319,018
<p>I try to create project on frontendMentor and have an issue. When i complete the form and click button element form doesnt hide. There are many new lines and this element is on the bottom. What is the problem? Code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const cardName = document.querySelector('.name'); const cardNumber = document.querySelector('.number'); const cardMonth = document.querySelector('.month'); const cardYear = document.querySelector('.year'); const cardCode = document.querySelector('.code'); const btn = document.querySelector('.button'); const resultName = document.querySelector('.card__name'); const resultNumber = document.querySelector('.header__cards-number'); const resultExpiry = document.querySelector('.card__expiry'); const resultCvv = document.querySelector('.header__cvv'); const summary = document.querySelector('.summary'); const form = document.querySelector('.form'); // const resultDate = document.querySelector(); btn.addEventListener('click', function () { resultName.innerHTML = cardName.value; resultNumber.innerHTML = cardNumber.value; resultExpiry.innerHTML = `${cardMonth.value}/${cardYear.value}`; resultCvv.innerHTML = cardCode.value; summary.classList.remove('hidden'); form.classList.add('hidden'); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>$white: hsl(0, 0%, 100%); $lightGrayishViolet: hsl(270, 3%, 87%); $darkGrayishViolet: hsl(279, 6%, 55%); $veryDarkViolet: hsl(278, 68%, 11%); $red: hsl(0, 100%, 66%); $linearGradient: hsl(249, 99%, 64%) to hsl(278, 94%, 30%); * { margin: 0; padding: 0; box-sizing: border-box; } body { font-size: 18px; font-family: 'Space Grotesk', sans-serif; height: 100vh; width: 100%; max-width: 375px; display: flex; flex-direction: column; font-weight: 500; } .header { flex-basis: 35%; background-image: url('../images/bg-main-mobile.png'); &amp;__card { display: flex; justify-content: center; align-items: center; width: 300px; height: 150px; border-radius: 0.5em; } &amp;__cards { &amp;-back { position: relative; margin-top: 1.5em; margin-left: 3em; background-color: $white; } &amp;-front { display: flex; flex-direction: column; position: absolute; background-image: url('../images/bg-card-front.png'); color: $white; top: 117px; left: 15px; z-index: 10; overflow: hidden; padding: 1em 1em; } &amp;-logo { flex-basis: 50%; width: 100%; svg { text-align-last: left; margin-left: -1em; transform: scale(0.5); } } &amp;-number { flex-basis: 20%; width: 100%; text-align: center; letter-spacing: 2px; } &amp;-details { width: 100%; flex-basis: 30%; display: flex; justify-content: space-between; align-items: flex-end; text-align: center; font-size: 0.7em; letter-spacing: 2px; text-transform: uppercase; } } &amp;__magneticbar { position: absolute; top: 0; left: 0; width: 100%; height: 30px; margin-top: 1em; background-color: #333; } &amp;__cvv { width: 80%; height: 30px; text-align: right; padding-right: 1em; background-color: $lightGrayishViolet; line-height: 30px; border-radius: 0.2em; color: $white; font-size: 0.7em; color: $white; letter-spacing: 2px; } .content { flex-basis: 65%; } } .content { flex-basis: 65%; padding: 1em; .description { text-transform: uppercase; letter-spacing: 2px; font-size: 0.7em; text-align: left; color: $veryDarkViolet; margin-bottom: 0.3em; } .form { height: 100%; display: flex; flex-direction: column; justify-content: flex-end; align-items: center; text-align: center; &amp;__item { width: 100%; margin-bottom: 0.5em; input { width: 100%; height: 3em; border-radius: 0.3em; border: 1px solid $lightGrayishViolet; } input::placeholder { font-size: 1.3em; color: $lightGrayishViolet; } } &amp;__row { display: flex; .form__item { input { width: 23%; text-align: center; } .code { width: 50%; } span { margin-left: 2em; } } } &amp;__button { width: 100%; height: 3em; margin-top: 1em; margin-bottom: 2em; line-height: 3em; background-color: $veryDarkViolet; color: $white; border-radius: 0.5em; } } } .summary { display: flex; height: 100%; flex-direction: column; align-items: center; justify-content: center; text-align: center; &amp;__icon { margin: 2em 0; } &amp;__text { h1 { text-transform: uppercase; letter-spacing: 3px; } p { color: $darkGrayishViolet; margin: 1em 0; } } &amp;__button { margin-top: 2em; background-color: lime; } } .hidden { display: none; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8" /&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /&gt; &lt;!-- displays site properly based on user's device --&gt; &lt;link rel="icon" type="image/png" sizes="32x32" href="./images/favicon-32x32.png" /&gt; &lt;title&gt;Frontend Mentor | Interactive card details form&lt;/title&gt; &lt;link rel="preconnect" href="https://fonts.googleapis.com" /&gt; &lt;link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /&gt; &lt;link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@500&amp;display=swap" rel="stylesheet" /&gt; &lt;link rel="stylesheet" href="./css/style.css" /&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="header"&gt; &lt;div class="header__cards"&gt; &lt;div class="header__card header__cards-back"&gt; &lt;div class="header__magneticbar"&gt;&lt;/div&gt; &lt;div class="header__cvv"&gt;000&lt;/div&gt; &lt;/div&gt; &lt;div class="header__card header__cards-front"&gt; &lt;div class="header__cards-logo"&gt; &lt;svg width="84" height="47" fill="none" xmlns="http://www.w3.org/2000/svg" &gt; &lt;ellipse cx="23.478" cy="23.5" rx="23.478" ry="23.5" fill="#fff" /&gt; &lt;path d="M83.5 23.5c0 5.565-4.507 10.075-10.065 10.075-5.559 0-10.065-4.51-10.065-10.075 0-5.565 4.506-10.075 10.065-10.075 5.558 0 10.065 4.51 10.065 10.075Z" stroke="#fff" /&gt; &lt;/svg&gt; &lt;/div&gt; &lt;div class="header__cards-number"&gt;0000 0000 0000 0000&lt;/div&gt; &lt;div class="header__cards-details"&gt; &lt;div class="card__name"&gt;Jane Appleseed&lt;/div&gt; &lt;div class="card__expiry"&gt;00/00&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="content"&gt; &lt;div class="summary hidden"&gt; &lt;div class="summary__icon"&gt; &lt;svg width="80" height="80" fill="none" xmlns="http://www.w3.org/2000/svg" &gt; &lt;circle cx="40" cy="40" r="40" fill="url(#a)" /&gt; &lt;path d="M28 39.92 36.08 48l16-16" stroke="#fff" stroke-width="3" /&gt; &lt;defs&gt; &lt;linearGradient id="a" x1="-23.014" y1="11.507" x2="0" y2="91.507" gradientUnits="userSpaceOnUse" &gt; &lt;stop stop-color="#6348FE" /&gt; &lt;stop offset="1" stop-color="#610595" /&gt; &lt;/linearGradient&gt; &lt;/defs&gt; &lt;/svg&gt; &lt;/div&gt; &lt;div class="summary__text"&gt; &lt;h1&gt;Thank you!&lt;/h1&gt; &lt;p&gt;We've added your card details&lt;/p&gt; &lt;/div&gt; &lt;div class="form__button summary__button"&gt;Continue&lt;/div&gt; &lt;/div&gt; &lt;div class="form"&gt; &lt;div class="form__item"&gt; &lt;div class="description"&gt;Cardholder Name&lt;/div&gt; &lt;input type="text" name="name" id="name" class="name" placeholder=" e.g. Jane Appleseed" /&gt; &lt;/div&gt; &lt;div class="form__item"&gt; &lt;div class="description"&gt;Card Number&lt;/div&gt; &lt;input type="text" name="number" id="number" class="number" placeholder="e.g. 1234 5678 9123 0000" maxlength="19" /&gt; &lt;/div&gt; &lt;div class="form__row"&gt; &lt;div class="form__item"&gt; &lt;div class="description"&gt; Exp. Date (MM/YY)&lt;span&gt;CVC&lt;/span&gt; &lt;/div&gt; &lt;input type="text" name="month" id="month" class="month" placeholder="MM" maxlength="2" minlength="2" /&gt; &lt;input type="text" name="year" id="year" class="year" placeholder="YY" maxlength="2" minlength="2" /&gt; &lt;input type="text" name="code" id="code" class="code" placeholder="e.g. 123" minlength="3" maxlength="3" /&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form__button button"&gt;Confirm&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src="./script.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>I add some images too<a href="https://i.stack.imgur.com/8M19X.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8M19X.png" alt="enter image description here" /></a><a href="https://i.stack.imgur.com/mCXdY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mCXdY.png" alt="enter image description here" /></a></p> <p>I know that my code is bad but i dont use any tutorials and hints.</p>
[ { "answer_id": 74320228, "author": "dcromley", "author_id": 3361377, "author_profile": "https://Stackoverflow.com/users/3361377", "pm_score": 0, "selected": false, "text": "lastrow = Cells(Rows.Count, 1).End(xlUp).row\n" }, { "answer_id": 74320848, "author": "VBasic2008", "author_id": 9814069, "author_profile": "https://Stackoverflow.com/users/9814069", "pm_score": 2, "selected": true, "text": "Sub CleanLoginTime()\n \n Const FindString As String = \":\"\n \n Dim FindStringLength As Long: FindStringLength = Len(FindString)\n \n Dim ws As Worksheet: Set ws = ActiveSheet ' improve!\n Dim rg As Range\n Set rg = ws.Range(\"A2\", ws.Cells(ws.Rows.Count, \"A\").End(xlUp))\n \n Dim cell As Range\n Dim FindStringPosition As Long\n Dim CellString As String\n \n For Each cell In rg.Cells\n CellString = CStr(cell.Value)\n FindStringPosition = InStr(CellString, FindString)\n If FindStringPosition > 0 Then ' string found\n cell.Value = Right(CellString, Len(CellString) _\n - FindStringPosition - FindStringLength + 1)\n 'Else ' string not found; do nothing\n End If\n Next cell\n\nEnd Sub\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74319018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16881950/" ]
74,319,034
<p>I am trying to check whether the key that the user presses is equal to the key in a word. e.g. the word is &quot;flower&quot; and the user enters &quot;f&quot; the output should be true, if the user presses &quot;x&quot; the output should be false. When I try to enter a character it give me System.InvalidCastException: 'Unable to cast object of type 'System.Char[]' to type 'System.IConvertible'.' where the code checks if user input matches key in the word.</p> <pre><code>private bool KeyCheck(char key) { //word arraylist values set to word in array currentWords at index 0 word.Add((currentWords[0].ToCharArray())); for (int i = 0; i &lt; word.Count; i++) { //checks if user input matches key in word if (Convert.ToChar(word[i]) == key) { correct++; return true; } } incorrect++; return false; } </code></pre>
[ { "answer_id": 74319136, "author": "Ghassen", "author_id": 4112547, "author_profile": "https://Stackoverflow.com/users/4112547", "pm_score": 0, "selected": false, "text": " private bool KeyCheck(char key)\n {\n return currentWords[0].Contains(key);\n }\n" }, { "answer_id": 74319161, "author": "frankM_DN", "author_id": 20034020, "author_profile": "https://Stackoverflow.com/users/20034020", "pm_score": -1, "selected": false, "text": "word[i]" }, { "answer_id": 74319922, "author": "Dmitry Bychenko", "author_id": 2319407, "author_profile": "https://Stackoverflow.com/users/2319407", "pm_score": 0, "selected": false, "text": "key" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74319034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20377406/" ]
74,319,047
<p>I want to make a code that receives a random list and stores only positive numbers. However, if I run it with the code I wrote, I only get positive numbers, but the order is reversed. What should I do?</p> <p>As an example of the code, [3, 2, 1, 0] is displayed. I want to print this out [0, 1, 2, 3].</p> <pre><code>def filter(list): flist = [] for i in list: if list[i]&gt;=0: flist.append(list[i]) else: continue return flist list = [-1,-2,-3,-4,0,1,2,3] print(filter(list)) </code></pre>
[ { "answer_id": 74319076, "author": "Will", "author_id": 12829151, "author_profile": "https://Stackoverflow.com/users/12829151", "pm_score": 0, "selected": false, "text": "def filter(list):\n flist = []\n for i in list:\n if list[i]>=0:\n flist.append(list[i])\n else:\n continue\n flist.sort()\n return flist\n \nlist = [-1,-2,-3,-4,0,1,2,3]\nprint(filter(list))\n" }, { "answer_id": 74319090, "author": "Remzinho", "author_id": 2484591, "author_profile": "https://Stackoverflow.com/users/2484591", "pm_score": -1, "selected": false, "text": "print(filter(list[::-1]))\n" }, { "answer_id": 74319093, "author": "Samwise", "author_id": 3799759, "author_profile": "https://Stackoverflow.com/users/3799759", "pm_score": 1, "selected": true, "text": "for i in list" }, { "answer_id": 74319316, "author": "Adrien Kinart", "author_id": 20378613, "author_profile": "https://Stackoverflow.com/users/20378613", "pm_score": 0, "selected": false, "text": "def filter(list):\n flist = []\n for i in list:\n if list[i]>=0:\n flist = [i] + flist\n else:\n continue\n return flist\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74319047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20250172/" ]
74,319,049
<p>I could not find this in the laravel docs on aggregate relationships</p> <p>I was able to do something like this</p> <pre class="lang-php prettyprint-override"><code> private function refreshUsers() { $this-&gt;users = User::withSum(['taskTimeSessions'=&gt; function ($query) { $query-&gt;whereMonth('created_at',$this-&gt;month) -&gt;where('is_reconciled',1); }],'session_duration_in_seconds') -&gt;get(); } </code></pre> <p>But now I am trying to query what is the total time a <code>Sprint</code> has or at the very least what the individual tasks inside a sprint have so that I can just sum the total of those somehow.</p> <ul> <li>Sprint has many SprintTasks (pivot table)</li> <li>SprintTask belongs to one Task</li> <li>Task has many TaskTimeSessions</li> </ul> <p>So I am trying to go find the total time of the TaskTimeSessions</p> <pre class="lang-php prettyprint-override"><code>Sprint::with([ 'sprintTasks.task'=&gt; function ($query) { $query-&gt;withSum('taskTimeSessions','session_duration_in_seconds'); }]) -&gt;get(); </code></pre> <p>I am not getting any errors, but not finding the result anywhere when <code>dd</code></p> <p>I thought i would get lucky and have something like this work</p> <pre class="lang-php prettyprint-override"><code>-&gt;withSum('sprintTasks.task.taskTimeSessions', 'session_duration_in_seconds') </code></pre> <p>But I am getting this error</p> <pre><code>Call to undefined method App\Models\Sprint::sprintTasks.task() </code></pre> <p>If anyone can help me out with some guidance on how to go about this, even if it doesn't include withSum it would be much appreciated.</p> <p>As requested, these are the models.</p> <pre><code>// Sprint public function sprintTasks() { return $this-&gt;hasMany(SprintTask::class, 'sprint_id'); } // SprintTask protected $fillable = [ 'sprint_id', 'task_id', 'is_completed' ]; public function task() { return $this-&gt;belongsTo(Task::class,'task_id'); } public function sprint() { return $this-&gt;belongsTo(Task::class,'sprint_id'); } // Task public function taskTimeSessions() { return $this-&gt;hasMany(TaskTimeSession::class, 'task_id'); } // TaskTimeSessions protected $fillable = [ 'task_id', 'session_duration_in_seconds' ]; public function task() { return $this-&gt;belongsTo(Task::class,'task_id'); } </code></pre> <p>Is it possible to abstract this into the model as like</p> <pre><code>public function totalTaskTime() { // using the relationship stuff to figure out the math and return it? } </code></pre> <p>Looking for any advice on what the best approach is to do this.</p> <p>Right now I am literally doing this in the blade and seems very bad</p> <pre class="lang-php prettyprint-override"><code>@php $timeTracked = 0; foreach ($sprint-&gt;sprintTasks as $sprintTask) { $timeTracked += $sprintTask-&gt;task-&gt;time_tracked_in_seconds; } @endphp </code></pre>
[ { "answer_id": 74319076, "author": "Will", "author_id": 12829151, "author_profile": "https://Stackoverflow.com/users/12829151", "pm_score": 0, "selected": false, "text": "def filter(list):\n flist = []\n for i in list:\n if list[i]>=0:\n flist.append(list[i])\n else:\n continue\n flist.sort()\n return flist\n \nlist = [-1,-2,-3,-4,0,1,2,3]\nprint(filter(list))\n" }, { "answer_id": 74319090, "author": "Remzinho", "author_id": 2484591, "author_profile": "https://Stackoverflow.com/users/2484591", "pm_score": -1, "selected": false, "text": "print(filter(list[::-1]))\n" }, { "answer_id": 74319093, "author": "Samwise", "author_id": 3799759, "author_profile": "https://Stackoverflow.com/users/3799759", "pm_score": 1, "selected": true, "text": "for i in list" }, { "answer_id": 74319316, "author": "Adrien Kinart", "author_id": 20378613, "author_profile": "https://Stackoverflow.com/users/20378613", "pm_score": 0, "selected": false, "text": "def filter(list):\n flist = []\n for i in list:\n if list[i]>=0:\n flist = [i] + flist\n else:\n continue\n return flist\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74319049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14192860/" ]
74,319,091
<p>I'm trying to create a script that reads the text from a cell and converts it into a URL Handle:</p> <p>Example: This is a test -&gt; this-is-a-test</p> <p>I´ve created a code that can convert the text just like the example, but im trying to apply this to a column with 20.000+ rows and the sheet gets very slow or crashes.</p> <p>Is there a way to optimize the code so that it wont crash and take less time to convert?</p> <p>This is the code that I've been trying to implement.</p> <p>This function applies the DASH_CASE to the whole column:</p> <pre><code>function ApplySeperatedateToColumnEsprinet() { var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(&quot;Esprinet_Original&quot;); ss.getRange(&quot;AH2&quot;).setFormula(&quot;=DASH_CASE(E2)&quot;) var lr = ss.getLastRow(); var fillDownRange = ss.getRange(2,34,lr-1); ss.getRange(&quot;AH2&quot;).copyTo(fillDownRange); } </code></pre> <p>Code that converts the text to a Handle:</p> <pre><code>function DASH_CASE(str) { return str .toLowerCase() .split(' ').filter(e =&gt; e.trim().length).join('-') } </code></pre>
[ { "answer_id": 74321093, "author": "TheMaster", "author_id": 8404453, "author_profile": "https://Stackoverflow.com/users/8404453", "pm_score": 3, "selected": true, "text": "=dash_case(E2:E100)\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74319091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20410556/" ]
74,319,112
<p>I am importing Image, ImageTk using <code>from PIL import Image, ImageTk</code> I get the error that the module doesnt exist, but when I try to install it, it says that the module is already installed.</p> <p>I get this error:</p> <pre><code> from PIL import Image, ImageTk ModuleNotFoundError: No module named 'PIL' </code></pre> <p>When I try to import pillow using <code>pip install pillow</code> I get the following message.</p> <pre><code>Requirement already satisfied: pillow in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (9.2.0) </code></pre> <p><a href="https://i.stack.imgur.com/eQvAX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eQvAX.png" alt="enter image description here" /></a></p> <p>This is on VS code, so I suspect the python interpreter.</p>
[ { "answer_id": 74321093, "author": "TheMaster", "author_id": 8404453, "author_profile": "https://Stackoverflow.com/users/8404453", "pm_score": 3, "selected": true, "text": "=dash_case(E2:E100)\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74319112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20297882/" ]