qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,423,699
<p>For example lest say I have those two lists:</p> <pre><code>x = [&quot;hi [ICON]&quot;, &quot;apple [ICON]&quot;, &quot;world [ICON]&quot; ] y = [&quot;hi&quot;, &quot;apple&quot;] </code></pre> <p>How can I tell if all of list <code>y</code> is inside of list <code>x</code>?</p>
[ { "answer_id": 74423757, "author": "I'mahdi", "author_id": 1740577, "author_profile": "https://Stackoverflow.com/users/1740577", "pm_score": 3, "selected": true, "text": "any" }, { "answer_id": 74423785, "author": "Giuseppe La Gualano", "author_id": 20249888, "author_profile": "https://Stackoverflow.com/users/20249888", "pm_score": 0, "selected": false, "text": "combined = ' '.join(x)\n\nyour_bool = False # init to false\nfor el in y:\n if el in combined:\n your_bool = True\n else:\n your_bool = False\n\nprint(your_bool)\n" }, { "answer_id": 74423789, "author": "romain gal", "author_id": 9612932, "author_profile": "https://Stackoverflow.com/users/9612932", "pm_score": 1, "selected": false, "text": "ly" }, { "answer_id": 74423795, "author": "dskrypa", "author_id": 19070573, "author_profile": "https://Stackoverflow.com/users/19070573", "pm_score": 0, "selected": false, "text": "y" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74423699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10014106/" ]
74,423,702
<p>I came across the Apple website where I can see the same image/design on scrolling up to some extent and also animation on scrolling to the bottom and up.</p> <p>Ref URL: <a href="https://www.apple.com/in/macbook-air-m2/" rel="nofollow noreferrer">https://www.apple.com/in/macbook-air-m2/</a></p> <p>I want to know how to implement those type feature.</p>
[ { "answer_id": 74536881, "author": "Shivangam Soni", "author_id": 16659219, "author_profile": "https://Stackoverflow.com/users/16659219", "pm_score": 1, "selected": false, "text": "const observer = new IntersectionObserver((entries) => {\n entries.forEach((entry) => {\n if (entry.isIntersecting) {\n entry.target.classList.add(\"show\");\n } else {\n entry.target.classList.remove(\"show\");\n }\n });\n});\n\nconst sections = document.querySelectorAll(\".section\");\nsections.forEach((el) => observer.observe(el));" }, { "answer_id": 74543859, "author": "WizardOfOz", "author_id": 19668106, "author_profile": "https://Stackoverflow.com/users/19668106", "pm_score": 0, "selected": false, "text": "gsap.timeline({\n scrollTrigger: {\n trigger: \".shoe\",\n start: \"center center\",\n end: \"bottom top\",\n scrub: true,\n pin: true\n }\n})\n .from(\".midsole\", { y: innerHeight * 1.5 })\n .from(\".outsole\", { y: innerHeight * 1.5 });\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74423702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11074422/" ]
74,423,719
<p>In my Vaadin (v.23.2.6) application I have a form tied up to Filter class which has 5 attributes. All of them are optional, i.e. user can leave the blank.</p> <pre><code> public FilterPanel(ApiBookUtils api) { this.api = api; this.authorField = new ComboBox&lt;Author&gt;(&quot;Author Name&quot;); this.countryField = new ComboBox&lt;&gt;(&quot;Country&quot;); this.countryField.setReadOnly(true); this.fromYear = new IntegerField (&quot;From&quot;); this.fromYear.setWidth(&quot;60px&quot;); this.toYear = new IntegerField (&quot;To&quot;); this.toYear.setWidth(&quot;60px&quot;); this.binder = new Binder(Filter.class); this.setModal(true); this.setCloseOnOutsideClick(false); this.setCloseOnEsc(true); buildDialog(); } private void buildDialog() { bindFields(); addFields(); setDialogListeners(); setDialogItems(); } private void bindFields() { this.binder.bind(authorField, Filter::getAuthor, Filter::setAuthor); this.binder.forField(countryField).bind(Filter::getCountry, Filter::setCountry); this.binder.forField(fromYear).bind(Filter::getFromYear, Filter::setFromYear); this.binder.forField(toYear).bind(Filter::getToYear, Filter::setToYear); this.binder.forField(postingDateField).bind(Filter::getPostingDate, Filter::setPostingDate); this.binder.forField(tagField).bind(Filter::getTags, Filter::setTags); } </code></pre> <p>I am getting getting exception if IntegerField is left blank.</p> <blockquote> <p>com.vaadin.flow.data.binder.BindingException: An exception has been thrown inside binding logic for the field element [label='From'] at com.vaadin.flow.data.binder.Binder$BindingImpl.execute(Binder.java:1570) ~[flow-data-23.2.5.jar:23.2.5] at com.vaadin.flow.data.binder.Binder$BindingImpl.writeFieldValue(Binder.java:1427) ~[flow-data-23.2.5.jar:23.2.5] at java.base/java.lang.Thread.run(Thread.java:832) ~[na:na] Caused by: java.lang.NullPointerException: null at com.vaadin.flow.data.binder.Binder$BindingImpl.lambda$writeFieldValue$5169480d$1(Binder.java:1431) ~[flow-data-23.2.5.jar:23.2.5]</p> </blockquote> <p>Does anybody know how to make binder to accept empty field and set up default value in the bean?</p>
[ { "answer_id": 74441237, "author": "Tatu Lund", "author_id": 8962195, "author_profile": "https://Stackoverflow.com/users/8962195", "pm_score": -1, "selected": false, "text": "IntegerField" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74423719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4103615/" ]
74,423,723
<p>I deploy a docker swarm with 6 nodes. I built some images and I am trying to add them as services to the swarm. I have 5 microservices. When I run the on one host with docker-compose everything works fine. I run this command docker service create rate --with-registry-auth and I get the following message.</p> <pre><code>image rate:latest could not be accessed on a registry to record its digest. Each node will access rate:latest independently, possibly leading to different nodes running different versions of the image. yyf9m49xw3enwano1scr55ufc overall progress: 0 out of 1 tasks 1/1: No such image: rate:latest </code></pre> <p>I run docker images and the rate image is appeared. rate is the repository name. I also tried with the image id but didn't worked. The only images that I can add to swarm is images that is public.</p>
[ { "answer_id": 74434087, "author": "BMitch", "author_id": 596285, "author_profile": "https://Stackoverflow.com/users/596285", "pm_score": 1, "selected": false, "text": "image rate:latest could not be accessed on a registry to record\nits digest. Each node will access rate:latest independently,\npossibly leading to different nodes running different\nversions of the image.\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74423723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17998172/" ]
74,423,732
<p>I have 2 folders separated, one for backend and one for frontend services:</p> <ul> <li>backend/docker-compose.yml</li> <li>frontend/docker-compose.yml</li> </ul> <p>The backend has a headless <code>wordpress</code> installation on <code>nginx</code>, with the scope to serve the frontend as an api service. The frontend runs on <code>next.js</code>. Here are the 2 different <code>docker-compose.yml</code>:</p> <p><code>backend/docker-compose.yml</code></p> <pre><code>version: '3.9' services: nginx: image: nginx:latest container_name: my-app-nginx ports: - '80:80' - '443:443' - '8080:8080' ... networks: - internal-network mysql: ... networks: - internal-network wordpress: ... networks: - internal-network networks: internal-network: external: true </code></pre> <p><code>frontend/docker-compose.yml</code></p> <pre><code>version: '3.9' services: nextjs: build: ... container_name: my-app-nextjs restart: always ports: - 3000:3000 networks: - internal-network networks: internal-network: driver: bridge name: internal-network </code></pre> <p>In the frontend I use the <code>fetch</code> api in <code>nextjs</code> as following:</p> <pre><code>fetch('http://my-app-nginx/wp-json/v1/enpoint', ...) </code></pre> <p>I tried also with ports <code>80</code> and <code>8080</code>, without success.</p> <p>The sequence of commands I run are:</p> <ul> <li><code>docker network create internal-network</code></li> <li>in <code>backend/</code> folder, <code>docker-compose up -d</code> (all backend containers run fine, I can fetch data with Postman from WordPress api)</li> <li>in <code>frontend/ folder</code>, <code>docker-compose up -d</code> fails with the error <code>Error: getaddrinfo EAI_AGAIN my-app-nginx</code></li> </ul> <p>I am not a very expert user of <code>docker</code> so I might miss something here, but I understand that there might be internal network issues over the containers. I read many answers regarding this topic but I couldn't figure it out.</p> <p>Any recommendations?</p>
[ { "answer_id": 74434087, "author": "BMitch", "author_id": 596285, "author_profile": "https://Stackoverflow.com/users/596285", "pm_score": 1, "selected": false, "text": "image rate:latest could not be accessed on a registry to record\nits digest. Each node will access rate:latest independently,\npossibly leading to different nodes running different\nversions of the image.\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74423732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4464905/" ]
74,423,762
<p>I am getting a multi-line block of text from the single column of a database query result set like this:</p> <pre><code>$data = &lt;&lt;&lt;DATA DATE = FEE = PAYMENT 2021-03-09 = 119.25 = 119.25 = 2021-04-13 2021-03-15 = 119.25 = 119.25 = 2021-04-13 DATA; </code></pre> <p>I need to parse this text, ignore the header line and any blank lines, extract the first and second values in each line (a date and a float value), then populate an array of associative arrays.</p> <p>Desired result:</p> <pre><code>[ {&quot;Date&quot;: &quot;2021-01-23&quot;, &quot;fee&quot;: 0.00, &quot;title&quot;: &quot;example&quot; }, {&quot;Date&quot;: &quot;2021-01-31&quot;, &quot;fee&quot;: 0.00, &quot;title&quot;: &quot;example&quot; }, ] </code></pre> <p>My current code:</p> <pre><code>$data = implode(&quot;=&quot;, $data); $data = str_replace(&quot;\n&quot;, &quot;=&quot;, $data); $data = str_replace(&quot; &quot;, &quot;&quot;, $data); $data = explode(&quot;=&quot;, $data); </code></pre> <p>But my result looks like this:</p> <pre><code>Array ( [0] =&gt; DATE [1] =&gt; FEE [2] =&gt; PAYMENT [3] =&gt; 2021-01-23 [4] =&gt; 119.25 [5] =&gt; 119.25 [6] =&gt; 2021-01-31 [7] =&gt; 2021-01-31 [8] =&gt; 119.25 [9] =&gt; 119.25 [10] =&gt; 2021-04-13 ) </code></pre> <p>I also tried iterating and saving every n row:</p> <pre><code>$result = array(); $data = array_values($data); $count = count($data); for($i = 0; $i &lt; $count; $i += 4) { $result = [&quot;Date&quot;.$i =&gt; $data[$i]]; } for($i = 0; $i &lt; $count; $i += 2) { $result[&quot;fee&quot;] = $data[$i]; } </code></pre>
[ { "answer_id": 74423844, "author": "Markus Zeller", "author_id": 2645713, "author_profile": "https://Stackoverflow.com/users/2645713", "pm_score": 1, "selected": true, "text": "$result = 'DATE = FEE = PAYMENT\n2021-03-09 = 119.25 = 119.25 = 2021-04-13\n\n2021-03-15 = 119.25 = 119.25 = 2021-04-13';\n\n$rows = explode(\"\\n\", $result);\narray_shift($rows);\n\n$results = [];\nforeach ($rows as $row) {\n $row = trim($row);\n if (empty($row)) continue;\n [$date, $fee] = array_map('trim', explode('=', $row));\n $results[] = [\n 'date' => $date,\n 'fee' => floatval($fee),\n 'title' => 'example',\n ];\n}\n\necho json_encode($results, JSON_PRETTY_PRINT);\n" }, { "answer_id": 74424992, "author": "mickmackusa", "author_id": 2943403, "author_profile": "https://Stackoverflow.com/users/2943403", "pm_score": 1, "selected": false, "text": "sscanf()" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74423762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10563104/" ]
74,423,764
<p>Need to create lists with the letters of the words of the first list by index. For example the first output list for the first index of all the words will be ['l', 'c', 'e', 't', 's', 'a', 's', 'm', 'p']. I have solved this problem in a certain way, but i need another way to do this without the except method.</p> <p>This is my code:</p> <pre><code>l = ['lion', 'cat', 'elephant', 'tiger', 'spyder', 'alligator','snake', 'monkey','penguin'] new_list = [] x = 0 y = 0 for words in l: z = len(words) if x &lt;= z: x = z while y != x: ultimate_list = [] for words in l: try: ultimate_list.append(words[y]) except Exception: pass new_list.append(ultimate_list) y += 1 print(new_list) </code></pre> <p>Thanks for the help!</p>
[ { "answer_id": 74423844, "author": "Markus Zeller", "author_id": 2645713, "author_profile": "https://Stackoverflow.com/users/2645713", "pm_score": 1, "selected": true, "text": "$result = 'DATE = FEE = PAYMENT\n2021-03-09 = 119.25 = 119.25 = 2021-04-13\n\n2021-03-15 = 119.25 = 119.25 = 2021-04-13';\n\n$rows = explode(\"\\n\", $result);\narray_shift($rows);\n\n$results = [];\nforeach ($rows as $row) {\n $row = trim($row);\n if (empty($row)) continue;\n [$date, $fee] = array_map('trim', explode('=', $row));\n $results[] = [\n 'date' => $date,\n 'fee' => floatval($fee),\n 'title' => 'example',\n ];\n}\n\necho json_encode($results, JSON_PRETTY_PRINT);\n" }, { "answer_id": 74424992, "author": "mickmackusa", "author_id": 2943403, "author_profile": "https://Stackoverflow.com/users/2943403", "pm_score": 1, "selected": false, "text": "sscanf()" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74423764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20494445/" ]
74,423,772
<p>I have a string with the names of a cities and the numbers of people living in them. I need to match only names of cities using Regex</p> <pre><code>city = &quot;New York - 8 468 000 Los Angeles - 3 849 000 Berlin - 3 645 000&quot; </code></pre> <p>tried this</p> <pre><code>[a-zA-Z]+(?:[\s-][a-zA-Z]+)*$ </code></pre> <p>but it returns &quot;None&quot;</p>
[ { "answer_id": 74423808, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 0, "selected": false, "text": "([^-]+?)\\s*-\\s*([\\d\\s]+)\n" }, { "answer_id": 74423817, "author": "Celius Stingher", "author_id": 11897007, "author_profile": "https://Stackoverflow.com/users/11897007", "pm_score": 2, "selected": true, "text": "[a-zA-Z]+" }, { "answer_id": 74423846, "author": "SaSkY", "author_id": 18104248, "author_profile": "https://Stackoverflow.com/users/18104248", "pm_score": 1, "selected": false, "text": "[a-zA-Z]+ ?[a-zA-Z]+(?= *-)\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74423772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20250998/" ]
74,423,773
<p>I have an array of points and I'm looking to print the name of the points instead of the actual points.</p> <pre><code>A = (2,0) B = (3, 4) C = (5, 6) array1 = [A, B, C] </code></pre> <p>when I do <code>print(array1[0])</code> it ends up printing the values. But I want to print the letters such as A, B or C. How would I print the letters instead?</p> <p>I've also tried <code>print(array1)</code> and it also just prints all the values instead.</p>
[ { "answer_id": 74423917, "author": "romano_fafard", "author_id": 4462565, "author_profile": "https://Stackoverflow.com/users/4462565", "pm_score": 1, "selected": false, "text": "print(\"A\")" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74423773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20494733/" ]
74,423,781
<p>I want the user to input values of elements to an array of 10 <code>int</code>s. Then I want to print out all the indexes of the values of the elements which when divided by 5 give 0.</p> <p>I've tried doing it like this, but it's not working. How do I append the i's into an array?</p> <pre><code>#include &lt;stdio.h&gt; #define N 10 int main() { int a[10]; int i; int index[10] = {}; printf(&quot;Input %d values into the array:\n&quot;, N); for (i = 0; i &lt; N; i++){ scanf(&quot;%d&quot;, &amp;a[i]); if (a[i] % 5 == 0){ index[10] += i; } } printf(&quot;%d&quot;, index); return 0; } </code></pre>
[ { "answer_id": 74423917, "author": "romano_fafard", "author_id": 4462565, "author_profile": "https://Stackoverflow.com/users/4462565", "pm_score": 1, "selected": false, "text": "print(\"A\")" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74423781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19297945/" ]
74,423,792
<p>I have some data which looks like:</p> <pre><code> NMUN 1 Cubo de Tierra del Vino, El 2 Peraleja, La 3 Franco, El 4 Pont de Vilomara i Rocafort, El 5 Gabias, Las 6 Adrada, La 7 Bola, A 8 Fayos, Los 9 Recuenco, El </code></pre> <p>What I am trying to do is to move everything after the last comma to the beginning of the place.</p> <p>Expected output:</p> <pre><code>NMUN El Cubo de Tierra del Vino La Peraleja El Franco El Pont de Vilomara i Rocafort Las Gabias </code></pre> <p>Data</p> <pre><code>data = structure(list(NMUN = c(&quot;Cubo de Tierra del Vino, El&quot;, &quot;Peraleja, La&quot;, &quot;Franco, El&quot;, &quot;Pont de Vilomara i Rocafort, El&quot;, &quot;Gabias, Las&quot;, &quot;Adrada, La&quot;, &quot;Bola, A&quot;, &quot;Fayos, Los&quot;, &quot;Recuenco, El&quot;, &quot;Pobra do Brollón, A&quot;, &quot;Viso de San Juan, El&quot;, &quot;Viso del Alcor, El&quot;, &quot;Granjuela, La&quot;, &quot;Bòrdes, Es&quot;, &quot;Guingueta d'Àneu, La&quot;, &quot;Villares, Los&quot;, &quot;Grove, O&quot;, &quot;Losar del Barco, El&quot;, &quot;Iglesuela, La&quot;, &quot;Vall de Bianya, La&quot;)), row.names = c(NA, -20L), class = &quot;data.frame&quot;) </code></pre>
[ { "answer_id": 74423837, "author": "stefan", "author_id": 12993861, "author_profile": "https://Stackoverflow.com/users/12993861", "pm_score": 3, "selected": true, "text": "gsub" }, { "answer_id": 74424090, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 1, "selected": false, "text": "library(dplyr)\nlibrary(tidyr)\n\ndata %>% \n separate(NMUN, c(\"NMUN\", \"a\"), sep = \",\") %>% \n unite(NMUN, c(a, NMUN), sep = \" \")\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74423792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6447399/" ]
74,423,811
<p>My goal is to view the content of the bottom page from the top of the other content page. In order to accomplish this, I used PushModalAsync to navigate and set the BackgroundColor property of the navigation page to Transparent. I can view the content on the bottom page on Android. However on the iOS platform, a black color is always displayed and I am unable to read the content of the bottom page. Why is the background color always black even when it is set to be transparent in PushModalAsync?</p> <p><strong>Note</strong>: The iOS platform displays a white screen when I change the navigation to PushAsync.</p> <p><strong>Expected Behavior:</strong> Background color should not be black and it should be transparent when navigating using PushModalAsync</p> <p><strong>Actual Behavior:</strong> Background color is always black even when the content page background color is set as transparent when navigating using PushModalAsync</p> <p><strong>Android Screenshot</strong></p> <p><a href="https://i.stack.imgur.com/erHlJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/erHlJ.png" alt="Android scenario" /></a></p> <p><strong>iOS Screenshot</strong></p> <p><a href="https://i.stack.imgur.com/LBT6o.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LBT6o.png" alt="iOS scenario" /></a></p> <p>The issue reproducing sample is provided below: <a href="https://syncfusion.bolddesk.com/attachment/download/preview?token=eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjM1MTE2NSIsIm9yZ2lkIjoiMyIsImlzcHJldmlldyI6InRydWUiLCJleHAiOjE2NjczMjE0NzIsImlzcyI6InN5bmNmdXNpb24uYm9sZGRlc2suY29tIn0.bFo4h9FVrgKJko8KnCXD4a4ffjifHZdul6y4X6-TxqQ" rel="nofollow noreferrer">DemoSample</a></p>
[ { "answer_id": 74425172, "author": "Ivan Ičin", "author_id": 202179, "author_profile": "https://Stackoverflow.com/users/202179", "pm_score": 1, "selected": false, "text": "ViewController" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74423811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7498552/" ]
74,423,822
<p>I have a list of times of events in strings (i.e. ['Apr 24th 10:00 p.m.','Apr 26th 7:00 p.m.']). I'd like to replace each instance of the number 10 with the number 7, 8 with the number 5 etc. Is there any way to have a list of values (i.e. [10,9,8,7,6,5]) that wherever one of those values is found in a string then that value is replaced with the value with the same index in another list (i.e. [7,6,5,4,3]). Essentially I'd like to loop through the items in my list and replace every instance of a number with the time 3 hours prior to it. This was my stab at it but I believe there's a cleaner way of doing it.</p> <pre><code>for x in resulter: y=x.split(':') first=y[0][:-1] hour=y[0][-1] end=y[1] new_hour=int(hour)-3 newtime=first+str(new_hour)+':'+ end new_western_times.append(newtime) newer_western_times=[string.replace('1-3', '7') for string in new_western_times] newest_western_times=[string.replace('0:', '12:') for string in newer_western_times] </code></pre>
[ { "answer_id": 74425172, "author": "Ivan Ičin", "author_id": 202179, "author_profile": "https://Stackoverflow.com/users/202179", "pm_score": 1, "selected": false, "text": "ViewController" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74423822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20494739/" ]
74,423,826
<p>I need to have a start and stop event on input range, so I can detect when dragging start and when it ends. Are these good events to use or is there a better way?</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 input = document.getElementById('input') input.addEventListener("mousedown", function() { console.log('start') }, false); input.addEventListener("change", function() { console.log('end') }, false);</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input id="input" type="range" min="0" max="100" value="" /&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74425172, "author": "Ivan Ičin", "author_id": 202179, "author_profile": "https://Stackoverflow.com/users/202179", "pm_score": 1, "selected": false, "text": "ViewController" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74423826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1009466/" ]
74,423,880
<p>For uni I have this project where i need to program a simple game in haskell. Right now I'm facing the following problem:</p> <pre><code>instance Renderable Player where render (MkPlayer pos rad bults _) = do playerpic &lt;- displayimg pos rad &quot;./images/player.bmp&quot; bulletpics &lt;- ... return $ pictures (playerpic:bulletpics) </code></pre> <p>at the <code>...</code> i need a function <code>f :: [Bullet] -&gt; IO [Picture]</code></p> <p>where the function producing a picture for the bullet object is :</p> <pre><code>render :: Bullet -&gt; IO Picture </code></pre> <p>is there a way to create the function I need. I've been toying around on paper with monads and functors but cannot find a way to get this done. Any help at all with this is greatly appreciated!!</p>
[ { "answer_id": 74423927, "author": "Willem Van Onsem", "author_id": 67579, "author_profile": "https://Stackoverflow.com/users/67579", "pm_score": 3, "selected": true, "text": "mapM :: (Traversable t, Monad m) => (a -> m b) -> t a -> m (t b)" }, { "answer_id": 74423929, "author": "Noughtmare", "author_id": 15207568, "author_profile": "https://Stackoverflow.com/users/15207568", "pm_score": 2, "selected": false, "text": "traverse :: (Traversable t, Applicative f) => (a -> f b) -> t a -> f (t b)" }, { "answer_id": 74430874, "author": "amalloy", "author_id": 625403, "author_profile": "https://Stackoverflow.com/users/625403", "pm_score": 1, "selected": false, "text": "do" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74423880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15547208/" ]
74,423,883
<p><a href="https://i.stack.imgur.com/tU9Ds.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tU9Ds.png" alt="enter image description here" /></a> React Routing Problem. I Install react-router-dom but it don't work how can i fix</p> <p><a href="https://i.stack.imgur.com/f11W5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f11W5.png" alt="enter image description here" /></a> This tutorial will be reading page. but my pc don't lick this</p>
[ { "answer_id": 74424010, "author": "Arsalan-Zahid", "author_id": 12104214, "author_profile": "https://Stackoverflow.com/users/12104214", "pm_score": 0, "selected": false, "text": "import React, { useContext, useEffect, useState } from \"react\";\nimport {useNavigate} from \"react-router-dom\";\nimport AuthContext from \"../../context/AuthContext\";\n\nexport default function Logout(){\n // in order to navigate, you need to first use the useNavigate hook.\n const navigate = useNavigate();\n //this is a function that logs out the user\n let {logoutUser} = useContext(AuthContext);\n\n\n //at the start, log out the user\n useEffect(()=>{\n logoutUser();\n //then -- and this is the part you want -- navigate them to the login page.\n navigate('/auth/login');\n },[])\n \n}\n" }, { "answer_id": 74424143, "author": "Drew Reese", "author_id": 8690857, "author_profile": "https://Stackoverflow.com/users/8690857", "pm_score": 2, "selected": true, "text": "react-router-dom@5" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74423883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19347218/" ]
74,423,896
<p>Here is my an example of a document from my &quot;Cart&quot; schema:</p> <pre><code>{ _id: 1, line_items: [ { item_id: 101, color: 'white', quantity: 1 }, { item_id: 101, color: 'green', quantity: 1 }, { item_id: 102, color: 'white', quantity: 1 }, ] } </code></pre> <p>I want to increase the quantity of the item which is uniquely identified by item_id = 101 and color = 'white'</p> <p>I want it to be increase by x amount where x can be any number. How do I do this?</p> <p>(edit 1) Here is what I have tried</p> <pre><code>await Cart.findById(1).then(doc =&gt; { const i = doc.line_items.findIndex(elm =&gt; { return (elm.item == item &amp;&amp; elm.color == color) // (edit 2) item is a variable = 101 and color is a variable = 'white' }); doc.line_items[i].quantity += quantity; doc.save(); }).catch(err =&gt; { throw err; }); </code></pre> <p>However, this isnt working because the changes in quantity aren't being saved to the database for some reason even though it is being updated when I console.log() it inside of this code.</p> <p>I also beleive it should be possible to solve my problem with a single findByIdAndUpdate function though, but I have no idea how to do that</p>
[ { "answer_id": 74424010, "author": "Arsalan-Zahid", "author_id": 12104214, "author_profile": "https://Stackoverflow.com/users/12104214", "pm_score": 0, "selected": false, "text": "import React, { useContext, useEffect, useState } from \"react\";\nimport {useNavigate} from \"react-router-dom\";\nimport AuthContext from \"../../context/AuthContext\";\n\nexport default function Logout(){\n // in order to navigate, you need to first use the useNavigate hook.\n const navigate = useNavigate();\n //this is a function that logs out the user\n let {logoutUser} = useContext(AuthContext);\n\n\n //at the start, log out the user\n useEffect(()=>{\n logoutUser();\n //then -- and this is the part you want -- navigate them to the login page.\n navigate('/auth/login');\n },[])\n \n}\n" }, { "answer_id": 74424143, "author": "Drew Reese", "author_id": 8690857, "author_profile": "https://Stackoverflow.com/users/8690857", "pm_score": 2, "selected": true, "text": "react-router-dom@5" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74423896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19643541/" ]
74,423,899
<p>I have a large panel data set that includes job descriptions. I would like to extract the wages/salaries from the job descriptions. However, there is a lot of variability in how the salaries are stated in the job descriptions. Here are a few examples:</p> <p>“The salary range in Colorado for this role is from USD $123,500 - $185,500”</p> <p>“The salary for this role is $180,000 to $216,000”</p> <p>“The salary for this role in the state of Colorado is between $150,800 to $226,000.”</p> <p>“Pay Range: $12.00 - $16.00”</p> <p>“Salary Range: $180,000 - $147,000”</p> <p>“The anticipated starting base pay for this position is: $100,000 to $142,000 per year”</p> <p>“Hourly wage estimate: $21.49 - $32.24 / hour”</p> <p>In addition, sometimes the job description will include a &quot;$&quot; sign referring to a company's budget or market value, so it isn't as simple as just taking the information after the dollar sign.</p> <p>I think the best way to go about this would be to use regular expressions. I think if I create a comprehensive set of key phrases (e.g., &quot;The salary range for this role is&quot;, &quot;Salary Range:&quot;, &quot;Pay Range:&quot;, &quot;The anticipated base pay for this position is:&quot;, etc.) that come before the salary information, I could then grab the pay information that comes after.</p> <p>Here is the code I have come up with:</p> <pre><code>pattern = r'\Starting\s+Pay\s+Range\: | \Salary\s+Range\: | \s+Pay\Range\:' pd_00['salary_info'] = pd_00['job_description'].str.extract(pattern, re.IGNORECASE, expand=False) </code></pre> <p>My issue is that I do not know the best way to go about pulling the salary information that comes after the set of key phrases. If you look at the above examples, sometimes the information has a &quot;-&quot; between the range, and sometimes it has a &quot;to&quot;. Also, sometimes there are decimals in the dollar values, and sometimes there is no decimal. Any help would be greatly appreciated!</p>
[ { "answer_id": 74424007, "author": "SaSkY", "author_id": 18104248, "author_profile": "https://Stackoverflow.com/users/18104248", "pm_score": 2, "selected": false, "text": "\\1" }, { "answer_id": 74424126, "author": "Celius Stingher", "author_id": 11897007, "author_profile": "https://Stackoverflow.com/users/11897007", "pm_score": 3, "selected": true, "text": "from transformers import pipeline\nqa_model = pipeline(\"question-answering\")\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74423899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20381052/" ]
74,423,910
<p>In <code>App.tsx</code>, I have:</p> <pre><code>export default function App() { const Stack = createNativeStackNavigator(); return ( &lt;NavigationContainer&gt; &lt;Stack.Navigator initialRouteName='feed' screenOptions={{ headerShown: false, gestureDirection: 'vertical' }}&gt; &lt;Stack.Screen name=&quot;feed&quot; component={IvoryFeedScreen} /&gt; &lt;Stack.Screen name=&quot;home&quot; component={HomeScreen} /&gt; &lt;/Stack.Navigator&gt; &lt;/NavigationContainer&gt; ); } </code></pre> <p>How can I have these stacks swipe-up-able like in TikTok?</p>
[ { "answer_id": 74459953, "author": "Hardik prajapati", "author_id": 18241250, "author_profile": "https://Stackoverflow.com/users/18241250", "pm_score": 0, "selected": false, "text": "const abc = [1, 2, 4];\n <FlatList\n horizontal={true}\n data={abc}\n maxToRenderPerBatch={1}\n bounces={false}\n windowSize={1}\n pagingEnabled={true}\n snapToAlignment={'end'}\n snapToInterval={SCREEN_WIDTH}\n decelerationRate={'fast'}\n showsHorizontalScrollIndicator={false}\n renderItem={({item, index}) => {\n return (\n <View\n style={{\n width: SCREEN_WIDTH,\n backgroundColor: index === 1 ? 'red' : 'yellow',\n }}></View>\n );\n }}\n />\n" }, { "answer_id": 74473940, "author": "Muhammad Numan", "author_id": 8079868, "author_profile": "https://Stackoverflow.com/users/8079868", "pm_score": 2, "selected": true, "text": "import React from 'react';\nimport { StyleSheet, View, Text } from 'react-native';\nimport PagerView from 'react-native-pager-view';\n\nconst MyPager = () => {\n return (\n <PagerView style={styles.pagerView} initialPage={0}>\n <View key=\"1\" style={styles.page}>\n <Text>First page</Text>\n </View>\n <View key=\"2\" style={styles.page}>\n <Text>Second page</Text>\n </View>\n </PagerView>\n );\n};\n\nconst styles = StyleSheet.create({\n pagerView: {\n flex: 1,\n },\n page: {\n flex: 1,\n },\n});\n" }, { "answer_id": 74480819, "author": "Xhirazi", "author_id": 6890414, "author_profile": "https://Stackoverflow.com/users/6890414", "pm_score": 0, "selected": false, "text": "snapToInterval" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74423910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239879/" ]
74,423,941
<p>I deployed NGinx, php-fpm and php 8 on a EC2 / Linux 2 instance (T4g / ARM) to run a php application. As I had done for the previous version of this application and php 7.</p> <p>It runs well, excepted for all first requests. Whatever the actions (clicking a button, submitted a text, etc.), the first request always takes 2.2x minutes, then the following ones run quickly. The browsers (Firefox and Chrome) are just waiting for the response, then react normally.</p> <p>I see nothing from the logs (especially, the slow-log is empty) and the caches seem to work well.</p> <p>I guess I missed a configuration point. Based on my readings, I tried a lot of things about the configuration of php-fpm and php, but unsuccessfully.</p> <p>Is someone already encountered this kind of issue?</p> <p>Thanks in advance</p> <p>Fred</p> <ul> <li>Activation of all logs for php-fpm and php,</li> <li>Augmentation of the memory for the process,</li> <li>Checking of the system parameters (nlimit, etc.),</li> <li>etc.</li> </ul>
[ { "answer_id": 74425072, "author": "symcbean", "author_id": 223992, "author_profile": "https://Stackoverflow.com/users/223992", "pm_score": 1, "selected": false, "text": "$upstream_response_time" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74423941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7863847/" ]
74,423,945
<p>I have a material ui design of a input type=&quot;file&quot;. How to validate the file and display the error message?</p> <p>App.js</p> <pre><code>import React from &quot;react&quot;; import {useForm } from &quot;react-hook-form&quot;; import Button from &quot;@mui/material/Button&quot;; import { MuiFileInput } from &quot;mui-file-input&quot;; export default function App() { const { register, handleSubmit, formState: { errors },} = useForm(); const [file, setFile] = React.useState(null); const handleFile = (event) =&gt; { setFile(event); }; const onSubmit = (data) =&gt; { alert(JSON.stringify(data.file?.name)); }; return ( &lt;form onSubmit={handleSubmit(onSubmit)}&gt; &lt;MuiFileInput sx={{ margin: 2 }} {...register(&quot;uploadFile&quot;, {required: &quot;Please select an image.&quot;}, )} onChange= {handleFile} value={file} label=&quot;Upload Image&quot; placeholder='Select a file' error={Boolean(errors.uploadFile)} helperText={errors.uploadFile?.message} /&gt; &lt;Button type=&quot;submit&quot; variant=&quot;contained&quot; sx={{ margin: 2 }}&gt;Submit&lt;/Button&gt; &lt;/form&gt; ) } </code></pre> <p>The error is displayed even after the file is selected</p> <p><a href="https://i.stack.imgur.com/xPUxD.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xPUxD.jpg" alt="enter image description here" /></a></p> <p>How to eliminate this error after file selection?</p>
[ { "answer_id": 74425072, "author": "symcbean", "author_id": 223992, "author_profile": "https://Stackoverflow.com/users/223992", "pm_score": 1, "selected": false, "text": "$upstream_response_time" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74423945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11766145/" ]
74,423,948
<p>Having this vector:</p> <pre><code>vector &lt;- c(&quot;236&quot;, &quot;234&quot;, &quot;&quot;, &quot;12&quot;, &quot;24&quot;, &quot;3&quot;) [1] &quot;236&quot; &quot;234&quot; &quot;&quot; &quot;12&quot; &quot;24&quot; &quot;3&quot; </code></pre> <p>I would like to check how many consecutive numbers there are in each element.</p> <p>Expected output:</p> <pre><code>2 3 0 2 0 0 </code></pre> <p>I have no idea how to do this!</p>
[ { "answer_id": 74424134, "author": "Waldi", "author_id": 13513328, "author_profile": "https://Stackoverflow.com/users/13513328", "pm_score": 4, "selected": true, "text": "sapply(strsplit(vector,\"\"),\n function(x) {s <- sum(diff(as.numeric(x))==1); \n if (s) {s+1} else 0})\n\n[1] 2 3 0 2 0 0\n" }, { "answer_id": 74424137, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 2, "selected": false, "text": "vector <- c(\"236\", \"234\", \"\", \"12\", \"24\", \"3\")\n\nsapply(strsplit(vector, \"\"), function(x) {\n r <- rle(diff(as.numeric(x) - seq(length(x))))\n if(0 %in% r$values) max(r$lengths[r$values == 0]) + 1 else 0\n})\n#> [1] 2 3 0 2 0 0\n" }, { "answer_id": 74425467, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 1, "selected": false, "text": "library(matrixStats)\nv1 <- rowSums(rowDiffs(as.matrix(read.fwf(textConnection(paste(vector,\n collapse = \"\\n\")), widths = rep(1, 3)))) == 1, na.rm = TRUE)\nreplace(v1, v1 != 0, v1[v1!=0] + 1)\n[1] 2 3 0 2 0 0\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74423948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13321647/" ]
74,423,972
<p>I have a dictionary that looks like this:</p> <pre><code>dict = {id: [&quot;gavin&quot;, &quot;gavin123@email.com&quot;, age, 55, [111, 222, 333]]} </code></pre> <p>There are more keys but that's not important. I want to be able to change the age value to be a number instead of <strong>age</strong> so the new dictionary would look like this</p> <pre><code>dict = {id: [&quot;gavin&quot;, &quot;gavin123@email.com&quot;, 20, 55, [111, 222, 222]]} </code></pre> <p>It is the 3rd value of the &quot;id&quot; key.</p> <p>I tried using the append() function but it just added a value at the end.</p> <pre><code>d[&quot;id&quot;].append(20) print(d) </code></pre> <p>The output just looks like this:</p> <pre><code>dict = {id: name, email, age, height, [value1, value2, value3], 20} </code></pre>
[ { "answer_id": 74424210, "author": "Brijesh Varsani", "author_id": 14525381, "author_profile": "https://Stackoverflow.com/users/14525381", "pm_score": 1, "selected": false, "text": "dict[id][2] = 20\n" }, { "answer_id": 74441207, "author": "Woody1193", "author_id": 3121975, "author_profile": "https://Stackoverflow.com/users/3121975", "pm_score": 0, "selected": false, "text": "class User:\n\n def __init__(self, name, email, age, height, values):\n self.name = name\n self.email = email\n self.age = age\n self.height = height\n self.values = values\n\ndict = {id: User(\"gavin\", \"gavin123@email.com\", 20, 55, [111, 222, 222])}\ndict[\"id\"].age = 20\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74423972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20494854/" ]
74,424,016
<p>I have a html table that I would like to make interactive, sorting, filtering etc. I watched this great <a href="https://www.youtube.com/watch?v=A20PY5RxdI8" rel="nofollow noreferrer">tutorial</a> &amp; thought I would try replicating it. However nothing happens what so ever, I am not sure what I am missing? My code is below.</p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;css/bootstrap.min.css&quot;&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;css/bootstrap-table.min.css&quot;&gt; &lt;/head&gt; &lt;body&gt; &lt;div class=&quot;container&quot;&gt; &lt;table class=&quot;table table-bordered table-hover&quot; data=toggle=&quot;table&quot; data-search=&quot;true&quot; data-show-columns=&quot;true&quot;&gt; &lt;thead&gt; &lt;tr&gt; &lt;th scope='col'&gt;Column 1&lt;/th&gt; &lt;th scope='col'&gt;Column 2&lt;/th&gt; &lt;th scope='col'&gt;Column 3&lt;/th&gt; &lt;th scope='col'&gt;Column 4&lt;/th&gt; &lt;th scope='col'&gt;Column 5&lt;/th&gt; &lt;th scope='col'&gt;Column 6&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;Conf&lt;/td&gt; &lt;td&gt;even 20 trail A&lt;/td&gt; &lt;td&gt;True&lt;/td&gt; &lt;td&gt;False&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;True&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Conf&lt;/td&gt; &lt;td&gt;even 20 trail B&lt;/td&gt; &lt;td&gt;True&lt;/td&gt; &lt;td&gt;False&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;True&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;script src=&quot;js/jQuery-3.1.1.min.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;js/bootstrap.min.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;js/bootstrap-table.js&quot;&gt;&lt;/script&gt; &lt;script&gt; $(document).ready(function(){ $('table').bootstrapTable(); }); &lt;/script&gt; </code></pre>
[ { "answer_id": 74424210, "author": "Brijesh Varsani", "author_id": 14525381, "author_profile": "https://Stackoverflow.com/users/14525381", "pm_score": 1, "selected": false, "text": "dict[id][2] = 20\n" }, { "answer_id": 74441207, "author": "Woody1193", "author_id": 3121975, "author_profile": "https://Stackoverflow.com/users/3121975", "pm_score": 0, "selected": false, "text": "class User:\n\n def __init__(self, name, email, age, height, values):\n self.name = name\n self.email = email\n self.age = age\n self.height = height\n self.values = values\n\ndict = {id: User(\"gavin\", \"gavin123@email.com\", 20, 55, [111, 222, 222])}\ndict[\"id\"].age = 20\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2730554/" ]
74,424,048
<p>I'm trying to make a video out of 4 still images with ffmpeg.</p> <p>This is the command I am having trouble with getting working at the moment:</p> <pre><code>ffmpeg -y -loop 1 -framerate 24 -t 3 \ -i ./images/title-card.png -loop 1 -framerate 24 -t 4 \ -i ./images/001.png -loop 1 -framerate 24 -t 4 \ -i ./images/002.png -loop 1 -framerate 24 -t 3 \ -i ./images/003.png -loop 1 -framerate 24 -t 4 \ -filter_complex &quot;[0][1][2][3]concat=n=4:v=1:a=0&quot; \ /tmp/silentVideoTest.mp4 </code></pre> <p>Unfortunately, I get this error:</p> <pre><code>[Parsed_concat_0 @ 0x5603df1c4080] Input link in1:v0 parameters (size 1024x1024, SAR 0:1) do not match the corresponding output link in0:v0 parameters (1024x1024, SAR 3937:3937) [Parsed_concat_0 @ 0x5603df1c4080] Failed to configure output pad on Parsed_concat_0 Error reinitializing filters! Failed to inject frame into filter network: Invalid argument Error while processing the decoded data for stream #3:0 </code></pre> <p>I have no idea what this error means. But if I use a different png for the first image, it works fine. I understand that there is something about the first png that ffmpeg does not like; the SAR, which I believe is some kind of png metadata bit or something?</p> <p>Problem is:</p> <ul> <li>The error is confusing to me</li> <li>I see no option to set the SAR when exporting images from Krita, Pinta, or Photopea.</li> <li>I do not know how to view the SAR value of an image, so I can't verify that this is really the problem</li> </ul> <p>Also, whats more is, I've used this command in the past to change an image's SAR (I think) but it seems to only work half the time?</p> <pre><code>ffmpeg -i title-card.png -vf setsar=1 title-card-new-sar.png </code></pre> <p>No idea what the value of setsar should be, so I am using 1.</p> <p>Would love if someone could tell me how to get it to work. In particular, how do I view the SAR of a PNG file?</p> <p>Maybe I am naieve, but shouldn't ffmpeg just be able to accept png images that are the same dimensions, compression, and stitch em together without errors? i.e. Is there an option just to say &quot;Fix the SAR?&quot; or &quot;Use the SAR of the first image for all images?&quot;</p> <hr /> <p>Edit: Trying it on some different images, having set the SAR with <code>ffmpeg -i ./card.png -vf setsar=1 ./card-new-sar.png</code>, I get a similar error:</p> <pre><code>[Parsed_concat_0 @ 0x55e7b6b8b640] Input link in2:v0 parameters (size 1024x1024, SAR 2834:2834) do not match the corresponding output link in0:v0 parameters (1024x1024, SAR 1:1) [Parsed_concat_0 @ 0x55e7b6b8b640] Failed to configure output pad on Parsed_concat_0 Error reinitializing filters! Failed to inject frame into filter network: Invalid argument Error while processing the decoded data for stream #26:0 </code></pre> <p>ffmpeg still seems to complain that the SARs don't match...but surely, as its a ratio, a SAR of <code>2834:2834</code> <em>does</em> match a SAR of <code>1:1</code>?</p> <hr /> <p>Edit: Tried setting the SAR with <code>ffmpeg -i ./card.png -vf setsar=2834:2834 ./card-new-sar.png</code>, but now the error is <code>(size 1024x1024, SAR 0:1) do not match the corresponding output link in0:v0 parameters (1024x1024, SAR 2834:2834)</code>.</p>
[ { "answer_id": 74424395, "author": "kesh", "author_id": 4516027, "author_profile": "https://Stackoverflow.com/users/4516027", "pm_score": 1, "selected": false, "text": "setsar" }, { "answer_id": 74424439, "author": "kohloth", "author_id": 1829990, "author_profile": "https://Stackoverflow.com/users/1829990", "pm_score": 0, "selected": false, "text": "ffmpeg" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1829990/" ]
74,424,049
<p>I want to write a script such that if the value is less than ...then color is red, if value = ...then color is yellow and if the value is greater than ...then color is dark magenta. I am just experimenting with powershell.</p> <p>I am a Data Science student, don't know any powershell scripting, just want to have some fun.</p>
[ { "answer_id": 74424395, "author": "kesh", "author_id": 4516027, "author_profile": "https://Stackoverflow.com/users/4516027", "pm_score": 1, "selected": false, "text": "setsar" }, { "answer_id": 74424439, "author": "kohloth", "author_id": 1829990, "author_profile": "https://Stackoverflow.com/users/1829990", "pm_score": 0, "selected": false, "text": "ffmpeg" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20379772/" ]
74,424,072
<p>I've read up on Readers-writer lock on wiki - <a href="https://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock</a> but tried using only one counter and one lock.</p> <p>I'm curious to know whether this implementation is valid. If yes, do you think this would be enough for a technical interview.</p> <pre><code> read() { lock g; while (num_of_writers &gt; 0) { g.wait(); // always yield to writers } doRead(); unlock g; } write() { lock g; numOfWriters++; // let all the writers to queue up here unlock g; lock g; doWrite(); num_of_writers--; g.notify(); unlock g; } </code></pre>
[ { "answer_id": 74424518, "author": "Dan Bonachea", "author_id": 3528321, "author_profile": "https://Stackoverflow.com/users/3528321", "pm_score": 3, "selected": true, "text": "doWrite()" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1745356/" ]
74,424,158
<p>I have a very easy question but somehow I'm having trouble with it...</p> <p>I'm creating an 81x41 string 2d-array with numpy. I then iterate through all positions of this array and want to put a certain string inside each position.</p> <p>For some reason, it doesn't assign the variable to the position. It remains empty.</p> <p>How can I do this simple value assignment? What am I missing?</p> <p>My code:</p> <pre class="lang-py prettyprint-override"><code>def create_discrete_values(self, threshold: list[int]): self.map_index_discreet = np.ndarray(shape=(81, 41), dtype=str) for i in range(81): for j in range(41): val = self.map_index[i][j] discreet_value = None if val &lt;= threshold[0]: discreet_value = &quot;Very Low&quot; elif val &lt;= threshold[1]: discreet_value = &quot;Low&quot; elif val &lt;= threshold[2]: discreet_value = &quot;Moderate&quot; elif val &lt;= threshold[3]: discreet_value = &quot;High&quot; elif val &lt;= threshold[4]: discreet_value = &quot;Very High&quot; elif val &lt;= threshold[5]: discreet_value = &quot;Extreme&quot; else: discreet_value = &quot;Very Extreme&quot; self.map_index_discreet[i][j] = discreet_value </code></pre>
[ { "answer_id": 74424518, "author": "Dan Bonachea", "author_id": 3528321, "author_profile": "https://Stackoverflow.com/users/3528321", "pm_score": 3, "selected": true, "text": "doWrite()" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11285228/" ]
74,424,178
<p>I created a table in PGSQL (version 13) using the following command:</p> <pre><code>db1=# create table temp2( foo int PRIMARY KEY, bar varchar(20) UNIQUE NOT NULL ); CREATE TABLE </code></pre> <p>The <code>\d</code> or <code>d+</code> command does not list the associated indexes for the table (contrary to what I gathered from reading various sites.)</p> <pre><code>db1=# \d temp2 foo | integer | | not null | bar | character varying(20) | | not null | db1=# \d+ temp2 foo | integer | | not null | | plain | | bar | character varying(20) | | not null | | extended | | </code></pre> <p>Is there a way I get list indexes associated with a table?</p> <p>Thank you, Ahmed.</p>
[ { "answer_id": 74424697, "author": "Adrian Klaver", "author_id": 7070613, "author_profile": "https://Stackoverflow.com/users/7070613", "pm_score": 3, "selected": true, "text": "tuples_only" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1348939/" ]
74,424,201
<p>I have a list of Strings that looks like that:</p> <pre><code>['training_tech26.txt', 'training_tech41.txt', 'training_tech68.txt', 'training_tech84.txt', 'training_tech52.txt', 'training_sales17.txt', 'training_sales2.txt', 'training_tech47.txt', 'training_sales23.txt', 'training_sales3.txt', 'training_tech9.txt', 'training_tech12.txt'] </code></pre> <p>I need to sort these files to be in a right order, like:</p> <pre><code>['training_tech1.txt', 'training_tech2.txt', 'training_sales3.txt', 'training_tech4.txt', 'training_tech5.txt'] </code></pre> <p>I am using these code to access all files inside my folder and append them into one list. In the folder itself they are placed in a right order, so I don't know why there are messed up in this list.</p> <pre><code>tech_dir_path = &quot;/path/to/folder/with/files&quot; res = [] tech_res = os.listdir(tech_dir_path) </code></pre>
[ { "answer_id": 74424304, "author": "The Myth", "author_id": 15042008, "author_profile": "https://Stackoverflow.com/users/15042008", "pm_score": 0, "selected": false, "text": "input = ['training_tech26.txt', 'training_tech41.txt', 'training_tech68.txt', 'training_tech84.txt', 'training_tech52.txt', 'training_sales17.txt', 'training_sales2.txt', 'training_tech47.txt', 'training_sales23.txt', 'training_sales3.txt', 'training_tech9.txt', 'training_tech12.txt']\n\ndef sorter(input):\n idx = [int(''.join([j for j in i if j.isdigit()])) for i in input] # gets the numbers in int\n idx.sort() # sort numbers\n res = []\n for i in idx: # iterate over idx\n for j in input: # iterate over input\n if i == int(''.join([k for k in j if k.isdigit()])): # checks if i is same as the j input\n res.append(j)\n return res\nprint(sorter(input))\n" }, { "answer_id": 74424405, "author": "Oghli", "author_id": 5169186, "author_profile": "https://Stackoverflow.com/users/5169186", "pm_score": 2, "selected": true, "text": "natsort" }, { "answer_id": 74424440, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 0, "selected": false, "text": "key" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18598837/" ]
74,424,229
<p>When i try to run &quot;docker-compose up&quot;. It is working. But when i try to run &quot;docker run denexbackend_denex-service&quot;. I am getting mongo connection timeout error.</p> <p><em><a href="https://github.com/mwlt68/Denex.BackEnd" rel="nofollow noreferrer">Denex.Backend</a> is open source project.</em></p> <p><strong>appsettings.json</strong></p> <pre><code> &quot;MongoDbSettings&quot;: { &quot;ConnectionString&quot;: &quot;mongodb://mongodb-service:27017&quot;, &quot;Database&quot;: &quot;DenexDB&quot; }, </code></pre> <p><strong>docker-compose.yml</strong></p> <pre><code>version: '3.8' services: denex-service: container_name: denex image: mevlutgur/denex.backend:latest build: . ports: - 3003:80 mongodb-service: image: mongo ports: - 27018:27017 volumes: - denex-data:/data/db volumes: denex-data: </code></pre> <p><strong>docker-compose.yml</strong> (After trying some solutions)</p> <pre><code>version: '3.8' services: mongodb-service: image: mongo ports: - 27018:27017 volumes: - denex-data:/data/db networks: - samplenetwork denex-service: container_name: denex-backend build: . ports: - 3003:80 depends_on: - mongodb-service networks: - samplenetwork volumes: denex-data: networks: samplenetwork: driver: bridge </code></pre> <p><strong>dockerfile</strong></p> <pre><code>FROM mcr.microsoft.com/dotnet/sdk:6.0-jammy AS build WORKDIR /app # copy csproj and restore as distinct layers COPY *.sln . COPY src/WebApi/Denex.WebApi/Denex.WebApi.csproj ./src/WebApi/Denex.WebApi/ COPY src/Core/Denex.Domain/Denex.Domain.csproj ./src/Core/Denex.Domain/ COPY src/Core/Denex.Application/Denex.Application.csproj ./src/Core/Denex.Application/ COPY src/Infrastructure/Denex.Persistance/Denex.Persistance.csproj ./src/Infrastructure/Denex.Persistance/ COPY tests/WebApi.UnitTest/WebApi.UnitTest.csproj ./tests/WebApi.UnitTest/ RUN dotnet restore # copy everything else and build app COPY src/WebApi/Denex.WebApi/. ./src/WebApi/Denex.WebApi/ COPY src/Core/Denex.Domain/. ./src/Core/Denex.Domain/ COPY src/Core/Denex.Application/. ./src/Core/Denex.Application/ COPY src/Infrastructure/Denex.Persistance/. ./src/Infrastructure/Denex.Persistance/ COPY tests/WebApi.UnitTest/. ./tests/WebApi.UnitTest/ WORKDIR /app/src/WebApi/Denex.WebApi RUN dotnet publish -c Release -o out WORKDIR /app/tests/WebApi.UnitTest RUN dotnet test --verbosity quiet # build runtime image FROM mcr.microsoft.com/dotnet/aspnet:6.0-jammy AS runtime WORKDIR /app COPY --from=build /app/src/WebApi/Denex.WebApi/out ./ EXPOSE 80 ENTRYPOINT [&quot;dotnet&quot;, &quot;Denex.WebApi.dll&quot;] </code></pre> <p><strong>Error message</strong></p> <pre><code>Unhandled exception. System.TimeoutException: A timeout occurred after 30000ms selecting a server using CompositeServerSelector{ Selectors = MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 }, OperationsCountServerSelector }. Client view of cluster state is { ClusterId : &quot;1&quot;, Type : &quot;Unknown&quot;, State : &quot;Disconnected&quot;, Servers : [{ ServerId: &quot;{ ClusterId : 1, EndPoint : &quot;Unspecified/mongodb-service:27017&quot; }&quot;, EndPoint: &quot;Unspecified/mongodb-service:27017&quot;, ReasonChanged: &quot;Heartbeat&quot;, State: &quot;Disconnected&quot;, ServerVersion: , TopologyVersion: , Type: &quot;Unknown&quot;, HeartbeatException: &quot;MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server. ---&gt; System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (00000005, 0xFFFDFFFF): Name or service not known at System.Net.Dns.GetHostEntryOrAddressesCore(String hostName, Boolean justAddresses, AddressFamily addressFamily, ValueStopwatch stopwatch) at System.Net.Dns.GetHostAddresses(String hostNameOrAddress, AddressFamily family) at MongoDB.Driver.Core.Connections.TcpStreamFactory.ResolveEndPoints(EndPoint initial) at MongoDB.Driver.Core.Connections.TcpStreamFactory.CreateStream(EndPoint endPoint, CancellationToken cancellationToken) at MongoDB.Driver.Core.Connections.BinaryConnection.OpenHelper(CancellationToken cancellationToken) --- End of inner exception stack trace --- at MongoDB.Driver.Core.Connections.BinaryConnection.OpenHelper(CancellationToken cancellationToken) at MongoDB.Driver.Core.Connections.BinaryConnection.Open(CancellationToken cancellationToken) at MongoDB.Driver.Core.Servers.ServerMonitor.InitializeConnection(CancellationToken cancellationToken) at MongoDB.Driver.Core.Servers.ServerMonitor.Heartbeat(CancellationToken cancellationToken)&quot;, LastHeartbeatTimestamp: &quot;2022-11-13T19:16:54.6844686Z&quot;, LastUpdateTimestamp: &quot;2022-11-13T19:16:54.6844692Z&quot; }] }. at MongoDB.Driver.Core.Clusters.Cluster.ThrowTimeoutException(IServerSelector selector, ClusterDescription description) at MongoDB.Driver.Core.Clusters.Cluster.WaitForDescriptionChangedHelper.HandleCompletedTask(Task completedTask) at MongoDB.Driver.Core.Clusters.Cluster.WaitForDescriptionChanged(IServerSelector selector, ClusterDescription description, Task descriptionChangedTask, TimeSpan timeout, CancellationToken cancellationToken) at MongoDB.Driver.Core.Clusters.Cluster.SelectServer(IServerSelector selector, CancellationToken cancellationToken) at MongoDB.Driver.MongoClient.AreSessionsSupportedAfterServerSelection(CancellationToken cancellationToken) at MongoDB.Driver.MongoClient.AreSessionsSupported(CancellationToken cancellationToken) at MongoDB.Driver.MongoClient.StartImplicitSession(CancellationToken cancellationToken) at MongoDB.Driver.OperationExecutor.StartImplicitSession(CancellationToken cancellationToken) at MongoDB.Driver.MongoDatabaseImpl.UsingImplicitSession[TResult](Func`2 func, CancellationToken cancellationToken) at MongoDB.Driver.MongoDatabaseImpl.ListCollectionNames(ListCollectionNamesOptions options, CancellationToken cancellationToken) at Denex.Persistance.Extensions.MongoImportExtension.AddMongoImport(IConfiguration configuration) in /app/src/Infrastructure/Denex.Persistance/Extensions/MongoImportExtension.cs:line 19 at Program.&lt;Main&gt;$(String[] args) in /app/src/WebApi/Denex.WebApi/Program.cs:line 24 </code></pre>
[ { "answer_id": 74424304, "author": "The Myth", "author_id": 15042008, "author_profile": "https://Stackoverflow.com/users/15042008", "pm_score": 0, "selected": false, "text": "input = ['training_tech26.txt', 'training_tech41.txt', 'training_tech68.txt', 'training_tech84.txt', 'training_tech52.txt', 'training_sales17.txt', 'training_sales2.txt', 'training_tech47.txt', 'training_sales23.txt', 'training_sales3.txt', 'training_tech9.txt', 'training_tech12.txt']\n\ndef sorter(input):\n idx = [int(''.join([j for j in i if j.isdigit()])) for i in input] # gets the numbers in int\n idx.sort() # sort numbers\n res = []\n for i in idx: # iterate over idx\n for j in input: # iterate over input\n if i == int(''.join([k for k in j if k.isdigit()])): # checks if i is same as the j input\n res.append(j)\n return res\nprint(sorter(input))\n" }, { "answer_id": 74424405, "author": "Oghli", "author_id": 5169186, "author_profile": "https://Stackoverflow.com/users/5169186", "pm_score": 2, "selected": true, "text": "natsort" }, { "answer_id": 74424440, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 0, "selected": false, "text": "key" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12603069/" ]
74,424,288
<p>I use WTelgramClient to remind patients about an upcoming doctor's appointment.</p> <p>I am sending a message and I need to make sure that it is read.</p> <pre><code>using var client = new WTelegram.Client(Config); var user = await client.LoginUserIfNeeded(); var contact = await client.Contacts_ImportContacts(new[] { new InputPhoneContact { phone = phoneNumber } }); object p = await client.SendMessageAsync(contact.users[contact.users.Keys.First()], patientMessage); </code></pre> <p>It seems that this can be done via <code>flag</code> <code>has_views</code>. I tried the code below, but I can't call <code>dialogs.messages[0].flag.has_views</code>.</p> <pre><code>var dialogs = await client.Messages_GetAllDialogs(); Console.WriteLine(dialogs.messages[0]); </code></pre>
[ { "answer_id": 74424304, "author": "The Myth", "author_id": 15042008, "author_profile": "https://Stackoverflow.com/users/15042008", "pm_score": 0, "selected": false, "text": "input = ['training_tech26.txt', 'training_tech41.txt', 'training_tech68.txt', 'training_tech84.txt', 'training_tech52.txt', 'training_sales17.txt', 'training_sales2.txt', 'training_tech47.txt', 'training_sales23.txt', 'training_sales3.txt', 'training_tech9.txt', 'training_tech12.txt']\n\ndef sorter(input):\n idx = [int(''.join([j for j in i if j.isdigit()])) for i in input] # gets the numbers in int\n idx.sort() # sort numbers\n res = []\n for i in idx: # iterate over idx\n for j in input: # iterate over input\n if i == int(''.join([k for k in j if k.isdigit()])): # checks if i is same as the j input\n res.append(j)\n return res\nprint(sorter(input))\n" }, { "answer_id": 74424405, "author": "Oghli", "author_id": 5169186, "author_profile": "https://Stackoverflow.com/users/5169186", "pm_score": 2, "selected": true, "text": "natsort" }, { "answer_id": 74424440, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 0, "selected": false, "text": "key" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20479693/" ]
74,424,292
<p>Is there any way to make the SetPosition of a LineRenderer smoother. I'm making a 2D game, and I'm making a chameleon tongue, where it pops out of the mouth to a point and then comes back, but this makes the animation very fast, is there any way to make it slower and smoother?</p> <p>My question is is there a way to smooth the setposition of a linerenderer? As I have in my script.</p> <pre><code>EdgeCollider2D edgeCollider; LineRenderer myLine; public Transform pointOne; public Transform pointfinalZero; public Transform pointfinal; public bool isTongue; void Start() { edgeCollider = this.GetComponent&lt;EdgeCollider2D&gt;(); myLine = this.GetComponent&lt;LineRenderer&gt;(); } void Update() { SetEdgeCollider(myLine); myLine.SetPosition(0, pointOne.position); if(isTongue) { myLine.SetPosition(1, pointfinal.position); } if(!isTongue) { myLine.SetPosition(1, pointfinalZero.position); } } void SetEdgeCollider(LineRenderer lineRenderer) { List&lt;Vector2&gt; edges = new List&lt;Vector2&gt;(); for(int point = 0; point&lt;lineRenderer.positionCount; point++) { Vector3 lineRendererPoint = lineRenderer.GetPosition(point); edges.Add(new Vector2(lineRendererPoint.x, lineRendererPoint.y)); } edgeCollider.SetPoints(edges); } </code></pre> <p>It's working fine, but I wanted to make it smoother to see the tongue stick out.</p>
[ { "answer_id": 74424304, "author": "The Myth", "author_id": 15042008, "author_profile": "https://Stackoverflow.com/users/15042008", "pm_score": 0, "selected": false, "text": "input = ['training_tech26.txt', 'training_tech41.txt', 'training_tech68.txt', 'training_tech84.txt', 'training_tech52.txt', 'training_sales17.txt', 'training_sales2.txt', 'training_tech47.txt', 'training_sales23.txt', 'training_sales3.txt', 'training_tech9.txt', 'training_tech12.txt']\n\ndef sorter(input):\n idx = [int(''.join([j for j in i if j.isdigit()])) for i in input] # gets the numbers in int\n idx.sort() # sort numbers\n res = []\n for i in idx: # iterate over idx\n for j in input: # iterate over input\n if i == int(''.join([k for k in j if k.isdigit()])): # checks if i is same as the j input\n res.append(j)\n return res\nprint(sorter(input))\n" }, { "answer_id": 74424405, "author": "Oghli", "author_id": 5169186, "author_profile": "https://Stackoverflow.com/users/5169186", "pm_score": 2, "selected": true, "text": "natsort" }, { "answer_id": 74424440, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 0, "selected": false, "text": "key" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19971812/" ]
74,424,298
<p>I have to make a C shell interpreter that can handle multiple ' | ' operators. So if I write something like this: <code>cat test.txt | sort | uniq -c | sort -nr</code> it works correctly. The problem comes when I try to use more complex functions, for example: <code>cat test.txt | awk '/&quot; 404 / {print%7}' | sort | uniq -c | sort -nr | head</code>. It breaks when 'awk' parameters are separated by strtok.</p> <p>The code that works:</p> <pre><code>#define TRUE 1 #define FALSE 0 #define BUF_SIZE 1024 #define ROW_SIZE 64 #define MIN 100000 void failed_allocation(){ fprintf(stderr, &quot;Faild to allocate memory.&quot;); exit(EXIT_FAILURE); } char* read_line(){ int buf_size = BUF_SIZE; int pos = 0; char* buffer = malloc(sizeof(char) * buf_size); int c; // using int because EOF is -1 if(buffer == NULL) failed_allocation(); // read char by char while(TRUE){ c = getchar(); // look for EOF or end of line if(c == EOF || c == '\n'){ buffer[pos] = '\0'; return buffer; } else{ buffer[pos] = c; } pos++; // if buffer max size is reached, then extend buffer if(pos &gt;= buf_size){ buf_size += BUF_SIZE; buffer = realloc(buffer, buf_size); if(buffer == NULL) failed_allocation(); } } } char** split_to_lines(char* str, char* delim){ int buf_size = ROW_SIZE; int pos = 0; char* buffer; char** buffer_list = malloc(buf_size * sizeof(char*)); if(buffer_list == NULL) failed_allocation(); // split into list buffer = strtok(str, delim); while(buffer != NULL){ buffer_list[pos] = buffer; pos++; // if buffer max size is reached, then extend buffer if(pos &gt;= buf_size){ buf_size += ROW_SIZE; buffer_list = realloc(buffer_list, buf_size * sizeof(char*)); if(buffer_list != NULL) failed_allocation(); } buffer = strtok(NULL, delim); // continue reading str } buffer_list[pos] = NULL; // end list return buffer_list; } int start_proc(char** args){ int fd[2]; int prev_fd = STDIN_FILENO; int i; char** list = NULL; for(i = 0; args[i + 1] != NULL; ++i){ if(pipe(fd) == -1){ perror(&quot;Pipe error: &quot;); return 1; } int pid = fork(); if(pid &lt; 0){ perror(&quot;Fork error:&quot;); return 1; } else if(pid == 0){ if(prev_fd != STDIN_FILENO){ dup2(prev_fd, STDIN_FILENO); close(prev_fd); } dup2(fd[1], STDOUT_FILENO); close(fd[1]); list = split_to_lines(args[i], &quot; \t\r\n&quot;); execvp(list[0], list); perror(&quot;Execvp error:&quot;); exit(EXIT_FAILURE); } close(prev_fd); close(fd[1]); prev_fd = fd[0]; free(list); } if(prev_fd != STDIN_FILENO){ dup2(prev_fd, STDIN_FILENO); close(prev_fd); } list = split_to_lines(args[i], &quot; \t\r\n&quot;); execvp(list[0], list); perror(&quot;Execvp error:&quot;); } int main(){ int flag = TRUE; while(flag == TRUE){ // input printf(&quot;\n&gt; &quot;); char* input = read_line(); char** list = NULL; // exit condition if(strcmp(input, &quot;exit&quot;) == 0) flag = FALSE; if(flag == TRUE){ list = split_to_lines(input, &quot;|&quot;); start_proc(list); } // free memory free(input); free(list); } return 0; } </code></pre> <p>I tried implementing my own way of separating strings, but in no vain as when trying to execute the code, it randomly creates empty space strings and then tries to execute them resulting in execvp errors.</p> <p>This is the implementation that I tried:</p> <pre><code>int get_length(char* str){ int counter = 0; for(int i = 0; str[i] != '\0'; ++i){ ++counter; } return counter; } int find_in_string(char* str, char look_for, int from){ int length = get_length(str); if(from &gt; length) return -1; for(int i = from; i &lt; length; ++i){ if(str[i] == look_for){ return i; } } return -1; } char* substr(char* str, int begin, int end){ int length = get_length(str); if(end &gt; length || begin &gt; length){ fprintf(stderr, &quot;Substr error: invalid interval values.&quot;); exit(EXIT_FAILURE); } if(end &lt; 0) end = length; else if(begin &lt; 0) begin = 0; char* buffer = malloc((end - begin) * sizeof(char)); int pos = 0; for(int i = begin; i &lt;= end; ++i){ buffer[pos] = str[i]; pos++; } buffer[pos] = '\0'; return buffer; } char** test_split_to_lines(char* str, char* delim){ char* buffer; char** buffer_list = malloc(ROW_SIZE * sizeof(char*)); int pos = 0; int cursor_pos = 0; int cursor_delim = 0; int length = get_length(str); loop: int delim_pos = MIN; for(int i = 0; delim[i] != '\0'; ++i){ int temp = find_in_string(str, delim[i], cursor_delim); if((temp &lt; delim_pos &amp;&amp; temp &gt; 0) || (temp &lt; 0 &amp;&amp; delim_pos == MIN) || (delim_pos &lt; 0 &amp;&amp; temp &gt; -1)) delim_pos = temp; } if(delim_pos == -1){ buffer = substr(str, cursor_pos, -1); if(get_length(buffer) != 0){ buffer_list[pos] = buffer; pos++; } buffer_list[pos] = NULL; return buffer_list; } int q_begin = find_in_string(str, 39, cursor_pos); int q_end = find_in_string(str, 39, q_begin + 1); if(delim_pos &lt; q_begin || delim_pos &gt; q_end){ buffer = substr(str, cursor_pos, delim_pos - 1); buffer_list[pos] = buffer; pos++; cursor_pos = delim_pos + 1; cursor_delim = cursor_pos; } else{ cursor_delim = q_end; } goto loop; } </code></pre> <p>So, basically I need help writing a function, that correctly separates strings.</p>
[ { "answer_id": 74424492, "author": "0___________", "author_id": 6110094, "author_profile": "https://Stackoverflow.com/users/6110094", "pm_score": 0, "selected": false, "text": "argv == NULL" }, { "answer_id": 74424822, "author": "JohnScott", "author_id": 18498344, "author_profile": "https://Stackoverflow.com/users/18498344", "pm_score": -1, "selected": false, "text": "strtok" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9535098/" ]
74,424,306
<p>Trying setting up my SQLite data and populating from database to Lists database will return an <code>async Task&lt;List&lt;T&gt;&gt;</code> that holds values I need to assign to my collection list. I get error code CS1503 :</p> <pre><code>Using System.Collections.Generic; Using SQLite; public Task&lt;List&lt;Reward&gt;&gt; rewards; public List&lt;Reward&gt; rewardsList; RewardDatabase reward; private async void GetRewards() { rewards = reward.GetItemsAsync(); } async void AssignIt() { rewardsList = await rewards; } </code></pre> <p>I am trying to get values from <code>rewards</code> to a collection I can access from <code>rewardsList</code>.</p>
[ { "answer_id": 74424949, "author": "Jason", "author_id": 1338, "author_profile": "https://Stackoverflow.com/users/1338", "pm_score": 2, "selected": false, "text": "await" }, { "answer_id": 74427704, "author": "koishi", "author_id": 17993868, "author_profile": "https://Stackoverflow.com/users/17993868", "pm_score": -1, "selected": false, "text": "task.Result" }, { "answer_id": 74457931, "author": "Jianwei Sun - MSFT", "author_id": 19902734, "author_profile": "https://Stackoverflow.com/users/19902734", "pm_score": 0, "selected": false, "text": "GetItemsAsync()" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20495037/" ]
74,424,324
<p>I want to increment progress bar value every second, but every time I increment variable, value start incrementing faster then I defined.</p> <p>Here is an example:</p> <pre class="lang-kotlin prettyprint-override"><code>var progress by remember { mutableStateOf(0.00f) } val animatedProgress by animateFloatAsState( targetValue = progress, animationSpec = ProgressIndicatorDefaults.ProgressAnimationSpec ) val mainHandler = Handler(Looper.getMainLooper()) mainHandler.post(object : Runnable { override fun run() { progress += 0.01f println(progress) mainHandler.postDelayed(this, 1000) } }) LinearProgressIndicator(progress = animatedProgress) </code></pre> <p>I don't know what to do. I tried the same thing with normal float and it works.</p> <pre class="lang-kotlin prettyprint-override"><code>var i = 0.00f val mainHandler = Handler(Looper.getMainLooper()) mainHandler.post(object : Runnable { override fun run() { i += 0.01f println(i) mainHandler.postDelayed(this, 1000) } }) </code></pre>
[ { "answer_id": 74424707, "author": "Gabriele Mariotti", "author_id": 2016562, "author_profile": "https://Stackoverflow.com/users/2016562", "pm_score": 1, "selected": false, "text": "val state = remember { ProgressState() }\n\nDisposableEffect(Unit) {\n state.start()\n onDispose {\n state.stop()\n }\n}\n\nCircularProgressIndicator(progress = state.progress)\n" }, { "answer_id": 74432416, "author": "T HC", "author_id": 19070894, "author_profile": "https://Stackoverflow.com/users/19070894", "pm_score": 3, "selected": true, "text": "jetpack-compose" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18939913/" ]
74,424,343
<p>I have created this pandas dataframe:</p> <pre><code>import numpy as np import pandas as pd ds = {&quot;col1&quot;:[1,2,3,2,2,2,3,4,1,0,0,0,0,0,1,2,3,5]} df = pd.DataFrame(data=ds) </code></pre> <p>which looks like this:</p> <pre><code>print(df) col1 0 1 1 2 2 3 3 2 4 2 5 2 6 3 7 4 8 1 9 0 10 0 11 0 12 0 13 0 14 1 15 2 16 3 17 5 </code></pre> <p>I need to create a new column (<code>col2</code>) which contains the cumulative count of the values in <code>col1</code>. So, the resulting dataframe would look like this:</p> <p><a href="https://i.stack.imgur.com/SlQwX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SlQwX.png" alt="enter image description here" /></a></p> <p>Does anybody know how to do it, please?</p>
[ { "answer_id": 74424707, "author": "Gabriele Mariotti", "author_id": 2016562, "author_profile": "https://Stackoverflow.com/users/2016562", "pm_score": 1, "selected": false, "text": "val state = remember { ProgressState() }\n\nDisposableEffect(Unit) {\n state.start()\n onDispose {\n state.stop()\n }\n}\n\nCircularProgressIndicator(progress = state.progress)\n" }, { "answer_id": 74432416, "author": "T HC", "author_id": 19070894, "author_profile": "https://Stackoverflow.com/users/19070894", "pm_score": 3, "selected": true, "text": "jetpack-compose" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15439524/" ]
74,424,356
<p>I am trying to create a very large wordlist with each word in a separate line. I generate the words using some logic and storing them using StringBuilder. It appears in tests that I create some duplicated words e.g.</p> <pre><code>!AngryDogAngry1916! @AngryAngryDog1916! :AngryDog1916! !AngryDogAngry1916! ... </code></pre> <p>In the example the generated first and fourth lines and I would like to remove one of them. How to remove the duplicate line(s) from the StringBuilder variable? Line-wise consideration is necessary, otherwise the words themselves would be manipulated e.g. modification of the word !AngryDogAngry1916! to !AngryDog1916! should NOT happen. Thanks.</p> <p>I could not find a method to access the content in a StringBuilder line-wise. I don't know where to start and do not to want to change the StringBuilder type.</p>
[ { "answer_id": 74425379, "author": "Jämes", "author_id": 2780334, "author_profile": "https://Stackoverflow.com/users/2780334", "pm_score": 0, "selected": false, "text": "HashSet<T>" }, { "answer_id": 74426497, "author": "Zakaria Najim", "author_id": 10155157, "author_profile": "https://Stackoverflow.com/users/10155157", "pm_score": 1, "selected": false, "text": "StringBuilder strbuilder = new StringBuilder(\"!AngryDogAngry1916!\\n@AngryAngryDog1916!\\n:AngryDog1916!\\n!AngryDogAngry1916!\");\nString[] splitstrings = strbuilder.ToString().Split('\\n');\nsplitstrings = splitstrings.Distinct < String > ().ToArray();\nstring result = string.Join(\"\\n\", splitstrings);\nstrbuilder.Clear();\nstrbuilder.Append(result);\nConsole.WriteLine(result);\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1806967/" ]
74,424,368
<p>I've got something challenging (at least for me) to do. There is this OpenAPI 3.0 file that needs some dicing based on the tags (i.e. cut into as many chunks as there are items in the <code>tags</code> property.</p> <p>For simplicity, there 2 tags in this example. So, all the <code>paths</code> that belong to the <strong>Rotor Parts</strong> tag will go into the first dictionary item. And other parts will go under the second dictionary item.</p> <p>Here's the input file:</p> <pre><code>{ &quot;openapi&quot;: &quot;3.0.0&quot;, &quot;info&quot;: { &quot;description&quot;: &quot;PREST APIs for external use.&quot;, &quot;version&quot;: &quot;v1&quot;, &quot;title&quot;: &quot;REST API Doc&quot;, &quot;contact&quot;: {}, &quot;license&quot;: { &quot;name&quot;: &quot;Public&quot; } }, &quot;tags&quot;:[ { &quot;name&quot;: &quot;Rotor Parts&quot;, &quot;description&quot;: &quot;Rotor Parts API&quot; }, { &quot;name&quot;: &quot;Cloud Accounts&quot;, &quot;description&quot;: &quot;Plant Locations APIs&quot; } ], &quot;paths&quot;: { &quot;/access_keys&quot;: { &quot;get&quot;: { &quot;tags&quot;: [ &quot;Rotor Parts&quot; ], &quot;summary&quot;: &quot;List Rotor Parts&quot;, &quot;description&quot;: &quot;Returns all rotor parts if you have an Admin role. Returns just your rotor parts if you don't have this role.&quot;, &quot;operationId&quot;: &quot;get-my-rotor-parts&quot;, &quot;responses&quot;: { &quot;200&quot;: { &quot;description&quot;: &quot;successful operation&quot;, &quot;content&quot;: { &quot;application/json&quot;: { &quot;schema&quot;: { &quot;type&quot;: &quot;array&quot;, &quot;items&quot;: { &quot;$ref&quot;: &quot;#/components/schemas/RotorPartsResponseModel&quot; } } } } }, &quot;400&quot;: { &quot;description&quot;: &quot;user_inactive_or_not_exist&quot; }, &quot;403&quot;: { &quot;description&quot;: &quot;unauthorized_to_use_rotor_parts&quot; }, &quot;500&quot;: { &quot;description&quot;: &quot;failed_fetch_user_profile&quot; } } }, &quot;post&quot;: { &quot;tags&quot;: [ &quot;Rotor Parts&quot; ], &quot;summary&quot;: &quot;Add Rotor Parts&quot;, &quot;description&quot;: &quot;Adds a new rotor part for the current user. If you have API access, you can create up to two rotor parts.&quot;, &quot;operationId&quot;: &quot;add-rotor-parts&quot;, &quot;requestBody&quot;: { &quot;content&quot;: { &quot;application/json&quot;: { &quot;schema&quot;: { &quot;$ref&quot;: &quot;#/components/schemas/UserRotorPartRequestModel&quot; } } }, &quot;description&quot;: &quot;Model user rotor part model&quot;, &quot;required&quot;: true }, &quot;responses&quot;: { &quot;200&quot;: { &quot;description&quot;: &quot;successful operation&quot;, &quot;content&quot;: { &quot;application/json&quot;: { &quot;schema&quot;: { &quot;$ref&quot;: &quot;#/components/schemas/CreateUserAccessKeyResponseModel&quot; } } } }, &quot;400&quot;: { &quot;description&quot;: &quot;invalid_expiry_access_key / already_have_two_access_keys / invalid_access_key_name_length / invalid_access_key_name&quot; }, &quot;403&quot;: { &quot;description&quot;: &quot;unauthorized_to_use_access_keys&quot; }, &quot;409&quot;: { &quot;description&quot;: &quot;duplicate_access_key_name&quot; } } } }, &quot;/account/{accountId}/config/status&quot;: { &quot;get&quot;: { &quot;tags&quot;: [ &quot;Cloud Accounts&quot; ], &quot;summary&quot;: &quot;List Account Status Details&quot;, &quot;description&quot;: &quot;Returns a list of Cloud services whose status indicates a warning or error for the given cloud account ID. Includes status details for each listed service.&quot;, &quot;operationId&quot;: &quot;list-cloud-account-status-details&quot;, &quot;parameters&quot;: [ { &quot;name&quot;: &quot;accountId&quot;, &quot;in&quot;: &quot;path&quot;, &quot;description&quot;: &quot;Cloud account ID&quot;, &quot;required&quot;: true, &quot;schema&quot;: { &quot;type&quot;: &quot;string&quot; } } ], &quot;responses&quot;: { &quot;200&quot;: { &quot;description&quot;: &quot;successful operation&quot;, &quot;content&quot;: { &quot;application/json; charset=UTF-8&quot;: { &quot;schema&quot;: { &quot;type&quot;: &quot;array&quot;, &quot;items&quot;: { &quot;$ref&quot;: &quot;#/components/schemas/CloudAccountConfigStatusView&quot; } } } } }, &quot;400&quot;: { &quot;description&quot;: &quot;bad_request&quot; }, &quot;500&quot;: { &quot;description&quot;: &quot;internal_error&quot; } } } } } } </code></pre> <p>And here's an expected output:</p> <pre><code>{ &quot;tag_RotorParts&quot;: { &quot;info&quot;: &quot;same content here&quot;, &quot;tags&quot;: [ { &quot;name&quot;: &quot;Rotor Parts&quot;, &quot;description&quot;: &quot;Rotor Parts API&quot; } ], &quot;paths&quot;: { &quot;/access_keys&quot;: { &quot;get&quot;: { &quot;tags&quot;: [ &quot;Rotor Parts&quot; ], &quot;summary&quot;: &quot;List Rotor Parts&quot;, &quot;description&quot;: &quot;Returns all rotor parts if you have an Admin role. Returns just your rotor parts if you don't have this role.&quot;, &quot;operationId&quot;: &quot;get-my-rotor-parts&quot;, &quot;responses&quot;: { &quot;200&quot;: { &quot;description&quot;: &quot;successful operation&quot;, &quot;content&quot;: { &quot;application/json&quot;: { &quot;schema&quot;: { &quot;type&quot;: &quot;array&quot;, &quot;items&quot;: { &quot;$ref&quot;: &quot;#/components/schemas/RotorPartsResponseModel&quot; } } } } }, &quot;400&quot;: { &quot;description&quot;: &quot;user_inactive_or_not_exist&quot; }, &quot;403&quot;: { &quot;description&quot;: &quot;unauthorized_to_use_rotor_parts&quot; }, &quot;500&quot;: { &quot;description&quot;: &quot;failed_fetch_user_profile&quot; } } }, &quot;post&quot;: { &quot;tags&quot;: [ &quot;Rotor Parts&quot; ], &quot;summary&quot;: &quot;Add Rotor Parts&quot;, &quot;description&quot;: &quot;Adds a new rotor part for the current user. If you have API access, you can create up to two rotor parts.&quot;, &quot;operationId&quot;: &quot;add-rotor-parts&quot;, &quot;requestBody&quot;: { &quot;content&quot;: { &quot;application/json&quot;: { &quot;schema&quot;: { &quot;$ref&quot;: &quot;#/components/schemas/UserRotorPartRequestModel&quot; } } }, &quot;description&quot;: &quot;Model user rotor part model&quot;, &quot;required&quot;: true }, &quot;responses&quot;: { &quot;200&quot;: { &quot;description&quot;: &quot;successful operation&quot;, &quot;content&quot;: { &quot;application/json&quot;: { &quot;schema&quot;: { &quot;$ref&quot;: &quot;#/components/schemas/CreateUserAccessKeyResponseModel&quot; } } } }, &quot;400&quot;: { &quot;description&quot;: &quot;invalid_expiry_access_key / already_have_two_access_keys / invalid_access_key_name_length / invalid_access_key_name&quot; }, &quot;403&quot;: { &quot;description&quot;: &quot;unauthorized_to_use_access_keys&quot; }, &quot;409&quot;: { &quot;description&quot;: &quot;duplicate_access_key_name&quot; } } } } } }, &quot;tag_CloudAccounts&quot;: &quot;Same Format as above&quot; } </code></pre> <p>So far, I've tried using <code>reduce</code> to achieve this:</p> <pre><code>. as $all | reduce .tags as $tag ({}; . + {&quot;tag_&quot; + $tag.name: (($all.paths) | select(.[][].tags | contains([$tag.name]))) }) </code></pre> <p>But can't even make the query valid. Really lost at this point.</p> <p>Any help/pointers much appreciated</p>
[ { "answer_id": 74425379, "author": "Jämes", "author_id": 2780334, "author_profile": "https://Stackoverflow.com/users/2780334", "pm_score": 0, "selected": false, "text": "HashSet<T>" }, { "answer_id": 74426497, "author": "Zakaria Najim", "author_id": 10155157, "author_profile": "https://Stackoverflow.com/users/10155157", "pm_score": 1, "selected": false, "text": "StringBuilder strbuilder = new StringBuilder(\"!AngryDogAngry1916!\\n@AngryAngryDog1916!\\n:AngryDog1916!\\n!AngryDogAngry1916!\");\nString[] splitstrings = strbuilder.ToString().Split('\\n');\nsplitstrings = splitstrings.Distinct < String > ().ToArray();\nstring result = string.Join(\"\\n\", splitstrings);\nstrbuilder.Clear();\nstrbuilder.Append(result);\nConsole.WriteLine(result);\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20463822/" ]
74,424,379
<p>In below query the <code>awarded</code>, <code>banned</code>, <code>featured</code> and <code>published</code> parts are being ignored, why?</p> <p>Query: Show me a list of all featured published books with an author that has been awarded and has not been banned.</p> <pre><code>$books = myBooks::with('authors') -&gt;whereHas('authors', function ($query) { $query -&gt;where([ 'awarded' =&gt; true, 'banned' =&gt; false ]); }) -&gt;where([ 'featured' =&gt; true, 'published' =&gt; true ]) -&gt;latest() -&gt;get(); </code></pre>
[ { "answer_id": 74424687, "author": "Vlad", "author_id": 20382571, "author_profile": "https://Stackoverflow.com/users/20382571", "pm_score": 0, "selected": false, "text": "awarded" }, { "answer_id": 74424751, "author": "apokryfos", "author_id": 487813, "author_profile": "https://Stackoverflow.com/users/487813", "pm_score": 1, "selected": false, "text": "$books = myBooks::with('authors')\n ->whereHas('authors', function ($query) {\n $query\n ->where([\n [ 'awarded', '=', true ],\n [ 'banned', '=', false ]\n ]);\n })\n ->where([\n [ 'featured', '=', true ],\n [ 'published', '=', true ]\n ])\n ->latest()\n ->get();\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78297/" ]
74,424,430
<p>I am breaking a monolith that is hosted as an app service on Azure. Application is made on .NET 4.8.</p> <p>Is it possible to keep existing API calls in place, but redirect to a microservice instead of processing it by existing APP service?</p> <p>Example: Call POST <strong>some-url.azurewebsites.com/api/some-endpoint</strong> should stay same, but getting processed by <strong>my-microservice.net/api/some-endpoint</strong></p>
[ { "answer_id": 74424687, "author": "Vlad", "author_id": 20382571, "author_profile": "https://Stackoverflow.com/users/20382571", "pm_score": 0, "selected": false, "text": "awarded" }, { "answer_id": 74424751, "author": "apokryfos", "author_id": 487813, "author_profile": "https://Stackoverflow.com/users/487813", "pm_score": 1, "selected": false, "text": "$books = myBooks::with('authors')\n ->whereHas('authors', function ($query) {\n $query\n ->where([\n [ 'awarded', '=', true ],\n [ 'banned', '=', false ]\n ]);\n })\n ->where([\n [ 'featured', '=', true ],\n [ 'published', '=', true ]\n ])\n ->latest()\n ->get();\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2200319/" ]
74,424,432
<p>I have my azure pipeline doing a kubernetes@1 task with my kubernetes config:</p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: tennant-service-deployment labels: app: tennant-service spec: replicas: 3 selector: matchLabels: app: tennant-service template: metadata: labels: app: tennant-service spec: containers: - name: tennant-service image: cronesharedwesteurope.azurecr.io/tennant-service:dev ports: - containerPort: 80 imagePullSecrets: - name: registrysecret </code></pre> <p>You can see that at the moment my image is hard coded in my yaml file (tennant-service:dev).</p> <p>I want the user to tell me witha azure devops pipeline parameter which version he wants (e.g, dev / 1.0 / latest). But because the kubernetes is a yaml config file, I can't change it with a parameter, can I? Are there any tools to do exactly this?</p>
[ { "answer_id": 74426348, "author": "Charles Han", "author_id": 11514907, "author_profile": "https://Stackoverflow.com/users/11514907", "pm_score": 0, "selected": false, "text": " resources:\n pipelines:\n - pipeline: TenentServiceImage\n source: Tenent Service Image\n branch: master\n" }, { "answer_id": 74441451, "author": "Kevin Lu-MSFT", "author_id": 13464420, "author_profile": "https://Stackoverflow.com/users/13464420", "pm_score": 0, "selected": false, "text": "parameters:\n - name: dockertag\n type: string\n default: dev\n \n\npool:\n vmImage: ubuntu-latest\n\nsteps:\n\n- task: RegExMatchReplace@2\n displayName: 'RegEx Match & Replace'\n inputs:\n PathToFile: test.yml\n RegEx: 'image: ([a-zA-Z]+(\\.[a-zA-Z]+)+)/[a-zA-Z]+-[a-zA-Z]+:[a-zA-Z]+'\n ValueToReplace: 'image: cronesharedwesteurope.azurecr.io/tennant-service:${{ parameters.dockertag }}'\n\n...\n" }, { "answer_id": 74446480, "author": "iamattiq1991", "author_id": 6745536, "author_profile": "https://Stackoverflow.com/users/6745536", "pm_score": 2, "selected": true, "text": "trigger:\n- none\n\npool:\n name: {name of my self hosted agent pool}\n \nvariables:\n imageTag: '$(Build.BuildId)'\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/133584/" ]
74,424,433
<p>In the React Navigation <a href="https://reactnavigation.org/docs/header-buttons" rel="nofollow noreferrer">documentation for Header Buttons</a>, there is a code that creates a function that updates the &quot;count&quot; state.</p> <p><code>const [count, setCount] = React.useState(0);</code></p> <p><code>&lt;Button onPress={() =&gt; setCount((c) =&gt; c + 1)} title=&quot;Update count&quot; /&gt;</code></p> <p><a href="https://snack.expo.io/?platform=android&amp;name=header%20interaction&amp;dependencies=%40expo%2Fvector-icons%40*%2C%40react-native-community%2Fmasked-view%40*%2Creact-native-gesture-handler%40*%2Creact-native-pager-view%40*%2Creact-native-paper%40%5E4.7.2%2Creact-native-reanimated%40*%2Creact-native-safe-area-context%40*%2Creact-native-screens%40*%2Creact-native-tab-view%40%5E3.0.0%2C%40react-navigation%2Fbottom-tabs%406.3.1%2C%40react-navigation%2Fdrawer%406.4.1%2C%40react-navigation%2Felements%401.3.3%2C%40react-navigation%2Fmaterial-bottom-tabs%406.2.1%2C%40react-navigation%2Fmaterial-top-tabs%406.2.1%2C%40react-navigation%2Fnative-stack%406.6.1%2C%40react-navigation%2Fnative%406.0.10%2C%40react-navigation%2Fstack%406.2.1&amp;hideQueryParams=true&amp;sourceUrl=https%3A%2F%2Freactnavigation.org%2Fexamples%2F6.x%2Fheader-interaction.js" rel="nofollow noreferrer">demo link from documentation</a></p> <p>I assume that the variable <code>c</code> is supposed to be the current count in the anonymous function that is created for onPress. However there is no reference to <code>c</code> elsewhere in the code.</p> <p>Where is the value of <code>c</code> coming from and how is it being linked to <code>count</code> state?</p>
[ { "answer_id": 74426348, "author": "Charles Han", "author_id": 11514907, "author_profile": "https://Stackoverflow.com/users/11514907", "pm_score": 0, "selected": false, "text": " resources:\n pipelines:\n - pipeline: TenentServiceImage\n source: Tenent Service Image\n branch: master\n" }, { "answer_id": 74441451, "author": "Kevin Lu-MSFT", "author_id": 13464420, "author_profile": "https://Stackoverflow.com/users/13464420", "pm_score": 0, "selected": false, "text": "parameters:\n - name: dockertag\n type: string\n default: dev\n \n\npool:\n vmImage: ubuntu-latest\n\nsteps:\n\n- task: RegExMatchReplace@2\n displayName: 'RegEx Match & Replace'\n inputs:\n PathToFile: test.yml\n RegEx: 'image: ([a-zA-Z]+(\\.[a-zA-Z]+)+)/[a-zA-Z]+-[a-zA-Z]+:[a-zA-Z]+'\n ValueToReplace: 'image: cronesharedwesteurope.azurecr.io/tennant-service:${{ parameters.dockertag }}'\n\n...\n" }, { "answer_id": 74446480, "author": "iamattiq1991", "author_id": 6745536, "author_profile": "https://Stackoverflow.com/users/6745536", "pm_score": 2, "selected": true, "text": "trigger:\n- none\n\npool:\n name: {name of my self hosted agent pool}\n \nvariables:\n imageTag: '$(Build.BuildId)'\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/761902/" ]
74,424,457
<p>I have data with timestamps, I want to make it into 1min time series and fill the missing values in rows that are created with the last input. However, also have a limit on the ffill function as well. So, if the next input is missing for too long, leave NaN.</p> <p>Data:</p> <pre><code>timestamp pay 2020-10-10 23:32 50 2020-10-11 21:55 80 2020-10-13 23:28 40 </code></pre> <p>Convert to this using <code>df.set_index('timestamp').asfreq('1Min', method='ffill')</code>, forward fill the pay column until the next input, <strong>but if the next input is more than 24 hours away (1440 rows), only fill up to 1440 rows.</strong></p> <p>So, <code>2020-10-11 21:55 80</code> should only filled with <strong>80</strong> until <code>2020-10-12 21:55</code> , then leave NaN until <code>2020-10-13 23:28 40</code>.</p> <p>How can I achieve this?</p>
[ { "answer_id": 74424776, "author": "Bushmaster", "author_id": 15415267, "author_profile": "https://Stackoverflow.com/users/15415267", "pm_score": 2, "selected": false, "text": "mask = df.set_index('timestamp').sort_index().resample('1Min').ffill(limit=1440)\n" }, { "answer_id": 74425066, "author": "Celius Stingher", "author_id": 11897007, "author_profile": "https://Stackoverflow.com/users/11897007", "pm_score": 1, "selected": false, "text": "sort_index()" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20489776/" ]
74,424,476
<p>I'm using Oracle and SQL Developer. I have downloaded HR schema and need to do some queries with it. Now I'm working with table Employees. As an user <strong>I need to see employees with the highest gap between their salary and the average salary of all later hired colleagues in corresponding department</strong>. It seems quite interesting and really complicated. I have read some documentation and tried, for example LEAD(), that provides access to more than one row of a table at the same time:</p> <pre><code>SELECT employee_id, first_name || ' ' || last_name, department_id, salary, hire_date, LEAD(hire_date) OVER(PARTITION BY department_id ORDER BY hire_date DESC ) AS Prev_hiredate FROM employees ORDER BY department_id, hire_date; </code></pre> <p>That shows for every person in department hiredate of later hired person. Also I have tried to use window clause to understand its concepts:</p> <pre><code>SELECT employee_id, first_name || ' ' || last_name, department_id, hire_date, salary, AVG(salary) OVER(PARTITION BY department_id ORDER BY hire_date ROWS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING ) AS avg_sal FROM employees ORDER BY department_id, hire_date; </code></pre> <p>The result of this query will be: <a href="https://i.stack.imgur.com/95Msl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/95Msl.png" alt="Result of query for 20 department" /></a></p> <p><a href="https://i.stack.imgur.com/5TeNz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5TeNz.png" alt="Result of query for 60 department" /></a></p> <p>However, it is not exactly what I need. I need to reduce the result just by adding column with gap (salary-avr_sal), where the gap will be highest and receive one employee per department. How should the result look like: for example, we have 60 department. We have 5 employees there ordering by hire_date. First has salary 4800, second – 9000, third – 4800, fourth – 4200, fifth – 6000. If we do calculations: <strong>4800 - ((9000+4800+4200+6000)/4)=-1200, 9000-((4800+4200+6000)/3)=4000, 4800 -((4200+6000)/2)=-300, 4200 - 6000=-1800</strong> and the last person in department will have the highest gap: <strong>6000 - 0 = 6000</strong>. Let's take a look on 20 department. We have two people there: first has salary 13000, second – 6000. Calculations: <strong>13000 - 6000 = 7000, 6000 - 0 = 6000</strong>. The highest gap will be for first person. So for department 20 the result should be person with salary 13000, for department 60 the result should be person with salary 6000 and so on. How should look my query to get the appropriate result (what I need is marked bold up, also I want to <strong>see column with highest gap</strong>, can be different solutions with <strong>analytic functions</strong>, but should be necessarily included <strong>window clause</strong>)?</p>
[ { "answer_id": 74424517, "author": "GMB", "author_id": 10676716, "author_profile": "https://Stackoverflow.com/users/10676716", "pm_score": 2, "selected": false, "text": " AVG(salary) OVER(\n PARTITION BY department_id\n ORDER BY hire_date \n ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING\n ) AS avg_salary\n" }, { "answer_id": 74435579, "author": "d r", "author_id": 19023353, "author_profile": "https://Stackoverflow.com/users/19023353", "pm_score": 2, "selected": true, "text": "WITH\n emp (ID, EMP_NAME, HIRE_DATE, SALARY, DEPT) AS \n (\n Select 601, 'HILLER', To_Date('23-JAN-82', 'dd-MON-yy'), 4800, 60 From Dual Union All\n Select 602, 'MILLER', To_Date('23-FEB-82', 'dd-MON-yy'), 9000, 60 From Dual Union All\n Select 603, 'SMITH', To_Date('23-MAR-82', 'dd-MON-yy'), 4800, 60 From Dual Union All\n Select 604, 'FORD', To_Date('23-APR-82', 'dd-MON-yy'), 4200, 60 From Dual Union All\n Select 605, 'KING', To_Date('23-MAY-82', 'dd-MON-yy'), 6000, 60 From Dual Union All\n Select 201, 'SCOT', To_Date('23-MAR-82', 'dd-MON-yy'), 13000, 20 From Dual Union All\n Select 202, 'JONES', To_Date('23-AUG-82', 'dd-MON-yy'), 6000, 20 From Dual \n ),\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18744508/" ]
74,424,507
<p>I am having a heck of a time using an environment variable with a semicolon in a properties file read by WildFly (24) in Linux. One like:</p> <p><code>DATABASE_JDBC_URL=jdbc:sqlserver://sqlserver.c3klg5a2ws.us-east-1.rds.amazonaws.com:1433;DatabaseName=ejbca;encrypt=false</code></p> <p>The issue is that its truncating things at the semicolon if I don't use quotes so I end up with it trying to write to master since it thinks no database is specified.</p> <p>I have it setup so that variable is in a file called datasource.properties that gets read from standalone.conf where this variable sits:</p> <p><code>JAVA_OPTS=&quot;$JAVA_OPTS -DDATABASE_JDBC_URL=${DATABASE_JDBC_URL}&quot;</code></p> <p>It's read in with the following in standalone.conf:</p> <pre><code>set -a . /opt/wildfly_config/datasource.properties set +a </code></pre> <p>That in turn gets populated in standalone.xml with:</p> <p><code>&lt;connection-url&gt;${env.DATABASE_JDBC_URL}&lt;/connection-url&gt;</code></p> <p>I try putting it in quotes and oddly enough it doesn’t start at all. Standalone.sh is no longer able to parse it:</p> <p><code>/opt/wildfly/bin/standalone.sh: line 338: --add-exports=java.desktop/sun.awt=ALL-UNNAMED: No such file or directory</code></p> <p>So I then escape it in quotes like this:</p> <p><code>DATABASE_JDBC_URL=&quot;jdbc:sqlserver://sqlserver.c3klg5a2ws.us-east-1.rds.amazonaws.com:1433\;DatabaseName=ejbca\;encrypt=false&quot;</code></p> <p>Startup looks good in the log output this way:</p> <p><code>-DDATABASE_JDBC_URL=jdbc:sqlserver://sqlserver.c3klg5a2ws.us-east-1.rds.amazonaws.com:1433;DatabaseName=ejbca;encrypt=false</code></p> <p>But then java doesn’t like it, for some reason it sees the escape ticks:</p> <p><code>Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The port number 1433\ is not valid.</code></p> <p>I can use sed to change the value in the standalone.xml, but all of the other properties I am doing work fine with the exception of this one and:</p> <p><code>&lt;check-valid-connection-sql&gt;${env.DATABASE_CONNECTION_CHECK}&lt;/check-valid-connection-sql&gt;</code></p> <p>Where that value is &quot;SELECT 1;&quot; which it also does not like. That one worked with &quot;'SELECT 1;'&quot; but this one does not. I tried single quotes as well. That also gives the parsing error above. Is there any way to read in this environment variable that keeps wildfly happy?</p>
[ { "answer_id": 74431578, "author": "andrewJames", "author_id": 12567365, "author_profile": "https://Stackoverflow.com/users/12567365", "pm_score": 2, "selected": true, "text": "{" }, { "answer_id": 74554745, "author": "Alex G.", "author_id": 16345396, "author_profile": "https://Stackoverflow.com/users/16345396", "pm_score": 0, "selected": false, "text": "#!/bin/bash\nexport DATABASE_JDBC_URL=\"jdbc:sqlserver://sqlserver.c3klg5a2ws.us-east-1.rds.amazonaws.com:1433;DatabaseName=ejbca;encrypt=false\"\n/opt/wildfly/bin/standalone.sh\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16345396/" ]
74,424,631
<p>I'm trying to initialize a dummy array of length <code>n</code> using <code>np.zeros(n)</code> with <code>dtype=object</code>. I want to use this dummy array to store <code>n</code> copies of another array of length <code>m</code>. I'm trying to avoid for loop to set values at each index.</p> <p>I tried using the below code but keep getting error -</p> <pre><code>temp = np.zeros(10, dtype=object) arr = np.array([1.1,1.2,1.3,1.4,1.5]) res = temp * arr </code></pre> <p>The desired result should be -</p> <pre><code>np.array([[1.1,1.2,1.3,1.4,1.5], [1.1,1.2,1.3,1.4,1.5], ... 10 copies]) </code></pre> <p>I keep getting the error -</p> <pre><code>operands could not be broadcast together with shapes (10,) (5,) </code></pre> <p>I understand that this error arises since the compiler thinks I'm trying to multiply those arrays. So how do I achieve the task?</p>
[ { "answer_id": 74431578, "author": "andrewJames", "author_id": 12567365, "author_profile": "https://Stackoverflow.com/users/12567365", "pm_score": 2, "selected": true, "text": "{" }, { "answer_id": 74554745, "author": "Alex G.", "author_id": 16345396, "author_profile": "https://Stackoverflow.com/users/16345396", "pm_score": 0, "selected": false, "text": "#!/bin/bash\nexport DATABASE_JDBC_URL=\"jdbc:sqlserver://sqlserver.c3klg5a2ws.us-east-1.rds.amazonaws.com:1433;DatabaseName=ejbca;encrypt=false\"\n/opt/wildfly/bin/standalone.sh\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20278669/" ]
74,424,654
<pre><code>SELECT CAST(purchase_price AS FLOAT64) FROM customer_data.customer_purchase ORDER BY CAST(purchase_price AS FLOAT64) DESC </code></pre> <p>This is what someone wrote, and it's working fine. Is it necessary to have <code>CAST</code> twice? Why is that so? Thank you!</p> <p>I tried removing <code>CAST</code> from the <code>SELECT</code> statement, and it produced the same result. So I'm confused as to why someone would write it twice.</p>
[ { "answer_id": 74431578, "author": "andrewJames", "author_id": 12567365, "author_profile": "https://Stackoverflow.com/users/12567365", "pm_score": 2, "selected": true, "text": "{" }, { "answer_id": 74554745, "author": "Alex G.", "author_id": 16345396, "author_profile": "https://Stackoverflow.com/users/16345396", "pm_score": 0, "selected": false, "text": "#!/bin/bash\nexport DATABASE_JDBC_URL=\"jdbc:sqlserver://sqlserver.c3klg5a2ws.us-east-1.rds.amazonaws.com:1433;DatabaseName=ejbca;encrypt=false\"\n/opt/wildfly/bin/standalone.sh\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19325292/" ]
74,424,661
<p>My current program prints all the different sums that are generated with the given integers. Instead of the program printing the content of the list, I would want to print only the lenght of the list.</p> <pre><code>def sums(items): if len(items) == 1: return items else: new_list = [] for i in items: new_list.append(i) for x in sums(items[1:]): new_list.append(x) new_list.append(x + items[0]) new_list = list(set(new_list)) return new_list if __name__ == &quot;__main__&quot;: print(sums([1, 2, 3])) # should print 6 print(sums([2, 2, 3])) # should print 5 </code></pre> <p>Just editing the sums function, instead of <code>return new_list</code> I tried to <code>return len(new_list)</code> this gives me an error of <code>TypeError: 'int' object is not iterable</code>. I'm just trying to return the lenght of the list, so I don't really understand the error.</p>
[ { "answer_id": 74424676, "author": "svfat", "author_id": 2419628, "author_profile": "https://Stackoverflow.com/users/2419628", "pm_score": 0, "selected": false, "text": "if __name__ == \"__main__\":\n print(len(sums([1, 2, 3]))) \n print(len(sums([2, 2, 3])))\n" }, { "answer_id": 74424699, "author": "mudi loodi", "author_id": 11962536, "author_profile": "https://Stackoverflow.com/users/11962536", "pm_score": 1, "selected": false, "text": "if __name__ == \"__main__\":\n print(len(sums([1, 2, 3]))) \n print(len(sums([2, 2, 3]))) \n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10332465/" ]
74,424,671
<p>My <code>python --version</code> is Python 3.9.6 And my <code>python3 --version</code> is Python 3.10.8</p> <p>I believe because of this I have a problem with running flask applications in VsCode. When I run one I receive <code>ModuleNotFoundError: No module named 'flask</code> error, however, I did install flask module</p> <pre><code>Requirement already satisfied: flask in /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages (2.2.2) </code></pre> <p>I know that sometimes this problem is caused by the wrong interpreter version, I tried all of them but no one worked</p> <p><a href="https://i.stack.imgur.com/5myCQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5myCQ.png" alt="" /></a></p> <p>Does anybody know what is the reason for my error and how can I fix it?</p>
[ { "answer_id": 74427331, "author": "JialeDu", "author_id": 19133920, "author_profile": "https://Stackoverflow.com/users/19133920", "pm_score": 2, "selected": true, "text": "import sys\nprint(sys.executable)\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18930222/" ]
74,424,684
<p>I'm using dash (python lib to make dashboards) and i'm having a problem with bootstrap components. I can´t exclude the right margin from the container. I'm usign this: <code>class_name='m-0'</code> on the container class. Already tried using <code>style={'margin': '0px'}</code> too, but keeps this same way.</p> <pre><code># Layout app.layout = dbc.Container(children=[ dbc.Row([ dbc.Col([ html.Div(children=[ html.H5(children='BAJA UEA'), html.H6(children=&quot;Visualização dos dados da telemetria&quot;), ]), ]), dbc.Col([ dcc.Dropdown(['2400', '4800', '9600', '115200'], id='baudrate-dropdown', value='9600', placeholder='Baudrate', style={'width': '150px'}), dcc.Dropdown(portList, id='ports-dropdown', value='portList[0]', placeholder='COM Ports', style={'width': '150px'}), dbc.Button('Connect', id='connect-button', style={'width': '150px'}), ], class_name='d-flex p-3 align-items-center justify-content-evenly'), ]), dbc.Row([ dbc.Col([ dcc.Graph( id='graph_temperature', figure=graph_temperature ), dcc.Graph( id='graph_velocidade', figure=graph_velocidade ), dcc.Graph( id='graph_PRM', figure=graph_PRM ), dcc.Graph( id='graph_ACC', figure=graph_ACC ) ]), dbc.Col([ ]) ]) ], class_name='m-0') </code></pre> <p><a href="https://i.stack.imgur.com/GRYfe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GRYfe.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74427331, "author": "JialeDu", "author_id": 19133920, "author_profile": "https://Stackoverflow.com/users/19133920", "pm_score": 2, "selected": true, "text": "import sys\nprint(sys.executable)\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17856015/" ]
74,424,691
<p><a href="https://i.stack.imgur.com/Jbll5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Jbll5.png" alt="My Code" /></a> I have been trying to solve the problem set 1 in CS50, language C. I've come to this point, but I got stuck in here. I want my code to ask for a new input while(n&gt;=9 || n&lt;=0) but it ends there, instead of asking for a new input. I have already tried return n; but it didn't work at all. You can see the console and the results.</p> <p>When I asked my code to return 0; I thought it would be asking for a new input. But as it can be seen, it ended up. What I want is it to ask for a new input, instead of stop working.</p> <p>This is my first time and post in here, so I hope I have described my problem good enough.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;cs50.h&gt; int main(void) { int n = get_int(&quot;Number: &quot;); while(n&gt;=9 || n&lt;=0) { return 0; } int i; for(i=0;i&lt;n;i++) { int a; for(a=n-1;a&gt;i;a--) { printf(&quot; &quot;); } int y; for(y=0;y&lt;=i;y++) { printf(&quot;#&quot;); } printf(&quot;\n&quot;); } } </code></pre>
[ { "answer_id": 74424777, "author": "eRtuSa", "author_id": 16422168, "author_profile": "https://Stackoverflow.com/users/16422168", "pm_score": 0, "selected": false, "text": "(n >= 9 || n <= 0)" }, { "answer_id": 74424898, "author": "emetsipe", "author_id": 18198735, "author_profile": "https://Stackoverflow.com/users/18198735", "pm_score": 2, "selected": true, "text": "return 0" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20493966/" ]
74,424,693
<p>I am about half way through an intro to python course. I very recently started studying lists/dictionaries. I was trying to create my own python code to try to learn how to work with dictionaries better. Basically, what I am trying to do is get a user's input as to what section of a video series they are on and then output the total time left in the series. So far the code looks something like this:</p> <pre><code>video_dict = { 1 : 9, # Section 1 is 9 minutes 2 : 75, 3 : 174, 4 : 100 } current_section = input('What section are you currently on?') total_time = 0 for key, value in video_dict.items(): if current_section &gt;= key: total_time += value print(total_time) </code></pre> <p>The issue I have had so far is that it seems to be taking the number entered by the user and going in reverse up the dictionary. So if you enter '2' as your current section, it adds up entry 1 and 2 and gives you a total_time of 84 minutes; instead of adding up 2,3, and 4 for a total time of 349 minutes. What do i need to correct to get it to go down the list instead of up it?</p>
[ { "answer_id": 74424715, "author": "Mark", "author_id": 2203038, "author_profile": "https://Stackoverflow.com/users/2203038", "pm_score": 3, "selected": true, "text": "video_dict = {\n 1 : 9, # Section 1 is 9 minutes\n 2 : 75,\n 3 : 174,\n 4 : 100\n}\n\n\n\ncurrent_section = int(input('What section are you currently on?'))\n\ntotal_time = 0\nfor key, value in video_dict.items():\n if current_section <= key :\n total_time += value\n\nprint(total_time)\n" }, { "answer_id": 74424728, "author": "islam abdelmoumen", "author_id": 19661530, "author_profile": "https://Stackoverflow.com/users/19661530", "pm_score": 0, "selected": false, "text": "video_dict = {\n 1 : 9, # Section 1 is 9 minutes\n 2 : 75,\n 3 : 174,\n 4 : 100\n}\n\ninp = int(input('What section are you currently on?'))\nres = 0\nfor key in range(inp,0,-1):\n res+=video_dict[key]\n\n\n print(res)\n" }, { "answer_id": 74424784, "author": "balderman", "author_id": 415016, "author_profile": "https://Stackoverflow.com/users/415016", "pm_score": 0, "selected": false, "text": "sections = [9, 75, 174, 100]\n\ncurrent_section = int(input('What section are you currently on?')) - 1\ntime_left = sum(sections[current_section:])\nprint(f'{time_left} minutes left')\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9221493/" ]
74,424,704
<p>I have a list of lists each of those lists having one element. Is there a &quot;pythonic&quot; way to turn this into a list of elements that aren't lists outside of using the loop displayed below?</p> <pre><code>un_list = [] for x in home_times: y=x[0] un_list.append(y) </code></pre>
[ { "answer_id": 74424715, "author": "Mark", "author_id": 2203038, "author_profile": "https://Stackoverflow.com/users/2203038", "pm_score": 3, "selected": true, "text": "video_dict = {\n 1 : 9, # Section 1 is 9 minutes\n 2 : 75,\n 3 : 174,\n 4 : 100\n}\n\n\n\ncurrent_section = int(input('What section are you currently on?'))\n\ntotal_time = 0\nfor key, value in video_dict.items():\n if current_section <= key :\n total_time += value\n\nprint(total_time)\n" }, { "answer_id": 74424728, "author": "islam abdelmoumen", "author_id": 19661530, "author_profile": "https://Stackoverflow.com/users/19661530", "pm_score": 0, "selected": false, "text": "video_dict = {\n 1 : 9, # Section 1 is 9 minutes\n 2 : 75,\n 3 : 174,\n 4 : 100\n}\n\ninp = int(input('What section are you currently on?'))\nres = 0\nfor key in range(inp,0,-1):\n res+=video_dict[key]\n\n\n print(res)\n" }, { "answer_id": 74424784, "author": "balderman", "author_id": 415016, "author_profile": "https://Stackoverflow.com/users/415016", "pm_score": 0, "selected": false, "text": "sections = [9, 75, 174, 100]\n\ncurrent_section = int(input('What section are you currently on?')) - 1\ntime_left = sum(sections[current_section:])\nprint(f'{time_left} minutes left')\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20494739/" ]
74,424,708
<blockquote> <p>Create a function in python that replaces at least four different words or phrases with internet slang acronyms such as LOL, OMG, TBH. For example, if the user enters a sentence &quot;Oh my god, I am scared to be honest.&quot; The output should be &quot;OMG I am scared TBH&quot;. <strong>The program must not use any built-in find, replace, encode, index, or translate functions.</strong> The program can use indexing (i.e., <code>[ ]</code> ), slicing (i.e., <code>:</code>), the <code>in</code> operator, and the <code>len()</code> function.</p> </blockquote> <p>This is what I have so far:</p> <pre><code>user_string = (input(&quot;Please enter a string: &quot;)).lower() punctuations = '''.,!@#$%^&amp;*()[]{};:-'&quot;\|&lt;&gt;/?_~''' new_string = &quot;&quot; list = [] for i in range(0, len(user_string)): if (user_string[i] not in punctuations): new_string = new_string + user_string[i] print(new_string) slang = &quot;to be honest&quot; for i in range(0, len(slang)): for j in range(0, len(new_string)): if (new_string[j] == slang[i]): list.append(j) if (i &lt; len(slang)): i = i + 1 elif (new_string[j] != slang[i]): if (len(list) &gt; 0): list.pop() print(list) </code></pre> <p>First I am getting the sentence from the user and removing all the punctuations from the sentence. Then I have created a variable called slang which holds the slang that I want to replace in the sentence with the acronym &quot;TBH&quot;.</p> <p>I have nested for loops which compare the string that the user has entered to the first letter of the slang variable. If the letters are the same, it compares the next letter of the string with the next letter of the slang.</p> <p>I'm getting an error from the last part. How do I check if &quot;to be honest&quot; is in the string that the user has entered? And if it is in the string, how do I replace it with &quot;TBH&quot;?</p>
[ { "answer_id": 74424902, "author": "not a tshirt", "author_id": 13190923, "author_profile": "https://Stackoverflow.com/users/13190923", "pm_score": 1, "selected": false, "text": "slang" }, { "answer_id": 74425792, "author": "Carl HR", "author_id": 14956120, "author_profile": "https://Stackoverflow.com/users/14956120", "pm_score": 0, "selected": false, "text": "# This is a dictionary so we can automate the replacement on the `__main__` scope\ntargets = {'to be honest': 'TBH', 'oh my god': 'OMG'}\n\n# Returns a list of intervals that tells where all occurences of the \n# `sequence` passed as parameter resides inside `source`.\n#\n# If `sequence` is not present, the list will be empty.\ndef findSequences(source, sequence):\n # This is our return value.\n intervals = []\n\n # len is O(1). But if you need to implement your own len function,\n # this might be handy to save for the linear complexity.\n srcLength = len(source)\n seqLength = len(sequence)\n\n # If the sequence is larger than source, it's not inside\n if (seqLength > srcLength):\n return intervals\n\n # If it's smaller or equal than source, it might be\n else:\n buffer = ''\n for i in range(srcLength):\n buffer = ''\n\n # From a starting character on index `i`, we will create\n # a temporary buffer with the length of sequence.\n for j in range(seqLength):\n # We must take care to not go out of the source string\n # otherwise, there's no point in continuing on building\n # buffer.\n if (i+j >= srcLength):\n break\n else:\n buffer += source[i+j]\n\n # If this temporary buffer equals sequence, we found the\n # substring!\n if (buffer == sequence):\n\n # Return the interval of the substring\n intervals.append((i, i+j))\n\n # Out of the for-loop.\n return intervals\n\n# Takes out any characters inside `punctuation` from source.\n#\n# Uses the `in` keyword on the if-statement. But as the post says,\n# it's allowed.\ndef takeOutPunctuation(source, punctuation='.,!@#$%^&*()[]{};:-\\'\"\\\\|<>/?_~'):\n buffer = ''\n for char in source:\n if (char not in punctuation):\n buffer += char\n\n return buffer\n\n# A naive approach would not to find all intervals, but to find the first \n# `phrase` occurence inside the `source` string, and replace it. If you do \n# that, it will get replacing \"TBH\" to \"TBH2\" infinitelly, always append \"2\" \n# to the string.\n#\n# This function is smart enough to avoid that.\n#\n# It replaces all occurences of the `phrase` string into a `target` string.\n#\n# As `findSequences` returns a list of all capture's intervals, the\n# replacement will not get stuck in an infinite loop if we use\n# parameters such as: myReplace(..., \"TBH\", \"TBH2\")\ndef myReplace(source, phrase, target):\n intervals = findSequences(source, phrase)\n\n if (len(intervals) == 0):\n return source\n else:\n # Append everything until the first capture\n buffer = source[:intervals[0][0]]\n\n # We insert this first interval just for writting less code inside the for-loop.\n #\n # This is not a capture, it's just so we can access (i-1) when the iteration\n # starts.\n intervals.insert(0, (0, intervals[0][0]))\n\n # Start a the second position of the `intervals` array so we can access (i-1)\n # at the start of the iteration.\n for i in range(1, len(intervals)):\n # For every `phrase` capture, we append:\n # - everything that comes before the capture\n # - the `target` string\n buffer += source[intervals[i-1][1]+1:intervals[i][0]] + target\n\n # Once the iteration ends, we must append everything that comes later\n # after the last capture.\n buffer += source[intervals[-1][1]+1:]\n\n # Return the modified string\n return buffer\n\nif __name__ == '__main__':\n # Note: I didn't wrote input() here so we can see what the actual input is.\n user_string = 'Oh my god, I am scared to be honest and to be honest and to be honest!'.lower()\n user_string = takeOutPunctuation(user_string)\n\n # Automated Replacement\n for key in targets:\n user_string = myReplace(user_string, key, targets[key])\n\n # Print the output:\n print(user_string)\n # -> OMG i am scared TBH and TBH and TBH\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20495039/" ]
74,424,760
<p>I have this code. I print the content of a DIV via its ID, but omit an image. I would like your support to know how to make that image be included. (the image is also inside the DIV)</p> <p>impresion = The DIV to print</p> <pre><code>function printDiv(impresion) { var contenido= document.getElementById(impresion).innerHTML; var contenidoOriginal= document.body.innerHTML; document.body.innerHTML = contenido; window.print(); document.body.innerHTML = contenidoOriginal; } </code></pre> <p>I have tried many things and nothing works</p>
[ { "answer_id": 74424902, "author": "not a tshirt", "author_id": 13190923, "author_profile": "https://Stackoverflow.com/users/13190923", "pm_score": 1, "selected": false, "text": "slang" }, { "answer_id": 74425792, "author": "Carl HR", "author_id": 14956120, "author_profile": "https://Stackoverflow.com/users/14956120", "pm_score": 0, "selected": false, "text": "# This is a dictionary so we can automate the replacement on the `__main__` scope\ntargets = {'to be honest': 'TBH', 'oh my god': 'OMG'}\n\n# Returns a list of intervals that tells where all occurences of the \n# `sequence` passed as parameter resides inside `source`.\n#\n# If `sequence` is not present, the list will be empty.\ndef findSequences(source, sequence):\n # This is our return value.\n intervals = []\n\n # len is O(1). But if you need to implement your own len function,\n # this might be handy to save for the linear complexity.\n srcLength = len(source)\n seqLength = len(sequence)\n\n # If the sequence is larger than source, it's not inside\n if (seqLength > srcLength):\n return intervals\n\n # If it's smaller or equal than source, it might be\n else:\n buffer = ''\n for i in range(srcLength):\n buffer = ''\n\n # From a starting character on index `i`, we will create\n # a temporary buffer with the length of sequence.\n for j in range(seqLength):\n # We must take care to not go out of the source string\n # otherwise, there's no point in continuing on building\n # buffer.\n if (i+j >= srcLength):\n break\n else:\n buffer += source[i+j]\n\n # If this temporary buffer equals sequence, we found the\n # substring!\n if (buffer == sequence):\n\n # Return the interval of the substring\n intervals.append((i, i+j))\n\n # Out of the for-loop.\n return intervals\n\n# Takes out any characters inside `punctuation` from source.\n#\n# Uses the `in` keyword on the if-statement. But as the post says,\n# it's allowed.\ndef takeOutPunctuation(source, punctuation='.,!@#$%^&*()[]{};:-\\'\"\\\\|<>/?_~'):\n buffer = ''\n for char in source:\n if (char not in punctuation):\n buffer += char\n\n return buffer\n\n# A naive approach would not to find all intervals, but to find the first \n# `phrase` occurence inside the `source` string, and replace it. If you do \n# that, it will get replacing \"TBH\" to \"TBH2\" infinitelly, always append \"2\" \n# to the string.\n#\n# This function is smart enough to avoid that.\n#\n# It replaces all occurences of the `phrase` string into a `target` string.\n#\n# As `findSequences` returns a list of all capture's intervals, the\n# replacement will not get stuck in an infinite loop if we use\n# parameters such as: myReplace(..., \"TBH\", \"TBH2\")\ndef myReplace(source, phrase, target):\n intervals = findSequences(source, phrase)\n\n if (len(intervals) == 0):\n return source\n else:\n # Append everything until the first capture\n buffer = source[:intervals[0][0]]\n\n # We insert this first interval just for writting less code inside the for-loop.\n #\n # This is not a capture, it's just so we can access (i-1) when the iteration\n # starts.\n intervals.insert(0, (0, intervals[0][0]))\n\n # Start a the second position of the `intervals` array so we can access (i-1)\n # at the start of the iteration.\n for i in range(1, len(intervals)):\n # For every `phrase` capture, we append:\n # - everything that comes before the capture\n # - the `target` string\n buffer += source[intervals[i-1][1]+1:intervals[i][0]] + target\n\n # Once the iteration ends, we must append everything that comes later\n # after the last capture.\n buffer += source[intervals[-1][1]+1:]\n\n # Return the modified string\n return buffer\n\nif __name__ == '__main__':\n # Note: I didn't wrote input() here so we can see what the actual input is.\n user_string = 'Oh my god, I am scared to be honest and to be honest and to be honest!'.lower()\n user_string = takeOutPunctuation(user_string)\n\n # Automated Replacement\n for key in targets:\n user_string = myReplace(user_string, key, targets[key])\n\n # Print the output:\n print(user_string)\n # -> OMG i am scared TBH and TBH and TBH\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13901700/" ]
74,424,769
<p>More specifically, <code>adjustment_type</code> keeps getting (seemingly) updated on each <code>terraform plan</code>. Why is that and can it be avoided?</p> <pre><code>Terraform will perform the following actions: # aws_autoscaling_policy.this will be updated in-place ~ resource &quot;aws_autoscaling_policy&quot; &quot;this&quot; { + adjustment_type = &quot;ChangeInCapacity&quot; </code></pre> <p>Here's autoscaling policy definition:</p> <pre><code>resource &quot;aws_autoscaling_policy&quot; &quot;this&quot; { name = var.service_name # Same between `terraform` invocations. autoscaling_group_name = aws_autoscaling_group.this.name adjustment_type = &quot;ChangeInCapacity&quot; policy_type = &quot;TargetTrackingScaling&quot; # ASG merely serves as an EC2-ready-to-be-made-scalable, hence `false`. enabled = false target_tracking_configuration { predefined_metric_specification { predefined_metric_type = &quot;ASGAverageCPUUtilization&quot; } target_value = 99.0 } } </code></pre> <ul> <li>terraform 1.3.1</li> <li>terragrunt 0.40.2</li> </ul>
[ { "answer_id": 74427390, "author": "Marcin", "author_id": 248823, "author_profile": "https://Stackoverflow.com/users/248823", "pm_score": 2, "selected": false, "text": "resource \"aws_autoscaling_policy\" \"this\" {\n name = var.service_name # Same between `terraform` invocations.\n autoscaling_group_name = aws_autoscaling_group.this.name\n adjustment_type = \"ChangeInCapacity\"\n policy_type = \"TargetTrackingScaling\"\n # ASG merely serves as an EC2-ready-to-be-made-scalable, hence `false`.\n enabled = false\n target_tracking_configuration {\n predefined_metric_specification {\n predefined_metric_type = \"ASGAverageCPUUtilization\"\n }\n target_value = 99.0\n }\n\n lifecycle {\n ignore_changes = [\n adjustment_type\n ]\n }\n\n}\n" }, { "answer_id": 74437228, "author": "Martin Atkins", "author_id": 281848, "author_profile": "https://Stackoverflow.com/users/281848", "pm_score": 2, "selected": true, "text": "hashicorp/aws" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16672610/" ]
74,424,771
<p>I am trying to fetch profile image from firestore. But it is giving an error. Here is the code of fuction which is use to get the image from database. Kindly help if you can</p> <pre><code>Future&lt;String&gt; getUserImage() async { final uid = auth.currentUser?.uid; final users = await firestore .collection(&quot;app&quot;) .doc(&quot;user&quot;) .collection(&quot;driver&quot;) .doc(uid) .get(); return users.data()?['dp']; } </code></pre>
[ { "answer_id": 74427390, "author": "Marcin", "author_id": 248823, "author_profile": "https://Stackoverflow.com/users/248823", "pm_score": 2, "selected": false, "text": "resource \"aws_autoscaling_policy\" \"this\" {\n name = var.service_name # Same between `terraform` invocations.\n autoscaling_group_name = aws_autoscaling_group.this.name\n adjustment_type = \"ChangeInCapacity\"\n policy_type = \"TargetTrackingScaling\"\n # ASG merely serves as an EC2-ready-to-be-made-scalable, hence `false`.\n enabled = false\n target_tracking_configuration {\n predefined_metric_specification {\n predefined_metric_type = \"ASGAverageCPUUtilization\"\n }\n target_value = 99.0\n }\n\n lifecycle {\n ignore_changes = [\n adjustment_type\n ]\n }\n\n}\n" }, { "answer_id": 74437228, "author": "Martin Atkins", "author_id": 281848, "author_profile": "https://Stackoverflow.com/users/281848", "pm_score": 2, "selected": true, "text": "hashicorp/aws" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14305969/" ]
74,424,780
<p>Im using selenium-java 4.6.0 and Im capturing network traffic.When I try to import the selenium class for 'Network', I get several options :</p> <p>-org.openqa.selenium.devtools.v107.network.Network; -org.openqa.selenium.devtools.v106.network.Network; -etc...</p> <p>Is there a way to select always the last version available? Or another way to not to change with each new release the import version?</p>
[ { "answer_id": 74427390, "author": "Marcin", "author_id": 248823, "author_profile": "https://Stackoverflow.com/users/248823", "pm_score": 2, "selected": false, "text": "resource \"aws_autoscaling_policy\" \"this\" {\n name = var.service_name # Same between `terraform` invocations.\n autoscaling_group_name = aws_autoscaling_group.this.name\n adjustment_type = \"ChangeInCapacity\"\n policy_type = \"TargetTrackingScaling\"\n # ASG merely serves as an EC2-ready-to-be-made-scalable, hence `false`.\n enabled = false\n target_tracking_configuration {\n predefined_metric_specification {\n predefined_metric_type = \"ASGAverageCPUUtilization\"\n }\n target_value = 99.0\n }\n\n lifecycle {\n ignore_changes = [\n adjustment_type\n ]\n }\n\n}\n" }, { "answer_id": 74437228, "author": "Martin Atkins", "author_id": 281848, "author_profile": "https://Stackoverflow.com/users/281848", "pm_score": 2, "selected": true, "text": "hashicorp/aws" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6317663/" ]
74,424,796
<p>I want to create a progress bar in flutter which is like this <a href="https://i.stack.imgur.com/faVdV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/faVdV.png" alt="enter image description here" /></a></p> <p>I get the data of week from backend but I have to create it this way. and the icon on weeks or survey should be touchable.</p> <p>thanks in advance.</p>
[ { "answer_id": 74424887, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 0, "selected": false, "text": "Stepper" }, { "answer_id": 74425698, "author": "Stellar Creed", "author_id": 1723187, "author_profile": "https://Stackoverflow.com/users/1723187", "pm_score": 2, "selected": true, "text": "import 'package:flutter/material.dart';\n\nvoid main() {\n runApp(const MyApp());\n}\n\nclass MyApp extends StatelessWidget {\n const MyApp({super.key});\n\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n title: 'Example',\n theme: ThemeData(\n primarySwatch: Colors.blue,\n ),\n home: const HomePage(),\n );\n }\n}\n\nclass HomePage extends StatelessWidget {\n const HomePage({super.key});\n\n @override\n Widget build(BuildContext context) {\n List<String> points = [\n 'Survey',\n 'Week 1',\n 'Week 2',\n 'Week 3',\n 'Week 4',\n ];\n\n var lineWidth =\n MediaQuery.of(context).size.width - 16.0; // screen width - 2 * padding\n var space = lineWidth / points.length; //space between dots\n var currentSteps = 3; // <---- change this one\n\n return Scaffold(\n body: Padding(\n padding: const EdgeInsets.all(8.0),\n child: Center(\n child: SizedBox(\n height: 60.0,\n child: Stack(\n children: [\n //grey line\n Positioned(\n top: 15,\n left: 0,\n right: 0,\n child: Container(\n height: 2.0,\n width: double.infinity,\n color: Colors.grey,\n ),\n ),\n //red line\n Positioned(\n top: 15,\n left: 0,\n child: Container(\n height: 2.0,\n width: space * (currentSteps - 1) + space / 2,\n color: Colors.orange,\n ),\n ),\n //circles\n Row(\n children: points\n .asMap()\n .map((i, point) => MapEntry(\n i,\n SizedBox(\n width: space,\n child: Column(\n children: [\n Stack(\n children: [\n Container(\n height: 30.0,\n width: 30.0,\n decoration: BoxDecoration(\n shape: BoxShape.circle,\n border: Border.all(\n width: 1.5,\n color: i == currentSteps - 1\n ? Colors.orange\n : Colors.transparent,\n ),\n ),\n child: Center(\n child: Container(\n height: 20.0,\n width: 20.0,\n decoration: BoxDecoration(\n shape: BoxShape.circle,\n color: i < currentSteps\n ? Colors.orange\n : Colors.grey,\n ),\n ),\n ),\n ),\n if (i < currentSteps - 1)\n const SizedBox(\n height: 30.0,\n width: 30.0,\n child: Center(\n child: Icon(\n Icons.check,\n size: 16.0,\n color: Colors.white,\n ),\n ),\n ),\n ],\n ),\n const SizedBox(height: 4.0),\n Text(\n point,\n textAlign: TextAlign.left,\n style: TextStyle(\n color: i < currentSteps\n ? Colors.orange\n : Colors.grey,\n ),\n ),\n ],\n ),\n ),\n ))\n .values\n .toList(),\n ),\n ],\n ),\n ),\n ),\n ),\n );\n }\n}\n\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14729488/" ]
74,424,807
<p>I have a dataframe as a result of a pivot which has several thousand columns (representing time-boxed attributes). Below is a much shortened version for resemblance.</p> <pre><code>d = {'incount - 14:00': [1,'NaN', 1,1,'NaN','NaN','NaN','NaN',1], 'incount - 15:00': [2,1,2,'NaN','NaN','NaN',1,4,'NaN'], 'outcount - 14:00':[2,'NaN',1,1,1,1,2,2,1] 'outcount - 15:00':[2,2,1,1,'NaN',2,'NaN',1,1]} df = pd.DataFrame(data=d) </code></pre> <p>I want to replace the NaNs in columns that contain &quot;incount&quot; with 0 (leaving other columns untouched). I have tried the following but predictably it does not recognise the column name.</p> <pre><code>df['incount'] = df_all['incount'].fillna(0) </code></pre> <p>I need the ability to search the column names and only impact those containing a defined string.</p>
[ { "answer_id": 74424887, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 0, "selected": false, "text": "Stepper" }, { "answer_id": 74425698, "author": "Stellar Creed", "author_id": 1723187, "author_profile": "https://Stackoverflow.com/users/1723187", "pm_score": 2, "selected": true, "text": "import 'package:flutter/material.dart';\n\nvoid main() {\n runApp(const MyApp());\n}\n\nclass MyApp extends StatelessWidget {\n const MyApp({super.key});\n\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n title: 'Example',\n theme: ThemeData(\n primarySwatch: Colors.blue,\n ),\n home: const HomePage(),\n );\n }\n}\n\nclass HomePage extends StatelessWidget {\n const HomePage({super.key});\n\n @override\n Widget build(BuildContext context) {\n List<String> points = [\n 'Survey',\n 'Week 1',\n 'Week 2',\n 'Week 3',\n 'Week 4',\n ];\n\n var lineWidth =\n MediaQuery.of(context).size.width - 16.0; // screen width - 2 * padding\n var space = lineWidth / points.length; //space between dots\n var currentSteps = 3; // <---- change this one\n\n return Scaffold(\n body: Padding(\n padding: const EdgeInsets.all(8.0),\n child: Center(\n child: SizedBox(\n height: 60.0,\n child: Stack(\n children: [\n //grey line\n Positioned(\n top: 15,\n left: 0,\n right: 0,\n child: Container(\n height: 2.0,\n width: double.infinity,\n color: Colors.grey,\n ),\n ),\n //red line\n Positioned(\n top: 15,\n left: 0,\n child: Container(\n height: 2.0,\n width: space * (currentSteps - 1) + space / 2,\n color: Colors.orange,\n ),\n ),\n //circles\n Row(\n children: points\n .asMap()\n .map((i, point) => MapEntry(\n i,\n SizedBox(\n width: space,\n child: Column(\n children: [\n Stack(\n children: [\n Container(\n height: 30.0,\n width: 30.0,\n decoration: BoxDecoration(\n shape: BoxShape.circle,\n border: Border.all(\n width: 1.5,\n color: i == currentSteps - 1\n ? Colors.orange\n : Colors.transparent,\n ),\n ),\n child: Center(\n child: Container(\n height: 20.0,\n width: 20.0,\n decoration: BoxDecoration(\n shape: BoxShape.circle,\n color: i < currentSteps\n ? Colors.orange\n : Colors.grey,\n ),\n ),\n ),\n ),\n if (i < currentSteps - 1)\n const SizedBox(\n height: 30.0,\n width: 30.0,\n child: Center(\n child: Icon(\n Icons.check,\n size: 16.0,\n color: Colors.white,\n ),\n ),\n ),\n ],\n ),\n const SizedBox(height: 4.0),\n Text(\n point,\n textAlign: TextAlign.left,\n style: TextStyle(\n color: i < currentSteps\n ? Colors.orange\n : Colors.grey,\n ),\n ),\n ],\n ),\n ),\n ))\n .values\n .toList(),\n ),\n ],\n ),\n ),\n ),\n ),\n );\n }\n}\n\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20215078/" ]
74,424,811
<p>I am getting the error:</p> <blockquote> <p>Error Code: 3780. Referencing column 'category' and referenced column 'category_id' in foreign key constraint 'product_ibfk_1' are incompatible.</p> </blockquote> <pre><code>drop table if exists Provider; drop table if exists Category; drop table if exists Product; create table Provider ( privider_id serial not null primary key, login_password varchar(20) not null constraint passrule3 check(login_password sounds like '[A-Za-z0-9]{6,20}'), fathersname varchar(20) not null, name_of_contact_face varchar(10) not null, surname varchar(15), e_mail varchar(25) unique constraint emailrule2 check(e_mail sounds like '[A-Za-z0-9]{10,10})\@gmail.com\s?') ); create table Category ( title varchar(20), category_id serial not null primary key ); create table Product ( barecode serial not null primary key, provider_id bigint not null, manufacturer varchar(25) not null, category_id bigint not null, dimensions varchar(10) not null, amount int not null, date_of_registration datetime not null, #constraint 'provider_for_product' foreign key (provider_id) references Provider (provider_id) on delete restrict on update cascade, foreign key (category_id) references Category (category_id) on delete restrict on update cascade ); </code></pre>
[ { "answer_id": 74424887, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 0, "selected": false, "text": "Stepper" }, { "answer_id": 74425698, "author": "Stellar Creed", "author_id": 1723187, "author_profile": "https://Stackoverflow.com/users/1723187", "pm_score": 2, "selected": true, "text": "import 'package:flutter/material.dart';\n\nvoid main() {\n runApp(const MyApp());\n}\n\nclass MyApp extends StatelessWidget {\n const MyApp({super.key});\n\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n title: 'Example',\n theme: ThemeData(\n primarySwatch: Colors.blue,\n ),\n home: const HomePage(),\n );\n }\n}\n\nclass HomePage extends StatelessWidget {\n const HomePage({super.key});\n\n @override\n Widget build(BuildContext context) {\n List<String> points = [\n 'Survey',\n 'Week 1',\n 'Week 2',\n 'Week 3',\n 'Week 4',\n ];\n\n var lineWidth =\n MediaQuery.of(context).size.width - 16.0; // screen width - 2 * padding\n var space = lineWidth / points.length; //space between dots\n var currentSteps = 3; // <---- change this one\n\n return Scaffold(\n body: Padding(\n padding: const EdgeInsets.all(8.0),\n child: Center(\n child: SizedBox(\n height: 60.0,\n child: Stack(\n children: [\n //grey line\n Positioned(\n top: 15,\n left: 0,\n right: 0,\n child: Container(\n height: 2.0,\n width: double.infinity,\n color: Colors.grey,\n ),\n ),\n //red line\n Positioned(\n top: 15,\n left: 0,\n child: Container(\n height: 2.0,\n width: space * (currentSteps - 1) + space / 2,\n color: Colors.orange,\n ),\n ),\n //circles\n Row(\n children: points\n .asMap()\n .map((i, point) => MapEntry(\n i,\n SizedBox(\n width: space,\n child: Column(\n children: [\n Stack(\n children: [\n Container(\n height: 30.0,\n width: 30.0,\n decoration: BoxDecoration(\n shape: BoxShape.circle,\n border: Border.all(\n width: 1.5,\n color: i == currentSteps - 1\n ? Colors.orange\n : Colors.transparent,\n ),\n ),\n child: Center(\n child: Container(\n height: 20.0,\n width: 20.0,\n decoration: BoxDecoration(\n shape: BoxShape.circle,\n color: i < currentSteps\n ? Colors.orange\n : Colors.grey,\n ),\n ),\n ),\n ),\n if (i < currentSteps - 1)\n const SizedBox(\n height: 30.0,\n width: 30.0,\n child: Center(\n child: Icon(\n Icons.check,\n size: 16.0,\n color: Colors.white,\n ),\n ),\n ),\n ],\n ),\n const SizedBox(height: 4.0),\n Text(\n point,\n textAlign: TextAlign.left,\n style: TextStyle(\n color: i < currentSteps\n ? Colors.orange\n : Colors.grey,\n ),\n ),\n ],\n ),\n ),\n ))\n .values\n .toList(),\n ),\n ],\n ),\n ),\n ),\n ),\n );\n }\n}\n\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20493776/" ]
74,424,827
<h2>Explanation</h2> <p>I'm making <strong>program that use a <em>XML</em> file to save some values to use as settings</strong>, and <strong>only need to read and modify the element values</strong> in the <em>XML</em>. The <strong>code is written in <em>Java</em></strong> and I'm <strong>using <em><a href="http://www.jdom.org/downloads/" rel="nofollow noreferrer">JDOM 2.0.6.1</a></em></strong> to manage the <em>XML</em> file, followed <a href="https://www.tutorialspoint.com/java_xml/java_jdom_parser.htm" rel="nofollow noreferrer">this tutorial</a>.</p> <p><strong>The code works when overwrite any element in the XML, but just 1 time</strong>. If make <strong>multiple operations</strong> to modify any value, the program <strong>start appending a new tree with the changes</strong>, which should not happen and would be the problem.</p> <p>The default XML:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;settings&gt; &lt;time&gt; &lt;time-work&gt;25&lt;/time-work&gt; &lt;time-break&gt;5&lt;/time-break&gt; &lt;time-rest&gt;15&lt;/time-rest&gt; &lt;time-interval&gt;3&lt;/time-interval&gt; &lt;/time&gt; &lt;auto-start&gt; &lt;start-work&gt;true&lt;/start-work&gt; &lt;start-break&gt;true&lt;/start-break&gt; &lt;start-rest&gt;true&lt;/start-rest&gt; &lt;/auto-start&gt; &lt;/settings&gt; </code></pre> <p>The Java code:</p> <pre class="lang-java prettyprint-override"><code>public class FileHandler { private final Writer settingsWriter; private final XMLOutputter xmlOutput; private final Document settingsDoc; private final Element settingsElement; FileHandler() throws IOException, JDOMException { Path settingsPath = Paths.get(&quot;res/settings/settings.xml&quot;); File settingsFile = settingsPath.toFile(); boolean settingsExist = settingsFile.createNewFile(); settingsWriter = Channels.newWriter( FileChannel.open(settingsPath, StandardOpenOption.WRITE), StandardCharsets.UTF_8); xmlOutput = new XMLOutputter(); xmlOutput.setFormat(Format.getPrettyFormat()); if (settingsExist) createSettings(); SAXBuilder saxBuilder = new SAXBuilder(); settingsDoc = saxBuilder.build(settingsFile); settingsElement = settingsDoc.getRootElement(); setElementValue(&quot;time-work&quot;, &quot;5&quot;); setElementValue(&quot;time-work&quot;, &quot;10&quot;); setElementValue(&quot;time-work&quot;, &quot;30&quot;); } public void setElementValue(String element, String newValue) throws IOException, JDOMException { Element groupElement = settingsElement.getChild(element.startsWith(&quot;time&quot;)? &quot;time&quot;:&quot;auto-start&quot;), toChangeElement = groupElement.getChild(element); toChangeElement.setText(newValue); xmlOutput.output(settingsDoc, settingsWriter); } /*More code, irrelevant for the post*/ } </code></pre> <h2>Examples</h2> <h3>Example 1 (Works)</h3> <pre class="lang-java prettyprint-override"><code> FileHandler() throws IOException, JDOMException { Path settingsPath = Paths.get(&quot;res/settings/settings.xml&quot;); File settingsFile = settingsPath.toFile(); boolean settingsExist = settingsFile.createNewFile(); settingsWriter = Channels.newWriter( FileChannel.open(settingsPath, StandardOpenOption.WRITE), StandardCharsets.UTF_8); xmlOutput = new XMLOutputter(); xmlOutput.setFormat(Format.getPrettyFormat()); if (settingsExist) createSettings(); SAXBuilder saxBuilder = new SAXBuilder(); settingsDoc = saxBuilder.build(settingsFile); settingsElement = settingsDoc.getRootElement(); setElementValue(&quot;time-work&quot;, &quot;5&quot;); } </code></pre> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;settings&gt; &lt;time&gt; &lt;time-work&gt;5&lt;/time-work&gt; &lt;time-break&gt;5&lt;/time-break&gt; &lt;time-rest&gt;15&lt;/time-rest&gt; &lt;time-interval&gt;3&lt;/time-interval&gt; &lt;/time&gt; &lt;auto-start&gt; &lt;start-work&gt;true&lt;/start-work&gt; &lt;start-break&gt;true&lt;/start-break&gt; &lt;start-rest&gt;true&lt;/start-rest&gt; &lt;/auto-start&gt; &lt;/settings&gt; </code></pre> <h3>Example 2 (Works)</h3> <pre class="lang-java prettyprint-override"><code> FileHandler() throws IOException, JDOMException { Path settingsPath = Paths.get(&quot;res/settings/settings.xml&quot;); File settingsFile = settingsPath.toFile(); boolean settingsExist = settingsFile.createNewFile(); settingsWriter = Channels.newWriter( FileChannel.open(settingsPath, StandardOpenOption.WRITE), StandardCharsets.UTF_8); xmlOutput = new XMLOutputter(); xmlOutput.setFormat(Format.getPrettyFormat()); if (settingsExist) createSettings(); SAXBuilder saxBuilder = new SAXBuilder(); settingsDoc = saxBuilder.build(settingsFile); settingsElement = settingsDoc.getRootElement(); setElementValue(&quot;start-rest&quot;, &quot;2&quot;); } </code></pre> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;settings&gt; &lt;time&gt; &lt;time-work&gt;25&lt;/time-work&gt; &lt;time-break&gt;5&lt;/time-break&gt; &lt;time-rest&gt;15&lt;/time-rest&gt; &lt;time-interval&gt;3&lt;/time-interval&gt; &lt;/time&gt; &lt;auto-start&gt; &lt;start-work&gt;true&lt;/start-work&gt; &lt;start-break&gt;true&lt;/start-break&gt; &lt;start-rest&gt;2&lt;/start-rest&gt; &lt;/auto-start&gt; &lt;/settings&gt; </code></pre> <h3>Example 3 (Fail)</h3> <pre class="lang-java prettyprint-override"><code> FileHandler() throws IOException, JDOMException { Path settingsPath = Paths.get(&quot;res/settings/settings.xml&quot;); File settingsFile = settingsPath.toFile(); boolean settingsExist = settingsFile.createNewFile(); settingsWriter = Channels.newWriter( FileChannel.open(settingsPath, StandardOpenOption.WRITE), StandardCharsets.UTF_8); xmlOutput = new XMLOutputter(); xmlOutput.setFormat(Format.getPrettyFormat()); if (settingsExist) createSettings(); SAXBuilder saxBuilder = new SAXBuilder(); settingsDoc = saxBuilder.build(settingsFile); settingsElement = settingsDoc.getRootElement(); setElementValue(&quot;time-work&quot;, &quot;5&quot;); setElementValue(&quot;time-work&quot;, &quot;10&quot;); setElementValue(&quot;time-work&quot;, &quot;30&quot;); } </code></pre> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;settings&gt; &lt;time&gt; &lt;time-work&gt;5&lt;/time-work&gt; &lt;time-break&gt;5&lt;/time-break&gt; &lt;time-rest&gt;15&lt;/time-rest&gt; &lt;time-interval&gt;3&lt;/time-interval&gt; &lt;/time&gt; &lt;auto-start&gt; &lt;start-work&gt;true&lt;/start-work&gt; &lt;start-break&gt;true&lt;/start-break&gt; &lt;start-rest&gt;true&lt;/start-rest&gt; &lt;/auto-start&gt; &lt;/settings&gt; &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;settings&gt; &lt;time&gt; &lt;time-work&gt;10&lt;/time-work&gt; &lt;time-break&gt;5&lt;/time-break&gt; &lt;time-rest&gt;15&lt;/time-rest&gt; &lt;time-interval&gt;3&lt;/time-interval&gt; &lt;/time&gt; &lt;auto-start&gt; &lt;start-work&gt;true&lt;/start-work&gt; &lt;start-break&gt;true&lt;/start-break&gt; &lt;start-rest&gt;true&lt;/start-rest&gt; &lt;/auto-start&gt; &lt;/settings&gt; &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;settings&gt; &lt;time&gt; &lt;time-work&gt;30&lt;/time-work&gt; &lt;time-break&gt;5&lt;/time-break&gt; &lt;time-rest&gt;15&lt;/time-rest&gt; &lt;time-interval&gt;3&lt;/time-interval&gt; &lt;/time&gt; &lt;auto-start&gt; &lt;start-work&gt;true&lt;/start-work&gt; &lt;start-break&gt;true&lt;/start-break&gt; &lt;start-rest&gt;true&lt;/start-rest&gt; &lt;/auto-start&gt; &lt;/settings&gt; </code></pre> <h3>Example 4 (Fail)</h3> <pre class="lang-java prettyprint-override"><code> FileHandler() throws IOException, JDOMException { Path settingsPath = Paths.get(&quot;res/settings/settings.xml&quot;); File settingsFile = settingsPath.toFile(); boolean settingsExist = settingsFile.createNewFile(); settingsWriter = Channels.newWriter( FileChannel.open(settingsPath, StandardOpenOption.WRITE), StandardCharsets.UTF_8); xmlOutput = new XMLOutputter(); xmlOutput.setFormat(Format.getPrettyFormat()); if (settingsExist) createSettings(); SAXBuilder saxBuilder = new SAXBuilder(); settingsDoc = saxBuilder.build(settingsFile); settingsElement = settingsDoc.getRootElement(); setElementValue(&quot;time-work&quot;, &quot;5&quot;); setElementValue(&quot;time-break&quot;, &quot;10&quot;); setElementValue(&quot;time-rest&quot;, &quot;30&quot;); } </code></pre> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;settings&gt; &lt;time&gt; &lt;time-work&gt;5&lt;/time-work&gt; &lt;time-break&gt;5&lt;/time-break&gt; &lt;time-rest&gt;15&lt;/time-rest&gt; &lt;time-interval&gt;3&lt;/time-interval&gt; &lt;/time&gt; &lt;auto-start&gt; &lt;start-work&gt;true&lt;/start-work&gt; &lt;start-break&gt;true&lt;/start-break&gt; &lt;start-rest&gt;true&lt;/start-rest&gt; &lt;/auto-start&gt; &lt;/settings&gt; &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;settings&gt; &lt;time&gt; &lt;time-work&gt;5&lt;/time-work&gt; &lt;time-break&gt;10&lt;/time-break&gt; &lt;time-rest&gt;15&lt;/time-rest&gt; &lt;time-interval&gt;3&lt;/time-interval&gt; &lt;/time&gt; &lt;auto-start&gt; &lt;start-work&gt;true&lt;/start-work&gt; &lt;start-break&gt;true&lt;/start-break&gt; &lt;start-rest&gt;true&lt;/start-rest&gt; &lt;/auto-start&gt; &lt;/settings&gt; &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;settings&gt; &lt;time&gt; &lt;time-work&gt;5&lt;/time-work&gt; &lt;time-break&gt;10&lt;/time-break&gt; &lt;time-rest&gt;30&lt;/time-rest&gt; &lt;time-interval&gt;3&lt;/time-interval&gt; &lt;/time&gt; &lt;auto-start&gt; &lt;start-work&gt;true&lt;/start-work&gt; &lt;start-break&gt;true&lt;/start-break&gt; &lt;start-rest&gt;true&lt;/start-rest&gt; &lt;/auto-start&gt; &lt;/settings&gt; </code></pre> <h3>Example 5 (Fail)</h3> <pre class="lang-java prettyprint-override"><code> FileHandler() throws IOException, JDOMException { Path settingsPath = Paths.get(&quot;res/settings/settings.xml&quot;); File settingsFile = settingsPath.toFile(); boolean settingsExist = settingsFile.createNewFile(); settingsWriter = Channels.newWriter( FileChannel.open(settingsPath, StandardOpenOption.WRITE), StandardCharsets.UTF_8); xmlOutput = new XMLOutputter(); xmlOutput.setFormat(Format.getPrettyFormat()); if (settingsExist) createSettings(); SAXBuilder saxBuilder = new SAXBuilder(); settingsDoc = saxBuilder.build(settingsFile); settingsElement = settingsDoc.getRootElement(); setElementValue(&quot;time-work&quot;, &quot;5&quot;); setElementValue(&quot;start-break&quot;, &quot;false&quot;); setElementValue(&quot;time-interval&quot;, &quot;2&quot;); } </code></pre> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;settings&gt; &lt;time&gt; &lt;time-work&gt;5&lt;/time-work&gt; &lt;time-break&gt;5&lt;/time-break&gt; &lt;time-rest&gt;15&lt;/time-rest&gt; &lt;time-interval&gt;3&lt;/time-interval&gt; &lt;/time&gt; &lt;auto-start&gt; &lt;start-work&gt;true&lt;/start-work&gt; &lt;start-break&gt;true&lt;/start-break&gt; &lt;start-rest&gt;true&lt;/start-rest&gt; &lt;/auto-start&gt; &lt;/settings&gt; &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;settings&gt; &lt;time&gt; &lt;time-work&gt;5&lt;/time-work&gt; &lt;time-break&gt;5&lt;/time-break&gt; &lt;time-rest&gt;15&lt;/time-rest&gt; &lt;time-interval&gt;3&lt;/time-interval&gt; &lt;/time&gt; &lt;auto-start&gt; &lt;start-work&gt;true&lt;/start-work&gt; &lt;start-break&gt;false&lt;/start-break&gt; &lt;start-rest&gt;true&lt;/start-rest&gt; &lt;/auto-start&gt; &lt;/settings&gt; &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;settings&gt; &lt;time&gt; &lt;time-work&gt;5&lt;/time-work&gt; &lt;time-break&gt;5&lt;/time-break&gt; &lt;time-rest&gt;15&lt;/time-rest&gt; &lt;time-interval&gt;2&lt;/time-interval&gt; &lt;/time&gt; &lt;auto-start&gt; &lt;start-work&gt;true&lt;/start-work&gt; &lt;start-break&gt;false&lt;/start-break&gt; &lt;start-rest&gt;true&lt;/start-rest&gt; &lt;/auto-start&gt; &lt;/settings&gt; </code></pre> <h2>What I tried</h2> <p>Tried to close the writer and use re-building the &quot;<em>Document <strong>settingsDoc</strong></em>&quot; inside the function.</p> <p>Everything I tried ended in the same result, appending a new <em>XML</em> tree <strong>after overwriting just 1</strong>.</p>
[ { "answer_id": 74428874, "author": "Michael Kay", "author_id": 415448, "author_profile": "https://Stackoverflow.com/users/415448", "pm_score": 1, "selected": false, "text": "setElementValue()" }, { "answer_id": 74438345, "author": "Cromega08", "author_id": 18646685, "author_profile": "https://Stackoverflow.com/users/18646685", "pm_score": 1, "selected": true, "text": "public class FileHandler {\n\n private final Writer settingsWriter;\n private final XMLOutputter xmlOutput;\n private final Document settingsDoc;\n private final Element settingsElement;\n private final FileChannel settingsChannel;\n private final Path settingsPath;\n\n\n FileHandler() throws IOException, JDOMException {\n\n settingsPath = Paths.get(\"res/settings/settings.xml\");\n File settingsFile = settingsPath.toFile();\n boolean settingsExist = settingsFile.createNewFile();\n settingsChannel = FileChannel.open(settingsPath, StandardOpenOption.WRITE);\n settingsWriter = Channels.newWriter(\n settingsChannel,\n StandardCharsets.UTF_8);\n xmlOutput = new XMLOutputter();\n xmlOutput.setFormat(Format.getPrettyFormat());\n\n if (settingsExist) createSettings();\n\n SAXBuilder saxBuilder = new SAXBuilder();\n settingsDoc = saxBuilder.build(settingsFile);\n settingsElement = settingsDoc.getRootElement();\n }\n\n /*Irrelevant code for the answer*/\n\n public void setElementValues(boolean[] newStart, String[] newTexts) throws IOException, JDOMException {\n\n Element timeElement = settingsElement.getChild(\"time\"),\n autoStartElement = settingsElement.getChild(\"auto-start\");\n List<Element> timeElements = timeElement.getChildren(),\n autoStartElements = autoStartElement.getChildren();\n\n for (int index = 0; index < autoStartElements.size(); ++index) {\n autoStartElements.get(index).setText(String.valueOf(newStart[index]));\n }\n\n for (int index = 0; index < timeElements.size(); ++index) {\n timeElements.get(index).setText(newTexts[index]);\n }\n\n settingsChannel.truncate(0);\n settingsWriter.flush();\n settingsChannel.force(true);\n xmlOutput.output(settingsDoc, settingsWriter);\n settingsWriter.flush();\n settingsChannel.force(true);\n }\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18646685/" ]
74,424,840
<p>Below is my review.html.erb:</p> <pre><code>&lt;% provide(:title, 'All reviews') %&gt; &lt;h1&gt;All reviews&lt;/h1&gt; &lt;ol class=&quot;reviews&quot;&gt; &lt;%= render @reviews %&gt; &lt;/ol&gt; &lt;%= will_paginate @reviews %&gt; </code></pre> <p>And my _review.html.erb looks like:</p> <pre><code>&lt;li&gt; &lt;p&gt;Student: &lt;%= Student.find(review.student_id).name%&gt;&lt;/p&gt; &lt;p&gt;Score: &lt;%= review.score%&gt;&lt;/p&gt; &lt;p&gt;Review: &lt;%= review.review%&gt;&lt;/p&gt; &lt;p&gt;Created at: &lt;%= review.created_at%&gt;&lt;/p&gt; &lt;/li&gt; </code></pre> <p>How can I pass @students as well to render for example?</p> <p>I tried &lt;%= render @reviews, @students %&gt; in review.html.erb and <p>Student: &lt;%= student.name%&gt;</p> in _review.html.erb. It didn't work.</p>
[ { "answer_id": 74428544, "author": "LihnNguyen", "author_id": 15527415, "author_profile": "https://Stackoverflow.com/users/15527415", "pm_score": -1, "selected": false, "text": "_review.html.erb " }, { "answer_id": 74432754, "author": "max", "author_id": 544825, "author_profile": "https://Stackoverflow.com/users/544825", "pm_score": 2, "selected": false, "text": "class Student < ApplicationRecord\n has_many :reviews\nend\n\nclass Review < ApplicationRecord\n belongs_to :student\n # optional but avoids a law of demeter violation\n delegate :name, to: :student, prefix: true\nend\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17257723/" ]
74,424,842
<p>Fairly new to python, I have been struggling with creating a calculated column based off of the variable values of each item.</p> <p>I Have this table below with DF being the dataframe name</p> <p><a href="https://i.stack.imgur.com/08DKR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/08DKR.png" alt="enter image description here" /></a></p> <p>I am trying to create a 'PE Comp' Column that gets the PE value for each ticker, and divides it by the **Industry ** average PE Ratio.</p> <p>My most successful attempt required me creating a .groupby industry dataframe (<strong>y</strong>) which has calculated the mean per industry. These numbers are correct. Once I did that I created this code block:</p> <pre><code>for i in DF['Industry']: DF['PE Comp'] = DF['PE Ratio'] / y.loc[i,'PE Ratio'] </code></pre> <p>However the numbers are coming out incorrect. I've tested this and the y.loc divisor is working fine with the right numbers, meaning that the issue is coming from the dividend.</p> <p>Any suggestions on how I can overcome this?</p> <p>Thanks in advance!</p>
[ { "answer_id": 74424976, "author": "Rawson", "author_id": 18571565, "author_profile": "https://Stackoverflow.com/users/18571565", "pm_score": 2, "selected": true, "text": "PE Ratio" }, { "answer_id": 74425007, "author": "Eloi", "author_id": 11591599, "author_profile": "https://Stackoverflow.com/users/11591599", "pm_score": 0, "selected": false, "text": "df['PE comp'] = df['PE ratio'] / y.loc[df['Industry']].value\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20427838/" ]
74,424,846
<p>Is there a way to remove entries from a counter object if the value matches a certain condition. For example:</p> <pre><code>Counter({'a': 1142,'b':1004,'c':100,'d':5}) </code></pre> <p>I want to drop all indexes where it is less than 1000, so I just have 'a' and 'b' left. I know I can loop through each and then delete if it doesnt match the condition as shown in this <a href="https://stackoverflow.com/questions/7154312/how-do-i-remove-entries-within-a-counter-object-with-a-loop-without-invoking-a-r">solution</a>. Just looking for a more efficient way.</p>
[ { "answer_id": 74424872, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 0, "selected": false, "text": "from collections import Counter\n\nc = Counter({'a': 1142,'b':1004,'c':100,'d':5})\n\nfor k in list(c):\n if c[k] < 1000:\n del c[k]\n\nprint(c)\n" }, { "answer_id": 74424874, "author": "Amirhossein Sefati", "author_id": 11856099, "author_profile": "https://Stackoverflow.com/users/11856099", "pm_score": 2, "selected": true, "text": "from collections import Counter\ncounter = Counter({'a': 1142, 'b': 1004, 'c': 100, 'd':5})\nCounter({k: c for k, c in counter.items() if c >= 1000})\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5137645/" ]
74,424,848
<pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.css&quot;&gt; &lt;title&gt;Contact Us&lt;/title&gt; &lt;style&gt; *{ margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; } .hero { width: 100%; height: 100vh; background-image: linear-gradient(black 0%, black 34%, white 34%, white 100%); position: relative; padding: 0 5%; display: flex; align-items: center; justify-content: center; overflow: auto; } nav { width: 100%; position: absolute; top: 0; left: 0; padding: 20px 8%; display: flex; align-items: center; justify-content: space-between; } nav .logo { width: 100px; margin-left: -80px; } nav ul li { list-style: none; display: inline-block; margin-left: 40px; } nav ul li a { text-decoration: none; color: #fff; font-size: 17px; } .content { text-align: left; } .content h1{ font-size: 70px; color: rgb(255, 255, 255); font-weight: 600; transition: 0.5s; margin-bottom: 700px; } .content h1:hover{ -webkit-text-stroke: 2px #fff; color: transparent; } .banner { position: relative; width: 90%; margin: 50px auto; } .heading { position: absolute; top: 50%; width: 50%; margin-top: -400px; margin-left: 650px; text-align: center; font-size: 3rem; } .food{ width: 400px; position:absolute; margin-top: -500px; margin-left: 580px; opacity: 0.4; transition: opacity .3s ease; background-color: rgba(0,0,0,0.6); } .contact-info{ display: inline; width: 100%; max-width: 1200px; align-items: center; justify-content: center; padding: 0 20px; margin-top: 320px; } .card{ background: #fff; padding: 0 20px; margin: 0 10px; width: calc(33% - 20px); height: 200px; display: flex; flex-direction: column; justify-content: center; align-items: center; color: rgb(0, 0, 0); cursor: pointer; } .card-icon{ font-size: 28px; background: #ff6348; width: 60px; height: 60px; text-align: center; line-height: 60px !important; border-radius: 50%; transition: 0.3s linear; } .card:hover .card-icon{ background: none; color: #ff6348; transform: scale(1.6); } .card p{ margin-top: 20px; font-weight: 300; letter-spacing: 2px; max-height: 0; opacity: 0; transition: 0.3s linear; } .card:hover p{ max-height: 40px; opacity: 1; } .contact{ position: relative; min-height: 100vh; padding: 50px 100px; display: inline; justify-content: center; align-items: center; flex-direction: column; } .contactform { width: 500px; padding: 10px; background: #fff; margin-top: 280px; } .contatform h2 { font-size: 30px; color: #333; font-weight: 500; } .contactform .inputBox{ position: relative; width: 100%; margin-top: 10px; } .contactform .inputBox input, .contactform .inputBox textarea{ width: 100%; padding: 5px 0; font-size: 16px; margin: 10px 0; border: none; border-bottom: 2px solid #333; outline: none; resize: none; } .contactform .inputBox input [type=&quot;submit&quot;] { width: 100px; background: #00bcd4; color: #fff; border: none; cursor: pointer; padding: 10px; font-size: 18px; } .map iframe { width: 300px; height: 400px; display: flex; flex-direction: row; margin-top: 100px; } @media (max-width: 991px) { .contact{ padding:50px; } .container { flex-direction: column; } .container .contact-info2 { margin-bottom: 40PX; } .container .contact-info2, .contatform{ width: 100%; } } @media screen and (max-width:800px) { .contact-info{ flex-direction: column; } .card{ width: 100%; max-width: 300px; margin: 10px 0; } } footer { text-align: center; background-color: rgb(29, 17, 17); color: #fff; padding: 12px; position: absolute; bottom: 0; width: 100%; margin-top: 40px; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class=&quot;hero&quot;&gt; &lt;nav&gt; &lt;img src=&quot;logo.png&quot; class=&quot;logo&quot;&gt; &lt;ul&gt; &lt;li&gt;&lt;a href=&quot;Turkish_grill2.html&quot;&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;photos.html&quot;&gt;Photos&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;menu.html&quot;&gt;Menu&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;contact.html&quot;&gt;Contact Us&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;div class=&quot;content&quot;&gt; &lt;div class =&quot;row&quot;&gt; &lt;div class = &quot;banner&quot;&gt; &lt;img class=&quot;food&quot; src=&quot;food.jpeg&quot; alt=&quot;[food]&quot;&gt; &lt;h1 class =&quot;heading&quot;&gt;Contact Us&lt;/h1&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;contact-info&quot;&gt; &lt;div class=&quot;card&quot;&gt; &lt;i class=&quot;card-icon far fa-envelope&quot;&gt;&lt;/i&gt; &lt;p&gt;&lt;a href=&quot;mailto:Mehmet.under@gmail.com&quot;&gt;Mehmet.under@gmail.com&lt;/a&gt;&lt;/p&gt; &lt;/div&gt; &lt;div class=&quot;card&quot;&gt; &lt;i class=&quot;card-icon fas fa-phone&quot;&gt;&lt;/i&gt; &lt;p&gt;+4799221199&lt;/p&gt; &lt;/div&gt; &lt;div class=&quot;card&quot;&gt; &lt;i class=&quot;card-icon fas fa-map-marker-alt&quot;&gt;&lt;/i&gt; &lt;p&gt;Karl Johans gate 5, 0154 OSLO&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;map&quot;&gt; &lt;iframe src=&quot;https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d2000.2351438173973!2d10. 746176751774849!3d59.911644771148914!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x46416e89e0be32c5% 3A0xa9aad198e39ddef9!2sKarl%20Johans%20gate%205%2C%200154%20Oslo!5e0!3m2!1sno!2sno!4v1667850923403!5m2!1sno!2sno&quot; style=&quot;border:0;&quot; allowfullscreen=&quot;&quot; loading=&quot;lazy&quot; referrerpolicy=&quot;no-referrer-when-downgrade&quot;&gt; &lt;/iframe&gt; &lt;/div&gt; &lt;section class=&quot;contact&quot;&gt; &lt;div class=&quot;contactform&quot;&gt; &lt;form action=&quot;&quot;&gt; &lt;h2&gt;Send Message&lt;/h2&gt; &lt;div class=&quot;inputBox&quot;&gt; &lt;input type=&quot;text&quot; name=&quot;&quot; placeholder= &quot;Full Name&quot; required=&quot;required&quot;&gt; &lt;/div&gt; &lt;div class=&quot;inputBox&quot;&gt; &lt;input type=&quot;text&quot; name=&quot;&quot; placeholder=&quot;Email&quot; required=&quot;required&quot;&gt; &lt;/div&gt; &lt;div class=&quot;inputBox&quot;&gt; &lt;textarea placeholder=&quot;Type Your Message&quot; required=&quot;required&quot;&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;div class=&quot;inputBox&quot;&gt; &lt;input type=&quot;submit&quot; name=&quot;&quot; value=&quot;Send&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/section&gt; &lt;footer&gt; &lt;p&gt;Just Turkey Grill is a 501c(3) organization, and your contributions are tax deductible.&lt;/p&gt; &lt;p id=&quot;copyright&quot;&gt;Copyright &amp;copy; 2022 by the Just Turkey Grill. Questions? &lt;a href=&quot;mailto:Mehmet.under@gmail.com&quot; &gt;Mail Mehmet Under.&lt;/a&gt;&lt;/p&gt; &lt;/footer&gt; &lt;!-- footer --&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I did nothing special. The first second it worked and the other, it stopped being clickable. I need help straight away because I have to give in this task about 2 hours. The only thing I changed was the section area, but nothing more. I just changed the form and added back the map, and changed and added more css code.</p>
[ { "answer_id": 74424872, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 0, "selected": false, "text": "from collections import Counter\n\nc = Counter({'a': 1142,'b':1004,'c':100,'d':5})\n\nfor k in list(c):\n if c[k] < 1000:\n del c[k]\n\nprint(c)\n" }, { "answer_id": 74424874, "author": "Amirhossein Sefati", "author_id": 11856099, "author_profile": "https://Stackoverflow.com/users/11856099", "pm_score": 2, "selected": true, "text": "from collections import Counter\ncounter = Counter({'a': 1142, 'b': 1004, 'c': 100, 'd':5})\nCounter({k: c for k, c in counter.items() if c >= 1000})\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20461001/" ]
74,424,878
<p>I started learning Thymeleaf templating with SpringBoot and my learning path was blocked by some implicit issue i could not find....</p> <p>The issue is: SpringBoot app does not see template, although:</p> <ol> <li><p>Controller looks like <a href="https://i.stack.imgur.com/s4wQJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/s4wQJ.png" alt="enter image description here" /></a></p> </li> <li><p>Project structure includes /templates:</p> </li> </ol> <p><a href="https://i.stack.imgur.com/1ZBZe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1ZBZe.png" alt="enter image description here" /></a></p> <ol start="3"> <li>All required dependencies are in place:</li> </ol> <p><a href="https://i.stack.imgur.com/1PsPQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1PsPQ.png" alt="enter image description here" /></a></p> <p>Spring Boot log:</p> <blockquote> <p>2022-11-13 22:21:13.196 INFO 20644 --- [ main] com.coffeeshop.Application : Starting Application using Java 11.0.10 on LAPTOP-O6B9USVI with PID 20644 (C:\Dev\Java\Projects\coffeeshop\build\classes\java\main started by User in C:\Dev\Java\Projects\coffeeshop) 2022-11-13 22:21:13.196 INFO 20644 --- [ main] com.coffeeshop.Application : No active profile set, falling back to 1 default profile: &quot;default&quot; 2022-11-13 22:21:13.588 INFO 20644 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode. 2022-11-13 22:21:13.604 INFO 20644 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 23 ms. Found 1 JPA repository interfaces. 2022-11-13 22:21:14.106 INFO 20644 --- [<br /> main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8081 (http) 2022-11-13 22:21:14.106 INFO 20644 --- [<br /> main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2022-11-13 22:21:14.106 INFO 20644 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.64] 2022-11-13 22:21:14.184 INFO 20644 --- [<br /> main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2022-11-13 22:21:14.184 INFO 20644 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 957 ms 2022-11-13 22:21:14.278 INFO 20644 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default] 2022-11-13 22:21:14.309 INFO 20644 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.9.Final 2022-11-13 22:21:14.309 INFO 20644 --- [ main] org.hibernate.cfg.Environment : HHH000205: Loaded properties from resource hibernate.properties: {hibernate.temp.use_jdbc_metadata_defaults=false, hibernate.bytecode.use_reflection_optimizer=false} 2022-11-13 22:21:14.404 INFO 20644 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final} 2022-11-13 22:21:14.466 INFO 20644 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect 2022-11-13 22:21:14.796 INFO 20644 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting... 2022-11-13 22:21:14.905 INFO 20644 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed. 2022-11-13 22:21:14.921 INFO 20644 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform] 2022-11-13 22:21:14.921 INFO 20644 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default' 2022-11-13 22:21:15.094 WARN 20644 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning 2022-11-13 22:21:15.298 INFO 20644 --- [<br /> main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8081 (http) with context path '' 2022-11-13 22:21:15.298 INFO 20644 --- [ main] com.coffeeshop.Application<br /> : Started Application in 2.409 seconds (JVM running for 2.7)</p> </blockquote> <p>When i check http://localhost:8081/home I got &quot;home&quot; string only.</p>
[ { "answer_id": 74424962, "author": "void void", "author_id": 18969611, "author_profile": "https://Stackoverflow.com/users/18969611", "pm_score": 3, "selected": true, "text": "@RestController" }, { "answer_id": 74426889, "author": "el idrissi oussama", "author_id": 15908297, "author_profile": "https://Stackoverflow.com/users/15908297", "pm_score": 1, "selected": false, "text": "@Controller\npublic class AppController {\n\n @GetMapping(\"/\")\n public String viewHomePage() {\n return \"home\";\n }\n\n}\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3292527/" ]
74,424,933
<p>I'm trying to create a simple search bar animation, more specifically, when hovering over the bar, the search history pops up. However, when I try .search-bar-input:hover + .search-history, code doesn't work. I'm new to html, so it's possible it's a basic bug - but I can't find an answer anywhere</p> <pre><code>&lt;div class=&quot;search-bar&quot;&gt; &lt;form class=&quot;search-form&quot; autocomplete=&quot;off&quot;&gt; &lt;input type=&quot;text&quot; class=&quot;search-bar-input&quot; name=&quot;search-request&quot; placeholder=&quot;Type here...&quot; required minlength=&quot;4&quot; maxlength=&quot;32&quot;&gt; &lt;/form&gt; &lt;div class=&quot;search-history&quot;&gt; search history &lt;/div&gt; &lt;/div&gt; </code></pre> <pre><code>.search-bar-input { text-align: center; height: 50px; width: 150px; margin: auto; } .search-bar-input:hover { border: solid 2px lightgrey; outline: none; } .search-history { display: none; height: 50px; width: 150px; background-color: rgb(226, 226, 226); } .search-bar-input:hover + .search-history { display: block; } .search-history:hover { display: block; } </code></pre>
[ { "answer_id": 74424962, "author": "void void", "author_id": 18969611, "author_profile": "https://Stackoverflow.com/users/18969611", "pm_score": 3, "selected": true, "text": "@RestController" }, { "answer_id": 74426889, "author": "el idrissi oussama", "author_id": 15908297, "author_profile": "https://Stackoverflow.com/users/15908297", "pm_score": 1, "selected": false, "text": "@Controller\npublic class AppController {\n\n @GetMapping(\"/\")\n public String viewHomePage() {\n return \"home\";\n }\n\n}\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20495411/" ]
74,424,945
<p>Full Error: InvalidOperationException: Cannot get the value of a token type 'Number' as a string. System.Text.Json.Utf8JsonReader.GetString()</p> <p>JsonException: The JSON value could not be converted to System.String. Path: $[0].status | LineNumber: 0 | BytePositionInLine: 197. System.Text.Json.ThrowHelper.ReThrowWithPath(ref ReadStack state, ref Utf8JsonReader reader, Exception ex)</p> <p>I have MVC project that is trying consume Web API that is working correctly. Now, there is <code>HouseController.cs</code></p> <pre><code>using Microsoft.AspNetCore.Mvc; using Task3.Controllers.Services; namespace Task3.Controllers; public class HouseController : Controller {     private readonly IHouseService _service;     public HouseController(IHouseService service)     {         _service = service ?? throw new ArgumentNullException(nameof(service));     }     public async Task&lt;IActionResult&gt; Index()     {         var houses = await _service.Find();         return View(houses);     } } </code></pre> <p>that is calling <code>Find()</code> method in interface <code>IHouseService</code></p> <pre><code>using Task3.Models; namespace Task3.Controllers.Services {     public interface IHouseService     {         Task&lt;IEnumerable&lt;HouseModel&gt;&gt; Find();     } } </code></pre> <p>that in its turn calls the same method in <code>HouseService.cs</code></p> <pre><code>using Task3.Controllers.Helper; using Task3.Models; namespace Task3.Controllers.Services {     public class HouseService : IHouseService     {         private readonly HttpClient _client;         public const string BasePath = &quot;/api/Houses&quot;;         public HouseService(HttpClient client)         {             _client = client ?? throw new ArgumentNullException(nameof(client));         }         public async Task&lt;IEnumerable&lt;HouseModel&gt;&gt; Find()         {             var response = await _client.GetAsync(BasePath);             return await response.ReadContentAsync&lt;List&lt;HouseModel&gt;&gt;();         }     } } </code></pre> <p>which calls <code>ReadContentAsync&lt;List&lt;HouseModel&gt;&gt;()</code></p> <pre><code>using Newtonsoft.Json; using JsonSerializer = System.Text.Json.JsonSerializer; namespace Task3.Controllers.Helper {     public static class HttpClientExtensions     {         public static async Task&lt;T&gt; ReadContentAsync&lt;T&gt;(this HttpResponseMessage response)         {             if (response.IsSuccessStatusCode == false)                 throw new ApplicationException($&quot;Something went wrong calling the API: {response.ReasonPhrase}&quot;);             var dataAsString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);             Console.WriteLine(dataAsString);             var result = JsonSerializer.Deserialize&lt;T&gt;(dataAsString);             return result;         }     } } </code></pre> <p>and the line with <code>Deserialize&lt;T&gt;</code> returns the before mentioned error.</p> <p>What I tried is obviously debugging, the <code>Deserialize&lt;T&gt;</code> method, besides returning error, returns null 'cause it apparently cannot convert Json result to Model attributes. Here is <code>HouseModel</code></p> <pre><code>namespace Task3.Models; public class HouseModel {     public string Price { get; set; }     public string Region { get; set; }     public string PublicationDate { get; set; }     public string GeoLat { get; set; }     public string GeoLon { get; set; }     public string BuildingType { get; set; }     public string Area { get; set; }     public string Rooms { get; set; }     public string FloorNum { get; set; }     public string TotalFloor { get; set; }     public string ObjectType { get; set; }     public string Id { get; set; }     public string status { get; set; }     public string Photo { get; set; } } </code></pre> <p>Btw, before that <code>HouseModel</code> attributes were int, DateTime etc. and the error was cannot convert to Int32.</p> <p>Also I used custom Converter <code>StringConverter</code></p> <pre><code>public class StringConverter : System.Text.Json.Serialization.JsonConverter&lt;string&gt;         {             public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)             {                 if (reader.TokenType == JsonTokenType.Number)                 {                     var stringValue = reader.GetInt32();                     stringValue = stringValue;                     return stringValue.ToString();                 }                 else if (reader.TokenType == JsonTokenType.String)                 {                     return reader.GetString();                 }                 throw new System.Text.Json.JsonException();             }             public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)             {                 writer.WriteStringValue(value);             }         } </code></pre> <p>but in that case every entry is <code>null</code>.</p> <p>Can anybody share some insight?</p>
[ { "answer_id": 74424962, "author": "void void", "author_id": 18969611, "author_profile": "https://Stackoverflow.com/users/18969611", "pm_score": 3, "selected": true, "text": "@RestController" }, { "answer_id": 74426889, "author": "el idrissi oussama", "author_id": 15908297, "author_profile": "https://Stackoverflow.com/users/15908297", "pm_score": 1, "selected": false, "text": "@Controller\npublic class AppController {\n\n @GetMapping(\"/\")\n public String viewHomePage() {\n return \"home\";\n }\n\n}\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19509283/" ]
74,424,963
<p>I want to get <code>&lt;a&gt;</code> element of html. I use xPath <code>/html/body/nav/div/a</code> but not correct. Someone know how I get the <code>Example text</code> ?</p> <pre><code>&lt;nav class=&quot;navbar navbar-expand-xl&quot; id=&quot;menu&quot;&gt; &lt;div&gt; &lt;a&gt; &lt;i class=&quot;fas fa-user mr-2&quot;&gt;&lt;/i&gt; Example text &lt;/a&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 74425146, "author": "Shaman Technology", "author_id": 15475207, "author_profile": "https://Stackoverflow.com/users/15475207", "pm_score": -1, "selected": false, "text": "<i class=\"fas fa-user mr-2\"> Example text </i>\n" }, { "answer_id": 74437861, "author": "Markus Zeller", "author_id": 2645713, "author_profile": "https://Stackoverflow.com/users/2645713", "pm_score": 0, "selected": false, "text": "$html = <<<'_HTML'\n<nav class=\"navbar navbar-expand-xl\" id=\"menu\">\n <div>\n <a><i class=\"fas fa-user mr-2\"></i>Example text</a>\n </div>\n</nav>\n_HTML;\n\nlibxml_use_internal_errors(true);\n$doc = new DOMDocument();\n$doc->loadHTML($html);\n\n// parsing the elements\n$nav = $doc->getElementById('menu');\n$text = $nav->getElementsByTagName('a')->item(0)->nodeValue;\necho $text;\n\n// using xpath\n$xpath = new DOMXPath($doc);\n$text = $xpath->query('//nav[@id=\"menu\"]/div/a')->item(0)->nodeValue;\necho $text;\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20409409/" ]
74,424,989
<p>I have a dataFrame containing a column of names and I want to extract the last name and make that a new column. However, I am running into a problem.</p> <p>Here is a toy example of my dataframe:</p> <pre><code> Candidate_Name Party State District Office Year Img_URL 961 Heather Mizeur D Maryland 1 House 2022 https://images.ctfassets.net/00vgtve3ank7/3v1O... 962 Heidi Campbell D Tennessee 5 House 2022 https://images.ctfassets.net/00vgtve3ank7/BbSQ... 963 Helen Brady R Massachusetts 9 House 2020 https://images.ctfassets.net/00vgtve3ank7/6WmS... 964 Henry Cuellar D Texas 28 House 2022 https://images.ctfassets.net/00vgtve3ank7/4GGP... 965 Henry Cuellar D Texas 28 House 2020 https://images.ctfassets.net/00vgtve3ank7/3xNd... 966 Henry Cuellar D Texas 28 House 2018 https://images.ctfassets.net/00vgtve3ank7/uCK7... 967 Henry Martin D Missouri 6 House 2022 https://images.ctfassets.net/00vgtve3ank7/5rfd... 968 Henry Robert Martin D Missouri 6 House 2018 https://images.ctfassets.net/00vgtve3ank7/MvL8... 969 Herb Jones D Virginia 1 House 2022 https://images.ctfassets.net/00vgtve3ank7/47Uy... 970 Herman West Jr. R Georgia 2 House 2018 https://images.ctfassets.net/00vgtve3ank7/534y... 971 Hilary Turner D West Virginia 3 House 2020 https://images.ctfassets.net/00vgtve3ank7/3ZIN... 972 Hillary O'Connor Mueri D Ohio 14 House 2020 https://images.ctfassets.net/00vgtve3ank7/5i5w... 973 Hillary Scholten D Michigan 3 House 2022 https://images.ctfassets.net/00vgtve3ank7/47KO... 974 Hillary Scholten D Michigan 3 House 2020 https://images.ctfassets.net/00vgtve3ank7/3g47... 975 Hiral Tipirneni D Arizona 8 House 2018 https://images.ctfassets.net/00vgtve3ank7/3e9V... 976 Hiral Tipirneni D Arizona 6 House 2020 https://images.ctfassets.net/00vgtve3ank7/1APF... 977 Holden Hoggatt R Louisiana 3 House 2022 https://images.ctfassets.net/00vgtve3ank7/4tQP... 978 Homer Markel D Illinois 12 House 2022 https://images.ctfassets.net/00vgtve3ank7/3XXY... 979 Hosea Cleveland D South Carolina 3 House 2020 https://images.ctfassets.net/00vgtve3ank7/FZKi... 980 Hung Cao R Virginia 10 House 2022 https://images.ctfassets.net/00vgtve3ank7/4Aql... 981 Ian Todd D Minnesota 6 House 2018 https://images.ctfassets.net/00vgtve3ank7/3WkL... 982 Ike McCorkle D Colorado 4 House 2022 https://images.ctfassets.net/00vgtve3ank7/d7UB... 983 Ilhan Omar D Minnesota 5 House 2022 https://images.ctfassets.net/00vgtve3ank7/3TS6... 984 Ilhan Omar D Minnesota 5 House 2020 https://images.ctfassets.net/00vgtve3ank7/4EDC... 985 Ilhan Omar D Minnesota 5 House 2018 https://images.ctfassets.net/00vgtve3ank7/4n9U... 986 Irene Armendariz-Jackson R Texas 16 House 2022 https://images.ctfassets.net/00vgtve3ank7/2nbG... 987 Irene Armendariz-Jackson R Texas 16 House 2020 https://images.ctfassets.net/00vgtve3ank7/6wKS... 988 Iro Omere D Texas 4 House 2022 https://images.ctfassets.net/00vgtve3ank7/gewL... 989 Isaac McCorkle D Colorado 4 House 2020 https://images.ctfassets.net/00vgtve3ank7/4sUc... 990 J. Michael Galbraith D Ohio 5 House 2018 https://images.ctfassets.net/00vgtve3ank7/27nQ... </code></pre> <p>I wrote a function that I've called names:</p> <pre><code>def names(df): &quot;&quot;&quot; Description: Function to extract last names of candidate Parameters: df: pandas dataFrame object Depends on pandas and re &quot;&quot;&quot; if df[&quot;Candidate_Name&quot;].eq('Jr.').all(): lastName = df[&quot;Candidate_Name&quot;].str.split(' ').str.get(-4) else: lastName = df[&quot;Candidate_Name&quot;].str.split(' ').str.get(-2) return lastName </code></pre> <p>The goal with this function is that I should be able to grab the last name from the Candidate_Name column. However, I do have some folks with that go by Jr. and so that is adding a little bit of a complication that I tried writing an if-else statement to handle. However, something is going wrong.</p> <p>Because when I run the following:</p> <pre><code>df[&quot;Last_Name&quot;] = names(df) </code></pre> <p>I am getting this:</p> <pre><code> Candidate_Name Party State District Office Year Img_URL Last_Name 961 Heather Mizeur D Maryland 1 House 2022 https://images.ctfassets.net/00vgtve3ank7/3v1O... Mizeur 962 Heidi Campbell D Tennessee 5 House 2022 https://images.ctfassets.net/00vgtve3ank7/BbSQ... Campbell 963 Helen Brady R Massachusetts 9 House 2020 https://images.ctfassets.net/00vgtve3ank7/6WmS... Brady 964 Henry Cuellar D Texas 28 House 2022 https://images.ctfassets.net/00vgtve3ank7/4GGP... Cuellar 965 Henry Cuellar D Texas 28 House 2020 https://images.ctfassets.net/00vgtve3ank7/3xNd... Cuellar 966 Henry Cuellar D Texas 28 House 2018 https://images.ctfassets.net/00vgtve3ank7/uCK7... Cuellar 967 Henry Martin D Missouri 6 House 2022 https://images.ctfassets.net/00vgtve3ank7/5rfd... Martin 968 Henry Robert Martin D Missouri 6 House 2018 https://images.ctfassets.net/00vgtve3ank7/MvL8... Martin 969 Herb Jones D Virginia 1 House 2022 https://images.ctfassets.net/00vgtve3ank7/47Uy... Jones 970 Herman West Jr. R Georgia 2 House 2018 https://images.ctfassets.net/00vgtve3ank7/534y... Jr. 971 Hilary Turner D West Virginia 3 House 2020 https://images.ctfassets.net/00vgtve3ank7/3ZIN... Turner 972 Hillary O'Connor Mueri D Ohio 14 House 2020 https://images.ctfassets.net/00vgtve3ank7/5i5w... Mueri 973 Hillary Scholten D Michigan 3 House 2022 https://images.ctfassets.net/00vgtve3ank7/47KO... Scholten 974 Hillary Scholten D Michigan 3 House 2020 https://images.ctfassets.net/00vgtve3ank7/3g47... Scholten 975 Hiral Tipirneni D Arizona 8 House 2018 https://images.ctfassets.net/00vgtve3ank7/3e9V... Tipirneni 976 Hiral Tipirneni D Arizona 6 House 2020 https://images.ctfassets.net/00vgtve3ank7/1APF... Tipirneni 977 Holden Hoggatt R Louisiana 3 House 2022 https://images.ctfassets.net/00vgtve3ank7/4tQP... Hoggatt 978 Homer Markel D Illinois 12 House 2022 https://images.ctfassets.net/00vgtve3ank7/3XXY... Markel 979 Hosea Cleveland D South Carolina 3 House 2020 https://images.ctfassets.net/00vgtve3ank7/FZKi... Cleveland 980 Hung Cao R Virginia 10 House 2022 https://images.ctfassets.net/00vgtve3ank7/4Aql... Cao 981 Ian Todd D Minnesota 6 House 2018 https://images.ctfassets.net/00vgtve3ank7/3WkL... Todd 982 Ike McCorkle D Colorado 4 House 2022 https://images.ctfassets.net/00vgtve3ank7/d7UB... McCorkle 983 Ilhan Omar D Minnesota 5 House 2022 https://images.ctfassets.net/00vgtve3ank7/3TS6... Omar 984 Ilhan Omar D Minnesota 5 House 2020 https://images.ctfassets.net/00vgtve3ank7/4EDC... Omar 985 Ilhan Omar D Minnesota 5 House 2018 https://images.ctfassets.net/00vgtve3ank7/4n9U... Omar 986 Irene Armendariz-Jackson R Texas 16 House 2022 https://images.ctfassets.net/00vgtve3ank7/2nbG... Armendariz-Jackson 987 Irene Armendariz-Jackson R Texas 16 House 2020 https://images.ctfassets.net/00vgtve3ank7/6wKS... Armendariz-Jackson 988 Iro Omere D Texas 4 House 2022 https://images.ctfassets.net/00vgtve3ank7/gewL... Omere 989 Isaac McCorkle D Colorado 4 House 2020 https://images.ctfassets.net/00vgtve3ank7/4sUc... McCorkle 990 J. Michael Galbraith D Ohio 5 House 2018 https://images.ctfassets.net/00vgtve3ank7/27nQ... Galbraith </code></pre> <p>So it is obviously not ignoring the element that contains Jr. in it... (see row 970 for example).</p> <p>What did I do incorrectly here? I've played around with different values for the <code>str.get()</code> function, but it still keeps giving me that. I also don't want to do it from the other direction because some folks have middle initials or go by their middle initial (see line 990 for an example). So what is not working here? Why is the if-else statement not catching it?</p>
[ { "answer_id": 74425146, "author": "Shaman Technology", "author_id": 15475207, "author_profile": "https://Stackoverflow.com/users/15475207", "pm_score": -1, "selected": false, "text": "<i class=\"fas fa-user mr-2\"> Example text </i>\n" }, { "answer_id": 74437861, "author": "Markus Zeller", "author_id": 2645713, "author_profile": "https://Stackoverflow.com/users/2645713", "pm_score": 0, "selected": false, "text": "$html = <<<'_HTML'\n<nav class=\"navbar navbar-expand-xl\" id=\"menu\">\n <div>\n <a><i class=\"fas fa-user mr-2\"></i>Example text</a>\n </div>\n</nav>\n_HTML;\n\nlibxml_use_internal_errors(true);\n$doc = new DOMDocument();\n$doc->loadHTML($html);\n\n// parsing the elements\n$nav = $doc->getElementById('menu');\n$text = $nav->getElementsByTagName('a')->item(0)->nodeValue;\necho $text;\n\n// using xpath\n$xpath = new DOMXPath($doc);\n$text = $xpath->query('//nav[@id=\"menu\"]/div/a')->item(0)->nodeValue;\necho $text;\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74424989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12394134/" ]
74,425,008
<p>I'm able to import data to a list. For example:</p> <pre><code>write.csv(mtcars, &quot;mtcars.csv&quot;) write.csv(iris, &quot;iris.csv&quot;) </code></pre> <pre><code>files &lt;- list.files(pattern=&quot;*.csv&quot;) </code></pre> <pre><code>imported_files &lt;- list() for(i in seq_along(files)){ imported_files[[i]] &lt;- readr::read_csv(file = files[[i]]) } </code></pre> <pre><code>names(imported_files) NULL </code></pre> <p>But the imported_files list has no names. I'd like to create a list with the names in them. Something like this:</p> <pre><code>names(imported_files) &quot;iris&quot; &quot;mtcars&quot; </code></pre> <p>I'm also wondering if it is possible to do this using <code>lapply</code> and <code>purrr::map()</code>.</p>
[ { "answer_id": 74425146, "author": "Shaman Technology", "author_id": 15475207, "author_profile": "https://Stackoverflow.com/users/15475207", "pm_score": -1, "selected": false, "text": "<i class=\"fas fa-user mr-2\"> Example text </i>\n" }, { "answer_id": 74437861, "author": "Markus Zeller", "author_id": 2645713, "author_profile": "https://Stackoverflow.com/users/2645713", "pm_score": 0, "selected": false, "text": "$html = <<<'_HTML'\n<nav class=\"navbar navbar-expand-xl\" id=\"menu\">\n <div>\n <a><i class=\"fas fa-user mr-2\"></i>Example text</a>\n </div>\n</nav>\n_HTML;\n\nlibxml_use_internal_errors(true);\n$doc = new DOMDocument();\n$doc->loadHTML($html);\n\n// parsing the elements\n$nav = $doc->getElementById('menu');\n$text = $nav->getElementsByTagName('a')->item(0)->nodeValue;\necho $text;\n\n// using xpath\n$xpath = new DOMXPath($doc);\n$text = $xpath->query('//nav[@id=\"menu\"]/div/a')->item(0)->nodeValue;\necho $text;\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74425008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13874036/" ]
74,425,023
<p>I'm working on an RPG project, and want to get a preview of how costs will shake out.</p> <p>The plan is for every raise of an attribute, you pay its new value times 9.</p> <p>Going from 1 to 2 costs 18 XP.</p> <p>If you wish to go from 1 to 4, you need to pay (2x9)+(3x9)+(4x9), or (9x9), 72.</p> <p>I want to be able to punch in 9 for an attribute in my google sheet, and have it able get to the 44x9 needed to get the 396 cost to get that. Is there an easy way to do this I'm not seeing?</p> <p>I looked at the Sum function, thinking I could set up an array (add all numbers between 2 and the value of the cell named Will) but the parsing doesn't work that way. I'm going all crosseyed, and feel that the answers either right in front of me, or is no.</p>
[ { "answer_id": 74425146, "author": "Shaman Technology", "author_id": 15475207, "author_profile": "https://Stackoverflow.com/users/15475207", "pm_score": -1, "selected": false, "text": "<i class=\"fas fa-user mr-2\"> Example text </i>\n" }, { "answer_id": 74437861, "author": "Markus Zeller", "author_id": 2645713, "author_profile": "https://Stackoverflow.com/users/2645713", "pm_score": 0, "selected": false, "text": "$html = <<<'_HTML'\n<nav class=\"navbar navbar-expand-xl\" id=\"menu\">\n <div>\n <a><i class=\"fas fa-user mr-2\"></i>Example text</a>\n </div>\n</nav>\n_HTML;\n\nlibxml_use_internal_errors(true);\n$doc = new DOMDocument();\n$doc->loadHTML($html);\n\n// parsing the elements\n$nav = $doc->getElementById('menu');\n$text = $nav->getElementsByTagName('a')->item(0)->nodeValue;\necho $text;\n\n// using xpath\n$xpath = new DOMXPath($doc);\n$text = $xpath->query('//nav[@id=\"menu\"]/div/a')->item(0)->nodeValue;\necho $text;\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74425023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20495521/" ]
74,425,038
<p>When implementing a reactive endpoint, is there any difference between returning <code>Uni&lt;List&lt;T&gt;&gt;</code> vs <code>Multi&lt;T&gt;</code> ?</p> <pre class="lang-java prettyprint-override"><code>@Path(&quot;/fruits&quot;) public class FruitResource { @GET @Path(&quot;uni&quot;) public Uni&lt;List&lt;Fruit&gt;&gt; getUni() { return Fruit.listAll(); } @GET @Path(&quot;multi&quot;) public Multi&lt;Fruit&gt; getMulti() { return Fruit.streamAll(); } } </code></pre> <p>I find it easier to use a <code>Multi</code> because I can simply transform each each element to a DTO using <code>onItem().transform(fruit -&gt; ...)</code><br/> With an <code>Uni</code>, I would get a <code>List</code> in the <code>transform</code> method which is less convenient.</p> <p>In all Quarkus guides, I see they are using a <code>Uni&lt;List&gt;&gt;</code>, is there any good reason for using this rather than a <code>Multi</code> ?</p>
[ { "answer_id": 74427724, "author": "geoand", "author_id": 2504224, "author_profile": "https://Stackoverflow.com/users/2504224", "pm_score": 1, "selected": false, "text": "Multi<T>" }, { "answer_id": 74427895, "author": "Davide D'Alto", "author_id": 2404683, "author_profile": "https://Stackoverflow.com/users/2404683", "pm_score": 3, "selected": true, "text": "HTTP/1.1 200 OK\nContent-Type: application/json;charset=UTF-8\ncontent-length: 75\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74425038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5521607/" ]
74,425,063
<p>How can I create a function to convert the string &quot;ABCD&quot; to an array like: [&quot;A&quot;, &quot;AB&quot;, &quot;ABC&quot;, &quot;ABCD&quot;] in Javascript ?</p> <hr /> <p>(I don't know how to exactly describe this process in English so I just put the question in the title, so, would be great if there was a special term for it to be known.. :))</p>
[ { "answer_id": 74425084, "author": "Dimava", "author_id": 5734961, "author_profile": "https://Stackoverflow.com/users/5734961", "pm_score": 1, "selected": false, "text": "const s = 'ABCD'\n\nfunction f(s) {\n return s // = 'ABCD'\n // make array of length s.length\n .split('') // = ['A','B','C','D']\n // map it to slices of length (i+1)\n .map(\n (\n e,// = 'A','B','C','D'\n i, // = 0,1,2,3\n ) => s.slice(0, i + 1)\n ) // = what you said\n}\n\nconsole.log(f(s))\n" }, { "answer_id": 74425098, "author": "Valeriu Ciuca", "author_id": 4527645, "author_profile": "https://Stackoverflow.com/users/4527645", "pm_score": 1, "selected": false, "text": "for" }, { "answer_id": 74425139, "author": "Mister Jojo", "author_id": 10669010, "author_profile": "https://Stackoverflow.com/users/10669010", "pm_score": 2, "selected": true, "text": "console.log( foo('ABCD') );\n\nfunction foo(str)\n {\n let res = [], s='';\n for (let c of str) res.push( s+=c );\n return res;\n }" }, { "answer_id": 74425329, "author": "damonholden", "author_id": 17670742, "author_profile": "https://Stackoverflow.com/users/17670742", "pm_score": 0, "selected": false, "text": "const getProgressiveArray = (string) => {\n let concat = '';\n const progressiveArray = [];\n\n for (let character of string) {\n concat += character;\n progressiveArray.push(concat);\n }\n\n return progressiveArray;\n};\n" }, { "answer_id": 74455576, "author": "Firoz", "author_id": 17848207, "author_profile": "https://Stackoverflow.com/users/17848207", "pm_score": 0, "selected": false, "text": " const str = 'ABCD'\n\n function convertString(str) {\n var str = str.split('') //['A','B','C','D']\n\n .map((items, index ) => str.slice(0, index + 1)) //[ 'A', 'AB', 'ABC', 'ABCD' ]\n return str \n }\n\n console.log(convertString(str))" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74425063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18094325/" ]
74,425,069
<p>guys.</p> <p>I have three string lists like that:</p> <pre><code>list1 list2 list3 [0]xxx25, [0]48,yyy [0]95,www [1]xxx36, [1]25,yyy [1]75,www [2]xxx95, [2]36,www [3]xxx48, [4]xxx75, </code></pre> <p>I want to end up with list1 like that:</p> <pre><code>list1 [0]xxx25,yyy [1]xxx36,www [2]xxx95,www [3]xxx48,yyy [4]xxx75,www </code></pre> <p>What's the best way to do this?</p>
[ { "answer_id": 74425084, "author": "Dimava", "author_id": 5734961, "author_profile": "https://Stackoverflow.com/users/5734961", "pm_score": 1, "selected": false, "text": "const s = 'ABCD'\n\nfunction f(s) {\n return s // = 'ABCD'\n // make array of length s.length\n .split('') // = ['A','B','C','D']\n // map it to slices of length (i+1)\n .map(\n (\n e,// = 'A','B','C','D'\n i, // = 0,1,2,3\n ) => s.slice(0, i + 1)\n ) // = what you said\n}\n\nconsole.log(f(s))\n" }, { "answer_id": 74425098, "author": "Valeriu Ciuca", "author_id": 4527645, "author_profile": "https://Stackoverflow.com/users/4527645", "pm_score": 1, "selected": false, "text": "for" }, { "answer_id": 74425139, "author": "Mister Jojo", "author_id": 10669010, "author_profile": "https://Stackoverflow.com/users/10669010", "pm_score": 2, "selected": true, "text": "console.log( foo('ABCD') );\n\nfunction foo(str)\n {\n let res = [], s='';\n for (let c of str) res.push( s+=c );\n return res;\n }" }, { "answer_id": 74425329, "author": "damonholden", "author_id": 17670742, "author_profile": "https://Stackoverflow.com/users/17670742", "pm_score": 0, "selected": false, "text": "const getProgressiveArray = (string) => {\n let concat = '';\n const progressiveArray = [];\n\n for (let character of string) {\n concat += character;\n progressiveArray.push(concat);\n }\n\n return progressiveArray;\n};\n" }, { "answer_id": 74455576, "author": "Firoz", "author_id": 17848207, "author_profile": "https://Stackoverflow.com/users/17848207", "pm_score": 0, "selected": false, "text": " const str = 'ABCD'\n\n function convertString(str) {\n var str = str.split('') //['A','B','C','D']\n\n .map((items, index ) => str.slice(0, index + 1)) //[ 'A', 'AB', 'ABC', 'ABCD' ]\n return str \n }\n\n console.log(convertString(str))" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74425069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16224909/" ]
74,425,076
<p>It's been a while since I played around with Shiny, and I want to insert a UI and remove the UI whenever I toggle between two values of <code>radioButtons()</code>. Ideally, I want the Z <code>selectInput()</code> to appear whenever the user selects <code>TRUE</code> from the radio button; I'd also want it to disappear whenever the user selects <code>FALSE</code> from the radio button. Below I have some very sad code that makes the Z input appear but not disappear.</p> <p>Any advice of how to accomplish this would be greatly appreciated.</p> <pre><code>library(shiny) # Define UI for application that draws a histogram ui &lt;- fluidPage( # Sidebar layout with input and output definitions ---- sidebarLayout( # Sidebar panel for inputs ---- sidebarPanel( # Radio buttons radioButtons(&quot;partial_val&quot;,&quot;Partial&quot;,choices = c(&quot;TRUE&quot;,&quot;FALSE&quot;), selected = &quot;FALSE&quot;) ), # Main panel for displaying outputs ---- mainPanel( # Output: Data file ---- tableOutput(&quot;contents&quot;) ) ) ) # Define server logic required to draw a histogram server &lt;- function(input, output) { observeEvent(input$partial_val==TRUE, { insertUI( selector = &quot;#partial_val&quot;, where = &quot;afterEnd&quot;, ui = selectInput('z_var', 'Z', choices = '') ) }) observeEvent(input$partial_val==FALSE, { removeUI( selector = &quot;#z_var)&quot; ) }) output$contents &lt;- renderTable({ # input$file1 will be NULL initially. After the user selects # and uploads a file, head of that data file by default, # or all rows if selected, will be shown. req(input$file1) # when reading semicolon separated files, # having a comma separator causes `read.csv` to error tryCatch( { df &lt;- read.csv(input$file1$datapath) }, error = function(e) { # return a safeError if a parsing error occurs stop(safeError(e)) } ) if(input$disp == &quot;head&quot;) { return(head(df)) } else { return(df) } }) } # Run the application shinyApp(ui = ui, server = server) </code></pre>
[ { "answer_id": 74425084, "author": "Dimava", "author_id": 5734961, "author_profile": "https://Stackoverflow.com/users/5734961", "pm_score": 1, "selected": false, "text": "const s = 'ABCD'\n\nfunction f(s) {\n return s // = 'ABCD'\n // make array of length s.length\n .split('') // = ['A','B','C','D']\n // map it to slices of length (i+1)\n .map(\n (\n e,// = 'A','B','C','D'\n i, // = 0,1,2,3\n ) => s.slice(0, i + 1)\n ) // = what you said\n}\n\nconsole.log(f(s))\n" }, { "answer_id": 74425098, "author": "Valeriu Ciuca", "author_id": 4527645, "author_profile": "https://Stackoverflow.com/users/4527645", "pm_score": 1, "selected": false, "text": "for" }, { "answer_id": 74425139, "author": "Mister Jojo", "author_id": 10669010, "author_profile": "https://Stackoverflow.com/users/10669010", "pm_score": 2, "selected": true, "text": "console.log( foo('ABCD') );\n\nfunction foo(str)\n {\n let res = [], s='';\n for (let c of str) res.push( s+=c );\n return res;\n }" }, { "answer_id": 74425329, "author": "damonholden", "author_id": 17670742, "author_profile": "https://Stackoverflow.com/users/17670742", "pm_score": 0, "selected": false, "text": "const getProgressiveArray = (string) => {\n let concat = '';\n const progressiveArray = [];\n\n for (let character of string) {\n concat += character;\n progressiveArray.push(concat);\n }\n\n return progressiveArray;\n};\n" }, { "answer_id": 74455576, "author": "Firoz", "author_id": 17848207, "author_profile": "https://Stackoverflow.com/users/17848207", "pm_score": 0, "selected": false, "text": " const str = 'ABCD'\n\n function convertString(str) {\n var str = str.split('') //['A','B','C','D']\n\n .map((items, index ) => str.slice(0, index + 1)) //[ 'A', 'AB', 'ABC', 'ABCD' ]\n return str \n }\n\n console.log(convertString(str))" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74425076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6710466/" ]
74,425,083
<p>I have a multipart form which includes 'Name', 'Email' and 'Phone Number' fields.</p> <p>Note: The phone number 'field' is actually made up of 10 individual 'single-digit' fields.</p> <p>I want to provide the user with a 'Clear Phone Number&quot; button to reset the phone number fields if they accidentally enter the number incorrectly and need to start over.</p> <p>However, I do not want the button to clear all of the form data they have already entered, just the collective phone number fields.</p> <p>I have entered the code I am using below and have tested it. But so far the 'Clear Phone Number' button will only clear the entire form.</p> <p>Any help in tweaking this code would greatly be appreciated.</p> <p>Thank you, Maddison</p> <p>HTML</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;!-- START FORM --&gt; &lt;form action=&quot;/formHandler.php&quot; method=&quot;post&quot; enctype=&quot;multipart/form-data&quot;&gt; &lt;!-- START CONTACT INFORMATION --&gt; Name: &lt;input type=&quot;text&quot; id=&quot;userName&quot; name=&quot;userName&quot; class=&quot;userName_Field&quot; placeholder=&quot; Name&quot;&gt;&lt;br&gt;&lt;br&gt; Email: &lt;input type=&quot;email&quot; id=&quot;userEmail&quot; name=&quot;userEmail&quot; class=&quot;userEmail_Field&quot; placeholder=&quot; Email&quot;&gt;&lt;br&gt;&lt;br&gt; &lt;!-- ////////// Start Phone Number ////////// --&gt; Phone Number: &lt;br&gt;&lt;br&gt; &lt;!-- Start userPhone Fields --&gt; &lt;div class=&quot;phoneField_Wrapper&quot;&gt; ( &lt;input type=&quot;text&quot; id=&quot;userPhone_digit-01&quot; name=&quot;userPhone_digit-01&quot; class=&quot;phoneField&quot; maxlength=&quot;1&quot; placeholder=&quot;0&quot;&gt; &lt;input type=&quot;text&quot; id=&quot;userPhone_digit-02&quot; name=&quot;userPhone_digit-02&quot; class=&quot;phoneField&quot; maxlength=&quot;1&quot; placeholder=&quot;0&quot;&gt; &lt;input type=&quot;text&quot; id=&quot;userPhone_digit-03&quot; name=&quot;userPhone_digit-03&quot; class=&quot;phoneField&quot; maxlength=&quot;1&quot; placeholder=&quot;0&quot;&gt; )&amp;nbsp &lt;input type=&quot;text&quot; id=&quot;userPhone_digit-04&quot; name=&quot;userPhone_digit-04&quot; class=&quot;phoneField&quot; maxlength=&quot;1&quot; placeholder=&quot;0&quot;&gt; &lt;input type=&quot;text&quot; id=&quot;userPhone_digit-05&quot; name=&quot;userPhone_digit-05&quot; class=&quot;phoneField&quot; maxlength=&quot;1&quot; placeholder=&quot;0&quot;&gt; &lt;input type=&quot;text&quot; id=&quot;userPhone_digit-06&quot; name=&quot;userPhone_digit-06&quot; class=&quot;phoneField&quot; maxlength=&quot;1&quot; placeholder=&quot;0&quot;&gt; &amp;nbsp-&amp;nbsp &lt;input type=&quot;text&quot; id=&quot;userPhone_digit-07&quot; name=&quot;userPhone_digit-07&quot; class=&quot;phoneField&quot; maxlength=&quot;1&quot; placeholder=&quot;0&quot;&gt; &lt;input type=&quot;text&quot; id=&quot;userPhone_digit-08&quot; name=&quot;userPhone_digit-08&quot; class=&quot;phoneField&quot; maxlength=&quot;1&quot; placeholder=&quot;0&quot;&gt; &lt;input type=&quot;text&quot; id=&quot;userPhone_digit-09&quot; name=&quot;userPhone_digit-09&quot; class=&quot;phoneField&quot; maxlength=&quot;1&quot; placeholder=&quot;0&quot;&gt; &lt;input type=&quot;text&quot; id=&quot;userPhone_digit-10&quot; name=&quot;userPhone_digit-10&quot; class=&quot;phoneField&quot; maxlength=&quot;1&quot; placeholder=&quot;0&quot;&gt; &lt;/div&gt; &lt;br&gt;&lt;br&gt; &lt;!-- End userPhone Fields --&gt; &lt;!-- Start Clear Fields Button --&gt; &lt;div&gt;&lt;button&gt;Clear Phone Number&lt;/button&gt;&lt;/div&gt; &lt;!-- End Clear Fields Button --&gt; &lt;br&gt;&lt;br&gt; &lt;!-- Start Advance Next Field Script --&gt; &lt;script&gt; var phoneField_Wrapper = document.getElementsByClassName(&quot;phoneField_Wrapper&quot;)[0]; phoneField_Wrapper.onkeyup = function(e) { var target = e.srcElement; var maxLength = parseInt(target.attributes[&quot;maxlength&quot;].value, 10); var myLength = target.value.length; if (myLength &gt;= maxLength) { var next = target; while (next = next.nextElementSibling) { if (next == null) break; if (next.tagName.toLowerCase() == &quot;input&quot;) { next.focus(); break; } } } } &lt;/script&gt; &lt;!-- End Advance Next Field Script --&gt; &lt;!-- Start Clear Fields Button Script --&gt; &lt;script&gt; let btnClear = document.querySelector('button'); let inputs = document.querySelectorAll('input'); btnClear.addEventListener('click', () =&gt; { inputs.forEach(input =&gt; input.value = ''); }); &lt;/script&gt; &lt;!-- End Clear Fields Button Script --&gt; &lt;!-- ////////// End Phone Number ////////// --&gt; &lt;!-- Start Submit Button --&gt; &lt;input type=&quot;submit&quot; id=&quot;submitForm_Button&quot; name=&quot;submitForm_Button&quot; class=&quot;submitForm_Button&quot; value=&quot;Submit Form&quot;&gt;&lt;/div&gt; &lt;!-- End Submit Button --&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>CSS</p> <pre><code>.phoneField {width: 14px; text-align: center;} </code></pre>
[ { "answer_id": 74425171, "author": "dale landry", "author_id": 1533592, "author_profile": "https://Stackoverflow.com/users/1533592", "pm_score": 3, "selected": true, "text": "let inputs = document.querySelectorAll('.phoneField');" }, { "answer_id": 74425184, "author": "mohorii", "author_id": 5910725, "author_profile": "https://Stackoverflow.com/users/5910725", "pm_score": 0, "selected": false, "text": "let inputs = document.querySelectorAll(“input.phoneField“)\n" }, { "answer_id": 74425392, "author": "html_coder", "author_id": 17942512, "author_profile": "https://Stackoverflow.com/users/17942512", "pm_score": 0, "selected": false, "text": ".phoneField {width: 14px; text-align: center;}" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74425083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8322896/" ]
74,425,090
<pre><code>def arithmetic_sequence(): a = float(input('Type the first term')) d = float(input('Type the difference')) n = float(input(&quot;Type the number of values&quot;)) if a == ValueError: print(&quot;Write a value&quot;) elif d == ValueError: print(&quot;Write a value&quot;) elif n == ValueError: print(&quot;Write a value&quot;) else: sum = float(n * (a + (a + d * (n - 1))) / 2) return sum print(arithmetic_sequence()) </code></pre> <p>My goal is that when a person writes a non number into the program for it to say Write a value but it only shows ValueError, why? I specifically write in the program for it to say &quot;Type a value&quot;.</p>
[ { "answer_id": 74425171, "author": "dale landry", "author_id": 1533592, "author_profile": "https://Stackoverflow.com/users/1533592", "pm_score": 3, "selected": true, "text": "let inputs = document.querySelectorAll('.phoneField');" }, { "answer_id": 74425184, "author": "mohorii", "author_id": 5910725, "author_profile": "https://Stackoverflow.com/users/5910725", "pm_score": 0, "selected": false, "text": "let inputs = document.querySelectorAll(“input.phoneField“)\n" }, { "answer_id": 74425392, "author": "html_coder", "author_id": 17942512, "author_profile": "https://Stackoverflow.com/users/17942512", "pm_score": 0, "selected": false, "text": ".phoneField {width: 14px; text-align: center;}" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74425090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20495630/" ]
74,425,102
<p>I'm trying to upload a script to my ESP32 DOIT board through Arduino IDE. tl;dr: I'm trying to get a string from a webform and print it on a 0.96&quot; OLED display.</p> <p>The code I'm using is a combination of two scripts: the first one was a <a href="https://randomnerdtutorials.com/esp32-esp8266-input-data-html-form/" rel="nofollow noreferrer">tutorial</a> about hosting a webserver with input html forms in an ESP32 and the second was the OLED SSD1306 example from the Adafruit Library.</p> <p>The final code I'm using is:</p> <pre><code>#include &lt;Arduino.h&gt; #include &lt;WiFi.h&gt; #include &lt;AsyncTCP.h&gt; #include &lt;ESPAsyncWebServer.h&gt; #include &lt;SPI.h&gt; #include &lt;Wire.h&gt; #include &lt;Adafruit_GFX.h&gt; #include &lt;Adafruit_SSD1306.h&gt; #define SCREEN_WIDTH 128 // OLED display width, in pixels #define SCREEN_HEIGHT 32 // OLED display height, in pixels #define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin) #define SCREEN_ADDRESS 0x3C ///&lt; See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32 Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &amp;Wire, OLED_RESET); AsyncWebServer server(80); // I REPLACED WITH MY NETWORK CREDENTIALS const char* ssid = &quot;my_ssid&quot;; const char* password = &quot;mypassword&quot;; const char* PARAM_INPUT_1 = &quot;input1&quot;; // HTML web page to handle 3 input fields (input1, input2, input3) const char index_html[] PROGMEM = R&quot;rawliteral( &lt;!DOCTYPE HTML&gt;&lt;html&gt;&lt;head&gt; &lt;title&gt;ESP Input Form&lt;/title&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt; &lt;/head&gt;&lt;body&gt; &lt;form action=&quot;/get&quot;&gt; input1: &lt;input type=&quot;text&quot; name=&quot;input1&quot;&gt; &lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt; &lt;/form&gt;&lt;br&gt; &lt;/body&gt;&lt;/html&gt;)rawliteral&quot;; void notFound(AsyncWebServerRequest *request) { request-&gt;send(404, &quot;text/plain&quot;, &quot;Not found&quot;); } void setup() { Serial.begin(115200); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); if (WiFi.waitForConnectResult() != WL_CONNECTED) { Serial.println(&quot;WiFi Failed!&quot;); return; } Serial.println(); Serial.print(&quot;IP Address: &quot;); Serial.println(WiFi.localIP()); // Send web page with input fields to client server.on(&quot;/&quot;, HTTP_GET, [](AsyncWebServerRequest *request){ request-&gt;send_P(200, &quot;text/html&quot;, index_html); }); // Send a GET request to &lt;ESP_IP&gt;/get?input1=&lt;inputMessage&gt; server.on(&quot;/get&quot;, HTTP_GET, [] (AsyncWebServerRequest *request) { String inputMessage; String inputParam; // GET input1 value on &lt;ESP_IP&gt;/get?input1=&lt;inputMessage&gt; if (request-&gt;hasParam(PARAM_INPUT_1)) { inputMessage = request-&gt;getParam(PARAM_INPUT_1)-&gt;value(); inputParam = PARAM_INPUT_1; } else { inputMessage = &quot;No message sent&quot;; inputParam = &quot;none&quot;; } Serial.println(inputMessage); request-&gt;send(200, &quot;text/html&quot;, &quot;HTTP GET request sent to your ESP on input field (&quot; + inputParam + &quot;) with value: &quot; + inputMessage + &quot;&lt;br&gt;&lt;a href=\&quot;/\&quot;&gt;Return to Home Page&lt;/a&gt;&quot;); delay(2000); display.clearDisplay(); display.setTextSize(5); display.setTextColor(WHITE); display.setCursor(0, 10); display.println(inputMessage); display.display(); delay(5000); display.clearDisplay(); display.display(); }); server.onNotFound(notFound); server.begin(); } void loop() { } </code></pre> <p>The code uploads just fine, but in Serial Monitor I get the message:</p> <pre><code>Guru Meditation Error: Core 1 panic'ed (LoadProhibited). Exception was unhandled. Core 1 register dump: PC : 0x400dafd2 PS : 0x00060d30 A0 : 0x800d2add A1 : 0x3ffb27a0 A2 : 0x3ffc2d6c A3 : 0x000001ff A4 : 0x00000000 A5 : 0x00000001 A6 : 0x0000ffff A7 : 0x0000007f A8 : 0x800daf9f A9 : 0x3ffb2780 A10 : 0x3ffc2f10 A11 : 0x00000040 A12 : 0x4014bb80 A13 : 0x00000006 A14 : 0x000000ff A15 : 0x4014bb80 SAR : 0x0000000a EXCCAUSE: 0x0000001c EXCVADDR: 0x00000000 LBEG : 0x40089a95 LEND : 0x40089aa5 LCOUNT : 0xfffffffe Backtrace:0x400dafcf:0x3ffb27a00x400d2ada:0x3ffb27d0 0x400dd3b2:0x3ffb2820 ELF file SHA256: 0000000000000000 Rebooting... </code></pre> <p>I tried 3 of my ESP32 boards and everytime I get the same message. When I remove the part where I print my string on the display, there's (obviously) no error.</p> <p>Can you please point out how to overcome this problem? Why using each part of my code seperately works, but combining them doesn't work?</p> <p>Thank you in advance!</p>
[ { "answer_id": 74425427, "author": "romkey", "author_id": 2670348, "author_profile": "https://Stackoverflow.com/users/2670348", "pm_score": 2, "selected": false, "text": "delay()" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74425102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20140130/" ]
74,425,104
<p>I'm using VSCode with Python 3.11.0 in a virtual enviroment. I have installed the aforementioned toolchain to configure and launch LTSpice models.</p> <p>However, it seems not to work and I cannot find why (I'm quite new to python programming). I attach here the actual code and the traceback. Notice that the main code is taken from the example given in its webpage.</p> <p>The code:</p> <pre><code>import os from PyLTSpice.LTSpiceBatch import SimCommander # get script absolute path meAbsPath = os.path.dirname(os.path.realpath(&quot;Draft1.asc&quot;)) meAbsPath = meAbsPath + '/Draft1.asc' print(str(meAbsPath)) # select spice model LTC = SimCommander(meAbsPath) # set default arguments # LTC.set_parameters(res=0, cap=100e-6) LTC.set_component_value('R1', '2k') LTC.set_component_value('L1', '1u') # LTC.set_element_model('V3', &quot;SINE(0 1 3k 0 0 0)&quot;) # define simulation LTC.add_instructions( &quot;; Simulation settings&quot;, &quot;.param run = 0&quot; ) LTC.reset_netlist() LTC.add_instructions( &quot;; Simulation settings&quot;, &quot;.tran 0 10u 0 1n&quot;, ) LTC.run() LTC.wait_completion() # Sim Statistics print('Successful/Total Simulations: ' + str(LTC.okSim) + '/' + str(LTC.runno)) </code></pre> <p>The traceback log:</p> <pre><code>(.venv) PS C:\Users\ciko9\Documents\VSCode_Projects\.venv&gt; c:; cd 'c:\Users\ciko9\Documents\VSCode_Projects\.venv'; &amp; 'c:\Users\ciko9\Documents\VSCode_Projects\.venv\Scripts\python.exe' 'c:\Users\ciko9\.vscode\extensions\ms-python.python-2022.18.2\pythonFiles\lib\python\debugpy\adapter/../..\debugpy\launcher' '51647' '--' 'c:\Users\ciko9\Documents\VSCode_Projects\.venv\lts_run.py' C:\Users\ciko9\Documents\VSCode_Projects\.venv/Draft1.asc Creating Netlist Traceback (most recent call last): File &quot;C:\Users\ciko9\AppData\Local\Programs\Python\Python311\Lib\runpy.py&quot;, line 198, in _run_module_as_main return _run_code(code, main_globals, None, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;C:\Users\ciko9\AppData\Local\Programs\Python\Python311\Lib\runpy.py&quot;, line 88, in _run_code exec(code, run_globals) File &quot;c:\Users\ciko9\.vscode\extensions\ms-python.python-2022.18.2\pythonFiles\lib\python\debugpy\adapter/../..\debugpy\launcher/../..\debugpy\__main__.py&quot;, line 39, in &lt;module&gt; cli.main() File &quot;c:\Users\ciko9\.vscode\extensions\ms-python.python-2022.18.2\pythonFiles\lib\python\debugpy\adapter/../..\debugpy\launcher/../..\debugpy/..\debugpy\server\cli.py&quot;, line 430, in main run() File &quot;c:\Users\ciko9\.vscode\extensions\ms-python.python-2022.18.2\pythonFiles\lib\python\debugpy\adapter/../..\debugpy\launcher/../..\debugpy/..\debugpy\server\cli.py&quot;, line 284, in run_file runpy.run_path(target, run_name=&quot;__main__&quot;) File &quot;c:\Users\ciko9\.vscode\extensions\ms-python.python-2022.18.2\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_runpy.py&quot;, line 321, in run_path return _run_module_code(code, init_globals, run_name, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;c:\Users\ciko9\.vscode\extensions\ms-python.python-2022.18.2\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_runpy.py&quot;, line 135, in _run_module_code _run_code(code, mod_globals, init_globals, File &quot;c:\Users\ciko9\.vscode\extensions\ms-python.python-2022.18.2\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_runpy.py&quot;, line 124, in _run_code exec(code, run_globals) File &quot;c:\Users\ciko9\Documents\VSCode_Projects\.venv\lts_run.py&quot;, line 11, in &lt;module&gt; LTC = SimCommander(meAbsPath) ^^^^^^^^^^^^^^^^^^^^^^^ File &quot;c:\Users\ciko9\Documents\VSCode_Projects\.venv\Lib\site-packages\PyLTSpice\LTSpiceBatch.py&quot;, line 288, in __init__ retcode = run_function(cmd_netlist) ^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;c:\Users\ciko9\Documents\VSCode_Projects\.venv\Lib\site-packages\PyLTSpice\LTSpiceBatch.py&quot;, line 136, in run_function result = subprocess.run(command, timeout=timeout) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;C:\Users\ciko9\AppData\Local\Programs\Python\Python311\Lib\subprocess.py&quot;, line 546, in run with Popen(*popenargs, **kwargs) as process: ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;C:\Users\ciko9\AppData\Local\Programs\Python\Python311\Lib\subprocess.py&quot;, line 1022, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File &quot;C:\Users\ciko9\AppData\Local\Programs\Python\Python311\Lib\subprocess.py&quot;, line 1491, in _execute_child hp, ht, pid, tid = _winapi.CreateProcess(executable, args, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;c:\Users\ciko9\.vscode\extensions\ms-python.python-2022.18.2\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydev_bundle\pydev_monkey.py&quot;, line 853, in new_CreateProcess return getattr(_subprocess, original_name)(app_name, cmd_line, *args) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ FileNotFoundError: [WinError 2] El sistema no puede encontrar el archivo especificado </code></pre> <p>I guess that it actually finds the &quot;.asc&quot; LTSpice model file, but at some point it misses something but I could not figure out what is it. Thanks in advance!</p> <pre><code></code></pre>
[ { "answer_id": 74596069, "author": "user20587669", "author_id": 20587669, "author_profile": "https://Stackoverflow.com/users/20587669", "pm_score": 0, "selected": false, "text": "else: # Windows\n LTspice_exe = [r\"C:\\Program Files\\LTC\\LTspiceXVII\\XVIIx64.exe\"]\n LTspice_arg = {'netlist': ['-netlist'], 'run': ['-b', '-Run']}\n PROCNAME = \"XVIIx64.exe\"\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74425104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20495620/" ]
74,425,134
<p>I have maybe a very naive question (I am no expert in C programming), but I couldn't get a fully satisfactory explanation. Here is just the declaration of static array and a few prints:</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; void main() { int N=3, a[N]; for (int i=0; i&lt;N; i++) a[i] = 1000+i; printf(&quot;&amp;a = %p\n&quot;,&amp;a); printf(&quot;a = %p\n&quot;,a); printf(&quot;*a = %d\n&quot;,*a); printf(&quot;*(&amp;a) = %d (as an int)\n&quot;,*(&amp;a)); printf(&quot;*(&amp;a) = %p\ (as a pointer)\n&quot;,*(&amp;a)); } </code></pre> <p>The output is:</p> <pre><code>&amp;a = 0x7ffee9043ae0 a = 0x7ffee9043ae0 *a = 1000 *(&amp;a) = -319989024 (as an int) *(&amp;a) = 0x7ffee9043ae0 (as a pointer) </code></pre> <p>Since <code>&amp;a</code> and <code>a</code> are identical, showing the same address in memory, I was first expecting <code>*(&amp;a)</code> and <code>*a</code> being identical as well, both equal to <code>1000</code>.</p> <p>Then I thought about the types: <code>a</code> is apparently considered as an <code>int*</code>, so <code>&amp;a</code> is a <code>int**</code>. It turns that <code>*a</code> is an <code>int</code>, while <code>*(&amp;a)</code> is an <code>int*</code>: they are not of the same type, the latter is a pointer.</p> <p>It makes sense... But my question is then: why are <code>&amp;a</code> and <code>a</code> identical in the first place?</p>
[ { "answer_id": 74425188, "author": "dbush", "author_id": 1687119, "author_profile": "https://Stackoverflow.com/users/1687119", "pm_score": 2, "selected": false, "text": "a" }, { "answer_id": 74425212, "author": "Vlad from Moscow", "author_id": 2877241, "author_profile": "https://Stackoverflow.com/users/2877241", "pm_score": 3, "selected": true, "text": "a" }, { "answer_id": 74425381, "author": "chux - Reinstate Monica", "author_id": 2410359, "author_profile": "https://Stackoverflow.com/users/2410359", "pm_score": 0, "selected": false, "text": "&a" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74425134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14778592/" ]
74,425,159
<p>I have a html page with a script, It looks like</p> <pre><code>&lt;html&gt; &lt;/html&gt; &lt;script&gt; &lt;script&gt; </code></pre> <p>The page needs to run this script to display the content correctly.</p> <p>But when I redirect to this page with following code:</p> <pre><code>redirect_to user_trips_path(params[:user_id]) </code></pre> <p>I noticed that it will not refresh the page. If I refresh the page manually it will display the content correctly.</p> <p>My question is how to make this automatic?</p> <p>I try to google this question.</p>
[ { "answer_id": 74425188, "author": "dbush", "author_id": 1687119, "author_profile": "https://Stackoverflow.com/users/1687119", "pm_score": 2, "selected": false, "text": "a" }, { "answer_id": 74425212, "author": "Vlad from Moscow", "author_id": 2877241, "author_profile": "https://Stackoverflow.com/users/2877241", "pm_score": 3, "selected": true, "text": "a" }, { "answer_id": 74425381, "author": "chux - Reinstate Monica", "author_id": 2410359, "author_profile": "https://Stackoverflow.com/users/2410359", "pm_score": 0, "selected": false, "text": "&a" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74425159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20495644/" ]
74,425,185
<p>So basically I found this piece of code that sorts map by value:</p> <pre><code>bool cmp(pair&lt;string, int&gt;&amp; a, pair&lt;string, int&gt;&amp; b) { return a.second &lt; b.second; } void sort(map&lt;string, int&gt;&amp; M) { vector&lt;pair&lt;string, int&gt; &gt; A; for (auto&amp; it : M) A.push_back(it); sort(A.begin(), A.end(), cmp); } </code></pre> <p>but it sorts map in an ascending order which I need to be in descending, how do I do it?</p> <p>I thought that I could just iterate through map backwards but couldn't because of mine lack of knowledge.</p>
[ { "answer_id": 74425188, "author": "dbush", "author_id": 1687119, "author_profile": "https://Stackoverflow.com/users/1687119", "pm_score": 2, "selected": false, "text": "a" }, { "answer_id": 74425212, "author": "Vlad from Moscow", "author_id": 2877241, "author_profile": "https://Stackoverflow.com/users/2877241", "pm_score": 3, "selected": true, "text": "a" }, { "answer_id": 74425381, "author": "chux - Reinstate Monica", "author_id": 2410359, "author_profile": "https://Stackoverflow.com/users/2410359", "pm_score": 0, "selected": false, "text": "&a" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74425185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18494367/" ]
74,425,203
<p>In my Rails 7 app I've got custom two_factor_authentication. Now I want to enable this 2fa only in development and test environment.</p> <pre><code>class ApplicationController &lt; ActionController::Base before_action :check_two_factor_authentication, except: :check_authentication private def check_two_factor_authentication return true unless session[:challenge_id] redirect_to two_factor_path end </code></pre> <p>I've no idea what is <code>check_authentication</code> because inside entire app there is no such method - it comes from Devise gem I guess.</p> <p>How to set that before action only to development environment?</p>
[ { "answer_id": 74425244, "author": "Ursus", "author_id": 3857758, "author_profile": "https://Stackoverflow.com/users/3857758", "pm_score": 3, "selected": true, "text": "if %w(development test).include?(Rails.env)\n before_action :check_two_factor_authentication, except: :check_authentication \nend\n" }, { "answer_id": 74425250, "author": "rmlockerd", "author_id": 10369647, "author_profile": "https://Stackoverflow.com/users/10369647", "pm_score": 1, "selected": false, "text": "Rails.env.development?" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74425203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19143199/" ]
74,425,204
<p>I have 2 lists a and b which contain sublists that have different lenghts, and i want to find a sublist in a and a sublist in b that have the same length. My approach was:</p> <pre><code>for j in range(0, len(a)-1): for k in range(0, len(b)-1): if len(a[j]) == len(b[k]): </code></pre> <p>Problem being that a and b can both contain around 150 elements, and those loops are also in a for loop which can run this clutter about 400 times. Is there a more effecient way to do it?</p> <p>I tried the code I provided and it still hasnt finished running as of writing this question.</p>
[ { "answer_id": 74425244, "author": "Ursus", "author_id": 3857758, "author_profile": "https://Stackoverflow.com/users/3857758", "pm_score": 3, "selected": true, "text": "if %w(development test).include?(Rails.env)\n before_action :check_two_factor_authentication, except: :check_authentication \nend\n" }, { "answer_id": 74425250, "author": "rmlockerd", "author_id": 10369647, "author_profile": "https://Stackoverflow.com/users/10369647", "pm_score": 1, "selected": false, "text": "Rails.env.development?" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74425204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16581025/" ]
74,425,218
<p>I installed a &quot;dnspython&quot; package with &quot;pip install dnspython&quot; under Ubuntu 22.10 and made a following short script:</p> <pre><code>#!/usr/bin/env python3 import dns.zone import dns.query zone = dns.zone.Zone(&quot;example.net&quot;) dns.query.inbound_xfr(&quot;10.0.0.1&quot;, zone) for (name, ttl, rdata) in zone.iterate_rdatas(&quot;SOA&quot;): serial_nr = rdata.serial </code></pre> <p>When I check this code snippet with mypy(version 0.990), then it reports an <code>error: Module has no attribute &quot;inbound_xfr&quot; [attr-defined]</code> for line number 7.</p> <p>According to <a href="https://mypy.readthedocs.io/en/stable/running_mypy.html#how-imports-are-found" rel="nofollow noreferrer">mypy documentation</a>, if a Python file and a stub file are both present in the same directory on the search path, then only the stub file is used. In case of &quot;dnspython&quot;, the stub file <code>query.pyi</code> is present in the <code>dns</code> package and the stub file indeed has no attribute &quot;inbound_xfr&quot;. When I rename or remove the stub file, then the <code>query.py</code> Python file is used instead of the stub file and mypy no longer complains about missing attribute.</p> <p>I guess this is a &quot;dnspython&quot; bug? Is there a way to tell to mypy that for <code>query</code> module, the stub file should be ignored?</p>
[ { "answer_id": 74462150, "author": "Victor Lee", "author_id": 6240879, "author_profile": "https://Stackoverflow.com/users/6240879", "pm_score": 2, "selected": false, "text": "--exclude PATTERN" }, { "answer_id": 74509997, "author": "Anonymous Guy", "author_id": 5677332, "author_profile": "https://Stackoverflow.com/users/5677332", "pm_score": 2, "selected": false, "text": "--exclude" }, { "answer_id": 74532672, "author": "Alexander Volkovsky", "author_id": 15862569, "author_profile": "https://Stackoverflow.com/users/15862569", "pm_score": 4, "selected": true, "text": "dns.query.inbound_xfr(\"10.0.0.1\", zone) # type: ignore[attr-defined]\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74425218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1053143/" ]
74,425,235
<p>I have Lua scripts, that uses variables such as:</p> <pre><code>VERSION_LOCALE = &quot;1.0&quot; MAX_MONSTERS = 5 FORBIDDEN_MONSTERS = {2827} </code></pre> <p>I would like to make the variables externally configurable using a simple C# Program.</p> <ol> <li>Load the Lua script from a dialog</li> <li>Overwrite the file with the modified variables (textbox)</li> <li>The actual variables retrieved from our Lua script, in our example <code>MAX_MONSTERS</code> should be returned in the textbox.</li> </ol> <p><a href="https://i.stack.imgur.com/Xqc0Y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Xqc0Y.png" alt="Program Idea" /></a></p> <p>What is the appropriate way to achieve? Here is what I have tried without success: <a href="https://stackoverflow.com/a/27219221/18756404">https://stackoverflow.com/a/27219221/18756404</a></p>
[ { "answer_id": 74462150, "author": "Victor Lee", "author_id": 6240879, "author_profile": "https://Stackoverflow.com/users/6240879", "pm_score": 2, "selected": false, "text": "--exclude PATTERN" }, { "answer_id": 74509997, "author": "Anonymous Guy", "author_id": 5677332, "author_profile": "https://Stackoverflow.com/users/5677332", "pm_score": 2, "selected": false, "text": "--exclude" }, { "answer_id": 74532672, "author": "Alexander Volkovsky", "author_id": 15862569, "author_profile": "https://Stackoverflow.com/users/15862569", "pm_score": 4, "selected": true, "text": "dns.query.inbound_xfr(\"10.0.0.1\", zone) # type: ignore[attr-defined]\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74425235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18756404/" ]
74,425,256
<p>I have the following table;</p> <pre><code>| uuid | user_id | user_created | profile_edited | |:---- |:------:| -----:|:------:|:------:| | 1c5d134c | user_3 | 2022-11-10T19:09:05+00:00 | 2022-11-18T18:00:05+00:00 | 1c5d134b | user_3 | 2022-11-10T19:09:05+00:00 | 2022-11-15T18:00:05+00:00 | 1c5d134a | user_3 | 2022-11-10T19:09:05+00:00 | 2022-11-14T18:00:05+00:00 | 1c5d434a | user_1 | 2022-11-10T19:09:05+00:00 | 2022-11-13T19:09:05+00:00 | 1c8b424b | user_1 | 2022-11-10T19:09:05+00:00 | 2022-11-10T16:09:05+00:00 | 1c8b424c | user_2 | 2022-11-01T19:09:05+00:000 | 2022-11-19T19:09:05+00:00 | 1c8b424a | user_2 | 2022-11-01T19:09:05+00:000 | 2022-11-22T19:09:05+00:00 | 1c8b424b | user_2 | 2022-11-01T19:09:05+00:000 | 2022-11-24T19:09:05+00:00 | 1c5d434c | user_1 | 2022-11-10T19:09:05+00:00 | 2022-11-18T19:09:05+00:00 | 1c5d434e | user_1 | 2022-11-10T19:09:05+00:00 | 2022-11-16T19:09:05+00:00 | 1c5d434c | user_1 | 2022-11-10T19:09:05+00:00 | 2022-11-14T19:09:05+00:00 </code></pre> <p>In the example above we can see the second and third profile edit times as below;</p> <pre><code>| user_id | second_edit | third_edit | difference |:---- |:------:| -----:|:------:|:------:| | user_1 | 2022-11-13T19:09:05+00:00 | 2022-11-14T19:09:05+00:00 | 24 hours | user_2 | 2022-11-22T19:09:05+00:00 | 2022-11-24T19:09:05+00:00 |48 hours | user_3 | 2022-11-15T18:00:05+00:00 | 2022-11-18T18:00:05+00:00 | 72 hours </code></pre> <p>And the resulting query should find the median between 24, 48, and 72.</p>
[ { "answer_id": 74462150, "author": "Victor Lee", "author_id": 6240879, "author_profile": "https://Stackoverflow.com/users/6240879", "pm_score": 2, "selected": false, "text": "--exclude PATTERN" }, { "answer_id": 74509997, "author": "Anonymous Guy", "author_id": 5677332, "author_profile": "https://Stackoverflow.com/users/5677332", "pm_score": 2, "selected": false, "text": "--exclude" }, { "answer_id": 74532672, "author": "Alexander Volkovsky", "author_id": 15862569, "author_profile": "https://Stackoverflow.com/users/15862569", "pm_score": 4, "selected": true, "text": "dns.query.inbound_xfr(\"10.0.0.1\", zone) # type: ignore[attr-defined]\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74425256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3719201/" ]
74,425,265
<p>I need help finding a regex that will allow most strings, except:</p> <ul> <li>if the string only contains whitespaces</li> <li>if the string contains <code>:</code> or <code>*</code></li> </ul> <p>I want to reject the following strings:</p> <ul> <li><code>&quot;hello:world&quot;</code></li> <li><code>&quot;hello*world&quot;</code></li> <li><code>&quot; &quot;</code> (just a whitespace)</li> </ul> <p>But the following strings will pass:</p> <ul> <li><code>&quot;hello world&quot;</code></li> <li><code>&quot;hello&quot;</code></li> </ul> <p>So far, I can accomplish what I want... in two patterns.</p> <ul> <li><code>[^:*]*</code> rejects the 2 special characters</li> <li><code>.*\S.*</code> rejects any string with only whitespaces</li> </ul> <p>I'm not sure how to combine these two patterns into one...</p> <p>I'll be using the regex pattern along with Java.</p>
[ { "answer_id": 74425310, "author": "Ted Lyngmo", "author_id": 7582247, "author_profile": "https://Stackoverflow.com/users/7582247", "pm_score": 2, "selected": false, "text": "^(?!\\s*$)[^:*]+$\n" }, { "answer_id": 74425872, "author": "MikeM", "author_id": 1565512, "author_profile": "https://Stackoverflow.com/users/1565512", "pm_score": 3, "selected": true, "text": "matches" }, { "answer_id": 74429796, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 1, "selected": false, "text": "matches" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74425265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3326166/" ]
74,425,292
<p>In a plain text file,</p> <pre><code>bag1: apple bag3: pear bag2: potato bag2: orange bag1: banana bag2: banana onion </code></pre> <p>needs to be converted to</p> <pre><code>bag1: [apple, banana] bag2: [banana, orange, potato] bag3: [pear] non-categorized: onion </code></pre> <p>Of course, <code>sort</code> is the first step, then using python to check go over one by one. But is there a shell script alternative?</p>
[ { "answer_id": 74425597, "author": "Fravadona", "author_id": 3387716, "author_profile": "https://Stackoverflow.com/users/3387716", "pm_score": 2, "selected": false, "text": "sort" }, { "answer_id": 74425966, "author": "dawg", "author_id": 298607, "author_profile": "https://Stackoverflow.com/users/298607", "pm_score": 1, "selected": false, "text": "awk" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74425292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12387370/" ]
74,425,293
<p>Hey I have an issue where I am collecting input from several inputs.. I tried to write a helper function for just updating the state object for each input, but it seems like the input is only gathering the first letter from my input and nothing else.. and it seems like it stores it once and then I can change it.. any idea what I'm missing her?</p> <p>`</p> <pre><code>export const Form = ({addStudent}) =&gt; { const [newStudent, setNewStudent] = useState({school:&quot;university&quot;}) const updateValue = e =&gt; { const { name, value } = e.target; setNewStudent({[name]: value, ...newStudent}); } return ( &lt;section&gt; &lt;p&gt;First Name&lt;/p&gt; &lt;input type=&quot;text&quot; name=&quot;firstName&quot; onChange={updateValue} /&gt; &lt;p&gt;Last Name&lt;/p&gt; &lt;input type=&quot;text&quot; name=&quot;lastName&quot; onChange={updateValue} /&gt; &lt;label&gt;Choose a school:&lt;/label&gt; &lt;select name=&quot;school&quot; onChange={updateValue} &gt; &lt;option value=&quot;university&quot;&gt;university&lt;/option&gt; &lt;option value=&quot;highSchool&quot;&gt;High School&lt;/option&gt; &lt;/select&gt; &lt;button onClick={() =&gt; addStudent(newStudent)}&gt; Add new Student &lt;/button&gt; &lt;/section&gt; ) } </code></pre> <p>`</p> <p>I tried to make the updateValue function dynamic with the values like this and now it seems to not work anymore...</p>
[ { "answer_id": 74425316, "author": "kind user", "author_id": 6695924, "author_profile": "https://Stackoverflow.com/users/6695924", "pm_score": 2, "selected": true, "text": "setNewStudent({[name]: value, ...newStudent});\n // ^^^^^^^^^^ overwriting existing value\n" }, { "answer_id": 74425348, "author": "Matias Bertoni", "author_id": 19272564, "author_profile": "https://Stackoverflow.com/users/19272564", "pm_score": 0, "selected": false, "text": "setNewStudent({...newStudent, [name]: value});\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74425293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20035901/" ]
74,425,320
<p>I tried to implement some controller test with the usage of jwt in Spring Boot Microservices.</p> <p>When I run the test method shown below, I got this error</p> <pre><code>java.lang.NoClassDefFoundError: org/springframework/security/oauth2/server/resource/authentication/JwtGrantedAuthoritiesConverter Caused by: java.lang.ClassNotFoundException: org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter </code></pre> <p>Here is the code snippets shown below.</p> <pre><code>@Test public void test_WhenPlaceOrderWithWrongAccess_thenThrow403() throws Exception { OrderRequest orderRequest = getMockOrderRequest(); MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post(&quot;/order/placeOrder&quot;) .with(jwt().authorities(new SimpleGrantedAuthority(&quot;ADMIN&quot;))) // HERE IS THE ERROR LINE .contentType(MediaType.APPLICATION_JSON_VALUE) .content(objectMapper.writeValueAsString(orderRequest)) ).andExpect(MockMvcResultMatchers.status().isForbidden()) .andReturn(); } </code></pre> <p>Even if I added <code>spring-security-oauth2-resource-server</code> dependency in pom.xml of order service, It didn't help me fix the issue.</p> <p>Here are the issue shown below after adding <code>spring-security-oauth2-resource-server</code> dependency in pom.xml of order service.</p> <pre><code>java.lang.NoClassDefFoundError: org/springframework/security/oauth2/jwt/Jwt$Builder Caused by: java.lang.ClassNotFoundException: org.springframework.security.oauth2.jwt.Jwt$Builder </code></pre> <p>How can I fix the issue?</p> <p>Here is the link of example : <a href="https://github.com/Rapter1990/microservicecoursedailybuffer" rel="nofollow noreferrer">Link</a></p>
[ { "answer_id": 74425316, "author": "kind user", "author_id": 6695924, "author_profile": "https://Stackoverflow.com/users/6695924", "pm_score": 2, "selected": true, "text": "setNewStudent({[name]: value, ...newStudent});\n // ^^^^^^^^^^ overwriting existing value\n" }, { "answer_id": 74425348, "author": "Matias Bertoni", "author_id": 19272564, "author_profile": "https://Stackoverflow.com/users/19272564", "pm_score": 0, "selected": false, "text": "setNewStudent({...newStudent, [name]: value});\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74425320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19721745/" ]
74,425,351
<p>I'm new to python and have started learning about functions. I am having trouble with homework to create my function to convert Fahrenheit to Celsius. Please see my code below.</p> <pre><code>def convert_f_to_c(temp_in_fahrenheit): celsius = float(temp_in_fahrenheit - 32.00) * float(5.00 / 9.00) return round(celsius) convert_f_to_c() </code></pre> <p>The arguments is that we have a float representing a temperature, that returns a float representing a temp in degrees Celsius, rounded to 1dp.</p> <p>I receive one of these errors when I run the test</p> <pre><code>TypeError: unsupported operand type(s) for -: 'str' and 'float' </code></pre> <p>I have tried to create a function to convert Fahrenheit to Celsius and I keep getting errors. Unsure how to proceed with this question.</p>
[ { "answer_id": 74425373, "author": "StonedTensor", "author_id": 6023918, "author_profile": "https://Stackoverflow.com/users/6023918", "pm_score": 3, "selected": false, "text": "temp_in_fahrenheit" }, { "answer_id": 74425409, "author": "Mark Tolonen", "author_id": 235698, "author_profile": "https://Stackoverflow.com/users/235698", "pm_score": 1, "selected": false, "text": "def convert_f_to_c(temp_in_fahrenheit):\n return (temp_in_fahrenheit - 32) * 5 / 9\n\ntempf = float(input('Fahrenheit? '))\ntempc = convert_f_to_c(tempf)\nprint(f'{tempc:.1f} degC')\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74425351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20495309/" ]
74,425,354
<p>I have little problem with my table. It is stylized by classes. One for TABLE that makes rounded corners and changes background to grey. The other is to make rest of the table white and I assign it to TBODY. After second class is asigned, bottom-left and bottom-right corners are no longer rounded.</p> <pre><code>&lt;table align=center class=&quot;grey&quot;&gt; &lt;thead&gt; &lt;tr height=50&gt; &lt;th&gt;header&lt;/th&gt; &lt;th&gt;header&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody class=&quot;white&quot;&gt; &lt;tr height=50&gt; &lt;td&gt;row two&lt;/td&gt; &lt;td&gt;row two&lt;/td&gt; &lt;/tr&gt; &lt;tr height=50 class=&quot;white&quot;&gt; &lt;td&gt;row three&lt;/td&gt; &lt;td&gt;row three&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <pre><code>body { background: #000; } table.grey { background: #F6F2F5; border: 3px solid #FFF; text-align: center; width: 80%; padding: 15px; border-collapse: collapse; border-left: 0; border-right: 0; border-radius: 10px; border-spacing: 0px; } .white { background: #FFF; color: #000; padding: 50px; border-bottom-left-radius: 10px; border-bottom-right-radius: 10px; } </code></pre> <p>Giving class to TR of each row gives same result as to TBODY. I'm dumb. <a href="https://jsfiddle.net/2tm4z90b/8/" rel="nofollow noreferrer">https://jsfiddle.net/2tm4z90b/8/</a></p>
[ { "answer_id": 74425376, "author": "Ronnie Royston", "author_id": 4797603, "author_profile": "https://Stackoverflow.com/users/4797603", "pm_score": 2, "selected": false, "text": "table {\n border-radius: 5px;\n border: 1px solid black;\n}\ntable thead {\n background: gray;\n}" }, { "answer_id": 74429053, "author": "G-Cyrillus", "author_id": 2442099, "author_profile": "https://Stackoverflow.com/users/2442099", "pm_score": 1, "selected": true, "text": "tbody" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74425354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20495756/" ]
74,425,382
<p>Let's say my text file looks like this:</p> <pre><code>John Doe 18 male Amy hun 19 female </code></pre> <p>I need to read this into an array like so</p> <pre><code>while(reader.hasNextLine()){ result[i] = new Person(reader.next(),reader.next(),reader.next()); reader.nextLine(); i++; } </code></pre> <p>but it keeps messing up my array because it treats each space as a delimiter and does not use it, where the columns are separated by whitespace.</p> <p>I tried using delimiter to spaces on my scanner but I get the error: Exception in thread &quot;main&quot; java.util.NoSuchElementException. Tried a few things but no luck too. I also can't just read in both names as separate Strings because some rows will only have one name.</p>
[ { "answer_id": 74425376, "author": "Ronnie Royston", "author_id": 4797603, "author_profile": "https://Stackoverflow.com/users/4797603", "pm_score": 2, "selected": false, "text": "table {\n border-radius: 5px;\n border: 1px solid black;\n}\ntable thead {\n background: gray;\n}" }, { "answer_id": 74429053, "author": "G-Cyrillus", "author_id": 2442099, "author_profile": "https://Stackoverflow.com/users/2442099", "pm_score": 1, "selected": true, "text": "tbody" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74425382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20495827/" ]
74,425,394
<p>I'm trying to learn c# and trying to make simple minesweeper game on console. When i am returning int to char it returns '' or an emoji when it should return me 0-3. I know that my code is not clean i am still learning just the basics.</p> <pre><code>public char howManyMinesHaveBeenPut(int xCoordinate, int yCoordinate) { short howMany = 0; if(canPlayerPut(xCoordinate - 1, yCoordinate - 1) &amp;&amp; isMine(xCoordinate - 1, yCoordinate - 1)) { howMany++; Console.WriteLine(&quot;Mina 1&quot;); } if (canPlayerPut(xCoordinate, yCoordinate - 1) &amp;&amp; isMine(xCoordinate, yCoordinate - 1)) { howMany++; Console.WriteLine(&quot;Mina 2&quot;); } if (canPlayerPut(xCoordinate + 1, yCoordinate - 1) &amp;&amp; isMine(xCoordinate + 1, yCoordinate - 1)) { howMany++; Console.WriteLine(&quot;Mina 3&quot;); } if (canPlayerPut(xCoordinate - 1, yCoordinate) &amp;&amp; isMine(xCoordinate - 1, yCoordinate)) { howMany++; Console.WriteLine(&quot;Mina 4&quot;); } if (canPlayerPut(xCoordinate + 1, yCoordinate) &amp;&amp; isMine(xCoordinate + 1, yCoordinate)) { howMany++; Console.WriteLine(&quot;Mina 5&quot;); } if (canPlayerPut(xCoordinate - 1, yCoordinate + 1) &amp;&amp; isMine(xCoordinate - 1, yCoordinate + 1)) { howMany++; Console.WriteLine(&quot;Mina 6&quot;); } if (canPlayerPut(xCoordinate, yCoordinate + 1) &amp;&amp; isMine(xCoordinate, yCoordinate + 1)) { howMany++; Console.WriteLine(&quot;Mina 7&quot;); } if (canPlayerPut(xCoordinate + 1, yCoordinate + 1) &amp;&amp; isMine(xCoordinate + 1, yCoordinate + 1)) { howMany++; Console.WriteLine(&quot;Mina 8&quot;); } return Convert.ToChar(howMany); } </code></pre> <p>I've tried (char), convert to char, changing from int to short.</p> <p>here is the link for full code: <a href="https://github.com/Thuthutka/minesweeper/blob/main/Program.cs" rel="nofollow noreferrer">https://github.com/Thuthutka/minesweeper/blob/main/Program.cs</a></p>
[ { "answer_id": 74425466, "author": "pm100", "author_id": 173397, "author_profile": "https://Stackoverflow.com/users/173397", "pm_score": -1, "selected": false, "text": " howMany.ToString()[0]\n" }, { "answer_id": 74425556, "author": "Enigmativity", "author_id": 259769, "author_profile": "https://Stackoverflow.com/users/259769", "pm_score": 1, "selected": true, "text": "48" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74425394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19845858/" ]
74,425,399
<p>I would like to pass IHttpContextAccessor in the startup class. Here is my startup page.</p> <pre><code> public class Startup { public Startup(IConfiguration configuration, IHttpContextAccessor httpContext) { Configuration = configuration; HttpContext = httpContext; } public IConfiguration Configuration { get; } public IHttpContextAccessor HttpContext { get; } } </code></pre> <p>However I get this error</p> <pre><code>Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' while attempting to activate 'project_name.Startup'.' </code></pre> <p>Here is my objective I want to passs htppcontext in DatabaseInterceptor.</p> <pre><code> public void ConfigureServices(IServiceCollection services) { services.Configure&lt;ApplicationSettings&gt;(Configuration.GetSection(&quot;AppSettings&quot;)); services.AddTransient&lt;DatabaseMigrator&gt;(); services.AddScoped&lt;TenantInfo&gt;(); services.UseSchemaPerTenant(Configuration); TenantInfo tenantInfo = new TenantInfo(); tenantInfo.Name = &quot;erp_colombia&quot;; services.AddDbContext&lt;erp_colombiaDbContext&gt;(options =&gt; options.UseMySql( Configuration.GetConnectionString(&quot;DefaultConnection&quot;)).AddInterceptors(new DatabaseInterceptor(tenantInfo, HOW_CAN_I_GET_HTTP_CONTEXT_HERE))); } </code></pre> <p>What must I do to fix this issue. Thank you</p>
[ { "answer_id": 74426983, "author": "Jason Pan", "author_id": 7687666, "author_profile": "https://Stackoverflow.com/users/7687666", "pm_score": 0, "selected": false, "text": "services. AddSingleton<IHttpContextAccessor, HttpContextAccessor>();\n" }, { "answer_id": 74492449, "author": "t.ouvre", "author_id": 5658778, "author_profile": "https://Stackoverflow.com/users/5658778", "pm_score": 3, "selected": true, "text": "CommandEventData" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74425399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10152435/" ]
74,425,436
<p>I'm using <code>fixest::feols()</code> and I have a function I want to pass an argument to in order to subset the data using the <code>subset =</code> argument. However when keep getting the error: <code>The argument 'subset' is a formula whose variables must be in the data set given in argument 'data'.</code></p> <p>I have tried the following code:</p> <pre><code>library(fixest) cars &lt;- mtcars my_fun &lt;- function(data, hp.c.off) { feols(mpg ~ disp + drat, data = data, subset = ~ hp &gt; substitute(hp.c.off)) } my_fun(data = cars, 150) </code></pre> <p>My expected outcome would be the same as if one typed:</p> <pre><code>feols(mpg ~ disp + drat, data = cars, subset = ~ hp &gt; 150) </code></pre> <p>I know I have to replace the value of <code>hp.c.off</code> <em>before</em> passing it onto a formula. And one could do this by creating a string expression first and then using <code>as.formula()</code> however, I was wondering if there is a better way to do programmatically build the expression that didn't require creating a string expression first and then converting it into a formula.</p> <p>Thanks!</p>
[ { "answer_id": 74425510, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 1, "selected": false, "text": "my_fun <- function(data,expr = ~ hp > 150){\n \n feols(mpg ~ disp + drat,\n data = data,\n subset = expr)\n}\n" }, { "answer_id": 74425751, "author": "zephryl", "author_id": 17303805, "author_profile": "https://Stackoverflow.com/users/17303805", "pm_score": 2, "selected": true, "text": "rlang::new_formula()" }, { "answer_id": 74427913, "author": "G. Grothendieck", "author_id": 516548, "author_profile": "https://Stackoverflow.com/users/516548", "pm_score": 2, "selected": false, "text": "my_fun <- function(data, hp.c.off) {\n \n feols(mpg ~ disp + drat,\n data = data,\n subset = as.formula(paste(\"~ hp >\", hp.c.off)))\n}\n" } ]
2022/11/13
[ "https://Stackoverflow.com/questions/74425436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18967565/" ]