qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,279,136
<p>With df.replace able to replace <strong>pd.NaT</strong> with any value but <strong>np.nan/None</strong></p> <p><strong>Note</strong>: I have to do multiple data transformations where I'd be using fillna('') which wont work on NaT and I don't want chained replace as it's bit expensive on massive dataframes.</p> <p>I have a df (provided after dtype info)</p> <pre><code>ID int64 TYPE object NAME object LOCATION_ID float64 COUNTRY_ID float64 REGION_ID float64 SLA_TIME_TO_FIRST_RESPONSE_START_TIME datetime64[ns] SLA_TIME_TO_FIRST_RESPONSE_STOP_TIME datetime64[ns] SLA_TIME_TO_RESOLUTION_START_TIME datetime64[ns] SLA_TIME_TO_RESOLUTION_STOP_TIME datetime64[ns] </code></pre> <p><a href="https://i.stack.imgur.com/9T5GO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9T5GO.png" alt="enter image description here" /></a></p> <pre><code>df.replace(pd.NaT,np.nan) </code></pre> <p><strong>Won't replace NaT to NaN</strong> <a href="https://i.stack.imgur.com/MmDUm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MmDUm.png" alt="enter image description here" /></a></p> <pre><code>df.replace(pd.NaT, 'anything') </code></pre> <p><strong>replaces NaT to 'anything'</strong> <a href="https://i.stack.imgur.com/BU7Zg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BU7Zg.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74279414, "author": "INGl0R1AM0R1", "author_id": 12845199, "author_profile": "https://Stackoverflow.com/users/12845199", "pm_score": 0, "selected": false, "text": "df.fillna('anything')\n" }, { "answer_id": 74279718, "author": "Ilya", "author_id": 1139541, "author_profile": "https://Stackoverflow.com/users/1139541", "pm_score": 2, "selected": true, "text": "pandas" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11753818/" ]
74,279,137
<p>I have a react component which I need to download a static file I have in an adjacent folder, I've tried loading the file using</p> <pre><code>import myFile from '../../myfile/myfile.pdf' &lt;Button onClick={(evt) =&gt; this.handleDownload(evt)}&gt;&lt;a href={myFile} download=&quot;My_File.pdf&quot;&gt;Temp Download BTN&lt;/a&gt;&lt;/Button&gt; </code></pre> <p>but when I try to import that, it throws the error below</p> <pre><code>Cannot find module '../../myfile/myfile.pdf' or its corresponding type declarations.ts(2307) </code></pre>
[ { "answer_id": 74279414, "author": "INGl0R1AM0R1", "author_id": 12845199, "author_profile": "https://Stackoverflow.com/users/12845199", "pm_score": 0, "selected": false, "text": "df.fillna('anything')\n" }, { "answer_id": 74279718, "author": "Ilya", "author_id": 1139541, "author_profile": "https://Stackoverflow.com/users/1139541", "pm_score": 2, "selected": true, "text": "pandas" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1712638/" ]
74,279,158
<p>I have a <a href="https://learn.microsoft.com/en-us/dotnet/core/extensions/workers" rel="nofollow noreferrer">.NET 6 Worker Service</a> app which is deployed to Azure in a Docker container running under an AppService <a href="https://azure.microsoft.com/en-us/products/app-service/containers/" rel="nofollow noreferrer">Web App for Containers</a>. Microsoft has a separate NuGet package for ApplicationInsights, <a href="https://www.nuget.org/packages/Microsoft.ApplicationInsights.WorkerService" rel="nofollow noreferrer">Microsoft.ApplicationInsights.WorkerService</a>, when deploying this type of app and I followed the corresponding documentation here: <a href="https://learn.microsoft.com/en-us/azure/azure-monitor/app/worker-service" rel="nofollow noreferrer">Application Insights for Worker Service applications (non-HTTP applications)</a>. However, I cannot seem to find the output from the logs anywhere under my app in the Azure Portal. Per the documentation I linked to above, I am using the <code>TelemetryClient</code> class in the following way:</p> <pre class="lang-csharp prettyprint-override"><code>using (TelemetryClient.StartOperation&lt;RequestTelemetry&gt;(&quot;operation&quot;)) try { SomthingThatMightFail(); } catch (Exception ex) { TelemetryClient.TrackEvent(&quot;Where can I be found in the Azure logs?!&quot;); } </code></pre> <p>But after spending much time digging thru everything in Azure, I cannot find the data I am explicitly logging using <code>TelemetryClient.TrackEvent()</code>. Where does this data wind up and how do I view it? ll I'm able to see are things being implicitly or automatically logged by the framework.</p>
[ { "answer_id": 74280527, "author": "Anthony G.", "author_id": 4196759, "author_profile": "https://Stackoverflow.com/users/4196759", "pm_score": 1, "selected": false, "text": "customEvents\n| limit 100 \n" }, { "answer_id": 74287042, "author": "Peter Bons", "author_id": 932728, "author_profile": "https://Stackoverflow.com/users/932728", "pm_score": 0, "selected": false, "text": "Events" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1404170/" ]
74,279,179
<p>I am bit new to javascript and I want to change a particular JSON element to string without changing the whole JSON.</p> <p>Input:</p> <pre><code> { &quot;Response&quot; : { &quot;Data&quot; : { &quot;Type&quot; : &quot;Set&quot;, &quot;Serial&quot; : &quot;75798&quot; } } } </code></pre> <p>The output I wanted is:</p> <pre><code>{ &quot;Response&quot; : { &quot;Data&quot; : { &quot;Type&quot; : &quot;Set&quot;, &quot;Serial&quot; : 75798 } } } </code></pre> <p>Got to know about <code>parseInt</code> function but not sure how to write the full code where I get the output as above after it processed by the javascript.</p>
[ { "answer_id": 74279254, "author": "Mister Jojo", "author_id": 10669010, "author_profile": "https://Stackoverflow.com/users/10669010", "pm_score": 2, "selected": false, "text": "const mydata = {\n \"Response\" : {\n \"Data\" : {\n \"Type\" : \"Set\",\n \"Serial\" : \"75798\"\n }\n }\n }\n\n\nmydata.Response.Data.Serial = Number(mydata.Response.Data.Serial)\n\nconsole.log(mydata)" }, { "answer_id": 74279315, "author": "Dr. Vortex", "author_id": 17637456, "author_profile": "https://Stackoverflow.com/users/17637456", "pm_score": 3, "selected": true, "text": "let json = `{\n \"Response\": {\n \"Data\": {\n \"Serial\": \"75798\"\n }\n }\n}`\n\nlet obj = JSON.parse(json);\nobj.Response.Data.Serial = parseInt(obj.Response.Data.Serial);\n\nlet newJson = JSON.stringify(obj);\n\nconsole.log(newJson);" }, { "answer_id": 74279407, "author": "Carsten Massmann", "author_id": 2610061, "author_profile": "https://Stackoverflow.com/users/2610061", "pm_score": 2, "selected": false, "text": "toNum()" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8434630/" ]
74,279,181
<p>I'm having a problem here. This is a program finding the maximum and minimum value in a custom list. Some cases work while other cases don't work so well.</p> <pre><code> #find the maximum and minimum number in an integer list def Custom_List(MyList): for i in range(len(MyList)): if MyList[i] &gt;= MyList[i-1]: myMax = MyList[i] if MyList[i] &lt;= MyList[i-1]: myMin = MyList[i] return myMax,myMin #inputing numbers to a list MyList = [] #first an empty list length = int(input(&quot;List length: )) #the length of a list for i in range(length): num= int(input()) #inputing our value MyList.append(num) #and inserting them into our list print(Custom_List(MyList)) '''Example of erroneous cases List length: 8 1645 12 -465 325 0 134 78 664 Output: (664, 78)''' </code></pre> <p>Could you tell me what is the problem here? I will be very much appreciated</p> <p>I expect the code to work on every case, but the error seems to appear sooner than I expected</p>
[ { "answer_id": 74279226, "author": "Zahin Zaman", "author_id": 14848796, "author_profile": "https://Stackoverflow.com/users/14848796", "pm_score": -1, "selected": false, "text": "length = int(input(\"List length: )) #the length of a list\n" }, { "answer_id": 74279288, "author": "Mohamed chouai", "author_id": 19371185, "author_profile": "https://Stackoverflow.com/users/19371185", "pm_score": 0, "selected": false, "text": " def Custom_List(MyList):\n for i in range(1,len(MyList)):\n if MyList[i] >= MyList[i-1]:\n myMax = MyList[i]\n if MyList[i] <= MyList[i-1]:\n myMin = MyList[i]\n \n return myMax,myMin\n" }, { "answer_id": 74280957, "author": "lroth", "author_id": 11032782, "author_profile": "https://Stackoverflow.com/users/11032782", "pm_score": 1, "selected": true, "text": "def Custom_List(MyList):\n # preset min, max with a value from the list\n myMax = MyList[0]\n myMin = MyList[0]\n for num in MyList:\n if num > myMax:\n myMax = num\n if num < myMin:\n myMin = num\n\n return myMax,myMin\n\nMyList = [1645, 12, -465, 325, 0, 134, 78, 664]\nprint(Custom_List(MyList)) \n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20371125/" ]
74,279,251
<p>I've got an Angular route resolver that has a list of items that gets loaded when my parent route gets loaded, like <code>/users</code>. I have implemented an Angular resolver that looks more or less like this:</p> <pre><code>export class UsersResolver implements Resolve&lt;UsersResponse&gt; { constructor(private usersService: UsersService) {} resolve(): Observable&lt;UsersResponse&gt; { return this.usersService.getUsers(); } } </code></pre> <p>The child components consume that resolver data in the standard way:</p> <pre><code>this.route.data.subscribe((data) =&gt; {const users = data['users']} ) </code></pre> <p>That works fine...until I perform any action that might change that list (add/delete/alter a user). In that case, I want that resolver to re-run. Well, more specifically, I want the data returned by the resolver to reflect the updated data. I don't think the static options on <code>runGuardsAndResolvers</code> will do the trick, nor do I think in my case that using the function you can hand to <code>runGuardsAndResolvers</code> will work in my case, either, because these data changes might not happen in concert with a route change.</p> <p>I think what I want is something along the lines of this:</p> <pre><code>export class UsersResolver implements Resolve&lt;UsersResponse&gt; { constructor(private usersService: UsersService) {} resolve(): Observable&lt;UsersResponse&gt; { return this.usersService.users$; } } </code></pre> <p>...where <code>this.usersService.users$</code> is an rxjs <code>Subject</code>. That would mean I could update that subject via other means and (I think) the data in the resolver would update, and therefore any child component subscribed to that resolver would get updated. But if that's right, then where do I trigger the initial data fetch, and how do I ensure that my resolver doesn't actually resolve until the initial data fetch completes?</p> <p>Is this a common issue with a reasonable solution, or am I going about this in the wrong way?</p>
[ { "answer_id": 74279997, "author": "Jonathan Lopez", "author_id": 10745050, "author_profile": "https://Stackoverflow.com/users/10745050", "pm_score": 1, "selected": false, "text": "resolver" }, { "answer_id": 74281237, "author": "Mehyar Sawas", "author_id": 5012127, "author_profile": "https://Stackoverflow.com/users/5012127", "pm_score": 2, "selected": true, "text": "data$: Observable<any>;\n" }, { "answer_id": 74282024, "author": "Andrew Allen", "author_id": 4711754, "author_profile": "https://Stackoverflow.com/users/4711754", "pm_score": 0, "selected": false, "text": " resolve(): Observable<Observable<number[]>> {\n const users$ = this.usersService.getUsers();\n return users$.pipe(\n take(1),\n map((firstValue) => {\n return users$.pipe(startWith(firstValue))\n })\n );\n }\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/474887/" ]
74,279,271
<p>I have a Spark dataframe like the one below:</p> <p><a href="https://i.stack.imgur.com/Jcc3A.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Jcc3A.png" alt="enter image description here" /></a></p> <p>Also, another dataframe:</p> <p><a href="https://i.stack.imgur.com/Jaa0Y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Jaa0Y.png" alt="enter image description here" /></a></p> <p>The output that I expect is below. I need two columns to be added conditionally to the original data dataframe where:<br /> &quot;offeramount1&quot; = 75% of (amount)<br /> &quot;offeramount2&quot; = 65% of (amount)</p> <p>This offer is only to be given when the code is not in the &quot;exclusioncode&quot;</p> <p><a href="https://i.stack.imgur.com/CqNwa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CqNwa.png" alt="enter image description here" /></a></p> <p>I am able to add the columns without any issues using <code>withColumn</code>, but I'm unable to compare the data frames properly.</p>
[ { "answer_id": 74279792, "author": "ZygD", "author_id": 2753501, "author_profile": "https://Stackoverflow.com/users/2753501", "pm_score": 2, "selected": true, "text": "'leftanti'" }, { "answer_id": 74281280, "author": "PieCot", "author_id": 5359797, "author_profile": "https://Stackoverflow.com/users/5359797", "pm_score": 0, "selected": false, "text": "amount_df" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20215310/" ]
74,279,293
<p>I've tried to use</p> <pre><code>TO_CHAR(ACTIVE_DT, 'YYYY-MM-DD'), TO_CHAR(CONTRACT_DATE, 'YYYY-MM-DD') </code></pre> <p>And then a <code>CASE</code> statement to find out which dates do not match.</p> <p>However when I do this it's telling me a lot of them don't match when they should because the contract date field has time in it and the active date does not. But I have used <code>TO_CHAR</code> to try and fix it. I'm not sure what else to try.</p> <pre><code>CASE WHEN CONTRACT_DATE = ACTIVE_DT THEN 'Correct' WHEN CONTRACT_DATE &lt;&gt; ACTIVE_DT THEN 'Error' ELSE ' ' END AS &quot;QC&quot; </code></pre>
[ { "answer_id": 74279792, "author": "ZygD", "author_id": 2753501, "author_profile": "https://Stackoverflow.com/users/2753501", "pm_score": 2, "selected": true, "text": "'leftanti'" }, { "answer_id": 74281280, "author": "PieCot", "author_id": 5359797, "author_profile": "https://Stackoverflow.com/users/5359797", "pm_score": 0, "selected": false, "text": "amount_df" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20224080/" ]
74,279,314
<p>I have a field &quot;Numbers&quot; that can have a value such as:</p> <p>&quot;01-02-03-04-Zero&quot;</p> <p>I want to change the substring &quot;Zero&quot; to &quot;00&quot; and move it to the front of the string, so that the result is:</p> <p>&quot;00-01-02-03-04&quot;</p> <p>Not all rows contain this &quot;Zero&quot; substring so I only want to perform this on fields that do.</p>
[ { "answer_id": 74279419, "author": "Ilya", "author_id": 1139541, "author_profile": "https://Stackoverflow.com/users/1139541", "pm_score": 0, "selected": false, "text": "s = \"01-02-03-04-Zero\"\ns_split = s.split(\"-\")\nzero_idxs = [n for n, elem in enumerate(s_split) if elem == \"Zero\"]\n\nfor idx in zero_idxs:\n s_split.pop(idx)\n\ns = \"-\".join([\"00\"] * len(zero_idxs) + s_split)\n" }, { "answer_id": 74279546, "author": "I'mahdi", "author_id": 1740577, "author_profile": "https://Stackoverflow.com/users/1740577", "pm_score": 1, "selected": false, "text": "regex" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19932973/" ]
74,279,330
<p>I am using a CSV file to read in terms that I am looking for in a text file.</p> <p>I would like to use a wildcard or 'Like' as a term. I am not looking for wildcard for text document name but for the terms I'm searching for found in the CSV file.</p> <p>For example: Terms in CSV file to search in Text File, each term is in it's own row.</p> <p>test* #search for test, tests, testing, etc project<br> list<br> table<br> chair<br></p> <p>Is there a wildcard that can be used in the CSV file so that all variants of that word is returned? I want to place the wildcard in the CSV file.</p> <p>Below is my code, the file it reads the terms I'm searching for is contract_search_terms.csv</p> <pre><code>def main(): txt_filepaths = glob.glob(&quot;**/*.txt&quot;, recursive=True) start = time.time() results = {} new_results = [] #place dictionary values organized per key = value instead of key = tuple of values term_filename = open('contract_search_terms.csv', 'r') #file where terms to be searched is found term_file = csv.DictReader(term_filename) search_terms =[] #append terms into a list, this means that we can use several columns and append them all to one list. #############search for the terms imported into the list############################################################ for col in term_file: search_terms.append(col['Contract Terms']) #indicate what columns you want read in print(search_terms) #this is just a check to show what terms are in the list for filepath in txt_filepaths: print(f&quot;Searching document {filepath}&quot;) #print what file the code is reading search_terms = search_terms #place terms list into search_terms so that the code below can read it when looping through the contracts. filename = os.path.basename(filepath) found_terms = {} #dictionary of the terms found line_number={} for term in search_terms: if term in found_terms.keys(): continue with open(filepath, &quot;r&quot;, encoding=&quot;utf-8&quot;) as fp: lines = str(fp.readlines()).split('.') #turns contract file lines as a list for line in lines: if line.find(term) != -1: #line by line is '-1', paragraph '\n' line_number = lines.index(line) new_results.append(f&quot;'{term}' New_Column '{filename}' New_Column '{line}' New_Column '{line_number}'&quot;) #placing the results from the print statement below into a list print(f&quot;Found '{term}' in document '{filename}' in line '{line_number}'&quot;) if term in results.keys(): pages = results[''.join(term)].append([filename,line,line_number]) else: results[term] = [filename] #Place results into dataframe and create a csv file to use as a check if results_reports is not correct d2=pd.DataFrame(new_results, columns=['Results']) #passing the list to a dataframe and giving it a column title d2.to_csv('results.csv', index=True) </code></pre>
[ { "answer_id": 74279419, "author": "Ilya", "author_id": 1139541, "author_profile": "https://Stackoverflow.com/users/1139541", "pm_score": 0, "selected": false, "text": "s = \"01-02-03-04-Zero\"\ns_split = s.split(\"-\")\nzero_idxs = [n for n, elem in enumerate(s_split) if elem == \"Zero\"]\n\nfor idx in zero_idxs:\n s_split.pop(idx)\n\ns = \"-\".join([\"00\"] * len(zero_idxs) + s_split)\n" }, { "answer_id": 74279546, "author": "I'mahdi", "author_id": 1740577, "author_profile": "https://Stackoverflow.com/users/1740577", "pm_score": 1, "selected": false, "text": "regex" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8769777/" ]
74,279,339
<p>How do I remove those duplicates that has different spellings?</p> <p>Example table with duplicates</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> <th>Score</th> </tr> </thead> <tbody> <tr> <td>Abi</td> <td>12</td> </tr> <tr> <td>Abby</td> <td>12</td> </tr> <tr> <td>Aby</td> <td>12</td> </tr> <tr> <td>Toom</td> <td>4</td> </tr> <tr> <td>Tom</td> <td>4</td> </tr> <tr> <td>Tm</td> <td>4</td> </tr> <tr> <td>Crow</td> <td>9</td> </tr> </tbody> </table> </div> <p>result I am looking for</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> <th>Score</th> </tr> </thead> <tbody> <tr> <td>Abby</td> <td>12</td> </tr> <tr> <td>Tom</td> <td>9</td> </tr> <tr> <td>Crow</td> <td>4</td> </tr> </tbody> </table> </div> <pre><code>name &lt;- c('Abi', 'Abby', 'Aby', 'Toom', 'Tom', 'Tm', 'Crow') score &lt;- c(12,12,12,4,4,4,9) duplicate &lt;- data.frame(name,score) </code></pre>
[ { "answer_id": 74279548, "author": "Maël", "author_id": 13460602, "author_profile": "https://Stackoverflow.com/users/13460602", "pm_score": 0, "selected": false, "text": "adist" }, { "answer_id": 74279551, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 1, "selected": false, "text": "library(dplyr)\nlibrary(phonics)\nkeyname <- c(\"Abby\", \"Tom\", \"Crow\")\n duplicate %>%\n mutate(name2 = keyname[match(name, keyname)]) %>% \n group_by(grp = soundex(name)) %>%\n mutate(name = name2[!is.na(name2)]) %>%\n ungroup %>% \n distinct(name, score)\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16706579/" ]
74,279,357
<p>Hey is there is simple way to show 12 as 12.00, when I convert it to string? I can't just add zeros, cause it also has inputs with digits, where only one 0 need to be added.</p> <p>Some inputs and there espected outputs:</p> <pre><code> 12 -&gt; 12.00 1.3 -&gt; 1.30 0.2 -&gt; 0.2 3.454 -&gt; 3.45 </code></pre> <p>I have tried this:</p> <p><code>String.Format(&quot;{0:0.00}&quot;, Regex.Replace(VerkaufspreisInput.Text, 12);</code></p> <p>Output 12</p> <p>It's the wrong function.</p> <p>Thanks for help!</p>
[ { "answer_id": 74279373, "author": "rotgers", "author_id": 2223566, "author_profile": "https://Stackoverflow.com/users/2223566", "pm_score": 2, "selected": true, "text": "ToString" }, { "answer_id": 74279474, "author": "Scott Czerneda", "author_id": 16475898, "author_profile": "https://Stackoverflow.com/users/16475898", "pm_score": 0, "selected": false, "text": "{0:0.00}" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20390110/" ]
74,279,358
<pre><code>const character = [ { id: 1, na: &quot;A&quot; }, { id: 2, na: &quot;B&quot; }, { id: 3, na: &quot;C&quot; }, { id: 4, na: &quot;D&quot; }, { id: 5, na: &quot;f&quot; }, ]; const character2 = [ { id: 3, na: &quot;C&quot; }, { id: 4, na: &quot;D&quot; }, ]; </code></pre> <p>How can I get the different elements in the two arrays For example, I need items A ,B AND F</p>
[ { "answer_id": 74279988, "author": "Gage", "author_id": 11870326, "author_profile": "https://Stackoverflow.com/users/11870326", "pm_score": 2, "selected": false, "text": "const a = [\n 1,2,3\n]\n\nconst b = [\n 3\n]\n\nconst filtered = a.filter(x => !b.includes(x))\nconsole.log(filtered);" }, { "answer_id": 74280063, "author": "Carsten Massmann", "author_id": 2610061, "author_profile": "https://Stackoverflow.com/users/2610061", "pm_score": 0, "selected": false, "text": "new Set()" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14880479/" ]
74,279,366
<p>I have output that looks like this:</p> <pre><code>BTC-USDT [FTX] 20460.91 20470.09 BTC-USDT [BINANCE_US] 20457.34 20467.28 BTC-USDT [BINANCE_US] 20457.50 20467.28 </code></pre> <p>I would like it to look like this:</p> <pre class="lang-none prettyprint-override"><code>BTC-USDT [ FTX] 20460.91 20470.09 BTC-USDT [BINANCE_US] 20457.34 20467.28 BTC-USDT [BINANCE_US] 20457.50 20467.28 </code></pre> <p>I think I am close with this code, but I am confused by <code>setw()</code></p> <pre><code>std::cout &lt;&lt; pair &lt;&lt; std::setfill(' ') &lt;&lt; std::setw(15) &lt;&lt; &quot; [&quot; &lt;&lt; exch &lt;&lt; &quot;] &quot; &lt;&lt; fixed &lt;&lt; setprecision(2) &lt;&lt; bid &lt;&lt; &quot; &quot; &lt;&lt; ask &lt;&lt; std::endl; </code></pre>
[ { "answer_id": 74279454, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 2, "selected": false, "text": "#include <iomanip>\n#include <iostream>\n\nint main() {\n std::cout << \"Foo \" << \"[\" \n << std::setfill(' ') << std::setw(15)\n << \"Bar\" << \"] \" \n << std::fixed << std::setprecision(2) << 20.897\n << \" \" << 1.4566 << std::endl;\n\n return 0;\n}\n" }, { "answer_id": 74279469, "author": "Remy Lebeau", "author_id": 65863, "author_profile": "https://Stackoverflow.com/users/65863", "pm_score": 3, "selected": true, "text": "pair" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/817659/" ]
74,279,371
<p>I have a table of data that summarizes prices vs. number of users. When I want to display the scatter plot overlaid with a moving average line I use the following Julia function:</p> <pre><code>function log_scatter(df::DataFrame; smooth=2, title=&quot;Price by Number of Users&quot;) sort(select(df, [:Price, :Users]), :Users) |&gt; @vlplot(width=640,height=512, title=title) + @vlplot(mark={:point, opacity=0.5}, x={field=:Users, scale={type=&quot;log&quot;},title=&quot;Users&quot;}, y={:Price,title=&quot;Price per User&quot;}) + @vlplot(transform=[ { groupby=[:Users], aggregate=[{ op=:mean, field=:Price, as=&quot;AvgPrice&quot; }] }, { frame=[-smooth,smooth], window=[{ field=&quot;AvgPrice&quot;, op=:mean, as=&quot;rolling&quot; }] } ], mark={:line,size=2,color=&quot;red&quot;}, x={:Users, title=&quot;Users&quot;}, y={&quot;rolling:q&quot;, title=&quot;Average&quot;}) end </code></pre> <p>It produces a nice plot: <a href="https://i.stack.imgur.com/8cWwP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8cWwP.png" alt="enter image description here" /></a></p> <p>Unfortunately when I want to do the same with grouping, I can't get the moving average to display</p> <pre><code>function log_scatter_and(df::DataFrame, other; smooth=2, title=&quot;Price by Number of Users&quot;) otherSym=Symbol(other) prices = price_and(df, other) sort(select(prices, [:Price, :Users, otherSym]), :Users) |&gt; @vlplot(width=640,height=512, title=title) + @vlplot(mark={:point, opacity=0.5}, color=otherSym, x={field=:Users, scale={type=&quot;log&quot;},title=&quot;Users&quot;}, y={:Price,title=&quot;Price per User&quot;}) + @vlplot(transform=[ { groupby=[:Users, otherSym], aggregate=[{ op=:mean, field=:Price, as=&quot;AvgPrice&quot; }] }, { frame=[-smooth,smooth], window=[{ field=&quot;AvgPrice&quot;, op=:mean, as=&quot;rolling&quot; }] } ], mark={:line,size=2,color=otherSym}, x={:Users, title=&quot;Users&quot;}, y={&quot;rolling:q&quot;, title=&quot;Average&quot;}) end </code></pre> <p>This is the output when I try to group by year <a href="https://i.stack.imgur.com/zliBp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zliBp.png" alt="enter image description here" /></a></p> <p>I want to have the rolling average lines show up as well as the scatter</p>
[ { "answer_id": 74296488, "author": "giantmoa", "author_id": 20258205, "author_profile": "https://Stackoverflow.com/users/20258205", "pm_score": 2, "selected": false, "text": "VegaLite" }, { "answer_id": 74296792, "author": "هنروقتان", "author_id": 17836238, "author_profile": "https://Stackoverflow.com/users/17836238", "pm_score": 1, "selected": false, "text": "function log_scatter_and(df::DataFrame, other; smooth=2, title=\"Price by Number of Users\")\n otherSym=Symbol(other)\n prices = price_and(df, other)\n sort(select(prices, [:Price, :Users, otherSym]), :Users) |> \n @vlplot(width=640,height=512, title=title) +\n @vlplot(mark={:point, opacity=0.5}, color=otherSym, x={field=:Users, scale={type=\"log\"},title=\"Users\"}, y={:Price,title=\"Price per User\"}) +\n @vlplot(transform=[\n { groupby=[:Users, otherSym], aggregate=[{ op=:mean, field=:Price, as=\"AvgPrice\" }] },\n { groupby=[:Users, otherSym],frame=[-smooth,smooth], window=[{ field=\"AvgPrice\", op=:mean, as=\"rolling\" }] }\n ],\n mark={:line,size=2,color=otherSym}, x={:Users, title=\"Users\"}, y={\"rolling:q\", title=\"Average\"})\nend\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2796502/" ]
74,279,381
<p>I have a powershell code which retrieves some data from the database, the declared data type is an array.</p> <pre><code> @my_data = @() $x = (invoke-sqlcmd -serverinstance x -database y -Query &quot;select name from first_table&quot;) $y = (invoke-sqlcmd -serverinstance xx -database yy -Query &quot;select name from second_table&quot;) $my_data = $x + $y $my_data = $my_data | select -unique $my_data = &quot;Tom Tim Jo&quot; $required_format = &quot;Tom,Tim,Jo&quot; </code></pre> <p>In the example above, I require the format to be comma delimited, at the moment its space delimited.</p> <p>The issue is that a function that I am passing <code>$my_data</code> to requires it to be comma delimited.</p> <p>I have tried to use <code>-join ','</code> as suggested on other SO pages and examples to no avail, as the variable isn't getting comma delimited.</p>
[ { "answer_id": 74279445, "author": "frankM_DN", "author_id": 20034020, "author_profile": "https://Stackoverflow.com/users/20034020", "pm_score": 1, "selected": false, "text": "$my_data" }, { "answer_id": 74279724, "author": "Dennis", "author_id": 8014824, "author_profile": "https://Stackoverflow.com/users/8014824", "pm_score": 2, "selected": false, "text": "$my_data.Replace(' ',',')\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/894827/" ]
74,279,409
<p>I don't or can't modify the Java source code. The goal to configure just the Kotlin compiler to know what is nullable and what isn't.</p>
[ { "answer_id": 74279662, "author": "user2340612", "author_id": 2340612, "author_profile": "https://Stackoverflow.com/users/2340612", "pm_score": 2, "selected": false, "text": "null" }, { "answer_id": 74279786, "author": "Tenfour04", "author_id": 506796, "author_profile": "https://Stackoverflow.com/users/506796", "pm_score": 1, "selected": false, "text": "@Nullable" }, { "answer_id": 74449349, "author": "Aaron Digulla", "author_id": 34088, "author_profile": "https://Stackoverflow.com/users/34088", "pm_score": 0, "selected": false, "text": "String foo()" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34088/" ]
74,279,475
<p>I am quite new in ADF so thats why i am asking you for any suggestions.</p> <p>The use case: I have a csv file which contains unique id and url's (see image below). i would like to use this file in order to export the value from various url's. In the second image you can see a example of the data from a url.</p> <p>So in the current situation i am using each url and insert this manually as a source from the ADF Copy Activity task to export the data to a SQL DB. This is very time consuming method.</p> <p>How can i create a ADF pipeline to use the csv file as a source, and that a copy activity use each row of the url and copy the data to Azure SQL DB? Do i need to add GetMetaData activity for example? so how?</p> <p>Many thanks.</p> <p><a href="https://i.stack.imgur.com/svFKN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/svFKN.png" alt="a csv file" /></a></p> <p><a href="https://i.stack.imgur.com/jCqAk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jCqAk.png" alt="a xml file" /></a></p>
[ { "answer_id": 74279662, "author": "user2340612", "author_id": 2340612, "author_profile": "https://Stackoverflow.com/users/2340612", "pm_score": 2, "selected": false, "text": "null" }, { "answer_id": 74279786, "author": "Tenfour04", "author_id": 506796, "author_profile": "https://Stackoverflow.com/users/506796", "pm_score": 1, "selected": false, "text": "@Nullable" }, { "answer_id": 74449349, "author": "Aaron Digulla", "author_id": 34088, "author_profile": "https://Stackoverflow.com/users/34088", "pm_score": 0, "selected": false, "text": "String foo()" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7318436/" ]
74,279,532
<p>I'm preprocessing tweets and need to set the maximum limit of the number of consecutive occurrences of &quot;@USER&quot; to 3 times. For example, a tweet like this:</p> <blockquote> <p>this tweet contains hate speech @USER@USER@USER@USER@USER about a target group @USER@USER</p> </blockquote> <p>after processing, should look like this:</p> <blockquote> <p>this tweet contains hate speech @USER@USER@USER about a target group @USER@USER</p> </blockquote> <p>I was able to achieve the desired result with a <code>while</code> loop, however, I'm wondering if someone knows how to do it a simpler way. Thanks!</p> <pre><code>tweets = [&quot;this tweet contains hate speech @USER@USER@USER@USER@USER about a target group @USER@USER&quot;] K = &quot;@USER&quot; limit = 3 i = 0 for tweet in tweets: tweet = tweet.split(' ') while i &lt; len(tweet): if tweet[i].count(K) &gt; limit: tweet[i] = K*int(limit) tweet = &quot; &quot;.join(str(item) for item in tweet) i +=1 print(tweet) # Output: this tweet contains hate speech @USER@USER@USER about a target group @USER@USER </code></pre>
[ { "answer_id": 74279662, "author": "user2340612", "author_id": 2340612, "author_profile": "https://Stackoverflow.com/users/2340612", "pm_score": 2, "selected": false, "text": "null" }, { "answer_id": 74279786, "author": "Tenfour04", "author_id": 506796, "author_profile": "https://Stackoverflow.com/users/506796", "pm_score": 1, "selected": false, "text": "@Nullable" }, { "answer_id": 74449349, "author": "Aaron Digulla", "author_id": 34088, "author_profile": "https://Stackoverflow.com/users/34088", "pm_score": 0, "selected": false, "text": "String foo()" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20389880/" ]
74,279,534
<p>I was using mongo in dev just fine, when deploying the app into test env I got this error:</p> <pre><code>com.mongodb.MongoCommandException: Command failed with error 2 (BadValue): 'cannot use 'j' option when a host does not have journaling enabled' on server localhost:34653. The full response is {&quot;ok&quot;: 0.0, &quot;errmsg&quot;: &quot;cannot use 'j' option when a host does not have journaling enabled&quot;, &quot;code&quot;: 2, &quot;codeName&quot;: &quot;BadValue&quot;} </code></pre> <p>full stuck trace:</p> <pre><code>Caused by: com.mongodb.MongoCommandException: Command failed with error 2 (BadValue): 'cannot use 'j' option when a host does not have journaling enabled' on server localhost:34653. The full response is {&quot;ok&quot;: 0.0, &quot;errmsg&quot;: &quot;cannot use 'j' option when a host does not have journaling enabled&quot;, &quot;code&quot;: 2, &quot;codeName&quot;: &quot;BadValue&quot;} at com.mongodb.internal.connection.ProtocolHelper.getCommandFailureException(ProtocolHelper.java:175) at com.mongodb.internal.connection.InternalStreamConnection.receiveCommandMessageResponse(InternalStreamConnection.java:303) at com.mongodb.internal.connection.InternalStreamConnection.sendAndReceive(InternalStreamConnection.java:259) at com.mongodb.internal.connection.UsageTrackingInternalConnection.sendAndReceive(UsageTrackingInternalConnection.java:99) at com.mongodb.internal.connection.DefaultConnectionPool$PooledConnection.sendAndReceive(DefaultConnectionPool.java:450) at com.mongodb.internal.connection.CommandProtocolImpl.execute(CommandProtocolImpl.java:72) at com.mongodb.internal.connection.DefaultServer$DefaultServerProtocolExecutor.execute(DefaultServer.java:218) at com.mongodb.internal.connection.DefaultServerConnection.executeProtocol(DefaultServerConnection.java:269) at com.mongodb.internal.connection.DefaultServerConnection.command(DefaultServerConnection.java:131) at com.mongodb.internal.connection.DefaultServerConnection.command(DefaultServerConnection.java:123) at com.mongodb.operation.CommandOperationHelper.executeWriteCommand(CommandOperationHelper.java:369) at com.mongodb.operation.CommandOperationHelper.executeWriteCommand(CommandOperationHelper.java:360) at com.mongodb.operation.CommandOperationHelper.executeCommand(CommandOperationHelper.java:284) at com.mongodb.operation.CommandOperationHelper.executeCommand(CommandOperationHelper.java:277) at com.mongodb.operation.CreateIndexesOperation$1.call(CreateIndexesOperation.java:177) at com.mongodb.operation.CreateIndexesOperation$1.call(CreateIndexesOperation.java:172) at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:530) at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:492) at com.mongodb.operation.CreateIndexesOperation.execute(CreateIndexesOperation.java:172) at com.mongodb.operation.CreateIndexesOperation.execute(CreateIndexesOperation.java:72) at com.mongodb.client.internal.MongoClientDelegate$DelegateOperationExecutor.execute(MongoClientDelegate.java:206) at com.mongodb.client.internal.MongoCollectionImpl.executeCreateIndexes(MongoCollectionImpl.java:886) at com.mongodb.client.internal.MongoCollectionImpl.createIndexes(MongoCollectionImpl.java:869) at com.mongodb.client.internal.MongoCollectionImpl.createIndexes(MongoCollectionImpl.java:864) at com.mongodb.client.internal.MongoCollectionImpl.createIndex(MongoCollectionImpl.java:849) at com.github.cloudyrock.mongock.driver.mongodb.sync.v4.repository.MongoSync4RepositoryBase.createRequiredUniqueIndex(MongoSync4RepositoryBase.java:99) at com.github.cloudyrock.mongock.driver.mongodb.sync.v4.repository.MongoSync4RepositoryBase.ensureIndex(MongoSync4RepositoryBase.java:58) at com.github.cloudyrock.mongock.driver.mongodb.sync.v4.repository.MongoSync4RepositoryBase.initialize(MongoSync4RepositoryBase.java:43) at com.github.cloudyrock.mongock.driver.core.driver.ConnectionDriverBase.initialize(ConnectionDriverBase.java:40) at com.github.cloudyrock.mongock.runner.core.executor.MigrationExecutor.initializationAndValidation(MigrationExecutor.java:225) at com.github.cloudyrock.spring.v5.core.SpringMigrationExecutor.initializationAndValidation(SpringMigrationExecutor.java:31) at com.github.cloudyrock.mongock.runner.core.executor.MigrationExecutor.executeMigration(MigrationExecutor.java:63) at com.github.cloudyrock.spring.v5.core.SpringMigrationExecutor.executeMigration(SpringMigrationExecutor.java:37) at com.github.cloudyrock.mongock.runner.core.executor.MongockRunnerBase.execute(MongockRunnerBase.java:53) ... 49 common frames omitted </code></pre> <p>dependencies:</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;com.github.cloudyrock.mongock&lt;/groupId&gt; &lt;artifactId&gt;mongock-bom&lt;/artifactId&gt; &lt;version&gt;4.3.8&lt;/version&gt; &lt;type&gt;pom&lt;/type&gt; &lt;scope&gt;import&lt;/scope&gt; &lt;/dependency&gt; </code></pre> <pre><code>&lt;dependency&gt; &lt;groupId&gt;com.github.cloudyrock.mongock&lt;/groupId&gt; &lt;artifactId&gt;mongock-spring-v5&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.github.cloudyrock.mongock&lt;/groupId&gt; &lt;artifactId&gt;mongodb-springdata-v3-driver&lt;/artifactId&gt; &lt;/dependency&gt; </code></pre> <p>configuration:</p> <pre><code>@Bean public MongockSpring5.MongockApplicationRunner mongockApplicationRunner( ApplicationContext springContext, MongoTemplate mongoTemplate) { log.debug(&quot;Configuring Mongock&quot;); return MongockSpring5.builder() .setDriver(SpringDataMongoV3Driver.withDefaultLock(mongoTemplate)) // package to scan for migrations .addChangeLogsScanPackage(&quot;ru.fabit.visor.config.dbmigrations&quot;) .setSpringContext(springContext) .setEnabled(true) .buildApplicationRunner(); } </code></pre> <p><a href="https://i.stack.imgur.com/Kf7u2.png" rel="nofollow noreferrer">enter image description here</a></p> <p>i set command: mongod --journal but the same error</p>
[ { "answer_id": 74279662, "author": "user2340612", "author_id": 2340612, "author_profile": "https://Stackoverflow.com/users/2340612", "pm_score": 2, "selected": false, "text": "null" }, { "answer_id": 74279786, "author": "Tenfour04", "author_id": 506796, "author_profile": "https://Stackoverflow.com/users/506796", "pm_score": 1, "selected": false, "text": "@Nullable" }, { "answer_id": 74449349, "author": "Aaron Digulla", "author_id": 34088, "author_profile": "https://Stackoverflow.com/users/34088", "pm_score": 0, "selected": false, "text": "String foo()" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16747918/" ]
74,279,539
<p>when i try to access the user profile by clicking on the profile icon it cause me this error that don't let get to profile page and block whole the app</p> <p><strong>Profile page source code:</strong></p> <pre class="lang-dart prettyprint-override"><code>import 'package:cached_network_image/cached_network_image.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:yumor/models/progress.dart'; import 'package:yumor/models/user_model.dart'; class profile extends StatefulWidget { const profile({Key? key,required this.userProfile}) : super(key: key); final String? userProfile; @override State&lt;profile&gt; createState() =&gt; _profileState(); } class _profileState extends State&lt;profile&gt; { final userRef = FirebaseFirestore.instance.collection('users'); Future&lt;UserModel?&gt; getData() async { final userRef = FirebaseFirestore.instance.collection('users'); final doc = await userRef.doc(widget.userProfile).get(); if (doc.exists) { var data = doc.data(); } else { return null; } final data = await FirebaseFirestore.instance .collection('users') .doc(userRef.id) .get(); if (data.exists) { UserModel user = UserModel.fromMap(data.data()!); return user; } } late final future = getData(); Widget buildprofileheader() { return FutureBuilder&lt;UserModel?&gt;(future:future, builder: ((context, snapshot) { if(!snapshot.hasData){ UserModel user=UserModel.fromMap(userRef.parameters); return Padding(padding:EdgeInsets.all(16.0), child: Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: &lt;Widget&gt;[ Icon(Icons.account_circle, size: 90,) ], ), Container( alignment: Alignment.center, padding: EdgeInsets.all(12.0), child: Text( user.Username as String, style: TextStyle( fontWeight: FontWeight.bold, fontSize:16.0, ), ), ), ], ), );} else{ return CircularProgress();} }), ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( centerTitle: true, title: Text( &quot;Profile&quot;, ), ), body: ListView(children: &lt;Widget&gt;[ buildprofileheader(), ])); } } </code></pre> <p><a href="https://i.stack.imgur.com/xt6aA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xt6aA.png" alt="enter image description here" /></a></p> <p><strong>User model(user firebase user creation):</strong></p> <pre class="lang-dart prettyprint-override"><code>import 'package:flutter/foundation.dart'; class UserModel { String? uid; String? Username; String? email; String? photoUrl; UserModel( {this.uid, this.email, this.Username, this.photoUrl}); // receving data from the server factory UserModel.fromMap(map) { return UserModel( uid: map['userId'], // also this line was causing NoSuchMethodError &lt;======== Username: map['Username'], email: map['email'], photoUrl: map['photoUrl'], ); } // /// sending data to firestore Map&lt;String, dynamic&gt; toMap() { return { 'userId': uid, 'Username': Username, 'email': email, 'photoUrl': photoUrl, }; } } </code></pre> <p><em>NoSuchMethodError (NoSuchMethodError: Class 'Type' has no instance method '[]'. Receiver: Map&lt;dynamic, dynamic&gt; Tried calling: )</em> called in this code</p> <p><strong>the error step by step :</strong></p> <p>here what happen when i click first there is the app</p> <p><a href="https://i.stack.imgur.com/yFYNy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yFYNy.png" alt="enter image description here" /></a></p> <p>here after some seconds after i click on the profile icon this page appear</p> <p><a href="https://i.stack.imgur.com/WHPSQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WHPSQ.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74279582, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 2, "selected": false, "text": " Text( user.Username ?? \"defaultValueOnNullCase\",)\n" }, { "answer_id": 74279653, "author": "Shaan Mephobic", "author_id": 14595863, "author_profile": "https://Stackoverflow.com/users/14595863", "pm_score": 2, "selected": true, "text": "Text" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16571275/" ]
74,279,565
<p>Hi I have a function which I would like to unit test. This is my function.</p> <pre><code>let docProcess: IDocProcess; public onCalling(args) { if (this.docProcess.viewMode) { this.makeCalls(args); } } </code></pre> <p>This IDocProcess is an interface:</p> <pre><code>export interface IDocProcess { viewMode: boolean; editMode: boolean; deleteMode: boolean; } </code></pre> <p>I would like to unit test the above function. If I pass docProcess.viewMode as true, makeCalls(args) function should be called. If false, then the function must not be called.</p> <p>The following is my Unit test code:</p> <pre><code> beforeEach(async(() =&gt; { TestBed.configureTestingModule({ imports: [RouterTestingModule], declarations: [CallsComponent], providers: [ MockData ], schemas: [CUSTOM_ELEMENTS_SCHEMA] }).compileComponents(); })); beforeEach(() =&gt; { fixture = TestBed.createComponent(CallsComponent); component = fixture.componentInstance; }); it('should call makeCalls() only on View Mode', () =&gt; { component.docProcess.viewMode = true; fixture.detectChanges(); component.onCalling(mockArgsData); expect(component.makeCalls).toHaveBeenCalled(); </code></pre> <p>But the test results get failed. Getting cannot read properties of undefined (reading:'viewMode').</p> <p>Is this because the Testing module couldn't recognize the interface. A similar situation like this, I am also getting &quot;Cannot set properties of undefined (setting: variable_name)&quot;</p> <p>Please help me in resolving this.</p> <pre><code></code></pre>
[ { "answer_id": 74279582, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 2, "selected": false, "text": " Text( user.Username ?? \"defaultValueOnNullCase\",)\n" }, { "answer_id": 74279653, "author": "Shaan Mephobic", "author_id": 14595863, "author_profile": "https://Stackoverflow.com/users/14595863", "pm_score": 2, "selected": true, "text": "Text" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20389984/" ]
74,279,628
<p>How to merge two csv files using python and create a merged csv file. I tried below code from available sources but was not able to attain my requirements.</p> <pre class="lang-py prettyprint-override"><code>def merge_csv(): # reading csv files data1 = pd.read_csv('C:/folder/csv1.csv') data2 = pd.read_csv('C:/folder/csv2.csv') # using merge function by setting how='outer' output4 = pd.merge(data1, data2, how='outer') print(output4) # I tried below code to create new csv but not working. I dont want to create a csv manually instead create automatically. output4.to_csv('C:\\folder\\merged.csv') or with open('C:/folder/merged.csv', 'w+', newline='') as data: dict_writer = csv.DictWriter(data) dict_writer.writeheader() dict_writer.writerows(output4) </code></pre> <p>Finaly I am trying to merge both columns .</p> <p><strong>Examples</strong>:<br /> <code>csv1</code></p> <pre><code> id name 1 abc </code></pre> <p><code>csv2</code></p> <pre><code> dept location cse xyz </code></pre> <p>merged csv to be like</p> <pre><code> id name dept location 1 abc cse xyz </code></pre>
[ { "answer_id": 74279890, "author": "Skapis9999", "author_id": 11002498, "author_profile": "https://Stackoverflow.com/users/11002498", "pm_score": 2, "selected": false, "text": "df1 = pd.read_csv('C:/folder/csv1.csv')\ndf2 = pd.read_csv('C:/folder/csv2.csv')\n" }, { "answer_id": 74286072, "author": "EvensF", "author_id": 2387806, "author_profile": "https://Stackoverflow.com/users/2387806", "pm_score": 1, "selected": false, "text": "import pandas as pd\n\ndata1 = pd.read_csv('csv1.csv')\ndata2 = pd.read_csv('csv2.csv')\n\noutput4 = pd.concat((data1, data2), axis='columns')\nprint(output4)\noutput4.to_csv('merge1.csv', index=False)\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11867978/" ]
74,279,679
<p>The following code returns a list of file-names in a given directory:</p> <pre><code>def get_files(dir_path_str): onlyfiles = next(os.walk(dir_path_str))[2] return onlyfiles </code></pre> <p>How can I make it return absolute file paths with minimal modification and preserve the behavior of the function?</p>
[ { "answer_id": 74279804, "author": "Jason Lunder", "author_id": 17129046, "author_profile": "https://Stackoverflow.com/users/17129046", "pm_score": 2, "selected": true, "text": "from pathlib import Path\n\n\ndef get_files(inp_path_str):\n directory = Path(inp_path_str)\n only_files = [file.absolute() for file in directory.iterdir() if file.is_file()]\n return only_files\n" }, { "answer_id": 74279806, "author": "AirSquid", "author_id": 10789207, "author_profile": "https://Stackoverflow.com/users/10789207", "pm_score": 0, "selected": false, "text": "import os\n\ndef get_files(dir_path_str):\n top_level = next(os.walk(dir_path_str))\n onlyfiles = top_level[2]\n abs_path = os.path.abspath(top_level[0])\n files = [os.path.join(abs_path, f) for f in onlyfiles]\n return files\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/159072/" ]
74,279,681
<p>I am using selenium webdriver to pull data from one website and my goal is to copy and paste that date into another site using python, I am able to pull the data from the 1st site using iFrame + XPATH but on the 2nd site I am failing to locate the exact web element. I pasted it below:</p> <pre><code>&lt;textarea rows=&quot;5&quot; aria-invalid=&quot;false&quot; placeholder=&quot;Paste in a list of emails separated by commas or new lines&quot; class=&quot;MuiOutlinedInput-input MuiInputBase-input MuiInputBase-inputMultiline MuiInputBase-inputSizeSmall TextInput-input css-x7mp9n&quot; id=&quot;mui-2&quot; style=&quot;height: 115px;&quot;&gt;&lt;/textarea&gt; </code></pre>
[ { "answer_id": 74279804, "author": "Jason Lunder", "author_id": 17129046, "author_profile": "https://Stackoverflow.com/users/17129046", "pm_score": 2, "selected": true, "text": "from pathlib import Path\n\n\ndef get_files(inp_path_str):\n directory = Path(inp_path_str)\n only_files = [file.absolute() for file in directory.iterdir() if file.is_file()]\n return only_files\n" }, { "answer_id": 74279806, "author": "AirSquid", "author_id": 10789207, "author_profile": "https://Stackoverflow.com/users/10789207", "pm_score": 0, "selected": false, "text": "import os\n\ndef get_files(dir_path_str):\n top_level = next(os.walk(dir_path_str))\n onlyfiles = top_level[2]\n abs_path = os.path.abspath(top_level[0])\n files = [os.path.join(abs_path, f) for f in onlyfiles]\n return files\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12346567/" ]
74,279,688
<p>I'm using Terraform to deploy Azure resources and now want to deploy across multiple regions.</p> <p>I'm finding even with Modules I'm repeating code, once for each region.</p> <p>How should I be writing code for multi region? I can't find any best practices</p>
[ { "answer_id": 74279804, "author": "Jason Lunder", "author_id": 17129046, "author_profile": "https://Stackoverflow.com/users/17129046", "pm_score": 2, "selected": true, "text": "from pathlib import Path\n\n\ndef get_files(inp_path_str):\n directory = Path(inp_path_str)\n only_files = [file.absolute() for file in directory.iterdir() if file.is_file()]\n return only_files\n" }, { "answer_id": 74279806, "author": "AirSquid", "author_id": 10789207, "author_profile": "https://Stackoverflow.com/users/10789207", "pm_score": 0, "selected": false, "text": "import os\n\ndef get_files(dir_path_str):\n top_level = next(os.walk(dir_path_str))\n onlyfiles = top_level[2]\n abs_path = os.path.abspath(top_level[0])\n files = [os.path.join(abs_path, f) for f in onlyfiles]\n return files\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10507547/" ]
74,279,709
<p>I am writing a program in Excel to compare PDF's when pasted into the file. I am trying to compare entries in cells of two worksheets and if there is a difference between any of the characters in the cells it should highlight that character red.</p> <p><a href="https://i.stack.imgur.com/MDUBn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MDUBn.png" alt="enter image description here" /></a></p> <p>I tried to loop down the worksheet and store each cell as a string and then convert each into an Array one at a time. The program would then loop through each element of the arrays and compare them and highlight each of the characters red if there was a difference between them.</p> <pre><code> Sub Standard_Solver() 'Code gets the amount of rows to loop through Dim rowsWithData1, rowsWithData, rowsToLoopTo As Integer rowsWithData1 = Worksheets(1).UsedRange.rows.Count rowsWithData2 = Worksheets(2).UsedRange.rows.Count If rowsWithData1 &lt; rowsWithData2 Then rowsToLoopTo = rowsWithData2 Else rowsToLoopTo = rowsWithData1 End If 'Loop to select each cell one by one and make their values a string Dim cell1, cell2, cell3, outst As String, range1, range2 As Range, stringToArray1, stringToArray2 As Variant For row = 1 To rowsToLoopTo Worksheets(1).Activate cell1 = Cells(row, 1).Value stringToArray1 = Array(cell1) Worksheets(2).Activate cell2 = Cells(row, 1).Value stringToArray2 = Array(cell2) 'What to do if the whole cell isn't equal If cell1 &lt;&gt; cell2 Then Dim charn As Integer If Len(cell1) &lt; Len(cell2) Then cell3 = Len(cell2) Else cell3 = Len(cell1) End If 'Comparing each character of each string For charn = 0 To cell3 'What to do if the two characters aren't equal 'Issue is that it is coloring the whole cell not the characters If stringToArray1(charn) &lt;&gt; stringToArray2(charn) Then Worksheets(1).Activate Cells(row, 1).Characters(charn).Font.ColorIndex = 3 Worksheets(2).Activate Cells(row, 1).Characters(charn).Font.ColorIndex = 3 'What to do if the two characters are equal Else End If Next charn 'If no differences do nothing and go to next row Else End If Next row End Sub </code></pre> <p>The problem is that upon running, it will color all of the characters in the first cell red and then have a runtime error. There may be a much simpler way to do this.</p>
[ { "answer_id": 74279804, "author": "Jason Lunder", "author_id": 17129046, "author_profile": "https://Stackoverflow.com/users/17129046", "pm_score": 2, "selected": true, "text": "from pathlib import Path\n\n\ndef get_files(inp_path_str):\n directory = Path(inp_path_str)\n only_files = [file.absolute() for file in directory.iterdir() if file.is_file()]\n return only_files\n" }, { "answer_id": 74279806, "author": "AirSquid", "author_id": 10789207, "author_profile": "https://Stackoverflow.com/users/10789207", "pm_score": 0, "selected": false, "text": "import os\n\ndef get_files(dir_path_str):\n top_level = next(os.walk(dir_path_str))\n onlyfiles = top_level[2]\n abs_path = os.path.abspath(top_level[0])\n files = [os.path.join(abs_path, f) for f in onlyfiles]\n return files\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18429589/" ]
74,279,764
<p>I have a long expression which may return a positive, negative or zero decimal value. I would like to do this:</p> <pre><code>SELECT CASE WHEN {long expression} &lt; 0 THEN 0 ELSE {long expression} END </code></pre> <p>But I don't want to repeat the long expression. I would like something like ISNULL, such as</p> <pre><code>SELECT ISNEGATIVE({long expression}, 0) </code></pre> <p>But that doesn't seem to be a thing. Obviously GREATER would work but it's 2017.</p> <p>I'm pretty sure I'm hosed, but was hoping for a miracle. Anyone?</p>
[ { "answer_id": 74279815, "author": "John Cappelletti", "author_id": 1570000, "author_profile": "https://Stackoverflow.com/users/1570000", "pm_score": 1, "selected": false, "text": "CROSS APPLY" }, { "answer_id": 74280289, "author": "Martin Smith", "author_id": 73226, "author_profile": "https://Stackoverflow.com/users/73226", "pm_score": 1, "selected": false, "text": "FORMAT" }, { "answer_id": 74281131, "author": "Ben Thul", "author_id": 568209, "author_profile": "https://Stackoverflow.com/users/568209", "pm_score": 0, "selected": false, "text": "with cte as (\n select *,\n longExpression = «long expression definition here»\n from yourTable\n)\nselect «other stuff»,\n CASE WHEN longExpression < 0 THEN 0 ELSE longExpression END\nfrom cte;\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8882016/" ]
74,279,784
<p>I was trying to <a href="https://stackoverflow.com/a/62366107/19595763">replicate this post,</a> in order to visualize the model, but now on a lmer model with a spline.</p> <pre><code>m9 &lt;- lmer(r ~ lspline(MINUTES, knots = c(5)) + ( 1 | ID) , data = dat ) summary(m9) df$pred &lt;- predict(m9, newdata=df) </code></pre> <p>Sadly, it seems it doesn't work.</p> <p>Is it possible to achieve the same result?</p> <p>data below:</p> <pre class="lang-r prettyprint-override"><code>dat &lt;- structure(list(r = c(61, 93, 92, 90, 88, 87, 85, 83, 105, 106, 107, 107, 107, 104, 87, 103, 96, 92, 88, 84, 84, 56, 87, 82, 82, 81, 82, 78, 74, 118, 115, 112, 108, 105, 102, 69, 81, 78, 73, 72, 70, 71, 88, 111, 104, 105, 104, 103, 97, 80, 99, 94, 96, 96, 92, 93, 76, 104, 100, 102, 100, 95, 95, 66, 91, 87, 83, 83, 80, 77, 90, 100, 95, 92, 90, 89, 84, 86, 91, 90, 89, 86, 88, 87, 64, 89, 85, 82, 80, 80, 77, 59, 86, 80, 78, 79, 79, 77, 82, 113, 110, 112, 109, 106, 110, 65, 93, 88, 87, 87, 84, 67, 87, 111, 102, 106, 103, 99, 99, 69, 97, 94, 92, 90, 88, 88, 75, 89, 84, 82, 80, 79, 77, 83, 103, 101, 98, 97, 96, 97, 73, 111, 90, 86, 100, 91, 95, 72, 102, 97, 96, 96, 97, 96, 71, 83, 84, 82, 84, 82, 83, 96, 93, 90, 89, 89, 95, 92, 117, 115, 112, 110, 111, 112, 63, 100, 95, 96, 93, 91, 92, 64, 74, 73, 71, 71, 70, 85, 67, 105, 103, 99, 96, 95, 98, 74, 105, 100, 102, 88, 99, 100, 54, 81, 78, 75, 80, 75, 77, 102, 112, 105, 102, 98, 95, 90, 79, 102, 99, 98, 92, 95, 90), MINUTES = c(0, 5, 10, 15, 20, 25, 30, 0, 5, 10, 15, 20, 25, 30, 0, 5, 10, 15, 20, 25, 30, 0, 5, 10, 15, 20, 25, 30, 0, 5, 10, 15, 20, 25, 30, 0, 5, 10, 15, 20, 25, 30, 0, 5, 10, 15, 20, 25, 30, 0, 5, 10, 15, 20, 25, 30, 0, 5, 10, 15, 20, 25, 30, 0, 5, 10, 15, 20, 25, 30, 0, 5, 10, 15, 20, 25, 30, 0, 5, 10, 15, 20, 25, 30, 0, 5, 10, 15, 20, 25, 30, 0, 5, 10, 15, 20, 25, 30, 0, 5, 10, 15, 20, 25, 30, 0, 5, 10, 15, 20, 25, 30, 0, 5, 10, 15, 20, 25, 30, 0, 5, 10, 15, 20, 25, 30, 0, 5, 10, 15, 20, 25, 30, 0, 5, 10, 15, 20, 25, 30, 0, 5, 10, 15, 20, 25, 30, 0, 5, 10, 15, 20, 25, 30, 0, 5, 10, 15, 20, 25, 30, 5, 10, 15, 20, 25, 30, 0, 5, 10, 15, 20, 25, 30, 0, 5, 10, 15, 20, 25, 30, 0, 5, 10, 15, 20, 25, 30, 0, 5, 10, 15, 20, 25, 30, 0, 5, 10, 15, 20, 25, 30, 0, 5, 10, 15, 20, 25, 30, 0, 5, 10, 15, 20, 25, 30, 0, 5, 10, 15, 20, 25, 30), ID = c(1, 1, 1, 1, 1, 1, 1, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 40, 40, 40, 40, 40, 40, 40, 41, 41, 41, 41, 41, 41, 41, 42, 42, 42, 42, 42, 42, 42, 43, 43, 43, 43, 43, 43, 43, 44, 44, 44, 44, 44, 44, 44, 45, 45, 45, 45, 45, 45, 45, 46, 46, 46, 46, 46, 46, 46, 49, 49, 49, 49, 49, 49, 49, 5, 5, 5, 5, 5, 5, 5, 52, 52, 52, 52, 52, 52, 52, 53, 53, 53, 53, 53, 53, 54, 54, 54, 54, 54, 54, 54, 55, 55, 55, 55, 55, 55, 55, 56, 56, 56, 56, 56, 56, 56, 57, 57, 57, 57, 57, 57, 57, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9)), row.names = c(8L, 9L, 10L, 11L, 12L, 13L, 14L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 36L, 37L, 38L, 39L, 40L, 41L, 42L, 43L, 44L, 45L, 46L, 47L, 48L, 49L, 50L, 51L, 52L, 53L, 54L, 55L, 56L, 64L, 65L, 66L, 67L, 68L, 69L, 70L, 78L, 79L, 80L, 81L, 82L, 83L, 84L, 85L, 86L, 87L, 88L, 89L, 90L, 91L, 99L, 100L, 101L, 102L, 103L, 104L, 105L, 106L, 107L, 108L, 109L, 110L, 111L, 112L, 120L, 121L, 122L, 123L, 124L, 125L, 126L, 134L, 135L, 136L, 137L, 138L, 139L, 140L, 148L, 149L, 150L, 151L, 152L, 153L, 154L, 155L, 156L, 157L, 158L, 159L, 160L, 161L, 162L, 163L, 164L, 165L, 166L, 167L, 168L, 169L, 170L, 171L, 172L, 173L, 174L, 175L, 176L, 177L, 178L, 179L, 180L, 181L, 182L, 183L, 184L, 185L, 186L, 187L, 188L, 189L, 190L, 191L, 192L, 193L, 194L, 195L, 196L, 197L, 198L, 199L, 200L, 201L, 202L, 203L, 204L, 205L, 206L, 207L, 208L, 209L, 210L, 218L, 219L, 220L, 221L, 222L, 223L, 224L, 225L, 226L, 227L, 228L, 229L, 230L, 231L, 232L, 233L, 234L, 235L, 236L, 237L, 238L, 239L, 240L, 241L, 242L, 243L, 244L, 245L, 246L, 247L, 248L, 249L, 250L, 251L, 252L, 253L, 254L, 255L, 256L, 257L, 258L, 259L, 260L, 261L, 262L, 263L, 264L, 265L, 273L, 274L, 275L, 276L, 277L, 278L, 279L, 287L, 288L, 289L, 290L, 291L, 292L, 293L, 294L, 295L, 296L, 297L, 298L, 299L, 300L, 308L, 309L, 310L, 311L, 312L, 313L, 314L), class = &quot;data.frame&quot;) </code></pre>
[ { "answer_id": 74279815, "author": "John Cappelletti", "author_id": 1570000, "author_profile": "https://Stackoverflow.com/users/1570000", "pm_score": 1, "selected": false, "text": "CROSS APPLY" }, { "answer_id": 74280289, "author": "Martin Smith", "author_id": 73226, "author_profile": "https://Stackoverflow.com/users/73226", "pm_score": 1, "selected": false, "text": "FORMAT" }, { "answer_id": 74281131, "author": "Ben Thul", "author_id": 568209, "author_profile": "https://Stackoverflow.com/users/568209", "pm_score": 0, "selected": false, "text": "with cte as (\n select *,\n longExpression = «long expression definition here»\n from yourTable\n)\nselect «other stuff»,\n CASE WHEN longExpression < 0 THEN 0 ELSE longExpression END\nfrom cte;\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19595763/" ]
74,279,790
<p>Given a function. for example:</p> <pre><code>suspend fun getUser(userId: Int): User? { val result: UserApiResult? = fetchTheApi(userId) //result != null || return null // Not smartcast if (result == null) return null // Will make an smartcast of result from UserApiResult? to UserApiResult return User(result.email, result.name) } </code></pre> <p>Inside my IDE, specifically Android Studio. The first condition won't perform a smartcast even though it visibly does the same thing as the second condition (unless it's doing some dark things under the hood).</p>
[ { "answer_id": 74279961, "author": "Marcus Dunn", "author_id": 12639399, "author_profile": "https://Stackoverflow.com/users/12639399", "pm_score": 2, "selected": false, "text": "result != null || return null" }, { "answer_id": 74280016, "author": "user2340612", "author_id": 2340612, "author_profile": "https://Stackoverflow.com/users/2340612", "pm_score": 3, "selected": true, "text": "fun returnSomething(): String? = null\n\nfun doSomething(): String? {\n val result: String? = returnSomething()\n\n result != null || return null\n\n return result.length.toString()\n}\n\nfun main() {\n println(doSomething())\n}\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12757722/" ]
74,279,798
<p>how to merge two dictonaries in python with union of values if the keys do exist in both. Each dictionary has values as list.</p> <p>I have three dictionaries:</p> <pre><code> d1 = {&quot;KEY1&quot;: [1, 2, 3]} d2 = {&quot;KEY1&quot;: [2, 3, 4]} d3 = {&quot;KEY2&quot;: [1, 2, 3]} </code></pre> <p>how could I merge then so if:</p> <pre><code> merge(d1,d2) --&gt; {&quot;KEY1&quot;: [1, 2, 3, 4]} merge(d1,d3) --&gt; {&quot;KEY1&quot;: [1, 2, 3],&quot;KEY2&quot;: [1, 2, 3]} </code></pre>
[ { "answer_id": 74279961, "author": "Marcus Dunn", "author_id": 12639399, "author_profile": "https://Stackoverflow.com/users/12639399", "pm_score": 2, "selected": false, "text": "result != null || return null" }, { "answer_id": 74280016, "author": "user2340612", "author_id": 2340612, "author_profile": "https://Stackoverflow.com/users/2340612", "pm_score": 3, "selected": true, "text": "fun returnSomething(): String? = null\n\nfun doSomething(): String? {\n val result: String? = returnSomething()\n\n result != null || return null\n\n return result.length.toString()\n}\n\nfun main() {\n println(doSomething())\n}\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6863010/" ]
74,279,830
<p>I'm trying to solve this problem in SQL Server. I need to get the customer's name when in the line there is the following condition:</p> <p>Start with any [letter]/[numbers][space][numbers][space]</p> <p>I used <code>[A-Z]/[0-9]%</code>, but I can't consider the space and the sequence of numbers followed by the other space</p> <p>Here's the line I'm working on:</p> <pre><code>K/31209536 9997530556 RICARDO JOSE DE OLIVEIRA QUEIROZ </code></pre> <p>When the condition is true, I need to get the name:</p> <pre><code>RICARDO JOSE DE OLIVEIRA QUEIROZ </code></pre>
[ { "answer_id": 74279990, "author": "Stuck at 1337", "author_id": 20091109, "author_profile": "https://Stackoverflow.com/users/20091109", "pm_score": 0, "selected": false, "text": "SELECT Original, ImportantPart = REVERSE([value]) \nFROM \n(\n SELECT Original = t.StringColumn,[key],[value]\n FROM dbo.YourTableName AS t \n CROSS APPLY OPENJSON('[\"' + REPLACE(\n REVERSE(LTRIM(RTRIM(t.StringColumn))), \n ' ', '\",\"') + '\"]')\n) AS j WHERE [key] = 0;\n" }, { "answer_id": 74280176, "author": "Yitzhak Khabinsky", "author_id": 1932311, "author_profile": "https://Stackoverflow.com/users/1932311", "pm_score": 1, "selected": false, "text": "-- DDL and sample data population, start\nDECLARE @tbl TABLE (StringColumn varchar(4000));\nINSERT @tbl VALUES\n('K/31209536 9997530556 RICARDO JOSE DE OLIVEIRA QUEIROZ');\n-- DDL and sample data population, end\n\nDECLARE @separator CHAR(2) = SPACE(2);\n\nSELECT t.*\n , c.value('(/root/r[last()]/text())[1]', 'VARCHAR(150)') AS Result\nFROM @tbl AS t\nCROSS APPLY (SELECT TRY_CAST('<root><r><![CDATA[' + \n REPLACE(StringColumn, @separator, ']]></r><r><![CDATA[') + \n ']]></r></root>' AS XML)) AS t1(c);\n" }, { "answer_id": 74280243, "author": "John Cappelletti", "author_id": 1570000, "author_profile": "https://Stackoverflow.com/users/1570000", "pm_score": 0, "selected": false, "text": "Select CustName = case when patindex('[A-Z]/[0-9][0-9][0-9]%',SomeCol)>0\n then right(SomeCol,charindex(' ',reverse(SomeCol))-1)\n end\n From YourTable\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14823459/" ]
74,279,870
<p>I can understand first output of first example, that is 2 as the i += 1 makes value to 2 than print calls, I also understand the second example's first output that is 1 because print calls i then increment begins. But, what about the end, as we have already defined &quot;while i &lt; 6:&quot; then why first example returns last output as 6 (why don't it breaks to 5) I'm a beginner so treat me like a kid and write the answer that is easy to understand. Thank you! :)</p> <pre><code>i = 1 while i &lt; 6: i += 1 print(i) # Print output after i increment, see the result &gt;&gt; The output is - 2 3 4 5 6 i = 1 while i &lt; 6: print(i) # Print output before i increment, see the result i += 1 &gt;&gt; The output is - 1 2 3 4 5 </code></pre> <p>I was expecting the output should be limited to 5 but it returns to 6 (in first example)</p>
[ { "answer_id": 74279945, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 1, "selected": false, "text": "while" }, { "answer_id": 74280015, "author": "Kungfu panda", "author_id": 15349625, "author_profile": "https://Stackoverflow.com/users/15349625", "pm_score": 0, "selected": false, "text": "i = 1\nwhile i < 6:# initially i value is 1.\n i += 1 # here you are incrementing. i value becomes 2.\n print(i) # print starts from 2 \n\nin the last check i value becomes 5 then it increments to 6 and prints.\nso the output starts from 2 and goes till 6.\n>> The output is -\n2\n3\n4\n5\n6\n\ni = 1\nwhile i < 6:\n print(i) # Print output before i increment, see the result\n i += 1\n\nhere you print the i value first and increment later .\nyou print the i value first \ninitially 1\nthen you print it . then you are incrementing it.\nin the final check 5<6. it prints 5 and in the next increment as i value equals to 6. the while statement becomes false.\n>> The output is -\n1\n2\n3\n4\n5\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19504766/" ]
74,279,873
<p>My question was inspired by <a href="https://stackoverflow.com/q/74267193/11732320">this post</a> in that I'm wondering if it's possible to create a formula to stack a dynamic amount of arrays based on a list (see below for clarification).</p> <h2>Sample Starting Data From Three Sources</h2> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Amount</th> </tr> </thead> <tbody> <tr> <td>India</td> <td>9</td> </tr> <tr> <td>Delta</td> <td>4</td> </tr> <tr> <td>Hotel</td> <td>8</td> </tr> </tbody> </table> </div><div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Amount</th> </tr> </thead> <tbody> <tr> <td>Alpha</td> <td>1</td> </tr> <tr> <td>Echo</td> <td>5</td> </tr> <tr> <td>Foxtrot</td> <td>6</td> </tr> </tbody> </table> </div><div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Amount</th> </tr> </thead> <tbody> <tr> <td>Bravo</td> <td>2</td> </tr> <tr> <td>Gulf</td> <td>7</td> </tr> <tr> <td>Charlie</td> <td>3</td> </tr> </tbody> </table> </div><h2>Desired final result:</h2> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Amount</th> </tr> </thead> <tbody> <tr> <td>Alpha</td> <td>1</td> </tr> <tr> <td>Bravo</td> <td>2</td> </tr> <tr> <td>Charlie</td> <td>3</td> </tr> <tr> <td>Delta</td> <td>4</td> </tr> <tr> <td>Echo</td> <td>5</td> </tr> <tr> <td>Foxtrot</td> <td>6</td> </tr> <tr> <td>Gulf</td> <td>7</td> </tr> <tr> <td>Hotel</td> <td>8</td> </tr> <tr> <td>India</td> <td>9</td> </tr> </tbody> </table> </div> <p>I can get the final result by using a query function as shown <a href="https://docs.google.com/spreadsheets/d/1ovuh1bpjAQWp5b_J3wuNclkt0ycBXpYsEMXQi4e35YA/edit?usp=sharing" rel="nofollow noreferrer">in this spreadsheet</a> with a formula referencing the appropriate cells with <code>fileID</code> and <code>range</code>:</p> <pre><code>=Query({IMPORTRANGE(E2,F2); IMPORTRANGE(E3,F3); IMPORTRANGE(E4,F4)},&quot;Select * where Col1 is not null order by Col1&quot;,1) </code></pre> <p>if you want to play with it in your own sheet, you could use this hard-coded function which is the same as above:</p> <pre><code>=Query({IMPORTRANGE(&quot;1WtI56_9mhyArMn_j_H4pZg8E0QdIBaKoJfAr-fDAoE0&quot;,&quot;'Sheet1'!A:B&quot;); IMPORTRANGE(&quot;1HamomAuLtwKJiFEtRKTuEkt--YDTtWChUavetBcAcBA&quot;,&quot;'Sheet1'!A2:B&quot;); IMPORTRANGE(&quot;1WtI56_9mhyArMn_j_H4pZg8E0QdIBaKoJfAr-fDAoE0&quot;,&quot;'Sheet2'!A2:B&quot;)},&quot;Select * where Col1 is not null order by Col1&quot;,1) </code></pre> <p><a href="https://i.stack.imgur.com/Uo4no.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Uo4no.png" alt="enter image description here" /></a></p> <h2>My Question:</h2> <p>Is there a way to leverage a formula to generate this result based on the number of file ids and ranges in columns <code>E</code> and <code>F</code>? So if a fourth <code>ID</code> and range were added, the desired result in columns <code>a</code> and <code>b</code> would be shown? I suspect Lambda would work, but I am not as strong with it as I should be.</p> <p><strong>Unsuccessful attempt:</strong></p> <p><code>=lambda(someIDs,SomeRanges,IMPORTRANGE(someIds,SomeRanges))(filter(E2:E,E2:E&lt;&gt;&quot;&quot;),filter(F2:F,F2:F&lt;&gt;&quot;&quot;))</code></p> <p><strong><em>REALLY</em> Bad Attempts:</strong></p> <p><code>=contact(Player()*1800-CoffeeBribe*Not(Home))</code></p> <p><code>=company(theMaster(emailed)*(false))&lt;&gt;</code></p> <p>All helpful answers will be upvoted if not accepted. Thanks.</p>
[ { "answer_id": 74279945, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 1, "selected": false, "text": "while" }, { "answer_id": 74280015, "author": "Kungfu panda", "author_id": 15349625, "author_profile": "https://Stackoverflow.com/users/15349625", "pm_score": 0, "selected": false, "text": "i = 1\nwhile i < 6:# initially i value is 1.\n i += 1 # here you are incrementing. i value becomes 2.\n print(i) # print starts from 2 \n\nin the last check i value becomes 5 then it increments to 6 and prints.\nso the output starts from 2 and goes till 6.\n>> The output is -\n2\n3\n4\n5\n6\n\ni = 1\nwhile i < 6:\n print(i) # Print output before i increment, see the result\n i += 1\n\nhere you print the i value first and increment later .\nyou print the i value first \ninitially 1\nthen you print it . then you are incrementing it.\nin the final check 5<6. it prints 5 and in the next increment as i value equals to 6. the while statement becomes false.\n>> The output is -\n1\n2\n3\n4\n5\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11732320/" ]
74,279,885
<p>Good afternoon, trying to output a random list item from this code</p> <pre><code>global anekdot def randanek(): anekdot = random.choice(anekdots) randanek() textaneka = anekdot </code></pre> <p>but for some reason the program doesn't see my variable and i see this error</p> <pre><code>Traceback (most recent call last): File &quot;&quot;, line 44, in &lt;module&gt; textaneka = anekdot NameError: name 'anekdot' is not defined. Did you mean: 'anekdots'? [Finished in 113ms with exit code 1] [cmd: ['python3', '-u', '']] [dir: /] [path: /] </code></pre> <p>i try to use different variable</p>
[ { "answer_id": 74280003, "author": "Anentropic", "author_id": 202168, "author_profile": "https://Stackoverflow.com/users/202168", "pm_score": 0, "selected": false, "text": "anekdots = [\n \"anekdot 1 blah blah blah\",\n \"anekdot 2 blah blah blah\",\n # etc\n]\n\n\ndef randanek():\n return random.choice(anekdots)\n\n\ntextaneka = randanek()\n" }, { "answer_id": 74280005, "author": "Vincent Rupp", "author_id": 4024409, "author_profile": "https://Stackoverflow.com/users/4024409", "pm_score": 1, "selected": false, "text": "texaneka = anekdot" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20390448/" ]
74,279,897
<p>In the following code, why does it take 10(0+1+2+3+4) seconds to finish, instead of 4 seconds, when I'm using asyncio?</p> <pre><code>import asyncio,time async def say_after(delay, what): await asyncio.sleep(delay) print(f&quot;what = {what}, at {time.strftime('%X')}&quot;) background_tasks = set() async def main(): for i in range(5): task = asyncio.create_task(say_after(delay=i,what=i)) # Add task to the set. This creates a strong reference. background_tasks.add(task) await task # To prevent keeping references to finished tasks forever, # make each task remove its own reference from the set after # completion: task.add_done_callback(background_tasks.discard) # discard is a set method. if __name__==&quot;__main__&quot;: asyncio.run(main()) </code></pre> <p>The result is in the picture.</p> <p><a href="https://i.stack.imgur.com/UHVy5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UHVy5.png" alt="enter image description here" /></a></p> <p>Edit: I'm following <a href="https://docs.python.org/3/library/asyncio-task.html#creating-tasks" rel="nofollow noreferrer">this official documentation</a></p>
[ { "answer_id": 74279977, "author": "mlokos", "author_id": 19570235, "author_profile": "https://Stackoverflow.com/users/19570235", "pm_score": -1, "selected": false, "text": "import asyncio,time\n\nasync def say_after(delay, what):\n await asyncio.sleep(delay)\n print(f\"what = {what}, at {time.strftime('%X')}\")\n\n\nbackground_tasks = set()\n\nasync def main():\n for i in range(5):\n task = asyncio.create_task(say_after(delay=i,what=i))\n \n # Add task to the set. This creates a strong reference.\n background_tasks.add(task)\n \n await task\n \n # To prevent keeping references to finished tasks forever,\n # make each task remove its own reference from the set after\n # completion:\n task.add_done_callback(background_tasks.discard) # discard is a set method.\n \nif __name__==\"__main__\":\n asyncio.run(main())\n" }, { "answer_id": 74284689, "author": "Artyom Vancyan", "author_id": 12755187, "author_profile": "https://Stackoverflow.com/users/12755187", "pm_score": 1, "selected": true, "text": "background_tasks" }, { "answer_id": 74293922, "author": "An old man in the sea.", "author_id": 3482266, "author_profile": "https://Stackoverflow.com/users/3482266", "pm_score": 0, "selected": false, "text": "import asyncio,time\n\nasync def say_after(delay, what):\n await asyncio.sleep(delay)\n print(f\"what = {what}, at {time.strftime('%X')}\")\n\n\nbackground_tasks = set()\n\nasync def main():\n for i in range(5):\n task = asyncio.create_task(say_after(delay=i,what=i))\n \n # Add task to the set. This creates a strong reference.\n background_tasks.add(task)\n # To prevent keeping references to finished tasks forever,\n # make each task remove its own reference from the set after\n # completion:\n task.add_done_callback(background_tasks.discard) # discard is a set method.\n\n while len(background_tasks)!=0:\n await task\n \nif __name__==\"__main__\":\n asyncio.run(main())\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3482266/" ]
74,279,899
<pre class="lang-xml prettyprint-override"><code>&lt;tac id=&quot;10&quot; name=&quot;KD&amp;#11;#36&quot;&gt; </code></pre> <p>I have a program that saves in xml (using Java). But after saving this line, the xml cannot be loaded anymore (SAX Parser). Do I need to change the xml header to something else than UTF-8, if yes, to what?</p>
[ { "answer_id": 74301793, "author": "nwellnhof", "author_id": 1956010, "author_profile": "https://Stackoverflow.com/users/1956010", "pm_score": 3, "selected": true, "text": "&#11;" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1832373/" ]
74,279,913
<p>I am trying to create a cumulative count for unique customers only by the month they purchased. The example Table is:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>customer_email</th> <th>cohortMonth</th> </tr> </thead> <tbody> <tr> <td>abc@gmail.com</td> <td>10/2019</td> </tr> <tr> <td>def@gmail.com</td> <td>10/2019</td> </tr> <tr> <td>ghi@gmail.com</td> <td>10/2019</td> </tr> <tr> <td>def@gmail.com</td> <td>11/2019</td> </tr> <tr> <td>jkl@gmail.com</td> <td>11/2019</td> </tr> <tr> <td>def@gmail.com</td> <td>12/2019</td> </tr> </tbody> </table> </div> <p>The output I am looking for is the total Customers for 10/2019 would be 3, The cumulative total customers for 11/2019 would be 4 taking all of the customers purchased in 10/2019 and adding jkl@gmail.com as this is the only Unique customer email for the month. The cumulative total customers for 12/2019 will still be 4 as no new customers purchased in this month.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>cohortMonth</th> <th>cumulative_total_customers</th> </tr> </thead> <tbody> <tr> <td>10/2019</td> <td>3</td> </tr> <tr> <td>11/2019</td> <td>4</td> </tr> <tr> <td>12/2019</td> <td>4</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74301793, "author": "nwellnhof", "author_id": 1956010, "author_profile": "https://Stackoverflow.com/users/1956010", "pm_score": 3, "selected": true, "text": "&#11;" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5806469/" ]
74,279,932
<p>Let's say I have a list of items like below and I would like to apply a list of filters onto it with ramda.</p> <pre class="lang-js prettyprint-override"><code>const data = [ {id: 1, name: &quot;Andreas&quot;}, {id: 2, name: &quot;Antonio&quot;}, {id: 3, name: &quot;Bernhard&quot;}, {id: 4, name: &quot;Carlos&quot;} ] </code></pre> <p>No biggie: pipe(filter(predA), filter(predB), ...)(data)</p> <p>The tricky part is I would like to define my filters with a key for tracking what items have been filtered out by which filter.</p> <pre class="lang-js prettyprint-override"><code>const filterBy = (key, pred) =&gt; subs =&gt; { const [res, rej] = partition(pred, subs) return [{[key]: rej.map(prop('id'))}, res] } </code></pre> <p>This all screams monad chaining or a transducer, but I can't get my head around it how to put it all together.</p> <p>Let's say I have a 2 predicates:</p> <pre class="lang-js prettyprint-override"><code>const isEven = filterBy('id', i =&gt; i % 2 === 0) const startsWithA = filterBy('name', startsWith('A')) </code></pre> <p>I would like to get a result that looks like this tuple with a rejection map and a list of &quot;accepted&quot; items (isEven threw out 1 and 3 and startsWithA rejected 3 and 4):</p> <pre class="lang-js prettyprint-override"><code>[ { id: [1, 3], name: [3, 4] }, [{id: 2, name: &quot;Antonio&quot;}] ] </code></pre>
[ { "answer_id": 74282791, "author": "Scott Sauyet", "author_id": 1243641, "author_profile": "https://Stackoverflow.com/users/1243641", "pm_score": 2, "selected": true, "text": "const nameTooLong = ({name}) => name .length < 8" }, { "answer_id": 74319806, "author": "Andreas Herd", "author_id": 4773272, "author_profile": "https://Stackoverflow.com/users/4773272", "pm_score": 0, "selected": false, "text": "class Partition extends Array {\n constructor(items, filtered = {}) {\n super(...items)\n this.filtered = filtered\n }\n\n filterWithKey = (key, pred) => {\n const [ok, notOk] = partition(pred, this.slice())\n const filtered = mergeDeepWith(concat, this.filtered, {[key]: notOk})\n return new Partition(ok, filtered)\n }\n\n filter = pred => this.filterWithKey(\"\", pred)\n}\n\nconst res = new Partition([\n {id: 1, name: \"Andreas\"},\n {id: 2, name: \"Antonio\"},\n {id: 3, name: \"Bernhard\"},\n {id: 4, name: \"Carlos\"}\n])\n .filterWithKey('id', ({id}) => id % 2 === 0)\n .filterWithKey('name', ({name}) => name.startsWith('A'))\n\nconst toIds = map(prop('id'))\nconst rejected = map(toIds, res.filtered)\nconst accepted = [...res]\n\nconsole.log(rejected, accepted)\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4773272/" ]
74,279,938
<p>I am running a Flask server and I have the following problem.</p> <p>When an user login in, a <code>Selenium webdriver</code> is initialized and performs some task. It store some cookies and then it communicates with frontend (I can't control WHEN it will save the cookies and I cannot close it with <code>driver.close()</code>. After this I need to start again the <code>chromedriver</code> but preserving the cookies (I'm using <code>User dir</code> for this reason and this works).</p> <p>The problem is that the second time I start the <code>webdriver</code> I get error because the previous one is not closed. How can I close it before starting a new one, using Python?</p> <p>Thanks!</p> <p>I expect to close all the active <code>chromedriver</code> sessions without using Selenium (I cannot use it), but using Python.</p>
[ { "answer_id": 74280047, "author": "LucasBorges-Santos", "author_id": 16464891, "author_profile": "https://Stackoverflow.com/users/16464891", "pm_score": 0, "selected": false, "text": " content_cookies = {\n 'name': <NAME_VARIABLE_COOKIE>,\n 'domain': '<URLSITE>',\n 'value': str(<VALUE_VARIABLE_COOKIE>)\n }\n driver.add_cookie(content_cookies)\n" }, { "answer_id": 74280184, "author": "PApostol", "author_id": 12881844, "author_profile": "https://Stackoverflow.com/users/12881844", "pm_score": 2, "selected": true, "text": "driver.quit()" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20390605/" ]
74,279,944
<p>I'm trying to create a deep copy of object but the complier is throwing this error<a href="https://i.stack.imgur.com/ZZ3yn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZZ3yn.png" alt="enter image description here" /></a></p> <p>As I'm beginner in C# and want to grip over these concepts of oop so your valuble answer explaining this concept would be highly appreciated</p>
[ { "answer_id": 74280014, "author": "Sabre", "author_id": 999897, "author_profile": "https://Stackoverflow.com/users/999897", "pm_score": 1, "selected": false, "text": "namespace ConsoleApp1\n{\n internal class Class1\n {\n\n public Class1()\n {\n\n }\n\n public Class1(int input)\n {\n\n }\n }\n}\n" }, { "answer_id": 74280018, "author": "cemahseri", "author_id": 10189024, "author_profile": "https://Stackoverflow.com/users/10189024", "pm_score": 0, "selected": false, "text": "public class Quadratic\n{\n public int A { get; set; }\n public int B { get; set; }\n public int C { get; set; }\n\n public Quadratic()\n {\n }\n\n public Quadratic(Quadratic quadraticToCopy)\n {\n A = quadraticToCopy.A;\n B = quadraticToCopy.B;\n C = quadraticToCopy.C;\n }\n\n public Quadratic CreateDeepCopy1() => new Quadratic(this);\n public Quadratic CreateDeepCopy2() => (Quadratic)this.MemberwiseClone();\n}\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19502523/" ]
74,279,971
<p>Hello Stackoverflow community,</p> <p>I am dealing with a VBA issue my code below works but I am running into the issue that this portion of the code &quot;MATCH('Worksheets1'!$D2,&quot; is not changing or updating based on the the row it is at for example if my worksheet contains 2000 rows that need to be index matched the formula will still just contain MATCH('Worksheets1'!$D2 as the cell it is referencing was wondering if anyone knows how to make the cell value change based on what what row number the code is at.</p> <pre><code>Sub trial() On Error Resume Next Dim Dept_Row As Long Dim Dept_Clm As Long Table1 = Worksheets1.Range(&quot;D:D&quot;) Table2 = Worksheets2.Range(&quot;A:B&quot;) Dept_Row = Worksheets1.Range(&quot;A2&quot;).Row Dept_Clm = Worksheets1.Range(&quot;A2&quot;).Column For Each cl In Table1 If IsEmpty(cl) Then Exit Sub If Not IsEmpty(cl) Then Worksheets(&quot;Worksheets1&quot;).Cells(Dept_Row, Dept_Clm) = _ &quot;=INDEX('Worksheets2'!$B:$B,MATCH('Worksheets1'!$D2,'Worksheets2'!A:A,0)) &quot; Dept_Row = Dept_Row + 1 Next cl Exit Sub </code></pre> <p>I created the loop in hopes of the formula updating giving it the</p> <p>Dept_Row = Dept_Row + 1.</p> <p>I tried both leaving it where it is currently at and introducing the code to quotation marks after the formula ended. However, my code is only able to run how the current code is. I was thinking of doing Plus 1 but I doubted that would work it would just turn the cell value of D2 into D3 for all.</p> <p>Any advice would be greatly appreciated it.</p> <p>Thank you</p>
[ { "answer_id": 74280630, "author": "findwindow", "author_id": 4971065, "author_profile": "https://Stackoverflow.com/users/4971065", "pm_score": 0, "selected": false, "text": "\"=INDEX('Worksheets2'!$B:$B,MATCH('Worksheets1'!$D\" & Dept_Row & \"'Worksheets2'!A:A,0))\"\n" }, { "answer_id": 74280809, "author": "BigBen", "author_id": 9245853, "author_profile": "https://Stackoverflow.com/users/9245853", "pm_score": 2, "selected": false, "text": "With Worksheets(\"worksheet1\")\n Dim lastRow As Long\n lastRow = .Range(\"D\" & .Rows.Count).End(xlUp).Row\n \n .Range(\"A2:A\" & lastRow).Formula = \"=INDEX('Worksheets2'!$B:$B,MATCH(D2,'Worksheets2'!A:A,0))\"\nEnd With\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17648731/" ]
74,279,976
<p>I am trying to create a common HTTP request validator middleware function that accepts type (maybe reflect.Type) as an argument and then using the package <code>github.com/go-playground/validator/v10</code> to be able to unmarshall JSON into struct of mentioned type and validate the struct. I've tried to explain with the following example code...</p> <p>EXAMPLE</p> <pre class="lang-golang prettyprint-override"><code>type LoginRequestBody struct { Username string `json:&quot;username&quot;,validate:&quot;required&quot;` Password string `json:&quot;password&quot;,validate:&quot;required&quot;` } type SignupReqBody struct { Username string `json:&quot;username&quot;,validate:&quot;required&quot;` Password string `json:&quot;password&quot;,validate:&quot;required&quot;` Age int `json:&quot;age&quot;,validate:&quot;required&quot;` } // sample routers with a common middleware validator function router.POST(&quot;/login&quot;, ReqValidate(&quot;LoginRequestBody&quot;), LoginController) router.POST(&quot;/signup&quot;, ReqValidate(&quot;SignupReqBody&quot;), SignupController) func ReqValidate(&lt;something&gt;) gin.HandlerFunc { return func (c *gin.Context) { // unmarshalling JSON into a struct // common validation logic... c.Next() } } </code></pre> <p>Overall, i wanna achieve the same validator flexibility as there in Node.js using Joi package.</p>
[ { "answer_id": 74280198, "author": "Juanes30", "author_id": 5270947, "author_profile": "https://Stackoverflow.com/users/5270947", "pm_score": 3, "selected": true, "text": "package main\nimport (\n \"github.com/gin-gonic/gin\"\n \"net/http\"\n)\ntype AnyStruct struct {\n Price uint `json:\"price\" binding:\"required,gte=10,lte=1000\"`\n}\nfunc main() {\n engine:=gin.New()\n engine.POST(\"/test\", func(context *gin.Context) {\n body:=AnyStruct{}\n if err:=context.ShouldBindJSON(&body);err!=nil{\n context.AbortWithStatusJSON(http.StatusBadRequest,\n gin.H{\n \"error\": \"VALIDATEERR-1\",\n \"message\": \"Invalid inputs. Please check your inputs\"})\n return\n }\n context.JSON(http.StatusAccepted,&body)\n })\n engine.Run(\":3000\")\n}\n" }, { "answer_id": 74280299, "author": "mkopriva", "author_id": 965900, "author_profile": "https://Stackoverflow.com/users/965900", "pm_score": 1, "selected": false, "text": "<something>" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5723295/" ]
74,279,978
<p>I am trying to filter my dataframe such that when I create a new columnoutput, it displays the &quot;medium&quot; rating. My dataframe has str values, so I convert them to numbers based on a ranking system I have and then I filter out the maximum and minimum rating per row.</p> <p>I am running into this error:</p> <pre><code>TypeError: unsupported operand type(s) for &amp;: 'str' and 'bool' </code></pre> <p>I've created a data frame that pulls str values from my csv file:</p> <pre><code>df = pdf.read_csv('csv path', usecols=['rating1','rating2','rating3']) </code></pre> <p>And my dataframe looks like this:</p> <pre><code> rating1 rating2 rating3 0 D D C 1 C B A 2 B B B </code></pre> <p>I need it to look like this</p> <pre><code> rating1 rating2 rating3 mediumrating 0 D D C 1 1 C B A 3 2 B B B 3 </code></pre> <p>I have a mapping dictionary that converts the values to numbers.</p> <pre><code>ranking = { 'D': 1, 'C':2, 'B': 3, 'A' : 4 } </code></pre> <p>Below you can find the code I use to determine the &quot;medium rating&quot;. Basically, if all the ratings are the same, you can pull the minimum rating. If two of the ratings are the same, pull in the lowest rating. If the three ratings differ, filter out the max rating and the min rating.</p> <pre><code>if df == df.loc[(['rating1'] == df['rating2'] &amp; df['rating1'] == df['rating3'])]: df['mediumrating'] = df.replace(ranking).min(axis=1) elif df == df.loc[(['rating1'] == df['rating2'] | df['rating1'] == df['rating3'] | df['rating2'] == df['rating3'])]: df['mediumrating'] = df.replace(ranking).min(axis=1) else: df['mediumrating'] == df.loc[(df.replace(ranking) &gt; df.replace(ranking).min(axis=1) &amp; df.replace(ranking) </code></pre> <p>Any help on my formatting or process would be welcomed!!</p>
[ { "answer_id": 74280198, "author": "Juanes30", "author_id": 5270947, "author_profile": "https://Stackoverflow.com/users/5270947", "pm_score": 3, "selected": true, "text": "package main\nimport (\n \"github.com/gin-gonic/gin\"\n \"net/http\"\n)\ntype AnyStruct struct {\n Price uint `json:\"price\" binding:\"required,gte=10,lte=1000\"`\n}\nfunc main() {\n engine:=gin.New()\n engine.POST(\"/test\", func(context *gin.Context) {\n body:=AnyStruct{}\n if err:=context.ShouldBindJSON(&body);err!=nil{\n context.AbortWithStatusJSON(http.StatusBadRequest,\n gin.H{\n \"error\": \"VALIDATEERR-1\",\n \"message\": \"Invalid inputs. Please check your inputs\"})\n return\n }\n context.JSON(http.StatusAccepted,&body)\n })\n engine.Run(\":3000\")\n}\n" }, { "answer_id": 74280299, "author": "mkopriva", "author_id": 965900, "author_profile": "https://Stackoverflow.com/users/965900", "pm_score": 1, "selected": false, "text": "<something>" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74279978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16633745/" ]
74,280,008
<p>I am using the sub function to define a resource within an aws IAM service.</p> <pre><code>Resource: - !Sub 'arn:aws:s3:::example-${TEST1}-${AWS::REGION}-test' </code></pre> <p>${TEST1}: it is an environment variable that I have in my java project.</p> <p>${AWS::REGION}: pseudo parameter</p> <p>I want to know if !sub is able to read the environment variable and if it can't, is there any way I can do it even if it's not with this function</p>
[ { "answer_id": 74280198, "author": "Juanes30", "author_id": 5270947, "author_profile": "https://Stackoverflow.com/users/5270947", "pm_score": 3, "selected": true, "text": "package main\nimport (\n \"github.com/gin-gonic/gin\"\n \"net/http\"\n)\ntype AnyStruct struct {\n Price uint `json:\"price\" binding:\"required,gte=10,lte=1000\"`\n}\nfunc main() {\n engine:=gin.New()\n engine.POST(\"/test\", func(context *gin.Context) {\n body:=AnyStruct{}\n if err:=context.ShouldBindJSON(&body);err!=nil{\n context.AbortWithStatusJSON(http.StatusBadRequest,\n gin.H{\n \"error\": \"VALIDATEERR-1\",\n \"message\": \"Invalid inputs. Please check your inputs\"})\n return\n }\n context.JSON(http.StatusAccepted,&body)\n })\n engine.Run(\":3000\")\n}\n" }, { "answer_id": 74280299, "author": "mkopriva", "author_id": 965900, "author_profile": "https://Stackoverflow.com/users/965900", "pm_score": 1, "selected": false, "text": "<something>" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19882964/" ]
74,280,048
<p>I have a React form where I can't control the value of the checkbox input with the useState hook. I don't have this problem with other inputs.</p> <p>I can't pass the checkbox input value to the AuthData object. When you click the &quot;Sign in&quot; button, the console should display an AuthData object with the fields { login: '', password: '', isRemember: '' }</p> <pre><code>import React from 'react' import { useState } from 'react' export const AuthForm = ({ handlers }) =&gt; { const [authData, setAuthData] = useState({ login: '', password: '', isRemember: '' }) const changeValue = (event) =&gt; { const { id, value } = event.target setAuthData((prevAuthData) =&gt; ({ ...prevAuthData, [id]: value })) } const signIn = () =&gt; { console.log(authData) } return ( &lt;form onSubmit={(e) =&gt; e.preventDefault()}&gt; &lt;input type=&quot;text&quot; id=&quot;login&quot; placeholder=&quot;Login/E-mail/Phone&quot; value={authData.login} onChange={changeValue} /&gt; &lt;input type=&quot;password&quot; id=&quot;password&quot; placeholder=&quot;Password&quot; value={authData.password} onChange={changeValue} /&gt; &lt;input type=&quot;checkbox&quot; id=&quot;isRemember&quot; value={authData.isRemember} onChange={changeValue} /&gt; &lt;button onClick={signIn}&gt;Sign in&lt;/button&gt; &lt;/form&gt; ) } </code></pre> <p>When you change inputs values, their values must be passed to the authValue object. With &quot;login&quot; and &quot;password&quot; inputs their values go into the authValue object, but with &quot;isRemember&quot; input this does not work. The value of checkbox inputs somehow does not get into the authValue object.</p>
[ { "answer_id": 74280198, "author": "Juanes30", "author_id": 5270947, "author_profile": "https://Stackoverflow.com/users/5270947", "pm_score": 3, "selected": true, "text": "package main\nimport (\n \"github.com/gin-gonic/gin\"\n \"net/http\"\n)\ntype AnyStruct struct {\n Price uint `json:\"price\" binding:\"required,gte=10,lte=1000\"`\n}\nfunc main() {\n engine:=gin.New()\n engine.POST(\"/test\", func(context *gin.Context) {\n body:=AnyStruct{}\n if err:=context.ShouldBindJSON(&body);err!=nil{\n context.AbortWithStatusJSON(http.StatusBadRequest,\n gin.H{\n \"error\": \"VALIDATEERR-1\",\n \"message\": \"Invalid inputs. Please check your inputs\"})\n return\n }\n context.JSON(http.StatusAccepted,&body)\n })\n engine.Run(\":3000\")\n}\n" }, { "answer_id": 74280299, "author": "mkopriva", "author_id": 965900, "author_profile": "https://Stackoverflow.com/users/965900", "pm_score": 1, "selected": false, "text": "<something>" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13853949/" ]
74,280,066
<p>I'm trying to migrate an enterprise app (can't share code) from Create React App to NextJS (with TypeScript).</p> <p>I've been able to replace the React Router with Next Routes/Pages, but I'm encountering this error message every time I try to build the app:</p> <pre><code>Error occurred prerendering page &quot;/&quot;. Read more: https://nextjs.org/docs/messages/prerender-error ReferenceError: window is not defined </code></pre> <p>I've gone into the code and, everywhere that window appears, wrapped that code in an if check (<code>if(typeof window !== 'undefined')</code>). But I am still getting this error.</p> <p>Is there any advice on how best to track down window references and make them NextJS compliant? Any &quot;gotchas&quot; that other folks have experienced?</p> <p>I've gone into the code and, everywhere that window appears, wrapped that code in an if check (<code>if(typeof window !== 'undefined')</code>). But I am still getting this error.</p>
[ { "answer_id": 74280198, "author": "Juanes30", "author_id": 5270947, "author_profile": "https://Stackoverflow.com/users/5270947", "pm_score": 3, "selected": true, "text": "package main\nimport (\n \"github.com/gin-gonic/gin\"\n \"net/http\"\n)\ntype AnyStruct struct {\n Price uint `json:\"price\" binding:\"required,gte=10,lte=1000\"`\n}\nfunc main() {\n engine:=gin.New()\n engine.POST(\"/test\", func(context *gin.Context) {\n body:=AnyStruct{}\n if err:=context.ShouldBindJSON(&body);err!=nil{\n context.AbortWithStatusJSON(http.StatusBadRequest,\n gin.H{\n \"error\": \"VALIDATEERR-1\",\n \"message\": \"Invalid inputs. Please check your inputs\"})\n return\n }\n context.JSON(http.StatusAccepted,&body)\n })\n engine.Run(\":3000\")\n}\n" }, { "answer_id": 74280299, "author": "mkopriva", "author_id": 965900, "author_profile": "https://Stackoverflow.com/users/965900", "pm_score": 1, "selected": false, "text": "<something>" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3632712/" ]
74,280,099
<pre><code>iLig1, iCol1 , iLig2 , iCol2 , carac = map(int, input ().split ()) </code></pre> <p>hello I try to get this ligne of input in my code right, I get 5 variables from an input that look like this:</p> <pre><code>1 12 7 14 u </code></pre> <p>how can I declare the last one as a str properly, I tried to consider them all as str and convert the 4 first as int but I cannot interpret str as int (you know..)</p> <p>Thank you for your help !</p>
[ { "answer_id": 74280159, "author": "I'mahdi", "author_id": 1740577, "author_profile": "https://Stackoverflow.com/users/1740577", "pm_score": 3, "selected": true, "text": "(*)" }, { "answer_id": 74280179, "author": "Scott Hunter", "author_id": 535275, "author_profile": "https://Stackoverflow.com/users/535275", "pm_score": 2, "selected": false, "text": "iLig1, iCol1 , iLig2 , iCol2 , carac = [int(x) if i<4 else x for i,x in enumerate(input ().split ())]\n" }, { "answer_id": 74280247, "author": "jvx8ss", "author_id": 11107859, "author_profile": "https://Stackoverflow.com/users/11107859", "pm_score": 0, "selected": false, "text": "iLig1, iCol1 , iLig2 , iCol2 , carac = map(lambda f: f[1](f[0]), zip(input().split(), [int, int, int, int, str]))\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20280079/" ]
74,280,103
<p>I have my <code>Scaffold</code> in <code>Safe Area</code> widget and I want to apply status bar theming but I guess <code>Safe Area</code> isn't allowing to do so.</p> <p>HomePage:</p> <pre><code>class _HomePageState extends State&lt;HomePage&gt; { @override Widget build(BuildContext context) { return SafeArea( child: Container( decoration: BoxDecoration( image: DecorationImage( image: Theme.of(context).brightness == Brightness.light ? const AssetImage('assets/images/lgt_bg.png') : const AssetImage('assets/images/drk_bg.png'), fit: BoxFit.cover, ), ), child: Scaffold( backgroundColor: Colors.transparent, appBar: AppBar( title: const Text( &quot;MnbPub&quot;, ), ), body: Container(), ), ), ); </code></pre> <p>Theme file:</p> <pre><code>class LightTheme { static final apptheme = ThemeData.light().copyWith( appBarTheme: const AppBarTheme( systemOverlayStyle: SystemUiOverlayStyle( statusBarColor: Color.fromARGB(255, 254, 222, 225), statusBarIconBrightness: Brightness.light, systemNavigationBarColor: Color.fromARGB(255, 254, 222, 225), systemNavigationBarIconBrightness: Brightness.light, ), ... </code></pre> <h3>Also I want the change to happen globally and not only for <code>home page</code>.</h3> <p>Any help?</p>
[ { "answer_id": 74280159, "author": "I'mahdi", "author_id": 1740577, "author_profile": "https://Stackoverflow.com/users/1740577", "pm_score": 3, "selected": true, "text": "(*)" }, { "answer_id": 74280179, "author": "Scott Hunter", "author_id": 535275, "author_profile": "https://Stackoverflow.com/users/535275", "pm_score": 2, "selected": false, "text": "iLig1, iCol1 , iLig2 , iCol2 , carac = [int(x) if i<4 else x for i,x in enumerate(input ().split ())]\n" }, { "answer_id": 74280247, "author": "jvx8ss", "author_id": 11107859, "author_profile": "https://Stackoverflow.com/users/11107859", "pm_score": 0, "selected": false, "text": "iLig1, iCol1 , iLig2 , iCol2 , carac = map(lambda f: f[1](f[0]), zip(input().split(), [int, int, int, int, str]))\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17411652/" ]
74,280,106
<p>I have a BigQuery table like the one below, where data wasn't necessarily recorded at a consistent rate:</p> <pre><code>| timestamp | value | |-------------------------|-------| | 2022-10-01 00:03:00 UTC | 2.43 | | 2022-10-01 00:17:00 UTC | 4.56 | | 2022-10-01 00:36:00 UTC | 3.64 | | 2022-10-01 00:58:00 UTC | 2.15 | | 2022-10-01 01:04:00 UTC | 2.90 | | 2022-10-01 01:13:00 UTC | 5.88 | ... ... </code></pre> <p>I want to calculate a rolling average (as a new column) on <code>value</code> over a certain timeframe, e.g. the previous 12 hours. I know it's relatively simple to do over a fixed number of rows, and I've tried using <code>LAG</code> and <code>TIMESTAMP_SUB</code> functions to select the right values to average over, but I'm quite new to SQL so I'm not even sure if this is the right approach.</p> <p>Does anyone know how to go about this? Thanks!</p>
[ { "answer_id": 74280159, "author": "I'mahdi", "author_id": 1740577, "author_profile": "https://Stackoverflow.com/users/1740577", "pm_score": 3, "selected": true, "text": "(*)" }, { "answer_id": 74280179, "author": "Scott Hunter", "author_id": 535275, "author_profile": "https://Stackoverflow.com/users/535275", "pm_score": 2, "selected": false, "text": "iLig1, iCol1 , iLig2 , iCol2 , carac = [int(x) if i<4 else x for i,x in enumerate(input ().split ())]\n" }, { "answer_id": 74280247, "author": "jvx8ss", "author_id": 11107859, "author_profile": "https://Stackoverflow.com/users/11107859", "pm_score": 0, "selected": false, "text": "iLig1, iCol1 , iLig2 , iCol2 , carac = map(lambda f: f[1](f[0]), zip(input().split(), [int, int, int, int, str]))\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17417816/" ]
74,280,131
<p>I have some Question and really need help on this thing but i really dont know where to start from</p> <p>I want to submit such data via html at once using text area</p> <pre><code>---START---- |FULLNAME: JANE DEO |BINF : 492BBJJ |PRICE: 10 |COUNTRY: GR ---END--- ---START---- |FULLNAME: JOHN DEO |BINF : K92BBJJ |PRICE: 24 |COUNTRY: AS ---END--- </code></pre> <p>my main point is i want to be able to store multiple data to database instead of inserting 1 by 1</p> <p>so i want to store each data where is START and END</p> <pre><code>#!/usr/bin/perl -w use DBI; use CGI qw/:standard/; my $CGI = CGI-&gt;new; my $host = &quot;localhost&quot;; my $dbname = &quot;&quot;; my $usr = &quot;&quot;; my $pwd = ''; my $dbh_usr = DBI-&gt;connect(&quot;DBI:mysql:$dbname:$host&quot;, $usr, $pwd, {RaiseError =&gt; 1,}) or die $DBI::errstr; # $binf extracted from data where is |BINF : # $price extracted from data where is |PRICE: # $info this is the whole ---START---- and ---END--- my $upload = $CGI-&gt;param(&quot;data&quot;); if ($upload) { my $update_info = $dbh_usr-&gt;prepare(&quot;INSERT INTO ITEMS(user, pid, basnm, binf, info, status, price) VALUES(?,?,?,?,?,?,?)&quot;); $update_info-&gt;execute('join123', '898', 'iono', $binf, $info, 'Active', $price); $update_info-&gt;finish; } $dbh_usr-&gt;commit; $dbh_usr-&gt;disconnect; print &quot;Content-type: text/html\n\n&quot;; print &lt;&lt;HTML; &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;The textarea&lt;/h1&gt; &lt;form method=&quot;POST&quot;&gt; &lt;textarea name=&quot;data&quot; rows=&quot;4&quot; cols=&quot;50&quot;&gt;&lt;/textarea&gt; &lt;br&gt; &lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; HTML </code></pre>
[ { "answer_id": 74280159, "author": "I'mahdi", "author_id": 1740577, "author_profile": "https://Stackoverflow.com/users/1740577", "pm_score": 3, "selected": true, "text": "(*)" }, { "answer_id": 74280179, "author": "Scott Hunter", "author_id": 535275, "author_profile": "https://Stackoverflow.com/users/535275", "pm_score": 2, "selected": false, "text": "iLig1, iCol1 , iLig2 , iCol2 , carac = [int(x) if i<4 else x for i,x in enumerate(input ().split ())]\n" }, { "answer_id": 74280247, "author": "jvx8ss", "author_id": 11107859, "author_profile": "https://Stackoverflow.com/users/11107859", "pm_score": 0, "selected": false, "text": "iLig1, iCol1 , iLig2 , iCol2 , carac = map(lambda f: f[1](f[0]), zip(input().split(), [int, int, int, int, str]))\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19956493/" ]
74,280,134
<p>I made a Django form. If the user tries to submit the form when entering wrong data then error is showed in the form and it is not submitted but when the user enters correct data and submit the form it gets submitted. The problem is that when the user presses the back button, he can still see that error in the form. The error message still stays. What can I do about it?</p> <p>The below screenshots will help you understand my problem.</p> <p><a href="https://i.stack.imgur.com/UF16X.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UF16X.png" alt="enter image description here" /></a></p> <p>In the above image I have entered the number of rooms as 0.</p> <p><a href="https://i.stack.imgur.com/qT3qY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qT3qY.png" alt="enter image description here" /></a></p> <p>As expected, I got an error.</p> <p><a href="https://i.stack.imgur.com/Ta5LZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ta5LZ.png" alt="enter image description here" /></a></p> <p>So I changed the number of rooms to 1.</p> <p><a href="https://i.stack.imgur.com/wgUWP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wgUWP.png" alt="enter image description here" /></a></p> <p>Now when I pressed the 'search availability' button I got the desired page.</p> <p><a href="https://i.stack.imgur.com/4s1dh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4s1dh.png" alt="enter image description here" /></a></p> <p>The problem arises if I press the browser back button. As you can see the error is still shown in the form.</p> <p>forms.py</p> <pre><code>class BookingForm(forms.ModelForm): class Meta: model = Booking fields = ['check_in_date', 'check_in_time', 'check_out_time', 'person', 'no_of_rooms'] widgets = { 'check_in_date': FutureDateInput(), 'check_in_time': TimeInput(), 'check_out_time': TimeInput(), } &quot;&quot;&quot;Function to ensure that booking is done for future and check out is after check in&quot;&quot;&quot; def clean(self): cleaned_data = super().clean() normal_book_date = cleaned_data.get(&quot;check_in_date&quot;) normal_check_in = cleaned_data.get(&quot;check_in_time&quot;) normal_check_out_time = cleaned_data.get(&quot;check_out_time&quot;) str_check_in = str(normal_check_in) format = '%H:%M:%S' try: datetime.datetime.strptime(str_check_in, format).time() except Exception: raise ValidationError( _('Wrong time entered.'), code='Wrong time entered.', ) # now is the date and time on which the user is booking. now = timezone.now() if (normal_book_date &lt; now.date() or (normal_book_date == now.date() and normal_check_in &lt; now.time())): raise ValidationError( &quot;You can only book for future.&quot;, code='only book for future' ) if normal_check_out_time &lt;= normal_check_in: raise ValidationError( &quot;Check out should be after check in.&quot;, code='check out after check in' ) </code></pre> <p>models.py</p> <pre><code>class Booking(models.Model): customer_name = models.CharField(max_length=30) check_in_date = models.DateField() check_in_time = models.TimeField() check_out_time = models.TimeField() room_number = models.CharField(validators=[validate_comma_separated_integer_list], max_length=9) ROOM_CATEGORIES = ( ('Regular', 'Regular'), ('Executive', 'Executive'), ('Deluxe', 'Deluxe'), ('King', 'King'), ('Queen', 'Queen'), ) category = models.CharField(max_length=9, choices=ROOM_CATEGORIES) PERSON = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), ) person = models.PositiveSmallIntegerField(choices=PERSON, default=1) no_of_rooms = models.PositiveSmallIntegerField( validators=[MaxValueValidator(1000), MinValueValidator(1)], default=1 ) </code></pre> <p>views.py</p> <pre><code>def booking(request): if request.method == 'POST': form = BookingForm(request.POST) if form.is_valid(): print(request.POST) request.session['normal_book_date'] = request.POST['check_in_date'] request.session['normal_check_in'] = request.POST['check_in_time'] request.session['normal_check_out'] = request.POST['check_out_time'] request.session['normal_person'] = int(request.POST['person']) request.session['normal_no_of_rooms_required'] = int( request.POST['no_of_rooms'] ) print(request.session['normal_check_in']) response = search_availability(request.session['normal_book_date'], request.session['normal_check_in'], request.session['normal_check_out'], request.session['normal_person'], request.session['normal_no_of_rooms_required']) if response: context = { 'categories': response, 'username': request.user.username } return render(request, 'categories.html', context) return HttpResponse(&quot;Not Available&quot;) else: context = { 'form': form, 'username': request.user.username } return render(request, 'book.html', context) context = { 'form': BookingForm(), 'username': request.user.username } return render(request, 'book.html', context) </code></pre> <p>GitHub repo link <a href="https://github.com/AnshulGupta22/room_slot_booking" rel="nofollow noreferrer">https://github.com/AnshulGupta22/room_slot_booking</a></p>
[ { "answer_id": 74280329, "author": "foobarna", "author_id": 2692704, "author_profile": "https://Stackoverflow.com/users/2692704", "pm_score": 1, "selected": false, "text": "runserver" }, { "answer_id": 74280568, "author": "LucasBorges-Santos", "author_id": 16464891, "author_profile": "https://Stackoverflow.com/users/16464891", "pm_score": 0, "selected": false, "text": "else:\n context = {\n 'form': BookingForm(),\n 'username': request.user.username\n }\n return render(request, 'book.html', context)\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10261048/" ]
74,280,148
<pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; int busqueda_indexada(int a[], int n, int x) { int elementos[3]; int indice[3]; int g; int i; int set=0; int ind=0; for (i=0; i&lt;n-1; i+=3) { elementos[ind].nombre=a[i]); elementos[ind].indice = i; i+=3; ind++; } if (x&lt;elementos[0].boleto) { return -1; } else { for (i=1; i&lt;g-1; i++) if (x&lt;elementos[i].elem) { int ini = elementos[i-1].indice; int fin = elementos[i].indice; set = 1; break; } } if (set==0) { int ini = elementos[G-1].indice; int fin = n-1; } } struct elementos { int indice; char nombre[100]; int boleto; } elementos a[3]; int main(int argc, char *argv[]) { struct elementos a[3] = {&quot;marco&quot;, 1, &quot;sin asignar&quot;, 2, &quot;pedro&quot;, 3}; printf(&quot;%s y %d&quot;, a[2].nombre, a[2].boleto); busqueda_indexada(a, n, x) return 0; } </code></pre> <p>I don't know how the indexed search can read my structure. I tried everything and always shows</p> <blockquote> <p>[Error] request for member '' in something not a structure or union</p> </blockquote> <p>every time I tried to call a structure. Maybe I defined bad my struct or I call it in the wrong way?</p>
[ { "answer_id": 74280191, "author": "Tenobaal", "author_id": 18861247, "author_profile": "https://Stackoverflow.com/users/18861247", "pm_score": 1, "selected": false, "text": "elementos[ind].nombre" }, { "answer_id": 74281549, "author": "the busybee", "author_id": 11294831, "author_profile": "https://Stackoverflow.com/users/11294831", "pm_score": 0, "selected": false, "text": "elementos" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20390642/" ]
74,280,156
<p>I have a nextflow process that outputs multiple files, like below:</p> <pre><code>[chr1,/path/to/chr1_chunk1.TC.linear] [chr1,/path/to/chr1_chunk1.HDL.linear] [chr1,/path/to/chr1_chunk2.TC.linear] [chr1,/path/to/chr1_chunk2.HDL.linear] ..... </code></pre> <p>The above example I got after using <code>transpose()</code> operator.</p> <p>Now, I want to concatenate All chunks and all chromosome together ordered by chunk and chromosome number so that I get 1 file for TC and another file for HDL. I have multiple traits in many chunks so this link wouldn't be helpful. <a href="https://stackoverflow.com/questions/67591229/output-files-chromosomal-chunks-merging-in-nextflow/68271631#68271631">output files (chromosomal chunks) merging in nextflow</a> Any help?</p>
[ { "answer_id": 74281230, "author": "mribeirodantas", "author_id": 2427138, "author_profile": "https://Stackoverflow.com/users/2427138", "pm_score": 1, "selected": false, "text": "branch" }, { "answer_id": 74291114, "author": "Steve", "author_id": 751863, "author_profile": "https://Stackoverflow.com/users/751863", "pm_score": 0, "selected": false, "text": "input_ch\n .map { key, chunk_file ->\n def matcher = chunk_file.name =~ /^chr(\\d+)_chunk(\\d+)\\.(\\w+)\\.linear$/\n def (_, chrom, chunk, trait) = matcher[0]\n\n tuple( (chrom as int), (chunk as int), trait, chunk_file )\n }\n .toSortedList( { a, b -> (a[0] <=> b[0]) ?: (a[1] <=> b[1]) } )\n .flatMap()\n .collectFile( sort: false ) { chrom, chunk, trait, chunk_file ->\n [ \"${trait}.linear\", chunk_file.text ]\n }\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4168405/" ]
74,280,168
<p>I am trying to decrypt a locally encrypted file using AWS KMS. The AWS KMS key was already created via the console and then I'm using the cli to to do the encryption and decryption. The decryption is failing.</p> <p>I have created a customer managed AWS KMS key on AWS, here's the output from aws kms describe-key command:</p> <pre><code>{ &quot;KeyMetadata&quot;: { &quot;AWSAccountId&quot;: &quot;&lt;redacted&gt;&quot;, &quot;KeyId&quot;: &quot;&lt;redacted&gt;&quot;, &quot;Arn&quot;: &quot;arn:aws:kms:eu-west-2:&lt;redacted&gt;:key/&lt;redeacted&gt;&quot;, &quot;CreationDate&quot;: &quot;2022-11-01T14:02:40.684000+00:00&quot;, &quot;Enabled&quot;: true, &quot;Description&quot;: &quot;CST MED1 FORT-B&quot;, &quot;KeyUsage&quot;: &quot;ENCRYPT_DECRYPT&quot;, &quot;KeyState&quot;: &quot;Enabled&quot;, &quot;Origin&quot;: &quot;AWS_KMS&quot;, &quot;KeyManager&quot;: &quot;CUSTOMER&quot;, &quot;CustomerMasterKeySpec&quot;: &quot;SYMMETRIC_DEFAULT&quot;, &quot;KeySpec&quot;: &quot;SYMMETRIC_DEFAULT&quot;, &quot;EncryptionAlgorithms&quot;: [ &quot;SYMMETRIC_DEFAULT&quot; ], &quot;MultiRegion&quot;: false } </code></pre> <p>I can successfully encrypt a local file using this command:</p> <pre><code>aws kms encrypt --key-id &lt;redacted&gt; --plaintext fileb://field342med1 --output text --query CiphertextBlob --region eu-west-2 &gt; field342med1.encrypted </code></pre> <p>However when decrypting this file using the following command:</p> <pre><code>aws kms decrypt --ciphertext-blob fileb://field342med1.encrypted --query Plaintext </code></pre> <p>i get the following error:</p> <pre><code>An error occurred (InvalidCiphertextException) when calling the Decrypt operation: </code></pre> <p>I have changed the fileb:// to file:// which eliminates the error but it's not decrypted to what was in the original plain textfile.</p> <p>Any ideas please?</p> <p>Any ideas how I can resolve this please?</p>
[ { "answer_id": 74281230, "author": "mribeirodantas", "author_id": 2427138, "author_profile": "https://Stackoverflow.com/users/2427138", "pm_score": 1, "selected": false, "text": "branch" }, { "answer_id": 74291114, "author": "Steve", "author_id": 751863, "author_profile": "https://Stackoverflow.com/users/751863", "pm_score": 0, "selected": false, "text": "input_ch\n .map { key, chunk_file ->\n def matcher = chunk_file.name =~ /^chr(\\d+)_chunk(\\d+)\\.(\\w+)\\.linear$/\n def (_, chrom, chunk, trait) = matcher[0]\n\n tuple( (chrom as int), (chunk as int), trait, chunk_file )\n }\n .toSortedList( { a, b -> (a[0] <=> b[0]) ?: (a[1] <=> b[1]) } )\n .flatMap()\n .collectFile( sort: false ) { chrom, chunk, trait, chunk_file ->\n [ \"${trait}.linear\", chunk_file.text ]\n }\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20300321/" ]
74,280,188
<p>So I'm using Puppeteer to scrap text from social media, I want to only scrap the text from a post, when I use the chrome developer tool to read what is the class name of the div which contains the text, it always displays a different class name when I reload the page but stay on the same post(see image)</p> <p><img src="https://i.stack.imgur.com/tUQ3c.png" alt="first page" /></p> <p><img src="https://i.stack.imgur.com/Y4M2E.png" alt="second page" /></p> <p>But I noticed that the div class name always ends with <code>.text-content</code>, is there a way to select a div with only the end of the class name?</p> <p>I tried to use the <code>$</code> selector like this :</p> <pre class="lang-js prettyprint-override"><code>document.querySelectorAll(&quot;[class$='text-content']&quot;) </code></pre> <p>And yes it finds the correct div but if I try to use <code>.textContent</code> or <code>.innerText</code> it doesn't work and it returns undefined.</p> <p>I also tried to select all divs from the developer console and then see if I could use the index of this div but it turns out that the index also changes every time I reload the page</p> <p>What I wrote in the developer console :</p> <pre class="lang-js prettyprint-override"><code>document.querySelectorAll('div') </code></pre> <p>and then it gave me an array of divs but as I said I can't use that if the index changes every time.</p>
[ { "answer_id": 74281230, "author": "mribeirodantas", "author_id": 2427138, "author_profile": "https://Stackoverflow.com/users/2427138", "pm_score": 1, "selected": false, "text": "branch" }, { "answer_id": 74291114, "author": "Steve", "author_id": 751863, "author_profile": "https://Stackoverflow.com/users/751863", "pm_score": 0, "selected": false, "text": "input_ch\n .map { key, chunk_file ->\n def matcher = chunk_file.name =~ /^chr(\\d+)_chunk(\\d+)\\.(\\w+)\\.linear$/\n def (_, chrom, chunk, trait) = matcher[0]\n\n tuple( (chrom as int), (chunk as int), trait, chunk_file )\n }\n .toSortedList( { a, b -> (a[0] <=> b[0]) ?: (a[1] <=> b[1]) } )\n .flatMap()\n .collectFile( sort: false ) { chrom, chunk, trait, chunk_file ->\n [ \"${trait}.linear\", chunk_file.text ]\n }\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20390388/" ]
74,280,194
<p>I'm following an AWS workshop for SaaS Serverless, however they wrote it with python code and i'm not very good at python so i'm trying to rewrite everything in javascript. It was doing ok until i get to the problem in title.</p> <p>They use this function to get authentication so i can register my tenant.</p> <pre><code>import boto3 from aws_requests_auth.aws_auth import AWSRequestsAuth def get_auth(host, region): session = boto3.Session() credentials = session.get_credentials() auth = AWSRequestsAuth(aws_access_key=credentials.access_key, aws_secret_access_key=credentials.secret_key, aws_token=credentials.token, aws_host=host, aws_region=region, aws_service='execute-api') return auth </code></pre> <p>The problem is I didn't find a way of getting credentials unless i hardcode it.</p> <p>My question is: How can i make this function work the same way in javascript?</p> <p>EDIT: This is the workshop i'm following:</p> <p><a href="https://catalog.us-east-1.prod.workshops.aws/workshops/b0c6ad36-0a4b-45d8-856b-8a64f0ac76bb/en-US" rel="nofollow noreferrer">https://catalog.us-east-1.prod.workshops.aws/workshops/b0c6ad36-0a4b-45d8-856b-8a64f0ac76bb/en-US</a></p> <p>This is the github repo (I'm currently on Lab 2):</p> <p><a href="https://github.com/aws-samples/aws-serverless-saas-workshop" rel="nofollow noreferrer">https://github.com/aws-samples/aws-serverless-saas-workshop</a></p> <p>This is the source of the function i talked about:</p> <p><a href="https://github.com/aws-samples/aws-serverless-saas-workshop/blob/main/Lab2/server/layers/utils.py" rel="nofollow noreferrer">https://github.com/aws-samples/aws-serverless-saas-workshop/blob/main/Lab2/server/layers/utils.py</a></p>
[ { "answer_id": 74280565, "author": "Zach J.", "author_id": 20276330, "author_profile": "https://Stackoverflow.com/users/20276330", "pm_score": 3, "selected": true, "text": "AWSRequestsAuth" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11287720/" ]
74,280,238
<pre><code>import React, { useState } from &quot;react&quot;; import { Link } from &quot;react-router-dom&quot;; const Form = (props) =&gt; { const [submit, setSubmit] = useState(false); const [inputData, setInputData] = useState({ firstname: &quot;&quot;, location: &quot;&quot; }); const InputHandle = async (event) =&gt; { setInputData({ ...inputData, [event.target.name]: event.target.value }); }; return ( &lt;div&gt; &lt;form id=&quot;form&quot; method=&quot;GET&quot;&gt; &lt;div className=&quot;inputs&quot;&gt; &lt;label for=&quot;firstname&quot;&gt; First Name&lt;/label&gt; &lt;input type=&quot;text&quot; id=&quot;firstname&quot; name=&quot;firstname&quot; onChange={InputHandle} &gt;&lt;/input&gt; &lt;/div&gt; &lt;div className=&quot;inputs&quot;&gt; &lt;label for=&quot;location&quot;&gt;User accessing application from&lt;/label&gt; &lt;input type=&quot;text&quot; id=&quot;location&quot; name=&quot;location&quot; onChange={InputHandle} &gt;&lt;/input&gt; &lt;Link to=&quot;/dashboard&quot;&gt; &lt;button type=&quot;submit&quot; className=&quot;btn&quot; onClick={() =&gt; { props.getData(inputData); }} &gt; Submit &lt;/button&gt; &lt;/Link&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; </code></pre> <p>App.js</p> <pre><code>import Dashboard from &quot;./components/Dashboard&quot;; import Form from &quot;./components/Form&quot;; import &quot;./App.css&quot;; import { BrowserRouter as Router, Switch, Routes, Route, Link, } from &quot;react-router-dom&quot;; import { useState } from &quot;react&quot;; function App() { const [data, setData] = useState({}); const getData = (inputData) =&gt; { setData(inputData); }; return ( &lt;Router&gt; &lt;div className=&quot;App&quot;&gt; &lt;Routes&gt; &lt;Route exact path=&quot;/&quot; element={&lt;Form getdata={getData()} /&gt;}&gt;&lt;/Route&gt; &lt;Route exact path=&quot;/dashboard&quot; element={&lt;Dashboard data={data} /&gt;} &gt;&lt;/Route&gt; &lt;/Routes&gt; &lt;/div&gt; &lt;/Router&gt; ); } export default App; </code></pre> <p>I am getting this error &quot;too many re-renders. react limits the number of renders to prevent an infinite loop.&quot; I don't know what exactly I am doing wrong here, could anyone please help. To help you understand: I have created a form where I want to take the input(name and location) from the user and show that input on a different page. I tried to integrate googleMaps API to show the location as per the input and m entire code crashed, otherwise it was working fine earlier, also if anyone could help me with the map here too? I have been banging my head trying to do it. I can display the map on a different page but I want to display the location on the map when the user writes any location in the input field of the form, hope I make sense.</p>
[ { "answer_id": 74280565, "author": "Zach J.", "author_id": 20276330, "author_profile": "https://Stackoverflow.com/users/20276330", "pm_score": 3, "selected": true, "text": "AWSRequestsAuth" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19336351/" ]
74,280,259
<p>I have a list : <code>var abc = {&quot;Apple&quot;, &quot;Orange&quot;};</code></p> <p>I also have a string : <code>var def = &quot;{[Mountain, Mountain, Apple ]}&quot;;</code></p> <p>I am able to check if the value is true or false with the below code</p> <pre><code>bool ghi = abc.Any(s =&gt; def.Contains(s)); </code></pre> <p><strong>How do I get the position or index in abc though ?</strong></p>
[ { "answer_id": 74280432, "author": "Dmitry Bychenko", "author_id": 2319407, "author_profile": "https://Stackoverflow.com/users/2319407", "pm_score": 1, "selected": false, "text": "for" }, { "answer_id": 74280508, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "var result = abc.Where(s => def.Contains(s));\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5746583/" ]
74,280,263
<p>I'm working with Nuxt JS v2 and need to run a function on every page change &amp; during page loads, I understand that I can add a route watcher in my layout, but this would mean having to add it to every layout, and I have many, e.g:</p> <pre class="lang-js prettyprint-override"><code>&lt;script&gt; export default { watch: { $route(to, from) { console.log('route change to', to) console.log('route change from', from) } } } &lt;/script&gt; </code></pre> <p>I have a plugin called <strong>cookie-tracking.js</strong> and was hoping that if I add a <code>console.log</code> to it that it would be called on each page change, but no, what could I add for this behaviour to occur:</p> <pre class="lang-js prettyprint-override"><code>export default ({ app, route }, inject) =&gt; { console.log('run on each page change...') } </code></pre>
[ { "answer_id": 74280432, "author": "Dmitry Bychenko", "author_id": 2319407, "author_profile": "https://Stackoverflow.com/users/2319407", "pm_score": 1, "selected": false, "text": "for" }, { "answer_id": 74280508, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "var result = abc.Where(s => def.Contains(s));\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9982090/" ]
74,280,284
<p>I have a data frame like this</p> <pre><code>+------------+-----------------+-------------------------------+ | Name | Age | Answers | +------------+-----------------+-------------------------------+ | Maria | 23 | [apple, mango, orange, banana]| | John | 55 | [apple, orange, banana] | | Brad | 44 | [banana] | +------------+-----------------+-------------------------------+ </code></pre> <p>The answers column contains an array of elements</p> <p><strong>Expected Output</strong></p> <pre><code>+------------+-----------------+-------------------------------+ | Name | Age | apple | mango |orange| banana | +------------+-----------------+-------------------------------+ | Maria | 23 | True | True | True | True | | John | 55 | True | False| True | True | | Brad | 44 | False | False | False| True | +------------+-----------------+-------------------------------+ </code></pre> <p>Is there a way where I can convert the array column into True and False columns?</p> <p>Thanks in advance.</p>
[ { "answer_id": 74280432, "author": "Dmitry Bychenko", "author_id": 2319407, "author_profile": "https://Stackoverflow.com/users/2319407", "pm_score": 1, "selected": false, "text": "for" }, { "answer_id": 74280508, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "var result = abc.Where(s => def.Contains(s));\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19831970/" ]
74,280,308
<p>I have a spreadsheet that has several columns. I'm only going to show data from 2 of them here, because they're the 2 that I'm dealing with in this problem.</p> <p>The first column is IP Addresses. The second column is how long ago the last response was or the last response date:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Address</th> <th>Last Response</th> </tr> </thead> <tbody> <tr> <td>10.1.1.109</td> <td>10/17/2022</td> </tr> <tr> <td>10.1.1.113</td> <td>10/17/2022</td> </tr> <tr> <td>10.1.1.137</td> <td>10/17/2022</td> </tr> <tr> <td>10.1.1.188</td> <td>4 days</td> </tr> <tr> <td>10.1.1.199</td> <td>10/17/2022</td> </tr> <tr> <td>10.1.21.5</td> <td>10/17/2022</td> </tr> <tr> <td>10.1.21.50</td> <td>45 days</td> </tr> <tr> <td>10.1.50.41</td> <td>10/17/2022</td> </tr> <tr> <td>10.1.50.71</td> <td>10/17/2022</td> </tr> <tr> <td>10.1.88.10</td> <td>10/17/2022</td> </tr> <tr> <td>10.1.88.249</td> <td>6 days</td> </tr> <tr> <td>10.16.6.190</td> <td>4 days</td> </tr> <tr> <td>10.64.0.76</td> <td>28 days</td> </tr> <tr> <td>10.64.3.48</td> <td>45 days</td> </tr> </tbody> </table> </div> <p>What I need to do is to get a few counts worked out. I want to know how many from each IP subnet have</p> <ol> <li>A response older than 1 week</li> <li>A Response older then 1 month.</li> </ol> <p>In the sample data you can see 3 IP subnets: 10.4, 10.16, and 10.64. I am expecting to get results like:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>IP Subnet</th> <th>&gt; Week</th> <th>&gt; Month</th> </tr> </thead> <tbody> <tr> <td>10.1</td> <td>9</td> <td>1</td> </tr> <tr> <td>10.16</td> <td>0</td> <td>0</td> </tr> <tr> <td>10.64</td> <td>2</td> <td>1</td> </tr> </tbody> </table> </div> <p>I have a formula for the &quot;&gt; Week&quot;, but I don't like it. I am not able to figure out how to count based on the number at the beginning of the text in that column. I tried a formula like this:</p> <pre><code>=COUNTIFS(AllIPAddresses,&quot;10.1.*&quot;,AllResponses, NUMBERVALUE(LEFT(AllResponses, FIND(&quot; &quot;,AllResponses)))&amp;&quot;&gt;7&quot;) </code></pre> <p>Obviously this doesn't work. It gives me a column full of 0's.</p> <p>What I have working for the &quot;&gt; Week&quot; column:</p> <pre><code>=COUNTIFS(AllIPAddresses,CONCAT(A2,&quot;*&quot;),AllResponses,&quot;&lt;&gt;7 days&quot;,AllResponses,&quot;&lt;&gt;6 days&quot;,AllResponses,&quot;&lt;&gt;5 days&quot;,AllResponses,&quot;&lt;&gt;4 days&quot;,AllResponses,&quot;&lt;&gt;3 days&quot;,AllResponses,&quot;&lt;&gt;2 days&quot;,AllResponses,&quot;&lt;&gt;Today&quot;,AllResponses,&quot;&lt;&gt;Yesterday&quot;) </code></pre> <p>But like I said, I don't like it as it is just looking at the column and not counting 8 of the options. I would prefer if I could have a way to get it to look at the column and count those whose number of days is &gt; 7. Something simple would be great, but something that is shorter and/or simpler than what I have I'll take. And I cannot reuse that effectively for the &quot;&gt; month&quot; result because then I'd have to list some 30 different options that I don't want to count.<br /> It would be better to have it look for the 1 option that I do want.</p> <p>I'm hoping for something like:</p> <ul> <li>First COUNTIFS counts all the text that have a number &gt; 7</li> <li>Second COUNTIFS counts all the dates that are more than 7 days before today</li> </ul> <pre><code>=COUNTIFS(AllIPAddresses, CONCAT(A2,&quot;*&quot;),AllResponses, LEFT(AllResponse,2)&amp;&quot;&gt;7&quot;)+COUNTIFS(AllIPAddresses, CONCAT(A2,&quot;*&quot;),AllResponses,&quot;&lt;&quot;&amp;today()-7) </code></pre> <p>And then I can reuse this for the &quot;&gt; month&quot; by changing the 7 to a 30.</p> <p>Though I know this formula doesn't work.</p> <p>Any assistance with this problem would be appreciated!</p> <p><strong>Some Notes about my formulas</strong><br /> For ease of use I have named ranges:<br /> <strong>AllIPAddresses</strong> = A2:A700<br /> <strong>AllResponses</strong> = B2:B700<br /> <em>(in my formula for &gt; week)</em> <strong>A2</strong> is referring to the &quot;10.1.&quot; so that the <code>CONCAT</code> will give the result of &quot;10.1.*&quot; to the <code>COUNTIFS</code></p> <p><strong>EDIT</strong></p> <p>I have added an answer that explains why I chose the solution that I did and how I had to tweak the answers I received to make them work for my specific scenario.</p>
[ { "answer_id": 74281980, "author": "P.b", "author_id": 12634230, "author_profile": "https://Stackoverflow.com/users/12634230", "pm_score": 3, "selected": true, "text": "=LET(data,A2:B15,\n _d1,INDEX(data,,1),\n _d2,INDEX(data,,2),\n lr,TODAY()-IF(ISNUMBER(_d2),_d2,TODAY()-(LEFT(_d2,LEN(_d2)-LEN(\" days\")))),\n lft,TEXTBEFORE(_d1,\".\",2),\n unq,UNIQUE(lft),\n sq,SEQUENCE(COUNTA(lft),,1,0),\n mm,--(TRANSPOSE(unq)=lft),\n wk,MMULT(--(TRANSPOSE(lft)=unq)*TRANSPOSE(lr>7),sq),\n mn,MMULT(--(TRANSPOSE(lft)=unq)*TRANSPOSE(lr>30),sq),\n stack,HSTACK(unq,wk,mn),\nVSTACK({\"IP Subnet\",\"> Week\",\"> Month\"},stack))\n" }, { "answer_id": 74282350, "author": "Terio", "author_id": 4840576, "author_profile": "https://Stackoverflow.com/users/4840576", "pm_score": 0, "selected": false, "text": "=LET(IP,TEXTBEFORE(AllIPAddresses,\".\",2),U,UNIQUE(IP),S,SEQUENCE(COUNTA(AllIPAddresses),,1,0),D,IFERROR(TODAY()-AllResponses,TEXTBEFORE(AllResponses,\" \")*1),W,MMULT((TRANSPOSE(IP)=U)*(TRANSPOSE(D)>7),S),M,MMULT((TRANSPOSE(IP)=U)*(TRANSPOSE(D)>30),S),HSTACK(U,W,M))\n" }, { "answer_id": 74284835, "author": "Mayukh Bhattacharya", "author_id": 8162520, "author_profile": "https://Stackoverflow.com/users/8162520", "pm_score": 1, "selected": false, "text": "D2" }, { "answer_id": 74306760, "author": "Mike", "author_id": 2911241, "author_profile": "https://Stackoverflow.com/users/2911241", "pm_score": 1, "selected": false, "text": "=LET(data,AllData, _d1,INDEX(data,,1)\n, _d2, INDEX(data,,4)\n, lr, TODAY()-IF(ISNUMBER(_d2),_d2,TODAY()-(IF(_d2=\"Today\",\"0\",IF(_d2=\"Yesterday\",\"1\",LEFT(_d2,LEN(_d2)-LEN(\" days\"))))))\n, lft, TEXTBEFORE(_d1,\".\",2)\n, unq, UNIQUE(lft)\n, sq, SEQUENCE(COUNTA(lft),,1,0)\n, mm, --(TRANSPOSE(unq)=lft)\n, wk, MMULT(--(TRANSPOSE(lft)=unq)*TRANSPOSE(lr>7),sq)\n, mn, MMULT(--(TRANSPOSE(lft)=unq)*TRANSPOSE(lr>30),sq)\n, stack, HSTACK(unq, wk, mn)\n, VSTACK({\"IP Subnet\", \"> Week\", \"> Month\"}, stack))\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2911241/" ]
74,280,328
<p>I need to unit test this code, but i have been seeing null pointer exceptions at buckets.builder().</p> <pre><code>import io.github.bucket4j.distributed.proxy.ProxyManager; private ProxyManager buckets; public Bucket resolveBucket(String key) { Supplier&lt;BucketConfiguration&gt; configSupplier = getConfigSupplierForUser(); return buckets.builder().build(key, configSupplier); } </code></pre>
[ { "answer_id": 74281980, "author": "P.b", "author_id": 12634230, "author_profile": "https://Stackoverflow.com/users/12634230", "pm_score": 3, "selected": true, "text": "=LET(data,A2:B15,\n _d1,INDEX(data,,1),\n _d2,INDEX(data,,2),\n lr,TODAY()-IF(ISNUMBER(_d2),_d2,TODAY()-(LEFT(_d2,LEN(_d2)-LEN(\" days\")))),\n lft,TEXTBEFORE(_d1,\".\",2),\n unq,UNIQUE(lft),\n sq,SEQUENCE(COUNTA(lft),,1,0),\n mm,--(TRANSPOSE(unq)=lft),\n wk,MMULT(--(TRANSPOSE(lft)=unq)*TRANSPOSE(lr>7),sq),\n mn,MMULT(--(TRANSPOSE(lft)=unq)*TRANSPOSE(lr>30),sq),\n stack,HSTACK(unq,wk,mn),\nVSTACK({\"IP Subnet\",\"> Week\",\"> Month\"},stack))\n" }, { "answer_id": 74282350, "author": "Terio", "author_id": 4840576, "author_profile": "https://Stackoverflow.com/users/4840576", "pm_score": 0, "selected": false, "text": "=LET(IP,TEXTBEFORE(AllIPAddresses,\".\",2),U,UNIQUE(IP),S,SEQUENCE(COUNTA(AllIPAddresses),,1,0),D,IFERROR(TODAY()-AllResponses,TEXTBEFORE(AllResponses,\" \")*1),W,MMULT((TRANSPOSE(IP)=U)*(TRANSPOSE(D)>7),S),M,MMULT((TRANSPOSE(IP)=U)*(TRANSPOSE(D)>30),S),HSTACK(U,W,M))\n" }, { "answer_id": 74284835, "author": "Mayukh Bhattacharya", "author_id": 8162520, "author_profile": "https://Stackoverflow.com/users/8162520", "pm_score": 1, "selected": false, "text": "D2" }, { "answer_id": 74306760, "author": "Mike", "author_id": 2911241, "author_profile": "https://Stackoverflow.com/users/2911241", "pm_score": 1, "selected": false, "text": "=LET(data,AllData, _d1,INDEX(data,,1)\n, _d2, INDEX(data,,4)\n, lr, TODAY()-IF(ISNUMBER(_d2),_d2,TODAY()-(IF(_d2=\"Today\",\"0\",IF(_d2=\"Yesterday\",\"1\",LEFT(_d2,LEN(_d2)-LEN(\" days\"))))))\n, lft, TEXTBEFORE(_d1,\".\",2)\n, unq, UNIQUE(lft)\n, sq, SEQUENCE(COUNTA(lft),,1,0)\n, mm, --(TRANSPOSE(unq)=lft)\n, wk, MMULT(--(TRANSPOSE(lft)=unq)*TRANSPOSE(lr>7),sq)\n, mn, MMULT(--(TRANSPOSE(lft)=unq)*TRANSPOSE(lr>30),sq)\n, stack, HSTACK(unq, wk, mn)\n, VSTACK({\"IP Subnet\", \"> Week\", \"> Month\"}, stack))\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6522341/" ]
74,280,331
<p>I would like to add multiple elements that all have the same value to an array of objects Something like '.push()' but with a count. I know I can do array.push(a, b, c), but I want to be able to do something like:</p> <pre><code>person { firstName: string; lastName: string; age: number; } people: Person[]; numberPeople: number; // some calculation to generate numberPeople, example: 23 person.push( {firstName: '', lastName: 'Smith', age: 0}, NumberPeople) </code></pre> <p>I know I can use a loop structure (for (i=0; i&lt;NumberPeople;i++) person.push) but that gets cumbersome. Is there an easier way? I'm relatively new to JavaScript and TypeScript.</p> <p>I've tried .fill() but that doesn't let me specify values.</p> <p>thanks,</p> <p>I know I can create my own function ( mpush(obj, count) ) but I would rather use something more elegant and standard, if there is something.</p>
[ { "answer_id": 74281980, "author": "P.b", "author_id": 12634230, "author_profile": "https://Stackoverflow.com/users/12634230", "pm_score": 3, "selected": true, "text": "=LET(data,A2:B15,\n _d1,INDEX(data,,1),\n _d2,INDEX(data,,2),\n lr,TODAY()-IF(ISNUMBER(_d2),_d2,TODAY()-(LEFT(_d2,LEN(_d2)-LEN(\" days\")))),\n lft,TEXTBEFORE(_d1,\".\",2),\n unq,UNIQUE(lft),\n sq,SEQUENCE(COUNTA(lft),,1,0),\n mm,--(TRANSPOSE(unq)=lft),\n wk,MMULT(--(TRANSPOSE(lft)=unq)*TRANSPOSE(lr>7),sq),\n mn,MMULT(--(TRANSPOSE(lft)=unq)*TRANSPOSE(lr>30),sq),\n stack,HSTACK(unq,wk,mn),\nVSTACK({\"IP Subnet\",\"> Week\",\"> Month\"},stack))\n" }, { "answer_id": 74282350, "author": "Terio", "author_id": 4840576, "author_profile": "https://Stackoverflow.com/users/4840576", "pm_score": 0, "selected": false, "text": "=LET(IP,TEXTBEFORE(AllIPAddresses,\".\",2),U,UNIQUE(IP),S,SEQUENCE(COUNTA(AllIPAddresses),,1,0),D,IFERROR(TODAY()-AllResponses,TEXTBEFORE(AllResponses,\" \")*1),W,MMULT((TRANSPOSE(IP)=U)*(TRANSPOSE(D)>7),S),M,MMULT((TRANSPOSE(IP)=U)*(TRANSPOSE(D)>30),S),HSTACK(U,W,M))\n" }, { "answer_id": 74284835, "author": "Mayukh Bhattacharya", "author_id": 8162520, "author_profile": "https://Stackoverflow.com/users/8162520", "pm_score": 1, "selected": false, "text": "D2" }, { "answer_id": 74306760, "author": "Mike", "author_id": 2911241, "author_profile": "https://Stackoverflow.com/users/2911241", "pm_score": 1, "selected": false, "text": "=LET(data,AllData, _d1,INDEX(data,,1)\n, _d2, INDEX(data,,4)\n, lr, TODAY()-IF(ISNUMBER(_d2),_d2,TODAY()-(IF(_d2=\"Today\",\"0\",IF(_d2=\"Yesterday\",\"1\",LEFT(_d2,LEN(_d2)-LEN(\" days\"))))))\n, lft, TEXTBEFORE(_d1,\".\",2)\n, unq, UNIQUE(lft)\n, sq, SEQUENCE(COUNTA(lft),,1,0)\n, mm, --(TRANSPOSE(unq)=lft)\n, wk, MMULT(--(TRANSPOSE(lft)=unq)*TRANSPOSE(lr>7),sq)\n, mn, MMULT(--(TRANSPOSE(lft)=unq)*TRANSPOSE(lr>30),sq)\n, stack, HSTACK(unq, wk, mn)\n, VSTACK({\"IP Subnet\", \"> Week\", \"> Month\"}, stack))\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20390759/" ]
74,280,339
<p>I have a simple autocomplete menu just like the one below. Is there any way to monitor if the user clicks outside the menu? By default, if the user clicks outside the menu, it will close the menu. But I would like to trigger other actions besides just closing the menu.</p> <p>I will keep it simple with the following scenario: I have a boolean variable called myBoolVar that has a default value of false. When the autocomplete is mounted, it will autofocus the input and the menu will only open when the user starts typing in the input. Untill here the myBoolVar remains false. but only when the user clicks outside of the menu, then the menu closes and the myBoolVar changes to true.</p> <p>I have been through vuetify api documentation without any luck so far.</p> <pre><code> &lt;v-autocomplete v-model=&quot;valuesActor&quot; :items=&quot;actorArray&quot; :search-input.sync=&quot;searchActor&quot; filled autofocus background-color=#313131 append-icon=&quot;&quot; prepend-inner-icon=&quot;mdi-arrow-left&quot; color=&quot;var(--textLightGrey)&quot; &gt; &lt;/v-autocomplete&gt; </code></pre>
[ { "answer_id": 74281803, "author": "Tanya Linska", "author_id": 16085970, "author_profile": "https://Stackoverflow.com/users/16085970", "pm_score": 2, "selected": true, "text": "You can use blur event for autocomplete like that:\n\n\n\n methods: {\n someMethod() {\n alert('tadam')\n }\n }\n <v-autocomplete\n v-model=\"value\"\n :items=\"items\"\n @blur=\"someMethod\"\n />\n\n\n\n\nYou can find the documentation here https://vuetifyjs.com/en/api/v-autocomplete/#events\n" }, { "answer_id": 74286361, "author": "Arslan Butt", "author_id": 2959918, "author_profile": "https://Stackoverflow.com/users/2959918", "pm_score": 0, "selected": false, "text": "v-click-outside" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12814680/" ]
74,280,350
<p>Working on a weather generator that using terrain and month to randomize a weather effect for that scenario. Its extremely bloated because I could not get while loops or classes to work in previous iterations. I decided to just to make a massive block of code that did the job and revisit later in my project.</p> <p>Using Python 3.10 is PyCharm IDE. Getting the following error for specific month variables:</p> <p>in Plains/Hills September and Forest/Hills/Plains November I get an error. Everything else works fine.</p> <pre><code>Traceback (most recent call last): File &quot;C:\\Users\\roman\\PycharmProjects\\videogame\\test.py&quot;, line 167, in \&lt;module\&gt; print(weather.current_weather) AttributeError: type object 'weather' has no attribute 'current_weather' Septemeber Plains </code></pre> <p>script</p> <pre><code>from random import * import random class month: estimated_day = randint(1, 359) if estimated_day &lt;= 30: current_month = (&quot;January&quot;) elif estimated_day &lt;= 60: current_month = (&quot;February&quot;) elif estimated_day &lt;= 90: current_month = (&quot;March&quot;) elif estimated_day &lt;= 120: current_month = (&quot;April&quot;) elif estimated_day &lt;= 150: current_month = (&quot;May&quot;) elif estimated_day &lt;= 180: current_month = (&quot;June&quot;) elif estimated_day &lt;= 210: current_month = (&quot;July&quot;) elif estimated_day &lt;= 240: current_month = (&quot;August&quot;) elif estimated_day &lt;= 270: current_month = (&quot;Septemeber&quot;) elif estimated_day &lt;= 300: current_month = (&quot;October&quot;) elif estimated_day &lt;= 330: current_month = (&quot;Novemeber&quot;) elif estimated_day &lt;= 360: current_month = (&quot;December&quot;) print(month.current_month) terrain_list = (&quot;Forest&quot;,&quot;Plains&quot;,&quot;Hills&quot;,&quot;Tundra&quot;,&quot;Desert&quot;) current_terrain = (random.choice(terrain_list)) print(current_terrain) class x: forest_weather_list = (&quot;Clear&quot;,&quot;Rain&quot;,&quot;Thunderstorm&quot;,&quot;Snowing&quot;,&quot;Blizzard&quot;) jan_forest_weather_list = (&quot;Clear&quot;,&quot;Snowing&quot;,&quot;Blizzard&quot;) feb_forest_weather_list = (&quot;Clear&quot;,&quot;Snowing&quot;,&quot;Blizzard&quot;) mar_forest_weather_list = (&quot;Clear&quot;,&quot;Rain&quot;,&quot;Thunderstorm&quot;) apr_forest_weather_list = (&quot;Clear&quot;,&quot;Rain&quot;,&quot;Thunderstorm&quot;) may_forest_weather_list = (&quot;Clear&quot;,&quot;Rain&quot;,&quot;Thunderstorm&quot;) jun_forest_weather_list = (&quot;Clear&quot;,&quot;Rain&quot;,&quot;Thunderstorm&quot;) jul_forest_weather_list = (&quot;Clear&quot;,&quot;Rain&quot;,&quot;Thunderstorm&quot;) aug_forest_weather_list = (&quot;Clear&quot;,&quot;Rain&quot;,&quot;Thunderstorm&quot;) sep_forest_weather_list = (&quot;Clear&quot;,&quot;Snowing&quot;) oct_forest_weather_list = (&quot;Clear&quot;,&quot;Snowing&quot;) nov_forest_weather_list = (&quot;Clear&quot;,&quot;Snowing&quot;) dec_forest_weather_list = (&quot;Clear&quot;,&quot;Snowing&quot;,&quot;Blizzard&quot;) plains_weather_list = (&quot;Clear&quot;,&quot;Rain&quot;,&quot;Thunderstorm&quot;,&quot;Snowing&quot;,&quot;Blizzard&quot;) jan_plains_weather_list = (&quot;Windy&quot;,&quot;Snowing&quot;,&quot;Blizzard&quot;) feb_plains_weather_list = (&quot;Windy&quot;,&quot;Snowing&quot;,&quot;Blizzard&quot;) mar_plains_weather_list = (&quot;Windy&quot;,&quot;Rain&quot;,&quot;Thunderstorm&quot;,&quot;Tornado&quot;) apr_plains_weather_list = (&quot;Windy&quot;,&quot;Rain&quot;,&quot;Thunderstorm&quot;,&quot;Tornado&quot;) may_plains_weather_list = (&quot;Windy&quot;,&quot;Rain&quot;,&quot;Thunderstorm&quot;,&quot;Tornado&quot;) jun_plains_weather_list = (&quot;Windy&quot;,&quot;Rain&quot;,&quot;Thunderstorm&quot;,&quot;Tornado&quot;) jul_plains_weather_list = (&quot;Windy&quot;,&quot;Rain&quot;,&quot;Thunderstorm&quot;,&quot;Tornado&quot;) aug_plains_weather_list = (&quot;Windy&quot;,&quot;Rain&quot;,&quot;Thunderstorm&quot;,&quot;Tornado&quot;) sep_plains_weather_list = (&quot;Windy&quot;,&quot;Snowing&quot;) oct_plains_weather_list = (&quot;Windy&quot;,&quot;Snowing&quot;) nov_plains_weather_list = (&quot;Windy&quot;,&quot;Snowing&quot;) dec_plains_weather_list = (&quot;Windy&quot;,&quot;Snowing&quot;,&quot;Blizzard&quot;) hills_weather_list = (&quot;Clear&quot;,&quot;Rain&quot;,&quot;Thunderstorm&quot;,&quot;Snowing&quot;,&quot;Blizzard&quot;) jan_hills_weather_list = (&quot;Clear&quot;,&quot;Snowing&quot;,&quot;Blizzard&quot;) feb_hills_weather_list = (&quot;Clear&quot;,&quot;Snowing&quot;,&quot;Blizzard&quot;) mar_hills_weather_list = (&quot;Clear&quot;,&quot;Rain&quot;,&quot;Thunderstorm&quot;) apr_hills_weather_list = (&quot;Clear&quot;,&quot;Rain&quot;,&quot;Thunderstorm&quot;) may_hills_weather_list = (&quot;Clear&quot;,&quot;Rain&quot;,&quot;Thunderstorm&quot;) jun_hills_weather_list = (&quot;Clear&quot;,&quot;Rain&quot;,&quot;Thunderstorm&quot;) jul_hills_weather_list = (&quot;Clear&quot;,&quot;Rain&quot;,&quot;Thunderstorm&quot;) aug_hills_weather_list = (&quot;Clear&quot;,&quot;Rain&quot;,&quot;Thunderstorm&quot;) sep_hills_weather_list = (&quot;Clear&quot;,&quot;Snowing&quot;) oct_hills_weather_list = (&quot;Clear&quot;,&quot;Snowing&quot;) nov_hills_weather_list = (&quot;Clear&quot;,&quot;Snowing&quot;) dec_hills_weather_list = (&quot;Clear&quot;,&quot;Snowing&quot;,&quot;Blizzard&quot;) tundra_weather_list = (&quot;Clear&quot;,&quot;Snowing&quot;,&quot;Blizzard&quot;) desert_weather_list = (&quot;Arid&quot;,&quot;Drought&quot;,&quot;Sandstorm&quot;) class weather: if current_terrain == &quot;Forest&quot;: if month.current_month == &quot;January&quot;: current_weather = (random.choice(x.jan_forest_weather_list)) elif month.current_month == &quot;February&quot;: current_weather = (random.choice(x.feb_forest_weather_list)) elif month.current_month == &quot;March&quot;: current_weather = (random.choice(x.mar_forest_weather_list)) elif month.current_month == &quot;April&quot;: current_weather = (random.choice(x.apr_forest_weather_list)) elif month.current_month == &quot;May&quot;: current_weather = (random.choice(x.may_forest_weather_list)) elif month.current_month == &quot;June&quot;: current_weather = (random.choice(x.jun_forest_weather_list)) elif month.current_month == &quot;July&quot;: current_weather = (random.choice(x.jul_forest_weather_list)) elif month.current_month == &quot;August&quot;: current_weather = (random.choice(x.aug_forest_weather_list)) elif month.current_month == &quot;September&quot;: current_weather = (random.choice(x.sep_forest_weather_list)) elif month.current_month == &quot;October&quot;: current_weather = (random.choice(x.oct_forest_weather_list)) elif month.current_month == &quot;November&quot;: current_weather = (random.choice(x.nov_forest_weather_list)) elif month.current_month == &quot;December&quot;: current_weather = (random.choice(x.dec_forest_weather_list)) elif current_terrain == &quot;Plains&quot;: if month.current_month == &quot;January&quot;: current_weather = (random.choice(x.jan_plains_weather_list)) elif month.current_month == &quot;February&quot;: current_weather = (random.choice(x.feb_plains_weather_list)) elif month.current_month == &quot;March&quot;: current_weather = (random.choice(x.mar_plains_weather_list)) elif month.current_month == &quot;April&quot;: current_weather = (random.choice(x.apr_plains_weather_list)) elif month.current_month == &quot;May&quot;: current_weather = (random.choice(x.may_plains_weather_list)) elif month.current_month == &quot;June&quot;: current_weather = (random.choice(x.jun_plains_weather_list)) elif month.current_month == &quot;July&quot;: current_weather = (random.choice(x.jul_plains_weather_list)) elif month.current_month == &quot;August&quot;: current_weather = (random.choice(x.aug_plains_weather_list)) elif month.current_month == &quot;September&quot;: current_weather = (random.choice(x.sep_plains_weather_list)) elif month.current_month == &quot;October&quot;: current_weather = (random.choice(x.oct_plains_weather_list)) elif month.current_month == &quot;November&quot;: current_weather = (random.choice(x.nov_plains_weather_list)) elif month.current_month == &quot;December&quot;: current_weather = (random.choice(x.dec_plains_weather_list)) elif current_terrain == &quot;Hills&quot;: if month.current_month == &quot;January&quot;: current_weather = (random.choice(x.jan_hills_weather_list)) elif month.current_month == &quot;February&quot;: current_weather = (random.choice(x.feb_hills_weather_list)) elif month.current_month == &quot;March&quot;: current_weather = (random.choice(x.mar_hills_weather_list)) elif month.current_month == &quot;April&quot;: current_weather = (random.choice(x.apr_hills_weather_list)) elif month.current_month == &quot;May&quot;: current_weather = (random.choice(x.may_hills_weather_list)) elif month.current_month == &quot;June&quot;: current_weather = (random.choice(x.jun_hills_weather_list)) elif month.current_month == &quot;July&quot;: current_weather = (random.choice(x.jul_hills_weather_list)) elif month.current_month == &quot;August&quot;: current_weather = (random.choice(x.aug_hills_weather_list)) elif month.current_month == &quot;September&quot;: current_weather = (random.choice(x.sep_hills_weather_list)) elif month.current_month == &quot;October&quot;: current_weather = (random.choice(x.oct_hills_weather_list)) elif month.current_month == &quot;November&quot;: current_weather = (random.choice(x.nov_hills_weather_list)) elif month.current_month == &quot;December&quot;: current_weather = (random.choice(x.dec_hills_weather_list)) elif current_terrain == &quot;Tundra&quot;: current_weather = (random.choice(x.tundra_weather_list)) elif current_terrain == &quot;Desert&quot;: current_weather = (random.choice(x.desert_weather_list)) print(weather.current_weather) </code></pre> <p>If managing the bloat helps I would appreciate that but I really just want to know why 10/12 month variables output my desired result but month nov/sep give an error.</p>
[ { "answer_id": 74281803, "author": "Tanya Linska", "author_id": 16085970, "author_profile": "https://Stackoverflow.com/users/16085970", "pm_score": 2, "selected": true, "text": "You can use blur event for autocomplete like that:\n\n\n\n methods: {\n someMethod() {\n alert('tadam')\n }\n }\n <v-autocomplete\n v-model=\"value\"\n :items=\"items\"\n @blur=\"someMethod\"\n />\n\n\n\n\nYou can find the documentation here https://vuetifyjs.com/en/api/v-autocomplete/#events\n" }, { "answer_id": 74286361, "author": "Arslan Butt", "author_id": 2959918, "author_profile": "https://Stackoverflow.com/users/2959918", "pm_score": 0, "selected": false, "text": "v-click-outside" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
74,280,354
<p>I am trying to output the length of a string using strlen(). But I want to do it through a pointer.</p> <p>Here's what I tried: `</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; int main() { char a[]=&quot;wel&quot;; int *p; p=&amp;a; printf(&quot;%d\n&quot;,strlen(*p)); } </code></pre> <p>The image shows the error I am getting while compiling:<a href="https://i.stack.imgur.com/m9HvZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/m9HvZ.png" alt="enter image description here" /></a></p> <p>Then made this change in the code declaration of *p to *p[]:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; int main() { char a[]=&quot;wel&quot;; int *p[]; p=&amp;a; printf(&quot;%d\n&quot;,strlen(*p)); } </code></pre> <p>But then I am getting an error &quot;storage size of 'p' isn't known.&quot; What am I still missing?</p>
[ { "answer_id": 74280417, "author": "Peter Irich", "author_id": 20275388, "author_profile": "https://Stackoverflow.com/users/20275388", "pm_score": -1, "selected": false, "text": "printf(\"%d\\n\",strlen(a));\n" }, { "answer_id": 74280430, "author": "ikegami", "author_id": 589924, "author_profile": "https://Stackoverflow.com/users/589924", "pm_score": 2, "selected": false, "text": "sizeof" }, { "answer_id": 74280526, "author": "Vlad from Moscow", "author_id": 2877241, "author_profile": "https://Stackoverflow.com/users/2877241", "pm_score": 0, "selected": false, "text": "a" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10838122/" ]
74,280,358
<p><a href="https://i.stack.imgur.com/h6x7H.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/h6x7H.png" alt="enter image description here" /></a></p> <p>I am trying to replicate this python code but I am unsure how to go about asking for a user inputted list one at a time and then how to present the list in order and then randomly. If anyone could point me in the right direction I would appreciate it</p> <pre><code>total = 0 while True: List = input('Enter an item or &quot;done&quot; to stop entering items: ') if List == 'done': break print(List) </code></pre> <p>This was my original idea but I don't think it makes any sense</p>
[ { "answer_id": 74280417, "author": "Peter Irich", "author_id": 20275388, "author_profile": "https://Stackoverflow.com/users/20275388", "pm_score": -1, "selected": false, "text": "printf(\"%d\\n\",strlen(a));\n" }, { "answer_id": 74280430, "author": "ikegami", "author_id": 589924, "author_profile": "https://Stackoverflow.com/users/589924", "pm_score": 2, "selected": false, "text": "sizeof" }, { "answer_id": 74280526, "author": "Vlad from Moscow", "author_id": 2877241, "author_profile": "https://Stackoverflow.com/users/2877241", "pm_score": 0, "selected": false, "text": "a" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20256918/" ]
74,280,377
<pre><code>import React, { Component } from 'react'; import './App.css'; import { todos } from './todos.json'; console.log(todos); class App extends Component { render() { return ( &lt;div className='App'&gt; &lt;/div&gt; ) } } export default App; </code></pre> <p>that is my app and and and I want to get the todos.json to display each of the sentences from the todos.json</p> <p>my error:</p> <p>Compiled with problems:X</p> <p>ERROR in ./src/App.js 8:12-17</p> <p>Should not import the named export 'todos' (imported as 'todos') from default-exporting module (only default export is available soon)</p> <pre><code>{ &quot;todos&quot;: [ { &quot;frase&quot;: &quot;la vida es bella&quot;, &quot;autor&quot;: &quot;La pelicula xd&quot; }, { &quot;frase&quot;: &quot;El iq esta sobrevalorado&quot;, &quot;autor&quot;: &quot;ni idea xd&quot; }, { &quot;frase&quot;: &quot;ganar es lo unico importante&quot;, &quot;autor&quot;: &quot;Ayanokoji&quot; } ] } </code></pre> <p>I want to display the todos.json in my app</p>
[ { "answer_id": 74280407, "author": "Cristhian Fernández", "author_id": 8666826, "author_profile": "https://Stackoverflow.com/users/8666826", "pm_score": 1, "selected": false, "text": "import json from './todos.json'" }, { "answer_id": 74280424, "author": "David", "author_id": 328193, "author_profile": "https://Stackoverflow.com/users/328193", "pm_score": 1, "selected": true, "text": "import data from './todos.json';\nconst { todos } = data;\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20390905/" ]
74,280,395
<p>I have the below code and am trying to generate a new dictionary of parameters. I would like the new dictionary to be a nested dictionary, and one of the nested keys be the most recent value, while the second nested key to be a counter that increases each time a value is updated.</p> <pre><code>options = {'threads' : '1', 'tolerance' : '1'} options_2 = {'threads' : '2', 'timeout': True} over_params = {} def overrides_tracker(options, over_params): print(options) for k, v in options.items(): over_params[k]['count'] += 1 over_params[k]['value'] = v return over_params over_params = overrides_tracker(options, over_params) over_params = overrides_tracker(options_2, over_params) print(over_params) </code></pre> <p>Right now my code is returning a KeyError. Is there an easier way to implement this sort of counter. Note that the value does not matter if the count of times that parameter is overridden is greater than 1. (That's why I don't mind just updating the value and replacing it.)</p> <p>I would like for the resulting dictionary to look like this with the given inputs and function calls. (Note that the 'threads' key has a count value of 2.</p> <pre><code>{'threads': {'count': 2, 'value': '2'}, 'tolerance': {'count': 1, 'value': '1'}, 'timeout': {'count': 1, 'value': True}} </code></pre>
[ { "answer_id": 74280501, "author": "Swifty", "author_id": 20267366, "author_profile": "https://Stackoverflow.com/users/20267366", "pm_score": 2, "selected": false, "text": "options = {'threads' : '1', 'tolerance' : '1'}\noptions_2 = {'threads' : '2', 'timeout': True}\n\nover_params = {}\n\ndef overrides_tracker(options, over_params):\n print(options)\n for k, v in options.items():\n if k in over_params:\n over_params[k]['count'] += 1\n over_params[k]['value'] = v\n else:\n over_params[k]={'count':1,'value':v}\n \n return over_params\n \n\nover_params = overrides_tracker(options, over_params)\nover_params = overrides_tracker(options_2, over_params)\n \nprint(over_params)\n# {'threads': {'count': 2, 'value': '2'}, 'tolerance': {'count': 1, 'value': '1'}, 'timeout': {'count': 1, 'value': True}}\n" }, { "answer_id": 74280513, "author": "jprebys", "author_id": 3268228, "author_profile": "https://Stackoverflow.com/users/3268228", "pm_score": 1, "selected": false, "text": "def overrides_tracker(options, over_params):\n print(options)\n for k, v in options.items():\n if k in over_params:\n over_params[k]['count'] += 1\n else:\n over_params[k] = {'count': 1}\n over_params[k]['value'] = v\n return over_params\n" }, { "answer_id": 74280514, "author": "Ben Borchard", "author_id": 4054720, "author_profile": "https://Stackoverflow.com/users/4054720", "pm_score": 0, "selected": false, "text": "over_params" }, { "answer_id": 74280547, "author": "Kyostenas", "author_id": 13132076, "author_profile": "https://Stackoverflow.com/users/13132076", "pm_score": 0, "selected": false, "text": "def overrides_tracker(_options, _over_params):\n for key, value in _options.items():\n \n try:\n _over_params[key]['count'] += 1\n except KeyError:\n _over_params[key] = {'count': 0, 'value': None}\n _over_params[key]['value'] = value\n \n return _over_params\n\n\ndef test_over_params():\n options = {'threads' : '1', 'tolerance' : '1'}\n options_2 = {'threads' : '2', 'timeout': True}\n \n over_params = {}\n\n over_params = overrides_tracker(options, over_params)\n over_params = overrides_tracker(options_2, over_params)\n \n print(over_params)\n \n \nif __name__ == '__main__':\n test_over_params()\n\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11710003/" ]
74,280,399
<p>I am pulling some data through tidycensus from the ACS. When I do this, I get two columns for all the variables I included. Since my final dataset has a lot of variables, is it possible to turn off the pull of the MOE. Failing that, can I delete all columns ending with M, and remove the E at the end of the estimate columns?</p> <pre><code>dv_acs = c( var1 = &quot;B25002_001&quot;, var2 = &quot;B25002_002&quot;, var3 = &quot;C24010_039&quot; ) acs_vars &lt;- get_acs( geography = &quot;tract&quot;, state = &quot;MD&quot;, variables = dv_acs , year = 2009, output = &quot;wide&quot;, geometry = FALSE ) </code></pre>
[ { "answer_id": 74287516, "author": "Lukas Wallrich", "author_id": 10581449, "author_profile": "https://Stackoverflow.com/users/10581449", "pm_score": 2, "selected": true, "text": "library(tidyverse)\ndf <- tibble(\n column1M = rnorm(10),\n column1E = rnorm(10),\n column2M = rnorm(10),\n column2E = rnorm(10)\n)\n\ndf %>% select(-ends_with(\"M\")) %>%\n rename_with(~str_remove(.x, \"E$\"))\n" }, { "answer_id": 74289690, "author": "Selcuk Disci", "author_id": 20018002, "author_profile": "https://Stackoverflow.com/users/20018002", "pm_score": 0, "selected": false, "text": "acs_vars %>% \n rename_with(.fn = ~ gsub(pattern = \"E\",\n replacement = \"\", \n x = .x, \n fixed =TRUE), \n .cols = matches(\"[0-9]\")) %>% \n select(-ends_with(\"M\"))\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14622403/" ]
74,280,428
<p>I am a beginner to python and I encountered a problem. This is what I wanted to do: If I I have 1 line that contains an input statement. while repeating the same line a few times by a loop, I want to store the data from the input and saving it from every repetition without loosing the previous data. after finishing the loop, I want to retrieve the data from all the iterations of the loop and then do something with each different data. In my case what I want to do is to compare the data. now the problem is that I were not able to save and store the data.</p> <pre><code> for i in range(2): x = input(&quot;give me a letter&quot;) if(x1==x2): #the x1 and x2 are only for demonstrating that they should be different variables from x. they are not real syntax print(&quot;you wrote the same letter twice!&quot;) </code></pre> <p>I tried to see if I can use the pickle model, but wasn't able to understand how to do so.</p>
[ { "answer_id": 74280447, "author": "LucasBorges-Santos", "author_id": 16464891, "author_profile": "https://Stackoverflow.com/users/16464891", "pm_score": 1, "selected": false, "text": "# we suppose input is -> 1 2 3 4 u\n>>> (*i, j) = input().split()\n\n>>> print(i)\n['1', '2', '3', '4']\n" }, { "answer_id": 74281129, "author": "Ibn Eratosthenes", "author_id": 20390868, "author_profile": "https://Stackoverflow.com/users/20390868", "pm_score": 1, "selected": false, "text": "listNumbers = []#Creates a list to check the values you input\nwhile True: #Creates a loop forever\n x = input(\"Give me a something: \") \n if x in listNumbers:#Checks if the piece of data is in that list \n print(\"You wrote the same data twice!\")\n elif len(listNumbers) >= 0:#This is to add to the list forever if its a new character\n listNumbers.append(x)#If it's new then it will add to the list\n print(listNumbers)#For visually checking your list" }, { "answer_id": 74281192, "author": "mdlatt", "author_id": 15178790, "author_profile": "https://Stackoverflow.com/users/15178790", "pm_score": 1, "selected": true, "text": "answers = []\n\nfor _ in range(3):\n x = input(\"Give me a letter: \")\n if x in answers:\n print(\"Duplicate\")\n else:\n answers.append(x)\n\nprint(answers) \n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20274855/" ]
74,280,438
<p>I am just beginning to learn Prolog:</p> <pre><code>% Doors door(kitchen, office). connect(X, Y) :- door(X, Y). connect(X, Y) :- door(Y, X). </code></pre> <p>Now, when I consult:</p> <pre><code>?- connect(kitchen, office). true ; false. ?- connect(office, kitchen). true. ?- </code></pre> <p>Why in the first query Prolog thought there's more, and had me press <strong><code>;</code></strong> ?</p>
[ { "answer_id": 74281212, "author": "TessellatingHeckler", "author_id": 478656, "author_profile": "https://Stackoverflow.com/users/478656", "pm_score": 2, "selected": false, "text": "door(X,Y)" }, { "answer_id": 74289980, "author": "Will Ness", "author_id": 849891, "author_profile": "https://Stackoverflow.com/users/849891", "pm_score": 2, "selected": false, "text": "connect/2" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11871747/" ]
74,280,454
<p>Hi sorry I just really need some answer for this question. I'm only using my phone.</p> <p>In the first pic is the simple conditional formatting that I use. Cell value with specific text</p> <p>But in picture #2 is what I would like to happen. Even in the blank between there would be a color. Not sure if this is possible but I would like to hear from you guys.</p> <p>Thank you.</p> <p>Picture #1</p> <p><a href="https://i.stack.imgur.com/WRCJH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WRCJH.png" alt="enter image description here" /></a></p> <p>Picture #2</p> <p><a href="https://i.stack.imgur.com/Qsg9Z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qsg9Z.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74281212, "author": "TessellatingHeckler", "author_id": 478656, "author_profile": "https://Stackoverflow.com/users/478656", "pm_score": 2, "selected": false, "text": "door(X,Y)" }, { "answer_id": 74289980, "author": "Will Ness", "author_id": 849891, "author_profile": "https://Stackoverflow.com/users/849891", "pm_score": 2, "selected": false, "text": "connect/2" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20170189/" ]
74,280,475
<p>I'm really new to Python, so forgive me if this is a ridiculously simple question. I have a given list</p> <pre><code>x = [0,1,2,3,4,5,6,7,8,9] </code></pre> <p>Now I want to make a list e, using list comprehension, that contains a list for each odd element of list x. All inner elements of this list should be true and the number of list elements is given by the current number of x. So it should look like this:</p> <pre><code>[[], [True, True], [True, True, True, True], ...] </code></pre> <p>The code I have so far is:</p> <pre><code>e = [[True for z in x] for z in x if z % 2 != 0] </code></pre> <p>When printed I get a list, where the amount of nested lists is equal to the amount of odd numbers in list x, but all of them contain True ten times. What do I have to do to make the lengths of the inner lists equal to the values of the odd numbers?</p>
[ { "answer_id": 74280548, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 1, "selected": false, "text": "z % 2 == 0" }, { "answer_id": 74280554, "author": "Green Cloak Guy", "author_id": 2648811, "author_profile": "https://Stackoverflow.com/users/2648811", "pm_score": 3, "selected": true, "text": "[[True for _ in range(z)] for z in x if z % 2 != 0]\n" }, { "answer_id": 74280572, "author": "I'mahdi", "author_id": 1740577, "author_profile": "https://Stackoverflow.com/users/1740577", "pm_score": 1, "selected": false, "text": "range" }, { "answer_id": 74280751, "author": "Kyostenas", "author_id": 13132076, "author_profile": "https://Stackoverflow.com/users/13132076", "pm_score": 0, "selected": false, "text": "def generate_number_list(quantity: int):\n \"\"\"\n This creates a list of numbers\n \"\"\"\n number_list = []\n for number in range(quantity):\n number_list.append(number) \n \n return number_list\n\n\ndef main():\n number_list = generate_number_list(10)\n odd_number_sub_lists = []\n \n # Be careful with list comprehensions. Storing them\n # could cause unexpected behaviour\n [\n odd_number_sub_lists.append(\n \n # Nested list comprehension that uses the current_number\n # as a range, only when its an odd number.\n [True for count in range(current_number)]\n )\n for current_number in number_list\n \n # As you typed odd Numbers. All of the previous\n # statements only work if the current_number\n # divided by two gives a residue greater than 0\n if (current_number % 2 > 0) \n ]\n return odd_number_sub_lists\n \n \nif __name__ == '__main__':\n result = main()\n print(result)\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20390902/" ]
74,280,477
<p>I have a small question in JS / JSON. I will need to make selects whose data would depend on the previous ones. Let me explain :</p> <p>I have a JSON &quot;type&quot; which has in data:</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>[ { "id": 0, "title": "fruit" }, { "id": 1, "title": "vegetables" }, { "id": 2, "title": "meat" }, ]</code></pre> </div> </div> </p> <p>I have a second &quot;food&quot; which has data:</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>[ { "id": 0, "title": "apple", "typeId": 0 }, { "id": 1, "title": "strawberry", "typeId": 0 }, { "id": 2, "title": "chicken", "typeId": 2 }, { "id": 3, "title": "beef", "typeId": 2 }, ]</code></pre> </div> </div> </p> <p>And a last one &quot;specie&quot; with these data :</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>[ { "id": 0, "titre": "green", "foodId": 0 }, { "id": 1, "titre": "red", "foodId": 1 } ]</code></pre> </div> </div> </p> <p>I would like three input selects in my HTML.</p> <p>The first will list the types, and depending on which one I choose I'll want the data from the second select to fit. For example if I choose &quot;fruit&quot; I would like to have in my second input select &quot;apple&quot; and &quot;strawberry&quot;. The third input will also change depending on the data of the second. So if I select &quot;apple&quot; we will have the choice between &quot;green&quot; and &quot;red&quot;</p> <p>How could I get this result in JS?</p> <p>Thanks in advance !</p>
[ { "answer_id": 74280964, "author": "Albert Badias", "author_id": 20090804, "author_profile": "https://Stackoverflow.com/users/20090804", "pm_score": -1, "selected": false, "text": " <button id=\"fruitbutton\">fruit</button>\n <button id=\"vegetablesbutton\">vegetables</button>\n <button id=\"meatbutton\">meat</button>\n <script>\n var type = [{\n \"id\": 0,\n \"title\": \"fruit\"\n },\n {\n \"id\": 1,\n \"title\": \"vegetables\"\n }, {\n \"id\": 2,\n \"title\": \"meat\"\n }\n ]\n\n var food = [{\n \"id\": 0,\n \"title\": \"apple\",\n \"typeId\": 0\n },\n {\n \"id\": 1,\n \"title\": \"strawberry\",\n \"typeId\": 0\n },\n {\n \"id\": 2,\n \"title\": \"chicken\",\n \"typeId\": 2\n },\n {\n \"id\": 3,\n \"title\": \"beef\",\n \"typeId\": 2\n },\n ]\n\n document.getElementById(\"fruitbutton\").onclick = () => {\n var selected = 0;\n selectnextbuttons(selected);\n }\n\n document.getElementById(\"vegetablesbutton\").onclick = () => {\n var selected = 1;\n selectnextbuttons(selected);\n }\n\n document.getElementById(\"meatbutton\").onclick = () => {\n var selected = 2;\n selectnextbuttons(selected);\n }\n\n function selectnextbuttons(selected) {\n var lengthfoodjson = Object.keys(food).length\n for (var i = 0; i < lengthfoodjson; i++) {\n if (food[i].typeId == selected) {\n console.log(food[i].title)\n } else {\n //console.log(\"nothing\")\n }\n }\n }\n</script>\n" }, { "answer_id": 74281011, "author": "Daniel ZA", "author_id": 3454921, "author_profile": "https://Stackoverflow.com/users/3454921", "pm_score": 1, "selected": true, "text": "// Load our JSON values.\nlet types = [\n {\n \"id\": 0,\n \"title\": \"fruit\"\n },\n {\n \"id\": 1,\n \"title\": \"vegetables\"\n },\n {\n \"id\": 2,\n \"title\": \"meat\"\n },\n];\n\nlet foods = [\n {\n \"id\": 0,\n \"title\": \"apple\",\n \"typeId\": 0\n },\n {\n \"id\": 1,\n \"title\": \"strawberry\",\n \"typeId\": 0\n },\n {\n \"id\": 2,\n \"title\": \"chicken\",\n \"typeId\": 2\n },\n {\n \"id\": 3,\n \"title\": \"beef\",\n \"typeId\": 2\n },\n];\n\n// Function to load the values.\nfunction loadTypes() {\n\n // Lets find our select control for the types.\n let typeSelector = document.getElementById(\"types\");\n\n // For each of the type values.\n for (let t = 0; t < types.length; t++) {\n\n // Lets get the type.\n let type = types[t];\n\n // Lets add an option.\n var option = document.createElement(\"option\");\n\n // Lets set it's properties.\n option.value = type.id;\n option.text = type.title;\n\n // Lets add this as an option to the typeSelector.\n typeSelector.add(option);\n }\n}\n\n// Function we can call onchange of selection.\nfunction loadFoods(typeSelected) {\n\n // Lets find our select control for the foods.\n let foodSelector = document.getElementById(\"foods\");\n\n // Remove all previous options.\n while (foodSelector.options.length > 0) {\n foodSelector.options.remove(0);\n }\n\n // For each of the food values.\n for (let t = 0; t < foods.length; t++) {\n\n // Lets get the food.\n let food = foods[t];\n\n // Lets see if it is of the same type.\n if (food.typeId == typeSelected) {\n\n // Lets add an option.\n var option = document.createElement(\"option\");\n\n // Lets set it's properties.\n option.value = food.id;\n option.text = food.title;\n\n // Lets add this as an option to the foodSelector.\n foodSelector.add(option);\n }\n }\n}\n\n// Call our default function to load the types.\nloadTypes();" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19400575/" ]
74,280,492
<p>I am in the process of implementing an API Gateway as a point of access to several existing APIs that run as microservices.</p> <p>Each microservice API is defined in OpenAPI and runs an instance of swagger-ui to document and expose endpoints. Everything is written in Ruby on Rails as separate API-only projects.</p> <p>I'm looking at Kong or Tyk in the role of API Gateway. Is it possible with either project to run swagger-ui on the gateway to document available routes through the gateway and to allow authenticated users to try the various endpoints exposed by the different services in one place rather than per-service? If not, does either project provide such an interface in any form?</p>
[ { "answer_id": 74280964, "author": "Albert Badias", "author_id": 20090804, "author_profile": "https://Stackoverflow.com/users/20090804", "pm_score": -1, "selected": false, "text": " <button id=\"fruitbutton\">fruit</button>\n <button id=\"vegetablesbutton\">vegetables</button>\n <button id=\"meatbutton\">meat</button>\n <script>\n var type = [{\n \"id\": 0,\n \"title\": \"fruit\"\n },\n {\n \"id\": 1,\n \"title\": \"vegetables\"\n }, {\n \"id\": 2,\n \"title\": \"meat\"\n }\n ]\n\n var food = [{\n \"id\": 0,\n \"title\": \"apple\",\n \"typeId\": 0\n },\n {\n \"id\": 1,\n \"title\": \"strawberry\",\n \"typeId\": 0\n },\n {\n \"id\": 2,\n \"title\": \"chicken\",\n \"typeId\": 2\n },\n {\n \"id\": 3,\n \"title\": \"beef\",\n \"typeId\": 2\n },\n ]\n\n document.getElementById(\"fruitbutton\").onclick = () => {\n var selected = 0;\n selectnextbuttons(selected);\n }\n\n document.getElementById(\"vegetablesbutton\").onclick = () => {\n var selected = 1;\n selectnextbuttons(selected);\n }\n\n document.getElementById(\"meatbutton\").onclick = () => {\n var selected = 2;\n selectnextbuttons(selected);\n }\n\n function selectnextbuttons(selected) {\n var lengthfoodjson = Object.keys(food).length\n for (var i = 0; i < lengthfoodjson; i++) {\n if (food[i].typeId == selected) {\n console.log(food[i].title)\n } else {\n //console.log(\"nothing\")\n }\n }\n }\n</script>\n" }, { "answer_id": 74281011, "author": "Daniel ZA", "author_id": 3454921, "author_profile": "https://Stackoverflow.com/users/3454921", "pm_score": 1, "selected": true, "text": "// Load our JSON values.\nlet types = [\n {\n \"id\": 0,\n \"title\": \"fruit\"\n },\n {\n \"id\": 1,\n \"title\": \"vegetables\"\n },\n {\n \"id\": 2,\n \"title\": \"meat\"\n },\n];\n\nlet foods = [\n {\n \"id\": 0,\n \"title\": \"apple\",\n \"typeId\": 0\n },\n {\n \"id\": 1,\n \"title\": \"strawberry\",\n \"typeId\": 0\n },\n {\n \"id\": 2,\n \"title\": \"chicken\",\n \"typeId\": 2\n },\n {\n \"id\": 3,\n \"title\": \"beef\",\n \"typeId\": 2\n },\n];\n\n// Function to load the values.\nfunction loadTypes() {\n\n // Lets find our select control for the types.\n let typeSelector = document.getElementById(\"types\");\n\n // For each of the type values.\n for (let t = 0; t < types.length; t++) {\n\n // Lets get the type.\n let type = types[t];\n\n // Lets add an option.\n var option = document.createElement(\"option\");\n\n // Lets set it's properties.\n option.value = type.id;\n option.text = type.title;\n\n // Lets add this as an option to the typeSelector.\n typeSelector.add(option);\n }\n}\n\n// Function we can call onchange of selection.\nfunction loadFoods(typeSelected) {\n\n // Lets find our select control for the foods.\n let foodSelector = document.getElementById(\"foods\");\n\n // Remove all previous options.\n while (foodSelector.options.length > 0) {\n foodSelector.options.remove(0);\n }\n\n // For each of the food values.\n for (let t = 0; t < foods.length; t++) {\n\n // Lets get the food.\n let food = foods[t];\n\n // Lets see if it is of the same type.\n if (food.typeId == typeSelected) {\n\n // Lets add an option.\n var option = document.createElement(\"option\");\n\n // Lets set it's properties.\n option.value = food.id;\n option.text = food.title;\n\n // Lets add this as an option to the foodSelector.\n foodSelector.add(option);\n }\n }\n}\n\n// Call our default function to load the types.\nloadTypes();" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022788/" ]
74,280,498
<p>I am trying to use query search in mongoose when user hast array of objects with different postalCodes. And I have an object which is called Job. At job I have postalCode as String. What I want to achieve it is for each postalCode from users to slice the postalCode on jobs and if possible to match them. Problem it is that always it is returning empty but in case it should match with the job and return it.<br /> User it is always the logged in user. So user is the given input to search into the collection of jobs</p> <p>Here is my Code of 1 user.</p> <pre><code>&quot;searchFilter&quot; : { &quot;remote&quot; : 0, &quot;data&quot; : [ { &quot;country&quot; : &quot;DEU&quot;, &quot;searchActive&quot; : false, &quot;postalCode&quot; : &quot;123&quot;, &quot;available&quot; : { &quot;$date&quot; : 1664955924380 } }, { &quot;country&quot; : &quot;DEU&quot;, &quot;searchActive&quot; : false, &quot;postalCode&quot; : &quot;850&quot;, &quot;available&quot; : { &quot;$date&quot; : 1667165151744 } } ] }, </code></pre> <p>And this is the job.</p> <pre><code>&quot;postalCode&quot; : &quot;12345&quot;, &quot;country&quot; : &quot;DEU&quot;, </code></pre> <p>And this is my actual query search.</p> <pre><code> let job = await Job.find({ $or: user.searchFilter.data.map((user) =&gt; user.postalCode) .map((postalCode) =&gt; ( { yearSubstring: { $substr: [ &quot;$postalCode&quot;, 0, postalCode.length ] }, })) }); if (!job) { res.status(204).json({ error: &quot;No Data&quot; }); return; } return res.status(200).send(job); </code></pre>
[ { "answer_id": 74309592, "author": "nimrod serok", "author_id": 18482310, "author_profile": "https://Stackoverflow.com/users/18482310", "pm_score": 0, "selected": false, "text": "unwind" }, { "answer_id": 74312450, "author": "turivishal", "author_id": 8987128, "author_profile": "https://Stackoverflow.com/users/8987128", "pm_score": 3, "selected": true, "text": "$in" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9560126/" ]
74,280,502
<p>How can I set data-* attributes of a div dynamically via an array or object in Vue.js?</p> <p>I found out that it is possible to set attributes dynamically via the data attributes or via calculated properties. But the problem is that I don't know how to name the calculated properties so that they end up with the attribute name &quot;data-customer-firstname&quot;, for example.</p> <p>Link to the <a href="https://vuejs.org/guide/essentials/template-syntax.html#dynamic-arguments" rel="nofollow noreferrer">vue.js doc</a></p> <p>I hope someone have an idea to solve the problem.</p> <p>EDIT (here is an example):</p> <pre><code>&lt;template&gt; &lt;div class=&quot;content&quot;&gt; &lt;div :[dataCountry] :[dataApplicantFirstname] :[dataApplicantLastName] &gt;&lt;/div&gt; &lt;!-- the result I needed --&gt; &lt;div data-country=&quot;ukraine&quot; data-applicant-firstname=&quot;Doe&quot; data-applicant-lastname=&quot;Joe&quot; &gt; &lt;/div&gt; &lt;!-- but if one of them is &quot;null&quot; it should be ignored for example if the country and the firstname are &quot;null&quot; so it should be ignored and it should likes so: --&gt; &lt;div data-applicant-lastname=&quot;Joe&quot; &gt; &lt;/div&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; export default { name: &quot;ExampleComponent&quot;, data() { return { country:&quot;ukraine&quot;, firstname: &quot;Doe&quot;, lastname: &quot;Joe&quot; } }, computed: { dataCountry: function () { return (this.country !== &quot;&quot;) ? this.country : null; }, dataCustomerFirstname:function (){ return (this.firstname !== &quot;&quot;)?this.firstname : null; }, dataCustomerLastName:function (){ return (this.lastname !== &quot;&quot;)?this.lastname : null; }, }, } &lt;/script&gt; </code></pre>
[ { "answer_id": 74280814, "author": "dominagy", "author_id": 15524006, "author_profile": "https://Stackoverflow.com/users/15524006", "pm_score": 1, "selected": false, "text": "<div :data-country=\"dataCountry\"></div>\n" }, { "answer_id": 74280846, "author": "Boussadjra Brahim", "author_id": 8172857, "author_profile": "https://Stackoverflow.com/users/8172857", "pm_score": 0, "selected": false, "text": " <div\n :[dataCountry]=\"country\"\n :[dataCustomerFirstname]=\"firstname\"\n :[dataCustomerLastname]=\"lastname\"\n >\n\n\n<script>\nexport default {\n name: \"ExampleComponent\",\n data() {\n return {\n country:\"ukraine\",\n firstname: \"Doe\",\n lastname: \"Joe\"\n }\n },\n computed: {\n dataCountry: function () {\n return (this.country !== \"\") ? 'data-applicant-country': '';\n },\n dataCustomerFirstname:function (){\n return (this.firstname !== \"\")? 'data-applicant-firstname' :'';\n },\n dataCustomerLastName:function (){\n return (this.lastname !== \"\")?'data-applicant-lastname' :''\n },\n\n },\n}\n</script>\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8576252/" ]
74,280,509
<p>I have a project on R as I am learning it, but I am totally lost about this problem : I have two dataframes (crime2020 and crime2021) but in crime2021, the column Primary.Type is missing. Each possible value of Primary.Type is linked with a particular &quot;ID&quot; corresponding to the value in the column IUCR. The idea is as follow : as I have IUCR in both dataframes, I want to compare the IUCR of 2020 and 2021, and when there are equal, I want to put the value of Primary.Type in 2021 in the dataframe of 2020. I don't think it is clear so I will give a simple example :</p> <p>Dataframe 2020 :</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">IUCR</th> <th style="text-align: center;">Primary.Type</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">0820</td> <td style="text-align: center;">NA</td> </tr> <tr> <td style="text-align: center;">0460</td> <td style="text-align: center;">NA</td> </tr> </tbody> </table> </div> <p>Dataframe 2021 :</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">IUCR</th> <th style="text-align: center;">Primary.Type</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">0820</td> <td style="text-align: center;">Theft</td> </tr> <tr> <td style="text-align: center;">0789</td> <td style="text-align: center;">Robbery</td> </tr> <tr> <td style="text-align: center;">0460</td> <td style="text-align: center;">Battery</td> </tr> </tbody> </table> </div> <p>So here, for the first column of 2020, where IUCR=0820, I want to test if a IUCR in 2021 is equal to 0820 and if yes, replace with the value in Primary.Type for this row, so Theft should be put in the first row of the colum Primary.Type of 2020. And I want to do it for each row of 2020. So I want to compare each row of 2020 with each row of 2021. The problem is that both dataframes have 200.000 rows...</p> <p>I tried first for just the first row (i=1) of my 2020 dataframe with the function that follows :</p> <pre><code>Create&lt;-function(i){ for(y in 1:nrow(crime2021)){ ifelse(crime2020[i,5]==crime2021[y,5], crime2020[i,22]&lt;-crime2021[y,6], (for(x in 1:(nrow(crime2021)-y)){ ifelse(crime2020[i,5]==crime2021[y+x,5], crime2020[i,22]&lt;-crime2021[y+x,5], crime2020[i,22]&lt;-&quot;NA&quot;)} ))}} </code></pre> <p>with :</p> <ul> <li>crime2020[i,5] = IUCR 2020</li> <li>crime2021[y,5] = IUCR 2021</li> <li>crime2020[i,22] = Primary.Type 2020</li> <li>crime2020[y,6] = Primary.Type 2021</li> </ul> <p>I don't know if it works because this function is too &quot;heavy&quot; so when I ran Create(1) it takes too long to and I had to stop it.</p> <p>If someone have a solution it will really helps me !</p> <p>Thanks you, and don't hesitate to ask for precisions, I don't know if it is very clear !</p>
[ { "answer_id": 74280814, "author": "dominagy", "author_id": 15524006, "author_profile": "https://Stackoverflow.com/users/15524006", "pm_score": 1, "selected": false, "text": "<div :data-country=\"dataCountry\"></div>\n" }, { "answer_id": 74280846, "author": "Boussadjra Brahim", "author_id": 8172857, "author_profile": "https://Stackoverflow.com/users/8172857", "pm_score": 0, "selected": false, "text": " <div\n :[dataCountry]=\"country\"\n :[dataCustomerFirstname]=\"firstname\"\n :[dataCustomerLastname]=\"lastname\"\n >\n\n\n<script>\nexport default {\n name: \"ExampleComponent\",\n data() {\n return {\n country:\"ukraine\",\n firstname: \"Doe\",\n lastname: \"Joe\"\n }\n },\n computed: {\n dataCountry: function () {\n return (this.country !== \"\") ? 'data-applicant-country': '';\n },\n dataCustomerFirstname:function (){\n return (this.firstname !== \"\")? 'data-applicant-firstname' :'';\n },\n dataCustomerLastName:function (){\n return (this.lastname !== \"\")?'data-applicant-lastname' :''\n },\n\n },\n}\n</script>\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20390933/" ]
74,280,557
<p>dart cant change 14.99942 to 14.99; toStringAsFixed() doesn't work properly. Example:</p> <p>(179.99 / 12.00).toStringAsFixed(2)</p> <p>expected result: 14.99</p> <p>actual result: 15.00</p>
[ { "answer_id": 74280814, "author": "dominagy", "author_id": 15524006, "author_profile": "https://Stackoverflow.com/users/15524006", "pm_score": 1, "selected": false, "text": "<div :data-country=\"dataCountry\"></div>\n" }, { "answer_id": 74280846, "author": "Boussadjra Brahim", "author_id": 8172857, "author_profile": "https://Stackoverflow.com/users/8172857", "pm_score": 0, "selected": false, "text": " <div\n :[dataCountry]=\"country\"\n :[dataCustomerFirstname]=\"firstname\"\n :[dataCustomerLastname]=\"lastname\"\n >\n\n\n<script>\nexport default {\n name: \"ExampleComponent\",\n data() {\n return {\n country:\"ukraine\",\n firstname: \"Doe\",\n lastname: \"Joe\"\n }\n },\n computed: {\n dataCountry: function () {\n return (this.country !== \"\") ? 'data-applicant-country': '';\n },\n dataCustomerFirstname:function (){\n return (this.firstname !== \"\")? 'data-applicant-firstname' :'';\n },\n dataCustomerLastName:function (){\n return (this.lastname !== \"\")?'data-applicant-lastname' :''\n },\n\n },\n}\n</script>\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14495509/" ]
74,280,570
<p>I required to implement a simple symbolic equation solver. The equation must be stored in a binary tree. Each operand or operator should be stored as a tuple of the form (TYPE, VALUE).</p> <p>For example: (OPERAND, 5), (OPERAND, 7), (OPERAND, 34), (OPERATOR, ‘+’) or (OPERATOR, '*’').</p> <p>Following operators should be supported: addition (+), subtraction (-), multiplication (*), and exponentiation (^).</p> <p>They gave me that sketch. but I couldn't understand to solve this. I should include my code that (#Include your code here) point. anyone can help me with that?</p> <pre><code>class Node: def __init__(self, data): self.left = None self.right = None self.data = data def get_output(self): ''' Print the output depending on the evaluated value. If the 0 &lt;= value &lt;= 999 the value is printed. If the value &lt; 0, UNDERFLOW is printed. If the value &gt; 999, OVERFLOW is printed. :return: None ''' value = self.evaluate() if value &gt; 999: print('OVERFLOW') elif value &lt; 0: print('UNDERFLOW') else: print(value) ##################################################################### ######### Your task is to implement the following methods. ########## ##################################################################### def insert(self, data, bracketed): ''' Insert operators and operands into the binary tree. :param data: Operator or operand as a tuple. E.g.: ('OPERAND', 34), ('OPERATOR', ‘+’) :param bracketed: denote whether an operator is inside brackets or not. If the operator is inside brackets, we set bracketed as True. :return: self ''' #Include your code here return self def evaluate(self): ''' Process the expression stored in the binary tree and compute the final result. To do that, the function should be able to traverse the binary tree. Note that the evaluate function does not check for overflow or underflow. :return: the evaluated value ''' #Include your code here pass </code></pre>
[ { "answer_id": 74280814, "author": "dominagy", "author_id": 15524006, "author_profile": "https://Stackoverflow.com/users/15524006", "pm_score": 1, "selected": false, "text": "<div :data-country=\"dataCountry\"></div>\n" }, { "answer_id": 74280846, "author": "Boussadjra Brahim", "author_id": 8172857, "author_profile": "https://Stackoverflow.com/users/8172857", "pm_score": 0, "selected": false, "text": " <div\n :[dataCountry]=\"country\"\n :[dataCustomerFirstname]=\"firstname\"\n :[dataCustomerLastname]=\"lastname\"\n >\n\n\n<script>\nexport default {\n name: \"ExampleComponent\",\n data() {\n return {\n country:\"ukraine\",\n firstname: \"Doe\",\n lastname: \"Joe\"\n }\n },\n computed: {\n dataCountry: function () {\n return (this.country !== \"\") ? 'data-applicant-country': '';\n },\n dataCustomerFirstname:function (){\n return (this.firstname !== \"\")? 'data-applicant-firstname' :'';\n },\n dataCustomerLastName:function (){\n return (this.lastname !== \"\")?'data-applicant-lastname' :''\n },\n\n },\n}\n</script>\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20345526/" ]
74,280,573
<p>I understand that the heart of Paxos consensus algorithm is that there is only one &quot;majority&quot; in any given set of nodes, therefore if a proposer gets accepted by a majority, there cannot be another majority that accepts a different value, given that any acceptor can only accept 1 single value.</p> <p>So the simplest &quot;happy path&quot; of a consensus algorithm is just for any proposer to ping a majority of acceptors and see if it can get them to accept its value, and if so, we're done.</p> <p>The collision comes when concurrent proposers leads to a case where no majority of nodes agrees on a value, which can be demonstrated with the simplest case of 3 nodes, and every node tries to get 2 nodes to accept its value but due to concurrency, every node ends up only get itself to &quot;accept&quot; the value, and therefore no majority agrees on anything.</p> <p>Paxos algorithm continues to invent a 2-phase algorithm to solve this problem.</p> <p>But why can't we just simply backoff a random amount of time and retry, until eventually one proposer will succeed in grabbing a majority opinion? This can be demonstrated to succeed <strong>eventually</strong>, since every proposer will backoff a random amount of time if it fails to grab a majority.</p> <p>I understand that this is not going to be ideal in terms of performance. But let's get performance out of the way first and only look at the correctness. Is there anything I'm missing here? Is this <em>a</em> correct (basic) consensus algorithm at all?</p>
[ { "answer_id": 74280814, "author": "dominagy", "author_id": 15524006, "author_profile": "https://Stackoverflow.com/users/15524006", "pm_score": 1, "selected": false, "text": "<div :data-country=\"dataCountry\"></div>\n" }, { "answer_id": 74280846, "author": "Boussadjra Brahim", "author_id": 8172857, "author_profile": "https://Stackoverflow.com/users/8172857", "pm_score": 0, "selected": false, "text": " <div\n :[dataCountry]=\"country\"\n :[dataCustomerFirstname]=\"firstname\"\n :[dataCustomerLastname]=\"lastname\"\n >\n\n\n<script>\nexport default {\n name: \"ExampleComponent\",\n data() {\n return {\n country:\"ukraine\",\n firstname: \"Doe\",\n lastname: \"Joe\"\n }\n },\n computed: {\n dataCountry: function () {\n return (this.country !== \"\") ? 'data-applicant-country': '';\n },\n dataCustomerFirstname:function (){\n return (this.firstname !== \"\")? 'data-applicant-firstname' :'';\n },\n dataCustomerLastName:function (){\n return (this.lastname !== \"\")?'data-applicant-lastname' :''\n },\n\n },\n}\n</script>\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192280/" ]
74,280,577
<blockquote> <p>In HTML, form elements such as <code>&lt;input&gt;</code>, <code>&lt;textarea&gt;</code>, and <code>&lt;select&gt;</code> typically maintain their own state and update it based on user input.</p> </blockquote> <p><a href="https://reactjs.org/docs/forms.html#controlled-components" rel="nofollow noreferrer">https://reactjs.org/docs/forms.html#controlled-components</a></p> <p>Can you give me an example?</p> <p>Thanks.</p>
[ { "answer_id": 74280814, "author": "dominagy", "author_id": 15524006, "author_profile": "https://Stackoverflow.com/users/15524006", "pm_score": 1, "selected": false, "text": "<div :data-country=\"dataCountry\"></div>\n" }, { "answer_id": 74280846, "author": "Boussadjra Brahim", "author_id": 8172857, "author_profile": "https://Stackoverflow.com/users/8172857", "pm_score": 0, "selected": false, "text": " <div\n :[dataCountry]=\"country\"\n :[dataCustomerFirstname]=\"firstname\"\n :[dataCustomerLastname]=\"lastname\"\n >\n\n\n<script>\nexport default {\n name: \"ExampleComponent\",\n data() {\n return {\n country:\"ukraine\",\n firstname: \"Doe\",\n lastname: \"Joe\"\n }\n },\n computed: {\n dataCountry: function () {\n return (this.country !== \"\") ? 'data-applicant-country': '';\n },\n dataCustomerFirstname:function (){\n return (this.firstname !== \"\")? 'data-applicant-firstname' :'';\n },\n dataCustomerLastName:function (){\n return (this.lastname !== \"\")?'data-applicant-lastname' :''\n },\n\n },\n}\n</script>\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17385061/" ]
74,280,613
<p>I would appreciate any help. I want to change the text color of the button every time it is a darker background color. I have been trying other variations of the below code. I cant seem to get the newColor to work. Thanks in advance for your help.</p> <pre><code>const button = document.querySelector('button'); const h1 = document.querySelector('h1'); button.addEventListener('click', () =&gt; { const newColor = randomColor(); document.body.style.backgroundColor = newColor; h1.innerText = newColor; }) let newColor; const randomColor = () =&gt; { const r = Math.floor(Math.random() * 255); const g = Math.floor(Math.random() * 255); const b = Math.floor(Math.random() * 255); newColor = r * 0.299 + g * 0.587 + b * 0.114 if(newColor &gt; 186) { newColor = 'black'; } else { newColor = 'white'; } return `rgb(${r}, ${g}, ${b})`; } </code></pre> <p>I tried making my own function, I have tried putting an if statement on the outside of the function.</p>
[ { "answer_id": 74280677, "author": "Albert Badias", "author_id": 20090804, "author_profile": "https://Stackoverflow.com/users/20090804", "pm_score": 1, "selected": false, "text": "var newRandomColor = Math.floor(Math.random()*16777215).toString(16)\n" }, { "answer_id": 74326790, "author": "Albert Badias", "author_id": 20090804, "author_profile": "https://Stackoverflow.com/users/20090804", "pm_score": 0, "selected": false, "text": "function RGBcolor() {\n var R = Math.floor(Math.random() * 256);\n var G = Math.floor(Math.random() * 256);\n var B = Math.floor(Math.random() * 256);\n var randomcolor = \"rgb(\" + R + \",\" + G + \",\" + B + \")\"; \n console.log(randomcolor);\n}\n\nRGBcolor();\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18850911/" ]
74,280,663
<p>I need to connect to Athena using Python.</p> <p>The code used is as follows:</p> <pre><code>import pyathena import pandas as pd athena_conn = pyathena.connect(access_key, secret_key, s3_staging_dir, region_name) df = pd.read_sql(&quot;SELECT * FROM db.tableLIMIT 10&quot;, athena_conn) df.head(5) </code></pre> <p>I, personally don't have access to Athena with my AWS, hence I'm borrowing the <code>access_key</code> and <code>secret_access_key</code></p> <p>from my colleague, who has access to Athena.</p> <p>I get the following error while running the code :</p> <pre><code>An error occurred (AccessDeniedException) when calling the StartQueryExecution operation: User: arn:aws:iam::xxxxx:user/xxxx is not authorized to perform: athena:StartQueryExecution on resource: arn:aws:athena:us-east-1:xxxx:workgroup/primary because no identity-based policy allows the athena:StartQueryExecution action unable to rollback </code></pre> <p>Is it because my account doesn't have access to Athena?</p>
[ { "answer_id": 74280677, "author": "Albert Badias", "author_id": 20090804, "author_profile": "https://Stackoverflow.com/users/20090804", "pm_score": 1, "selected": false, "text": "var newRandomColor = Math.floor(Math.random()*16777215).toString(16)\n" }, { "answer_id": 74326790, "author": "Albert Badias", "author_id": 20090804, "author_profile": "https://Stackoverflow.com/users/20090804", "pm_score": 0, "selected": false, "text": "function RGBcolor() {\n var R = Math.floor(Math.random() * 256);\n var G = Math.floor(Math.random() * 256);\n var B = Math.floor(Math.random() * 256);\n var randomcolor = \"rgb(\" + R + \",\" + G + \",\" + B + \")\"; \n console.log(randomcolor);\n}\n\nRGBcolor();\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17804077/" ]
74,280,678
<p>I am trying to get some data from a project using API. In this case I need to set NIH API to get information. I need to use <code>findDrugInteractions</code> rest point but I do not have idea on how to set the extraction. I only know that I need <code>httr</code> to get the data and <code>jsonlite</code> to format it. This is the link of the API:</p> <p><a href="https://lhncbc.nlm.nih.gov/RxNav/APIs/api-Interaction.findDrugInteractions.html" rel="nofollow noreferrer">https://lhncbc.nlm.nih.gov/RxNav/APIs/api-Interaction.findDrugInteractions.html</a></p> <p>In the help options there is an example:</p> <p><a href="https://rxnav.nlm.nih.gov/REST/interaction/interaction.json?rxcui=88014&amp;sources=ONCHigh" rel="nofollow noreferrer">https://rxnav.nlm.nih.gov/REST/interaction/interaction.json?rxcui=88014&amp;sources=ONCHigh</a></p> <p>This API uses rxcui (a code) to get the data. In the case of previous example is 88014. But I do not know how to replicate this example using <code>R</code>.</p> <p>Can anybody please help me? Many thanks!</p> <p><em>Update</em></p> <p>With the answer provided I have obtained the data but I am not sure how I can process the long json object. I tried using <code>rrapply</code> but it returns a very large dataframe. Is there any way I can format the json objet properly to have columns that identify interactions?</p> <pre><code>library(httr) library(rrapply) #Code #Code v1 &lt;- httr::GET(&quot;https://rxnav.nlm.nih.gov/REST/interaction/interaction.json&quot;, query=list(rxcui=88014)) #Format cont &lt;- content(v1, as = &quot;parsed&quot;, type = &quot;application/json&quot;) #explicit convertion to data frame o1 &lt;- rrapply(cont$interactionTypeGroup, f = function(x) replace(x, is.null(x), NA), how = 'bind') </code></pre>
[ { "answer_id": 74280677, "author": "Albert Badias", "author_id": 20090804, "author_profile": "https://Stackoverflow.com/users/20090804", "pm_score": 1, "selected": false, "text": "var newRandomColor = Math.floor(Math.random()*16777215).toString(16)\n" }, { "answer_id": 74326790, "author": "Albert Badias", "author_id": 20090804, "author_profile": "https://Stackoverflow.com/users/20090804", "pm_score": 0, "selected": false, "text": "function RGBcolor() {\n var R = Math.floor(Math.random() * 256);\n var G = Math.floor(Math.random() * 256);\n var B = Math.floor(Math.random() * 256);\n var randomcolor = \"rgb(\" + R + \",\" + G + \",\" + B + \")\"; \n console.log(randomcolor);\n}\n\nRGBcolor();\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18747807/" ]
74,280,684
<p>I want to convert the string to color but I can't,</p> <p><strong>My Code</strong></p> <pre><code>String color = &quot;0xffff5252&quot;; Color result= Color(int.parse(color, radix: 16)); print(&quot;$result&quot;); </code></pre> <p>** I get the following problem**</p> <p><code>Invalid radix-16 number (at character 1) 0xffff5252</code></p>
[ { "answer_id": 74280677, "author": "Albert Badias", "author_id": 20090804, "author_profile": "https://Stackoverflow.com/users/20090804", "pm_score": 1, "selected": false, "text": "var newRandomColor = Math.floor(Math.random()*16777215).toString(16)\n" }, { "answer_id": 74326790, "author": "Albert Badias", "author_id": 20090804, "author_profile": "https://Stackoverflow.com/users/20090804", "pm_score": 0, "selected": false, "text": "function RGBcolor() {\n var R = Math.floor(Math.random() * 256);\n var G = Math.floor(Math.random() * 256);\n var B = Math.floor(Math.random() * 256);\n var randomcolor = \"rgb(\" + R + \",\" + G + \",\" + B + \")\"; \n console.log(randomcolor);\n}\n\nRGBcolor();\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12959809/" ]
74,280,697
<p>I am looking for a <code>dplyr</code> way to break variable into multiple columns according to dictionary:</p> <pre><code>vardic &lt;- data.frame(varname=c('a','b','c','d'), length=c(2,6,3,1) ) %&gt;% mutate(end=cumsum(length),start=end-length+1) d &lt;- data.frame(orig_string=c('11333333444A', '22444444111C', '55666666000B')) </code></pre> <p>The desired output is:</p> <pre><code>d2 &lt;- data.frame(a=c(11,22,55),b=c(333333,444444,666666),c=c(444,111,000),d=c('A','C','B') </code></pre> <p>This has to be done using only dplyr commands because this will be implemented via arrow on a larger than memory dataset (<a href="https://stackoverflow.com/questions/74276222/r-arrow-how-to-read-fwf-format-in-r-using-arrow/74279929#74279929">asked in this other question)</a></p> <p>UPDATE (responding to comments): functions outside <code>dplyr</code> could be used, as long as supported by arrow. <a href="https://arrow.apache.org/docs/r/reference/acero.html" rel="nofollow noreferrer">arrow's list of R/dplyr supported functions</a> describes what has been implemented so far. Hopefully this pseudocode illustrates the pipeline:</p> <pre><code>library(tidyverse) library(arrow) d %&gt;% write_dataset('myfile',format='parquet') 'myfile' %&gt;% open_dataset %&gt;% sequence_of_arrowsupported_commands_to_split_columns </code></pre> <p>Update2: added cols indicating <code>start</code> and <code>end</code> position in <code>vardic</code></p> <p>Update3: made the arrow pipeline, above, more reproducible. then tested @akrun's solution. But <code>separate</code> is not supported by <code>arrow</code></p>
[ { "answer_id": 74281176, "author": "Chris Ruehlemann", "author_id": 8039978, "author_profile": "https://Stackoverflow.com/users/8039978", "pm_score": 2, "selected": false, "text": "dplyr" }, { "answer_id": 74281380, "author": "zephryl", "author_id": 17303805, "author_profile": "https://Stackoverflow.com/users/17303805", "pm_score": 1, "selected": false, "text": "# instantiate d2 with nrow(d) rows and 0 columns\nd2 <- d\nd2$orig_string <- NULL\n\nfor (i in seq(to = nrow(vardic))) {\n d2[[vardic$varname[[i]]]] <- substr(\n d$orig_string, \n vardic$start[[i]], \n vardic$end[[i]]\n )\n}\n\nd2\n" }, { "answer_id": 74290896, "author": "LucasMation", "author_id": 3609265, "author_profile": "https://Stackoverflow.com/users/3609265", "pm_score": 3, "selected": true, "text": "arrow" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3609265/" ]
74,280,704
<p>I have a large text file in Python. Firstly, I want to read the text then, delete lines which have only numbers. Then, I open a new text file and write with my changes.</p> <p>If the line contains numbers and strings, I want to keep them. I tried with isdigit and regex but I couldn't...</p> <p>e.g. I tried: but it deletes all lines that contain numbers.</p> <pre><code> if not all(line.isdigit() for line in text_data): </code></pre> <hr /> <p>new question:</p> <p>line1: 324 4234 23456</p> <p>if I have a line which contains numbers and space only like line1, how I skip them to my new text file?</p>
[ { "answer_id": 74280908, "author": "wwii", "author_id": 2823755, "author_profile": "https://Stackoverflow.com/users/2823755", "pm_score": 2, "selected": true, "text": "for line in text_data:\n if line.strip().isdigit():\n # do what is required for a line with all numbers\n else:\n # do what is required for an alphanumeric line\n" }, { "answer_id": 74281436, "author": "Arifa Chan", "author_id": 19574157, "author_profile": "https://Stackoverflow.com/users/19574157", "pm_score": 0, "selected": false, "text": "with open('old.txt') as old, open('new.txt', 'w') as new:\n for line in filter(lambda text: not text.strip().isnumeric(), old): new.write(line)\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20391139/" ]
74,280,707
<p>i would like to switch the colors between the active element on my project, but this way both of them are changing the style on click, how could i fix this? thanks!</p> <pre><code>function Language() { const [style, setStyle] = useState(false); const changeStyle = () =&gt; { setStyle(!style); }; return ( &lt;&gt; &lt;ul className=&quot;lang&quot;&gt; {languages.map(({ code, name, country_code }) =&gt; ( &lt;li key={country_code}&gt; &lt;h4 onClick={() =&gt; {i18next.changeLanguage(code); changeStyle()}} className={style ? &quot;cont&quot; : &quot;cont2&quot;}&gt;{name}&lt;/h4&gt; &lt;/li&gt; ))} &lt;/ul&gt; &lt;/&gt; ); } </code></pre>
[ { "answer_id": 74280908, "author": "wwii", "author_id": 2823755, "author_profile": "https://Stackoverflow.com/users/2823755", "pm_score": 2, "selected": true, "text": "for line in text_data:\n if line.strip().isdigit():\n # do what is required for a line with all numbers\n else:\n # do what is required for an alphanumeric line\n" }, { "answer_id": 74281436, "author": "Arifa Chan", "author_id": 19574157, "author_profile": "https://Stackoverflow.com/users/19574157", "pm_score": 0, "selected": false, "text": "with open('old.txt') as old, open('new.txt', 'w') as new:\n for line in filter(lambda text: not text.strip().isnumeric(), old): new.write(line)\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19691469/" ]
74,280,756
<p>I want to combine the content of multiple objects inside an array that have the same key and join the content in one array.</p> <p>I have the following array of object and I need to join in one array the content key value when I have AT_CALLCENTER or AT_SITE</p> <pre><code>[ { candidateId: 'DEMO-000031', content: 'test', stage: 'AT_CALLCENTER' }, { candidateId: 'DEMO-000031', content: 'test', stage: 'AT_CALLCENTER' }, { candidateId: 'DEMO-000031', content: 'Hello Alex', stage: 'AT_CALLCENTER' }, { candidateId: 'DEMO-000031', content: 'test', stage: 'AT_CALLCENTER' }, { candidateId: 'DEMO-000031', content: 'ttests', stage: 'AT_SITE' }, { candidateId: 'DEMO-000031', content: 'test', stage: 'AT_SITE' }, { candidateId: 'DEMO-000031', content: 'testest', stage: 'AT_SITE' }, { candidateId: 'DEMO-000031', content: 'test', stage: 'AT_SITE' } ] </code></pre> <p>Expected result</p> <pre><code>{ &quot;AT_CALLCENTER&quot;: [&quot;test&quot;, &quot;test&quot;, &quot;Hello Alex&quot;, &quot;test&quot;], &quot;AT_SITE&quot;: [&quot;ttests&quot;, &quot;...&quot;, &quot;...&quot;] } </code></pre> <p>The result above shows that I need to have in one array all the content of the original object under the same key <code>AT_CALLCENTER</code> or <code>AT_SITE</code></p>
[ { "answer_id": 74280908, "author": "wwii", "author_id": 2823755, "author_profile": "https://Stackoverflow.com/users/2823755", "pm_score": 2, "selected": true, "text": "for line in text_data:\n if line.strip().isdigit():\n # do what is required for a line with all numbers\n else:\n # do what is required for an alphanumeric line\n" }, { "answer_id": 74281436, "author": "Arifa Chan", "author_id": 19574157, "author_profile": "https://Stackoverflow.com/users/19574157", "pm_score": 0, "selected": false, "text": "with open('old.txt') as old, open('new.txt', 'w') as new:\n for line in filter(lambda text: not text.strip().isnumeric(), old): new.write(line)\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7882685/" ]
74,280,792
<p>I'm parsing a Uint8 array that is an HTML document. It contains a script tag which in turn contains JSON data that I would like to parse.</p> <p>I first converted the array to text:</p> <pre><code>data = Buffer.from(str).toString('utf8') </code></pre> <p>I then searched for the script tag, and extracted the string containing the JSON:</p> <pre><code>... {\&quot;phrase\&quot;:\&quot;Go to \&quot;California\&quot;\&quot;,\&quot;color\&quot;:\&quot;red\&quot;,\&quot;html\&quot;:\&quot;&lt;div class=\&quot;myclass\&quot;&gt;Ok&lt;/div&gt;\&quot;} ... </code></pre> <p>I then did a replace to clean it up.</p> <pre><code>data = data.replace(/\\&quot;/g, &quot;\&quot;&quot;).replace(/\\/g, &quot;&quot;). {&quot;phrase&quot;:&quot;Go to &quot;California&quot;&quot;,&quot;color&quot;:&quot;red&quot;,&quot;html&quot;:&quot;&lt;div class=&quot;myclass&quot;&gt;Ok&lt;/div&gt;&quot;} </code></pre> <p>I tried to parse using JSON.parse() and got an error because the attributes contain quotes. Is there a way to process this further using a regex ? Or perhaps a library? I am working with Cheerio, so can use that if helpful.</p>
[ { "answer_id": 74280908, "author": "wwii", "author_id": 2823755, "author_profile": "https://Stackoverflow.com/users/2823755", "pm_score": 2, "selected": true, "text": "for line in text_data:\n if line.strip().isdigit():\n # do what is required for a line with all numbers\n else:\n # do what is required for an alphanumeric line\n" }, { "answer_id": 74281436, "author": "Arifa Chan", "author_id": 19574157, "author_profile": "https://Stackoverflow.com/users/19574157", "pm_score": 0, "selected": false, "text": "with open('old.txt') as old, open('new.txt', 'w') as new:\n for line in filter(lambda text: not text.strip().isnumeric(), old): new.write(line)\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11854352/" ]
74,280,800
<p>In my function, I have a parameter a <code>manager: TextManager</code>, but when I try to bind its text to a <code>Binding&lt;String&gt;</code>, it says &quot;Cannot find '$manager' in scope&quot;. Why cannot it find the 'manager', it is right there in the function parameter?</p> <p>The main UI code is the following:</p> <pre><code> struct BugView: View { @ObservedObject var textManager = TextManager(limit: 30) var body: some View { VStack { Text(&quot;line 1&quot;) fetchTextView(title:&quot;Name&quot;, manager: textManager) Text(&quot;line 3&quot;) } } @ViewBuilder private func fetchTextView(title: String, manager : TextManager) -&gt; some View { TextField(title, text: $manager.text) // &lt;- Cannot find '$manager' in scope Text(&quot;\(manager.text.count)/\(manager.characterLimit)&quot;) } } </code></pre> <p>where the <code>TextManager</code> is the following</p> <pre><code>class TextManager: ObservableObject { let characterLimit: Int @Published var text = &quot;&quot; { didSet { if text.count &gt; characterLimit &amp;&amp; oldValue.count &lt;= characterLimit { text = oldValue } } } init(limit: Int = 10) { characterLimit = limit } } </code></pre> <p>I started with this code, and it works fine</p> <pre><code>struct BugView: View { @ObservedObject var textManager = TextManager(limit: 30) var body: some View { VStack { Text(&quot;line 1&quot;) TextField(&quot;good case&quot;, text: $textManager.text) Text(&quot;line 3&quot;) } } } </code></pre> <p>I just want to wrap the some text view generation logic inside a function because I would have multiple of those views, and I would like to avoid code duplication.</p>
[ { "answer_id": 74282416, "author": "BlowMyMind", "author_id": 10349656, "author_profile": "https://Stackoverflow.com/users/10349656", "pm_score": -1, "selected": false, "text": "ObservableObject" }, { "answer_id": 74288560, "author": "Wahid Tariq", "author_id": 18333574, "author_profile": "https://Stackoverflow.com/users/18333574", "pm_score": -1, "selected": false, "text": "struct BugView: View {\n \n @StateObject var textManager = TextManager(limit: 30) // <-- when creating an instance make sure use StateObject\n \n var body: some View {\n VStack {\n Text(\"line 1\")\n \n fetchTextView(title:\"Name\")\n \n Text(\"line 3\")\n }\n }\n \n @ViewBuilder\n private func fetchTextView(title: String) -> some View {\n TextField(title, text: $textManager.text) // <-- just use textManagerDirectly...\n Text(\"\\(textManager.text.count)/\\(textManager.characterLimit)\")\n }\n}\n" }, { "answer_id": 74308163, "author": "malhal", "author_id": 259521, "author_profile": "https://Stackoverflow.com/users/259521", "pm_score": 1, "selected": true, "text": "TextManager" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10349656/" ]
74,280,840
<p>I have a sequence that needs to be an output.. which is 8 so what i did (with a help of a friend of course.. bec i'm not smart and have adhd.. is this:</p> <pre><code>let a = 1; let b = 1; let c = a + b; a = b; // 1 b = c; // 2 c = a + b; // 3 a = b; // a = 2 b = c; // b = 3 c = a + b; // 2 + 3 = 5 c = 5 </code></pre> <p>what i need next, is to make a for loop, that will calculate it to 8 (perform the exact same calc task as above <code>(a = b and b = c and c = a + b)</code></p> <p>to make the function get print an output of 8..</p> <pre><code>let a = 1; let b = 1; let c = a + b; a = b; // 1 b = c; // 2 c = a + b; // 3 a = b; // a = 2 b = c; // b = 3 c = a + b; // 2 + 3 = 5 c = 5 function calc () { for (let i=0; i&lt;= ( ? ? ? ? ? ?); i++){ console.log(i); } } calc() </code></pre>
[ { "answer_id": 74280934, "author": "Alexey Zelenin", "author_id": 6290921, "author_profile": "https://Stackoverflow.com/users/6290921", "pm_score": 1, "selected": false, "text": "function calc () {\n for (let a = 0, b = 1, c = 0; c < 8;) {\n c = a + b;\n a = b;\n b = c;\n console.log(c);\n }\n}\ncalc();" }, { "answer_id": 74281027, "author": "Tom", "author_id": 8851732, "author_profile": "https://Stackoverflow.com/users/8851732", "pm_score": 0, "selected": false, "text": "\nfunction calc() {\n // We need to hard-code the first two numbers in the sequence to get started\n let a = 1;\n let b = 1;\n console.log(a);\n console.log(b);\n\n // If we do 4 loops, the last value printed will be 8\n for (let i = 0; i < 4; i++) {\n let c = a + b\n console.log(c);\n // Shift a and b along the sequence\n // a gets the value held by b, and b gets the value held by c\n a = b\n b = c\n }\n}\ncalc();\n" }, { "answer_id": 74281081, "author": "Carsten Massmann", "author_id": 2610061, "author_profile": "https://Stackoverflow.com/users/2610061", "pm_score": 0, "selected": false, "text": "a" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20386686/" ]
74,280,849
<pre><code># Initialized list of cities CitiesInMichigan = [&quot;Acme&quot;, &quot;Albion&quot;, &quot;Detroit&quot;, &quot;Watervliet&quot;, &quot;Coloma&quot;, &quot;Saginaw&quot;, &quot;Richland&quot;, &quot;Glenn&quot;, &quot;Midland&quot;, &quot;Brooklyn&quot;] # Get user input inCity = input(&quot;Enter name of city: &quot;) # Write your test statement here to see if there is a match. for i in range(len(CitiesInMichigan)): if CitiesInMichigan[i] == inCity: while CitiesInMichigan is True: print(&quot;City found. &quot;) break else: print(&quot;Not a city in Michigan. &quot;) input(&quot;Enter name of city: &quot;) # If the city is found, print &quot;City found.&quot; # Otherwise, &quot;Not a city in Michigan&quot; message should be printed. </code></pre> <p>So what I am trying to go for was to have the input case insensitive so (Acme, ACME, acMe, etc.) would work and to have it break if input matches or try again if input is false. Instead I have been receiving that all inputs are not a city of Michigan. What am I doing wrong?</p> <p><em>P.S</em> I am studying python for school and as a passion, I am still new and wrapping my head around it please criticize anything I do wrong to further improve my codings. Thank you</p>
[ { "answer_id": 74280982, "author": "Ben Borchard", "author_id": 4054720, "author_profile": "https://Stackoverflow.com/users/4054720", "pm_score": 1, "selected": false, "text": "while" }, { "answer_id": 74281085, "author": "AudioBaton", "author_id": 19373112, "author_profile": "https://Stackoverflow.com/users/19373112", "pm_score": 1, "selected": false, "text": "while" }, { "answer_id": 74281170, "author": "Kungfu panda", "author_id": 15349625, "author_profile": "https://Stackoverflow.com/users/15349625", "pm_score": 0, "selected": false, "text": "CitiesInMichigan = [\"Acme\", \"Albion\", \"Detroit\", \"Watervliet\", \"Coloma\", \"Saginaw\", \"Richland\", \"Glenn\", \"Midland\",\n \"Brooklyn\"]\nCitiesInMichigan_casefold = [i.casefold() for i in CitiesInMichigan ]\ninCity = input(\"Enter name of city: \")\nwhile True:\n if inCity.casefold() in CitiesInMichigan_casefold:\n print(\"city found\",inCity)\n break\n else:\n print(\"city not found\")\n inCity = input(\"Enter name of city again: \")\n\nTry this. you have to compare case fold strings both in input and as well as from the mentioned list.\nif the city is found, it prints city name and breaks the loop.\nelse it continues until the city is matched.\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20170723/" ]
74,280,854
<p>I have a table with this kind of data for vehicles (with more rows).<br /> ** <a href="https://i.stack.imgur.com/2Q0cT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2Q0cT.png" alt="enter image description here" /></a></p> <p>So far I got a boxplot using car segments as categories and pricing for the Y-axis, however I added the points with geom_jitter but like to colour them according to the region, so getting two colours for either Europe or China. As of now, the points have the same colour as the boxes and I am not sure about how to input the &quot;region&quot; category colour.</p> <p>Here's the code I used so far</p> <pre><code>Boxplot_data%&gt;% ggplot(aes(Segment, Price, colour=Segment))+ geom_boxplot()+ geom_jitter( alpha=0.5 ) </code></pre> <p><strong>your text</strong></p> <p>I tried using a few different ways to obtain the coloured points according to the Region category, but none worked.</p>
[ { "answer_id": 74280982, "author": "Ben Borchard", "author_id": 4054720, "author_profile": "https://Stackoverflow.com/users/4054720", "pm_score": 1, "selected": false, "text": "while" }, { "answer_id": 74281085, "author": "AudioBaton", "author_id": 19373112, "author_profile": "https://Stackoverflow.com/users/19373112", "pm_score": 1, "selected": false, "text": "while" }, { "answer_id": 74281170, "author": "Kungfu panda", "author_id": 15349625, "author_profile": "https://Stackoverflow.com/users/15349625", "pm_score": 0, "selected": false, "text": "CitiesInMichigan = [\"Acme\", \"Albion\", \"Detroit\", \"Watervliet\", \"Coloma\", \"Saginaw\", \"Richland\", \"Glenn\", \"Midland\",\n \"Brooklyn\"]\nCitiesInMichigan_casefold = [i.casefold() for i in CitiesInMichigan ]\ninCity = input(\"Enter name of city: \")\nwhile True:\n if inCity.casefold() in CitiesInMichigan_casefold:\n print(\"city found\",inCity)\n break\n else:\n print(\"city not found\")\n inCity = input(\"Enter name of city again: \")\n\nTry this. you have to compare case fold strings both in input and as well as from the mentioned list.\nif the city is found, it prints city name and breaks the loop.\nelse it continues until the city is matched.\n" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16192496/" ]
74,280,891
<p>Im want to obtain the each coordinate, long and lat, but all data are in the same cell. The idea is put each coordeante in a diferent colums.</p> <p>Im create number variable but dont get all number of Store Location.</p> <pre><code>liquor2 &lt;- structure(list(`Store Location` = c(&quot; -93.619455 42.022848&quot;, &quot; -93.669896 42.02160500000001&quot;, &quot; -93.669896 42.02160500000001&quot;, NA, NA, &quot; -93.618911 42.022854&quot;, &quot; -93.669896 42.02160500000001&quot;, &quot; -93.619455 42.022848&quot;, &quot; -93.669896 42.02160500000001&quot;, NA, &quot; -93.669896 42.02160500000001&quot;, NA, &quot; -93.618911 42.022854&quot;, NA, &quot; -93.618911 42.022854&quot;, NA, &quot; -93.669896 42.02160500000001&quot;, &quot; -93.669896 42.02160500000001&quot;, &quot; -93.610343 42.017115&quot;, &quot; -93.618911 42.022854&quot; )), row.names = c(NA, -20L), class = c(&quot;tbl_df&quot;, &quot;tbl&quot;, &quot;data.frame&quot; )) ### Run this code but only obtained long data liquor2 %&gt;% mutate(number= as.numeric(parse_number(`Store Location`)), long=str_sub(number,1,10), lat=str_sub(number, 11,13)) %&gt;% View() # `Store Location` number long lat # &lt;chr&gt; &lt;dbl&gt; &lt;chr&gt; &lt;chr&gt; # 1 &quot; -93.619455 42.022848&quot; -93.6 -93.619455 &quot;&quot; # 2 &quot; -93.669896 42.02160500000001&quot; -93.7 -93.669896 &quot;&quot; # 3 &quot; -93.669896 42.02160500000001&quot; -93.7 -93.669896 &quot;&quot; # 4 NA NA NA NA # 5 NA NA NA NA # 6 &quot; -93.618911 42.022854&quot; -93.6 -93.618911 &quot;&quot; # 7 &quot; -93.669896 42.02160500000001&quot; -93.7 -93.669896 &quot;&quot; # 8 &quot; -93.619455 42.022848&quot; -93.6 -93.619455 &quot;&quot; # 9 &quot; -93.669896 42.02160500000001&quot; -93.7 -93.669896 &quot;&quot; # 10 NA NA NA NA # 11 &quot; -93.669896 42.02160500000001&quot; -93.7 -93.669896 &quot;&quot; # 12 NA NA NA NA # 13 &quot; -93.618911 42.022854&quot; -93.6 -93.618911 &quot;&quot; # 14 NA NA NA NA # 15 &quot; -93.618911 42.022854&quot; -93.6 -93.618911 &quot;&quot; # 16 NA NA NA NA # 17 &quot; -93.669896 42.02160500000001&quot; -93.7 -93.669896 &quot;&quot; # 18 &quot; -93.669896 42.02160500000001&quot; -93.7 -93.669896 &quot;&quot; # 19 &quot; -93.610343 42.017115&quot; -93.6 -93.610343 &quot;&quot; # 20 &quot; -93.618911 42.022854&quot; -93.6 -93.618911 &quot;&quot; # </code></pre>
[ { "answer_id": 74281061, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 3, "selected": true, "text": "tidyr::separate" }, { "answer_id": 74283000, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 1, "selected": false, "text": "base R" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15449339/" ]
74,280,902
<p>First off, I always like to post runnable examples, but since this is a mix of js and server side rendered liquid on shopify I can't get a running example.</p> <p>In shopify, you can access the <code>product</code> object like so <code>{{ product }}</code> from the product template.</p> <p>The cart object has an <code>items</code> property which is an array of all the items in the cart. Each <code>item</code> object in the cart differs from the <code>product</code> object. The <code>product</code> object has a list of variants, the cart <code>item</code> object does not.</p> <p>The purpose of this is to be able to edit the size of an item in the cart.</p> <p>My question is, how would you be able to get all the linked variants? You would have to move up to the product and get a list of all the variants there, from the variant by it's <code>product_id</code>.</p> <p>The reason this is tricky is because when you get the fetch response of the cart object, you get a <code>product_id</code> for each <code>item</code> in the cart. You can't get the product object though unless you are on the product page.</p> <p>Just to help visualize the cart is something like this:</p> <pre class="lang-js prettyprint-override"><code>{ items: [ { handle: 'product-handle', product_id: 123, variant_title: 'product variant' } ] } </code></pre> <p>what needs to be accomplished is:</p> <pre class="lang-js prettyprint-override"><code>{ items: [ { handle: 'product-handle', product_id: 123, /** * to get this you need first access to the product object from the product * template. You could convert the product to json with a filter * e.g. const product = {{ product | json }} but you don't have the * opportunity to be on the product template each time you edit a cart item */ variants: [ { color: 'white', size: 's' }, { color: 'white', size: 'm' } ] } ] } </code></pre>
[ { "answer_id": 74281061, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 3, "selected": true, "text": "tidyr::separate" }, { "answer_id": 74283000, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 1, "selected": false, "text": "base R" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17422582/" ]
74,280,939
<p>I am trying to filter the ID's that has at least one observation in both pre period and post period each. For example, I select ID 1 as that has pre1,2 and post 1, also ID 3 for the same reason. But, ID2,5 does not have post period observations and ID4 does not have pre period observations so those ID's(2, 4, and 5) are dropped.</p> <p>I am currently divide the sample into pre and post parts and merge them by intersection using merge(pre, post, by='ID', all=FALSE). However, it gives me wrong result so I was wondering if there is other ways to do this. I would appreciate it if you help me with this. Thank you!</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Year</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>pre1</td> </tr> <tr> <td>1</td> <td>pre2</td> </tr> <tr> <td>1</td> <td>post1</td> </tr> <tr> <td>2</td> <td>pre2</td> </tr> <tr> <td>2</td> <td>pre3</td> </tr> <tr> <td>3</td> <td>pre1</td> </tr> <tr> <td>3</td> <td>post1</td> </tr> <tr> <td>4</td> <td>post2</td> </tr> <tr> <td>4</td> <td>post3</td> </tr> <tr> <td>5</td> <td>pre1</td> </tr> <tr> <td>5</td> <td>pre2</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74281061, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 3, "selected": true, "text": "tidyr::separate" }, { "answer_id": 74283000, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 1, "selected": false, "text": "base R" } ]
2022/11/01
[ "https://Stackoverflow.com/questions/74280939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15429827/" ]