qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,480,941
<p>I have two functions, and both can return an empty string, so what is the best practice to save memory and avoid duplicated .txt empty string?</p> <p><strong>Example</strong></p> <pre><code>const char* function_one() { return &quot;&quot;; } const char* function_two() { return &quot;&quot;; } int main() { printf(&quot;One: %s\n&quot;, function_one()); printf(&quot;Two: %s\n&quot;, function_two()); } </code></pre> <p><strong>Is this optimization correct ?</strong></p> <pre><code>const char* empty = &quot;&quot;; const char* function_one() { return empty; } const char* function_two() { return empty; } int main() { printf(&quot;One: %s\n&quot;, function_one()); printf(&quot;Two: %s\n&quot;, function_two()); } </code></pre>
[ { "answer_id": 74481042, "author": "Vlad from Moscow", "author_id": 2877241, "author_profile": "https://Stackoverflow.com/users/2877241", "pm_score": 3, "selected": true, "text": "const char* function_one() {\n return \"\";\n}\nconst char* function_two() {\n return \"\";\n}\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20292772/" ]
74,480,957
<p>I am trying to group and summarise a pandas dataframe into a single column</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">ID</th> <th style="text-align: center;">LayerName</th> <th style="text-align: right;">Name</th> <th style="text-align: right;">Count</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">A</td> <td style="text-align: center;">SC</td> <td style="text-align: right;">B</td> <td style="text-align: right;">2</td> </tr> <tr> <td style="text-align: left;">A</td> <td style="text-align: center;">SC</td> <td style="text-align: right;">R</td> <td style="text-align: right;">8</td> </tr> <tr> <td style="text-align: left;">A</td> <td style="text-align: center;">BLD</td> <td style="text-align: right;">S</td> <td style="text-align: right;">7</td> </tr> <tr> <td style="text-align: left;">A</td> <td style="text-align: center;">BLD</td> <td style="text-align: right;">K</td> <td style="text-align: right;">6</td> </tr> </tbody> </table> </div> <p>I will like the resulting table to be summarised by the LayerName, Name and Count into a single output field like thi</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">ID</th> <th style="text-align: center;">Output</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">A</td> <td style="text-align: center;">10 - SC : (B,R) ; 13 - BLD : (S,K)</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74481041, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": true, "text": "groupby.agg" }, { "answer_id": 74481190, "author": "d.b", "author_id": 7128934, "author_profile": "https://Stackoverflow.com/users/7128934", "pm_score": 0, "selected": false, "text": "df.groupby([\"ID\", \"LayerName\"], sort=False).\\\napply(lambda x: f\"{x.Count.sum()} - {x.LayerName.iloc[0]}: ({','.join(x.Name.to_list())})\").\\\nstr.cat(sep=\"; \")\n# '10 - SC: (B,R); 13 - BLD: (S,K)'\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6768849/" ]
74,480,960
<p>I am trying to parse the array value from the response of one request and pass it to another request.From one api I get the response as : {&quot;id&quot;:95,&quot;email&quot;:&quot;Test_rider_00002@popup.com&quot;,&quot;firstname&quot;:&quot;test&quot;,&quot;lastname&quot;:&quot;rider&quot;,&quot;phoneNumber&quot;:&quot;9999990002&quot;,&quot;phoneNumberVerified&quot;:true,&quot;emailVerified&quot;:true,&quot;address&quot;:{&quot;address&quot;:&quot;2400 Perimeter Rd, Auburn, WA 98001, USA&quot;,&quot;zipCode&quot;:&quot;98001&quot;},&quot;dateOfBirth&quot;:&quot;2000-10-05&quot;,&quot;gender&quot;:&quot;UNKNOWN&quot;,&quot;fullName&quot;:&quot;test rider&quot;,&quot;enabled&quot;:true,&quot;isDriver&quot;:false,&quot;avatars&quot;:[{&quot;id&quot;:131,&quot;type&quot;:&quot;RIDER&quot;,&quot;active&quot;:true}]}</p> <p>I need to use the id from the avatars array in the next request .But ,I am unable to do so using the pre and post processors .</p> <p>I have tried using the JSON Extractor,JSR223 Processor and RegEx extractor but to no use.</p>
[ { "answer_id": 74481041, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": true, "text": "groupby.agg" }, { "answer_id": 74481190, "author": "d.b", "author_id": 7128934, "author_profile": "https://Stackoverflow.com/users/7128934", "pm_score": 0, "selected": false, "text": "df.groupby([\"ID\", \"LayerName\"], sort=False).\\\napply(lambda x: f\"{x.Count.sum()} - {x.LayerName.iloc[0]}: ({','.join(x.Name.to_list())})\").\\\nstr.cat(sep=\"; \")\n# '10 - SC: (B,R); 13 - BLD: (S,K)'\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20509925/" ]
74,480,966
<p>i created a function to count the value of a blackjack hand with a for loop but it keep telling me that the index is out of range and i can't figure out why</p> <p>i tried switching from &quot;for card in total_cards&quot; to a &quot;for card in range(0, len(total_cards))&quot; hoping that that would solve my problem, but i keep getting the same error. Since both errors seems to originate from the function, what am i missing here? Thank you all in advance.</p> <pre><code>import random def count_total(total_cards): total = 0 for card in total_cards: total += total_cards[card] return total cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] house_cards = [] player_cards = [] for i in range (1, 5): if i % 2 == 0: player_cards.append(cards[random.randint(0, len(cards) - 1)]) elif i % 2 != 0: house_cards.append(cards[random.randint(0, len(cards) - 1)]) print(house_cards) print(player_cards) should_continue = True while should_continue: action = input(&quot;Typr 'y' to ask for a card or 'n' to stop: &quot;) if action == &quot;n&quot;: should_continue = False break elif action == &quot;y&quot;: player_cards.append(cards[random.randint(0, len(cards) - 1)]) count_total(player_cards) if count_total(player_cards) &gt; 21: should_continue = False print(&quot;You have gone over 21, you lost!&quot;) break </code></pre>
[ { "answer_id": 74481001, "author": "Woodford", "author_id": 8451814, "author_profile": "https://Stackoverflow.com/users/8451814", "pm_score": 3, "selected": true, "text": "for card in total_cards:\n total += total_cards[card]\n" }, { "answer_id": 74481055, "author": "sentinel_33", "author_id": 19553215, "author_profile": "https://Stackoverflow.com/users/19553215", "pm_score": 2, "selected": false, "text": "for card in total_cards:\n total += total_cards[card]\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20494293/" ]
74,480,998
<p>Write a function named <code>place_random_bricks(m, n, colours)</code> that randomly places bricks row-wise (completes the current row placement before moving to the next row) on the baseplate.</p> <p>It must have three parameters:</p> <ul> <li><code>m</code> - the number of rows on the base-plate,</li> <li><code>n</code> - the number of columns on the base-plate, and</li> <li><code>colours</code> - a random string constructed over “G, R, B, Y, C” (G-Green, R-Red, Blue-B, Y-Yellow, C-Cyan).</li> </ul> <p>This function should return a string of length <code>m * n</code>, where a character at any position <code>i</code> represents the colour of a brick placed on the baseplate <code>(0 ≤ i &lt; (m x n), i ∈ “colours′′);</code> a value “G” (Green colour) represents no brick was placed.</p> <p>All colours have an equal probability of being selected.</p> <pre><code>import random import colorama import string def place_random_bricks(m, n, colours): v_string=['G', 'R', 'B', 'Y', 'C'] for i in range(m * n): colours = string.ascii_uppercase a = print(''.join(random.choices(colours))) </code></pre> <p>I am expecting a random number of RYBCG.</p>
[ { "answer_id": 74481001, "author": "Woodford", "author_id": 8451814, "author_profile": "https://Stackoverflow.com/users/8451814", "pm_score": 3, "selected": true, "text": "for card in total_cards:\n total += total_cards[card]\n" }, { "answer_id": 74481055, "author": "sentinel_33", "author_id": 19553215, "author_profile": "https://Stackoverflow.com/users/19553215", "pm_score": 2, "selected": false, "text": "for card in total_cards:\n total += total_cards[card]\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20359366/" ]
74,481,029
<p>I have a scenario such as follows and cannot get my <code>SpecificApi</code> service to register.</p> <pre><code> public interface IDetail { string Name { get; set;} } public class SpecificDetail : IDetail { public string Name { get; set; } } public interface IBaseApi&lt;TDetail&gt; where TDetail: IDetail { TDetail Method1(); } public interface ISpecificApi&lt;TDetail&gt; : IBaseApi&lt;TDetail&gt; where TDetail : IDetail { } public class SpecificApi : ISpecificApi&lt;SpecificDetail&gt; { public SpecificDetail Method1() { return new SpecificDetail(); } } public class Consumer { public Consumer(ISpecificApi&lt;IDetail&gt; api) // Generic must be of IDetail, not SpecificDetail { } } </code></pre> <p>I've tried the following to register the service, but with no luck.</p> <pre><code>// Fails at runtime with System.ArgumentException: 'Open generic service type 'DiGenericsTest.ISpecificApi`1[TDetail]' requires registering an open generic implementation type. (Parameter 'descriptors')' builder.Services.AddSingleton(typeof(ISpecificApi&lt;&gt;), typeof(SpecificApi)); // Fails at build time with &quot;there is no implicit reference conversion&quot; builder.Services.AddSingleton&lt;ISpecificApi&lt;IDetail&gt;, SpecificApi&gt;(); // This runs, but then I have to inject ISpecificApi&lt;SpecificDetail&gt; into Consumer instead of ISpecificApi&lt;IDetail&gt;. builder.Services.AddSingleton&lt;ISpecificApi&lt;SpecificDetail&gt;, SpecificApi&gt;(); builder.Services.AddSingleton&lt;Consumer&gt;(); </code></pre>
[ { "answer_id": 74481551, "author": "Yevhen Cherkes", "author_id": 7901167, "author_profile": "https://Stackoverflow.com/users/7901167", "pm_score": 2, "selected": false, "text": "public interface IBaseApi<out TDetail> where TDetail : IDetail\n{\n TDetail Method1();\n}\n\npublic interface ISpecificApi<out TDetail> : IBaseApi<TDetail> where TDetail : IDetail\n{\n\n}\n" }, { "answer_id": 74482741, "author": "Chris Schaller", "author_id": 1690217, "author_profile": "https://Stackoverflow.com/users/1690217", "pm_score": 2, "selected": true, "text": "SpecificDetail" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3165621/" ]
74,481,054
<p>I have one query which return correct results for the parameters that are there but not what the goal is.</p> <p>There are two columns <code>month</code> and <code>year</code>. What I want is when I choose from dropdowns:</p> <p>4/2020 to 12/2022 to return everything after month 4 of 2020 till month 12 of 2022. Currently, when I choose 4/2020 to 12/2022 it returns everything but removes months up to 4th from each year.</p> <p>Example when the query is 1/2020 to 12/2022:</p> <pre><code>country_id rate month year value 160 1.60 3 2020 1.4 160 1.30 9 2020 1.4 160 1.2983 3 2021 1.4 160 NULL 3 2022 2 160 NULL 6 2022 1.4 </code></pre> <p>When I run the query 4/2020 to 12/2022 the result is</p> <pre><code>country_id rate month year value 160 1.30 9 2020 1.4 160 NULL 6 2022 1.4 </code></pre> <p>but it must be</p> <pre><code>country_id rate month year value 160 1.30 9 2020 1.4 160 1.2983 3 2021 1.4 160 NULL 3 2022 2 160 NULL 6 2022 1.4 </code></pre> <p>Here is the query which shows all the results</p> <pre><code>SELECT r.country_id, r.rate as rate, r.month, d.country_id, d.year, d.month as value FROM `data_prod` d INNER JOIN monthly_data r ON r.country_id = d.country_id AND r.year=d.year AND r.month=d.month WHERE d.country_id IN (160) AND d.year BETWEEN 2020 AND 2022 AND r.year BETWEEN 2020 AND 2022 AND d.month BETWEEN 1 AND 12 ORDER BY d.year, d.month </code></pre> <p>The query which removes up to 4th month (in this case) from each year</p> <pre><code>SELECT r.country_id, r.rate as rate, r.month, d.country_id, d.year, d.month as value FROM `data_prod` d INNER JOIN monthly_data r ON r.country_id = d.country_id AND r.year=d.year AND r.month=d.month WHERE d.country_id IN (160) AND d.year BETWEEN 2020 AND 2022 AND r.year BETWEEN 2020 AND 2022 AND d.month BETWEEN 4 AND 12 ORDER BY d.year, d.month </code></pre> <p>Here is the php part</p> <pre><code>$countryIds = $countries; $month_clause = &quot;AND d.month BETWEEN $selectedStartMonth AND $selectedEndMonth&quot;; $query = &quot;SELECT r.country_id, r.rate as rate, r.month, d.country_id, d.year, d.month as value FROM `data_prod` d INNER JOIN monthly_data r ON r.country_id = d.country_id AND r.year=d.year AND r.month=d.month WHERE d.country_id IN (&quot;.implode(&quot;,&quot;,$countryIds).&quot;) AND d.year BETWEEN $periodStart AND $periodEnd AND r.year BETWEEN $periodStart AND $periodEnd $month_clause ORDER BY d.year, d.month&quot;; </code></pre> <p>Can anyone help a bit here?</p>
[ { "answer_id": 74481347, "author": "Luuk", "author_id": 724039, "author_profile": "https://Stackoverflow.com/users/724039", "pm_score": 3, "selected": true, "text": "SELECT r.country_id, r.rate as rate, r.month, d.country_id, d.year, d.month as value \nFROM `data_prod` d \nINNER JOIN monthly_data r ON r.country_id = d.country_id \n AND r.year=d.year AND r.month=d.month \nWHERE d.country_id IN (160) \nAND ((d.year=2020 and d.month>=4) OR\n (d.year>2020 and d.year<2022) OR\n (d.year=2022 and d.month<=12))\nORDER BY d.year, d.month\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20263317/" ]
74,481,064
<p>I'm trying to search and replace string from a yaml file that I use for helm values. I have used the following command to extract the values that are different between two files:</p> <pre><code>diff a.yaml b.yaml|grep &quot;&gt;&quot;|cut -c 3- &gt; new_file.yaml </code></pre> <p>The a.yaml file contains the following lines:</p> <pre><code>NAME_VAR: {{ .Data.data.name_var }} SOME_VALUE: {{ .Data.data.some_value }} ONE_MORE: {{ .Data.data.one_more }} </code></pre> <p>and b.yaml this:</p> <pre><code>NAME_VAR: {{ .Data.data.name_var }} SOME_VALUE: {{ .Data.data.some_value }} ONE_MORE: {{ .Data.data.one_more }} ADD_THIS: {{ .Data.data.&lt;change_me&gt; }} </code></pre> <p>The output in new_file.yaml gives me the following:</p> <pre><code>ADD_THIS: {{ .Data.data.&lt;change_me&gt; }} </code></pre> <p>I need to replace the string inside &lt;change_me&gt; with the key of the output &quot;ADD_THIS&quot; it should look like this:</p> <pre><code>ADD_THIS: {{ .Data.data.add_this }} </code></pre> <p>These changes will be updated with vault later automatically in argocd.</p> <p>I've thought about using awk but I can't seem to replace it.....</p> <p><strong>Edit</strong></p> <p>In case you want to replace several fields, e.g.</p> <p>a.yaml file</p> <pre><code>NAME_VAR: {{ .Data.data.name_var }} SOME_VALUE: {{ .Data.data.some_value }} ONE_MORE: {{ .Data.data.one_more }} </code></pre> <p>b.yaml file</p> <pre><code>NAME_VAR: {{ .Data.data.name_var }} SOME_VALUE: {{ .Data.data. }} ONE_MORE: {{ .Data.data. }} ADD_THIS: {{ .Data.data. }} </code></pre> <p>Using James' answer this is the output:</p> <pre><code>ADD_THIS: {{ .Data.data.add_this }} SOME_VALUE: {{ .Data.data.some_value }} ONE_MORE: {{ .Data.data.one_more }} SOME_VALUE: {{ .Data.data.some_value }} ONE_MORE: {{ .Data.data.one_more }} </code></pre>
[ { "answer_id": 74481203, "author": "Gilles Quenot", "author_id": 465183, "author_profile": "https://Stackoverflow.com/users/465183", "pm_score": 2, "selected": false, "text": "$ sed 's/<change_me>/add_this/' file\nADD_THIS: {{ .Data.data.add_this }}\n" }, { "answer_id": 74481266, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 1, "selected": false, "text": "$ awk '{str = tolower($1)\n sub(\":\", \"\", str)\n sub(\"<change_me>\", str, $0)}1' new_file.yaml\nADD_THIS: {{ .Data.data.add_this }}\n" }, { "answer_id": 74481481, "author": "Dave Pritlove", "author_id": 2005666, "author_profile": "https://Stackoverflow.com/users/2005666", "pm_score": 1, "selected": false, "text": "echo \"ADD_THIS: {{ .Data.data.<change_me> }}\" | awk ' {n=split($3,parts,\".\"); sub(parts[n],tolower($1), $3); print $0} ';\n" }, { "answer_id": 74481491, "author": "James Brown", "author_id": 4162356, "author_profile": "https://Stackoverflow.com/users/4162356", "pm_score": 3, "selected": true, "text": "diff" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9960678/" ]
74,481,067
<p>I have the following PySpark dataframe:</p> <pre><code>df = spark.createDataFrame( [ ('31,2', 'foo'), ('33,1', 'bar'), ], ['cost', 'label'] ) </code></pre> <p>I need to cast the ´cost´ column to float. I do it as follows:</p> <pre><code>df = df.withColumn('cost', df.cost.cast('float')) </code></pre> <p>However, as I result I get <code>null</code> values instead of numbers in the <code>cost</code> column.</p> <p>How can I convert <code>cost</code> to float numbers?</p>
[ { "answer_id": 74481361, "author": "CharlieBONS", "author_id": 20529340, "author_profile": "https://Stackoverflow.com/users/20529340", "pm_score": 3, "selected": true, "text": "df = (df.withColumn('cost', F.regexp_replace(df.cost, ',', '.')\n .withColumn('cost', df.cost.cast('float')))\n\n" }, { "answer_id": 74483156, "author": "Ben Y", "author_id": 9005114, "author_profile": "https://Stackoverflow.com/users/9005114", "pm_score": 1, "selected": false, "text": " df.loc[:, 'cost'] = df.cost.apply(lambda x: float(x.replace(',', '.')))\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11622712/" ]
74,481,090
<p>I need to know the way to get the users of a specific group through the REST API of Azure DevOps Server 2022, that is, <strong>on-premise</strong>. We are going to use as an example url 192.168.0.1 and the DefaultCollection as practice purposes. I have searched the documentation but when I try to apply them in my case they don't work for me, I get a 404 Not Found.</p> <p>For now I am doing:</p> <p><a href="http://192.168.0.1:8080/tfs/_apis/groupentitlements?api-version=6.0-preview.1" rel="nofollow noreferrer">http://192.168.0.1:8080/tfs/_apis/groupentitlements?api-version=6.0-preview.1</a> <a href="http://192.168.0.1:8080/tfs/DefaultCollection/_apis/groupentitlements?api-version=6.0-preview.1" rel="nofollow noreferrer">http://192.168.0.1:8080/tfs/DefaultCollection/_apis/groupentitlements?api-version=6.0-preview.1</a></p> <p>Neither seems to work. They throw 404.</p> <p>I don't know if it has something to do with it, but I was reading on this <a href="https://michaelmaillot.github.io/tips/20210914-azdo-project-admin-members-programmatically/" rel="nofollow noreferrer">website</a> that a &quot;vsaex&quot; prefix is used for groupentitlements, &quot;vssps&quot; for graph and &quot;status&quot; for status, so I tried the following: <a href="http://vsaex.192.168.0.1:8080/tfs/_apis/groupentitlements?api-version=6.0-preview.1" rel="nofollow noreferrer">http://vsaex.192.168.0.1:8080/tfs/_apis/groupentitlements?api-version=6.0-preview.1</a> <a href="http://vsaex.192.168.0.1:8080/tfs/DefaultCollection/_apis/groupentitlements?api-version=6.0-preview.1" rel="nofollow noreferrer">http://vsaex.192.168.0.1:8080/tfs/DefaultCollection/_apis/groupentitlements?api-version=6.0-preview.1</a></p> <p>Again, neither seems to work.</p> <p>Also I tried differents api-versions, or without using any of them. I don't have any trouble using other parts of the REST API, e.g.: I can get Projects of a collection, Teams by Project, etc. and they work fine.</p>
[ { "answer_id": 74481361, "author": "CharlieBONS", "author_id": 20529340, "author_profile": "https://Stackoverflow.com/users/20529340", "pm_score": 3, "selected": true, "text": "df = (df.withColumn('cost', F.regexp_replace(df.cost, ',', '.')\n .withColumn('cost', df.cost.cast('float')))\n\n" }, { "answer_id": 74483156, "author": "Ben Y", "author_id": 9005114, "author_profile": "https://Stackoverflow.com/users/9005114", "pm_score": 1, "selected": false, "text": " df.loc[:, 'cost'] = df.cost.apply(lambda x: float(x.replace(',', '.')))\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15665766/" ]
74,481,137
<p>I am having trouble getting this to work and any help would be greatly appreciated. I want to have a variable number of nested for loops for the following code. The idea is to write every combination possible to a csv file.</p> <p>here is my code: `</p> <pre><code>ka = [0.217, 0.445] kb = [0.03, 0.05] kc = [10] kd = [0.15625, 0.7] ke = [1.02, 0.78] La = [0.15, 0.25] Lb = [0.025, 0.075] tc = [0.002, 0.007] Ld = [0.025, 0.115] Le = [0.07, 0.2] NUMBER_OF_VARIABLES = 10 with open('test.csv', 'w') as file: writer = csv.writer(file, lineterminator = '\n') row = [0] * len(NUMBER_OF_VARIABLES) for E in Le: for D in Ld: for C in tc: for B in Lb: for A in La: for e in ke: for d in kd: for c in kc: for b in kb: for a in ka: row[0] = a row[1] = b row[2] = c row[3] = d row[4] = e row[5] = A row[6] = B row[7] = C row[8] = D row[9] = E writer.writerow(row) </code></pre> <p>` the idea is I would like to be able to add more or remove variables. the k and L of each letter are related. For example to add another variable would include a Lf and kf. I would like to do it without manually adding more loops. The variable structure does not have to remain if it would be better to make it one list.</p> <p>I feel like I need to write a recursive function but am having trouble figuring this out, any help would be greatly appreciated.</p> <p>I have tried importing a csv file where each line has a variable but can not figure out the variable number of for loops.</p>
[ { "answer_id": 74481178, "author": "jsbueno", "author_id": 108205, "author_profile": "https://Stackoverflow.com/users/108205", "pm_score": 0, "selected": false, "text": "itertools.product" }, { "answer_id": 74481181, "author": "Tim Roberts", "author_id": 1883316, "author_profile": "https://Stackoverflow.com/users/1883316", "pm_score": 2, "selected": true, "text": "itertools.product" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20533394/" ]
74,481,166
<p>i created my own component that contains 2 inputs(type: range, number). I want to hide one of them after another checkbox is clicked but getElementById is returning null.</p> <p>Error</p> <p><a href="https://i.stack.imgur.com/wp5Z8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wp5Z8.png" alt="enter image description here" /></a></p> <p>This is in one js file</p> <pre><code>customElements.define(&quot;my-component&quot;,MyComponent); document.getElementById('check').addEventListener(&quot;click&quot;, hideComponent, false); function hideComponent() { if(document.getElementById('check').checked) { document.getElementById('inp').style.display = 'none'; document.getElementById('slider').style.display = ''; } else { document.getElementById('inp').style.display = ''; document.getElementById('slider').style.display = 'none'; } } </code></pre> <p>This is my custom Element</p> <pre><code>export class MyComponent extends HTMLElement { constructor(){ super(); this.attachShadow({mode: &quot;open&quot;}); const wrapper = document.createElement(&quot;div&quot;); wrapper.setAttribute(&quot;class&quot;,&quot;wrapper&quot;); const slider = wrapper.appendChild(document.createElement(&quot;input&quot;)); slider.setAttribute(&quot;class&quot;,&quot;slider&quot;); slider.setAttribute(&quot;type&quot;,&quot;range&quot;); slider.setAttribute(&quot;id&quot;,&quot;slider&quot;); let minVal = this.hasAttribute(&quot;min-val&quot;) ? this.getAttribute(&quot;min-val&quot;) : &quot;0&quot;; let maxVal = this.hasAttribute(&quot;max-val&quot;) ? this.getAttribute(&quot;max-val&quot;) : &quot;5&quot;; slider.setAttribute(&quot;min&quot;,minVal); slider.setAttribute(&quot;max&quot;,maxVal); slider.setAttribute(&quot;value&quot;,minVal); const ampInput = wrapper.appendChild(document.createElement(&quot;input&quot;)); ampInput.setAttribute(&quot;type&quot;,&quot;number&quot;); ampInput.setAttribute(&quot;id&quot;,&quot;inp&quot;); ampInput.setAttribute(&quot;value&quot;,&quot;5&quot;); const style = document.createElement(&quot;style&quot;); style.textContent = `.slider{ backround: #cfc; } .inp{ display: block; } .wrapper { display: inline-grid; }`; this.shadowRoot.append(style,wrapper); </code></pre> <p>I added style in my custom Element so i dont understand this error. What should i change to make it work ? Or how differently should i hide the element when checkbox is clicked ?</p>
[ { "answer_id": 74481178, "author": "jsbueno", "author_id": 108205, "author_profile": "https://Stackoverflow.com/users/108205", "pm_score": 0, "selected": false, "text": "itertools.product" }, { "answer_id": 74481181, "author": "Tim Roberts", "author_id": 1883316, "author_profile": "https://Stackoverflow.com/users/1883316", "pm_score": 2, "selected": true, "text": "itertools.product" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20088244/" ]
74,481,196
<p>I've a Release pipeline in AzureDevops which pulls it's artifact from Azure Container Registry.</p> <p>By creating a new release, at the &quot;dockerbuild&quot; needs to be selected which image from ACR shall be chosen: <a href="https://i.stack.imgur.com/HMpKc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HMpKc.png" alt="enter image description here" /></a></p> <p>Currently i can't access the variable &quot;dockerbuild&quot; with it's value &quot;1358 in the release pipeline. How do i need to write this, for access from powerShell?</p> <p>I tried these approaches, without luck:</p> <p><a href="https://i.stack.imgur.com/Uzgf2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Uzgf2.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/2RI9k.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2RI9k.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74482238, "author": "Afshin Alizadeh", "author_id": 1034266, "author_profile": "https://Stackoverflow.com/users/1034266", "pm_score": -1, "selected": false, "text": "$(Build.BuildNumber)" }, { "answer_id": 74483889, "author": "Charles Han", "author_id": 11514907, "author_profile": "https://Stackoverflow.com/users/11514907", "pm_score": 2, "selected": false, "text": "Write-Host $env:RELEASE_ARTIFACTS_dockerbuild_BUILDNUMBER\n" }, { "answer_id": 74484473, "author": "Bowman Zhu-MSFT", "author_id": 6261890, "author_profile": "https://Stackoverflow.com/users/6261890", "pm_score": 2, "selected": true, "text": "Write-Host \"$ env:RELEASE_ARTIFACTS_dockerbuild_BUILDNUMBER\"\n\nWrite-Host $env:RELEASE_ARTIFACTS_dockerbuild_BUILDNUMBER #This only works on windows.\n\nWrite-Host \"$ env:RELEASE_ARTIFACTS_DOCKERBUILD_BUILDNUMBER\"\n\nWrite-Host $env:RELEASE_ARTIFACTS_DOCKERBUILD_BUILDNUMBER #This will work both on windows and linux.\n\nWrite-Host \"$ (Release.Artifacts.dockerbuild.BuildNumber)\"\n\nWrite-Host $(Release.Artifacts.dockerbuild.BuildNumber) #In Inline script, this will always work.\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6797189/" ]
74,481,205
<p>Imagine a NxN chess board, I have a tuple <code>t = (0,3,2,1)</code> which represents chess pieces location at each column (col = index), and each number represents the row, starting at 0 from bottom.</p> <p>For this example, it has 4 columns, first piece is at row=0 (bottom row), second piece is on row=3 (fourth/highest row), third piece is on row=2 (third row from bottom), fourth piece is on second row from bottom.</p> <p>I would like to represent it as a 2D array as follows:</p> <pre><code>[[0,1,0,0], [0,0,1,0], [0,0,0,1], [1,0,0,0]] </code></pre> <p>I was able to generate the 2D array using this code</p> <pre><code>pieces_locations = (0,3,2,1) pieces_locations = list(pieces_locations) table_size = len(pieces_locations) arr = [[0 for col in range(table_size)] for row in range(table_size)] </code></pre> <p>However, I was not able to assign the 1's in their correct locations.</p> <p>I was able to understand this: arr[row][col], but the rows are inverted (0 is top to N is bottom).</p>
[ { "answer_id": 74481280, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 1, "selected": false, "text": "arr = [[0] * table_size for _ in range(table_size)]\n" }, { "answer_id": 74481281, "author": "CharlieBONS", "author_id": 20529340, "author_profile": "https://Stackoverflow.com/users/20529340", "pm_score": 2, "selected": true, "text": "for x, i in enumerate(range(1, len(arr))):\n arr[-i][pieces_locations[x]] = 1\n" }, { "answer_id": 74481360, "author": "Saleh", "author_id": 20424322, "author_profile": "https://Stackoverflow.com/users/20424322", "pm_score": 0, "selected": false, "text": "pieces_locations = (0,3,2,1)\npieces_locations = list(pieces_locations)\n\ntable_size = len(pieces_locations)\n\narr = [[0 for col in range(table_size)] for row in range(table_size)]\n\n\nfor row in range(0, table_size):\n arr[row][pieces_locations.index(row)] = 1\n\n\nres = arr[::-1]\nprint (res)\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20424322/" ]
74,481,217
<p>Consider I have the following collection:</p> <pre class="lang-json prettyprint-override"><code>[ { &quot;total&quot;: 48.0, &quot;status&quot;: &quot;CO&quot; }, { &quot;total&quot;: 11.0, &quot;status&quot;: &quot;CA&quot; }, { &quot;total&quot;: 15916.0, &quot;status&quot;: &quot;PE&quot; } ] </code></pre> <p>I need to realize the difference of PE status - (CO + CA).</p> <p>The expected result is:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;_id&quot; : null, &quot;total&quot; : 15857.0 } </code></pre>
[ { "answer_id": 74481336, "author": "ray", "author_id": 14732669, "author_profile": "https://Stackoverflow.com/users/14732669", "pm_score": 2, "selected": false, "text": "$switch" }, { "answer_id": 74481346, "author": "nimrod serok", "author_id": 18482310, "author_profile": "https://Stackoverflow.com/users/18482310", "pm_score": 2, "selected": true, "text": "status" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10022279/" ]
74,481,243
<p>I am looking for how to execute javascript code in the URL bar via xJavascript.</p> <p>The standard way would be <code>xJavascript:JAVASCRIPTCODEHERE</code>, you would remove the &quot;x&quot; and it would execute the code, but that is not working.</p> <p>Am I doing it wrong, or is no longer possible?</p> <p>Please help!</p>
[ { "answer_id": 74481336, "author": "ray", "author_id": 14732669, "author_profile": "https://Stackoverflow.com/users/14732669", "pm_score": 2, "selected": false, "text": "$switch" }, { "answer_id": 74481346, "author": "nimrod serok", "author_id": 18482310, "author_profile": "https://Stackoverflow.com/users/18482310", "pm_score": 2, "selected": true, "text": "status" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20253121/" ]
74,481,245
<p>Is it possible to limit s3 bucket to lowercase files/directories only?</p> <p>Some downstream systems are case insensitive so I want to prevent any issues.</p> <p>There's a Lambda workaround, but is it possible to specify this requirement as a bucket policy?</p> <pre class="lang-json prettyprint-override"><code>{ &quot;Version&quot;: &quot;2012-10-17&quot;, &quot;Statement&quot;: [ { &quot;Sid&quot;: &quot;Enforce lower-case&quot;, &quot;Effect&quot;: &quot;Deny&quot;, &quot;Principal&quot;:&quot;*&quot;, &quot;Action&quot;: &quot;s3:PutObject&quot;, &quot;Resource&quot;: &quot;arn:aws:s3:::mybucket/*&quot;, &quot;Condition&quot;: { &quot;StringNotEquals&quot;: { &quot;s3:KeyName&quot;: &quot;lower(s3:KeyName)&quot; } } } ] } </code></pre>
[ { "answer_id": 74481679, "author": "John Rotenstein", "author_id": 174777, "author_profile": "https://Stackoverflow.com/users/174777", "pm_score": 1, "selected": false, "text": "Key" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2425753/" ]
74,481,246
<p>I want to return the left association of an expression given (haskell), so if we have a + (b + c) the function has to return (a + b) + c, this also applies for the multiplication since these 2 operations are associative. taking onto consideration the other operations that are not associative therefor I have to put a condition to not left associate those expressions. so the leftAssociate function turns every expression given into an equivalent left-associated one with the same constants</p> <p>the function is defined as follow :</p> <pre><code>data Expr = Val Int | App Op Expr Expr leftAssociate :: Expr -&gt; Expr leftAssociate (App Add (Val a) (App Add (Val b) (Val c))) = App Add (App Add (Val a) (Val b)) (Val c) </code></pre> <p>I have tried pattern matching but it's too overwhelming as there is a lot of possibilities and also I cannot specify the number of operations given as input as it's not limited.</p>
[ { "answer_id": 74481765, "author": "Daniel Wagner", "author_id": 791604, "author_profile": "https://Stackoverflow.com/users/791604", "pm_score": 2, "selected": false, "text": "leftAssociate (App Add x (App Add y z)) = -- ...\nleftAssociate (App Mul x (App Mul y z)) = -- ...\nleftAssociate (App op x y) = -- ...\nleftAssociate (Val n) = -- ...\n" }, { "answer_id": 74482673, "author": "K. A. Buhr", "author_id": 7203016, "author_profile": "https://Stackoverflow.com/users/7203016", "pm_score": 1, "selected": false, "text": "App op _ _" }, { "answer_id": 74488931, "author": "Franky", "author_id": 412549, "author_profile": "https://Stackoverflow.com/users/412549", "pm_score": 0, "selected": false, "text": " +\n / \\\n / \\\n a +\n / \\\n / \\\n b c\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17517912/" ]
74,481,252
<p>I'm writing my own implementation of an <code>Vector</code>. I want this to be as wide as possible so I wrote it with all fields and values being <code>double</code>. Now I made a second Object <code>FloatVector</code> which extends my main Class <code>2DVector</code>. It's only job is to provide Getter-Methods of <code>2DVector</code> that are already cast my double-Values to float-Values (I know, there are other - and probably better - ways of doing that, but I really can't be bothered adding <code>(float) ...</code> to everything related with my Vectors).</p> <p>Anyway, while doing the above I ran into a problem I didn't expect to happen. Looking at the code below:</p> <pre><code>public class Vector2D { double x; public double getX() { return x;} } </code></pre> <pre><code>public class FloatVector extends 2DVector { @Override public float getX() { return (float) super.getX(); } } </code></pre> <p>Eclipse throws an Error, that <code>The return Type is incompatible with Vector2D.getX()</code> and I can't really understand why this is.</p> <p>I tried replacing the primitive casting to the following:</p> <pre><code>@Override public Float angleBetween() { return Float.valueOf( (float) super.getMagnitude() ); } </code></pre> <p>but also to no avail.</p>
[ { "answer_id": 74486771, "author": "王大拿", "author_id": 8541039, "author_profile": "https://Stackoverflow.com/users/8541039", "pm_score": 1, "selected": false, "text": "public class Vector2D<T> {\n T x;\n\n public T getX() {\n return x;\n }\n}\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13689169/" ]
74,481,253
<p>I want to unsort a list. For you to understand:</p> <pre class="lang-py prettyprint-override"><code>list1 = [&quot;Hi&quot;, &quot;Whats up this Morning&quot; &quot;Hello&quot;, &quot;Good Morning&quot;] new_list = sorted(list1, key=len, reverse=True) [&quot;Whats up this Morning&quot;, &quot;Good Morning&quot;, &quot;Hello&quot;, &quot;Hi&quot;] </code></pre> <p>And know it should go back exactly in the same way it was in the beginning</p> <pre><code>[&quot;Hi&quot;, &quot;Whats up this Morning&quot;, &quot;Hello&quot;, &quot;Good Morning&quot;] </code></pre> <p>Anyone knows the answer?</p>
[ { "answer_id": 74486771, "author": "王大拿", "author_id": 8541039, "author_profile": "https://Stackoverflow.com/users/8541039", "pm_score": 1, "selected": false, "text": "public class Vector2D<T> {\n T x;\n\n public T getX() {\n return x;\n }\n}\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20533469/" ]
74,481,278
<p>We server markdown files as documentation for using our SDK and one of our websites uses remark and rehype to process and display them inline in the browser as html:</p> <pre><code>const processor = unified() .use(remarkParse) .use(remarkRehype, { allowDangerousHtml: true, }) .use(rehypeHighlight, { ignoreMissing: true, languages: { gradle, java, kotlin, xml, }, subset: [&quot;kotlin&quot;, &quot;java&quot;, &quot;gradle&quot;, &quot;xml&quot;], }) .use(rehypeReact, { createElement: React.createElement, }); </code></pre> <p>The markdown documentation contains some inlined images that need to be displayed in the html:</p> <pre><code>##Consent Notice The below consent notice should be shown to: * All new users of your app * All existing and returning users who have not seen the consent request before &lt;img src=&quot;data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAA2ADYAAD...==&quot; width=&quot;300&quot;&gt; </code></pre> <p>(We don't have a convenient place to put hostable images so this is our temporary solution.)</p> <p>When I render the HTML from remarkRehype, it has stripped the image out of the rendered html. Is there a way to allow it to persist through the conversion?</p>
[ { "answer_id": 74486771, "author": "王大拿", "author_id": 8541039, "author_profile": "https://Stackoverflow.com/users/8541039", "pm_score": 1, "selected": false, "text": "public class Vector2D<T> {\n T x;\n\n public T getX() {\n return x;\n }\n}\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/977524/" ]
74,481,307
<p>I'm new to pandas and would like to know how to do the following: Given specific conditions, I would like to mark the whole group with a specific label rather than just the rows that meet the conditions. For example, if I have a DataFrame like this:</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame({&quot;id&quot;: [1, 2, 3, 4, 5, 6, 7, 8], &quot;process&quot;: [&quot;pending&quot;, &quot;finished&quot;, &quot;finished&quot;, &quot;finished&quot;, &quot;finished&quot;, &quot;finished&quot;, &quot;finished&quot;, &quot;pending&quot;], &quot;working_group&quot;: [&quot;a&quot;, &quot;a&quot;, &quot;c&quot;, &quot;d&quot;, &quot;d&quot;, &quot;f&quot;, &quot;g&quot;, &quot;g&quot;], &quot;size&quot;: [2, 2, 1, 2, 2, 1, 2, 2]}) conditions = [(df['size'] &gt;= 2) &amp; (df['process'].isin([&quot;pending&quot;]))] choices = [&quot;not_done&quot;] df['state'] = df['state'] = np.select(conditions, choices, default = &quot;something_else&quot;) </code></pre> <p>df:</p> <pre><code> id process working_group size state 0 1 pending a 2 not_done 1 2 finished a 2 something_else 2 3 finished c 1 something_else 3 4 finished d 2 something_else 4 5 finished d 2 something_else 5 6 finished f 1 something_else 6 7 finished g 2 something_else 7 8 pending g 2 not_done </code></pre> <p>However I would like the whole working_group marked as not_done when a individual task is pending, so for instance a &amp; g should be marked as not_done.</p> <pre><code> id process working_group size state 0 1 pending a 2 not_done 1 2 finished a 2 not_done 2 3 finished c 1 something_else 3 4 finished d 2 something_else 4 5 finished d 2 something_else 5 6 finished f 1 something_else 6 7 finished g 2 not_done 7 8 pending g 2 not_done </code></pre>
[ { "answer_id": 74486771, "author": "王大拿", "author_id": 8541039, "author_profile": "https://Stackoverflow.com/users/8541039", "pm_score": 1, "selected": false, "text": "public class Vector2D<T> {\n T x;\n\n public T getX() {\n return x;\n }\n}\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3790995/" ]
74,481,315
<p>I am trying to flatten API response. This is the response</p> <pre><code>data = [{ &quot;id&quot;: 1, &quot;status&quot;: &quot;Public&quot;, &quot;Options&quot;: [ { &quot;id&quot;: 8, &quot;pId&quot;: 9 }, { &quot;id&quot;: 10, &quot;pId&quot;: 11 } ] }, { &quot;id&quot;: 2, &quot;status&quot;: &quot;Public&quot;, &quot;Options&quot;: [ { &quot;id&quot;: 12, &quot;pId&quot;: 13 }, { &quot;id&quot;: 14, &quot;pId&quot;: 15 } ] } ] </code></pre> <p>I am trying to do this(applying ast literal eval, df.pop and json normalize). And then i am concatinating the results</p> <pre><code>def pop(child_df, column_value): child_df = child_df.dropna(subset=[column_value]) if isinstance(child_df[column_value][0], str): print(&quot;yes&quot;) child_df[column_value] = child_df[column_value].apply(ast.literal_eval) normalized_json = [json_normalize(x) for x in child_df.pop(column_value)] expanded_child_df = child_df.join(pd.concat(normalized_json, ignore_index=True, sort=False).add_prefix(column_value + '_')) expanded_child_df.columns = [str(col).replace('\r','') for col in expanded_child_df.columns] expanded_child_df.columns = map(str.lower, expanded_child_df.columns) return expanded_child_df df = pd.DataFrame.from_dict(data) df2 = pop(df,'Options') </code></pre> <p>This is the output i am getting</p> <pre><code> id status options_id options_pid 0 1 Public 8 9 1 2 Public 10 11 </code></pre> <p>But the code is skipping some values inside the <code>Options</code> list. This is the expected output</p> <pre><code> id status options_id options_pid 0 1 Public 8 9 1 1 Public 10 11 2 2 Public 12 13 3 2 Public 14 15 </code></pre> <p>What am i missing here ?</p>
[ { "answer_id": 74481565, "author": "Bushmaster", "author_id": 15415267, "author_profile": "https://Stackoverflow.com/users/15415267", "pm_score": 1, "selected": false, "text": "df=pd.json_normalize(data).explode('Options')\ndf=df.join(df['Options'].apply(pd.Series).add_prefix('options_')).drop(['Options'],axis=1).drop_duplicates()\nprint(df)\n'''\n id status optionsid optionspId\n0 1 Public 8 9\n0 1 Public 10 11\n1 2 Public 12 13\n1 2 Public 14 15\n'''\n" }, { "answer_id": 74481580, "author": "crashMOGWAI", "author_id": 5373105, "author_profile": "https://Stackoverflow.com/users/5373105", "pm_score": 1, "selected": false, "text": "df = pd.json_normalize(data, record_path=\"Options\", meta=['id','status'], record_prefix='options.')\n" }, { "answer_id": 74481629, "author": "Reuben Jacob Mathew", "author_id": 11358838, "author_profile": "https://Stackoverflow.com/users/11358838", "pm_score": 0, "selected": false, "text": "df = pd.json_normalize(data).explode('Options')\ntmp= df['Options'].apply(pd.Series)\ndf = pd.concat([df[['id', 'status']], tmp], axis=1)\nprint(df)\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19671817/" ]
74,481,351
<p>I'm new here and also new to react js and I'm having trouble solving 1 exercise that asks to display a list of users coming from a REST API and then to be able to filter it.</p> <p>I have managed to show it but I don't know how to do the filter.</p> <p>EDIT:</p> <p>Well Thanx I manage to use filters as you say :D.</p> <p>But now I want the user to be able to select which columns are shown and which are not.</p> <p>For this I have created a select from which I plan to remove the filter but I don't really know how to proceed :/</p> <p><a href="https://i.stack.imgur.com/fJfOc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fJfOc.png" alt="my app" /></a></p> <p>This is how I'm doing the filter, using a text input.</p> <pre><code>//Query const [query, setQuery] = useState(&quot;&quot;); const search = (data) =&gt; { return data.filter( item =&gt; item.name.toLowerCase().includes(query)); } </code></pre> <p>the select</p> <pre><code>&lt;select className='select' onChange={changeFilter}&gt; &lt;option value=&quot;&quot;&gt;All&lt;/option&gt; &lt;option value=&quot;name&quot;&gt;Name&lt;/option&gt; &lt;option value=&quot;username&quot;&gt;Username&lt;/option&gt; &lt;option value=&quot;email&quot;&gt;Email&lt;/option&gt; &lt;option value=&quot;phone&quot;&gt;Phone&lt;/option&gt; &lt;/select&gt; </code></pre> <p>So basically I pretend to change the &quot;name&quot; here: item.<strong>name</strong>.toLowerCase().includes(query)); for filter and if <strong>All</strong> is selected its shows all.</p> <p>Any help with this?</p> <p>Code from the fetch:</p> <pre><code>// users from API. const [users, setUsers] = useState([]); useEffect(() =&gt; { fetchData(); }, []); // async function const fetchData = async () =&gt; { await fetch('https://jsonplaceholder.typicode.com/users') .then(response =&gt; response.json()) .then(data =&gt; setUsers(data)) .catch((error) =&gt; { console.log(&quot;ERROR:&quot; + error); }) } </code></pre> <p><strong>I modified the way I call the component in App.js</strong></p> <pre><code> &lt;div className=&quot;App&quot;&gt; &lt;h1&gt;PRUEBA DE NIVEL&lt;/h1&gt; &lt;select className='select' onChange={changeSelectedFilter}&gt; &lt;option value=&quot;&quot;&gt;All&lt;/option&gt; &lt;option value=&quot;name&quot;&gt;Name&lt;/option&gt; &lt;option value=&quot;username&quot;&gt;Username&lt;/option&gt; &lt;option value=&quot;email&quot;&gt;Email&lt;/option&gt; &lt;option value=&quot;phone&quot;&gt;Phone&lt;/option&gt; &lt;/select&gt; &lt;input type=&quot;text&quot; placeholder='Search...' className='search' onChange={e =&gt; setQuery(e.target.value.toLowerCase())} /&gt; &lt;UserTable data={search(users)} filter={selectedFilter} /&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 74481396, "author": "Anurag Bhagsain", "author_id": 8885198, "author_profile": "https://Stackoverflow.com/users/8885198", "pm_score": 0, "selected": false, "text": "users.filter(user => user.name.startsWith('R')).map((user) => (\n <UsersList\n key={user.id}\n name={user.name}\n username={user.username}\n email={user.email}\n phone={user.phone}\n />\n ));\n\n" }, { "answer_id": 74481453, "author": "yousoumar", "author_id": 15288641, "author_profile": "https://Stackoverflow.com/users/15288641", "pm_score": 1, "selected": false, "text": "filterInput" }, { "answer_id": 74481627, "author": "Amirhossein", "author_id": 11342834, "author_profile": "https://Stackoverflow.com/users/11342834", "pm_score": 3, "selected": true, "text": "filter" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20533545/" ]
74,481,402
<p>I'm migrating the backend a budget database from Access to SQL Server and I ran into an issue.</p> <p>I have 2 tables (let's call them t1 and t2) that share many fields in common: Fund, Department, Object, Subcode, TrackingCode, Reserve, and FYEnd.</p> <p>If I want to join the tables to find records where all 7 fields match, I can create an inner join using each field:</p> <pre><code>SELECT * FROM t1 INNER JOIN t2 ON t1.Fund = t2.Fund AND t1.Department = t2.Department AND t1.Object = t2.Object AND t1.Subcode = t2.Subcode AND t1.TrackingCode = t2.TrackingCode AND t1.Reserve = t2.Reserve AND t1.FYEnd = t2.FYEnd; </code></pre> <p>This works, but it runs very slowly. When the backend was in Access, I was able to solve the problem by adding a calculated column to both tables. It basically, just concatenated the fields using &quot;-&quot; as a delimiter. The revised query is as follows:</p> <pre><code>SELECT * FROM t1 INNER JOIN t2 ON CalculatedColumn = CalculatedColumn </code></pre> <p>This looks cleaner and runs much faster. The problem is when I moved t1 and t2 to SQL Server, the same query gives me an error message:</p> <p><a href="https://i.stack.imgur.com/ZIKg9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZIKg9.png" alt="enter image description here" /></a></p> <p>I'm new to SQL Server. Can anyone explain what's going on here? Is there a setting I need to change for the calculated column?</p>
[ { "answer_id": 74481396, "author": "Anurag Bhagsain", "author_id": 8885198, "author_profile": "https://Stackoverflow.com/users/8885198", "pm_score": 0, "selected": false, "text": "users.filter(user => user.name.startsWith('R')).map((user) => (\n <UsersList\n key={user.id}\n name={user.name}\n username={user.username}\n email={user.email}\n phone={user.phone}\n />\n ));\n\n" }, { "answer_id": 74481453, "author": "yousoumar", "author_id": 15288641, "author_profile": "https://Stackoverflow.com/users/15288641", "pm_score": 1, "selected": false, "text": "filterInput" }, { "answer_id": 74481627, "author": "Amirhossein", "author_id": 11342834, "author_profile": "https://Stackoverflow.com/users/11342834", "pm_score": 3, "selected": true, "text": "filter" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10508285/" ]
74,481,418
<p>I need a List of objects whose properties will be the columns' names.</p> <p>This is my approach:</p> <pre><code>var list = (from student in context.Student join school in context.School on student.idSchool equals school.idSchool into allcolumns from entry in allcolumns select entry).ToList(); </code></pre> <p>but list happens to be only a list of <code>School</code>s. How can I accomplish my goal? Thank you.</p>
[ { "answer_id": 74481746, "author": "Diego", "author_id": 20478349, "author_profile": "https://Stackoverflow.com/users/20478349", "pm_score": 1, "selected": false, "text": "var mylist = from student in context.Student\n join school in context.School\n on student.idSchool equals school.idSchool\n select new \n {\n Stud = student,\n Scho = school\n };\n" }, { "answer_id": 74481850, "author": "T.S.", "author_id": 1704458, "author_profile": "https://Stackoverflow.com/users/1704458", "pm_score": 3, "selected": true, "text": "IEnumerable<T>" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19297836/" ]
74,481,447
<p>I have two data sources that are loaded into Azure Synapse. Both raw data sources contain an 'Apple' table.</p> <p>I merge these into a single 'Apple' table in my Enriched data store.</p> <p><code>SELECT * FROM datasource1.apple JOIN datasource2.apple on datasource1.apple.id = datasource2.apple.id</code></p> <p>However, both data sourecs also contain a one to many relation <code>AppleColours</code>.</p> <p>Please could someone help me understand the correct approach to creating a single <code>AppleColours</code> table in my enriched zone?</p>
[ { "answer_id": 74481746, "author": "Diego", "author_id": 20478349, "author_profile": "https://Stackoverflow.com/users/20478349", "pm_score": 1, "selected": false, "text": "var mylist = from student in context.Student\n join school in context.School\n on student.idSchool equals school.idSchool\n select new \n {\n Stud = student,\n Scho = school\n };\n" }, { "answer_id": 74481850, "author": "T.S.", "author_id": 1704458, "author_profile": "https://Stackoverflow.com/users/1704458", "pm_score": 3, "selected": true, "text": "IEnumerable<T>" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2207559/" ]
74,481,454
<p>I am trying to understand a Python for loop that is implemented as below</p> <pre><code>samples= [(objectinstance.get('sample', record['token'])['timestamp'], record) for record in objectinstance.scene] </code></pre> <p>'scene' is a JSON file with list of dictionaries and each dictionary entry refers through values of the token to another JSON file called 'sample' containing 'timestamp' key among other keys.</p> <p>Although I can roughly understand at a high level, I am not able to decipher how the 'record' is being used here as the output of object's get method. I am thinking this is some sort of list comprehension, but not sure. Can you help understand this and also point me any reference to understand this better? thank you</p>
[ { "answer_id": 74481746, "author": "Diego", "author_id": 20478349, "author_profile": "https://Stackoverflow.com/users/20478349", "pm_score": 1, "selected": false, "text": "var mylist = from student in context.Student\n join school in context.School\n on student.idSchool equals school.idSchool\n select new \n {\n Stud = student,\n Scho = school\n };\n" }, { "answer_id": 74481850, "author": "T.S.", "author_id": 1704458, "author_profile": "https://Stackoverflow.com/users/1704458", "pm_score": 3, "selected": true, "text": "IEnumerable<T>" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20533556/" ]
74,481,467
<p>I have created a Next js app. As they said in their documentation, I integrated TailwindCSS into my project. Everything went well. However, the result I got was a web page where no TailwindCSS styles were applied on.</p> <p>I will provide the files that I think are causing this issue.</p> <p>I would appreciate it if someone could clarify where I am wrong.</p> <p><strong>Index.js file</strong></p> <pre><code>return ( &lt;div className=&quot;flex justify-center&quot;&gt; &lt;div className=&quot;px-4&quot; style={{maxWidth: &quot;1600px&quot;}}&gt; &lt;div className=&quot;grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-2&gt; Test &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; ) </code></pre> <p><strong>postcss.config.js file:</strong></p> <pre><code>module.exports = { plugins: { tailwindcss: {}, autoprefixer: {}, }, } </code></pre> <p><strong>tailwind.config.js</strong></p> <pre><code>module.exports = { content: [ &quot;./pages/**/*.{js,ts,jsx,tsx}&quot;, &quot;./components/**/*.{js,ts,jsx,tsx}&quot;, ], theme: { extend: {}, }, plugins: [], } </code></pre> <p><strong>globals.css</strong></p> <pre><code>@tailwind base; @tailwind components; @tailwind utilities; </code></pre>
[ { "answer_id": 74481513, "author": "Samathingamajig", "author_id": 12101554, "author_profile": "https://Stackoverflow.com/users/12101554", "pm_score": 0, "selected": false, "text": "tailwind.config.js" }, { "answer_id": 74481575, "author": "Prashant Singh", "author_id": 15326534, "author_profile": "https://Stackoverflow.com/users/15326534", "pm_score": 0, "selected": false, "text": "module.exports = {\ncontent: [\n \"./pages/**/*.{js,ts,jsx,tsx}\",\n \"./components/**/*.{js,ts,jsx,tsx}\",\n],\ntheme: {\n extend: {},\n},\nplugins: [],\n} ```\n\nIt should work fine.\n\n\n" }, { "answer_id": 74481594, "author": "Sanusi hassan", "author_id": 10944954, "author_profile": "https://Stackoverflow.com/users/10944954", "pm_score": 0, "selected": false, "text": "watch" }, { "answer_id": 74481624, "author": "Ahmed Chabayta", "author_id": 18410254, "author_profile": "https://Stackoverflow.com/users/18410254", "pm_score": 0, "selected": false, "text": "module.exports = {\n content: [\n \"./pages/**/*.{js,ts,jsx,tsx}\", //path to components/pages\n \"./components/**/*.{js,ts,jsx,tsx}\", //path to components/pages\n ],\n theme: {\n extend: {},\n },\n plugins: [],\n}\n" }, { "answer_id": 74530347, "author": "Sina Rahimi", "author_id": 15388111, "author_profile": "https://Stackoverflow.com/users/15388111", "pm_score": 1, "selected": false, "text": "import '../styles/globals.css'" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15388111/" ]
74,481,494
<p>How to set the variables - key/value pair from a text file before running any targets in a Makefile?</p> <p>Let's say text <strong>.p4config</strong> file contains the following: <code>P4PORT=ilp4.il.domain.com:1667 P4CLIENT=ws:domain.com::user:container.IP_V1:a0a12fc1</code></p> <p>in makefile this wont work:</p> <p><code>export $(cat .p4config | grep P4CLIENT | xargs) test: env &gt; env.log</code></p> <p>Expecting to see the variables P4PORT and P4CLIENT in the env.log</p> <p><code>cat .p4config | grep P4CLIENT | xargs</code></p> <p>results:</p> <p><code>P4PORT=ilp4.il.domain.com:1667 P4CLIENT=ws:domain.com::user:container.IP_V1:a0a12fc1 </code></p> <p>but adding the &quot;export&quot; inside the makefile won't do the trick</p>
[ { "answer_id": 74481769, "author": "MadScientist", "author_id": 939557, "author_profile": "https://Stackoverflow.com/users/939557", "pm_score": 0, "selected": false, "text": "env.log:\n cat .p4config | grep P4CLIENT | xargs > $@\n" }, { "answer_id": 74482917, "author": "Philippe", "author_id": 2125671, "author_profile": "https://Stackoverflow.com/users/2125671", "pm_score": 2, "selected": true, "text": ".ONESHELL:\n\nall:\n eval \"$$(perl -ne 'if (/P4CLIENT/) { map {print \"export $$_\\n\"} split }' .p4config)\"\n env | grep P4\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18117529/" ]
74,481,506
<p>Hey i'm using laravel 9 here and im using the SB ADMIN template from bootstrap , i'm making the template as a component <code>&lt;x-dashboard &gt;...&lt;/x-dashboard&gt;</code> and i'm passing children inside it ! but i want the children to have it's own css ( not the bootstrap one ) which is in my app.css file i added the head just so i can link the css file to the blade file but still doesn't work any solutions ?</p> <p><strong>seeProscpect.blade.php</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;{{ asset('../css/app.css') }}&quot;&gt; &lt;/head&gt; &lt;body&gt; &lt;x-dashboard &gt; &lt;h3 class=&quot;changeColor&quot;&gt;TRYING CSS&lt;/h3&gt; &lt;/x-dashboard&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>app.css</strong></p> <pre><code> .changeColor { color: green; } </code></pre>
[ { "answer_id": 74481769, "author": "MadScientist", "author_id": 939557, "author_profile": "https://Stackoverflow.com/users/939557", "pm_score": 0, "selected": false, "text": "env.log:\n cat .p4config | grep P4CLIENT | xargs > $@\n" }, { "answer_id": 74482917, "author": "Philippe", "author_id": 2125671, "author_profile": "https://Stackoverflow.com/users/2125671", "pm_score": 2, "selected": true, "text": ".ONESHELL:\n\nall:\n eval \"$$(perl -ne 'if (/P4CLIENT/) { map {print \"export $$_\\n\"} split }' .p4config)\"\n env | grep P4\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13647720/" ]
74,481,509
<p>I have taken data from csv file using get-content I need to print data in table format how can I do that? CSV data looks like this after printing it in the mail.</p> <pre><code>ID OP_ID STATE OUP_ID METHOD time ------------ -------- ----- ---------------- ---- 2187 ab8262 working ky981 IN 09.40.13.161000 2779 ab9128 working ky359 Out 89.9 09.52.04.962000 </code></pre> <p>Fyi: Data will be different every time</p> <p>But I want to represent it as a table</p>
[ { "answer_id": 74481616, "author": "user20234075", "author_id": 20234075, "author_profile": "https://Stackoverflow.com/users/20234075", "pm_score": 1, "selected": false, "text": "ft" }, { "answer_id": 74485416, "author": "Dilly B", "author_id": 2670623, "author_profile": "https://Stackoverflow.com/users/2670623", "pm_score": 0, "selected": false, "text": "$csvfile = Import-Csv -Path c:\\temp\\test.csv\n$csvfile.Header1\n$csvfile.Header2\n$csvfile.Header3\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20212257/" ]
74,481,533
<p>I made a function that is supposed to help me order strings in alphabetical order: it should return -1 if the first string comes before the second one, 0 if they are the same string and 1 if the first string comes after the second one. This is the code:</p> <p>`</p> <pre><code>int testString(char* a, char* b){ int i = 0; while(a[i] != EOF &amp;&amp; b[i] != EOF){ if(a[i] &gt; b[i]){ return 1; } else{ if(a[i] &lt; b[i]){ return -1; } else{ i++; } } } if(a[i] == EOF &amp;&amp; b[i]!=EOF){ return -1; } else{ if(a[i] != EOF &amp;&amp; b[i] == EOF){ return 1; } else{ if(a[i] == EOF &amp;&amp; b[i] == EOF){ return 0; } else{ printf(&quot;Problem in the string comparison\n&quot;); return -2; } } } } </code></pre> <p>`</p> <p>So: it does a while cycle as long as there are characters in the string and, if one string is the same as the other, but longer, it should return 1, -1 in the very opposite case and 0 if they are the very same, so same length. Though, this returns -1 with the very same strings and i don't get why.</p> <p>I tried using it to order an array of structs of which one element was of type char* and it does work (because the sorting algorithm is a quick sort, and the one i made doesn't make a distinction between less than and equal to, during the sorting). I later printed out the strings of the array of structs and they were indeed ordered. Problem is that the testing (which used this same function) to see whether or not they were in order told me that they weren't, as it returned -1 instead of 0, when the strings were the same, so the anti-alphabetical order wasn't respected. Now i looked at the function, but it looks OK and i don't get what's wrong with it</p>
[ { "answer_id": 74481651, "author": "Vlad from Moscow", "author_id": 2877241, "author_profile": "https://Stackoverflow.com/users/2877241", "pm_score": 2, "selected": false, "text": "-1" }, { "answer_id": 74490914, "author": "John Bode", "author_id": 134554, "author_profile": "https://Stackoverflow.com/users/134554", "pm_score": 0, "selected": false, "text": "while(a[i] != EOF && b[i] != EOF){\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19618641/" ]
74,481,613
<p>I have a dataset like this</p> <pre><code>data = {'weight': ['NaN',2,3,4,'NaN',6,7,8,9,'NaN',11,12,13,14,15], 'MI': ['NaN', 21, 19, 18, 'NaN',16,15,14,13,'NaN',11,10,9,8,7]} df = pd.DataFrame(data, index= ['group1', &quot;gene1&quot;, &quot;gene2&quot;, 'gene3', 'group2', &quot;gene1&quot;, 'gene21', 'gene4', 'gene7', 'group3', 'gene2', 'gene10', 'gene3', 'gene43', 'gene1']) </code></pre> <p><a href="https://i.stack.imgur.com/u1ZRP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u1ZRP.png" alt="enter image description here" /></a></p> <p>I need to stack it to gene by group dataframe with MI values. If there are no gene values for particular group the imputated value should be 0.1. 'weights' column should be removed. The final dataframe should look like this</p> <p><a href="https://i.stack.imgur.com/X2xse.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/X2xse.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74481825, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "m = df['weight'].ne('NaN')\n\n(df[m]\n .set_index((~m).cumsum()[m], append=True)['MI']\n .unstack('weight', fill_value=0.1)\n .add_prefix('group')\n )\n" }, { "answer_id": 74482873, "author": "sammywemmy", "author_id": 7175713, "author_profile": "https://Stackoverflow.com/users/7175713", "pm_score": 1, "selected": false, "text": "pivot" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12149817/" ]
74,481,647
<p>Given a string s consisting of lowercase English letters, find the number of consecutive triplets within s formed by unique characters. In other words, count the number of indices i, such that s[i], s[i + 1], and s[i + 2] are all pairwise distinct.</p> <p>Got this on a test and was completely stumped. I am less than a year in to programming so my mind just doesn't even understand how to tackle this.</p> <p>My main issue is not understanding how to get back a sum of the unique triplets.</p>
[ { "answer_id": 74481742, "author": "caTS", "author_id": 18244921, "author_profile": "https://Stackoverflow.com/users/18244921", "pm_score": 2, "selected": false, "text": "a != b && b != c" }, { "answer_id": 74481841, "author": "user3425506", "author_id": 3425506, "author_profile": "https://Stackoverflow.com/users/3425506", "pm_score": 1, "selected": false, "text": "const s = 'rabbit';\nconst triplets = [];\nfor(let i = 0; i < s.length; i=i+1){\n triplets.push(s.substring(i, i+3))\n}\nconst arrTriplets = [];\ntriplets.forEach(function(triplet){\n const tripArr = triplet.split('');\n arrTriplets.push(tripArr) \n})\nconst indexesToKeep = [];\narrTriplets.forEach(function(triplet, index){\n if (triplet.length === 3 && triplet[0] !== triplet[1] && triplet[1] !== triplet[2] && triplet[0] !== triplet[2]){\n indexesToKeep.push(index);\n }\n})\nconst result = [];\nindexesToKeep.forEach(function(index){\n result.push(arrTriplets[index]);\n})\nconsole.log('n =', result.length);\nconsole.log('result', result);" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20375229/" ]
74,481,678
<p>I have two datasets of sales data at the end of month. I am just trying to find the matching rows from the dataset A and pull the shipped value from the dataset B. I have tried using merge and match but the values don't line up or the dataset explodes. I made a small example the real dataset has over 100 columns and around 500,00 rows but I didn't feel they were relevant.</p> <p>Data set A</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Order</th> <th>Shipped</th> </tr> </thead> <tbody> <tr> <td>John</td> <td>S</td> <td>300</td> <td>Y</td> </tr> <tr> <td>Tim</td> <td>B</td> <td>331</td> <td>Y</td> </tr> <tr> <td>Kathy</td> <td>J</td> <td>365</td> <td>N</td> </tr> <tr> <td>Clayton</td> <td>S</td> <td>362</td> <td>Y</td> </tr> <tr> <td>Ashley</td> <td>R</td> <td>364</td> <td>N</td> </tr> <tr> <td>John</td> <td>A</td> <td>321</td> <td>N</td> </tr> <tr> <td>John</td> <td>S</td> <td>388</td> <td>Y</td> </tr> <tr> <td>Ashley</td> <td>R</td> <td>338</td> <td>N</td> </tr> </tbody> </table> </div> <p>Dataset B</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Order</th> <th>Shipped</th> </tr> </thead> <tbody> <tr> <td>John</td> <td>S</td> <td>300</td> <td>Y</td> </tr> <tr> <td>Tim</td> <td>B</td> <td>331</td> <td>N</td> </tr> <tr> <td>Kathy</td> <td>J</td> <td>365</td> <td>N</td> </tr> <tr> <td>Clayton</td> <td>S</td> <td>362</td> <td>Y</td> </tr> <tr> <td>Ashley</td> <td>R</td> <td>364</td> <td>Y</td> </tr> <tr> <td>John</td> <td>A</td> <td>321</td> <td>Y</td> </tr> <tr> <td>Jake</td> <td>K</td> <td>333</td> <td>N</td> </tr> <tr> <td>Bobby</td> <td>J</td> <td>398</td> <td>N</td> </tr> </tbody> </table> </div> <p>Desired output</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Order</th> <th>Shipped A</th> <th>Shipped B</th> </tr> </thead> <tbody> <tr> <td>John</td> <td>S</td> <td>300</td> <td>Y</td> <td>Y</td> </tr> <tr> <td>Tim</td> <td>B</td> <td>331</td> <td>Y</td> <td>N</td> </tr> <tr> <td>Kathy</td> <td>J</td> <td>365</td> <td>N</td> <td>N</td> </tr> <tr> <td>Clayton</td> <td>S</td> <td>362</td> <td>Y</td> <td>Y</td> </tr> <tr> <td>Ashley</td> <td>R</td> <td>364</td> <td>N</td> <td>Y</td> </tr> <tr> <td>John</td> <td>A</td> <td>321</td> <td>N</td> <td>Y</td> </tr> <tr> <td>John</td> <td>S</td> <td>388</td> <td>Y</td> <td>N/A</td> </tr> <tr> <td>Ashley</td> <td>R</td> <td>338</td> <td>N</td> <td>N/A</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74481742, "author": "caTS", "author_id": 18244921, "author_profile": "https://Stackoverflow.com/users/18244921", "pm_score": 2, "selected": false, "text": "a != b && b != c" }, { "answer_id": 74481841, "author": "user3425506", "author_id": 3425506, "author_profile": "https://Stackoverflow.com/users/3425506", "pm_score": 1, "selected": false, "text": "const s = 'rabbit';\nconst triplets = [];\nfor(let i = 0; i < s.length; i=i+1){\n triplets.push(s.substring(i, i+3))\n}\nconst arrTriplets = [];\ntriplets.forEach(function(triplet){\n const tripArr = triplet.split('');\n arrTriplets.push(tripArr) \n})\nconst indexesToKeep = [];\narrTriplets.forEach(function(triplet, index){\n if (triplet.length === 3 && triplet[0] !== triplet[1] && triplet[1] !== triplet[2] && triplet[0] !== triplet[2]){\n indexesToKeep.push(index);\n }\n})\nconst result = [];\nindexesToKeep.forEach(function(index){\n result.push(arrTriplets[index]);\n})\nconsole.log('n =', result.length);\nconsole.log('result', result);" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10342813/" ]
74,481,682
<p>I wrote two Python functions for converting RGB colors of an image representing tuples to single integer values using two different approaches.</p> <p>In order to test if both the approaches deliver the same results it was necessary to frequently switch between the two code sections choosing which one should be run.</p> <p>Finally I decided to use only one of the approaches, but decided to keep the other one in the script code as it better demonstrates what the code does.</p> <p>In order to 'switch off' one block of code and 'switch on' another one I have used two different methods: an <code>if</code> code block (see one of the functions in the code below) and a triple quoted string.</p> <p>The first approach (with <code>if</code>) makes it necessary to introduce additional indentation to the code and the other one required to move a line with triple quotes from the bottom to the top of the code block with an intermediate triple quotes. Both methods work ok, but ...</p> <p>Is there a better and more easy way of such switching? Best if it would require to press a key on the keyboard only once in order to switch between the two code blocks?</p> <p>Here my code:</p> <pre><code># ====================================================================== ''' Conversion functions for single RGB-color values ''' def rgb2int(rgb_tuple): if 1: # &lt;&lt;&lt; change to 0 to switch to the else: part of code from sys import byteorder as endian # endianiness = sys.byteorder # 'little' int_rgb = int.from_bytes(bytearray(rgb_tuple), endian) # ,signed=False) else: if len(rgb_tuple) == 4: # RGBA tuple R,G,B,A = rgb_tuple else: R,G,B = rgb_tuple A = None if A is not None: int_rgb =( 0 ) + A else: int_rgb = 0 int_rgb = (int_rgb&lt;&lt;8) + B int_rgb = (int_rgb&lt;&lt;8) + G # ! int_rgb&lt;&lt;8 + G == int_rgb&lt;&lt;(8+G) ! int_rgb = (int_rgb&lt;&lt;8) + R return int_rgb def int2rgb(int_rgb, alpha=False): from sys import byteorder as endian tplsize = 4 if alpha else 3 rgb_tuple = tuple(int_rgb.to_bytes(tplsize, endian)) # ,signed=False)) &quot;&quot;&quot; if not alpha: rgb_tuple = ( int_rgb &amp; 0xff, ( int_rgb &gt;&gt; 8 ) &amp; 0xff, ( int_rgb &gt;&gt; 16 ) &amp; 0xff ) else: # with alpha channel: rgb_tuple = ( int_rgb &amp; 0xff, ( int_rgb &gt;&gt; 8 ) &amp; 0xff, ( int_rgb &gt;&gt; 16 ) &amp; 0xff, ( int_rgb &gt;&gt; 24 ) &amp; 0xff ) &quot;&quot;&quot; # &lt;&lt;&lt; move to top to switch to the code block above return rgb_tuple rgb = (32,253,200,100) int_rgb = rgb2int(rgb) rgb_ = int2rgb(int_rgb, alpha=True) print(rgb, int_rgb, rgb_, sep='\n') assert rgb == rgb_ rgb = (32,253,200) int_rgb = rgb2int(rgb) rgb_ = int2rgb(int_rgb) assert rgb == rgb_ # --- if __name__ == &quot;__main__&quot;: print(' --- ') print(rgb) print(int_rgb) print(rgb_) #This gives: [32, 253, 200] 13172000 [32, 253, 200] </code></pre> <p>UPDATE because of response:</p> <p>Responding to a comment an explanation why I haven't choose to use two different functions to separate the pieces of code:</p> <p><em>Two separate functions would separate parts of code which belong together as code of one function and makes it necessary to explain in the code that both functions are doing exactly the same in spite of the fact they have different names.</em></p> <p>The use case is to test if two parts of code actually do exactly the same after editing their code in order to decide later which version to use. In the provided case the second code block can be used as an explanation what the other does, so it makes sense to keep it in the function in spite of the fact it won't be used.</p>
[ { "answer_id": 74481683, "author": "Claudio", "author_id": 7711283, "author_profile": "https://Stackoverflow.com/users/7711283", "pm_score": -1, "selected": false, "text": "'#'" }, { "answer_id": 74481741, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 1, "selected": false, "text": "def rgb2int_v1(rgb_tuple):\n from sys import byteorder as endian\n # endianiness = sys.byteorder # 'little'\n int_rgb = int.from_bytes(bytearray(rgb_tuple), endian) # ,signed=False)\n return int_rgb\n\n\ndef rgb2int_v2(rgb_tuple):\n if len(rgb_tuple) == 4: # RGBA tuple\n R,G,B,A = rgb_tuple\n else:\n R,G,B = rgb_tuple\n A = None\n if A is not None: \n int_rgb =( 0 ) + A \n else:\n int_rgb = 0\n int_rgb = (int_rgb<<8) + B\n int_rgb = (int_rgb<<8) + G # ! int_rgb<<8 + G == int_rgb<<(8+G) !\n int_rgb = (int_rgb<<8) + R\n return int_rgb\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7711283/" ]
74,481,688
<p>I am using a triangle to mark an event on a timeline in R, and I've given the coordinates to the specific position on the line where the event occurs in days. In the <code>points(</code> function, I have supplied <code>pch=25</code> to create the &quot;filled triangle&quot; shape. However, the positioning of the character is based on the center of the triangle. Is it possible to use an argument like &quot;pos&quot; (i.e. pos=3) so that the triangle is positioned immediately above the line and points to to X coordinate of interest?</p> <p>Example:</p> <pre><code>plot.new() segments(0, 0.5, 1, 0.5) points(0.5, 0.5, pch=25) </code></pre> <p>have</p> <p><a href="https://i.stack.imgur.com/fAKwH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fAKwH.png" alt="enter image description here" /></a></p> <p>want</p> <p><a href="https://i.stack.imgur.com/YPRb4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YPRb4.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74481683, "author": "Claudio", "author_id": 7711283, "author_profile": "https://Stackoverflow.com/users/7711283", "pm_score": -1, "selected": false, "text": "'#'" }, { "answer_id": 74481741, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 1, "selected": false, "text": "def rgb2int_v1(rgb_tuple):\n from sys import byteorder as endian\n # endianiness = sys.byteorder # 'little'\n int_rgb = int.from_bytes(bytearray(rgb_tuple), endian) # ,signed=False)\n return int_rgb\n\n\ndef rgb2int_v2(rgb_tuple):\n if len(rgb_tuple) == 4: # RGBA tuple\n R,G,B,A = rgb_tuple\n else:\n R,G,B = rgb_tuple\n A = None\n if A is not None: \n int_rgb =( 0 ) + A \n else:\n int_rgb = 0\n int_rgb = (int_rgb<<8) + B\n int_rgb = (int_rgb<<8) + G # ! int_rgb<<8 + G == int_rgb<<(8+G) !\n int_rgb = (int_rgb<<8) + R\n return int_rgb\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/821649/" ]
74,481,703
<p>How do I convert this input:</p> <pre><code>values = ['v1,v2', 'v3'] </code></pre> <p>to this output:</p> <pre><code>['v1', 'v2', 'v3'] </code></pre> <hr /> <p>Attempt without list comprehension that works:</p> <pre><code>values = ['v1,v2', 'v3'] parsed_values = [] for v in values: if ',' in v: parsed_values.extend(v.split(',')) else: parsed_values.append(v) print(parsed_values) # ['v1', 'v2', 'v3'] </code></pre> <hr /> <p>Attempt with list comprehension that does not work:</p> <pre><code>parsed_values = [_ for _ in [v.split(',') if ',' in v else v for v in values]] # [['v1', 'v2'], 'v3'] </code></pre>
[ { "answer_id": 74481730, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 2, "selected": false, "text": "values = [\"v1,v2\", \"v3\"]\n\nvalues = \",\".join(values).split(\",\")\nprint(values)\n" }, { "answer_id": 74481738, "author": "azro", "author_id": 7212686, "author_profile": "https://Stackoverflow.com/users/7212686", "pm_score": 3, "selected": false, "text": "values = ['v1,v2', 'v3']\nparsed_values = [word for value in values for word in value.split(\",\")]\nprint(parsed_values)\n# ['v1', 'v2', 'v3']\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8430155/" ]
74,481,723
<p>In my code, on hover the direction of linear-gradient animation is like counterclockwise, how can do it stright linear from top right to bottom left?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.boxstyle { background-color:rgba(0,69,255,1); background-size: 0% 100%; transition: background-color .5s; width: 150px; height: 150px; } .boxstyle:hover { background-image:linear-gradient(to left bottom, rgba(189,41,242,0) 0%, rgba(189,41,242,0) 40%, rgba(189,41,242, 0.9) 100%); background-repeat:no-repeat; background-size: 200% 100%; transition:background-size 1s, background-color 1s; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="boxstyle"&gt;hover it&lt;/div&gt;</code></pre> </div> </div> <a href="https://i.stack.imgur.com/NI1xq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NI1xq.png" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/gTPpy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gTPpy.png" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/KrBQU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KrBQU.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74481730, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 2, "selected": false, "text": "values = [\"v1,v2\", \"v3\"]\n\nvalues = \",\".join(values).split(\",\")\nprint(values)\n" }, { "answer_id": 74481738, "author": "azro", "author_id": 7212686, "author_profile": "https://Stackoverflow.com/users/7212686", "pm_score": 3, "selected": false, "text": "values = ['v1,v2', 'v3']\nparsed_values = [word for value in values for word in value.split(\",\")]\nprint(parsed_values)\n# ['v1', 'v2', 'v3']\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3014233/" ]
74,481,728
<p>I am attempting to create a put request to an API using Flutter using the following function:</p> <pre><code>Future&lt;http.Response&gt; login(String username, String password) { return http.put( Uri.parse('apiurl'), headers: &lt;String, String&gt;{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode( &lt;String, String&gt;{'username': username, 'password': password})); } </code></pre> <p>The issue I am running into is that it keeps erroring out at the <code>jsonEncode</code> line, saying it is not defined. I have included the following packages:</p> <pre><code>import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; </code></pre> <p>What am I missing to make the <code>jsonEncode</code> function exist?</p>
[ { "answer_id": 74481730, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 2, "selected": false, "text": "values = [\"v1,v2\", \"v3\"]\n\nvalues = \",\".join(values).split(\",\")\nprint(values)\n" }, { "answer_id": 74481738, "author": "azro", "author_id": 7212686, "author_profile": "https://Stackoverflow.com/users/7212686", "pm_score": 3, "selected": false, "text": "values = ['v1,v2', 'v3']\nparsed_values = [word for value in values for word in value.split(\",\")]\nprint(parsed_values)\n# ['v1', 'v2', 'v3']\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5326923/" ]
74,481,748
<p>permutations might not be exactly the right word.</p> <p>say <code>x = &quot;123456&quot;</code>. I want my code to output <code>['12','23','34','45','56']</code>. Right now, I know how to split it into <code>['12','34','56']</code></p>
[ { "answer_id": 74481730, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 2, "selected": false, "text": "values = [\"v1,v2\", \"v3\"]\n\nvalues = \",\".join(values).split(\",\")\nprint(values)\n" }, { "answer_id": 74481738, "author": "azro", "author_id": 7212686, "author_profile": "https://Stackoverflow.com/users/7212686", "pm_score": 3, "selected": false, "text": "values = ['v1,v2', 'v3']\nparsed_values = [word for value in values for word in value.split(\",\")]\nprint(parsed_values)\n# ['v1', 'v2', 'v3']\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20533786/" ]
74,481,753
<p>I am trying to select multiple values between a range fom all rows per each column and plot them all-together.</p> <p>The values in the dataframe are between 0 and 100. I want to select a range of values between 0 to 10 for all rows of one column, and then repeat that iteration every 10 values until 100 (e.g.: values between 0 to 10: 2, 4, 6, 9, 1 and then 10 to 20, 20 to 30, etc.) for each column.</p> <p>After importing data</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame(np.random.randint(0, 100, size = (100, 10)), columns=list('ABCDEFGHIJ')) </code></pre> <p>I am aware that I can select rows based on multiple column conditions with the following function</p> <pre><code>df_1 = df.A[(df.A &gt; 0) &amp; (df.A &lt; 10)] </code></pre> <p>However, by doing it this way I can only select one range of values per one column at a time.</p> <p>Is there a better way how to do this for a full range of values (0 to 100 every 10 iterations) and for all columns, rather than doing it manually for every range for all columns? If done manually, I need to set up 10 conditions per column and since there are 10 columns in the dataframe, it would end up with 100 conditions, which I wish to omit if possible.</p> <p>I am also interested if there is a counter library that can do this kind of operation, just to provide an output of how many rows are between 0 to 10 every 10 iterations for each column.</p>
[ { "answer_id": 74481730, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 2, "selected": false, "text": "values = [\"v1,v2\", \"v3\"]\n\nvalues = \",\".join(values).split(\",\")\nprint(values)\n" }, { "answer_id": 74481738, "author": "azro", "author_id": 7212686, "author_profile": "https://Stackoverflow.com/users/7212686", "pm_score": 3, "selected": false, "text": "values = ['v1,v2', 'v3']\nparsed_values = [word for value in values for word in value.split(\",\")]\nprint(parsed_values)\n# ['v1', 'v2', 'v3']\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20528268/" ]
74,481,783
<p>I'm using Python/ Pandas. I'm receiving output that is coming in this format where the actual date value is in the column header of the csv</p> <p><a href="https://i.stack.imgur.com/Wp4kG.png" rel="nofollow noreferrer">enter image description here</a></p> <p>I need it to be in this format where there is a column &quot;date&quot; and &quot;value&quot; that hold the data</p> <p><a href="https://i.stack.imgur.com/lBGtA.png" rel="nofollow noreferrer">enter image description here</a></p> <p>I was trying to use Pandas but I'm not sure exactly how to transpose this csv</p>
[ { "answer_id": 74482144, "author": "CharlieBONS", "author_id": 20529340, "author_profile": "https://Stackoverflow.com/users/20529340", "pm_score": 0, "selected": false, "text": "import pandas as pd\nfrom datetime import datetime\n\ndf = pd.DataFrame({'Name':['Profit', 'Loss'],\n 'Account Code':['ABC', 'DEF'],\n 'Level Name':['Winner', 'Loser'],\n '01/2022':['100', '200'],\n '02/2022':['300', '400']})\n\nnew_df_dict = {'Name':[],\n 'Account Code' :[],\n 'Level Name':[],\n 'Value' : [],\n 'Date':[]}\n\nfor i in range(len(df['Name'])):\n for date_ in df.columns.values[list(df.columns.values).index('Level Name')+1:]:\n new_df_dict['Name'].append(df['Name'][i])\n new_df_dict['Account Code'].append(df['Account Code'][i])\n new_df_dict['Level Name'].append(df['Name'][i])\n new_df_dict['Value'].append(df[date_][i])\n new_df_dict['Date'].append(date_)\n\n\nfor dt in range(len(new_df_dict['Date'])):\n new_df_dict['Date'][dt] = datetime.strptime(new_df_dict['Date'][dt], '%m/%Y')\n\nnew_df = pd.DataFrame(new_df_dict)\n" }, { "answer_id": 74482311, "author": "Guillaume BEDOYA", "author_id": 20522241, "author_profile": "https://Stackoverflow.com/users/20522241", "pm_score": 1, "selected": false, "text": "melt" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20533745/" ]
74,481,785
<p>I have this table</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Column A</th> <th>Column B</th> </tr> </thead> <tbody> <tr> <td>Kelly</td> <td>0530,0630,1730</td> </tr> <tr> <td>Mark</td> <td>0830,1630,1530</td> </tr> <tr> <td>Jenn</td> <td>0530,0630,1630</td> </tr> </tbody> </table> </div> <p>I am trying to find a formula that will return all the people from column A that have 0530 in column B. So my output in a single cell would be Kelly, Jenn. I've tried several things on my own, but nothing seems to be working. Can anyone help?</p> <p>I've tried</p> <pre><code>=ARRAYFORMULA(TEXTJOIN(&quot;&quot;,FALSE,IF(D2:D8=&quot;0530&quot;,C2:C8,&quot;no&quot;))) </code></pre> <p>but everything is a &quot;no&quot; because the cells don't match exactly.</p>
[ { "answer_id": 74482144, "author": "CharlieBONS", "author_id": 20529340, "author_profile": "https://Stackoverflow.com/users/20529340", "pm_score": 0, "selected": false, "text": "import pandas as pd\nfrom datetime import datetime\n\ndf = pd.DataFrame({'Name':['Profit', 'Loss'],\n 'Account Code':['ABC', 'DEF'],\n 'Level Name':['Winner', 'Loser'],\n '01/2022':['100', '200'],\n '02/2022':['300', '400']})\n\nnew_df_dict = {'Name':[],\n 'Account Code' :[],\n 'Level Name':[],\n 'Value' : [],\n 'Date':[]}\n\nfor i in range(len(df['Name'])):\n for date_ in df.columns.values[list(df.columns.values).index('Level Name')+1:]:\n new_df_dict['Name'].append(df['Name'][i])\n new_df_dict['Account Code'].append(df['Account Code'][i])\n new_df_dict['Level Name'].append(df['Name'][i])\n new_df_dict['Value'].append(df[date_][i])\n new_df_dict['Date'].append(date_)\n\n\nfor dt in range(len(new_df_dict['Date'])):\n new_df_dict['Date'][dt] = datetime.strptime(new_df_dict['Date'][dt], '%m/%Y')\n\nnew_df = pd.DataFrame(new_df_dict)\n" }, { "answer_id": 74482311, "author": "Guillaume BEDOYA", "author_id": 20522241, "author_profile": "https://Stackoverflow.com/users/20522241", "pm_score": 1, "selected": false, "text": "melt" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20533778/" ]
74,481,798
<p>I am working on an algorithm where you press a button and 2 checks happen:</p> <ul> <li>You can only push a word into array if that word doesn't exist in the array already and starts with the same letter that the last word in the array ends with.</li> </ul> <p>I think i figured out the checks but i am trying to optimize it. If i type all lower case or all upper case it works, but if my word is &quot;Maine&quot;...the next word has to start with e and its &quot;Egypt&quot;, it will not accept it, i need to lower case it to be accepted.</p> <p>From what i understand one solution is to automatically convert all words in the Array to lower case or upper case and do the same to the word that is being added from field.value input.</p> <p>For the life of me, i cannot implement it for some reason, iv been at it for 3 hours already and tried different tutorials. Not sure what i am doing wrong at this point.</p> <p>Thank you for your time and explanation.</p> <pre><code>HTML &lt;div id=&quot;main-container&quot;&gt; &lt;input type=&quot;text&quot; id=&quot;field&quot; class=&quot;button&quot;&gt; &lt;div id=&quot;message&quot;&gt;&lt;/div&gt; &lt;button class=&quot;button&quot; id=&quot;play&quot;&gt;Plasdfay&lt;/button&gt; &lt;/div&gt; </code></pre> <pre><code>JS const field = document.querySelector('#field'); const message = document.querySelector('#message'); const playBtn = document.querySelector('#play') let usedCities = []; playBtn.addEventListener('click', function() { let fieldView = field.value; let lastWordInArray = usedCities[usedCities.length - 1] if(!usedCities[0] || !usedCities.includes(fieldView) &amp;&amp; lastWordInArray[lastWordInArray.length - 1] === fieldView[0]) { usedCities.push(fieldView) } console.log(usedCities) }) </code></pre>
[ { "answer_id": 74481875, "author": "DevQuayle", "author_id": 4604457, "author_profile": "https://Stackoverflow.com/users/4604457", "pm_score": 0, "selected": false, "text": "const field = document.querySelector('#field');\nconst message = document.querySelector('#message');\nconst playBtn = document.querySelector('#play')\n\nlet usedCities = [];\n\nplayBtn.addEventListener('click', function() {\n let fieldView = field.value;\n let lastWordInArray = usedCities[usedCities.length - 1]\n\n if(!usedCities[0] || !usedCities.includes(fieldView) && lastWordInArray[lastWordInArray.length - 1].toLowerCase() === fieldView[0].toLowerCase()) {\n usedCities.push(fieldView)\n\n }\n\n console.log(usedCities)\n \n})\n" }, { "answer_id": 74481897, "author": "kernell", "author_id": 5530875, "author_profile": "https://Stackoverflow.com/users/5530875", "pm_score": 1, "selected": false, "text": "const field = document.querySelector('#field');\nconst message = document.querySelector('#message');\nconst playBtn = document.querySelector('#play')\n\nlet usedCities = [];\n\nplayBtn.addEventListener('click', function() {\n let fieldView = field.value;\n let fieldViewLc = fieldView.toLowerCase();\n let checkUsedCities = usedCities.map(el => el.toLowerCase()); \n let lastWordInArray = checkUsedCities[checkUsedCities.length - 1]\n \n if(!checkUsedCities[0] || !checkUsedCities.includes(fieldViewLc) && lastWordInArray[lastWordInArray.length - 1] === fieldViewLc[0]) {\n usedCities.push(fieldView)\n\n }\n\n console.log(usedCities)\n \n})" }, { "answer_id": 74482005, "author": "Mohammed Jhosawa", "author_id": 5599067, "author_profile": "https://Stackoverflow.com/users/5599067", "pm_score": 2, "selected": true, "text": "const field = document.querySelector('#field');\nconst message = document.querySelector('#message');\nconst playBtn = document.querySelector('#play')\n\nlet usedCities = [];\n\nplayBtn.addEventListener('click', function() {\n let fieldView = field.value;\n let lastWordInArray = usedCities[usedCities.length - 1];\n\n if(!usedCities[0] || !usedCities.includes(fieldView) && lastWordInArray[lastWordInArray.length - 1] === (fieldView[0].toLowerCase() || fieldView[0].toUpperCase())) {\n usedCities.push(fieldView)\n }\n console.log(usedCities)\n})" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18992987/" ]
74,481,801
<p>I have a string that looks something similar to this:</p> <pre><code>28f1e5f7-47c6-4d67-bcbf-9e807c379076-9780-gThGFkHY0CeFCPwA6Efys7 </code></pre> <p>I would like to split it based on '-' but also tell it at what position or point to do the split. My goal is to drop the last two strings</p> <p>The end result of what I want should look something like this:</p> <pre><code>28f1e5f7-47c6-4d67-bcbf-9e807c379076 </code></pre> <p>I know i can split offset and then concat. I'm wondering if there is a more straight forward way around as it will require me to split 5 times and then concatenate 5 times?</p>
[ { "answer_id": 74481875, "author": "DevQuayle", "author_id": 4604457, "author_profile": "https://Stackoverflow.com/users/4604457", "pm_score": 0, "selected": false, "text": "const field = document.querySelector('#field');\nconst message = document.querySelector('#message');\nconst playBtn = document.querySelector('#play')\n\nlet usedCities = [];\n\nplayBtn.addEventListener('click', function() {\n let fieldView = field.value;\n let lastWordInArray = usedCities[usedCities.length - 1]\n\n if(!usedCities[0] || !usedCities.includes(fieldView) && lastWordInArray[lastWordInArray.length - 1].toLowerCase() === fieldView[0].toLowerCase()) {\n usedCities.push(fieldView)\n\n }\n\n console.log(usedCities)\n \n})\n" }, { "answer_id": 74481897, "author": "kernell", "author_id": 5530875, "author_profile": "https://Stackoverflow.com/users/5530875", "pm_score": 1, "selected": false, "text": "const field = document.querySelector('#field');\nconst message = document.querySelector('#message');\nconst playBtn = document.querySelector('#play')\n\nlet usedCities = [];\n\nplayBtn.addEventListener('click', function() {\n let fieldView = field.value;\n let fieldViewLc = fieldView.toLowerCase();\n let checkUsedCities = usedCities.map(el => el.toLowerCase()); \n let lastWordInArray = checkUsedCities[checkUsedCities.length - 1]\n \n if(!checkUsedCities[0] || !checkUsedCities.includes(fieldViewLc) && lastWordInArray[lastWordInArray.length - 1] === fieldViewLc[0]) {\n usedCities.push(fieldView)\n\n }\n\n console.log(usedCities)\n \n})" }, { "answer_id": 74482005, "author": "Mohammed Jhosawa", "author_id": 5599067, "author_profile": "https://Stackoverflow.com/users/5599067", "pm_score": 2, "selected": true, "text": "const field = document.querySelector('#field');\nconst message = document.querySelector('#message');\nconst playBtn = document.querySelector('#play')\n\nlet usedCities = [];\n\nplayBtn.addEventListener('click', function() {\n let fieldView = field.value;\n let lastWordInArray = usedCities[usedCities.length - 1];\n\n if(!usedCities[0] || !usedCities.includes(fieldView) && lastWordInArray[lastWordInArray.length - 1] === (fieldView[0].toLowerCase() || fieldView[0].toUpperCase())) {\n usedCities.push(fieldView)\n }\n console.log(usedCities)\n})" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20533789/" ]
74,481,873
<p>I am learning Flutter and currently am trying to send the index of the list item that is clicked, to another page. I have figured out how to open the new page using GestureDetector but am getting an error when trying to send the index as a string. Here is my code:</p> <pre><code>@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: ListView.builder( itemCount: totalItems, itemBuilder: (context, index) { return GestureDetector( child: Container( // This is the back container which will show next cell colour on the rounded edge color: index == totalItems-1 ? Colors.transparent : colours[(index+1)%2], child: Container( height: 180, decoration: BoxDecoration( borderRadius: const BorderRadius.only(bottomLeft: Radius.circular(85.0)), color: colours[index%2], ), child: Center( child: Text( index.toString(), style: const TextStyle(color: Colors.white, fontSize: 50), ), ), ), ), onTap: () =&gt; Navigator.push( context, MaterialPageRoute( builder: (context) =&gt; const Portfolio(title: 'Portfolio', index: toString(index)), ) ); }, ) </code></pre> <p>When trying to send index to the next page as &quot;toString(index)&quot;, I am getting an error that states</p> <blockquote> <p>&quot;A value of type Null can't be assigned to a parameter of type String in a const constructor&quot;</p> </blockquote> <p>When hardcoding a string, the code works. I just don't understand how index is a type Null here.</p> <p>Thank you!</p>
[ { "answer_id": 74481992, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 1, "selected": false, "text": "index" }, { "answer_id": 74482109, "author": "Delwinn", "author_id": 16714498, "author_profile": "https://Stackoverflow.com/users/16714498", "pm_score": 3, "selected": true, "text": "String" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18001565/" ]
74,481,905
<p>I have the following data</p> <pre><code>data have; input id seq value; datalines; 1 1 4 1 2 4 1 3 0 1 4 0 1 5 0 1 6 4 1 7 4 2 1 1 2 2 1 2 3 5 2 4 5 2 5 5 2 6 8 ; run; </code></pre> <p>I need to create a groupid variable, which depends on the id and value, so that the output looks like this,</p> <pre><code>id seq value grpid 1 1 4 1 1 2 4 1 1 3 0 2 1 4 0 2 1 5 0 2 1 6 4 3 1 7 4 3 2 1 1 1 2 2 1 1 2 3 5 2 2 4 5 2 2 5 5 2 2 6 8 3 </code></pre> <p>I have no idea how to achieve this, the error that I run into is this,</p> <blockquote> <p>ERROR: BY variables are not properly sorted on data set</p> </blockquote> <p>But I cannot change the sorting, the dataset needs to be sorted by id and seq variables first before generating the grpid.</p>
[ { "answer_id": 74481992, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 1, "selected": false, "text": "index" }, { "answer_id": 74482109, "author": "Delwinn", "author_id": 16714498, "author_profile": "https://Stackoverflow.com/users/16714498", "pm_score": 3, "selected": true, "text": "String" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1592397/" ]
74,481,925
<p>I'm trying to transform a PostGreSQL Query in Laravel Query Builder Syntax, but isn't working</p> <pre><code>SELECT users.*, rifs.rif FROM users JOIN rif_user on users.id = rif_user.user_id JOIN rifs ON rifs.id = rif_user.rif_id WHERE email = 'email@email.com'; $busq = DB::table(['users','rifs']) -&gt;select('rifs.nombre','users.email','rifs.rif') -&gt;join('rif_user','users.id', '=', 'rif_user.user_id') -&gt;join('rifs', 'rifs.id', '=', 'rif_user.rif_id') -&gt;where('email' ,'email@email.com') -&gt;get(); </code></pre> <p>I Try the code on Laravel Tinker and there is the Output:</p> <blockquote> <blockquote> <blockquote> <p>-&gt;select('rifs.nombre','users.email','rifs.rif') PHP Parse error: Syntax error, unexpected T_OBJECT_OPERATOR on line 1 -&gt;join('rif_user','users.id', '=', 'rif_user.user_id') PHP Parse error: Syntax error, unexpected T_OBJECT_OPERATOR on line 1 -&gt;join('rifs', 'rifs.id', '=', 'rif_user.rif_id') PHP Parse error: Syntax error, unexpected T_OBJECT_OPERATOR on line 1 -&gt;where('email' ,'email@email.com') PHP Parse error: Syntax error, unexpected T_OBJECT_OPERATOR on line 1 -&gt;get();</p> </blockquote> </blockquote> </blockquote>
[ { "answer_id": 74481992, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 1, "selected": false, "text": "index" }, { "answer_id": 74482109, "author": "Delwinn", "author_id": 16714498, "author_profile": "https://Stackoverflow.com/users/16714498", "pm_score": 3, "selected": true, "text": "String" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20533784/" ]
74,481,937
<p>I have stored some data in python and now I want to display it in django how can I do that?</p> <pre><code> animeUrl = &quot;https://api.jikan.moe/v4/top/anime&quot; animeResponse = requests.get(animeUrl).json() def topAnime(): for idx, video in enumerate(animeResponse['data']): animeUrl = video['url'] title = video['title'] status = video['status'] type = video['type'] images = video['images']['jpg']['image_url'] #if status == &quot;Currently Airing&quot;: print (idx+1,&quot;:&quot;,animeUrl, &quot;:&quot;, status, &quot;:&quot;, title, &quot;:&quot;, type, &quot;:&quot;, images) topAnime() </code></pre> <p>this is my stored data and now I want to display it on website, how can I do that? I'm newbie in django I'm looking for some suggestions</p> <p>I have tried using templates but it didn't worked</p>
[ { "answer_id": 74481992, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 1, "selected": false, "text": "index" }, { "answer_id": 74482109, "author": "Delwinn", "author_id": 16714498, "author_profile": "https://Stackoverflow.com/users/16714498", "pm_score": 3, "selected": true, "text": "String" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17685223/" ]
74,481,953
<p>In my tailwind config i extend the custom colors as followed:</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> theme: { extend: { colors: { // BACKGROUND COLORS // Light colorBgLight: "#fffef7", colorHeaderBgLight: $colorBgLight, } } }</code></pre> </div> </div> </p> <p>is there a way in the tailwind config I can reference the colorBgLight as a variable for the colorHeaderBgLight just like the example ?</p>
[ { "answer_id": 74482063, "author": "Raphael Cunha", "author_id": 7884624, "author_profile": "https://Stackoverflow.com/users/7884624", "pm_score": 3, "selected": true, "text": "// tailwind.config.js\n\nlet colorBgLight = \"#fffef7\"\n\ntheme: {\n extend: {\n colors: {\n // BACKGROUND COLORS\n // Light\n colorBgLight: colorBgLight,\n colorHeaderBgLight: colorBgLight,\n }\n }\n}\n" }, { "answer_id": 74482147, "author": "Edwin Fernando Pirajan Arevalo", "author_id": 20534030, "author_profile": "https://Stackoverflow.com/users/20534030", "pm_score": 1, "selected": false, "text": "let color1 = #f3f3f3\n\nlet color2 = #b5b4b9\n\ntheme: {\n extends: {\n colors: {\n colorBgLight: color1, //<---variable1\n colorHeaderBgLight: color2, //<---variable2\n }\n }\n}\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1443063/" ]
74,481,961
<p>Can Anyone please tell me the difference between these 3 snippets? I am facing these global and local variable access issue. No idea what is ({counter}). and why others are not giving me output.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var counter = 3; function example() { let counter = 50; console.log(this.counter); console.log(counter); }; example();</code></pre> </div> </div> </p> <p>Output :</p> <pre><code>Undefined 50 </code></pre> <p>VS</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var counter = 3; var example = function() { let counter = 50; console.log(this.counter); console.log(counter); } example.call(counter);</code></pre> </div> </div> </p> <p>Output :</p> <pre><code>Undefined 50 </code></pre> <p>VS</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var counter = 3; var example = function() { let counter = 50; console.log(this.counter); console.log(counter); } example.call({counter});</code></pre> </div> </div> </p> <p>Output</p> <pre><code>3 50 </code></pre>
[ { "answer_id": 74482298, "author": "Toban Harnish", "author_id": 20427085, "author_profile": "https://Stackoverflow.com/users/20427085", "pm_score": 1, "selected": false, "text": "function test(){\n return this;\n}\nconst returnVal = test.call({a:'a',b:'b',c:'c'});\nconsoel.log(returnVal) // prints out {a:'a',b:'b',c:'c'}\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74481961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5007664/" ]
74,482,035
<p>during deploing my Spring Boot App on heroku i got this error</p> <pre><code> Exception in thread &quot;main&quot; java.lang.NoClassDefFoundError: org/springframework/boot/SpringApplication </code></pre> <p>My Pom.xml build part:</p> <pre><code> &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;com.heroku.sdk&lt;/groupId&gt; &lt;artifactId&gt;heroku-maven-plugin&lt;/artifactId&gt; &lt;version&gt;1.1.3&lt;/version&gt; &lt;executions&gt; &lt;execution&gt; &lt;phase&gt;package&lt;/phase&gt; &lt;configuration&gt; &lt;artifactItems&gt; &lt;artifactItem&gt; &lt;groupId&gt;com.github.jsimone&lt;/groupId&gt; &lt;artifactId&gt;webapp-runner&lt;/artifactId&gt; &lt;version&gt;8.5.11.3&lt;/version&gt; &lt;destFileName&gt;webapp-runner.jar&lt;/destFileName&gt; &lt;/artifactItem&gt; &lt;/artifactItems&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; </code></pre> <p>I only found some solutions for running application localy but i have this problem only on Heroku side. In other solutions it is solved by updating dependencies. Problem is i have no idea how can i deploy my dependencies to HerokuApp.</p>
[ { "answer_id": 74488534, "author": "Hamza Khadhri", "author_id": 9523051, "author_profile": "https://Stackoverflow.com/users/9523051", "pm_score": 1, "selected": false, "text": "import org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class Application {\n\n public static void main(String[] args) {\n SpringApplication.run(Application.class, args);\n }\n}\n" }, { "answer_id": 74591049, "author": "Wiktor Bartoszyn", "author_id": 20479883, "author_profile": "https://Stackoverflow.com/users/20479883", "pm_score": 0, "selected": false, "text": "package com.wiktor.ecommerce;\n\nimport com.wiktor.ecommerce.Service.UserService;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;\nimport org.springframework.context.annotation.AnnotationConfigApplicationContext;\n\n\n@SpringBootApplication(exclude = {SecurityAutoConfiguration.class })\npublic class EcommerceApplication {\n\n public static void main(String[] args) {\n SpringApplication.run(EcommerceApplication.class, args);\n }\n\n}\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20479883/" ]
74,482,055
<p>After consulting the <a href="https://v2.ocaml.org/api/Format.html" rel="nofollow noreferrer">Format</a> and <a href="https://v2.ocaml.org/api/Printf.html" rel="nofollow noreferrer">Printf</a> module documentation, I'm still left with an unanswered question about the <code>%a</code> specifier.</p> <p>Starting with a very simple type:</p> <pre><code>type b = C of float </code></pre> <p>I can easily create a printing routine:</p> <pre><code>let pp ppf (C f) = Format.fprintf ppf &quot;%.2f&quot; f </code></pre> <p>Such that <code>Format.asprintf &quot;%a&quot; pp (C 7.6)</code> yields <code>&quot;7.60&quot;</code>.</p> <p>Now, <code>Format.asprintf &quot;%.3a&quot; pp (C 7.6)</code> runs without issue, but of course I still get <code>&quot;7.60&quot;</code>.</p> <p>Is there a way to access the modifier within <code>pp</code> to determine the precision to use?</p>
[ { "answer_id": 74482621, "author": "octachron", "author_id": 7369366, "author_profile": "https://Stackoverflow.com/users/7369366", "pm_score": 3, "selected": true, "text": "%a" }, { "answer_id": 74482712, "author": "glennsl", "author_id": 7943564, "author_profile": "https://Stackoverflow.com/users/7943564", "pm_score": 1, "selected": false, "text": "pp" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15261315/" ]
74,482,083
<p>I have a dataset, <strong>where when the sum of Q1 24 - Q4 24 is between the number 1 - 2.5, I would like to place the number 2 in that row under Q4 24.</strong></p> <p><strong>Data</strong></p> <pre><code>ID type Q1 24 Q2 24 Q3 24 Q4 24 AA hi 2.0 1.2 0.5 0.6 AA hello 0.7 2.0 0.6 0.6 AA bye 0.6 0.6 0.6 0.4 AA ok 0.3 0.4 0.2 0.2 </code></pre> <p><strong>Desired</strong></p> <pre><code>ID type Q1 24 Q2 24 Q3 24 Q4 24 AA hi 2.0 1.2 0.5 0.6 AA hello 0.7 2.0 0.6 0.6 AA bye 0.0 0.0 0.0 2.0 AA ok 0.0 0.0 0.0 2.0 </code></pre> <p><strong>Doing</strong></p> <pre><code>df.loc[df.iloc[:,2:].sum(axis=1)&gt;1&lt;2.5, ['Q1 24','Q2 24','Q3 24','Q4 24']]= 2 </code></pre> <p>A SO member helped with the above script, but how would I only target that row under Q4 24. I am thinking I can utilize iloc again for this. Any suggestion is appreciated.</p>
[ { "answer_id": 74482621, "author": "octachron", "author_id": 7369366, "author_profile": "https://Stackoverflow.com/users/7369366", "pm_score": 3, "selected": true, "text": "%a" }, { "answer_id": 74482712, "author": "glennsl", "author_id": 7943564, "author_profile": "https://Stackoverflow.com/users/7943564", "pm_score": 1, "selected": false, "text": "pp" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5942100/" ]
74,482,102
<p>That is maybe a dumb question or asked many times (if so, answer with existing link and I will close this post).</p> <p>Let's say in laravel by example, when send model id in route, everything is ok in php. But when a route must optional parameter defined as null in Vuejs (or undefined), Php gets this parameter as string.</p> <pre><code>//vuejs in methods: myFunction(id1, id2 = null) { axios.post(`/api/model1/${id1}/model2/${id2}`) .then((response) =&gt; { console.log(response); }) .catch(err =&gt; { console.log(err); }); }, </code></pre> <p>And</p> <pre><code>//Laravel routes/api.php for my api Route::post('model1/{id}/model2/{id2}', 'SomeController@doThis'); </code></pre> <blockquote> <p>Example: myapi/model1/{id1}/model2/{id2} and myapi/model1/987/model2/null</p> </blockquote> <p>So I get 'null' here for model2. (sometimes it is 'undefined' according to the situation)</p> <p>What is the better way to deal with it? without adding regex for my parameters? because I do not need regex for the first param what is id1.</p> <p>I try to deal with it many times, but it seems I always come back to this problem from time to time. I need to keep this in my mind once for all.</p>
[ { "answer_id": 74482621, "author": "octachron", "author_id": 7369366, "author_profile": "https://Stackoverflow.com/users/7369366", "pm_score": 3, "selected": true, "text": "%a" }, { "answer_id": 74482712, "author": "glennsl", "author_id": 7943564, "author_profile": "https://Stackoverflow.com/users/7943564", "pm_score": 1, "selected": false, "text": "pp" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7142629/" ]
74,482,117
<p>I have a class I wrote where a majority (but not all) of its methods take in an int parameter <code>foo</code>:</p> <pre class="lang-py prettyprint-override"><code>class MyClass: def fun_one(self, foo: int): pass def fun_two(self, foo: int, flu: int): pass def fun_three(self, flu: str, foo: int): pass def fun_four(self): pass </code></pre> <p>Is there any way I can make my program log the values of <code>foo</code> whenever they come in in any of the methods without needing to manually go to every relevant function and add <code>print(foo)</code>?</p> <p>Also important to note, sometimes <code>None</code> will be passed as a parameter to these functions. There needs to be a distinction between functions which simply don't have the parameter and functions where the parameter's value is <code>None</code>.</p> <p>The easiest solution I can think of is using regex to find every instance of <code>def … foo … :</code>, then adding a line break and print statement after each line, but I'm trying to see if there's a built-in, nicer way I can do this.</p> <p>Thank you so much!</p>
[ { "answer_id": 74482621, "author": "octachron", "author_id": 7369366, "author_profile": "https://Stackoverflow.com/users/7369366", "pm_score": 3, "selected": true, "text": "%a" }, { "answer_id": 74482712, "author": "glennsl", "author_id": 7943564, "author_profile": "https://Stackoverflow.com/users/7943564", "pm_score": 1, "selected": false, "text": "pp" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10442089/" ]
74,482,138
<p>I have a function like this:</p> <pre><code>function refactorQueryResult&lt;D, E&gt;( name: string, original: UseQueryResult&lt;D, E&gt; ) { return { [name]: original.data, [`${name}UpdatedAt`]: original.dataUpdatedAt, [`${name}Error`]: original.error, [`${name}ErrorUpdatedAt`]: original.errorUpdatedAt, [`${name}FailureCount`]: original.failureCount, [`${name}HasError`]: original.isError, [`${name}Fetched`]: original.isFetched, [`${name}FetchedAfterMount`]: original.isFetchedAfterMount, [`${name}Fetching`]: original.isFetching, [`${name}Idle`]: original.isIdle, [`${name}Loading`]: original.isLoading, [`${name}HasLoadingError`]: original.isLoadingError, [`${name}IsPlaceholder`]: original.isPlaceholderData, [`${name}IsPrevious`]: original.isPreviousData, [`${name}HasRefetchError`]: original.isRefetchError, [`${name}Refetching`]: original.isRefetching, [`${name}HasSuccess`]: original.isSuccess, [`${name}IsStale`]: original.isStale, [`fetch${name[0].toUpperCase()}${name.slice(1)}`]: original.refetch, [`remove${name[0].toUpperCase()}${name.slice(1)}`]: original.remove, [`${name}Status`]: original.status, }; } </code></pre> <p>But to my dismay, when I use the result:</p> <pre><code>const { cards } = refactorQueryResult(&quot;cards&quot;, useQuery(listCards(filters))) </code></pre> <p>Typescript complains that cards does not exists, but of course it does.</p> <p>Is there a way to type hint the return value?</p> <p>Keep in mind I do realize I can just do:</p> <pre><code>const { data: cards, isFetched: cardsFetched /*, etc */ } = useQuery(listCards(filters)) </code></pre> <p>But I'm both lazy and curious, so I am wondering if there isn't a way to waste a couple of processor cycles so I have to type less.</p> <p>For a much simpler function, I've tried:</p> <pre><code>function renameData&lt;D, E&gt;( name: string, queryResult: UseQueryResult&lt;D, E&gt; ): { [name]: D } &amp; UseQueryOptions&lt;D, E&gt; { } &amp; UseQueryResult&lt;D, E&gt; { return { [name]: queryResult.data, ...queryResult } } </code></pre> <p>But here typescript complains: <code>A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type</code></p> <p>I think it is probably not possible without adding another type parameter. So something like:</p> <pre><code>export function refactorQueryResult&lt;T, D, E&gt;( name: string, original: UseQueryResult&lt;D, E&gt; ): ComplicatedTemplateMapping&lt;T, UseQueryResult&lt;D, E&gt;&gt; { // ... } // Then elsewhere const { cards, cardsFetched } = refactorQueryResult&lt;{ cards }&gt;( &quot;cards&quot;, useQuery(listCards(filters)) ) </code></pre> <p>But here I'm not sure how to even begin with the checks and slicing in <code>ComplicatedTemplateMapping</code></p>
[ { "answer_id": 74520223, "author": "kaan_a", "author_id": 1788771, "author_profile": "https://Stackoverflow.com/users/1788771", "pm_score": 0, "selected": false, "text": "function refactorQueryResult<D, E>(\n name: string,\n original: UseQueryResult<D, E>\n) \n" }, { "answer_id": 74543543, "author": "captain-yossarian from Ukraine", "author_id": 8495254, "author_profile": "https://Stackoverflow.com/users/8495254", "pm_score": 2, "selected": true, "text": "interface UseQueryResult<TData = unknown, TError = unknown> {\n data: TData | undefined;\n dataUpdatedAt: number;\n error: TError | null;\n errorUpdatedAt: number;\n failureCount: number;\n isError: boolean;\n}\n\nfunction refactorQueryResult<D, E, T extends string>(\n name: T,\n original: UseQueryResult<D, E>\n): TransformedData<UseQueryResult<D, E>, T> {\n return {\n [name]: original.data,\n [`${name}UpdatedAt`]: original.dataUpdatedAt,\n [`${name}Error`]: original.error,\n [`${name}ErrorUpdatedAt`]: original.errorUpdatedAt,\n [`${name}FailureCount`]: original.failureCount,\n [`${name}HasError`]: original.isError,\n };\n}\n\ntype MappedData<N extends string> = {\n data: N,\n dataUpdatedAt: `${N}UpdatedAt`,\n error: `${N}Error`,\n errorUpdatedAt: `${N}ErrorUpdatedAt`,\n failureCount: `${N}FailureCount`\n isError: `${N}HasError`\n}\n\ntype TransformedData<QR, N extends string> = {\n [P in keyof QR as P extends keyof MappedData<N> ? MappedData<N>[P] : never]: QR[P]\n}\n\nfunction test(queryResult: UseQueryResult) {\n const {\n test,\n testError,\n testUpdatedAt,\n testErrorUpdatedAt,\n testHasError,\n } = refactorQueryResult(\"test\", queryResult)\n}\n\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1788771/" ]
74,482,143
<pre><code> if(toggle == 1){ fill(150,10); rect(width+435,400,200,height); fill(0); textSize(20); text(&quot; R = Restart&quot;,1120,500); } } } void keyPressed() { if(key=='R' || key == 'r') { } } </code></pre> <p>I have done everything that I know and still haven't reached a point. I have done and approached my problem with a lot of methods and neither one of them was true for my case.my problem is with the r which stands for restart the sketch.</p>
[ { "answer_id": 74520223, "author": "kaan_a", "author_id": 1788771, "author_profile": "https://Stackoverflow.com/users/1788771", "pm_score": 0, "selected": false, "text": "function refactorQueryResult<D, E>(\n name: string,\n original: UseQueryResult<D, E>\n) \n" }, { "answer_id": 74543543, "author": "captain-yossarian from Ukraine", "author_id": 8495254, "author_profile": "https://Stackoverflow.com/users/8495254", "pm_score": 2, "selected": true, "text": "interface UseQueryResult<TData = unknown, TError = unknown> {\n data: TData | undefined;\n dataUpdatedAt: number;\n error: TError | null;\n errorUpdatedAt: number;\n failureCount: number;\n isError: boolean;\n}\n\nfunction refactorQueryResult<D, E, T extends string>(\n name: T,\n original: UseQueryResult<D, E>\n): TransformedData<UseQueryResult<D, E>, T> {\n return {\n [name]: original.data,\n [`${name}UpdatedAt`]: original.dataUpdatedAt,\n [`${name}Error`]: original.error,\n [`${name}ErrorUpdatedAt`]: original.errorUpdatedAt,\n [`${name}FailureCount`]: original.failureCount,\n [`${name}HasError`]: original.isError,\n };\n}\n\ntype MappedData<N extends string> = {\n data: N,\n dataUpdatedAt: `${N}UpdatedAt`,\n error: `${N}Error`,\n errorUpdatedAt: `${N}ErrorUpdatedAt`,\n failureCount: `${N}FailureCount`\n isError: `${N}HasError`\n}\n\ntype TransformedData<QR, N extends string> = {\n [P in keyof QR as P extends keyof MappedData<N> ? MappedData<N>[P] : never]: QR[P]\n}\n\nfunction test(queryResult: UseQueryResult) {\n const {\n test,\n testError,\n testUpdatedAt,\n testErrorUpdatedAt,\n testHasError,\n } = refactorQueryResult(\"test\", queryResult)\n}\n\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20534025/" ]
74,482,151
<p>I want to render a list in react native. The list items should be very simple, at least in theory. It has a header and a body. The header is no problem. It's just a <code>Text</code> component. But I do struggle with the body component.</p> <p>This is how the list item looks like right now:<a href="https://i.stack.imgur.com/u2M5h.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u2M5h.png" alt="" /></a></p> <p>Below is an illustration on how I would like the list item to look like:</p> <p><a href="https://i.stack.imgur.com/LHlVk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LHlVk.png" alt="enter image description here" /></a></p> <p>As you see, the desired result would be to stack all the components in the body next to each other horizontally(flexDirection:'row'), this would require that part of the custom component(se below:&quot;ListItemBodyElement&quot;) should break to a new line if it doesn't fit the previous line.</p> <p>This is the current code(I've left out the code for the header component for brevity):</p> <p>ParentView:</p> <pre><code>const ListItemBody = props =&gt; { return &lt;View style={{flexDirection:'row',flexWrap:'wrap',justifyContent:'flex-start'}}&gt;{props.children}&lt;/View&gt;; }; </code></pre> <p>The <code>props.children</code> contains of x <code>ListItemBodyElement</code>:</p> <pre><code>const ListItemBodyElement = props =&gt; { return ( &lt;View style={{flexDirection:'row'}}&gt; {props.icon &amp;&amp; &lt;props.icon style={styles.icon} name={props.iconName} /&gt;} &lt;Text style={{...styles.label, ...props.labelStyle}}&gt;{props.label}&lt;/Text&gt; &lt;/View&gt; ); }; </code></pre> <p>Is it possible to achieve the desired result?<br /> Thanks in advance. /Arif</p>
[ { "answer_id": 74520223, "author": "kaan_a", "author_id": 1788771, "author_profile": "https://Stackoverflow.com/users/1788771", "pm_score": 0, "selected": false, "text": "function refactorQueryResult<D, E>(\n name: string,\n original: UseQueryResult<D, E>\n) \n" }, { "answer_id": 74543543, "author": "captain-yossarian from Ukraine", "author_id": 8495254, "author_profile": "https://Stackoverflow.com/users/8495254", "pm_score": 2, "selected": true, "text": "interface UseQueryResult<TData = unknown, TError = unknown> {\n data: TData | undefined;\n dataUpdatedAt: number;\n error: TError | null;\n errorUpdatedAt: number;\n failureCount: number;\n isError: boolean;\n}\n\nfunction refactorQueryResult<D, E, T extends string>(\n name: T,\n original: UseQueryResult<D, E>\n): TransformedData<UseQueryResult<D, E>, T> {\n return {\n [name]: original.data,\n [`${name}UpdatedAt`]: original.dataUpdatedAt,\n [`${name}Error`]: original.error,\n [`${name}ErrorUpdatedAt`]: original.errorUpdatedAt,\n [`${name}FailureCount`]: original.failureCount,\n [`${name}HasError`]: original.isError,\n };\n}\n\ntype MappedData<N extends string> = {\n data: N,\n dataUpdatedAt: `${N}UpdatedAt`,\n error: `${N}Error`,\n errorUpdatedAt: `${N}ErrorUpdatedAt`,\n failureCount: `${N}FailureCount`\n isError: `${N}HasError`\n}\n\ntype TransformedData<QR, N extends string> = {\n [P in keyof QR as P extends keyof MappedData<N> ? MappedData<N>[P] : never]: QR[P]\n}\n\nfunction test(queryResult: UseQueryResult) {\n const {\n test,\n testError,\n testUpdatedAt,\n testErrorUpdatedAt,\n testHasError,\n } = refactorQueryResult(\"test\", queryResult)\n}\n\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5236141/" ]
74,482,161
<p>I am able to work with queries in C#. But I don't know how to write this subquery. Thank you for any help.</p> <pre><code>SELECT * FROM Stores.PerformanceRealization PR LEFT JOIN Stores.GroupRealization ON Stores.GroupRealization.Id = PR.GroupRealizationId WHERE PR.Deadline = (SELECT MAX(Deadline) FROM Stores.PerformanceRealization PR2 WHERE PR.GroupRealizationId = PR2.GroupRealizationId) </code></pre> <p>I tried something like this:</p> <pre><code>var result = from aa in _context.PerformanceRealization join bb in _context.GroupRealization on bb.Id equals aa.GroupRealizationId where aa.Deadline = (from cc in _context.PerformanceRealization where aa.GroupRealizationId = cc.GroupRealizationId select max(cc.Deadline)) select aa; </code></pre>
[ { "answer_id": 74520223, "author": "kaan_a", "author_id": 1788771, "author_profile": "https://Stackoverflow.com/users/1788771", "pm_score": 0, "selected": false, "text": "function refactorQueryResult<D, E>(\n name: string,\n original: UseQueryResult<D, E>\n) \n" }, { "answer_id": 74543543, "author": "captain-yossarian from Ukraine", "author_id": 8495254, "author_profile": "https://Stackoverflow.com/users/8495254", "pm_score": 2, "selected": true, "text": "interface UseQueryResult<TData = unknown, TError = unknown> {\n data: TData | undefined;\n dataUpdatedAt: number;\n error: TError | null;\n errorUpdatedAt: number;\n failureCount: number;\n isError: boolean;\n}\n\nfunction refactorQueryResult<D, E, T extends string>(\n name: T,\n original: UseQueryResult<D, E>\n): TransformedData<UseQueryResult<D, E>, T> {\n return {\n [name]: original.data,\n [`${name}UpdatedAt`]: original.dataUpdatedAt,\n [`${name}Error`]: original.error,\n [`${name}ErrorUpdatedAt`]: original.errorUpdatedAt,\n [`${name}FailureCount`]: original.failureCount,\n [`${name}HasError`]: original.isError,\n };\n}\n\ntype MappedData<N extends string> = {\n data: N,\n dataUpdatedAt: `${N}UpdatedAt`,\n error: `${N}Error`,\n errorUpdatedAt: `${N}ErrorUpdatedAt`,\n failureCount: `${N}FailureCount`\n isError: `${N}HasError`\n}\n\ntype TransformedData<QR, N extends string> = {\n [P in keyof QR as P extends keyof MappedData<N> ? MappedData<N>[P] : never]: QR[P]\n}\n\nfunction test(queryResult: UseQueryResult) {\n const {\n test,\n testError,\n testUpdatedAt,\n testErrorUpdatedAt,\n testHasError,\n } = refactorQueryResult(\"test\", queryResult)\n}\n\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17638875/" ]
74,482,195
<p>I have a project of mine where a click should happen (click first one from collapsed list item), but it should happen automatically without user taking mouse on it(cursor) and clicking it.</p> <p>that list item collapse comes from material ui.</p> <p>any idea is appreciated.</p> <p>my code to try : <a href="https://codesandbox.io/s/material-ui-nested-list-forked-2sqtum?file=/src/components/NestedItem/index.js" rel="nofollow noreferrer">https://codesandbox.io/s/material-ui-nested-list-forked-2sqtum?file=/src/components/NestedItem/index.js</a></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>import React, { useState } from "react"; import List from "@material-ui/core/List"; import ListItem from "@material-ui/core/ListItem"; import ListItemText from "@material-ui/core/ListItemText"; import Collapse from "@material-ui/core/Collapse"; const NestedItem = ({ children }) =&gt; { const [isOpen, setIsOpen] = useState(false); const handleIsOpen = () =&gt; { setIsOpen((prev) =&gt; !prev); }; const data = ["Someshit inside Collapse", "Someshit inside Collapse 2"]; return ( &lt;List&gt; &lt;ListItem button onClick={handleIsOpen}&gt; &lt;ListItemText primary={children} /&gt; &lt;/ListItem&gt; &lt;Collapse in={isOpen}&gt; {data.map((el) =&gt; ( &lt;List&gt; &lt;ListItem button&gt; &lt;ListItemText primary={el} /&gt; &lt;/ListItem&gt;{" "} &lt;/List&gt; ))} &lt;List&gt;&lt;/List&gt; &lt;/Collapse&gt; &lt;/List&gt; ); }; export default NestedItem;</code></pre> </div> </div> </p> <p>this should be clicked ('Someshit inside Collapse') when user opens the page and just once, it could print console.log('text Someshit inside Collapse is clicked'):</p> <p><a href="https://i.stack.imgur.com/tyzgp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tyzgp.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74520223, "author": "kaan_a", "author_id": 1788771, "author_profile": "https://Stackoverflow.com/users/1788771", "pm_score": 0, "selected": false, "text": "function refactorQueryResult<D, E>(\n name: string,\n original: UseQueryResult<D, E>\n) \n" }, { "answer_id": 74543543, "author": "captain-yossarian from Ukraine", "author_id": 8495254, "author_profile": "https://Stackoverflow.com/users/8495254", "pm_score": 2, "selected": true, "text": "interface UseQueryResult<TData = unknown, TError = unknown> {\n data: TData | undefined;\n dataUpdatedAt: number;\n error: TError | null;\n errorUpdatedAt: number;\n failureCount: number;\n isError: boolean;\n}\n\nfunction refactorQueryResult<D, E, T extends string>(\n name: T,\n original: UseQueryResult<D, E>\n): TransformedData<UseQueryResult<D, E>, T> {\n return {\n [name]: original.data,\n [`${name}UpdatedAt`]: original.dataUpdatedAt,\n [`${name}Error`]: original.error,\n [`${name}ErrorUpdatedAt`]: original.errorUpdatedAt,\n [`${name}FailureCount`]: original.failureCount,\n [`${name}HasError`]: original.isError,\n };\n}\n\ntype MappedData<N extends string> = {\n data: N,\n dataUpdatedAt: `${N}UpdatedAt`,\n error: `${N}Error`,\n errorUpdatedAt: `${N}ErrorUpdatedAt`,\n failureCount: `${N}FailureCount`\n isError: `${N}HasError`\n}\n\ntype TransformedData<QR, N extends string> = {\n [P in keyof QR as P extends keyof MappedData<N> ? MappedData<N>[P] : never]: QR[P]\n}\n\nfunction test(queryResult: UseQueryResult) {\n const {\n test,\n testError,\n testUpdatedAt,\n testErrorUpdatedAt,\n testHasError,\n } = refactorQueryResult(\"test\", queryResult)\n}\n\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17292277/" ]
74,482,208
<p>I want to delete the angular mat table selected row, can you help with that?</p> <p>Delete the row using a button placed outside of the table instead of using a delete button on each row of the table.</p> <p><a href="https://i.stack.imgur.com/84bPI.png" rel="nofollow noreferrer">enter image description here</a></p>
[ { "answer_id": 74520223, "author": "kaan_a", "author_id": 1788771, "author_profile": "https://Stackoverflow.com/users/1788771", "pm_score": 0, "selected": false, "text": "function refactorQueryResult<D, E>(\n name: string,\n original: UseQueryResult<D, E>\n) \n" }, { "answer_id": 74543543, "author": "captain-yossarian from Ukraine", "author_id": 8495254, "author_profile": "https://Stackoverflow.com/users/8495254", "pm_score": 2, "selected": true, "text": "interface UseQueryResult<TData = unknown, TError = unknown> {\n data: TData | undefined;\n dataUpdatedAt: number;\n error: TError | null;\n errorUpdatedAt: number;\n failureCount: number;\n isError: boolean;\n}\n\nfunction refactorQueryResult<D, E, T extends string>(\n name: T,\n original: UseQueryResult<D, E>\n): TransformedData<UseQueryResult<D, E>, T> {\n return {\n [name]: original.data,\n [`${name}UpdatedAt`]: original.dataUpdatedAt,\n [`${name}Error`]: original.error,\n [`${name}ErrorUpdatedAt`]: original.errorUpdatedAt,\n [`${name}FailureCount`]: original.failureCount,\n [`${name}HasError`]: original.isError,\n };\n}\n\ntype MappedData<N extends string> = {\n data: N,\n dataUpdatedAt: `${N}UpdatedAt`,\n error: `${N}Error`,\n errorUpdatedAt: `${N}ErrorUpdatedAt`,\n failureCount: `${N}FailureCount`\n isError: `${N}HasError`\n}\n\ntype TransformedData<QR, N extends string> = {\n [P in keyof QR as P extends keyof MappedData<N> ? MappedData<N>[P] : never]: QR[P]\n}\n\nfunction test(queryResult: UseQueryResult) {\n const {\n test,\n testError,\n testUpdatedAt,\n testErrorUpdatedAt,\n testHasError,\n } = refactorQueryResult(\"test\", queryResult)\n}\n\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20534077/" ]
74,482,213
<p>Suppose the following data:</p> <pre><code>foo &lt;- data.frame( key=c('one', 'two', 'three'), val=c('a', 'b|c', 'd|e|f'), stringsAsFactors = F) </code></pre> <p>It looks like</p> <pre><code>&gt; foo key val 1 one a 2 two b|c 3 three d|e|f </code></pre> <p>I want output that is as follows:</p> <pre><code>bar &lt;- data.frame(key=c('one', 'two', 'two', 'three', 'three', 'three'), val=c('a', 'b', 'c', 'd', 'e', 'f'), stringsAsFactors = F) </code></pre> <p>That looks like</p> <pre><code>&gt; bar key val 1 one a 2 two b 3 two c 4 three d 5 three e 6 three f </code></pre> <p>The psuedo-code might be: split <code>val</code> by pipe (<code>|</code>), but into a variable (unknown) number of columns, then pivot longer.</p> <p>Suggestions?</p> <p>Ideally using the tidyverse.</p>
[ { "answer_id": 74520223, "author": "kaan_a", "author_id": 1788771, "author_profile": "https://Stackoverflow.com/users/1788771", "pm_score": 0, "selected": false, "text": "function refactorQueryResult<D, E>(\n name: string,\n original: UseQueryResult<D, E>\n) \n" }, { "answer_id": 74543543, "author": "captain-yossarian from Ukraine", "author_id": 8495254, "author_profile": "https://Stackoverflow.com/users/8495254", "pm_score": 2, "selected": true, "text": "interface UseQueryResult<TData = unknown, TError = unknown> {\n data: TData | undefined;\n dataUpdatedAt: number;\n error: TError | null;\n errorUpdatedAt: number;\n failureCount: number;\n isError: boolean;\n}\n\nfunction refactorQueryResult<D, E, T extends string>(\n name: T,\n original: UseQueryResult<D, E>\n): TransformedData<UseQueryResult<D, E>, T> {\n return {\n [name]: original.data,\n [`${name}UpdatedAt`]: original.dataUpdatedAt,\n [`${name}Error`]: original.error,\n [`${name}ErrorUpdatedAt`]: original.errorUpdatedAt,\n [`${name}FailureCount`]: original.failureCount,\n [`${name}HasError`]: original.isError,\n };\n}\n\ntype MappedData<N extends string> = {\n data: N,\n dataUpdatedAt: `${N}UpdatedAt`,\n error: `${N}Error`,\n errorUpdatedAt: `${N}ErrorUpdatedAt`,\n failureCount: `${N}FailureCount`\n isError: `${N}HasError`\n}\n\ntype TransformedData<QR, N extends string> = {\n [P in keyof QR as P extends keyof MappedData<N> ? MappedData<N>[P] : never]: QR[P]\n}\n\nfunction test(queryResult: UseQueryResult) {\n const {\n test,\n testError,\n testUpdatedAt,\n testErrorUpdatedAt,\n testHasError,\n } = refactorQueryResult(\"test\", queryResult)\n}\n\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34935/" ]
74,482,219
<p>I'm trying to make an animation that draws an SVG as you scroll down the page.</p> <p>I've managed to get it to work in vanilla js but having issues with react. Each time I refresh the page it crashes.</p> <p>I think it's due to the browser struggling to keep up to date with the most recent path length. as the error I'm getting is (path.getTotalLength is not a function) on each refresh.</p> <p>I'm also unsure how to link a react event listener to my HTML.</p> <p>Any advice about tackling this would be great</p> <p>Thanks</p> <pre><code>import { useRef } from &quot;react&quot;; function About() { const pathRef = useRef(); let path = pathRef; let pathLength = path.getTotalLength(); path.style.strokeDasharray = pathLength + &quot; &quot; + pathLength; path.style.strokeDashoffset = pathLength; window.addEventListener(&quot;scroll&quot;, () =&gt; { let scrollPercentage = (document.documentElement.scrollTop + document.body.scrollTop) / (document.documentElement.scrollHeight - document.documentElement.clientHeight); let drawLength = pathLength * scrollPercentage; path.style.strokeDashoffset = pathLength - drawLength; }); return ( &lt;div className=&quot;about&quot;&gt; &lt;div className=&quot;about__container&quot;&gt; &lt;svg viewBox=&quot;0 0 1043 1831&quot; fill=&quot;none&quot; preserveAspectRatio=&quot;xMidYMax meet&quot; &gt; &lt;path ref={path} d=&quot;M1184.5 3C503.5 3 763 316 595.5 431.5V376.5L645.5 423.5C664.167 436.167 708 446.5 736 426C764.312 405.271 763 402.5 763 402.5C754 390.667 730.4 368 690 368C649.6 368 620.5 409.624 612 418.276L609.5 609H995.5L1.5 1051.5H587.5C590 1059.67 603.3 1076 636.5 1076C638.5 1076 638.667 1074.67 638.5 1074C638.833 1065.33 640.5 1048.2 644.5 1049C649.5 1050 576 1037.5 603 980.5L609.5 971C607.833 961 605.5 941.1 609.5 941.5C613.5 941.9 631.167 950.333 639.5 954.5C651.9 951.3 679.333 952.167 691.5 953C699.667 948.167 716.2 939.1 717 941.5C718 944.5 721 967.5 719 972.5C726 986.5 745.5 1041 681.5 1050C684.5 1049 689.4 1057.8 689 1069L681.5 1440.5C677.5 1793.5 820 1654 1082.5 1654&quot; stroke=&quot;#0000FF&quot; stroke-width=&quot;6&quot; /&gt; ; &lt;/svg&gt; &lt;div className=&quot;about__landing&quot;&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; ); } export default About; </code></pre>
[ { "answer_id": 74520223, "author": "kaan_a", "author_id": 1788771, "author_profile": "https://Stackoverflow.com/users/1788771", "pm_score": 0, "selected": false, "text": "function refactorQueryResult<D, E>(\n name: string,\n original: UseQueryResult<D, E>\n) \n" }, { "answer_id": 74543543, "author": "captain-yossarian from Ukraine", "author_id": 8495254, "author_profile": "https://Stackoverflow.com/users/8495254", "pm_score": 2, "selected": true, "text": "interface UseQueryResult<TData = unknown, TError = unknown> {\n data: TData | undefined;\n dataUpdatedAt: number;\n error: TError | null;\n errorUpdatedAt: number;\n failureCount: number;\n isError: boolean;\n}\n\nfunction refactorQueryResult<D, E, T extends string>(\n name: T,\n original: UseQueryResult<D, E>\n): TransformedData<UseQueryResult<D, E>, T> {\n return {\n [name]: original.data,\n [`${name}UpdatedAt`]: original.dataUpdatedAt,\n [`${name}Error`]: original.error,\n [`${name}ErrorUpdatedAt`]: original.errorUpdatedAt,\n [`${name}FailureCount`]: original.failureCount,\n [`${name}HasError`]: original.isError,\n };\n}\n\ntype MappedData<N extends string> = {\n data: N,\n dataUpdatedAt: `${N}UpdatedAt`,\n error: `${N}Error`,\n errorUpdatedAt: `${N}ErrorUpdatedAt`,\n failureCount: `${N}FailureCount`\n isError: `${N}HasError`\n}\n\ntype TransformedData<QR, N extends string> = {\n [P in keyof QR as P extends keyof MappedData<N> ? MappedData<N>[P] : never]: QR[P]\n}\n\nfunction test(queryResult: UseQueryResult) {\n const {\n test,\n testError,\n testUpdatedAt,\n testErrorUpdatedAt,\n testHasError,\n } = refactorQueryResult(\"test\", queryResult)\n}\n\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18624593/" ]
74,482,251
<pre><code>public class Test12CompressString { public static String getCompressedString(String str) { String newString = &quot;&quot;; int count = 1; int len = str.length()-1; for (int i = 0; i &lt;= len ; i++) { if(i != len) { System.out.println(i); if(str.charAt(i) == str.charAt(i+1)) { count++; continue; } if(count == 1) { newString = newString+str.charAt(i); } else { newString = newString+str.charAt(i)+count; } if ( str.charAt(i) != str.charAt(i+1)) { count = 1; continue; } } } return newString; } public static void main(String[] args) { String str = &quot;abbbccccc&quot;; String ans = getCompressedString(str); System.out.print(ans); } } </code></pre> <h1>Expected Output : ab3c4</h1> <h1>Output I am getting : ab3</h1> <p>Can someone tell what am I missing and why the last character and it's count is missing from my output? Can someone correct my code?</p>
[ { "answer_id": 74520223, "author": "kaan_a", "author_id": 1788771, "author_profile": "https://Stackoverflow.com/users/1788771", "pm_score": 0, "selected": false, "text": "function refactorQueryResult<D, E>(\n name: string,\n original: UseQueryResult<D, E>\n) \n" }, { "answer_id": 74543543, "author": "captain-yossarian from Ukraine", "author_id": 8495254, "author_profile": "https://Stackoverflow.com/users/8495254", "pm_score": 2, "selected": true, "text": "interface UseQueryResult<TData = unknown, TError = unknown> {\n data: TData | undefined;\n dataUpdatedAt: number;\n error: TError | null;\n errorUpdatedAt: number;\n failureCount: number;\n isError: boolean;\n}\n\nfunction refactorQueryResult<D, E, T extends string>(\n name: T,\n original: UseQueryResult<D, E>\n): TransformedData<UseQueryResult<D, E>, T> {\n return {\n [name]: original.data,\n [`${name}UpdatedAt`]: original.dataUpdatedAt,\n [`${name}Error`]: original.error,\n [`${name}ErrorUpdatedAt`]: original.errorUpdatedAt,\n [`${name}FailureCount`]: original.failureCount,\n [`${name}HasError`]: original.isError,\n };\n}\n\ntype MappedData<N extends string> = {\n data: N,\n dataUpdatedAt: `${N}UpdatedAt`,\n error: `${N}Error`,\n errorUpdatedAt: `${N}ErrorUpdatedAt`,\n failureCount: `${N}FailureCount`\n isError: `${N}HasError`\n}\n\ntype TransformedData<QR, N extends string> = {\n [P in keyof QR as P extends keyof MappedData<N> ? MappedData<N>[P] : never]: QR[P]\n}\n\nfunction test(queryResult: UseQueryResult) {\n const {\n test,\n testError,\n testUpdatedAt,\n testErrorUpdatedAt,\n testHasError,\n } = refactorQueryResult(\"test\", queryResult)\n}\n\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20096129/" ]
74,482,257
<p>I recognized some unwanted and unintuitive behavior with spring-batch and chunk based reader/processor/writer setup where the item writer is called more often than I want.</p> <p><strong>I would like to have a setup in which on any exception the writer will not be called again.</strong></p> <p>Please have a look at this very stripped down initialization of a demo step:</p> <pre class="lang-java prettyprint-override"><code>stepBuilder .chunk(1) .reader(new ListItemReader&lt;&gt;(List.of(&quot;1&quot;, &quot;2&quot;, &quot;3&quot;))) .writer(items -&gt; { LOGGER.info(&quot;About to write &quot; + items); throw new RuntimeException(); }) .faultTolerant() .skipPolicy((throwable, skipCount) -&gt; true) .retryPolicy(new MaxAttemptsRetryPolicy(1)) // or //.retryPolicy(new NeverRetryPolicy()) </code></pre> <p>No matter what combination of <code>skipPolicy</code> and <code>retryPolicy</code> I use, the result is always</p> <pre><code>About to write [1] About to write [1] About to write [2] About to write [2] About to write [3] About to write [3] </code></pre> <p>My expectation - or what I would like to achieve - is that after each exception the next item is processed/written.</p> <p>A fully executable (but still minimalistic) demo can be found here <a href="https://github.com/LorenzSchumann/spring-batch-demo-simple" rel="noreferrer">https://github.com/LorenzSchumann/spring-batch-demo-simple</a></p> <p>A similar version with JPA can be found here. <a href="https://github.com/LorenzSchumann/spring-batch-demo-jpa" rel="noreferrer">https://github.com/LorenzSchumann/spring-batch-demo-jpa</a> This demo also triggers two different types of exceptions. The one with the optimistic locking scenario is the one I really care about.</p>
[ { "answer_id": 74520223, "author": "kaan_a", "author_id": 1788771, "author_profile": "https://Stackoverflow.com/users/1788771", "pm_score": 0, "selected": false, "text": "function refactorQueryResult<D, E>(\n name: string,\n original: UseQueryResult<D, E>\n) \n" }, { "answer_id": 74543543, "author": "captain-yossarian from Ukraine", "author_id": 8495254, "author_profile": "https://Stackoverflow.com/users/8495254", "pm_score": 2, "selected": true, "text": "interface UseQueryResult<TData = unknown, TError = unknown> {\n data: TData | undefined;\n dataUpdatedAt: number;\n error: TError | null;\n errorUpdatedAt: number;\n failureCount: number;\n isError: boolean;\n}\n\nfunction refactorQueryResult<D, E, T extends string>(\n name: T,\n original: UseQueryResult<D, E>\n): TransformedData<UseQueryResult<D, E>, T> {\n return {\n [name]: original.data,\n [`${name}UpdatedAt`]: original.dataUpdatedAt,\n [`${name}Error`]: original.error,\n [`${name}ErrorUpdatedAt`]: original.errorUpdatedAt,\n [`${name}FailureCount`]: original.failureCount,\n [`${name}HasError`]: original.isError,\n };\n}\n\ntype MappedData<N extends string> = {\n data: N,\n dataUpdatedAt: `${N}UpdatedAt`,\n error: `${N}Error`,\n errorUpdatedAt: `${N}ErrorUpdatedAt`,\n failureCount: `${N}FailureCount`\n isError: `${N}HasError`\n}\n\ntype TransformedData<QR, N extends string> = {\n [P in keyof QR as P extends keyof MappedData<N> ? MappedData<N>[P] : never]: QR[P]\n}\n\nfunction test(queryResult: UseQueryResult) {\n const {\n test,\n testError,\n testUpdatedAt,\n testErrorUpdatedAt,\n testHasError,\n } = refactorQueryResult(\"test\", queryResult)\n}\n\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1474426/" ]
74,482,346
<p>I need help with the following. My input dataset is as follows: <a href="https://i.stack.imgur.com/cuBPf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cuBPf.png" alt="enter image description here" /></a></p> <p>If one of the values in the QC column is a FAIL, all of the values in the last column 'Final' should be REPEAT, irrespective of what other values are found in the QC column. Desired output dataset: <a href="https://i.stack.imgur.com/QoYri.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QoYri.png" alt="enter image description here" /></a></p> <p>Thank you.</p> <p>The following code does not give expected results as no condition is specified for other qc values.</p> <pre><code>data exp; set exp; if QC = &quot;FAIL&quot; then do; FINAL= &quot;REPEAT&quot;; end; run; </code></pre>
[ { "answer_id": 74483038, "author": "Richard", "author_id": 1249962, "author_profile": "https://Stackoverflow.com/users/1249962", "pm_score": 1, "selected": true, "text": "FAIL" }, { "answer_id": 74484203, "author": "Tom", "author_id": 4965549, "author_profile": "https://Stackoverflow.com/users/4965549", "pm_score": 1, "selected": false, "text": "data want ;\n do while(not eof1);\n set have end=eof1;\n if qc = 'FAIL' then do;\n final='REPEAT';\n eof1=1;\n end;\n end;\n do while(not eof2);\n set have end=eof2;\n output;\n end;\n stop;\nrun;\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20534059/" ]
74,482,389
<p>I'm making a web app with react and in one of my functions I fetch some data from the backend and then I show it to the user by changing the value of the textarea. The problem is that I want the textarea not to be edited when the user presses a button to fetch the data from the backend but then if I click the textarea I want it to erease the data fetched and allow the user to write into itself.</p> <p>This is how the code looks like in the component that contains the textarea:</p> <pre><code>&lt;div id=&quot;text-div&quot; onClick={this.onWrite}&gt; &lt;textarea id=&quot;text&quot; rows={13} value={this.state.value} onChange={this.handleChange}&gt;&lt;/textarea&gt;&lt;/div&gt; &lt;Button onClick={this.handleRead}&gt;Read&lt;/Button&gt; //functions within the code onWrite() { // do stuff document.getElementById(&quot;text&quot;).setAttribute(&quot;contentEditable&quot;, true); } async handleRead() { // fetches data and saves it into this.state.value document.getElementById(&quot;text&quot;).setAttribute(&quot;contentEditable&quot;, false); } </code></pre> <p>I've also tried using <code>readOnly</code> but it doesn't work either, when I call <code>handleRead()</code> it doesnt let the user write and shows the data (as expected) but when i call <code>onWrite()</code> (it would set readOnly property to false) it does not let the user write. So I cant revert what <code>handleRead()</code> did.</p> <p>I would really appreciate some suggestions because I'm kind of a noob in React and this is my first project, sorry if I missed something.</p>
[ { "answer_id": 74482447, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 2, "selected": false, "text": "contenteditable" }, { "answer_id": 74482617, "author": "Prashanth Yarram", "author_id": 15913488, "author_profile": "https://Stackoverflow.com/users/15913488", "pm_score": 1, "selected": false, "text": "defaultValue" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19420592/" ]
74,482,392
<p>I am using Python 3.9.13. I installed scikit-learn from the terminal: <code>pip install scikit-learn</code></p> <p>Then I tried to download the mnist dataset using <code>fetch_openml</code>:</p> <pre><code>from sklearn.datasets import fetch_openml raw_data = fetch_openml('mnist_784') </code></pre> <p>That gave me a long error message ending with:</p> <pre><code>fetch_openml with as_frame=True requires pandas. </code></pre> <p>However, I had <code>pandas</code> installed. So I looked more deeply inside the error message and I found that the exception causing that error was this:</p> <pre><code>ModuleNotFoundError: No module named '_bz2' </code></pre>
[ { "answer_id": 74482447, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 2, "selected": false, "text": "contenteditable" }, { "answer_id": 74482617, "author": "Prashanth Yarram", "author_id": 15913488, "author_profile": "https://Stackoverflow.com/users/15913488", "pm_score": 1, "selected": false, "text": "defaultValue" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19422169/" ]
74,482,413
<p><a href="https://www.imagemagick.org/Usage/basics/#duplicate" rel="nofollow noreferrer">-duplicate</a></p> <pre><code>convert img*.png -duplicate 3 out.gif </code></pre> <p>makes</p> <pre><code>0 1 2 2 2 2 </code></pre> <p>where <code>0</code> is <code>img0.png</code>, and <code>1</code> is <code>img1.png</code>, etc, making a GIF. But can I make below?</p> <pre><code>0 0 0 0 1 2 2 2 2 </code></pre> <p>that is, append to end <em>and</em> start? I get I can use indexing to make</p> <pre><code>0 1 2 2 2 2 0 0 0 </code></pre> <p>which is identical in a loop, but I need the <code>0</code>s at start in context.</p>
[ { "answer_id": 74482775, "author": "Mark Setchell", "author_id": 2836621, "author_profile": "https://Stackoverflow.com/users/2836621", "pm_score": 2, "selected": false, "text": "convert img0.png -duplicate 3 img1.png img2.png -duplicate 3 ...\n" }, { "answer_id": 74482784, "author": "GeeMack", "author_id": 8174768, "author_profile": "https://Stackoverflow.com/users/8174768", "pm_score": 3, "selected": true, "text": "0 0 0 1 2 3 ... 20 21 21 21" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10133797/" ]
74,482,438
<p>From below log we can see <em><strong>rejected value</strong></em> is display user data(example: User PII data with some special characters)</p> <p><code>[Field error in object 'Customer' on field 'FirstName': rejected value [robert% steve];</code></p> <p>So we tried to use <strong>@ControllerAdvice</strong>, <strong>MethodArgumentNotValidException</strong> and customize default error msg to show defined error msg.</p> <p>But somehow this approach is not working for us with feature testcases. So do there any configuration not to display rejected value? or to show rejected value with masking?</p> <p>thanks.</p>
[ { "answer_id": 74515790, "author": "Mor Blau", "author_id": 5599966, "author_profile": "https://Stackoverflow.com/users/5599966", "pm_score": 2, "selected": false, "text": "@Documented\n@Constraint(validatedBy = MyValidator.class) \n@Target( { ElementType.METHOD, ElementType.FIELD }) // set the desired context\n@Retention(RetentionPolicy.RUNTIME)\npublic @interface MyValidation {\n String message() default \"Validation error! Not going to display rejected value.\";\n Class<?>[] groups() default {};\n Class<? extends Payload>[] payload() default {};\n}\n" }, { "answer_id": 74548938, "author": "dekkard", "author_id": 4571544, "author_profile": "https://Stackoverflow.com/users/4571544", "pm_score": 0, "selected": false, "text": "HandlerExceptionResolver" }, { "answer_id": 74550143, "author": "aatwork", "author_id": 14263933, "author_profile": "https://Stackoverflow.com/users/14263933", "pm_score": 3, "selected": true, "text": "@RestControllerAdvice\npublic class CustomExceptionHandler extends ResponseEntityExceptionHandler {\n @Override\n protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {\n Map<String, String> error = Map.of(\"message\", \"Field value not valid.\");\n return handleExceptionInternal(ex, error, headers, HttpStatus.BAD_REQUEST, request);\n }\n}\n" }, { "answer_id": 74590389, "author": "muhammed ozbilici", "author_id": 2165146, "author_profile": "https://Stackoverflow.com/users/2165146", "pm_score": 0, "selected": false, "text": "@InitBinder" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/668970/" ]
74,482,449
<p>Why aren't the top, left, and right edges of the red <code>p</code> element's border not directly aligned with the top, left, and right edges of the viewport?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { background-color: green; } p { padding: 0px; background-color: red; margin: 0px; border-style: solid; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;body&gt; &lt;p&gt;p tag&lt;/p&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74482461, "author": "18jad", "author_id": 15927691, "author_profile": "https://Stackoverflow.com/users/15927691", "pm_score": -1, "selected": false, "text": "* {\n padding: 0;\n margin: 0;\n box-sizing: border-box;\n}\n" }, { "answer_id": 74482464, "author": "borderr", "author_id": 20486034, "author_profile": "https://Stackoverflow.com/users/20486034", "pm_score": 1, "selected": false, "text": "body" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8386132/" ]
74,482,457
<p>thats my function:</p> <pre><code>import pandas as pd shopping_list = pd.DataFrame() shopping_list = shopping_list.assign(Order=0, Type=0, Price=0, Quantity=0) def add_item(order: str, type_transaction: str, price: float, quantity: int, shopping_list=shopping_list): new_item_data = pd.DataFrame({&quot;Order&quot;: [order], &quot;Type&quot;: [type_transaction], &quot;Price&quot;: [price], &quot;Quantity&quot;: [quantity]}) return pd.concat([shopping_list, new_item_data], ignore_index=True) add_item(order=&quot;Buy&quot;, type_transaction=&quot;Add&quot;, price=20.0, quantity=100) add_item(order=&quot;Sell&quot;, type_transaction=&quot;Add&quot;, price=25.0, quantity=200) print(shopping_list) </code></pre> <p>Output:</p> <pre><code>Empty DataFrame Columns: [Order, Type, Price, Quantity] Index: [] </code></pre> <p>What i should do to add this items into my dataframe ? bcz they vanish and idk why</p>
[ { "answer_id": 74482461, "author": "18jad", "author_id": 15927691, "author_profile": "https://Stackoverflow.com/users/15927691", "pm_score": -1, "selected": false, "text": "* {\n padding: 0;\n margin: 0;\n box-sizing: border-box;\n}\n" }, { "answer_id": 74482464, "author": "borderr", "author_id": 20486034, "author_profile": "https://Stackoverflow.com/users/20486034", "pm_score": 1, "selected": false, "text": "body" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19123282/" ]
74,482,465
<p>I am trying to use the raster package in R but since I bought a new computer and have the latest version of R on macOS it mentions certain packages are not available for this version of R.</p> <p>I tried downloading R directly on R studio and that gave me errors.</p> <p>Next I tried installing directly from GitHUB using the following command:</p> <pre><code>install.packages('raster', repos='https://rspatial.r-universe.dev') </code></pre> <p>and this is the error message I receive:</p> <pre><code>Installing package into ‘/Users/username/Library/R/arm64/4.2/library’ (as ‘lib’ is unspecified) also installing the dependency ‘terra’ Packages which are only available in source form, and may need compilation of C/C++/Fortran: ‘terra’ ‘raster’ Do you want to attempt to install these from sources? (Yes/no/cancel) yes installing the source packages ‘terra’, ‘raster’ trying URL 'https://rspatial.r-universe.dev/src/contrib/terra_1.6-43.tar.gz' Content type 'application/x-gzip' length 1777090 bytes (1.7 MB) ================================================== downloaded 1.7 MB trying URL 'https://rspatial.r-universe.dev/src/contrib/raster_3.6-6.tar.gz' Content type 'application/x-gzip' length 1310884 bytes (1.3 MB) ================================================== downloaded 1.3 MB * installing *source* package ‘terra’ ... ** using staged installation configure: CC: clang -arch arm64 configure: CXX: clang++ -arch arm64 -std=gnu++11 checking for gdal-config... no no configure: error: gdal-config not found or not executable. ERROR: configuration failed for package ‘terra’ * removing ‘/Users/username/Library/R/arm64/4.2/library/terra’ Warning in install.packages : installation of package ‘terra’ had non-zero exit status ERROR: dependency ‘terra’ is not available for package ‘raster’ * removing ‘/Users/username/Library/R/arm64/4.2/library/raster’ Warning in install.packages : installation of package ‘raster’ had non-zero exit status The downloaded source packages are in ‘/private/var/folders/zp/vysqcnr95g5d08jhlmzrvj9m0000gn/T/Rtmpn4J6eA/downloaded_packages’ </code></pre> <p>When I load raster next this is what I see:</p> <pre><code>library(raster) #Error: package or namespace load failed for ‘raster’ in #loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]): # there is no package called ‘terra’ </code></pre> <p>When i try to install Terra this is the error message I see:</p> <pre><code>&gt; install.packages('terra') Installing package into ‘/Users/sofigreen/Library/R/arm64/4.2/library’ (as ‘lib’ is unspecified) trying URL 'http://cran.rstudio.com/bin/macosx/big-sur-arm64/contrib/4.2/terra_1.6-41.tgz' Content type 'application/x-gzip' length 99009623 bytes (94.4 MB) =============== downloaded 28.7 MB Warning in install.packages : downloaded length 30079735 != reported length 99009623 Warning in install.packages : URL 'http://cran.rstudio.com/bin/macosx/big-sur-arm64/contrib/4.2/terra_1.6-41.tgz': status was 'Failure when receiving data from the peer' Error in download.file(url, destfile, method, mode = &quot;wb&quot;, ...) : download from 'http://cran.rstudio.com/bin/macosx/big-sur-arm64/contrib/4.2/terra_1.6-41.tgz' failed Warning in install.packages : download of package ‘terra’ failed </code></pre> <p>And when trying to download terra from source:</p> <pre><code>&gt; install.packages('terra', repos='https://rspatial.r-universe.dev') Installing package into ‘/Users/username/Library/R/arm64/4.2/library’ (as ‘lib’ is unspecified) Package which is only available in source form, and may need compilation of C/C++/Fortran: ‘terra’ Do you want to attempt to install these from sources? (Yes/no/cancel) yes installing the source package ‘terra’ trying URL 'https://rspatial.r-universe.dev/src/contrib/terra_1.6-43.tar.gz' Content type 'application/x-gzip' length 1786823 bytes (1.7 MB) ================================================== downloaded 1.7 MB * installing *source* package ‘terra’ ... ** using staged installation configure: CC: clang -arch arm64 configure: CXX: clang++ -arch arm64 -std=gnu++11 checking for gdal-config... no no configure: error: gdal-config not found or not executable. ERROR: configuration failed for package ‘terra’ * removing ‘/Users/username/Library/R/arm64/4.2/library/terra’ Warning in install.packages : installation of package ‘terra’ had non-zero exit status The downloaded source packages are in ‘/private/var/folders/zp/vysqcnr95g5d08jhlmzrvj9m0000gn/T/RtmpfniygU/downloaded_packages’ </code></pre> <p>I really need the raster package. Please help.</p>
[ { "answer_id": 74482461, "author": "18jad", "author_id": 15927691, "author_profile": "https://Stackoverflow.com/users/15927691", "pm_score": -1, "selected": false, "text": "* {\n padding: 0;\n margin: 0;\n box-sizing: border-box;\n}\n" }, { "answer_id": 74482464, "author": "borderr", "author_id": 20486034, "author_profile": "https://Stackoverflow.com/users/20486034", "pm_score": 1, "selected": false, "text": "body" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13576833/" ]
74,482,501
<p>Is there anyway that I can override a directive like: src/Schema/Directives/WhereDirective.php for instance this doesn't support some methods on my custom builder, I know I can make another directive and extend this like @myWhere but that's dirty, would be nice to be able to override the @where itself.</p> <p>I've searched around but nothing was found about this sadly!</p>
[ { "answer_id": 74482461, "author": "18jad", "author_id": 15927691, "author_profile": "https://Stackoverflow.com/users/15927691", "pm_score": -1, "selected": false, "text": "* {\n padding: 0;\n margin: 0;\n box-sizing: border-box;\n}\n" }, { "answer_id": 74482464, "author": "borderr", "author_id": 20486034, "author_profile": "https://Stackoverflow.com/users/20486034", "pm_score": 1, "selected": false, "text": "body" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10268067/" ]
74,482,502
<p>I can do it in only O(k) time can someone be that kind to help me. I can not use build in functions.</p> <pre><code>def potnr(a, b): rez = 1 while b&gt;0: if b%2: rez = rez * a b = b // 2 a = a * a return rez def liczba(n, m): k = 1 while potnr(n, k) &lt; m: k += 1 return k print(liczba(2, 16)) </code></pre> <p>I can do it in only O(k) time can someone be that kind to help me</p>
[ { "answer_id": 74482615, "author": "QWERTYL", "author_id": 11777402, "author_profile": "https://Stackoverflow.com/users/11777402", "pm_score": 2, "selected": false, "text": "n^k >= m" }, { "answer_id": 74483214, "author": "Swifty", "author_id": 20267366, "author_profile": "https://Stackoverflow.com/users/20267366", "pm_score": 1, "selected": false, "text": "import math\ndef min_power(n,m):\n b=1\n while n**b < m:\n b *= 2\n a = b/2\n while b-a > 1:\n c = (a+b)/2\n if n**c < m:\n a = c\n else:\n b = c\n k = math.ceil(a)\n return k if (n**k >= m) else k+1\n\nmin_power(35,10**250)\n# Out[23]: 162\n" }, { "answer_id": 74483383, "author": "anatolyg", "author_id": 509868, "author_profile": "https://Stackoverflow.com/users/509868", "pm_score": 0, "selected": false, "text": "k" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20534220/" ]
74,482,505
<p>I am trying to create an input function that returns a value for the corresponding first and last name. For this example i'd like to be able to enter &quot;Emily&quot; and &quot;Bell&quot; and return &quot;attempts: 3&quot;</p> <p>Heres my code so far:</p> <pre><code>import pandas as pd import numpy as np data = { 'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'], 'lastname': ['Thompson','Wu', 'Downs','Hunter','Bell','Cisneros', 'Becker', 'Sims', 'Gallegos', 'Horne'], 'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19], 'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1], 'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes'] } data labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] df = pd.DataFrame(data, index=labels) df </code></pre> <pre><code>fname = input() lname = input() print(f&quot;{fname} {lname}'s number of attempts: {???}&quot;) </code></pre> <p>I thought there would be specific documentation for this but I cant find any on the pandas dataframe documentation. I am assuming its pretty simple but can't find it.</p>
[ { "answer_id": 74482615, "author": "QWERTYL", "author_id": 11777402, "author_profile": "https://Stackoverflow.com/users/11777402", "pm_score": 2, "selected": false, "text": "n^k >= m" }, { "answer_id": 74483214, "author": "Swifty", "author_id": 20267366, "author_profile": "https://Stackoverflow.com/users/20267366", "pm_score": 1, "selected": false, "text": "import math\ndef min_power(n,m):\n b=1\n while n**b < m:\n b *= 2\n a = b/2\n while b-a > 1:\n c = (a+b)/2\n if n**c < m:\n a = c\n else:\n b = c\n k = math.ceil(a)\n return k if (n**k >= m) else k+1\n\nmin_power(35,10**250)\n# Out[23]: 162\n" }, { "answer_id": 74483383, "author": "anatolyg", "author_id": 509868, "author_profile": "https://Stackoverflow.com/users/509868", "pm_score": 0, "selected": false, "text": "k" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20526246/" ]
74,482,518
<p>I apologize if there are errors in my code or anything like that, I have been searching for a solution, and have not found anything.</p> <p>I am trying to use a /logout route to clear a cookie with res.clearCookie(). My understanding is that in order for the cookie to be cleared, all the options passed to res.clearCookie must match the options passed to res.cookie, when the cookie was originally created. I have tried including the domain (5.161.134.120) as well, but nothing seems to work, the cookie still persists.</p> <p>Cookies work fine throughout the rest of the site for accessing specific pages, it appears to be just deleting them that is causing the issue. Deleting cookies worked fine locally, it's only after deploying to a server.</p> <blockquote class="spoiler"> <p> Initializing the cookie:</p> </blockquote> <pre><code>router.get(&quot;/callback&quot;, async function (req, res, next) { try { let tokenData = await SpotifyClientService.getSpotifyToken(req.query.code); let sessionId = await SpotifyClientService.validateUserAndGetSessionId(tokenData); res.cookie(&quot;sessionId&quot;, sessionId, { path: '/', httpOnly: true }); res.redirect(HOME_REDIRECT); } catch (err) { console.log(err); return next(err); } }) </code></pre> <blockquote class="spoiler"> <p> Logout route</p> </blockquote> <pre><code>router.post(&quot;/logout&quot;, async function (req, res, next) { try { res.clearCookie('sessionId', { path: '/', httpOnly: true }); res.end(); } catch (err) { return next(err); } }) </code></pre> <p>My backend's app.js, with cors:</p> <pre><code>const express = require(&quot;express&quot;); const morgan = require(&quot;morgan&quot;); const cors = require(&quot;cors&quot;); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); const reviewsRoutes = require(&quot;./routes/reviews&quot;); const userRoutes = require(&quot;./routes/users&quot;); const albumRoutes = require(&quot;./routes/albums&quot;); const authRoutes = require(&quot;./routes/auth.js&quot;) const app = express(); app.use(cookieParser()); app.use(bodyParser.json()) app.use(morgan(&quot;tiny&quot;)); app.use(express.json()); app.use(cors({origin:&quot;http://5.161.134.120:3000&quot;, credentials:true})); app.use(&quot;/reviews&quot;, reviewsRoutes); app.use(&quot;/users&quot;, userRoutes); app.use(&quot;/albums&quot;, albumRoutes); app.use(&quot;/auth&quot;, authRoutes.router); // 404 Not Found handler * // app.use(function (req, res, next) { const err = new Error(&quot;Not Found&quot;); err.status = 404; next(err); }); // Generic error handler. *// app.use(function (err, req, res, next) { res.status(err.status || 500).json({ message: err.message }); }); module.exports = app; </code></pre> <p>Lastly, the function from the React component that is calling the logout route:</p> <pre><code> async function doLogout() { let result = await axios.post(`${BASE_URL}/auth/logout`,{ withCredentials: true}); dispatch({ type: &quot;LOGOUT-CURR-USER&quot; }) navigate(&quot;/&quot;); } </code></pre> <p>I did search pretty extensively and I apologize if I missed this issue being fixed. Thank you for reading.</p> <p>Attempted to use the res.clearCookie function with options identical to res.Cookie, to clear a cookie.</p>
[ { "answer_id": 74482615, "author": "QWERTYL", "author_id": 11777402, "author_profile": "https://Stackoverflow.com/users/11777402", "pm_score": 2, "selected": false, "text": "n^k >= m" }, { "answer_id": 74483214, "author": "Swifty", "author_id": 20267366, "author_profile": "https://Stackoverflow.com/users/20267366", "pm_score": 1, "selected": false, "text": "import math\ndef min_power(n,m):\n b=1\n while n**b < m:\n b *= 2\n a = b/2\n while b-a > 1:\n c = (a+b)/2\n if n**c < m:\n a = c\n else:\n b = c\n k = math.ceil(a)\n return k if (n**k >= m) else k+1\n\nmin_power(35,10**250)\n# Out[23]: 162\n" }, { "answer_id": 74483383, "author": "anatolyg", "author_id": 509868, "author_profile": "https://Stackoverflow.com/users/509868", "pm_score": 0, "selected": false, "text": "k" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20534226/" ]
74,482,520
<p>So I'm having an issue getting Server Side Events working with PHP. I've tried various different tutorials online that utilise an infinite while loop but all of my attempts end up in a 500 error after a couple of minutes, instead of the data being sent.</p> <p>For my application I need the script to keep running in an infinite loop as I'm getting updates from a hardware device via TCP sockets, and for the device to send me updates I have to keep the socket connection open.</p> <p>My setup is as follows:<br /> PHP Version 7.3.33<br /> Windows Server 2022 with IIS 10 (Also tried on Windows Server 2016 with IIS 10)<br /> output_buffering and zlib.output_compression are both set to &quot;Off&quot;<br /> responseBufferLimit is set to 0 in the FastCGI Handler settings for PHP.</p> <p>The basic test code I'm currently using is as follows:</p> <p>sse.php</p> <pre><code>&lt;?PHP header('Content-Type: text/event-stream'); header('Cache-Control: no-cache'); while(true) { $now = date('r'); echo &quot;data: The time is : {$now}\n\n&quot;; @ob_flush(); flush(); sleep(2); } ?&gt; </code></pre> <p>test.html</p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;title&gt;Untitled Document&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;script&gt; var source = new EventSource(&quot;sse.php&quot;); source.onopen = function(e) { console.log(&quot;The connection to your server has been opened&quot;); } source.onmessage = function(e) { console.log (&quot;message: &quot; + e.data); } source.onerror = function(e) { console.log(&quot;The server connection has been closed due to some errors&quot;); } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>This should (in theory) send a data string to the client with the current time every 2 seconds, but instead is 500 erroring. I must add it is only when a while loop is implemented. If I remove the while loop then it works with the client reconnecting every 3 seconds (which won't work for my application).</p> <p>The PHP logs only show the following errors which don't appear to be linked to my issue, unless anyone can suggest otherwise:<br /> [17-Nov-2022 21:26:28 UTC] PHP Warning: Module 'mysqli' already loaded in Unknown on line 0<br /> [17-Nov-2022 21:26:28 UTC] PHP Warning: Module 'mbstring' already loaded in Unknown on line 0<br /> [17-Nov-2022 21:26:28 UTC] PHP Deprecated: Directive 'track_errors' is deprecated in Unknown on line 0</p> <p>I've searched for days for a solution with nothing working so far. Does anyone have any suggestions on potential settings that need altering with the IIS/PHP setup to get this to work?</p> <p>Some tutorials have suggested making these config changes: php.ini &gt; output_buffering and zlib.output_compression set to &quot;Off&quot; responseBufferLimit is set to 0 in the FastCGI Handler settings for PHP.</p> <p>But neither of these have had any effect on the script.</p>
[ { "answer_id": 74482615, "author": "QWERTYL", "author_id": 11777402, "author_profile": "https://Stackoverflow.com/users/11777402", "pm_score": 2, "selected": false, "text": "n^k >= m" }, { "answer_id": 74483214, "author": "Swifty", "author_id": 20267366, "author_profile": "https://Stackoverflow.com/users/20267366", "pm_score": 1, "selected": false, "text": "import math\ndef min_power(n,m):\n b=1\n while n**b < m:\n b *= 2\n a = b/2\n while b-a > 1:\n c = (a+b)/2\n if n**c < m:\n a = c\n else:\n b = c\n k = math.ceil(a)\n return k if (n**k >= m) else k+1\n\nmin_power(35,10**250)\n# Out[23]: 162\n" }, { "answer_id": 74483383, "author": "anatolyg", "author_id": 509868, "author_profile": "https://Stackoverflow.com/users/509868", "pm_score": 0, "selected": false, "text": "k" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1376648/" ]
74,482,542
<p>I am using the code snippet below from <a href="https://learn.microsoft.com/en-us/xamarin/essentials/email?context=xamarin%2Fxamarin-forms&amp;tabs=ios" rel="nofollow noreferrer">here</a> and getting '+' signs instead of spaces in my Outlook email app. All other text is correct. I do not think I am doing anything fancy with the strings, but I am using string interpolation.</p> <p>`</p> <pre><code>public async Task SendEmail(string subject, string body, List&lt;string&gt; recipients) { try { var message = new EmailMessage { Subject = @&quot;{StoreName} Needs a Payer&quot;, Body = @&quot;It needs a separate payer...&quot;, To = recipients, //Cc = ccRecipients, //Bcc = bccRecipients }; await Email.ComposeAsync(message); } catch (FeatureNotSupportedException fbsEx) { // Email is not supported on this device } catch (Exception ex) { // Some other exception occurred } } </code></pre> <p>`</p> <p>This is a .NET Xamarin iOS app. What can I do to make sure spaces are used and not '+' signs ?</p> <p><strong>EDIT 1</strong>: I tried changing the BodyFormat property and got the following results: Setting the BodyFormat to Text does not change the behavior. Still get + signs instead of spaces, BUT if I use a iOS Mail application, the spaces are fine. If I set it to BodyFormat HTML, the Outlook application just crashes, but the iOS Mail application is fine.</p>
[ { "answer_id": 74528405, "author": "Jabbar", "author_id": 16930239, "author_profile": "https://Stackoverflow.com/users/16930239", "pm_score": 0, "selected": false, "text": "%20" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/303631/" ]
74,482,600
<p>I have a query with multiple joins that is being used to extract data from multiple tables. As part of the select I have multiple case statements. I a stuck with one of them. I need to add one condition where I get only one row each for Chris and John with flag 'Y', if they have PCT as 100 and the '0' or 'NULL' PCT rows should not be displayed.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: right;">DeptID</th> <th>Employee</th> <th style="text-align: right;">PCT</th> <th>Utlility_PCT</th> </tr> </thead> <tbody> <tr> <td style="text-align: right;">101</td> <td>Chris</td> <td style="text-align: right;">100</td> <td>Y</td> </tr> <tr> <td style="text-align: right;">101</td> <td>Chris</td> <td style="text-align: right;"></td> <td>N</td> </tr> <tr> <td style="text-align: right;">101</td> <td>Sam</td> <td style="text-align: right;">0</td> <td>N</td> </tr> <tr> <td style="text-align: right;">101</td> <td>John</td> <td style="text-align: right;">100</td> <td>Y</td> </tr> <tr> <td style="text-align: right;">101</td> <td>John</td> <td style="text-align: right;"></td> <td>N</td> </tr> </tbody> </table> </div> <p>Currently my case statement is case when PCT = 100 then 'Y' else 'N' end Utility_PCT</p> <p>I want my result set to look like:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: right;">DeptID</th> <th>Employee</th> <th style="text-align: right;">PCT</th> <th>Utlility_PCT</th> </tr> </thead> <tbody> <tr> <td style="text-align: right;">101</td> <td>Chris</td> <td style="text-align: right;">100</td> <td>Y</td> </tr> <tr> <td style="text-align: right;">101</td> <td>Sam</td> <td style="text-align: right;">0</td> <td>N</td> </tr> <tr> <td style="text-align: right;">101</td> <td>John</td> <td style="text-align: right;">100</td> <td>Y</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74528405, "author": "Jabbar", "author_id": 16930239, "author_profile": "https://Stackoverflow.com/users/16930239", "pm_score": 0, "selected": false, "text": "%20" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16399158/" ]
74,482,601
<p>So i want to display the filename and the size of the file in MB using the &quot;du&quot; command in my bash script but it outputs the filepath for the file</p> <p>I have used the command:</p> <pre><code>du -s -BM /home/user/test/test_file_check </code></pre> <p>But my output is:</p> <pre><code>0M /home/user/test/test_file_check </code></pre> <p>How do i get rid of the <code>/home/user/test</code> path from the output? Would it be possible to use sed to remove the filepath?</p> <p>Is there alternatively another command better suited for this?</p>
[ { "answer_id": 74482646, "author": "markp-fuso", "author_id": 7366100, "author_profile": "https://Stackoverflow.com/users/7366100", "pm_score": 0, "selected": false, "text": "sed" }, { "answer_id": 74482887, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 1, "selected": false, "text": "du" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20534276/" ]
74,482,602
<p>I am getting NaN for non mathcing pattern w.r.t to split in pandas.</p> <p>Source Data:</p> <pre><code>Attr [ABC].[xyz] CDE </code></pre> <p>Code Used:</p> <pre><code>df['Extr_Attr'] = np.where((df.Attr.str.contains('.')),df['Attr'].str.split('.',1).str[1], df.Attr) This returns NaN for data that does not have a match of '.' in source data. </code></pre> <p>Expected output:</p> <pre><code>Attr Extr_Attr [ABC].[xyz] [xyz] CDE CDE </code></pre>
[ { "answer_id": 74482679, "author": "Umar.H", "author_id": 9375102, "author_profile": "https://Stackoverflow.com/users/9375102", "pm_score": 0, "selected": false, "text": "str.contains" }, { "answer_id": 74482710, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "rsplit" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18412253/" ]
74,482,607
<p>I need to output the property of the Variable DisplayVersion which contains the version of the application in the result how do I do that in foreach loop?</p> <pre><code>$programList = @( 'SAP' 'Tanium' 'Sentinel' 'DisplayLink' 'Cisco AnyConnect' 'Adobe Acrobat Reader' 'Google' 'Lotus Notes' 'Java Runtime' 'My IT Windows' 'Qualys' 'Snow' 'LogRhythm' ) $Regpath = @( 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*' 'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*' ) $installedPrograms = (Get-ItemProperty $Regpath).where({$_.DisplayName}) $result = foreach($program in $programList) { $check = $installedPrograms.DisplayName -match $program if($check) { foreach($match in $check) { [pscustomobject]@{ Program = $program Status = 'Found' Match = $match } } continue } [pscustomobject]@{ Program = $program Status = 'Not Found' Match = $null version = $null } } $result </code></pre> <p>The output should look something like</p> <pre class="lang-none prettyprint-override"><code>Program Status Match Version ------- ------ ----- ------- SAP Found SAP GUI for Windows 7.60 (Patch 4) 7.60.4 </code></pre>
[ { "answer_id": 74482849, "author": "Santiago Squarzon", "author_id": 15339544, "author_profile": "https://Stackoverflow.com/users/15339544", "pm_score": 2, "selected": false, "text": "Group-Object -AsHashtable" }, { "answer_id": 74483347, "author": "Metzli_Tonaltzintli", "author_id": 20223471, "author_profile": "https://Stackoverflow.com/users/20223471", "pm_score": 3, "selected": true, "text": "$installedPrograms.Where({$PSItem.DisplayName -eq $match}).DisplayVersion" }, { "answer_id": 74524196, "author": "js2010", "author_id": 6654942, "author_profile": "https://Stackoverflow.com/users/6654942", "pm_score": 0, "selected": false, "text": "get-package *chrome*,*notepad++*,*vlc*\n\nName Version Source ProviderName\n---- ------- ------ ------------\nNotepad++ (64-bit x64) 7.8.9 msi\nGoogle Chrome 107.0.5304.107 msi\nVLC media player 3.0.11 Programs\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7363126/" ]
74,482,626
<p>I have data for all the time I've spent coding. This data is represented as a dictionary where the key is the date and the value is a list of tuples containing the time I started a coding session and how long the coding session lasted.</p> <p>I have successfully plotted this on a <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.broken_barh.html#matplotlib.axes.Axes.broken_barh" rel="nofollow noreferrer">broken_barh</a> using the below code, where the y-axis is the date, the x-axis is the time in that day and each broken bar is an individual session.</p> <pre><code>for i,subSessions in enumerate(sessions.values()): plt.broken_barh(subSessions, (i,1)) months = {} start = getStartMonth() for month in period_range(start=start,end=datetime.today(),freq=&quot;M&quot;): month = str(month) months[month] = (datetime.strptime(month,'%Y-%m')-start).days plt.yticks(list(months.values()),months.keys()) plt.xticks(range(0,24*3600,3600),[str(i)+&quot;:00&quot; for i in range(24)],rotation=45) plt.gca().invert_yaxis() plt.show() </code></pre> <p><img src="https://i.stack.imgur.com/cdJbOm.png" alt="Broken bar chart produced by the above code" /></p> <p>I want to use this data to discover what times of the day I spend the most time coding, but it isn't very clear from the above chart so I'd like to display it as a line graph or heatmap where the y-axis is the number of days I spent coding at the time on the x-axis (or, in other words, how many sessions are present in that column of the above chart). How do I accomplish this?</p>
[ { "answer_id": 74482849, "author": "Santiago Squarzon", "author_id": 15339544, "author_profile": "https://Stackoverflow.com/users/15339544", "pm_score": 2, "selected": false, "text": "Group-Object -AsHashtable" }, { "answer_id": 74483347, "author": "Metzli_Tonaltzintli", "author_id": 20223471, "author_profile": "https://Stackoverflow.com/users/20223471", "pm_score": 3, "selected": true, "text": "$installedPrograms.Where({$PSItem.DisplayName -eq $match}).DisplayVersion" }, { "answer_id": 74524196, "author": "js2010", "author_id": 6654942, "author_profile": "https://Stackoverflow.com/users/6654942", "pm_score": 0, "selected": false, "text": "get-package *chrome*,*notepad++*,*vlc*\n\nName Version Source ProviderName\n---- ------- ------ ------------\nNotepad++ (64-bit x64) 7.8.9 msi\nGoogle Chrome 107.0.5304.107 msi\nVLC media player 3.0.11 Programs\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17168710/" ]
74,482,635
<p>In my MERN app I am trying to take a screenshot of a portion of the webpage to send it to the database with other info that is submitted such as submitter and description. The problem is, the image is only saved after I ctrl+S in my editor, not when I click the button or when I refresh the page. How can I fix this? Also, I would appreciate some direction in how to store the png and how to save it in the database.</p> <pre><code>import React, { useState } from 'react'; import { useDispatch } from 'react-redux'; import { createPost } from '../../actions/posts' import domtoimage from 'dom-to-image'; import './form.css'; const Form = () =&gt; { const [postData, setPostData] = useState({ submittor: '', description: '' }) const dispatch = useDispatch(); const handleSubmit = (event) =&gt; { event.preventDefault(); dispatch(createPost(postData)); } function saveImg(){ domtoimage.toBlob(document.getElementById('main')) .then(function(blob) { window.saveAs(blob, 'test'); }); } return( &lt;div className='form'&gt; &lt;form autoComplete='off' noValidate onSubmit={handleSubmit}&gt; &lt;h1&gt;Submit Position&lt;/h1&gt; &lt;label className='label' for='submittorName'&gt;Your Name&lt;/label&gt; &lt;input name='submittor name' id='submittorName' type='text' variant='outlined' placeholder='Your name...' value={postData.submittor} onChange={(event) =&gt; setPostData({...postData, submittor: event.target.value})}/&gt; &lt;label className='label' for='description'&gt;Description&lt;/label&gt; &lt;input name='description' id='description' type='text' variant='outlined' placeholder='Description...' value={postData.description} onChange={(event) =&gt; setPostData({...postData, description: event.target.value})}/&gt; &lt;button type='submit' className='button' onClick={saveImg()}&gt;Submit&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; ) } export default Form; </code></pre>
[ { "answer_id": 74482849, "author": "Santiago Squarzon", "author_id": 15339544, "author_profile": "https://Stackoverflow.com/users/15339544", "pm_score": 2, "selected": false, "text": "Group-Object -AsHashtable" }, { "answer_id": 74483347, "author": "Metzli_Tonaltzintli", "author_id": 20223471, "author_profile": "https://Stackoverflow.com/users/20223471", "pm_score": 3, "selected": true, "text": "$installedPrograms.Where({$PSItem.DisplayName -eq $match}).DisplayVersion" }, { "answer_id": 74524196, "author": "js2010", "author_id": 6654942, "author_profile": "https://Stackoverflow.com/users/6654942", "pm_score": 0, "selected": false, "text": "get-package *chrome*,*notepad++*,*vlc*\n\nName Version Source ProviderName\n---- ------- ------ ------------\nNotepad++ (64-bit x64) 7.8.9 msi\nGoogle Chrome 107.0.5304.107 msi\nVLC media player 3.0.11 Programs\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14551989/" ]
74,482,650
<p>I made a project from scratch just with the schema.sql and the data.sql just to try the schema.sql and the data.sql:</p> <ul> <li><a href="https://github.com/rmmcosta/TestSchema" rel="nofollow noreferrer">https://github.com/rmmcosta/TestSchema</a> Everything works fine. The table inside schema.sql is created in a MySql database (previously created and the grants were given to the user defined in application.properties) and the data.sql populates the data as it's supposed to do.</li> </ul> <p>But, when I change schema.sql and data.sql to schema-mysql.sql and data-mysql.sql and I put in the application.properties the property spring.datasource.platform=mysql the schema-mysql.sql and the data-mysql.sql are not being executed. No errors are being thrown, simple nothing happens on the database. I tried with spring boot 2.2.4 and it works fine, but with spring boot 2.7.5 it isn't working.</p> <p>Do you know if the spring.datasource.platform was deprecated? And if so, do you know how can I set the application.properties in order to run schema-mysql.sql?</p> <p>Thank you in advance, Ricardo</p> <p>Note: I tried without using spring.datasource.platform=mysql and with schema.sql and data.sql and everything works fine. I tried with an old project, spring boot 2.2.4 and java 1.8, and works fine.</p>
[ { "answer_id": 74482849, "author": "Santiago Squarzon", "author_id": 15339544, "author_profile": "https://Stackoverflow.com/users/15339544", "pm_score": 2, "selected": false, "text": "Group-Object -AsHashtable" }, { "answer_id": 74483347, "author": "Metzli_Tonaltzintli", "author_id": 20223471, "author_profile": "https://Stackoverflow.com/users/20223471", "pm_score": 3, "selected": true, "text": "$installedPrograms.Where({$PSItem.DisplayName -eq $match}).DisplayVersion" }, { "answer_id": 74524196, "author": "js2010", "author_id": 6654942, "author_profile": "https://Stackoverflow.com/users/6654942", "pm_score": 0, "selected": false, "text": "get-package *chrome*,*notepad++*,*vlc*\n\nName Version Source ProviderName\n---- ------- ------ ------------\nNotepad++ (64-bit x64) 7.8.9 msi\nGoogle Chrome 107.0.5304.107 msi\nVLC media player 3.0.11 Programs\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14344214/" ]
74,482,675
<p>I'm trying to generate 3 new calculated fields in Google Data Studio / Looker Studio using the <code>REGEXP_EXTRACT</code> function.</p> <p>Here is the sample data that I have on a Google sheet:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Sample data</th> </tr> </thead> <tbody> <tr> <td>Serviços de Impressão &gt; Impressoras &gt; Falha na impressão &gt; Troca de Tonner</td> </tr> <tr> <td>Aplicativos e Softwares &gt; Avaliação de Aplicativos e Software &gt; Pacote Office</td> </tr> <tr> <td>Computadores e Periféricos &gt; Manutenção &gt; Teclado / Mouse &gt; Aquisição de equipamento</td> </tr> <tr> <td>Acessos &gt; Certificado Digital</td> </tr> </tbody> </table> </div> <p>Each <code> &gt; </code> represents a division and ideally what I would like to do is extract the first three fields and disregard the rest, something like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Calculated field 1</th> <th>Calculated field 2</th> <th>Calculated field 3</th> </tr> </thead> <tbody> <tr> <td>Serviços de Impressão</td> <td>Impressoras</td> <td>Falha na impressão</td> </tr> <tr> <td>Aplicativos e Softwares</td> <td>Avaliação de Aplicativos e Software</td> <td>Pacote Office</td> </tr> <tr> <td>Computadores e Periféricos</td> <td>Manutenção</td> <td>Teclado / Mouse</td> </tr> <tr> <td>Acessos</td> <td>Certificado Digital</td> <td>null</td> </tr> </tbody> </table> </div> <p>I managed to generate a code to extract the first calculated field using</p> <pre><code>REGEXP_EXTRACT(Sample data,'^(.+?)&gt;') </code></pre> <p>but in the second I didn't know how to do it, since I can always have one or more separators <code> &gt; </code> as in the example of the last line.</p> <p>How can I formulate the codes for calculated fields 2 and 3 please?</p>
[ { "answer_id": 74483482, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 2, "selected": true, "text": " > (.*?)(?: > |$)\n" }, { "answer_id": 74488487, "author": "rockinfreakshow", "author_id": 5479575, "author_profile": "https://Stackoverflow.com/users/5479575", "pm_score": 0, "selected": false, "text": "REGEXP_EXTRACT(test1,'^(?:[^>]+>){0}([^>]+)')\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20534149/" ]
74,482,685
<p>I am having trouble centering a row of 3 social media icons in the middle of my popup modal and have it actually be responsive.</p> <p>My failed method is adjusting the icons' &quot;left&quot; property by individual percentages..</p> <p>Every time I think I have it centered, I test it out on a different screen size and it's too much to the right or too much to the left.</p> <pre><code>&lt;section class=&quot;popup-modal&quot;&gt; &lt;div class=&quot;popup-box&quot;&gt; &lt;div class=&quot;popup-image-container&quot;&gt; &lt;div class=&quot;popup-img&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;popup-content&quot;&gt; &lt;div class=&quot;popup-close&quot;&gt;&amp;times;&lt;/div&gt; &lt;h1&gt;FOLLOW US ON SOCIAL MEDIA&lt;/h1&gt; &lt;p&gt;@gravitasdesign&lt;/p&gt; &lt;h3&gt;Learn about our current and upcoming projects.&lt;/h3&gt; &lt;a href=&quot;#&quot;&gt; &lt;i id=&quot;popup-facebook&quot; class=&quot;bi bi-facebook&quot;&gt;&lt;/i&gt;&lt;/a&gt; &lt;a href=&quot;#&quot;&gt; &lt;i id=&quot;popup-instagram&quot; class=&quot;bi bi-instagram&quot;&gt;&lt;/i&gt;&lt;/a&gt; &lt;a href=&quot;#&quot;&gt; &lt;i id=&quot;popup-linkedin&quot; class=&quot;bi bi-linkedin&quot;&gt;&lt;/i&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; </code></pre> <pre><code>.popup-modal{ position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 1099; background-color: rgba(0, 0, 0, 0.8); visibility: hidden; opacity: 0; transition: all 0.5s ease; } .popup-modal.show { visibility: visible; opacity: 1; } .popup-box { background-color: #fff; width: 750px; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); display: flex; flex-wrap: wrap; border-radius: 2.5px; } .popup-image-container{ flex: 0 0 50%; max-width: 50%; position: relative; overflow: hidden; } .popup-img { position: absolute; width: 100%; height: 100%; background-image: url(images/popupmodal.jpg); background-size: cover; background-position: left; animation: zoomInOut 50s linear infinite; } @keyframes zoomInOut{ 0%,100%{ transform: scale(1); } 50%{ transform: scale(1.2); } } .popup-content { flex: 0 0 50%; max-width: 50%; padding: 30px; } .popup-content h1{ font-family: interstate, sans-serif; font-weight: 700; font-style: normal; font-size: 36px; text-align: center; line-height: 55px; word-spacing: 4px; color: #300600; } .popup-content h3{ font-family: interstate, sans-serif; font-weight: 500; font-style: normal; font-size: 24px; text-align: center; line-height: 40px; color: #300600; padding-bottom: 35px; } .popup-content p { font-family: 'interstate', sans-serif; font-weight: 700; padding-top: 30px; padding-bottom: 35px; text-align: center; font-size: 28px; line-height: 42.5px; color: #300600; } #popup-facebook, #popup-instagram, #popup-linkedin{ position: relative; left: 9.5%; font-size: 32px; margin-right: 24px; margin-left: 24px; transition: 0.2s ease-in-out; } #popup-facebook{ color: #4267B2; } #popup-linkedin{ color: #0077b5; } #popup-instagram { color: #0077b5; } .popup-close { font-size: 32px; position: absolute; left: 96%; top: 1%; cursor: pointer; transition: 0.2s ease-in-out; color: #300600; } </code></pre>
[ { "answer_id": 74483482, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 2, "selected": true, "text": " > (.*?)(?: > |$)\n" }, { "answer_id": 74488487, "author": "rockinfreakshow", "author_id": 5479575, "author_profile": "https://Stackoverflow.com/users/5479575", "pm_score": 0, "selected": false, "text": "REGEXP_EXTRACT(test1,'^(?:[^>]+>){0}([^>]+)')\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19991177/" ]
74,482,714
<p>To illustrate the problem see this example using dplyr/tidyr, answers appreciated using any other packages:</p> <pre><code>#data df1 &lt;- data.frame(&quot;SNP&quot; = c(&quot;rs11807834&quot;, &quot;rs3729986&quot;), &quot;Symbols&quot; = c(&quot;GRIN1,SETD1A&quot;, &quot;MADD,STAC3,SPI1&quot;)) # SNP Symbols # 1 rs11807834 GRIN1,SETD1A # 2 rs3729986 MADD,STAC3,SPI1 </code></pre> <p>As expected Symbols column with multiple genes is gone:</p> <pre><code>df1 %&gt;% separate_rows(Symbols, sep = &quot;,&quot;) # # A tibble: 5 x 2 # SNP Symbols # &lt;chr&gt; &lt;chr&gt; # 1 rs11807834 GRIN1 # 2 rs11807834 SETD1A # 3 rs3729986 MADD # 4 rs3729986 STAC3 # 5 rs3729986 SPI1 </code></pre> <p>I could join the original data to get the values</p> <pre><code>df1 %&gt;% separate_rows(Symbols, sep = &quot;,&quot;) %&gt;% left_join(df1, by = &quot;SNP&quot;) # # A tibble: 5 x 3 # SNP Symbols.x Symbols.y # &lt;chr&gt; &lt;chr&gt; &lt;chr&gt; # 1 rs11807834 GRIN1 GRIN1,SETD1A # 2 rs11807834 SETD1A GRIN1,SETD1A # 3 rs3729986 MADD MADD,STAC3,SPI1 # 4 rs3729986 STAC3 MADD,STAC3,SPI1 # 5 rs3729986 SPI1 MADD,STAC3,SPI1 </code></pre> <p>Or I could paste them back again using group/ungroup:</p> <pre><code>df1 %&gt;% separate_rows(Symbols, sep = &quot;,&quot;) %&gt;% group_by(SNP) %&gt;% mutate(Genes = paste(Symbols, collapse = &quot;,&quot;)) %&gt;% ungroup() # # A tibble: 5 x 3 # SNP Symbols Genes # &lt;chr&gt; &lt;chr&gt; &lt;chr&gt; # 1 rs11807834 GRIN1 GRIN1,SETD1A # 2 rs11807834 SETD1A GRIN1,SETD1A # 3 rs3729986 MADD MADD,STAC3,SPI1 # 4 rs3729986 STAC3 MADD,STAC3,SPI1 # 5 rs3729986 SPI1 MADD,STAC3,SPI1 </code></pre> <p>Am I missing something obvious? I'd hoped there would be something like:</p> <pre><code># doesn't have such argument df1 %&gt;% separate_rows(Symbols, sep = &quot;,&quot;, keep = TRUE) </code></pre>
[ { "answer_id": 74482789, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 2, "selected": false, "text": "mutate" }, { "answer_id": 74482966, "author": "AndrewGB", "author_id": 15293191, "author_profile": "https://Stackoverflow.com/users/15293191", "pm_score": 2, "selected": false, "text": "cSplit" }, { "answer_id": 74492076, "author": "langtang", "author_id": 4447540, "author_profile": "https://Stackoverflow.com/users/4447540", "pm_score": 2, "selected": false, "text": "library(data.table)\nsetDT(df1)[, .(Genes = strsplit(Symbols,\",\")[[1]]), SNP][df1,on=\"SNP\"]\n" }, { "answer_id": 74492309, "author": "B. Christian Kamgang", "author_id": 10848898, "author_profile": "https://Stackoverflow.com/users/10848898", "pm_score": 1, "selected": false, "text": "library(data.table)\n\nsetDT(df1)[, .(Genes=strsplit(Symbols, \",\")[[1]]), by=.(SNP, Symbols)]\n\n SNP Symbols Genes\n <char> <char> <char>\n1: rs11807834 GRIN1,SETD1A GRIN1\n2: rs11807834 GRIN1,SETD1A SETD1A\n3: rs3729986 MADD,STAC3,SPI1 MADD\n4: rs3729986 MADD,STAC3,SPI1 STAC3\n5: rs3729986 MADD,STAC3,SPI1 SPI1\n" }, { "answer_id": 74512175, "author": "ThomasIsCoding", "author_id": 12158757, "author_profile": "https://Stackoverflow.com/users/12158757", "pm_score": 2, "selected": false, "text": "unnest" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/680068/" ]
74,482,745
<p>When I try to run the following in the terminal it should ask me for username and password but nothing comes up other than the error bellow.</p> <pre><code>npm login --registry=https://npm.pkg.github.com --scope=@Psychedelic npm notice Log in on https://npm.pkg.github.com/ npm ERR! code ENYI npm ERR! Web login not supported` </code></pre> <p>Any ideas?</p> <p>I think i might need to create a ~/.npmrc file with token etc but can't work out how to do that.</p>
[ { "answer_id": 74495262, "author": "Devv", "author_id": 16177977, "author_profile": "https://Stackoverflow.com/users/16177977", "pm_score": 1, "selected": false, "text": ".npmrc" }, { "answer_id": 74519453, "author": "Bora", "author_id": 5904656, "author_profile": "https://Stackoverflow.com/users/5904656", "pm_score": 2, "selected": false, "text": "--auth-type=legacy" }, { "answer_id": 74588199, "author": "Ruslan D.", "author_id": 7896074, "author_profile": "https://Stackoverflow.com/users/7896074", "pm_score": 2, "selected": false, "text": "--auth-type=legacy" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19054702/" ]
74,482,753
<p>Is it possible to somehow export huge SVN repository and load it as a single revision into the new SVN repository?</p> <p>I already spent quite some time for research and couldn't really find a clear answer.</p> <p>Examples always help so let's assume that we have a repository with 1000000 revisions. Now I would like to ask if it's possible to export this repository and load it as a single revision into the new repository.</p> <p>I know that svn doesn't support revision squashing like git does. I know that dump and load commands exist. I also know that this question exists <a href="https://stackoverflow.com/questions/8062691/why-is-a-svn-dump-of-a-single-revision-larger-than-a-full-dump">Why is a SVN dump of a single revision larger than a full dump?</a> But I'm not sure if I understand what's been said there</p> <blockquote> <p>&quot;To ensure that the output of each execution of svnadmin dump is self-sufficient, the first dumped revision is by default a full representation of every directory, file, and property in that revision of the repository. However, you can change this default behavior. If you add the --incremental option&quot;</p> </blockquote> <p>Does it mean that if I dump the last revision, the resulting dump file will contain latest version of every file in my repository? Or will it contain latest version of every file which has been changed in this last revision? Could this help me achieve my goal?</p> <p>My second option seems to be svn export. I understand that it will export all files and directories but will they be in their latest version? In other words will this export contain the same set of files, directories and file contents as if I check outed HEAD revision in this huge repository? If so then is there some easy way to load it back into the new repository with just one revision? Something like svn export /path/to/repo | svn load /path/to/new/repo/containing/only/one/revision</p> <p>I don't really care about the history and I care about the storage. Does any of the above gets me even close to making 1mln revision repository into the new repository with just one revision? Is it even possible to do something like that with SVN? Maybe it's possible to do this with git svn? I think it's going to be next on my research list if above ideas will fail.</p>
[ { "answer_id": 74482928, "author": "Lazy Badger", "author_id": 960558, "author_profile": "https://Stackoverflow.com/users/960558", "pm_score": 1, "selected": false, "text": "--incremental" }, { "answer_id": 74483061, "author": "bahrep", "author_id": 761095, "author_profile": "https://Stackoverflow.com/users/761095", "pm_score": 2, "selected": false, "text": "svnadmin dump" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8960867/" ]
74,482,761
<p>I'm using useHistory and useLocation on two components. When passing data on history.push with a string &quot;test&quot; state will be &quot;test&quot;. However, if I pass &quot;test test&quot; state becomes undefined. Also, useEffect runs twice which I cannot understand why. I have it pointing to search.</p> <p><strong>First Component</strong></p> <pre><code>import React, { useState, useEffect } from &quot;react&quot;; import { useHistory } from &quot;react-router-dom&quot;; const history = useHistory(); const [value, setValue] = useState(&quot;&quot;); const onKeyPress = event =&gt; { if (event.key === &quot;Enter&quot; &amp;&amp; event.target.value.length &gt; 0) { setValue(event.target.value); event.preventDefault(); history.push({ pathname: &quot;/home/Search&quot;, search: `SearchText=${value}`, state: { value } }) } } </code></pre> <p><strong>Second Component Consuming Data</strong></p> <pre><code>import React, { useState, useEffect } from &quot;react&quot;; import { useLocation } from &quot;react-router-dom&quot;; const { search, state } = useLocation(); useEffect(() =&gt; { console.log(&quot;search&quot;, search) console.log(&quot;state&quot;, state) }, [search]) </code></pre> <p><strong>Result if I pass the string &quot;test&quot;.</strong> <a href="https://i.stack.imgur.com/LJMxz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LJMxz.png" alt="enter image description here" /></a></p> <p><strong>Results if I pass the string &quot;test test&quot;.</strong> <a href="https://i.stack.imgur.com/Qk7mz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qk7mz.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74483057, "author": "Lakruwan Pathirage", "author_id": 12383492, "author_profile": "https://Stackoverflow.com/users/12383492", "pm_score": 1, "selected": false, "text": "import React, { useState, useEffect } from \"react\";\nimport { useHistory } from \"react-router-dom\";\n\n const history = useHistory();\n const [value, setValue] = useState(\"\");\n\n const onKeyPress = event => {\n if (event.key === \"Enter\" && event.target.value.length > 0) {\n setValue(event.target.value);\n event.preventDefault();\n history.push({\n pathname: \"/home/Search\",\n search: `SearchText=${event.target.value}`,\n state: { event.target.value}\n })\n }\n }\n" }, { "answer_id": 74484038, "author": "pt2t", "author_id": 11318523, "author_profile": "https://Stackoverflow.com/users/11318523", "pm_score": 0, "selected": false, "text": " useEffect(() => {\n if (state && state.length > 0) {\n const search = state;\n console.log(\"search\", search);\n }\n }, [search])\n\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11318523/" ]
74,482,768
<p>I want to add dynamic fields to my table via button.</p> <p>since the for loop depends on the model's count, when I add a new , I need to add another object to the list.</p> <pre><code> &lt;button type=&quot;button&quot; onclick=&quot;addBtn()&quot;&gt;Add&lt;/button&gt; &lt;table&gt; &lt;tr&gt; &lt;th&gt;Page&lt;/th&gt; &lt;th&gt;Price&lt;/th&gt; &lt;/tr&gt; &lt;button type=&quot;button&quot; onclick=&quot;RazorFunction()&quot;&gt;Click&lt;/button&gt; @for (int i = 0; i &lt; Model.Books.Count; i++) { tr&gt; &lt;td&gt; &lt;label asp-for=&quot;@Model.Books[i].Page&quot; class=&quot;control-label&quot;&gt;Page&lt;/label&gt; &lt;input type=&quot;number&quot; asp-for=&quot;@Model.Books[i].Page&quot; class=&quot;form-control&quot; /&gt; &lt;/td&gt; &lt;td&gt; &lt;label asp-for=&quot;@Model.Books[i].Price&quot; class=&quot;control-label&quot;&gt;Price&lt;/label&gt; &lt;input type=&quot;number&quot; asp-for=&quot;@Model.Books[i].Price&quot; class=&quot;form-control&quot; /&gt; &lt;/td&gt; &lt;/tr&gt; } &lt;/table&gt; </code></pre> <p>it doesn't work as below.</p> <pre><code>@section Scripts { &lt;script&gt; function addBtn() { @Model.Books.Add(new BooksDto() { Page = 500, Price = 0 }); } &lt;/script&gt; @{ await Html.RenderPartialAsync(&quot;_ValidationScriptsPartial&quot;); } } </code></pre>
[ { "answer_id": 74483057, "author": "Lakruwan Pathirage", "author_id": 12383492, "author_profile": "https://Stackoverflow.com/users/12383492", "pm_score": 1, "selected": false, "text": "import React, { useState, useEffect } from \"react\";\nimport { useHistory } from \"react-router-dom\";\n\n const history = useHistory();\n const [value, setValue] = useState(\"\");\n\n const onKeyPress = event => {\n if (event.key === \"Enter\" && event.target.value.length > 0) {\n setValue(event.target.value);\n event.preventDefault();\n history.push({\n pathname: \"/home/Search\",\n search: `SearchText=${event.target.value}`,\n state: { event.target.value}\n })\n }\n }\n" }, { "answer_id": 74484038, "author": "pt2t", "author_id": 11318523, "author_profile": "https://Stackoverflow.com/users/11318523", "pm_score": 0, "selected": false, "text": " useEffect(() => {\n if (state && state.length > 0) {\n const search = state;\n console.log(\"search\", search);\n }\n }, [search])\n\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20235631/" ]
74,482,774
<p>I'm trying to make Autodesk forge web app as presenter web app &amp; viewer web app for VR navigation. I followed the tutorial 'autodesk forge Share Viewer staste with websockets'. (And I learned javascript a little.)</p> <p>Before, the last line was <code> app.listen(PORT, () =&gt; { console.log(`Server listening on port ${PORT}`); });</code></p> <p>And the tutorial want me to adjust some additional lines to that line. code(it doesn't work) - start.js</p> <pre><code>const path = require('path'); const express = require('express'); const PORT = process.env.PORT || 3000; const config = require('./config'); if (config.credentials.client_id == null || config.credentials.client_secret == null) { console.error('Missing FORGE_CLIENT_ID or FORGE_CLIENT_SECRET env. variables.'); return; } let app = express(); app.use(express.static(path.join(__dirname, 'public'))); app.use(express.json({ limit: '50mb' })); app.use('/api/forge/oauth', require('./routes/oauth')); app.use('/api/forge/oss', require('./routes/oss')); app.use('/api/forge/modelderivative', require('./routes/modelderivative')); app.use((err, req, res, next) =&gt; { console.error(err); res.status(err.statusCode).json(err); }); app.listen(PORT, () =&gt; { console.log(`Server listening on port ${PORT}`); }); var server = app.listen(PORT, () =&gt; { console.log(`Server listening on port ${PORT}`); var io = require('socket.io').listen(server); io.on('connection', function (socket) { // any custom action here? socket.on('disconnect', function () { // Any custom action? }); socket.on('join', function (data) { socket.join(data.modelView); }); socket.on('leave', function (data) { socket.leave(data.modelView); }); socket.on('statechanged', function (data) { socket.to(data.modelView).emit('newstate', data.state); }); }); }); </code></pre> <p>my local folder, captured below. <a href="https://i.stack.imgur.com/3wzwH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3wzwH.png" alt="enter image description here" /></a></p> <p>And this web site, <a href="https://forge.autodesk.com/blog/share-viewer-state-websockets" rel="nofollow noreferrer">https://forge.autodesk.com/blog/share-viewer-state-websockets</a></p> <p>So how can I use app.listen when the app.listen function is inside a var type variable?</p> <p>The problem part of above code.</p> <pre><code>var server = app.listen(PORT, () =&gt; { console.log(`Server listening on port ${PORT}`); var io = require('socket.io').listen(server); io.on('connection', function (socket) { // any custom action here? socket.on('disconnect', function () { // Any custom action? }); socket.on('join', function (data) { socket.join(data.modelView); }); socket.on('leave', function (data) { socket.leave(data.modelView); }); socket.on('statechanged', function (data) { socket.to(data.modelView).emit('newstate', data.state); }); }); }); </code></pre> <p>I want the node.js run and duplicate one web app's camera view to another web app's camera view.</p>
[ { "answer_id": 74482809, "author": "jfriend00", "author_id": 816620, "author_profile": "https://Stackoverflow.com/users/816620", "pm_score": 2, "selected": true, "text": "server" }, { "answer_id": 74533647, "author": "Petr Broz", "author_id": 1759915, "author_profile": "https://Stackoverflow.com/users/1759915", "pm_score": 0, "selected": false, "text": "?presenter=1" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15042045/" ]
74,482,776
<p>I created <code>myBatis</code> mapper based on annotations as this <em>changed code</em> example:</p> <pre><code>import org.apache.ibatis.annotations.*; import java.util.List; @Mapper public interface MyTableMapper { @Insert(&quot;INSERT INTO MY_TABLE(&quot; + &quot;Column_1, &quot; + &quot;Column_2 &quot; + &quot;) VALUES (&quot; + &quot;#{myTableModel.columnOne}, &quot; + &quot;#{myTableModel.columnTwo} &quot; + &quot;)&quot;) int insert(MyTableModel myTableModel); @Select(&quot;SELECT * FROM MY_TABLE&quot;) @Results(value = { @Result(id = true, property = &quot;columnOne&quot;, column = &quot;Column_1&quot;), @Result(property = &quot;columnTwo&quot;, column = &quot;Column_2&quot;) }) List&lt;MyTableModel&gt; findAll(); @ResultType(Integer.class) @Select(&quot;SELECT COUNT(*) FROM MY_TABLE &quot; + &quot;WHERE Column_1 = #{columnOne} AND Column_2 = #{columnTwo}&quot;) int countByColumnOneAndColumnTwo(@Param(&quot;columnOne&quot;) String columnOne, @Param(&quot;columnTwo&quot;) String columnTwo); @Update(&quot;UPDATE MY_TABLE SET &quot; + &quot;Column_3 = #{myTableModel.columnThree}, &quot; &quot;Column_4 = #{myTableModel.columnFour} &quot; + &quot;WHERE Column_1 = #{myTableModel.columnOne} AND Column_2 = #{myTableModel.columnTwo}&quot;) int updateByColumnOneAndColumnTwo(@Param(&quot;myTableModel&quot;) MyTableModel myTableModel); @Delete(&quot;DELETE FROM MY_TABLE &quot; + &quot;WHERE Column_1 = #{myTableModel.columnOne} AND Column_2 = #{myTableModel.columnTwo}&quot;) void deleteByColumnOneAndColumnTwo(@Param(&quot;myTableModel&quot;) MyTableModel myTableModel); } </code></pre> <p><strong>CONSIDERATIONS!</strong> I'm using <strong><code>Spring Cloud Config</code></strong> and <strong><code>Hashicorp Vault</code></strong>.</p> <pre><code>spring: datasource: url: jdbc:sqlserver://172.xx.yy.zzz:1433;databaseName=myDatabase;encrypt=true;trustServerCertificate=true; driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver testWhileIdle: true testOnBorrow: true hikari: connection-test-query: SELECT 1 .... </code></pre> <p><em>Some <code>yaml</code> config file</em></p> <pre><code> #Hashicorp Vault spring.cloud.vault: scheme: ${VAULT_SCHEME:http} host: ${VAULT_HOST:localhost} port: ${VAULT_PORT:8xyz0} ... application-name: my-microservice-name #Config Server spring.cloud.config: ... uri: ${SPRING_CLOUD_CONFIG_URI:http://localhost:8xx8} </code></pre> <p>The credentials are stored in vault (<em>To create <strong>SqlSession</strong>, and other things in XML file <strong>are not option</strong></em>)</p> <p>Now I would like to test my mapper. I found this <a href="http://mybatis.org/spring-boot-starter/mybatis-spring-boot-test-autoconfigure/" rel="nofollow noreferrer">documentation</a> <em>Using @MybatisTest</em> part.</p> <p>My Test <code>Spock</code> File!</p> <pre><code>import org.springframework.beans.factory.annotation.Autowired import spock.lang.Specification class MyTableMapperSpec extends Specification { @Autowired private MyTableMapper myTableMapper private MyTableModel myTableModel void setup() { def myTableModelId = MyTableModelId.builder() //.someFields .build() myTableModel = MyTableModel.builder() //.someFields .build() myTableMapper.deleteByColumnOneAndColumnTwo(myTableModel) myTableMapper.insert(myTableModel) } def &quot;FindAll&quot;() { when: List&lt;MyTableModel&gt; listMyTableModel = myTableMapper.findAll() then: !listMyTableModel.isEmpty() } void cleanup() { //myTableMapper.deleteByColumnOneAndColumnTwo(myTableMapper) } } </code></pre> <p>When I like to test this line: <code>myTableMapper.deleteByColumnOneAndColumnTwo(myTableModel)</code> I noted that my <strong><code>myTableMapper</code></strong> is <code>null</code>! Maybe the <code>@Autowired</code> annotation is not suitable in my code!</p> <p><strong>How solve this (Obtain an implementation of my mapper)?</strong></p>
[ { "answer_id": 74482809, "author": "jfriend00", "author_id": 816620, "author_profile": "https://Stackoverflow.com/users/816620", "pm_score": 2, "selected": true, "text": "server" }, { "answer_id": 74533647, "author": "Petr Broz", "author_id": 1759915, "author_profile": "https://Stackoverflow.com/users/1759915", "pm_score": 0, "selected": false, "text": "?presenter=1" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1410223/" ]
74,482,853
<p>I'm trying to read a csv file into a multidimensional list with 52 rows and 7 columns. Currently it's only displaying me the last line as 52 rows of the csv file.</p> <p>I am pretty sure there is something wrong in my readfile function but I couldn't figure it out where I'm making the mistake.</p> <p>Here is my code:</p> <pre><code>rows = 52 cols = 7 def readFile(): matrix = [] file = open(&quot;rainfall.csv&quot;,&quot;r&quot;) for line in file: data = line.split(&quot;,&quot;) for row in range(rows): matrix.append([]) for col in range(cols): matrix[row].append(data[col]) return matrix def display(matrix): for counter in matrix: for values in counter: print(values, end=&quot; &quot;) print() matrix = readFile() display(matrix) </code></pre> <p>Here is the output:</p> <pre><code>8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 8 25 1 6 21 23 0 </code></pre> <p>I have the following csv file:</p> <pre><code>0,0,30,2,21,13,23 29,3,29,30,7,8,25 26,5,26,13,4,13,4 22,30,13,15,15,0,2 3,12,11,10,17,0,15 8,13,11,24,30,24,27 22,18,2,29,11,13,18 15,1,29,23,18,7,0 23,27,3,7,13,14,28 6,25,24,14,20,23,5 24,29,26,22,0,9,18 22,27,22,20,24,29,21 23,13,14,4,13,1,21 25,21,21,6,28,17,19 4,6,11,10,21,1,5 11,7,22,11,10,24,15 25,11,23,3,23,8,3 22,23,0,29,15,12,5 21,11,18,22,1,4,3 11,10,3,1,30,14,22 2,16,10,2,12,9,9 2,29,17,16,13,18,7 22,15,27,19,6,26,11 21,7,18,4,14,14,2 6,30,12,4,26,22,11 21,16,14,11,28,20,3 19,10,22,18,30,9,27 8,15,17,4,11,16,6 19,17,16,6,18,18,6 2,15,3,25,27,16,11 15,5,26,24,24,30,5 15,11,16,22,14,23,28 25,6,7,20,26,18,16 5,5,21,22,24,16,5 6,27,11,8,24,1,16 28,4,1,4,3,19,24 19,3,27,14,12,24,0 6,3,26,15,15,22,26 18,5,0,14,15,7,26 10,5,12,22,8,7,11 11,1,18,29,6,9,26 3,23,2,21,29,15,25 5,7,1,6,15,18,24 28,11,0,6,28,11,26 4,28,9,24,11,13,2 6,2,14,18,20,21,1 20,29,22,21,11,14,20 28,23,14,17,25,3,18 6,27,6,20,19,5,24 25,3,27,22,7,12,21 12,22,8,7,0,11,8 8,25,1,6,21,23,0 </code></pre>
[ { "answer_id": 74482925, "author": "Khaled DELLAL", "author_id": 15852600, "author_profile": "https://Stackoverflow.com/users/15852600", "pm_score": 0, "selected": false, "text": " for line in file:\n data = line.split(\",\")\n" }, { "answer_id": 74483033, "author": "Mark Tolonen", "author_id": 235698, "author_profile": "https://Stackoverflow.com/users/235698", "pm_score": 2, "selected": true, "text": "csv" }, { "answer_id": 74483040, "author": "Michael Ruth", "author_id": 4583620, "author_profile": "https://Stackoverflow.com/users/4583620", "pm_score": 0, "selected": false, "text": "csv" }, { "answer_id": 74483067, "author": "AziMez", "author_id": 13809290, "author_profile": "https://Stackoverflow.com/users/13809290", "pm_score": 0, "selected": false, "text": "#Read data file\nwith open('rainfall.csv', 'r') as f:\n lst = [[int(num) for num in line.split(',')] for line in f]\n\n#Display result\nfor i in lst:\n print(*i)\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4174508/" ]
74,482,860
<p>I have a ton of modals on a page and I'm using this script to link the ID of an HTML button to the ID of the modal and it's close button:</p> <pre><code>var target = document.getElementById('show1'); var currentOpacity = 0; $(document).ready(function () { $(&quot;#hide1&quot;).click(function () { $(&quot;#details1&quot;).hide(); target.style.opacity = currentOpacity + 1; }); $(&quot;#show1&quot;).click(function () { $(&quot;#details1&quot;).show(); target.style.opacity = currentOpacity - 1; }); }); const button1 = document.querySelector(&quot;#show1&quot;); const readout1 = document.querySelector(&quot;p&quot;); button1.addEventListener(&quot;mousemove&quot;, (e) =&gt; { const { x, y } = button1.getBoundingClientRect(); button1.style.setProperty(&quot;--x&quot;, e.clientX - x); button1.style.setProperty(&quot;--y&quot;, e.clientY - y); }); </code></pre> <p>This works but I have 56 buttons... How could I write this script so that #show1 #details1 #hide1, #show2 #details2 #hide2, #show3 #details3 #hide3 etc. all the way to 56 work without duplicating this code block 56 times?</p> <p>EDIT</p> <p>Here is the HTML for an item:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;section id="photo01" class="item-module-wrap"&gt; &lt;div class="item-module"&gt; &lt;div class="blurred-image" style="background-image: url('xxxxx');"&gt;&lt;/div&gt; &lt;div class="dot-texture"&gt;&lt;/div&gt; &lt;article&gt; &lt;div class="dgov-grid"&gt; &lt;div class="dgov-col-sm-7 dgov-col-md-8 dgov-col-lg-9"&gt; &lt;div class="main-photo-module"&gt; &lt;div class="sticky"&gt; &lt;h2&gt;xxxxx&lt;/h2&gt; &lt;/div&gt; &lt;div class="sticky"&gt;&lt;span&gt;xxxxx&lt;/span&gt;&lt;/div&gt; &lt;div class="sticky"&gt; &lt;button type="button" id="show1" class="details-button shiny"&gt;Details&lt;/button&gt; &lt;/div&gt; &lt;img src="xxxxx" alt="xxxxx"/&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="dgov-col-sm-5 dgov-col-md-4 dgov-col-lg-3"&gt; &lt;div class="aside-module"&gt; &lt;div class="details" id="details1"&gt; &lt;div class="close" id="hide1"&gt;&lt;i class="fa fa-times" aria-hidden="true"&gt;&lt;/i&gt;&lt;/div&gt; &lt;p class="description"&gt;xxxxx&lt;/p&gt; &lt;p class="extra"&gt;xxxxx&lt;/p&gt; &lt;p class="extra"&gt;xxxxx&lt;/p&gt; &lt;div class="social"&gt; xxxxx &lt;/div&gt; &lt;/div&gt; &lt;div class="sticky"&gt; &lt;time&gt; 1 of 56 &lt;/time&gt; &lt;/div&gt; &lt;div class="item-number layer" data-px-per-scroll="0.5" data-initial-position="450"&gt;01&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/article&gt; &lt;/div&gt; &lt;/section&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74483152, "author": "Sushanth --", "author_id": 941272, "author_profile": "https://Stackoverflow.com/users/941272", "pm_score": 1, "selected": false, "text": "section" }, { "answer_id": 74486171, "author": "Carsten Massmann", "author_id": 2610061, "author_profile": "https://Stackoverflow.com/users/2610061", "pm_score": 0, "selected": false, "text": "<section>" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74482860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20534486/" ]