qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,412,333
<p>I have a canvas and when i click on it, it draws a line.</p> <p>Line is a function:</p> <pre><code>const line = (x1, y1, x2, y2) =&gt; { return ( &lt;line id=&quot;lineD&quot; x1={x1} y1={y1} x2={x2} y2={y2} style={{ stroke: &quot;black&quot;, strokeWidth: 3, strokeLinecap: &quot;round&quot; }}&gt;&lt;/line&gt; ) } </code></pre> <p>It works fine, except when I scale the canvas. When I do so, I change a <code>scale</code> state.</p> <p>So I want line attributes to be like this: <code>x1={x1 * scale}</code>, but it only sets it once.</p> <p>This is how I add lines, (content is another state):</p> <pre><code>content.push(line(100, 100, 200, 200)) </code></pre> <p>(these are just random numbers)<br /> And svg is: <code>&lt;svg&gt;{content}&lt;/svg&gt;</code></p>
[ { "answer_id": 74412468, "author": "rocambille", "author_id": 6612932, "author_profile": "https://Stackoverflow.com/users/6612932", "pm_score": 2, "selected": true, "text": "line" }, { "answer_id": 74422629, "author": "RubenSmn", "author_id": 20088324, "author_profile": "https://Stackoverflow.com/users/20088324", "pm_score": 0, "selected": false, "text": "const [content, setContent] = [\n {\n x1: 100,\n y1: 100,\n x2: 100,\n y2: 100,\n },\n];\n\nconst [scale, setScale] = useState(1);\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20197693/" ]
74,412,342
<p>For example, I have table</p> <pre><code>id;name 1;John 2;Mary 3;Cat 4;Cheng </code></pre> <p>I want selection to stop right after 3;Cat and still have as much rows in it as exist berore 3;Cat I think this could be described with such a query</p> <p><code>SELECT * FROM table WHERE condition ORDER BY id LIMIT name = 'Cat'</code></p> <p>but of course there is no such a construction <strong>LIMIT name='Cat'</strong> in SQL. Maybe something else fits?</p> <p>Currently Im using extensive select, but it requires enormous 1200 rows to be sure that it has at least one record expected.</p>
[ { "answer_id": 74412468, "author": "rocambille", "author_id": 6612932, "author_profile": "https://Stackoverflow.com/users/6612932", "pm_score": 2, "selected": true, "text": "line" }, { "answer_id": 74422629, "author": "RubenSmn", "author_id": 20088324, "author_profile": "https://Stackoverflow.com/users/20088324", "pm_score": 0, "selected": false, "text": "const [content, setContent] = [\n {\n x1: 100,\n y1: 100,\n x2: 100,\n y2: 100,\n },\n];\n\nconst [scale, setScale] = useState(1);\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1475428/" ]
74,412,345
<p>I'm trying to create a function in python that from a list of strings will return me a dict where the key(index) shows the most repetitive character for each index between all the strings. for example a list1 = ['one', 'two', 'twin', 'who'] should return index 0=t index 1=w index 2=o index 3=n in fact the most frequent character at the index 1 between all the string is 'w'. I found a solution but if I have lists with thousands of strings inside it will require too much time to perform. I would like to know if you can give me some help to decrease the time of execution.</p> <p>Here is what I tried to do but seems too slow to perform with lists of thousands strings inside</p> <pre><code>list1 = ['one', 'two', 'twin', 'who'] width = len(max(list1, key=len)) chars = {} for i, item in enumerate(zip(*[s.ljust(width) for s in list1])): set1 = set(item) if ' ' in set1: set1.remove(' ') chars[i] = max(set1, key=item.count) print(chars) </code></pre>
[ { "answer_id": 74412569, "author": "MatsLindh", "author_id": 137650, "author_profile": "https://Stackoverflow.com/users/137650", "pm_score": 3, "selected": true, "text": "collections.Counter" }, { "answer_id": 74412716, "author": "Thaiminhpv", "author_id": 11806050, "author_profile": "https://Stackoverflow.com/users/11806050", "pm_score": 0, "selected": false, "text": "ljust()" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20485030/" ]
74,412,363
<p>I have a list(string): []</p> <p>I need to multiply every two elements and than sum up the results</p> <p>So for the list:[0,1,2,3,4]</p> <p>I need to get the result: 105.</p> <p>(0+1)×(1+2)×(2+3)×(3+4)=105</p> <p>How do I do that?</p> <p>I tried to write this code:</p> <pre class="lang-py prettyprint-override"><code>Lst3= [0,1,2,3,4] multiply=0 sum=0 count=1 for i in lst3: multiply= i*lst3[i+1] sum= sum+multiply count=count+1 print (sum) </code></pre>
[ { "answer_id": 74412427, "author": "ILS", "author_id": 10017662, "author_profile": "https://Stackoverflow.com/users/10017662", "pm_score": 1, "selected": false, "text": "zip" }, { "answer_id": 74412511, "author": "Ryan", "author_id": 18242026, "author_profile": "https://Stackoverflow.com/users/18242026", "pm_score": 0, "selected": false, "text": " lst1 = [0, 1, 2, 3, 4]\n # mul is the multiplication variable that stores the result\n # It is given 1 as its value as we are multiplying with it\n mul = 1\n # the for loop will literate from the first to the second last element in the list\n for i in range(0, len(lst1) - 1):\n # a local variable that stores the sum of the 2 values\n sumval = lst1[i] + lst1[i+1]\n mul = mul * sumval\n # print the result\n print(mul)\n" }, { "answer_id": 74412518, "author": "S A", "author_id": 16348606, "author_profile": "https://Stackoverflow.com/users/16348606", "pm_score": 0, "selected": false, "text": "num = [0,1,2,3,4]\n\nsum = 1\nfor i in range(len(num)-1):\n a = num[i] + num[i+1]\n sum = sum * a\nprint(sum)\n" }, { "answer_id": 74412528, "author": "Bhargav", "author_id": 15358800, "author_profile": "https://Stackoverflow.com/users/15358800", "pm_score": 1, "selected": false, "text": "import math\nl=[0,1,2,3,4]\n\ncu= [l[i] + l[(i+1)%len(l)] for i in range (len(l)-1)] \nprint(math.prod(cu))\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20485025/" ]
74,412,364
<p>I have made this login form from my basic HTML CSS and JavaScript knowledge. There is a Remember me button in this login form I have created and now I have to give it a functionality. I want to click OK button and then it should: Create a cookie if Remember Me is set and save Student Id and Name. I am using Visual Studio Code. Here is my HTML + JavaScript Code:</p> <pre><code>!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=&lt;device-width&gt;, initial-scale=1.0&quot;&gt; &lt;title&gt;Login Form&lt;/title&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;style1.css&quot;&gt; &lt;/head&gt; &lt;body&gt; &lt;div class = &quot;f1&quot;&gt; &lt;label for = &quot;uname&quot;&gt; &lt;b&gt;Username&lt;/b&gt; &lt;/label&gt; &lt;input type = &quot;text&quot; placeholder = &quot;Enter Username&quot; id = &quot;user&quot; name = &quot;uname&quot; requitred&gt; &lt;span id = &quot;username&quot; class = &quot;text-danger font-weight-bold&quot;&gt;&lt;/span&gt; &lt;label for = &quot;psw&quot;&gt; &lt;b&gt;Password&lt;/b&gt; &lt;/label&gt; &lt;input type = &quot;text&quot; placeholder = &quot;Enter Password&quot; id = &quot;pass&quot; name = &quot;psw&quot; requitred&gt; &lt;button type=&quot;button&quot; onclick=&quot;alert('Login is clicked')&quot;&gt;OK&lt;/button&gt; &lt;button type=&quot;button&quot; onclick=&quot;alert('Cancel is clicked')&quot;&gt;Cancel&lt;/button&gt; &lt;input type=&quot;checkbox&quot; value=&quot;lsRememberMe&quot; id=&quot;rememberMe&quot;&gt; &lt;label for=&quot;rememberMe&quot;&gt;Remember me&lt;/label&gt; &lt;input type=&quot;submit&quot; value=&quot;Login&quot; onclick=&quot;lsRememberMe()&quot;&gt; &lt;script&gt; if (onclick == &quot;alert('Login is clicked')&quot;){ window.location.assign(&quot;Home.html&quot;); } &lt;/script&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>CSS Code:-</strong></p> <pre><code>form{ border: 3px solid black; } input[type=text], input[type=password]{ width:27%; padding:12px 20px; margin:8px 0; display: inline-block; border: 1px solid black; box-sizing: border-box; } button{ background-color: #04aa6d; color: white; padding: 14px 20px; margin: 8px 0; border: none; cursor: pointer; width: 27%; } input[type=&quot;checkbox&quot;] { -webkit-appearance: checkbox; -moz-appearance: checkbox; appearance: checkbox; display: inline-block; width: auto; } body { background-image: url('cool.jpg'); color: #FFFFFF; } input[type = Clear]{ font-size : 18px; padding : 5px; width : 20%; border-radius: 0 10px; border : none; } </code></pre> <p>I have tried a lot of different techniques but it not work for me. (Code must be in JavaScript and HTML). Thanks.</p>
[ { "answer_id": 74412427, "author": "ILS", "author_id": 10017662, "author_profile": "https://Stackoverflow.com/users/10017662", "pm_score": 1, "selected": false, "text": "zip" }, { "answer_id": 74412511, "author": "Ryan", "author_id": 18242026, "author_profile": "https://Stackoverflow.com/users/18242026", "pm_score": 0, "selected": false, "text": " lst1 = [0, 1, 2, 3, 4]\n # mul is the multiplication variable that stores the result\n # It is given 1 as its value as we are multiplying with it\n mul = 1\n # the for loop will literate from the first to the second last element in the list\n for i in range(0, len(lst1) - 1):\n # a local variable that stores the sum of the 2 values\n sumval = lst1[i] + lst1[i+1]\n mul = mul * sumval\n # print the result\n print(mul)\n" }, { "answer_id": 74412518, "author": "S A", "author_id": 16348606, "author_profile": "https://Stackoverflow.com/users/16348606", "pm_score": 0, "selected": false, "text": "num = [0,1,2,3,4]\n\nsum = 1\nfor i in range(len(num)-1):\n a = num[i] + num[i+1]\n sum = sum * a\nprint(sum)\n" }, { "answer_id": 74412528, "author": "Bhargav", "author_id": 15358800, "author_profile": "https://Stackoverflow.com/users/15358800", "pm_score": 1, "selected": false, "text": "import math\nl=[0,1,2,3,4]\n\ncu= [l[i] + l[(i+1)%len(l)] for i in range (len(l)-1)] \nprint(math.prod(cu))\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13912027/" ]
74,412,421
<p>Consider microservices architecture, where you need to expose functionality to manage simple configuration shared with different microservices. Configuration is not changing often, but still, I would like to see changes whenever I ask for any value. Using REST microservice seems easy, but it is adding latency. Alternative could be RPC over messaging (i.e. RabbitMQ), but interface becomes more complicated.</p> <p>What communication are you using for internal, simple services and what are pros and cons? Any examples?</p> <p>I tried with REST API, but it means a lot of &quot;slow&quot; requests, which add a latency to overall requests.</p>
[ { "answer_id": 74412427, "author": "ILS", "author_id": 10017662, "author_profile": "https://Stackoverflow.com/users/10017662", "pm_score": 1, "selected": false, "text": "zip" }, { "answer_id": 74412511, "author": "Ryan", "author_id": 18242026, "author_profile": "https://Stackoverflow.com/users/18242026", "pm_score": 0, "selected": false, "text": " lst1 = [0, 1, 2, 3, 4]\n # mul is the multiplication variable that stores the result\n # It is given 1 as its value as we are multiplying with it\n mul = 1\n # the for loop will literate from the first to the second last element in the list\n for i in range(0, len(lst1) - 1):\n # a local variable that stores the sum of the 2 values\n sumval = lst1[i] + lst1[i+1]\n mul = mul * sumval\n # print the result\n print(mul)\n" }, { "answer_id": 74412518, "author": "S A", "author_id": 16348606, "author_profile": "https://Stackoverflow.com/users/16348606", "pm_score": 0, "selected": false, "text": "num = [0,1,2,3,4]\n\nsum = 1\nfor i in range(len(num)-1):\n a = num[i] + num[i+1]\n sum = sum * a\nprint(sum)\n" }, { "answer_id": 74412528, "author": "Bhargav", "author_id": 15358800, "author_profile": "https://Stackoverflow.com/users/15358800", "pm_score": 1, "selected": false, "text": "import math\nl=[0,1,2,3,4]\n\ncu= [l[i] + l[(i+1)%len(l)] for i in range (len(l)-1)] \nprint(math.prod(cu))\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20485048/" ]
74,412,442
<p>I'm using Angular 14, when I put this code, it works fine and the value is initialized.</p> <pre><code>&lt;input type=&quot;text&quot; name=&quot;name&quot; value=&quot;John&quot; &gt; </code></pre> <p>But when I add ngModel, the value is no longer initialized, and nothing is showed in the text box.</p> <pre><code>&lt;input type=&quot;text&quot; ngModel name=&quot;name&quot; value=&quot;John&quot; &gt; </code></pre> <p>How can I put a value in text box with ngModel ?</p>
[ { "answer_id": 74412427, "author": "ILS", "author_id": 10017662, "author_profile": "https://Stackoverflow.com/users/10017662", "pm_score": 1, "selected": false, "text": "zip" }, { "answer_id": 74412511, "author": "Ryan", "author_id": 18242026, "author_profile": "https://Stackoverflow.com/users/18242026", "pm_score": 0, "selected": false, "text": " lst1 = [0, 1, 2, 3, 4]\n # mul is the multiplication variable that stores the result\n # It is given 1 as its value as we are multiplying with it\n mul = 1\n # the for loop will literate from the first to the second last element in the list\n for i in range(0, len(lst1) - 1):\n # a local variable that stores the sum of the 2 values\n sumval = lst1[i] + lst1[i+1]\n mul = mul * sumval\n # print the result\n print(mul)\n" }, { "answer_id": 74412518, "author": "S A", "author_id": 16348606, "author_profile": "https://Stackoverflow.com/users/16348606", "pm_score": 0, "selected": false, "text": "num = [0,1,2,3,4]\n\nsum = 1\nfor i in range(len(num)-1):\n a = num[i] + num[i+1]\n sum = sum * a\nprint(sum)\n" }, { "answer_id": 74412528, "author": "Bhargav", "author_id": 15358800, "author_profile": "https://Stackoverflow.com/users/15358800", "pm_score": 1, "selected": false, "text": "import math\nl=[0,1,2,3,4]\n\ncu= [l[i] + l[(i+1)%len(l)] for i in range (len(l)-1)] \nprint(math.prod(cu))\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8011367/" ]
74,412,450
<p>I have following task:</p> <p>Define a function <strong>replace-element</strong> that searches a given list for a given element x and replaces each element x with a given element y.</p> <p>I am a super beginner and have no idea how to do this.</p> <p>Maybe there is someone who can help me. Thanks a lot!!</p> <p>For example:</p> <p>(replace-element ‘a ‘b ‘(a b c a b c))</p> <p>(B B C B B C)</p>
[ { "answer_id": 74412427, "author": "ILS", "author_id": 10017662, "author_profile": "https://Stackoverflow.com/users/10017662", "pm_score": 1, "selected": false, "text": "zip" }, { "answer_id": 74412511, "author": "Ryan", "author_id": 18242026, "author_profile": "https://Stackoverflow.com/users/18242026", "pm_score": 0, "selected": false, "text": " lst1 = [0, 1, 2, 3, 4]\n # mul is the multiplication variable that stores the result\n # It is given 1 as its value as we are multiplying with it\n mul = 1\n # the for loop will literate from the first to the second last element in the list\n for i in range(0, len(lst1) - 1):\n # a local variable that stores the sum of the 2 values\n sumval = lst1[i] + lst1[i+1]\n mul = mul * sumval\n # print the result\n print(mul)\n" }, { "answer_id": 74412518, "author": "S A", "author_id": 16348606, "author_profile": "https://Stackoverflow.com/users/16348606", "pm_score": 0, "selected": false, "text": "num = [0,1,2,3,4]\n\nsum = 1\nfor i in range(len(num)-1):\n a = num[i] + num[i+1]\n sum = sum * a\nprint(sum)\n" }, { "answer_id": 74412528, "author": "Bhargav", "author_id": 15358800, "author_profile": "https://Stackoverflow.com/users/15358800", "pm_score": 1, "selected": false, "text": "import math\nl=[0,1,2,3,4]\n\ncu= [l[i] + l[(i+1)%len(l)] for i in range (len(l)-1)] \nprint(math.prod(cu))\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20434143/" ]
74,412,463
<p>I'm trying deploy openstack using Kolla-ansible approach with <a href="https://docs.openstack.org/kolla-ansible/latest/user/quickstart.html" rel="nofollow noreferrer">this guide</a> using a virtual environment. while I write the command:</p> <pre><code>kolla-ansible -i ./all-in-one bootstrap-servers </code></pre> <p>I get this error:</p> <pre class="lang-bash prettyprint-override"><code>TASK [openstack.kolla.packages : Install packages] ***************************************************** [WARNING]: Updating cache and auto-installing missing dependency: python3-apt fatal: [localhost]: FAILED! =&gt; {&quot;changed&quot;: false, &quot;msg&quot;: &quot;python3-apt must be installed and visible from /root/my_venv/bin/python.&quot;} </code></pre> <p>I googled but didn't find anything helpful and I'm super new to ansible, openstack and linux. What is the best course of action to take?</p> <p>I expect the outcome to be something like this:</p> <pre class="lang-bash prettyprint-override"><code>PLAY RECAP ********************************************************************************************* localhost: ok=8 changed=0 unreachable=0 **failed=0** skipped=3 rescued=0 ignored=0 </code></pre>
[ { "answer_id": 74412640, "author": "n. m.", "author_id": 775806, "author_profile": "https://Stackoverflow.com/users/775806", "pm_score": 2, "selected": true, "text": "/root/my_venv/" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15452154/" ]
74,412,467
<p>A user clicks on the switcher and add an item to a localStorage (as you see we add id:coindID every time on click)</p> <p>If a user decided not to choose it, he clicks again on the switcher, so I wanna remove the item from the localStorage with a localStorage.removeItem(key)</p> <p>(key is checkedCoins). But for some reason, it removes everything like clear()</p> <pre><code> function switchClick(event) { if(event.target.checked){ let coinId = event.currentTarget.id; const jsonString = localStorage.getItem(&quot;checkedCoins&quot;) if (jsonString) { let cryptoCoins = JSON.parse(jsonString) cryptoCoins.push({id: coinId}); let checkedCoinsString = JSON.stringify(cryptoCoins); localStorage.setItem(&quot;checkedCoins&quot;, checkedCoinsString); if(cryptoCoins.length &gt; 6 ) { alert(&quot;delete&quot;) } } else { localStorage.setItem(&quot;checkedCoins&quot;, JSON.stringify([{id: coinId}])); } } else { localStorage.removeItem(&quot;checkedCoins&quot;); } } </code></pre>
[ { "answer_id": 74412571, "author": "Nick Vu", "author_id": 9201587, "author_profile": "https://Stackoverflow.com/users/9201587", "pm_score": 2, "selected": false, "text": "localStorage.removeItem" }, { "answer_id": 74417321, "author": "Mac", "author_id": 2158270, "author_profile": "https://Stackoverflow.com/users/2158270", "pm_score": 0, "selected": false, "text": "<script\n src=\"https://cdn.jsdelivr.net/gh/macmcmeans/localDataStorage@master/localDataStorage-3.0.0.min.js\" \n integrity=\"sha512-dEhk3bL90qpWkcHCJDErHbZEY7hGc4ozmKss33HSjwMeSBKBtiw/XVIE7tb5u+iOEp6dTIR9sCWW7J3txeTQIw==\" \n crossorigin=\"anonymous\"\n></script>\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20157290/" ]
74,412,469
<p>I'm building a basic calculator, and keep getting &quot;TypeError: not all arguments converted during string formatting&quot; at a line with returning the remainder. How can I fix this?</p> <pre><code>a = (input()) b = (input()) c = str(input()) if (b==0.0) and ((c=='mod') or (c=='/') or (c=='div')): print ('Zero division!') if c == '+': print(a+b) if c == '-': print(a-b) if c == '/': print(a/b) if c == 'mod': print(a % b) #this is the problem line if c == 'pow': print(a**b) if c == 'div': print(a//b) </code></pre>
[ { "answer_id": 74412571, "author": "Nick Vu", "author_id": 9201587, "author_profile": "https://Stackoverflow.com/users/9201587", "pm_score": 2, "selected": false, "text": "localStorage.removeItem" }, { "answer_id": 74417321, "author": "Mac", "author_id": 2158270, "author_profile": "https://Stackoverflow.com/users/2158270", "pm_score": 0, "selected": false, "text": "<script\n src=\"https://cdn.jsdelivr.net/gh/macmcmeans/localDataStorage@master/localDataStorage-3.0.0.min.js\" \n integrity=\"sha512-dEhk3bL90qpWkcHCJDErHbZEY7hGc4ozmKss33HSjwMeSBKBtiw/XVIE7tb5u+iOEp6dTIR9sCWW7J3txeTQIw==\" \n crossorigin=\"anonymous\"\n></script>\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20352757/" ]
74,412,477
<p>I have to run the report with start time between 00.00 AM and 05.00 AM , but the start time field is varchar field and its has &quot;20211110200336&quot;</p> <p>I am trying with</p> <p>WHERE TO_CHAR(TO_DATE(starttime,' YYYY-MM-DD HH24:MI:SS'), 'HH24:MI:SS')BETWEEN '000000' AND '050000'</p> <p>but i am getting error as &quot;ORA-01840: input value not long enough for date format 01840. 00000 - &quot;input value not long enough for date format&quot; *Cause: &quot;</p> <p>Can anyone help me how to use it</p>
[ { "answer_id": 74412671, "author": "Marmite Bomber", "author_id": 4808122, "author_profile": "https://Stackoverflow.com/users/4808122", "pm_score": 2, "selected": false, "text": "DATE" }, { "answer_id": 74413456, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 2, "selected": false, "text": "SELECT *\nFROM table_name\nWHERE SUBSTR(starttime, 9) BETWEEN '000000' AND '050000'\n" }, { "answer_id": 74413487, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 0, "selected": false, "text": "create table mytime(tm varchar2(14))\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7677388/" ]
74,412,482
<p>If I run a basic TWS example, I receive the error message . If I comment out the error() call back it runs fine. I've tried this on several examples and get the same result.</p> <pre><code> Exception has occurred: TypeError error() takes 4 positional arguments but 5 were given File &quot;/Users/jayurbain/Dropbox/twsapi/Algorithmic Trading using Interactive Broker's Python API /ib_basic_app.py&quot;, line 20, in &lt;module&gt; app.run() </code></pre> <p>Please advise.</p> <p>Thanks,</p> <p>Jay</p> <p>Here's the call back that is being overridden in wrapper.py:</p> <pre><code> def error(self, reqId:TickerId, errorCode:int, errorString:str, advancedOrderRejectJson = &quot;&quot;): </code></pre> <p>Here is the entire code:</p> <pre><code>from ibapi.client import EClient from ibapi.wrapper import EWrapper class TradingApp(EWrapper, EClient): def __init__(self): EClient.__init__(self,self) def error(self, reqId, errorCode, errorString): print(&quot;Error {} {} {}&quot;.format(reqId,errorCode,errorString)) app = TradingApp() app.connect(&quot;127.0.0.1&quot;, 7497, clientId=1) app.run() </code></pre>
[ { "answer_id": 74412671, "author": "Marmite Bomber", "author_id": 4808122, "author_profile": "https://Stackoverflow.com/users/4808122", "pm_score": 2, "selected": false, "text": "DATE" }, { "answer_id": 74413456, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 2, "selected": false, "text": "SELECT *\nFROM table_name\nWHERE SUBSTR(starttime, 9) BETWEEN '000000' AND '050000'\n" }, { "answer_id": 74413487, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 0, "selected": false, "text": "create table mytime(tm varchar2(14))\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/988288/" ]
74,412,498
<p>How can you write a function f that takes another function g as an argument, but where function g has arguments that change dynamically depending on what happens in function f?</p> <p>A pseudocode example would be:</p> <pre><code>def function(another_function(parameters)): # another function passed as an argument, with parameters for i in range(10): print(another_function(i)) </code></pre> <p>So when i iterates, function f is called with a new argument i every time. How could that be implemented?</p> <p>I found one can use *args as a parameter, but did not see how it could be implemented.</p> <p>Cheers</p>
[ { "answer_id": 74412541, "author": "Cobra", "author_id": 17580381, "author_profile": "https://Stackoverflow.com/users/17580381", "pm_score": 3, "selected": true, "text": "def func1(func, p):\n func(p)\n\nfunc1(print, 'Hello world!')\n" }, { "answer_id": 74412556, "author": "Jasmijn", "author_id": 573255, "author_profile": "https://Stackoverflow.com/users/573255", "pm_score": 1, "selected": false, "text": "def function(another_function):\n for i in range(10):\n print(another_function(i))\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8032824/" ]
74,412,503
<p>I don't know why when <code>a</code> is located in <code>def test()</code> it can not be found and gives the error</p> <blockquote> <p>UnboundLocalError: cannot access local variable 'a' where it is not associated with a value</p> </blockquote> <pre class="lang-py prettyprint-override"><code>import keyboard import time a = 0 def test(): a+= 1 print(&quot;The number is now &quot;, a) time.sleep(1) while keyboard.is_pressed('i') == False: test() </code></pre> <p>I tried setting <code>a</code> as <code>global a</code> or using a <code>nonlocal</code> modifier on it inside the <code>def</code> but it doesn't seem to work. Is there a way I can get it to recognize <code>a</code> and run properly?</p>
[ { "answer_id": 74412557, "author": "Remzinho", "author_id": 2484591, "author_profile": "https://Stackoverflow.com/users/2484591", "pm_score": 0, "selected": false, "text": "a" }, { "answer_id": 74412646, "author": "MSH", "author_id": 2681662, "author_profile": "https://Stackoverflow.com/users/2681662", "pm_score": 0, "selected": false, "text": "def func():\n a = 1\n\nfunc()\nprint(a)\n" }, { "answer_id": 74412647, "author": "José Juan", "author_id": 20386708, "author_profile": "https://Stackoverflow.com/users/20386708", "pm_score": 1, "selected": false, "text": "import keyboard\nimport time\n\na = 0\n\ndef test():\n global a\n a+= 1\n print(\"The number is now \", a)\n time.sleep(1)\n\nwhile keyboard.is_pressed('i') == False:\n \n test()\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20485120/" ]
74,412,532
<p>I am trying to using with recursion function. But I got failed which is segmentation fault.</p> <pre><code>#include &lt;stdio.h&gt; int factorial( int x ); int main(){ factorial(4); return 0; } int factorial( int x ){ return x* factorial(x-1); } </code></pre> <p>I have seen the same code in Python and C programming does not give the same success. I'm wondering why and how can I get around this problem</p>
[ { "answer_id": 74412557, "author": "Remzinho", "author_id": 2484591, "author_profile": "https://Stackoverflow.com/users/2484591", "pm_score": 0, "selected": false, "text": "a" }, { "answer_id": 74412646, "author": "MSH", "author_id": 2681662, "author_profile": "https://Stackoverflow.com/users/2681662", "pm_score": 0, "selected": false, "text": "def func():\n a = 1\n\nfunc()\nprint(a)\n" }, { "answer_id": 74412647, "author": "José Juan", "author_id": 20386708, "author_profile": "https://Stackoverflow.com/users/20386708", "pm_score": 1, "selected": false, "text": "import keyboard\nimport time\n\na = 0\n\ndef test():\n global a\n a+= 1\n print(\"The number is now \", a)\n time.sleep(1)\n\nwhile keyboard.is_pressed('i') == False:\n \n test()\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15205118/" ]
74,412,543
<p>I was making a project in react so the problem I was encountering was that there is a submit button in a form field and whenever someone clicks on it should have a fetch, I did the same there, and then when I saw the output and clicks the button the page refreshes and it didn't fetch</p> <p>Here's some code</p> <p>Function to be called on button click</p> <pre><code>const submit = () =&gt; { fetch('http://localhost:3001/quizInfo',{ method: 'POST', mode: 'cors', cache: 'no-cache', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, redirect: 'follow', referrerPolicy: 'no-referrer', body: JSON.stringify({ ID: GameId }) }) .then(res =&gt; res.json()) .then(data =&gt; console.log(data[0].ques1)) } </code></pre> <p>form field</p> <pre><code>form&gt; &lt;div id=&quot;jn&quot;&gt; &lt;div id=&quot;inps&quot;&gt; &lt;input type=&quot;number&quot; className='si' id=&quot;mdinp&quot; onChange={formChangeID} placeholder='Enter Id'&gt;&lt;/input&gt;&lt;br&gt;&lt;/br&gt; &lt;input type=&quot;password&quot; className='si is' id=&quot;mdinp2&quot; onChange={formChangePASS} disabled placeholder='Enter Password'&gt;&lt;/input&gt;&lt;br&gt;&lt;/br&gt; &lt;input type=&quot;submit&quot; onClick={submit} id='mdg' value=&quot;GO!&quot; disabled&gt;&lt;/input&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>After this code the page refreshes and I also use e.preventDefault function to stop it because I same issue before but it doesn't worked</p> <p>function with preventDefault:</p> <pre><code>const submit = (event) =&gt; { event.preventDefault(); fetch('http://localhost:3001/quizInfo',{ method: 'POST', mode: 'cors', cache: 'no-cache', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, redirect: 'follow', referrerPolicy: 'no-referrer', body: JSON.stringify({ ID: GameId }) }) .then(res =&gt; res.json()) .then(data =&gt; console.log(data[0].ques1)) event.preventDefault(); } </code></pre> <p>I would be grateful if someone helps me.</p>
[ { "answer_id": 74412557, "author": "Remzinho", "author_id": 2484591, "author_profile": "https://Stackoverflow.com/users/2484591", "pm_score": 0, "selected": false, "text": "a" }, { "answer_id": 74412646, "author": "MSH", "author_id": 2681662, "author_profile": "https://Stackoverflow.com/users/2681662", "pm_score": 0, "selected": false, "text": "def func():\n a = 1\n\nfunc()\nprint(a)\n" }, { "answer_id": 74412647, "author": "José Juan", "author_id": 20386708, "author_profile": "https://Stackoverflow.com/users/20386708", "pm_score": 1, "selected": false, "text": "import keyboard\nimport time\n\na = 0\n\ndef test():\n global a\n a+= 1\n print(\"The number is now \", a)\n time.sleep(1)\n\nwhile keyboard.is_pressed('i') == False:\n \n test()\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16418576/" ]
74,412,546
<p>I'm using a ReorderableListView builder in combination with a Bottom App Bar with a FAB. I set extendBody because I want the FAB notch to be transparent when scrolling up/down the list. However with a ReorderableListView I cannot scroll down to the last list item because the list item is hidden behind the Bottom App Bar.</p> <p>Here's a demonstration:</p> <p><a href="https://i.stack.imgur.com/h5Vxf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/h5Vxf.png" alt="enter image description here" /></a></p> <p>This is not the case with a regular ListView as you can see in the code example below and on this picture right here. This would be my intended behaviour because the last list item is fully visible:</p> <p><a href="https://i.stack.imgur.com/o8V5H.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/o8V5H.png" alt="enter image description here" /></a></p> <p>Important: It's not a solution to just set extendBody to false because there would be no transparent notch when scrolling. The scrolling behaviour itself is correct for ReorderableListView and ListView and looks like this when scrolling:</p> <p><a href="https://i.stack.imgur.com/8Wkwc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8Wkwc.png" alt="enter image description here" /></a></p> <p>Is there a way to access the last list element with a Reorderable List View similar than with a List View?</p> <p>Here's a code example with both versions:</p> <pre><code>import 'package:flutter/material.dart'; void main() { runApp(SO()); } class SO extends StatelessWidget { List&lt;String&gt; myList = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;, &quot;f&quot;, &quot;g&quot;, &quot;h&quot;]; @override Widget build(BuildContext context) { return MaterialApp( home: Builder( builder: (context) =&gt; Scaffold( extendBody: true, appBar: AppBar(), body: // CANNOT scroll up to the last element ReorderableListView.builder( itemCount: myList.length, itemBuilder: (BuildContext context, int index) { return Container( key: ValueKey(myList[index]), height: 150, color: Colors.green, child: Center(child: Text('Entry ${myList[index]}')), ); }, onReorder: (oldIndex, newIndex){ if (newIndex &gt; oldIndex) newIndex --; final item = myList.removeAt(oldIndex); myList.insert(newIndex, item); }, ), /* // CAN scroll up to the last element ListView.builder(itemCount: myList.length, itemBuilder: (BuildContext context, int index) { return Container( key: ValueKey(myList[index]), height: 150, color: Colors.green, child: Center(child: Text('Entry ${myList[index]}')), ); }, ), */ floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, floatingActionButton: FloatingActionButton( onPressed: () {}, ), bottomNavigationBar: BottomAppBar( shape: const CircularNotchedRectangle(), notchMargin: 18, color: Colors.blue, child: Container( height: 60, ), ), ) ) ); } } </code></pre>
[ { "answer_id": 74412615, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 2, "selected": true, "text": "padding" }, { "answer_id": 74412636, "author": "Ganesh Somani", "author_id": 1220868, "author_profile": "https://Stackoverflow.com/users/1220868", "pm_score": 0, "selected": false, "text": "ReorderableListView.builder(\n padding(EdgeInsets.only(bottom: 60.0)),\n ...\n)\n" }, { "answer_id": 74412731, "author": "fazilSizzlers", "author_id": 1889044, "author_profile": "https://Stackoverflow.com/users/1889044", "pm_score": 0, "selected": false, "text": "\nReorderableListView.builder(\npadding: EdgeInsets.only(bottom: kBottomNavigationBarHeight + 15.0), // add this\n itemCount: myList.length,\n itemBuilder: (BuildContext context, int index) {\n return Container(\n key: ValueKey(myList[index]),\n height: 150,\n color: Colors.green,\n child: Center(child: Text('Entry ${myList[index]}')),\n );\n },\n onReorder: (oldIndex, newIndex){\n if (newIndex > oldIndex) newIndex --;\n final item = myList.removeAt(oldIndex);\n myList.insert(newIndex, item);\n },\n ),\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9564867/" ]
74,412,568
<p>The python version in my OS:</p> <pre><code>python3 --version Python 3.9.2 </code></pre> <p>Create a folder with <code>venv</code>.</p> <pre><code>python3 -m venv myproject </code></pre> <p>Now i can activate the virtual environment.</p> <pre><code>cd myproject ~/myproject$ sh bin/activate </code></pre> <p>I can't deactivate it,no deactivate script in the myproject.</p> <pre><code>tree -r myproject | rg deactivate #Nothing as output deactivate bash: deactivate: command not found </code></pre> <p>How can deactivate the virtual environment then?</p>
[ { "answer_id": 74412615, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 2, "selected": true, "text": "padding" }, { "answer_id": 74412636, "author": "Ganesh Somani", "author_id": 1220868, "author_profile": "https://Stackoverflow.com/users/1220868", "pm_score": 0, "selected": false, "text": "ReorderableListView.builder(\n padding(EdgeInsets.only(bottom: 60.0)),\n ...\n)\n" }, { "answer_id": 74412731, "author": "fazilSizzlers", "author_id": 1889044, "author_profile": "https://Stackoverflow.com/users/1889044", "pm_score": 0, "selected": false, "text": "\nReorderableListView.builder(\npadding: EdgeInsets.only(bottom: kBottomNavigationBarHeight + 15.0), // add this\n itemCount: myList.length,\n itemBuilder: (BuildContext context, int index) {\n return Container(\n key: ValueKey(myList[index]),\n height: 150,\n color: Colors.green,\n child: Center(child: Text('Entry ${myList[index]}')),\n );\n },\n onReorder: (oldIndex, newIndex){\n if (newIndex > oldIndex) newIndex --;\n final item = myList.removeAt(oldIndex);\n myList.insert(newIndex, item);\n },\n ),\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20311786/" ]
74,412,579
<p>I investigate boguszpawlowski Compose Calendar and I cannot find a way to track state changes of the component, because there are no callback for it. For example I need to get events only for current month (send a request) and after it I should show them in calendar. When user switch month I should send a request again. Author in description suggest using state hoisting for it.</p> <blockquote> <p>In case you need to react to the state changes, or change the state from the outside of the composable, you need to hoist the state out of the Calendar composable:</p> </blockquote> <pre><code> @Composable fun MainScreen() { val calendarState = rememberCalendarState() StaticCalendar(calendarState = calendarState) // now you can manipulate the state from scope of this composable calendarState.monthState.currentMonth = MonthYear.of(2020, 5) } </code></pre> <p>I understand how to change current of initial month, but I do not know how to listen event when user swipe calendar or click the button to change month. How can I do it?</p> <p><a href="https://github.com/boguszpawlowski/ComposeCalendar" rel="nofollow noreferrer">boguszpawlowski ComposeCalendar github link</a></p>
[ { "answer_id": 74412735, "author": "Gabriele Mariotti", "author_id": 2016562, "author_profile": "https://Stackoverflow.com/users/2016562", "pm_score": 1, "selected": false, "text": "CalendarState" }, { "answer_id": 74412767, "author": "Arvin Rezaei", "author_id": 2851528, "author_profile": "https://Stackoverflow.com/users/2851528", "pm_score": 3, "selected": true, "text": "LaunchedEffect(calendarState){\n// your conditions\n// do your api call here\n}\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4200187/" ]
74,412,581
<p>I have a set of callbacks that may run on different durations before I close my web app. I also have a timeout where if it reaches past the timeout duration, I also close the application. The reason for this is to prevent the callbacks from blocking in closing the web app if it passes timeout duration.</p> <p>Here is my current solution:</p> <pre><code> public close() { const callbacks = this.onBeforeCloseCallbacks.map((cb) =&gt; new Promise(res =&gt; res(cb()))); const timeout = new Promise((res) =&gt; setTimeout(res, TIMEOUT_DURATION)); await Promise.race([Promise.all(callbacks), timeout]).then((value) =&gt; { // Currently returns Promise.all(callbacks) right away console.log(value) }); await this.pluginEngine.close(); } } </code></pre> <p>These are my tests</p> <pre><code>it('Should still close the plugin when timing out', async () =&gt; { // Arrange const cleanupMock = jest.fn(); const cb1 = jest.fn().mockReturnValue(async () =&gt; new Promise(resolve =&gt; setTimeout(() =&gt; resolve(console.log('cb1')), 3000))); const cleanupMock2 = jest.fn(); const cb2 = jest.fn().mockReturnValue(async () =&gt; new Promise(resolve =&gt; setTimeout(() =&gt; resolve(console.log('cb2')), 11000))); const placementCloseService = new PlacementCloseService(integrationMock, pluginInterface); // Act // onBeforeClose is registering callbacks that needs to be run before close placementCloseService.onBeforeClose(cb1); placementCloseService.onBeforeClose(cb2); await placementCloseService.close(); // Assert expect(cleanupMock).toBeCalled(); expect(cleanupMock2).not.toBeCalled(); expect(pluginInterface.context.close).toBeCalled(); }); </code></pre> <p>My current solution is returning <code>Promise.all(callbacks)</code> even if it hasn't called expected callbacks to run yet. What I expect to happen is that it passes through my <code>timeout</code> instead since it has a timer of 4000 and the last closeCallback has a timer of 5000.</p> <p>What am I doing wrong?</p>
[ { "answer_id": 74412604, "author": "Matthieu Riegler", "author_id": 884123, "author_profile": "https://Stackoverflow.com/users/884123", "pm_score": 1, "selected": false, "text": "closeCallbacks" }, { "answer_id": 74412606, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 0, "selected": false, "text": "async" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5871609/" ]
74,412,625
<p>I have algorithm that uses iterators, but there is a problem with transforming values, when we need more than single source value. All transform iterators just get some one arg and transforms it. (see <a href="https://stackoverflow.com/questions/11424565/how-can-i-write-an-iterator-wrapper-that-combines-groups-of-sequential-values-fr">similar question from the past</a>) Code example:</p> <pre><code>template&lt;typename ForwardIt&gt; double some_algorithm(ForwardIt begin, ForwardIt end) { double result = 0; for (auto it = begin; it != end; ++it) { double t = *it; /* do some calculations.. */ result += t; } return result; } int main() { { std::vector&lt;double&gt; distances{ 1, 2, 3, 4 }; double t = some_algorithm(distances.begin(), distances.end()); std::cout &lt;&lt; t &lt;&lt; std::endl; /* works great */ } { /* lets now work with vector of points.. */ std::vector&lt;double&gt; points{ 1, 2, 4, 7, 11 }; /* convert to distances.. */ std::vector&lt;double&gt; distances; distances.resize(points.size() - 1); for (size_t i = 0; i + 1 &lt; points.size(); ++i) distances[i] = points[i + 1] - points[i]; /* invoke algorithm */ double t = some_algorithm(distances.begin(), distances.end()); std::cout &lt;&lt; t &lt;&lt; std::endl; } } </code></pre> <p>Is there a way (especialy using std) to create such an iterator wrapper to avoid explicitly generating distances value? It could be fine to perform something like this:</p> <pre><code>template&lt;typename BaseIterator, typename TransformOperator&gt; struct GenericTransformIterator { GenericTransformIterator(BaseIterator it, TransformOperator op) : it(it), op(op) {} auto operator*() { return op(it); } GenericTransformIterator&amp; operator++() { ++it; return *this; } BaseIterator it; TransformOperator op; friend bool operator!=(GenericTransformIterator a, GenericTransformIterator b) { return a.it != b.it; } }; </code></pre> <p>and use like:</p> <pre><code>{ /* lets now work with vector of points.. */ std::vector&lt;double&gt; points{ 1, 2, 4, 7, 11 }; /* use generic transform iterator.. */ /* invoke algorithm */ auto distance_op = [](auto it) { auto next_it = it; ++next_it; return *next_it - *it; }; double t = some_algorithm( generic_transform_iterator(points.begin(), distance_op), generic_transform_iterator(points.end() -1 , distance_op)); std::cout &lt;&lt; t &lt;&lt; std::endl; } </code></pre> <p>So general idea is that transform function is not invoked on underlying object, but on iterator (or at least has some index value, then lambda can capture whole container and access via index).</p> <p>I used to use boost which has lot of various iterator wrapping class. But since cpp20 and ranges I'm curious if there is a way to use something existing from std:: rather than writing own wrappers.</p>
[ { "answer_id": 74413258, "author": "rturrado", "author_id": 260313, "author_profile": "https://Stackoverflow.com/users/260313", "pm_score": 1, "selected": false, "text": "points" }, { "answer_id": 74413685, "author": "bcsb1001", "author_id": 3529323, "author_profile": "https://Stackoverflow.com/users/3529323", "pm_score": 3, "selected": true, "text": "std::views::pairwise" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2561762/" ]
74,412,630
<p>I am looking for an elegant way to check if a given index is inside a numpy array (for example for BFS algorithms on a grid).</p> <p>The following code does what I want:</p> <pre><code>import numpy as np def isValid(np_shape: tuple, index: tuple): if min(index) &lt; 0: return False for ind,sh in zip(index,np_shape): if ind &gt;= sh: return False return True arr = np.zeros((3,5)) print(isValid(arr.shape,(0,0))) # True print(isValid(arr.shape,(2,4))) # True print(isValid(arr.shape,(4,4))) # False </code></pre> <p>But I'd prefer something build-in or more elegant than writing my own function including python for-loops (yikes)</p>
[ { "answer_id": 74412751, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "def isValid(np_shape: tuple, index: tuple):\n index = np.array(index)\n return (index >= 0).all() and (index < arr.shape).all()\n\narr = np.zeros((3,5))\nprint(isValid(arr.shape,(0,0))) # True\nprint(isValid(arr.shape,(2,4))) # True\nprint(isValid(arr.shape,(4,4))) # False\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20345339/" ]
74,412,645
<p>I have a <code>func_df</code> with 4 functions:</p> <pre><code> x y1 y2 y3 y4 0 -20.0 -0.839071 10.0 0.816164 -8795.000 1 -19.9 -0.865213 9.9 0.994372 -8667.619 2 -19.8 -0.889191 9.8 1.162644 -8541.472 3 -19.7 -0.910947 9.7 1.319299 -8416.553 4 -19.6 -0.930426 9.6 1.462772 -8292.856 .. ... ... ... ... ... 395 19.5 -0.947580 9.5 1.591630 6659.375 396 19.6 -0.930426 9.6 1.462772 6766.216 397 19.7 -0.910947 9.7 1.319299 6874.193 398 19.8 -0.889191 9.8 1.162644 6983.312 399 19.9 -0.865213 9.9 0.994372 7093.579 </code></pre> <p>And a <code>test_df</code> with scatter points:</p> <pre><code> x y 0 -6.2 0.360801 1 6.4 -3.655422 2 -17.6 -6065.659700 3 -1.5 -3.247304 4 -17.7 -0.785430 .. ... ... 95 1.6 3.722551 96 16.3 -1.067487 97 -13.3 1.857445 98 -3.8 -0.008831 99 -13.2 1.294064 </code></pre> <p>I want to find the deviation(distance) between all the scatter points and the 4 functions when the x-value is the same on both data frames.</p> <p>There are some scatter points with same x-value and different y-value.</p> <p><strong>Edit:</strong> A quick example:</p> <p>Starting with column <code>y1</code> from <code>func_df</code>:</p> <p>1st value is x = -20.0 , y1 = -0.839071.</p> <p>I want the program to search if there a row in which x = -20.0 in <code>test_df</code> and if so, then find the difference between the y-value of that row and the y-value of <code>func_df</code>, which is -0.839071.</p> <p>Imagine that in <code>test_df</code> there is a row with x = -20, y = -1. Then what I want is <code>abs(-1 - 0.839071)</code>. I used <code>abs()</code> because the distance has to be a positive value</p> <p>This was for the row 0 of column y1. I need it for all rows and also for y2, y3 and y4 of <code>func_df</code>.</p> <hr /> <p>I tried something like this:</p> <pre><code>if test_df.x.equals(func.x): result_df = func.iloc[:, 1:5].apply(lambda cell: cell - test_df.y[cell.index]) </code></pre> <p>But honestly was a shot in the dark, no idea what I'm doing.</p>
[ { "answer_id": 74414970, "author": "The Lazy Graybeard", "author_id": 9608497, "author_profile": "https://Stackoverflow.com/users/9608497", "pm_score": 2, "selected": false, "text": "merged_df = pandas.merge(test_df, func_df, on='x')\nabs_delta_y1 = (merged_df['y'] - merged_df['y1']).abs()\n\netc...\n" }, { "answer_id": 74415107, "author": "Bushmaster", "author_id": 15415267, "author_profile": "https://Stackoverflow.com/users/15415267", "pm_score": 3, "selected": true, "text": "func_df=pd.DataFrame(data={'x':[-20.9,-20.8,-20.7,-20.6],'y1':[-0.12,-0.021,-0.04,-0.91],\n 'y2':[10.0,9.9,9.8,9.7],'y3':[0.99437,1.162644,1.319299,1.462772],\n 'y4':[-8667.619,-8541.472,-8416.553,-8292.856]})\nprint(func_df)\n'''\n\n x y1 y2 y3 y4\n0 -20.9 -0.120 10.0 0.994370 -8667.619\n1 -20.8 -0.021 9.9 1.162644 -8541.472\n2 -20.7 -0.040 9.8 1.319299 -8416.553\n3 -20.6 -0.910 9.7 1.462772 -8292.856\n'''\ntest_df=pd.DataFrame(data={'x':[-20.9,-15.2],'y':[0.360801,-3.655422]})\nprint(test_df)\n'''\n x y\n0 -20.9 0.360801\n1 -15.2 -3.655422\n'''\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20458338/" ]
74,412,648
<p>I have a empty list of tuple and I wish to enter values inside that tuple.</p> <p>The desired output is :</p> <p><code>lst = [()] --&gt; lst = [(1,2,'string1','string2',3)]</code></p>
[ { "answer_id": 74412705, "author": "Igor Cantele", "author_id": 16807584, "author_profile": "https://Stackoverflow.com/users/16807584", "pm_score": 1, "selected": false, "text": "lst = [()]\nlst[0] = (\"item1\", \"item2\")\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16022823/" ]
74,412,665
<p>Currently, I have this script which if it errors, it completely restarts. Which is perfect for what I need.</p> <p>But there is one problem, I want the script to automatically restart, even when it did not crash. every 30 seconds.</p> <p>This is what I have:</p> <pre><code>while True: try: do_main_logic() except: pass </code></pre> <p>I am expecting for it to just restart the entire script every 30 seconds and start from the begin. Even if it has not crashed or not.</p>
[ { "answer_id": 74412703, "author": "José Juan", "author_id": 20386708, "author_profile": "https://Stackoverflow.com/users/20386708", "pm_score": 0, "selected": false, "text": "import time\n \nwhile True:\n time.sleep(30)\n try: \n do_main_logic()\n except:\n pass\n" }, { "answer_id": 74412710, "author": "Will", "author_id": 12829151, "author_profile": "https://Stackoverflow.com/users/12829151", "pm_score": 1, "selected": false, "text": "import time\n\nwhile True:\n try:\n do_main_logic()\n except:\n pass\n finally:\n time.sleep(30)\n" }, { "answer_id": 74412884, "author": "zzkluck", "author_id": 20483971, "author_profile": "https://Stackoverflow.com/users/20483971", "pm_score": 0, "selected": false, "text": "threading.Timer" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16901344/" ]
74,412,672
<p>What I have</p> <pre><code>import Home from &quot;./components/underpages/Home&quot;; import Kontakt from &quot;./components/underpages/Kontakt&quot;; import FAQ from &quot;./components/underpages/FAQ&quot;; // [...] &lt;Routes&gt; &lt;Route path=&quot;/&quot; element={&lt;Home /&gt;} /&gt; &lt;Route path=&quot;/Kontakt&quot; element={&lt;Kontakt /&gt;} /&gt; &lt;Route path=&quot;/FAQ&quot; element={&lt;FAQ /&gt;} /&gt; &lt;/Routes&gt; </code></pre> <p>What I want:</p> <pre><code>{siteList.map((sites) =&gt; ( import {site.Name} from &quot;./components/underpages&quot; + {site.path}; ))} // [...] {siteList.map((sites) =&gt; ( &lt;Route path= {site.path} element={&lt;{site.emelent} /&gt;} /&gt; ))} </code></pre> <p>is there a way something like this, which will work?</p> <p>I want to shorten my <code>Routes</code> and use the <code>.map</code>-function. in this way, it doesn't work, but is there another way?</p>
[ { "answer_id": 74412703, "author": "José Juan", "author_id": 20386708, "author_profile": "https://Stackoverflow.com/users/20386708", "pm_score": 0, "selected": false, "text": "import time\n \nwhile True:\n time.sleep(30)\n try: \n do_main_logic()\n except:\n pass\n" }, { "answer_id": 74412710, "author": "Will", "author_id": 12829151, "author_profile": "https://Stackoverflow.com/users/12829151", "pm_score": 1, "selected": false, "text": "import time\n\nwhile True:\n try:\n do_main_logic()\n except:\n pass\n finally:\n time.sleep(30)\n" }, { "answer_id": 74412884, "author": "zzkluck", "author_id": 20483971, "author_profile": "https://Stackoverflow.com/users/20483971", "pm_score": 0, "selected": false, "text": "threading.Timer" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19749827/" ]
74,412,690
<pre class="lang-cs prettyprint-override"><code>save: try { s.Save(); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { FSErrorDialog fsError = new(ex, FSVerb.Access, new FileInfo(path), Button.Retry, Button.Ignore); if (fsError.ShowDialog().ClickedButton == Button.Retry) { goto save; } } </code></pre> <p>The <code>Save()</code> method saves the object to the disk. If an exogenous exception occurs, the user is prompted to retry the operation to avoid loosing unsaved data.</p> <p>I know I could use a <code>while (true)</code> loop with break statements but I think the goto approach is more readable. It also saves an indentation level.</p> <p>I am scared of using goto.</p> <p>Is this a legitimate use of goto statements?</p>
[ { "answer_id": 74412704, "author": "ProgrammingLlama", "author_id": 3181933, "author_profile": "https://Stackoverflow.com/users/3181933", "pm_score": 2, "selected": false, "text": "bool shouldRetry;\ndo\n{\n try\n {\n s.Save();\n shouldRetry = false;\n }\n catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)\n {\n FSErrorDialog fsError = new(ex, FSVerb.Access, new FileInfo(AppDirectory.Scripts.Join(s.FilePath)), Button.Retry, Button.Ignore);\n shouldRetry = fsError.ShowDialog().ClickedButton == Button.Retry;\n }\n}\nwhile (shouldRetry);\n" }, { "answer_id": 74413247, "author": "Dmitry Bychenko", "author_id": 2319407, "author_profile": "https://Stackoverflow.com/users/2319407", "pm_score": 1, "selected": false, "text": "while (true) {\n try {\n s.Save();\n\n break; // No more looping (success)\n }\n catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) {\n FSErrorDialog fsError = new(ex, FSVerb.Access, new FileInfo(path), Button.Retry, Button.Ignore);\n \n if (fsError.ShowDialog().ClickedButton != Button.Retry)\n break; // No more looping (no more tries) \n }\n}\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11718061/" ]
74,412,691
<p>I am trying to print all paths from source= 2 to destination = 3 with a graph that has the following edges:</p> <pre><code>g.addEdge(0, 1) g.addEdge(0, 2) g.addEdge(0, 3) g.addEdge(2, 0) g.addEdge(2, 1) g.addEdge(1, 3) </code></pre> <p>When I print the variable &quot;all_paths&quot;, it prints all possible paths correctly. However, when I try to append this result to a list (&quot;all_paths&quot;), it returns a list of empty list.</p> <p>See the part in the code:</p> <pre><code> if u == d: all_paths.append(path) print(path) </code></pre> <p>print(path) prints:</p> <pre><code> [2, 0, 1, 3] [2, 0, 3] [2, 1, 3] </code></pre> <p>The code returns:</p> <pre><code>[[], [], []] </code></pre> <p>It probably has something to do with the recursion but I cannot seem to figure it out.</p> <p>I would like to return a list that contains:</p> <pre><code>[[2, 0, 1, 3], [2, 0, 3], [2, 1, 3]] </code></pre> <p>Below you can view the code:</p> <pre><code>from collections import defaultdict # This class represents a directed graph # using adjacency list representation class Graph: def __init__(self, vertices): # No. of vertices self.V = vertices # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) '''A recursive function to print all paths from 'u' to 'd'. visited[] keeps track of vertices in current path. path[] stores actual vertices and path_index is current index in path[]''' def printAllPathsUtil(self, u, d, visited, path, all_paths): # Mark the current node as visited and store in path visited[u]= True path.append(u) # If current vertex is same as destination, then print # current path[] if u == d: all_paths.append(path) print(path) else: # If current vertex is not destination # Recur for all the vertices adjacent to this vertex for i in self.graph[u]: if visited[i]== False: self.printAllPathsUtil(i, d, visited, path, all_paths) # Remove current vertex from path[] and mark it as unvisited path.pop() visited[u]= False return all_paths # Prints all paths from 's' to 'd' def printAllPaths(self, s, d): # Mark all the vertices as not visited visited =[False]*(self.V) # Create an array to store paths path = [] all_paths = [] # Call the recursive helper function to print all paths all_paths = self.printAllPathsUtil(s, d, visited, path, all_paths) print(all_paths) return all_paths g = Graph(4) g.addEdge(0, 1) g.addEdge(0, 2) g.addEdge(0, 3) g.addEdge(2, 0) g.addEdge(2, 1) g.addEdge(1, 3) s = 2 ; d = 3 print (&quot; These are the all unique paths from node %d to %d : &quot; %(s, d)) g.printAllPaths(s, d) </code></pre> <p>I also tried to store it in a self.all_paths but this did not work. I was expecting that when appending the path to all_paths it would work.</p>
[ { "answer_id": 74416279, "author": "Tadhg McDonald-Jensen", "author_id": 5827215, "author_profile": "https://Stackoverflow.com/users/5827215", "pm_score": 0, "selected": false, "text": "path" }, { "answer_id": 74419498, "author": "Stacker", "author_id": 20485288, "author_profile": "https://Stackoverflow.com/users/20485288", "pm_score": 1, "selected": false, "text": "if u == d:\n all_paths.append(path)\n print(path)\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20485288/" ]
74,412,693
<p>I'm trying to fetch file from Google Drive using Apache Beam. I tried,</p> <pre><code>filenames = ['https://drive.google.com/file/d/&lt;file_id&gt;'] with beam.Pipeline() as pipeline: lines = (pipeline | beam.Create(filenames)) print(lines) </code></pre> <p>This returns a string like <code>PCollection[[19]: Create/Map(decode).None]</code></p> <p>I need to read a file from Google Drive and write it into GCS bucket. How can I read a file form G Drive from Apache beam?</p>
[ { "answer_id": 74416279, "author": "Tadhg McDonald-Jensen", "author_id": 5827215, "author_profile": "https://Stackoverflow.com/users/5827215", "pm_score": 0, "selected": false, "text": "path" }, { "answer_id": 74419498, "author": "Stacker", "author_id": 20485288, "author_profile": "https://Stackoverflow.com/users/20485288", "pm_score": 1, "selected": false, "text": "if u == d:\n all_paths.append(path)\n print(path)\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3943600/" ]
74,412,741
<p>I want to get a variable from a JSON file to python but it says that the local variable 'id' is referenced before assignment</p> <pre><code>def getInfo(name): with open(&quot;data.json&quot;) as file: file_data = json.load(file) for i in file_data[&quot;data&quot;]: if i[&quot;name&quot;] == name: id = i[&quot;id&quot;] return id </code></pre>
[ { "answer_id": 74412808, "author": "Eliav Louski", "author_id": 10577976, "author_profile": "https://Stackoverflow.com/users/10577976", "pm_score": -1, "selected": true, "text": "class Info:\n\n def __init__(self):\n pass\n def getInfo(self,name):\n with open(\"data.json\") as file:\n file_data = json.load(file)\n id=None # <<< here\n for i in file_data[\"data\"]:\n if i[\"name\"] == name:\n id = i[\"id\"]\n\n\n return id\n\n" }, { "answer_id": 74412872, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 0, "selected": false, "text": "getInfo()" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14726294/" ]
74,412,744
<p>I've created a new swiftui project in Xcode 14.1 on a MacBook Air M1</p> <p>It will build and run if I add these pods</p> <p>pod 'FirebaseFirestoreSwift'<br /> pod 'GoogleMLKit/Translate', '3.2.0'</p> <p><strong>OR</strong></p> <p>pod 'FirebaseStorage'<br /> pod 'GoogleMLKit/Translate', '3.2.0'</p> <p><strong>OR</strong></p> <p>pod 'FirebaseFirestoreSwift'<br /> pod 'FirebaseStorage'</p> <p>But if I try to add all three pods together (</p> <p>'FirebaseStorage'<br /> 'FirebaseFirestoreSwift'<br /> 'GoogleMLKit/Translate', '3.2.0'</p> <p>) the project will not build and the Xcode error is:</p> <p>~/Pods/GoogleUtilitiesComponents/GoogleUtilitiesComponents/Sources/GULCCComponentContainer.m:22:9 'GoogleUtilities/GULLogger.h' file not found</p> <p>There are also these warnings in the terminal after <code>pod install</code> but only when installing the three problematic pods together.</p> <pre><code>Analyzing dependencies Downloading dependencies Installing BoringSSL-GRPC (0.0.24) Installing FirebaseAnalytics (3.4.2) Installing FirebaseCore (10.1.0) Installing FirebaseCoreExtension (10.1.0) Installing FirebaseCoreInternal (10.1.0) Installing FirebaseFirestore (10.1.0) Installing FirebaseFirestoreSwift (10.1.0) Installing FirebaseInstanceID (1.0.9) Installing FirebaseSharedSwift (10.1.0) Installing FirebaseStorage (1.0.4) Installing GTMSessionFetcher (1.7.2) Installing GoogleDataTransport (9.2.0) Installing GoogleInterchangeUtilities (1.2.2) Installing GoogleMLKit (3.2.0) Installing GoogleSymbolUtilities (1.1.2) Installing GoogleToolboxForMac (2.3.2) Installing GoogleUtilities (1.3.2) Installing GoogleUtilities (7.10.0) Installing GoogleUtilitiesComponents (1.1.0) Installing Libuv-gRPC (0.0.10) Installing MLKitCommon (8.0.0) Installing MLKitNaturalLanguage (4.2.0) Installing MLKitTranslate (2.2.0) Installing PromisesObjC (2.1.1) Installing Protobuf (3.21.9) Installing SSZipArchive (2.4.3) Installing abseil (1.20211102.0) Installing gRPC-C++ (1.44.0) Installing gRPC-Core (1.44.0) Installing leveldb-library (1.22.1) Installing nanopb (2.30909.0) Generating Pods project Integrating client project Pod installation complete! There are 3 dependencies from the Podfile and 31 total pods installed. [!] Unable to read the license file `LICENSE` for the spec `GoogleUtilities (7.10.0)` [!] Unable to read the license file `LICENSE` for the spec `GoogleUtilities (7.10.0)` [!] [Xcodeproj] Generated duplicate UUIDs: PBXFileReference -- Pods.xcodeproj/mainGroup/children/children:children:|,|,|,displayName:BoringSSL-GRPC,isa:PBXGroup,name:BoringSSL-GRPC,path:BoringSSL-GRPC,sourceTree:&lt;group&gt;,,children:|,|,displayName:FirebaseAnalytics,isa:PBXGroup,name:FirebaseAnalytics,path:FirebaseAnalytics,sourceTree:&lt;group&gt;,,children:|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,displayName:FirebaseCore,isa:PBXGroup,name:FirebaseCore,path:FirebaseCore,sourceTree:&lt;group&gt;,,children:|,|,|,|,|,|,|,|,|,|,|,|,displayName:FirebaseCoreExtension,isa:PBXGroup,name:FirebaseCoreExtension,path:FirebaseCoreExtension,sourceTree:&lt;group&gt;,,children:|,|,|,|,|,|,|,|,|,|,|,|,displayName:FirebaseCoreInternal,isa:PBXGroup,name:FirebaseCoreInternal,path:FirebaseCoreInternal,sourceTree:&lt;group&gt;,,children:|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,displayName:FirebaseFirestore,isa:PBXGroup,name:FirebaseFirestore,path:FirebaseFirestore,sourceTree:&lt;group&gt;,,children:|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,displayName:FirebaseFirestoreSwift,isa:PBXGroup,name:FirebaseFirestoreSwift,path:FirebaseFirestoreSwift,sourceTree:&lt;group&gt;,,children:|,|,displayName:FirebaseInstanceID,isa:PBXGroup,name:FirebaseInstanceID,path:FirebaseInstanceID,sourceTree:&lt;group&gt;,,children:|,|,|,displayName:FirebaseSharedSwift,isa:PBXGroup,name:FirebaseSharedSwift,path:FirebaseSharedSwift,sourceTree:&lt;group&gt;,,children:|,|,displayName:FirebaseStorage,isa:PBXGroup,name:FirebaseStorage,path:FirebaseStorage,sourceTree:&lt;group&gt;,,children:|,|,displayName:GTMSessionFetcher,isa:PBXGroup,name:GTMSessionFetcher,path:GTMSessionFetcher,sourceTree:&lt;group&gt;,,children:|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,displayName:GoogleDataTransport,isa:PBXGroup,name:GoogleDataTransport,path:GoogleDataTransport,sourceTree:&lt;group&gt;,,children:|,|,displayName:GoogleInterchangeUtilities,isa:PBXGroup,name:GoogleInterchangeUtilities,path:GoogleInterchangeUtilities,sourceTree:&lt;group&gt;,,children:|,|,displayName:GoogleMLKit,isa:PBXGroup,name:GoogleMLKit,path:GoogleMLKit,sourceTree:&lt;group&gt;,,children:|,|,displayName:GoogleSymbolUtilities,isa:PBXGroup,name:GoogleSymbolUtilities,path:GoogleSymbolUtilities,sourceTree:&lt;group&gt;,,children:|,|,|,|,|,|,|,|,displayName:GoogleToolboxForMac,isa:PBXGroup,name:GoogleToolboxForMac,path:GoogleToolboxForMac,sourceTree:&lt;group&gt;,,children:|,|,displayName:GoogleUtilities,isa:PBXGroup,name:GoogleUtilities,path:GoogleUtilities,sourceTree:&lt;group&gt;,,children:|,|,|,|,|,|,|,|,|,|,|,displayName:GoogleUtilitiesComponents,isa:PBXGroup,name:GoogleUtilitiesComponents,path:GoogleUtilitiesComponents,sourceTree:&lt;group&gt;,,children:|,|,|,displayName:Libuv-gRPC,isa:PBXGroup,name:Libuv-gRPC,path:Libuv-gRPC,sourceTree:&lt;group&gt;,,children:|,|,displayName:MLKitCommon,isa:PBXGroup,name:MLKitCommon,path:MLKitCommon,sourceTree:&lt;group&gt;,,children:|,|,displayName:MLKitNaturalLanguage,isa:PBXGroup,name:MLKitNaturalLanguage,path:MLKitNaturalLanguage,sourceTree:&lt;group&gt;,,children:|,|,|,displayName:MLKitTranslate,isa:PBXGroup,name:MLKitTranslate,path:MLKitTranslate,sourceTree:&lt;group&gt;,,children:|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,displayName:PromisesObjC,isa:PBXGroup,name:PromisesObjC,path:PromisesObjC,sourceTree:&lt;group&gt;,,children:|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,displayName:Protobuf,isa:PBXGroup,name:Protobuf,path:Protobuf,sourceTree:&lt;group&gt;,,children:|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,displayName:SSZipArchive,isa:PBXGroup,name:SSZipArchive,path:SSZipArchive,sourceTree:&lt;group&gt;,,children:|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,displayName:abseil,isa:PBXGroup,name:abseil,path:abseil,sourceTree:&lt;group&gt;,,children:|,|,|,|,displayName:gRPC-C++,isa:PBXGroup,name:gRPC-C++,path:gRPC-C++,sourceTree:&lt;group&gt;,,children:|,|,|,displayName:gRPC-Core,isa:PBXGroup,name:gRPC-Core,path:gRPC-Core,sourceTree:&lt;group&gt;,,children:|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,displayName:leveldb-library,isa:PBXGroup,name:leveldb-library,path:leveldb-library,sourceTree:&lt;group&gt;,,children:|,|,|,|,|,|,|,|,|,|,displayName:nanopb,isa:PBXGroup,name:nanopb,path:nanopb,sourceTree:&lt;group&gt;,,displayName:Pods,isa:PBXGroup,name:Pods,sourceTree:&lt;group&gt;,/Pods/children/children:children:|,displayName:Frameworks,isa:PBXGroup,name:Frameworks,sourceTree:&lt;group&gt;,,children:|,|,|,|,displayName:Support Files,isa:PBXGroup,name:Support Files,path:../Target Support Files/GoogleUtilities,sourceTree:&lt;group&gt;,,displayName:GoogleUtilities,isa:PBXGroup,name:GoogleUtilities,path:GoogleUtilities,sourceTree:&lt;group&gt;,/Pods/GoogleUtilities/children/children:displayName:GoogleUtilities.debug.xcconfig,includeInIndex:1,isa:PBXFileReference,lastKnownFileType:text.xcconfig,path:GoogleUtilities.debug.xcconfig,sourceTree:&lt;group&gt;,,displayName:GoogleUtilities.release.xcconfig,includeInIndex:1,isa:PBXFileReference,lastKnownFileType:text.xcconfig,path:GoogleUtilities.release.xcconfig,sourceTree:&lt;group&gt;,,displayName:GoogleUtilities.debug.xcconfig,includeInIndex:1,isa:PBXFileReference,lastKnownFileType:text.xcconfig,path:GoogleUtilities.debug.xcconfig,sourceTree:&lt;group&gt;,,displayName:GoogleUtilities.release.xcconfig,includeInIndex:1,isa:PBXFileReference,lastKnownFileType:text.xcconfig,path:GoogleUtilities.release.xcconfig,sourceTree:&lt;group&gt;,,displayName:Support Files,isa:PBXGroup,name:Support Files,path:../Target Support Files/GoogleUtilities,sourceTree:&lt;group&gt;,/Pods/GoogleUtilities/Support Files/children/displayName:GoogleUtilities.debug.xcconfig,includeInIndex:1,isa:PBXFileReference,lastKnownFileType:text.xcconfig,path:GoogleUtilities.debug.xcconfig,sourceTree:&lt;group&gt;,/Pods/GoogleUtilities/Support Files/GoogleUtilities.debug.xcconfig PBXFileReference -- Pods.xcodeproj/mainGroup/children/children:children:|,|,|,displayName:BoringSSL-GRPC,isa:PBXGroup,name:BoringSSL-GRPC,path:BoringSSL-GRPC,sourceTree:&lt;group&gt;,,children:|,|,displayName:FirebaseAnalytics,isa:PBXGroup,name:FirebaseAnalytics,path:FirebaseAnalytics,sourceTree:&lt;group&gt;,,children:|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,displayName:FirebaseCore,isa:PBXGroup,name:FirebaseCore,path:FirebaseCore,sourceTree:&lt;group&gt;,,children:|,|,|,|,|,|,|,|,|,|,|,|,displayName:FirebaseCoreExtension,isa:PBXGroup,name:FirebaseCoreExtension,path:FirebaseCoreExtension,sourceTree:&lt;group&gt;,,children:|,|,|,|,|,|,|,|,|,|,|,|,displayName:FirebaseCoreInternal,isa:PBXGroup,name:FirebaseCoreInternal,path:FirebaseCoreInternal,sourceTree:&lt;group&gt;,,children:|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,displayName:FirebaseFirestore,isa:PBXGroup,name:FirebaseFirestore,path:FirebaseFirestore,sourceTree:&lt;group&gt;,,children:|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,displayName:FirebaseFirestoreSwift,isa:PBXGroup,name:FirebaseFirestoreSwift,path:FirebaseFirestoreSwift,sourceTree:&lt;group&gt;,,children:|,|,displayName:FirebaseInstanceID,isa:PBXGroup,name:FirebaseInstanceID,path:FirebaseInstanceID,sourceTree:&lt;group&gt;,,children:|,|,|,displayName:FirebaseSharedSwift,isa:PBXGroup,name:FirebaseSharedSwift,path:FirebaseSharedSwift,sourceTree:&lt;group&gt;,,children:|,|,displayName:FirebaseStorage,isa:PBXGroup,name:FirebaseStorage,path:FirebaseStorage,sourceTree:&lt;group&gt;,,children:|,|,displayName:GTMSessionFetcher,isa:PBXGroup,name:GTMSessionFetcher,path:GTMSessionFetcher,sourceTree:&lt;group&gt;,,children:|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,displayName:GoogleDataTransport,isa:PBXGroup,name:GoogleDataTransport,path:GoogleDataTransport,sourceTree:&lt;group&gt;,,children:|,|,displayName:GoogleInterchangeUtilities,isa:PBXGroup,name:GoogleInterchangeUtilities,path:GoogleInterchangeUtilities,sourceTree:&lt;group&gt;,,children:|,|,displayName:GoogleMLKit,isa:PBXGroup,name:GoogleMLKit,path:GoogleMLKit,sourceTree:&lt;group&gt;,,children:|,|,displayName:GoogleSymbolUtilities,isa:PBXGroup,name:GoogleSymbolUtilities,path:GoogleSymbolUtilities,sourceTree:&lt;group&gt;,,children:|,|,|,|,|,|,|,|,displayName:GoogleToolboxForMac,isa:PBXGroup,name:GoogleToolboxForMac,path:GoogleToolboxForMac,sourceTree:&lt;group&gt;,,children:|,|,displayName:GoogleUtilities,isa:PBXGroup,name:GoogleUtilities,path:GoogleUtilities,sourceTree:&lt;group&gt;,,children:|,|,|,|,|,|,|,|,|,|,|,displayName:GoogleUtilitiesComponents,isa:PBXGroup,name:GoogleUtilitiesComponents,path:GoogleUtilitiesComponents,sourceTree:&lt;group&gt;,,children:|,|,|,displayName:Libuv-gRPC,isa:PBXGroup,name:Libuv-gRPC,path:Libuv-gRPC,sourceTree:&lt;group&gt;,,children:|,|,displayName:MLKitCommon,isa:PBXGroup,name:MLKitCommon,path:MLKitCommon,sourceTree:&lt;group&gt;,,children:|,|,displayName:MLKitNaturalLanguage,isa:PBXGroup,name:MLKitNaturalLanguage,path:MLKitNaturalLanguage,sourceTree:&lt;group&gt;,,children:|,|,|,displayName:MLKitTranslate,isa:PBXGroup,name:MLKitTranslate,path:MLKitTranslate,sourceTree:&lt;group&gt;,,children:|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,displayName:PromisesObjC,isa:PBXGroup,name:PromisesObjC,path:PromisesObjC,sourceTree:&lt;group&gt;,,children:|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,displayName:Protobuf,isa:PBXGroup,name:Protobuf,path:Protobuf,sourceTree:&lt;group&gt;,,children:|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,displayName:SSZipArchive,isa:PBXGroup,name:SSZipArchive,path:SSZipArchive,sourceTree:&lt;group&gt;,,children:|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,displayName:abseil,isa:PBXGroup,name:abseil,path:abseil,sourceTree:&lt;group&gt;,,children:|,|,|,|,displayName:gRPC-C++,isa:PBXGroup,name:gRPC-C++,path:gRPC-C++,sourceTree:&lt;group&gt;,,children:|,|,|,displayName:gRPC-Core,isa:PBXGroup,name:gRPC-Core,path:gRPC-Core,sourceTree:&lt;group&gt;,,children:|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,|,displayName:leveldb-library,isa:PBXGroup,name:leveldb-library,path:leveldb-library,sourceTree:&lt;group&gt;,,children:|,|,|,|,|,|,|,|,|,|,displayName:nanopb,isa:PBXGroup,name:nanopb,path:nanopb,sourceTree:&lt;group&gt;,,displayName:Pods,isa:PBXGroup,name:Pods,sourceTree:&lt;group&gt;,/Pods/children/children:children:|,displayName:Frameworks,isa:PBXGroup,name:Frameworks,sourceTree:&lt;group&gt;,,children:|,|,|,|,displayName:Support Files,isa:PBXGroup,name:Support Files,path:../Target Support Files/GoogleUtilities,sourceTree:&lt;group&gt;,,displayName:GoogleUtilities,isa:PBXGroup,name:GoogleUtilities,path:GoogleUtilities,sourceTree:&lt;group&gt;,/Pods/GoogleUtilities/children/children:displayName:GoogleUtilities.debug.xcconfig,includeInIndex:1,isa:PBXFileReference,lastKnownFileType:text.xcconfig,path:GoogleUtilities.debug.xcconfig,sourceTree:&lt;group&gt;,,displayName:GoogleUtilities.release.xcconfig,includeInIndex:1,isa:PBXFileReference,lastKnownFileType:text.xcconfig,path:GoogleUtilities.release.xcconfig,sourceTree:&lt;group&gt;,,displayName:GoogleUtilities.debug.xcconfig,includeInIndex:1,isa:PBXFileReference,lastKnownFileType:text.xcconfig,path:GoogleUtilities.debug.xcconfig,sourceTree:&lt;group&gt;,,displayName:GoogleUtilities.release.xcconfig,includeInIndex:1,isa:PBXFileReference,lastKnownFileType:text.xcconfig,path:GoogleUtilities.release.xcconfig,sourceTree:&lt;group&gt;,,displayName:Support Files,isa:PBXGroup,name:Support Files,path:../Target Support Files/GoogleUtilities,sourceTree:&lt;group&gt;,/Pods/GoogleUtilities/Support Files/children/displayName:GoogleUtilities.release.xcconfig,includeInIndex:1,isa:PBXFileReference,lastKnownFileType:text.xcconfig,path:GoogleUtilities.release.xcconfig,sourceTree:&lt;group&gt;,/Pods/GoogleUtilities/Support Files/GoogleUtilities.release.xcconfig [!] [Xcodeproj] Generated duplicate UUIDs: PBXAggregateTarget -- 8D7F5D5DD528D21A72DC87ADA5B12E2D </code></pre> <p>and her is the Podfile:</p> <pre><code> target 'testTranslateAndFirebase' do use_frameworks! pod 'FirebaseStorage' pod 'FirebaseFirestoreSwift' pod 'GoogleMLKit/Translate', '3.2.0' end </code></pre> <p>EDIT: - I tried the depreciated 'FirebaseMLNLTranslate' in place of 'GoogleMLKit/Translate' and there is no build error. App builds, runs and translates. How can I get the current GoogleMLKit/Translate working with both firebase pods as it does install and build when in conjunction with a single firebase pod?</p> <p>Can anyone help or confirm this as a bug?</p>
[ { "answer_id": 74412808, "author": "Eliav Louski", "author_id": 10577976, "author_profile": "https://Stackoverflow.com/users/10577976", "pm_score": -1, "selected": true, "text": "class Info:\n\n def __init__(self):\n pass\n def getInfo(self,name):\n with open(\"data.json\") as file:\n file_data = json.load(file)\n id=None # <<< here\n for i in file_data[\"data\"]:\n if i[\"name\"] == name:\n id = i[\"id\"]\n\n\n return id\n\n" }, { "answer_id": 74412872, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 0, "selected": false, "text": "getInfo()" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3858484/" ]
74,412,790
<p>When I apply COUNTIF to a range that contains calculations, I get an error message. To avoid that, can I also narrow the range only to certain columns?</p> <p>For example, instead of <code>=COUNTIF($A$1:E;F1)</code> something like <code>=COUNTIF($A$1:A AND $C$1:C AND $E$1:E;F1)</code></p> <p>So that certain columns like B and D in my example are not included in the range?</p>
[ { "answer_id": 74412896, "author": "Anton Dementiev", "author_id": 7586528, "author_profile": "https://Stackoverflow.com/users/7586528", "pm_score": 0, "selected": false, "text": "=COUNTIFS(A1:A, \"=\" & F1, C1:C, \"=\" & F1, E1:E, \"=\" & F1)\n" }, { "answer_id": 74413019, "author": "Martín", "author_id": 20363318, "author_profile": "https://Stackoverflow.com/users/20363318", "pm_score": 3, "selected": true, "text": "=countif({A1:A;C1:C;E1:E},F1)\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3392296/" ]
74,412,804
<p>I have been struggling on this for a while without prevail. I am trying to run a test script with</p> <pre><code>import numpy as np array1 = np.array([1,2,3]) </code></pre> <p>However, I get the error &quot;No module named 'numpy'&quot;. The same goes for Tensorflow. But trying &quot;pip install numpy&quot; on terminal gives &quot;Requirement already satisfied: numpy in /usr/local/lib/python3.9/site-packages (1.23.4)&quot;.</p> <p>And when I move the script to another directory, in which I already have ran Numpy in, it runs without error. Why does the Numpy module (also Tensorflow) work in that directory, but not in the new one I created?</p> <p>Tried to uninstall and install Numpy in Terminal</p>
[ { "answer_id": 74412897, "author": "Thaiminhpv", "author_id": 11806050, "author_profile": "https://Stackoverflow.com/users/11806050", "pm_score": 2, "selected": false, "text": "pip install" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20158158/" ]
74,412,806
<p>Suppose I have an <code>Optional</code> containing a <code>Stream</code>:</p> <pre class="lang-java prettyprint-override"><code>Optional&lt;Stream&lt;Integer&gt;&gt; optionalStream = Optional.of(Stream.of(1, 2, 3)); </code></pre> <p>Now I need to extract the <code>Stream</code> itself. If the <code>Optional</code> is empty, you want to get an empty Stream.</p> <p>I'm looking of is something like <code>flatStream()</code> that performs transformation in one step. How can I do this?</p> <p><em>My current attempt:</em></p> <pre class="lang-java prettyprint-override"><code>Stream&lt;Integer&gt; stream = optionalStream.stream().flatMap(Function.identity()); </code></pre> <hr /> <h3>The Context of the Problem</h3> <p>In my real scenario, I have something like this, which gives me a <code>Stream&lt;Optional&lt;Foo&gt;&gt;</code>:</p> <pre><code>stream.findFirst().map(e -&gt; e.getChildren()) </code></pre>
[ { "answer_id": 74412838, "author": "Julio César Estravis", "author_id": 20121447, "author_profile": "https://Stackoverflow.com/users/20121447", "pm_score": 3, "selected": true, "text": "orElseGet()" }, { "answer_id": 74412877, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 3, "selected": false, "text": "Stream.empty()" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17133024/" ]
74,412,812
<p>I have the below data structure in Ruby:</p> <pre><code>people = [ { &quot;name&quot; =&gt; &quot;John&quot;, &quot;hobby&quot; =&gt; &quot;tennis&quot;, &quot;food&quot; =&gt; &quot;pizza&quot; }, { &quot;name&quot; =&gt; &quot;Joseph&quot;, &quot;hobby&quot; =&gt; &quot;tennis&quot;, &quot;food&quot; =&gt; &quot;burgers&quot; }, { &quot;name&quot; =&gt; &quot;Lauren&quot;, &quot;hobby&quot; =&gt; &quot;board games&quot;, &quot;food&quot; =&gt; &quot;salads&quot; } { &quot;name&quot; =&gt; &quot;Amir&quot;, &quot;hobby&quot; =&gt; &quot;cycling&quot;, &quot;food&quot; =&gt; &quot;burgers&quot; }, { &quot;name&quot; =&gt; &quot;Mary&quot;, &quot;hobby&quot; =&gt; &quot;tennis&quot;, &quot;food&quot; =&gt; &quot;salads&quot; }, { &quot;name&quot; =&gt; &quot;Karen&quot;, &quot;hobby&quot; =&gt; &quot;board games&quot;, &quot;food&quot; =&gt; &quot;pie&quot; }, { &quot;name&quot; =&gt; &quot;Will&quot;, &quot;hobby&quot; =&gt; &quot;cycling&quot;, &quot;food&quot; =&gt; &quot;pizza&quot; }, ] </code></pre> <p>I need to write a program that will take in user input - either &quot;hobby&quot; or &quot;food&quot; and will then puts out a list of people grouped under subheadings for each hobby or food.</p> <p>e.g. user inputs 'hobby' and a list is puts'ed to the console similar to the below:</p> <p>tennis John Joseph Mary board games Lauren Karen cycling Amir Will</p> <p>So far I have got as far as being able to generate a new array that has the hobbies and the names, however they are seperate and I'm not sure if it's the best way of going around getting the category name with a list of people underneath... also there are a few nil values being pulled out too e.g. below:</p> <pre><code> puts &quot;Enter what category to search&quot; category = gets.chomp grouped_data = people.group_by { |x| x[category] } new_array = [] grouped_data.each { |n| new_array.push n[0] } grouped_data.flatten.flatten.each { |n| new_array.push n[&quot;name&quot;] } p new_array </code></pre> <p>With input &quot;hobby&quot; gives me an array:</p> <pre><code> [&quot;tennis&quot;, &quot;board games&quot;, &quot;cycling&quot;, nil, &quot;John&quot;, &quot;Joseph&quot;, &quot;Mary&quot;, nil, &quot;Lauren&quot;, &quot;Karen&quot;, nil, &quot;Amir&quot;, &quot;Will&quot;] </code></pre> <p>Am I on the right track? Is there another avenue worth exploring?</p> <p>Thanks! Hope this has been laid out alright as it's first time posting on SA.</p>
[ { "answer_id": 74412838, "author": "Julio César Estravis", "author_id": 20121447, "author_profile": "https://Stackoverflow.com/users/20121447", "pm_score": 3, "selected": true, "text": "orElseGet()" }, { "answer_id": 74412877, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 3, "selected": false, "text": "Stream.empty()" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20478187/" ]
74,412,815
<p>I'm trying to iterate over a list and change its values with a &quot;for in&quot; loop:</p> <pre><code>example_string = &quot;This is a string.&quot; for char in example_string : char = 'r' example_list = list(example_string) for char in example_list: char = 'r' </code></pre> <p>The string object is not modified by the iteration.</p> <p>Does the &quot;for in&quot; iteration in Python returns another variable and not the actual list/string element?</p> <p>I tried doing it with lists. I expected that the items in the list or string would get changed by the assignment.</p>
[ { "answer_id": 74412891, "author": "FAB", "author_id": 6373435, "author_profile": "https://Stackoverflow.com/users/6373435", "pm_score": 1, "selected": false, "text": "example_string = [\"This is a string.\", \"This is another string\"]\n\nfor i in range(len(example_string)):\n example_string[i] = \"r\"\n\nprint(example_string)\n" }, { "answer_id": 74413023, "author": "Kryrena", "author_id": 18229254, "author_profile": "https://Stackoverflow.com/users/18229254", "pm_score": 1, "selected": false, "text": "def change_in_list(_list):\n new_list = []\n for element in _list:\n element = 'CHANGED'\n new_list.append(element)\n return new_list\n\nexample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nprint(example_list)\nprint(change_in_list(example_list))\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6046407/" ]
74,412,834
<p>How to find duplicate items from the list below and delete one?</p> <pre><code>var mylist = new List&lt;string&gt;(){ &quot;itemA.config&quot;, &quot;itemA.en-us.config&quot;, &quot;itemB.config&quot;, &quot;itemC.config&quot;, &quot;itemC.en-us.config&quot;, &quot;itemC.fa-ir.config&quot; }; </code></pre> <p>If it has a value of &quot;*.fa-ir.config&quot;, keep it. Otherwise, keep *.config</p> <pre><code>var mylist = new List&lt;string&gt;(){ &quot;itemA.config&quot;, &quot;itemB.config&quot;, &quot;itemC.fa-ir.config&quot; }; </code></pre>
[ { "answer_id": 74412945, "author": "Dmitry Bychenko", "author_id": 2319407, "author_profile": "https://Stackoverflow.com/users/2319407", "pm_score": 1, "selected": false, "text": "GroupBy" }, { "answer_id": 74412980, "author": "Tim Schmelter", "author_id": 284240, "author_profile": "https://Stackoverflow.com/users/284240", "pm_score": 0, "selected": false, "text": "mylist = mylist \n .Select(s => (Name:s, Culture:GetConfigCulture(s, out string[] tokens), Tokens:tokens))\n .GroupBy(x => x.Tokens.First(), StringComparer.InvariantCultureIgnoreCase)\n .Select(g => g.OrderBy(x => GetOrder(x.Culture)).First().Name)\n .ToList();\n\nstring GetConfigCulture(string name, out string[] tokens)\n{\n tokens = name.Split('.');\n if(tokens.Length < 3) return null;\n return tokens[1];\n}\n\nint GetOrder(string culture)\n{\n if(StringComparer.InvariantCultureIgnoreCase.Equals(culture, \"fa-ir\")) return 0;\n if(StringComparer.InvariantCultureIgnoreCase.Equals(culture, null)) return 1;\n return 2;\n}\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10241851/" ]
74,412,851
<p>I am doing my custom image file format to display images in CLI but i need to convert <code>size_t</code> to <code>std::string</code>:</p> <pre class="lang-cpp prettyprint-override"><code>namespace csfo { class Res { public: char* BLANK_DATA = &quot;...&quot;; }; ... inline char* generate(int COLOR, size_t x, size_t y, bool verbose) { csfo::Res RES; ... std::string dimenssions[2] = { std::to_string(x), std::to_string(y) }; std::string DATA = RES.BLANK_DATA; DATA = DATA.replace(DATA.begin(), DATA.end(), &quot;[X_SIZE]&quot;, dimenssions[0]); ... }; ... } </code></pre> <p>But i get this error when i try to call std::to_string()</p> <p>No instance of overloaded function matches the argument list c/c++(304)</p> <p>Can someone please help me? Thanks.</p> <p>I except my code to work</p>
[ { "answer_id": 74412941, "author": "john", "author_id": 882003, "author_profile": "https://Stackoverflow.com/users/882003", "pm_score": 0, "selected": false, "text": "size_t n = DATA.find(\"[X_SIZE]\"); // find where [X_SIZE] is in DATA\nDATA.replace(n, n + 8, dimenssions[0]); // and replace it with dimenssions[0]\n" }, { "answer_id": 74413169, "author": "Michał Jaroń", "author_id": 6835932, "author_profile": "https://Stackoverflow.com/users/6835932", "pm_score": 2, "selected": true, "text": "std::string" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19643069/" ]
74,412,866
<p>I am a super CL beginner and I am very stumped on the following task:</p> <blockquote> <p>Define a recursive function <strong><code>shorten</code></strong> that deletes the last <em>n</em> elements from a given list. The function should return the shortened list at the end.</p> <p>For example:</p> <pre><code> (shorten 5 '(1 2 3 4 5 6 7 8 9)) =&gt; (1 2 3 4) </code></pre> </blockquote>
[ { "answer_id": 74417809, "author": "Will Ness", "author_id": 849891, "author_profile": "https://Stackoverflow.com/users/849891", "pm_score": 1, "selected": false, "text": "p0" }, { "answer_id": 74421085, "author": "ignis volens", "author_id": 17026934, "author_profile": "https://Stackoverflow.com/users/17026934", "pm_score": 1, "selected": false, "text": "tconc" }, { "answer_id": 74423032, "author": "Francis King", "author_id": 9841104, "author_profile": "https://Stackoverflow.com/users/9841104", "pm_score": -1, "selected": false, "text": "(defun shorten (n lst &optional (res '()))\n (if (or (= n 0) (null lst))\n (reverse res)\n (shorten (1- n) (cdr lst) (cons (car lst) res))))\n\n(shorten 5 '(1 2 3 4 5 6 7 8 9 10)) ; (1 2 3 4 5)\n(shorten 1 '(1 2 3 4 5 6 7 8 9 10)) ; (1)\n(shorten 11 '(1 2 3 4 5 6 7 8 9 10)) ; (1 2 3 4 5 6 7 8 9 10)\n(shorten 0 '(1 2 3 4 5 6 7 8 9 10)) ; NIL\n(shorten 5 '()) ; NIL\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20434143/" ]
74,412,959
<p><a href="https://i.stack.imgur.com/30SYz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/30SYz.png" alt="Spring Boot" /></a></p> <p>My application is mainly based on spring boot micro services. Currently it uses OAuth with password grant_type which is deprecated in the latest spring security authorization server release. For receiving JWT token, it stores client id and client secret in React JS frontend which is not secure and not recommended. Users need to register to access certain resources and application maintains login credentials in mysql DB</p> <p>I am trying to upgrade spring security and want 'account service' to act as authorization server to issue JWT tokens.</p> <ol> <li>Am I correct in my understanding that I need to use authorization_code grand type with PKCE?</li> <li>If I use PKCE then I do not need users to provide passwords while registering, is that correct? Storing only username/email should suffice because users just need to pass client ID and code_challenge to get authorization code?</li> </ol>
[ { "answer_id": 74417809, "author": "Will Ness", "author_id": 849891, "author_profile": "https://Stackoverflow.com/users/849891", "pm_score": 1, "selected": false, "text": "p0" }, { "answer_id": 74421085, "author": "ignis volens", "author_id": 17026934, "author_profile": "https://Stackoverflow.com/users/17026934", "pm_score": 1, "selected": false, "text": "tconc" }, { "answer_id": 74423032, "author": "Francis King", "author_id": 9841104, "author_profile": "https://Stackoverflow.com/users/9841104", "pm_score": -1, "selected": false, "text": "(defun shorten (n lst &optional (res '()))\n (if (or (= n 0) (null lst))\n (reverse res)\n (shorten (1- n) (cdr lst) (cons (car lst) res))))\n\n(shorten 5 '(1 2 3 4 5 6 7 8 9 10)) ; (1 2 3 4 5)\n(shorten 1 '(1 2 3 4 5 6 7 8 9 10)) ; (1)\n(shorten 11 '(1 2 3 4 5 6 7 8 9 10)) ; (1 2 3 4 5 6 7 8 9 10)\n(shorten 0 '(1 2 3 4 5 6 7 8 9 10)) ; NIL\n(shorten 5 '()) ; NIL\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1498826/" ]
74,412,991
<p>I have a function that gets a number and should return the minimum digit. This is what I was trying to do, but maybe I didn't fully understand how recursion works.</p> <pre><code>def min_dig(num): minimum = 9 if num &lt; 10: return num min_dig(num / 10) if num % 10 &lt; minimum: minimum = num % 10 return minimum print(min_dig(98918)) </code></pre> <p>Output is 8 but supposed to be 1.</p>
[ { "answer_id": 74413050, "author": "techy", "author_id": 19969692, "author_profile": "https://Stackoverflow.com/users/19969692", "pm_score": 0, "selected": false, "text": "number = 98918\nnumberArray = number.split\nsmallest = numberArray[0]\nfor (digit in numberArray){\n if (digit < smallest){\n smallest = digit\n }\n}\nprint(smallest)\n" }, { "answer_id": 74413059, "author": "LEGION GREEN", "author_id": 17495765, "author_profile": "https://Stackoverflow.com/users/17495765", "pm_score": 4, "selected": true, "text": "def min_dig(num):\n if num < 10:\n return num\n return min(num % 10, min_dig(num // 10))\n\nprint(min_dig(98918))\n" }, { "answer_id": 74413080, "author": "Kryrena", "author_id": 18229254, "author_profile": "https://Stackoverflow.com/users/18229254", "pm_score": 2, "selected": false, "text": "def min_dig(number):\n if number < 10:\n return number\n else:\n return min(number % 10, min_dig(number // 10))\n" }, { "answer_id": 74413093, "author": "Nakul Mitra", "author_id": 20485576, "author_profile": "https://Stackoverflow.com/users/20485576", "pm_score": -1, "selected": false, "text": "minimum = 9\ndef min_dig(num):\n global minimum\n if num < 10:\n return num\n min_dig(num // 10)\n if num % 10 < minimum:\n minimum = num % 10\n return minimum\n\n\nprint(min_dig(98918))\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74412991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14148435/" ]
74,413,013
<pre><code>#include &lt;stdio.h&gt; #include &lt;ctype.h&gt; #include &lt;string.h&gt; int main(){ char S[10007]; scanf(&quot;%[^\n]&quot;, S); getchar(); int i = 0; char u; while(S[i]){ u = toupper(S[i]); if(strcmp(u, &quot;I&quot;) == 0){ u = '1'; } else if(strcmp(u, &quot;R&quot;) == 0){ u = '2'; } else if(strcmp(u, &quot;E&quot;) == 0){ u = '3'; } else if(strcmp(u, &quot;A&quot;) == 0){ u = '4'; } else if(strcmp(u, &quot;S&quot;) == 0){ u = '5'; } else if(strcmp(u, &quot;G&quot;) == 0){ u = '6'; } else if(strcmp(u, &quot;T&quot;) == 0){ u = '7'; } else if(strcmp(u, &quot;B&quot;) == 0){ u = '8'; } else if(strcmp(u, &quot;P&quot;) == 0){ u = '9'; } else if(strcmp(u, &quot;O&quot;) == 0){ u = '0'; } printf(&quot;%s&quot;, u); i++; } return 0; } </code></pre> <p>I got a case where i need to make an inputted string uppercase then change some of the uppercase alphabet to the following number, (example input: im waterswell, the otuput: 1M W4T325W33L) so i created the program but it returns to following error: invalid conversion from 'char' to 'const char*' [-fpermissive]. Can anyone help me? thank you</p>
[ { "answer_id": 74413048, "author": "Yksisarvinen", "author_id": 7976805, "author_profile": "https://Stackoverflow.com/users/7976805", "pm_score": 2, "selected": true, "text": "strcmp" }, { "answer_id": 74413087, "author": "Pepijn Kramer", "author_id": 16649550, "author_profile": "https://Stackoverflow.com/users/16649550", "pm_score": 1, "selected": false, "text": "#include <string>\n#include <iostream>\n#include <unordered_map>\n\n// lookup table\nstatic std::unordered_map<char, char> mapping\n{\n {'I','1'}, {'i','1'},\n {'R','2'}, {'r','2'},\n {'E','3'}, {'e','3'},\n {'A','4'}, {'a','4'},\n {'S','5'}, {'s','5'},\n {'G','6'}, {'g','6'},\n {'T','7'}, {'t','7'},\n {'B','8'}, {'b','8'},\n {'O','9'}, {'o','9'},\n {'U','0'}, {'u','0'},\n};\n\nint main()\n{\n //std::string input;\n //std::cin >> input;\n\n std::string input{ \"TESTcase\" };\n for (const char c : input)\n {\n // check if key can be found\n auto it = mapping.find(c);\n\n if (it == mapping.end())\n {\n // if not cast to upper, std::toupper doesn't return a char\n // so cast it.\n std::cout << static_cast<char>(std::toupper(c));\n }\n else\n {\n // structured binging\n const auto&[key, value] = *it; // *it refers to an key value pair in the map\n std::cout << value;\n }\n }\n\n return 0;\n}\n" }, { "answer_id": 74413146, "author": "fabian", "author_id": 2991525, "author_profile": "https://Stackoverflow.com/users/2991525", "pm_score": 0, "selected": false, "text": "if (u == 'O')\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20485607/" ]
74,413,028
<p>I am building a web application with a login form and stripe subscription functionality.</p> <p>In order to receive JSON data I am using <code>express.json</code> as</p> <pre><code>app.use(express.json()); </code></pre> <p>When I was using the above middleware to receive <code>stripe webhook secret</code> the server could not receive it.</p> <p>So I had to add the <code>express.raw</code></p> <p>My middleware looked like this:</p> <pre><code>app.use(express.raw({ type: &quot;application/json&quot; })); app.use(express.json()); </code></pre> <p>But now I am unable to receive form JSON data.</p> <p>Here is my stripe logic:</p> <pre><code>export const postStripeWebhook = async (req: ExtendedRequest, res: Response) =&gt; { let data; let eventType; let event = req.body; const webhookSecret = &quot;web hook secret provided by stripe&quot;; if (webhookSecret) { let signature = req.headers[&quot;stripe-signature&quot;]; try { event = stripe.webhooks.constructEvent(req.body, signature , webhookSecret); } catch (err) { console.log(`⚠️ Webhook signature verification failed.`); //This part is throwing the error return res.sendStatus(400); } data = event.data; eventType = event.type; } else { data = req.body.data; eventType = req.body.type; } let subscription; switch (eventType) { // Here webhook events are managed } res.sendStatus(200); }; </code></pre> <p>Here is the index.js code:</p> <pre><code> app.use(express.raw({ type: &quot;application/json&quot; })); app.use(express.json()); app.use(express.static(&quot;public&quot;)); app.use(express.urlencoded({ extended: true })); app.use(cors()); app.post(&quot;/webhooks&quot;, postStripeWebhook); </code></pre> <p>Updated code-------------------------</p> <p>index.js:</p> <pre><code>app.use(express.json()); app.use(express.static(&quot;public&quot;)); app.use(express.urlencoded({ extended: true })); app.use(cors()); app.post(&quot;/webhooks&quot;, postStripeWebhook); </code></pre> <p>Middleware code:</p> <pre><code>export const postStripeWebhook = async (req: ExtendedRequest, res: Response) =&gt; { let data; let eventType; let event = req.body; const webhookSecret = &quot;web hook secret provided by stripe&quot;; if (webhookSecret) { let signature = req.headers[&quot;stripe-signature&quot;]; try { event = stripe.webhooks.constructEvent(JSON.stringify(req.body), signature , webhookSecret); //updated this line } catch (err) { console.log(`⚠️ Webhook signature verification failed.`); //This part is throwing the error return res.sendStatus(400); } data = event.data; eventType = event.type; } else { data = req.body.data; eventType = req.body.type; } let subscription; switch (eventType) { // Here webhook events are managed } res.sendStatus(200); }; </code></pre> <p>I updated the code but still, but the problem persists.</p> <p>Please guide me on how to modify my middleware to receive both types of data.</p>
[ { "answer_id": 74413048, "author": "Yksisarvinen", "author_id": 7976805, "author_profile": "https://Stackoverflow.com/users/7976805", "pm_score": 2, "selected": true, "text": "strcmp" }, { "answer_id": 74413087, "author": "Pepijn Kramer", "author_id": 16649550, "author_profile": "https://Stackoverflow.com/users/16649550", "pm_score": 1, "selected": false, "text": "#include <string>\n#include <iostream>\n#include <unordered_map>\n\n// lookup table\nstatic std::unordered_map<char, char> mapping\n{\n {'I','1'}, {'i','1'},\n {'R','2'}, {'r','2'},\n {'E','3'}, {'e','3'},\n {'A','4'}, {'a','4'},\n {'S','5'}, {'s','5'},\n {'G','6'}, {'g','6'},\n {'T','7'}, {'t','7'},\n {'B','8'}, {'b','8'},\n {'O','9'}, {'o','9'},\n {'U','0'}, {'u','0'},\n};\n\nint main()\n{\n //std::string input;\n //std::cin >> input;\n\n std::string input{ \"TESTcase\" };\n for (const char c : input)\n {\n // check if key can be found\n auto it = mapping.find(c);\n\n if (it == mapping.end())\n {\n // if not cast to upper, std::toupper doesn't return a char\n // so cast it.\n std::cout << static_cast<char>(std::toupper(c));\n }\n else\n {\n // structured binging\n const auto&[key, value] = *it; // *it refers to an key value pair in the map\n std::cout << value;\n }\n }\n\n return 0;\n}\n" }, { "answer_id": 74413146, "author": "fabian", "author_id": 2991525, "author_profile": "https://Stackoverflow.com/users/2991525", "pm_score": 0, "selected": false, "text": "if (u == 'O')\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17348251/" ]
74,413,029
<p>I need to serialize an xml schema in c#. The problem is that I don't know how to serialize the paragraph element of this schema.</p> <pre><code> &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;p:EsitoRichiestaCertificatoDispositivo xmlns:env=&quot;http://schemas.xmlsoap.org/soap/envelope/&quot; xmlns:p=&quot;http://ivaservizi.agenziaentrate.gov.it/docs/xsd/corrispettivi/v1.0&quot; versione=&quot;1.0&quot;&gt; &lt;/p:EsitoRichiestaCertificatoDispositivo&gt; </code></pre> <p>This is the class i wrote:</p> <pre><code> [Serializable] [XmlRootAttribute(Namespace = &quot;http://ivaservizi.agenziaentrate.gov.it/docs/xsd/corrispettivi/v1.0&quot;, IsNullable = false)] public class EsitoRichiestaCertificatoDispositivo { public string IdOperazione; [SoapElement(DataType = &quot;base64Binary&quot;)] public string Certificato; public ErroriType Errori; public EsitoRichiestaCertificatoDispositivo() { IdOperazione = &quot;&quot;; Certificato = &quot;&quot;; Errori = new ErroriType(); } } </code></pre> <p>This is the xml schema: <a href="https://www.agenziaentrate.gov.it/portale/documents/20143/296358/Provvedimento+30+marzo+2017+Distributori+automatici_CorrispettiviMessaggiTypes_v1.0.xsd/69bec22c-92f1-7c6a-f5db-ad213b93443d" rel="nofollow noreferrer">https://www.agenziaentrate.gov.it/portale/documents/20143/296358/Provvedimento+30+marzo+2017+Distributori+automatici_CorrispettiviMessaggiTypes_v1.0.xsd/69bec22c-92f1-7c6a-f5db-ad213b93443d</a></p>
[ { "answer_id": 74413048, "author": "Yksisarvinen", "author_id": 7976805, "author_profile": "https://Stackoverflow.com/users/7976805", "pm_score": 2, "selected": true, "text": "strcmp" }, { "answer_id": 74413087, "author": "Pepijn Kramer", "author_id": 16649550, "author_profile": "https://Stackoverflow.com/users/16649550", "pm_score": 1, "selected": false, "text": "#include <string>\n#include <iostream>\n#include <unordered_map>\n\n// lookup table\nstatic std::unordered_map<char, char> mapping\n{\n {'I','1'}, {'i','1'},\n {'R','2'}, {'r','2'},\n {'E','3'}, {'e','3'},\n {'A','4'}, {'a','4'},\n {'S','5'}, {'s','5'},\n {'G','6'}, {'g','6'},\n {'T','7'}, {'t','7'},\n {'B','8'}, {'b','8'},\n {'O','9'}, {'o','9'},\n {'U','0'}, {'u','0'},\n};\n\nint main()\n{\n //std::string input;\n //std::cin >> input;\n\n std::string input{ \"TESTcase\" };\n for (const char c : input)\n {\n // check if key can be found\n auto it = mapping.find(c);\n\n if (it == mapping.end())\n {\n // if not cast to upper, std::toupper doesn't return a char\n // so cast it.\n std::cout << static_cast<char>(std::toupper(c));\n }\n else\n {\n // structured binging\n const auto&[key, value] = *it; // *it refers to an key value pair in the map\n std::cout << value;\n }\n }\n\n return 0;\n}\n" }, { "answer_id": 74413146, "author": "fabian", "author_id": 2991525, "author_profile": "https://Stackoverflow.com/users/2991525", "pm_score": 0, "selected": false, "text": "if (u == 'O')\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6117549/" ]
74,413,034
<p>So, I have a ball and some obstacles, which disallow the ball to move to the target. Ball is shotting bullets and after each shot I'm checking if the ball can reach the target. I need the ball to stay on starting position until the path is clear. Unfortunately, even if some obsacles are on the way, the ball keeps moving until countering them.</p> <p>That's what I've tried to do: `</p> <pre><code> private void TryReachTheTarget() { if (NavMesh.CalculatePath(_agent.transform.position, _target.position, NavMesh.AllArea s, _path) &amp;&amp; _path.status == NavMeshPathStatus.PathComplete) { _agent.SetPath(_path); } } </code></pre> <p>`</p> <p><a href="https://i.stack.imgur.com/lwrje.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lwrje.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74413048, "author": "Yksisarvinen", "author_id": 7976805, "author_profile": "https://Stackoverflow.com/users/7976805", "pm_score": 2, "selected": true, "text": "strcmp" }, { "answer_id": 74413087, "author": "Pepijn Kramer", "author_id": 16649550, "author_profile": "https://Stackoverflow.com/users/16649550", "pm_score": 1, "selected": false, "text": "#include <string>\n#include <iostream>\n#include <unordered_map>\n\n// lookup table\nstatic std::unordered_map<char, char> mapping\n{\n {'I','1'}, {'i','1'},\n {'R','2'}, {'r','2'},\n {'E','3'}, {'e','3'},\n {'A','4'}, {'a','4'},\n {'S','5'}, {'s','5'},\n {'G','6'}, {'g','6'},\n {'T','7'}, {'t','7'},\n {'B','8'}, {'b','8'},\n {'O','9'}, {'o','9'},\n {'U','0'}, {'u','0'},\n};\n\nint main()\n{\n //std::string input;\n //std::cin >> input;\n\n std::string input{ \"TESTcase\" };\n for (const char c : input)\n {\n // check if key can be found\n auto it = mapping.find(c);\n\n if (it == mapping.end())\n {\n // if not cast to upper, std::toupper doesn't return a char\n // so cast it.\n std::cout << static_cast<char>(std::toupper(c));\n }\n else\n {\n // structured binging\n const auto&[key, value] = *it; // *it refers to an key value pair in the map\n std::cout << value;\n }\n }\n\n return 0;\n}\n" }, { "answer_id": 74413146, "author": "fabian", "author_id": 2991525, "author_profile": "https://Stackoverflow.com/users/2991525", "pm_score": 0, "selected": false, "text": "if (u == 'O')\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20431488/" ]
74,413,043
<p>I have a websocket server that sends an object containing some hashes every 15 seconds. When the client receives a hash, I want to check with my current hash. If they differ, I want to make a call to an API to fetch new data.</p> <p>The socket is working and sending the hash correctly. If the data updates on the server I get a different hash. My problem is that the hash variable I use to store the current hash is not updated correctly.</p> <p>I have disabled the socket listening in my component, just to make sure that that is not the problem. Instead I have added a <code>setInterval</code> to mimik the socket update.</p> <p>This is my code (socked code disabled but left as a comment):</p> <pre><code>import { useCallback, useEffect, useState } from &quot;react&quot;; import { useAuth, useSocket } from &quot;../utils/hooks&quot;; const Admin = () =&gt; { const [ questionLists, setQuestionLists ] = useState&lt;QuestionListModel[]&gt;([]); const { user } = useAuth(); const { socket } = useSocket(); const [ hash, setHash ] = useState&lt;Hash&gt;({questionList: &quot;&quot;}); const fetchHash = useCallback(async () =&gt; { setHash({questionList: &quot;sdhfubvwuedfhvfeuvyqhwvfeuq&quot;}); }, []); const fetchQuestionLists = useCallback(async () =&gt; { console.log(&quot;fetching new question lists&quot;); const response: ApiResponse | boolean = await getQuestionLists(user?.token); if (typeof response !== &quot;boolean&quot; &amp;&amp; response.data) { setQuestionLists(response.data); } }, [hash]); useEffect(() =&gt; { fetchHash(); fetchQuestionLists(); }, []); const update = useCallback((newHash: Hash) =&gt; { console.log(&quot;called update&quot;); let shouldUpdate = false; let originalHash = { ...hash }; let updatedHash = { ...newHash }; console.log(&quot;new: &quot;, newHash); console.log(&quot;stored: &quot;, originalHash); if (hash.questionList !== newHash.questionList) { console.log(&quot;was not equal&quot;); updatedHash = { ...updatedHash, questionList: newHash.questionList} shouldUpdate = true; } if (shouldUpdate) { console.log(&quot;trying to set new hash: &quot;, updatedHash); setHash(updatedHash); fetchQuestionLists(); } }, [hash]); /*useEffect(() =&gt; { socket?.on('aHash', (fetchedHash) =&gt; update(fetchedHash)); }, []);*/ useEffect(() =&gt; { setInterval(() =&gt; { update({questionList: &quot;sdhfubvwuedfhvfeuvyqhwvfeuq&quot;}); }, 15000) }, []); return ( &lt;&gt; ... Things here later ... &lt;/&gt; ); }; export default Admin; </code></pre> <p>After the initial render, and waiting two interval cycles, this is what I see in the console:</p> <pre><code>fetching new question lists called update new: {questionList: 'sdhfubvwuedfhvfeuvyqhwvfeuq'} stored: {questionList: ''} was not equal trying to set new hash: {questionList: 'sdhfubvwuedfhvfeuvyqhwvfeuq'} fetching new question lists called update new: {questionList: 'sdhfubvwuedfhvfeuvyqhwvfeuq'} stored: {questionList: ''} was not equal trying to set new hash: {questionList: 'sdhfubvwuedfhvfeuvyqhwvfeuq'} fetching new question lists </code></pre> <p>You can see that <code>stored</code> is empty. That leads me to believe that <code>setHash(updatedHash);</code> never runs for some reason. Why is that?</p>
[ { "answer_id": 74413472, "author": "Hamid fadili", "author_id": 13118602, "author_profile": "https://Stackoverflow.com/users/13118602", "pm_score": 0, "selected": false, "text": "socket?.on('aHash', (hash) => update(hash));\n" }, { "answer_id": 74415788, "author": "Shortchange", "author_id": 14334812, "author_profile": "https://Stackoverflow.com/users/14334812", "pm_score": 0, "selected": false, "text": " const [ hash, setHash ] = useState<Hash>({questionList: \"\"});\n\n const fetchHash = useCallback(async () => {\n setHash({questionList: \"sdhfubvwuedfhvfeuvyqhwvfeuq\"});\n }, []);\n" }, { "answer_id": 74416346, "author": "Gaja", "author_id": 20488236, "author_profile": "https://Stackoverflow.com/users/20488236", "pm_score": 0, "selected": false, "text": "import { useCallback, useEffect, useState } from \"react\";\n\nimport { faker } from '@faker-js/faker';\n\nconst Admin = () => {\n const [ questionLists, setQuestionLists ] = useState([]); \n const [ hash, setHash ] = useState({questionList: \"\"});\n\n const fetchHash = useCallback(async () => {\n setHash({questionList: \"sdhfubvwuedfhvfeuvyqhwvfeuq\"});\n }, []);\n\n const fetchQuestionLists = useCallback(async () => {\n console.log(\"fetching new question lists\");\n const response = {data: {hash: 'asdf-1234'}}\n\n setQuestionLists(response.data);\n }, [hash]);\n\n useEffect(() => {\n fetchHash();\n fetchQuestionLists();\n }, []);\n\n const update = (newHash) => {\n console.log(\"called update\");\n\n setHash(oldHash => {\n console.log('old hash: ', oldHash);\n console.log('new hash', newHash);\n if (JSON.stringify(oldHash) !== JSON.stringify(newHash)) {\n return newHash\n }\n })\n };\n\n /*useEffect(() => { \n socket?.on('aHash', (fetchedHash) => update(fetchedHash));\n }, []);*/\n\n useEffect(() => { \n setInterval(() => {\n update({questionList: faker.random.numeric(36)});\n }, 15000)\n }, []);\n\n return (\n <>\n <h2>Hash</h2>\n {JSON.stringify(hash)}\n </>\n );\n};\n\nexport default Admin;\n" }, { "answer_id": 74416454, "author": "alunturner", "author_id": 13714440, "author_profile": "https://Stackoverflow.com/users/13714440", "pm_score": 3, "selected": true, "text": "useEffect" }, { "answer_id": 74418061, "author": "Marek Gola", "author_id": 18259261, "author_profile": "https://Stackoverflow.com/users/18259261", "pm_score": 0, "selected": false, "text": "React.useEffect(() => {\nsocketRef?.current?.on(\n 'private_message_sent_to_client',\n (data: IMessageResult) => {\n savePrivateMessages(data);\n }\n);\nreturn () => {\n socketRef?.current?.off('private_message_sent_to_client');\n };\n}, [meta, selectedChatId, savePrivateMessages]); \n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2695816/" ]
74,413,126
<p>I would like to write a bash script for transferring multiple directories from a Raspberry Pi to my laptop using scp command. But my code only work on one laptop (MacBook Pro 2016), but it failed on another laptop (MacBook Pro 2020), which is quite strange.</p> <p>What I would like to execute is some command like:</p> <pre><code>scp -rp pi@192.168.0.163:/home/pi/Documents/data/{directory1,directory2,directory3} . </code></pre> <p>This command work well when I directly execute it in terminal, on both of the laptop. But when I put it into a bash script:</p> <pre><code>#!/bin/bash scp -rp &quot;pi@192.168.0.163:/home/pi/Documents/data/{directory1,directory2,directory3}&quot; &quot;.&quot; </code></pre> <p>it shows error <code>scp: /home/pi/Documents/data/{directory1,directory2,directory3}: No such file or directory</code> on my MacBook Pro 2020, but it works well on my MacBook Pro 2016.</p> <p>I have checked the bash version on both laptop, but it seems like they don't have too much difference</p> <blockquote> <p>MacBook Pro 2016: GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin21)<br /> MacBook Pro 2020: GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin22)</p> </blockquote> <p>Can anyone help me?</p> <p>-------------------------------- Below are updates --------------------------------</p> <p>Seem like I didn't explain my problem very well.</p> <p>My actual situation is a litter more complicated. I am working on a bash script which takes multiple directory as parameter for doing scp from my Raspberry Pi remote. My script.sh is like:</p> <pre><code>#!/bin/bash while getopts &quot;hu:&quot; option; do case $option in h) # display Help Help exit;; u) user_list+=(&quot;$OPTARG&quot;);; \?) # incorrect option echo &quot;Error: Invalid option&quot; exit;; esac done RASPBERRYPI_DATA_PATH=&quot;/home/pi/Documents/data&quot; RASPBERRYPI_ADDR=$1 RASPBERRYPI_USER_NAME=&quot;pi&quot; scp -rp ${RASPBERRYPI_USER_NAME}@${RASPBERRYPI_ADDR}:${RASPBERRYPI_DATA_PATH}/{${user_list[@]// /,}} . </code></pre> <p>I execute the script in this way:</p> <pre><code>./script.sh -u &quot;directory1 directory2&quot; 192.168.0.163 </code></pre> <p>It shows error: <code>scp: /home/pi/Documents/data/{directory1,directory2}: No such file or directory</code> on my MacBook Pro 2020, but it works well on my MacBook Pro 2016.</p> <p>I am a novice in bash development. I think I am having some mistake on grammar. But the script works well on my old MacBook Pro, which is quite strange.</p> <p>Thank you very much for helping me.</p>
[ { "answer_id": 74413472, "author": "Hamid fadili", "author_id": 13118602, "author_profile": "https://Stackoverflow.com/users/13118602", "pm_score": 0, "selected": false, "text": "socket?.on('aHash', (hash) => update(hash));\n" }, { "answer_id": 74415788, "author": "Shortchange", "author_id": 14334812, "author_profile": "https://Stackoverflow.com/users/14334812", "pm_score": 0, "selected": false, "text": " const [ hash, setHash ] = useState<Hash>({questionList: \"\"});\n\n const fetchHash = useCallback(async () => {\n setHash({questionList: \"sdhfubvwuedfhvfeuvyqhwvfeuq\"});\n }, []);\n" }, { "answer_id": 74416346, "author": "Gaja", "author_id": 20488236, "author_profile": "https://Stackoverflow.com/users/20488236", "pm_score": 0, "selected": false, "text": "import { useCallback, useEffect, useState } from \"react\";\n\nimport { faker } from '@faker-js/faker';\n\nconst Admin = () => {\n const [ questionLists, setQuestionLists ] = useState([]); \n const [ hash, setHash ] = useState({questionList: \"\"});\n\n const fetchHash = useCallback(async () => {\n setHash({questionList: \"sdhfubvwuedfhvfeuvyqhwvfeuq\"});\n }, []);\n\n const fetchQuestionLists = useCallback(async () => {\n console.log(\"fetching new question lists\");\n const response = {data: {hash: 'asdf-1234'}}\n\n setQuestionLists(response.data);\n }, [hash]);\n\n useEffect(() => {\n fetchHash();\n fetchQuestionLists();\n }, []);\n\n const update = (newHash) => {\n console.log(\"called update\");\n\n setHash(oldHash => {\n console.log('old hash: ', oldHash);\n console.log('new hash', newHash);\n if (JSON.stringify(oldHash) !== JSON.stringify(newHash)) {\n return newHash\n }\n })\n };\n\n /*useEffect(() => { \n socket?.on('aHash', (fetchedHash) => update(fetchedHash));\n }, []);*/\n\n useEffect(() => { \n setInterval(() => {\n update({questionList: faker.random.numeric(36)});\n }, 15000)\n }, []);\n\n return (\n <>\n <h2>Hash</h2>\n {JSON.stringify(hash)}\n </>\n );\n};\n\nexport default Admin;\n" }, { "answer_id": 74416454, "author": "alunturner", "author_id": 13714440, "author_profile": "https://Stackoverflow.com/users/13714440", "pm_score": 3, "selected": true, "text": "useEffect" }, { "answer_id": 74418061, "author": "Marek Gola", "author_id": 18259261, "author_profile": "https://Stackoverflow.com/users/18259261", "pm_score": 0, "selected": false, "text": "React.useEffect(() => {\nsocketRef?.current?.on(\n 'private_message_sent_to_client',\n (data: IMessageResult) => {\n savePrivateMessages(data);\n }\n);\nreturn () => {\n socketRef?.current?.off('private_message_sent_to_client');\n };\n}, [meta, selectedChatId, savePrivateMessages]); \n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10109615/" ]
74,413,175
<p>I dockerized my react app using these commands:</p> <pre><code>docker build -t image-name . docker run -e CHOKIDAR_USEPOLLING=true -v %cd%\src:/app/src -p 3000:3000 --name container-name image-name </code></pre> <p>The problem is that when I save any updates in my components, they do not show up in the browser, although they have been updated in <code>/app/src</code>.</p> <p>I thought that <code>-e CHOKIDAR_USEPOLLING=true</code> would fix it, but it didn't.</p> <p>When I go to: <code>docker exec -it container-name bash</code>. I can see that everything saves correctly, but the changes don't show up in the browser after <code>ctrl + s</code>.</p> <p>When I open <code>localhost:3000</code>, there is a popup <code>Compiled with problems</code> beacause I have some typescript warnings, but when I close it the website works great, but without updates.</p> <p>My Dockerfile:</p> <pre><code>FROM node WORKDIR /app COPY package.json . RUN npm install COPY . . EXPOSE 3000 CMD [&quot;npm&quot;, &quot;start&quot;] </code></pre> <p>.dockerignore:</p> <pre><code>node_modules Dockerfile .git .gitignore .dockerignore .env </code></pre> <p>Docker logs:</p> <pre><code>(node:26) [DEP_WEBPACK_DEV_SERVER_ON_AFTER_SETUP_MIDDLEWARE] DeprecationWarning: 'onAfterSetupMiddleware' option is deprecated. Please use the 'setupMiddlewares' option. (Use `node --trace-deprecation ...` to show where the warning was created) (node:26) [DEP_WEBPACK_DEV_SERVER_ON_BEFORE_SETUP_MIDDLEWARE] DeprecationWarning: 'onBeforeSetupMiddleware' option is deprecated. Please use the 'setupMiddlewares' option. </code></pre> <p>NODE_VERSION 19.0.1</p>
[ { "answer_id": 74416731, "author": "some nooby questions", "author_id": 14514276, "author_profile": "https://Stackoverflow.com/users/14514276", "pm_score": 0, "selected": false, "text": "scripts/start" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14514276/" ]
74,413,176
<p>I have a string containing placeholders which I want replace with other strings, but I would also like to split the string whenever I encounter a placeholder.</p> <p>So, by splitting I mean that</p> <pre><code>&quot;This {0} is an example {1} with a placeholder&quot; </code></pre> <p>should become:</p> <pre><code>parts[0] -&gt; &quot;This&quot; parts[1] -&gt; &quot;{0}&quot; parts[2] -&gt; &quot;is an example&quot; parts[3] -&gt; &quot;{1}&quot; parts[4] -&gt; &quot;with a placeholder&quot; </code></pre> <p>and then the next step would be to replace the placeholders (this part is simple):</p> <pre><code>parts[0] -&gt; &quot;This&quot; parts[1] -&gt; value[0] parts[2] -&gt; &quot;is an example&quot; parts[3] -&gt; value[1] parts[4] -&gt; &quot;with a placeholder&quot; </code></pre> <p>I know how to match and replace the placeholders (e.g. <code>({\d+})</code>), but no clue how to tell regex to &quot;match non placeholders&quot; and &quot;match placeholders&quot; at the same time.</p> <p>My idea was something like: <code>(?!{\d+})+ | ({\d+})</code> but it's not working. I am doing this in JavaScript if Regex flavor is important.</p> <p>If I can also replace the placeholders with a value in one step it would be neat, but I can also do this after I split.</p>
[ { "answer_id": 74413203, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 3, "selected": true, "text": "{\\d+}|\\S.*?(?=\\s*(?:{\\d+}|$))\n" }, { "answer_id": 74413310, "author": "bobble bubble", "author_id": 5527985, "author_profile": "https://Stackoverflow.com/users/5527985", "pm_score": 1, "selected": false, "text": "let parts = str.split(/ *({\\d+}) */);\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1488067/" ]
74,413,185
<p>I have the following code to demonstrate a function been called inside another function.</p> <p>The below code works correctly:</p> <pre><code>#include &lt;iostream&gt; int thirds() { return 6 + 1; } template &lt;typename T, typename B&gt; int hello(T x, B y , int (*ptr)() ){ int first = x + 1; int second = y + 1; int third = (*ptr) (); ; return first + second + third; } int add(){ int (*ptr)() = &amp;thirds; return hello(1,1, thirds); } int main() { std::cout&lt;&lt;add(); return 0; } </code></pre> <p>Now I want to pass one number as a parameter from add function ie into thirds function (thirds(6)).</p> <p>I am trying this way:</p> <pre><code>#include &lt;iostream&gt; int thirds(int a){ return a + 1; } template &lt;typename T, typename B&gt; int hello(T x, B y , int (*ptr)(int a)() ){ int first = x + 1; int second = y + 1; int third = (*ptr)(a) (); ; return first + second + third; } int add(){ int (*ptr)() = &amp;thirds; return hello(1,1, thirds(6)); //from here pass a number } int main() { std::cout&lt;&lt;add(); return 0; } </code></pre> <p>My expected output is:</p> <pre><code>11 </code></pre> <p>But It is not working. Please can someone show me what I am doing wrong?</p>
[ { "answer_id": 74413253, "author": "wohlstad", "author_id": 18519921, "author_profile": "https://Stackoverflow.com/users/18519921", "pm_score": 3, "selected": true, "text": "add" }, { "answer_id": 74413266, "author": "EnMag", "author_id": 6134279, "author_profile": "https://Stackoverflow.com/users/6134279", "pm_score": 1, "selected": false, "text": "#include <stdio.h>\n#include <iostream>\n\nint thirds(int a){\n return a + 1;\n}\n\ntemplate <typename T, typename B>\nint hello(T x, B y , int (*ptr)(int)){\n\n int first = x + 1;\n int second = y + 1;\n int third = ptr(first);\n\n return first + second + third;\n}\n\nint add(){\n\n int (*ptr)(int) = &thirds;\n return hello(1, 1, ptr); //from here pass a number\n}\n\nint main()\n{\n\n std::cout << add();\n\n return 0;\n}\n" }, { "answer_id": 74413376, "author": "fabian", "author_id": 2991525, "author_profile": "https://Stackoverflow.com/users/2991525", "pm_score": 2, "selected": false, "text": "thirds(6)\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20483318/" ]
74,413,187
<p>I would like to extract real-time data from a file that does not have a .</p> <p>this file is a history of an application developed with nwjs</p> <p>file example:</p> <p><a href="https://i.stack.imgur.com/j8vWj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j8vWj.png" alt="" /></a></p> <p>do you have a solution to this problem?</p>
[ { "answer_id": 74413253, "author": "wohlstad", "author_id": 18519921, "author_profile": "https://Stackoverflow.com/users/18519921", "pm_score": 3, "selected": true, "text": "add" }, { "answer_id": 74413266, "author": "EnMag", "author_id": 6134279, "author_profile": "https://Stackoverflow.com/users/6134279", "pm_score": 1, "selected": false, "text": "#include <stdio.h>\n#include <iostream>\n\nint thirds(int a){\n return a + 1;\n}\n\ntemplate <typename T, typename B>\nint hello(T x, B y , int (*ptr)(int)){\n\n int first = x + 1;\n int second = y + 1;\n int third = ptr(first);\n\n return first + second + third;\n}\n\nint add(){\n\n int (*ptr)(int) = &thirds;\n return hello(1, 1, ptr); //from here pass a number\n}\n\nint main()\n{\n\n std::cout << add();\n\n return 0;\n}\n" }, { "answer_id": 74413376, "author": "fabian", "author_id": 2991525, "author_profile": "https://Stackoverflow.com/users/2991525", "pm_score": 2, "selected": false, "text": "thirds(6)\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20485761/" ]
74,413,201
<p>I want to achieve this format. As you can see on the output there's a bracket but I want to get only the <strong>'10': [&quot;11/21/2022&quot;, &quot;11/25/2022&quot;]</strong> or this one.</p> <pre><code>{ '10': [&quot;11/21/2022&quot;, &quot;11/25/2022&quot;] } </code></pre> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const data = [{ user_id: "10", dates: ["11/21/2022", "11/25/2022"], }, ]; const output = data.map(({ user_id, dates }) =&gt; ({ [user_id]: dates })); console.log(output);</code></pre> </div> </div> </p>
[ { "answer_id": 74413253, "author": "wohlstad", "author_id": 18519921, "author_profile": "https://Stackoverflow.com/users/18519921", "pm_score": 3, "selected": true, "text": "add" }, { "answer_id": 74413266, "author": "EnMag", "author_id": 6134279, "author_profile": "https://Stackoverflow.com/users/6134279", "pm_score": 1, "selected": false, "text": "#include <stdio.h>\n#include <iostream>\n\nint thirds(int a){\n return a + 1;\n}\n\ntemplate <typename T, typename B>\nint hello(T x, B y , int (*ptr)(int)){\n\n int first = x + 1;\n int second = y + 1;\n int third = ptr(first);\n\n return first + second + third;\n}\n\nint add(){\n\n int (*ptr)(int) = &thirds;\n return hello(1, 1, ptr); //from here pass a number\n}\n\nint main()\n{\n\n std::cout << add();\n\n return 0;\n}\n" }, { "answer_id": 74413376, "author": "fabian", "author_id": 2991525, "author_profile": "https://Stackoverflow.com/users/2991525", "pm_score": 2, "selected": false, "text": "thirds(6)\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17919686/" ]
74,413,215
<p>I have a button and I would like to press it to open the dafult application of the phone emails. I tried to search online but I only find references to the url_launcher package which, from what I understand, allows you to open the email app and automatically write to someone, but I don't want this, I just want to open the email app and leave it on the main screen.</p>
[ { "answer_id": 74413386, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 0, "selected": false, "text": " Future<void> sendMailto({\n String email = \"mail@example.com\",\n }) async {\n final String emailSubject = \"some subject here\";\n final Uri parsedMailto = Uri.parse(\n \"mailto:<$email>?subject=$emailSubject\");\n\n if (!await launchUrl(\n parsedMailto,\n mode: LaunchMode.externalApplication,\n )) {\n throw \"error\"\n }\n }\n" }, { "answer_id": 74413404, "author": "jraufeisen", "author_id": 2641242, "author_profile": "https://Stackoverflow.com/users/2641242", "pm_score": 2, "selected": true, "text": "url_launcher" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16774958/" ]
74,413,281
<p>I tried to make a function that would subtract from a number, for example number <code>25</code>, to display the result <code>3</code> (because <code>5-2=3</code>) - the <code>smallest</code> is subtracted from the <code>large</code> number - while the numbers from <code>1</code> to <code>9</code> will remain the same so it will take into account only what is of 2 digits. unfortunately I kind of failed in my attempt and I would need a little help.</p> <pre><code>Dim lines As String() = originalString.Split(CChar(Environment.NewLine)) For Each line As String In lines Dim lineSum As String = 0 Dim index As Integer = 0 Dim numchars1 As Char Dim numchars2 As Char For Each numberChar As Char In line index += 1 If index = 1 Then numchars1 = numberChar End If If index &gt;= 2 Then numchars2 = numberChar End If Next If Val(numchars1) AndAlso Val(numchars2) &gt; 0 Then If Val(numchars2) &gt; Val(numchars1) Then lineSum = Val(numchars2) - Val(numchars1) ElseIf Val(numchars1) &gt; Val(numchars2) Then lineSum = Val(numchars1) - Val(numchars2) End If Else lineSum = numchars1 End If </code></pre>
[ { "answer_id": 74413386, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 0, "selected": false, "text": " Future<void> sendMailto({\n String email = \"mail@example.com\",\n }) async {\n final String emailSubject = \"some subject here\";\n final Uri parsedMailto = Uri.parse(\n \"mailto:<$email>?subject=$emailSubject\");\n\n if (!await launchUrl(\n parsedMailto,\n mode: LaunchMode.externalApplication,\n )) {\n throw \"error\"\n }\n }\n" }, { "answer_id": 74413404, "author": "jraufeisen", "author_id": 2641242, "author_profile": "https://Stackoverflow.com/users/2641242", "pm_score": 2, "selected": true, "text": "url_launcher" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12168973/" ]
74,413,304
<p>I have a column called <code>Email Address</code> that I want to mask the display of the addresses with <code>*</code>.</p> <p>Something like this:</p> <pre><code>aaron0@adventure-works.com --&gt; a****0@adventure-works.com aaron1@adventure-works.com --&gt; a****1@adventure-works.com aaron14@adventure-works.com --&gt; a*****4@adventure-works.com </code></pre> <p>How can I achieve this? How to implement the stuff or replace function?</p>
[ { "answer_id": 74413368, "author": "Bouke", "author_id": 6864688, "author_profile": "https://Stackoverflow.com/users/6864688", "pm_score": 2, "selected": false, "text": "ALTER COLUMN EmailAddress NVARCHAR(100) MASKED WITH (FUNCTION = 'email()')\n" }, { "answer_id": 74414911, "author": "Stu", "author_id": 15332650, "author_profile": "https://Stackoverflow.com/users/15332650", "pm_score": 1, "selected": false, "text": "with t as ( -- Sample data\n select * from (values\n ('aaron0@adventure-works.com'),\n ('aaron1@adventure-works.com'),\n ('aaron14@adventure-works.com')\n )e(email)\n) \nselect email, Stuff(email, 2, p, Replicate('*', p)) masked\nfrom t\ncross apply(values(CharIndex('@', email) - 3))a(p);\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6061660/" ]
74,413,329
<p>i want to make a function that return 0 if the list is empty otherwise 1</p> <p>and the binding shoul be ( val len = fn : (int * int * int) list list list list -&gt; int )</p> <pre><code>fun len[[[(x:(int*int*int)list)]]]= if null x then 0 else 1 this code seems working but there is a warning </code></pre> <p>Warning: match nonexhaustive ((x :: nil) :: nil) :: nil =&gt; ...</p> <pre><code> </code></pre>
[ { "answer_id": 74414645, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 1, "selected": false, "text": "len" }, { "answer_id": 74417521, "author": "John Coleman", "author_id": 4996248, "author_profile": "https://Stackoverflow.com/users/4996248", "pm_score": 1, "selected": true, "text": "0" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18005626/" ]
74,413,330
<p>The following code presents a way to add two traces to a Plotly figure:</p> <pre class="lang-py prettyprint-override"><code>import plotly.graph_objs as go fig = go.Figure() fig.add_trace(go.Scatter( x = [0, 1, 2, 3], y = [1, 2, 3, 4], mode = 'lines+markers', name = &quot;Trace 0&quot;, )) fig.add_trace(go.Scatter( x = [5,6,7,8], y = [1, 2, 3, 4], mode = 'lines+markers', name = &quot;Trace 1&quot;, )) fig.show() </code></pre> <p>Which looks like this: <a href="https://i.stack.imgur.com/2eseR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2eseR.png" alt="enter image description here" /></a></p> <p>Is it possible to merge these two traces into a single one such that they appear under the same title in the legend and share the same visual properties (i.e, color, markers, etc)? More over, merging these traces should enable toggling the visibility when clicking the title in the legend.</p>
[ { "answer_id": 74413520, "author": "medium-dimensional", "author_id": 7789963, "author_profile": "https://Stackoverflow.com/users/7789963", "pm_score": 1, "selected": false, "text": "import plotly.express as px\nimport plotly.graph_objects as go\nimport pandas as pd\n\ndf = pd.DataFrame({\"x\" : [0, 1, 2, 3, 5, 6, 7, 8], \"y\" : [1, 2, 3, 4] * 2})\ndf['color'] = ['Trace 0'] * len(df.index)\ndf['trace'] = [1] * int(len(df.index)/2) + [2] * int(len(df.index)/2)\n\nfig1 = px.line(df[df['trace'] == 1], x='x', y='y', color='color')\nfig2 = px.line(df[df['trace'] == 2], x='x', y='y')\n\nfig = go.Figure(data = fig1.data + fig2.data)\nfig.show()\n" }, { "answer_id": 74414021, "author": "Derek O", "author_id": 5327068, "author_profile": "https://Stackoverflow.com/users/5327068", "pm_score": 3, "selected": true, "text": "import plotly.graph_objs as go\nfig = go.Figure()\ntrace_color = \"#636EFA\" ## default plotly blue\nfig.add_trace(go.Scatter(\n x = [0, 1, 2, 3], y = [1, 2, 3, 4],\n mode = 'lines+markers',\n name = \"Trace 0\",\n marker = dict(color = trace_color),\n showlegend = False,\n legendgroup = \"Trace\",\n))\nfig.add_trace(go.Scatter(\n x = [5,6,7,8], y = [1, 2, 3, 4],\n mode = 'lines+markers',\n name = \"Trace\",\n marker = dict(color = trace_color),\n legendgroup = \"Trace\",\n))\nfig.show()\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5189462/" ]
74,413,364
<p>I am trying to add custom color to menu on tabs , I want color to fill the entire menu , currently this menu is in tab and I wanted a custom color to be added on top of it.</p> <p><a href="https://codesandbox.io/s/semantic-ui-example-forked-muho2n?file=/example.js" rel="nofollow noreferrer">current code </a></p> <p>if you see the above code default colors like red and orange works fine but when i try to add a custom color the entire menu turns black. how i can resolve this ?</p>
[ { "answer_id": 74413520, "author": "medium-dimensional", "author_id": 7789963, "author_profile": "https://Stackoverflow.com/users/7789963", "pm_score": 1, "selected": false, "text": "import plotly.express as px\nimport plotly.graph_objects as go\nimport pandas as pd\n\ndf = pd.DataFrame({\"x\" : [0, 1, 2, 3, 5, 6, 7, 8], \"y\" : [1, 2, 3, 4] * 2})\ndf['color'] = ['Trace 0'] * len(df.index)\ndf['trace'] = [1] * int(len(df.index)/2) + [2] * int(len(df.index)/2)\n\nfig1 = px.line(df[df['trace'] == 1], x='x', y='y', color='color')\nfig2 = px.line(df[df['trace'] == 2], x='x', y='y')\n\nfig = go.Figure(data = fig1.data + fig2.data)\nfig.show()\n" }, { "answer_id": 74414021, "author": "Derek O", "author_id": 5327068, "author_profile": "https://Stackoverflow.com/users/5327068", "pm_score": 3, "selected": true, "text": "import plotly.graph_objs as go\nfig = go.Figure()\ntrace_color = \"#636EFA\" ## default plotly blue\nfig.add_trace(go.Scatter(\n x = [0, 1, 2, 3], y = [1, 2, 3, 4],\n mode = 'lines+markers',\n name = \"Trace 0\",\n marker = dict(color = trace_color),\n showlegend = False,\n legendgroup = \"Trace\",\n))\nfig.add_trace(go.Scatter(\n x = [5,6,7,8], y = [1, 2, 3, 4],\n mode = 'lines+markers',\n name = \"Trace\",\n marker = dict(color = trace_color),\n legendgroup = \"Trace\",\n))\nfig.show()\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4442307/" ]
74,413,381
<p>I am trying to create a button with 2 parts of text, first the button text itself (title) and then (on the other side -&gt; right) the price, also the price should have another color. So, if this is the button -&gt; |title 3$|, the price must be aligned on the right! How would I do something like this? Please help, kind regards.</p> <p>This is my button:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input type="submit" name="message" class="myClass" style="text-align: left;" value="&amp;nbsp Title"&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74413422, "author": "Henryc17", "author_id": 14595300, "author_profile": "https://Stackoverflow.com/users/14595300", "pm_score": 2, "selected": true, "text": "<button type=\"submit\" style=\"width:10em;\"><span style=\"float:left;\">title</span><span style=\"float:right;\">3$</span></button>" }, { "answer_id": 74416198, "author": "codingGuy", "author_id": 19960658, "author_profile": "https://Stackoverflow.com/users/19960658", "pm_score": 0, "selected": false, "text": "<div style=\"position: relative;\" class=\"border-indigo br-8 flex my-5\">\n\n<input type=\"submit\"\nname=\"message\"\nclass=\"' . $class . '\"\nstyle=\"text-align: left;\"\nvalue=\"&nbsp; ' . $row['title'] . '\">\n \n<span style=\"position: absolute; right: 10px; color: lightgreen; font-size: 150%; line-height: 245%\">3$</span>\n\n</div>\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19960658/" ]
74,413,419
<p>i have the table:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>person</th> <th>score</th> <th>Job type</th> </tr> </thead> <tbody> <tr> <td>person 1</td> <td>6.5</td> <td>job 1</td> </tr> <tr> <td>person 1</td> <td>4.3</td> <td>job 2</td> </tr> <tr> <td>person 2</td> <td>1.2</td> <td>job 1</td> </tr> <tr> <td>person 2</td> <td>3.4</td> <td>job 2</td> </tr> <tr> <td>person 2</td> <td>4.3</td> <td>job 3</td> </tr> </tbody> </table> </div> <p>i want to ad a column with the job type, with highest score, like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>person</th> <th>score</th> <th>Job type</th> <th>Higest score</th> </tr> </thead> <tbody> <tr> <td>person 1</td> <td>6.5</td> <td>job 1</td> <td>job 1</td> </tr> <tr> <td>person 1</td> <td>4.3</td> <td>job 2</td> <td>job 1</td> </tr> <tr> <td>person 2</td> <td>1.2</td> <td>job 1</td> <td>job 3</td> </tr> <tr> <td>person 2</td> <td>3.4</td> <td>job 2</td> <td>job 3</td> </tr> <tr> <td>person 3</td> <td>4.3</td> <td>job 3</td> <td>job 3</td> </tr> </tbody> </table> </div> <p>Any idea how can I achieve this?</p>
[ { "answer_id": 74413517, "author": "Bushmaster", "author_id": 15415267, "author_profile": "https://Stackoverflow.com/users/15415267", "pm_score": 0, "selected": false, "text": "mask=df.sort_values('score').groupby('person').tail(1).rename(columns={'Job type':'Higest_score'})\n\nfinal=df.merge(mask[['person','Higest_score']],how='left')\nfinal\n'''\n person score Job type Higest_score\n0 person 1 6.5 job 1 job 1\n1 person 1 4.3 job 2 job 1\n2 person 2 1.2 job 1 job 3\n3 person 2 3.4 job 2 job 3\n4 person 2 4.3 job 3 job 3\n\n'''\n" }, { "answer_id": 74413573, "author": "Panda Kim", "author_id": 20430449, "author_profile": "https://Stackoverflow.com/users/20430449", "pm_score": 0, "selected": false, "text": "df.groupby('person')['score'].transform(lambda x:df.loc[x.idxmax(), 'Job type'])\n" }, { "answer_id": 74413576, "author": "ouroboros1", "author_id": 18470692, "author_profile": "https://Stackoverflow.com/users/18470692", "pm_score": 2, "selected": false, "text": "df.groupby" }, { "answer_id": 74413738, "author": "Алексей Р", "author_id": 15035314, "author_profile": "https://Stackoverflow.com/users/15035314", "pm_score": 0, "selected": false, "text": "merge()" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20485886/" ]
74,413,427
<p>I have been following all of the tutorials for using <strong>docker compose</strong> with regards to <strong>azure</strong> and have been running into a problem with regards to volumes.</p> <p>My docker compose file looks like this :</p> <pre><code>version: '3.7' services: app-server: build: context: . dockerfile: Dockerfile ports: - &quot;8080:8080&quot; depends_on: - db environment: SPRING_DATASOURCE_URL: jdbc:mysql://db:3306/shapeshop?useSSL=false&amp;serverTimezone=UTC&amp;useLegacyDatetimeCode=false SPRING_DATASOURCE_USERNAME: root SPRING_DATASOURCE_PASSWORD: root SERVER_PORT: 8080 networks: - backend db: image: mysql:5.7 ports: - &quot;3306:3306&quot; restart: always environment: MYSQL_DATABASE: shapeshop MYSQL_USER: admin MYSQL_PASSWORD: admin MYSQL_ROOT_PASSWORD: root volumes: - &quot;db-data:/var/lib/mysql&quot; networks: - backend volumes: db-data: driver: azure_file driver_opts: share_name: shapeshopfileshare storage_account_name: shapeshopstorageaccount networks: backend: </code></pre> <p>In the above YML file I am defining the <strong>volume</strong> for the mysql container (db) to point to azure artifacts. The tutorials state that I should use &quot;azure_file&quot; as a driver and then create a file share and a storage account.</p> <p>I created both of these (shapeshopfileshare and shapeshopstorageaccount):</p> <p><a href="https://i.stack.imgur.com/Se5GP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Se5GP.png" alt="enter image description here" /></a></p> <p>Now if I log into &quot;az&quot; CLI like so :</p> <pre><code>az login </code></pre> <p>I see my subscription &quot;<strong>shapeShopResourceGroup</strong>&quot;</p> <pre><code> { &quot;id&quot;: &quot;/subscriptions/8cdb50cb-ede8-4eac-80df-55afadf861cd/resourceGroups/shapeShopResourceGroup&quot;, &quot;location&quot;: &quot;eastus&quot;, &quot;managedBy&quot;: null, &quot;name&quot;: &quot;shapeShopResourceGroup&quot;, &quot;properties&quot;: { &quot;provisioningState&quot;: &quot;Succeeded&quot; }, &quot;tags&quot;: null, &quot;type&quot;: &quot;Microsoft.Resources/resourceGroups&quot; }, </code></pre> <p>I am also using the &quot;aci&quot; context :</p> <p><a href="https://i.stack.imgur.com/IRrUn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IRrUn.png" alt="enter image description here" /></a></p> <p>However when I do <strong>docker compose up</strong> I get this error :</p> <blockquote> <p>error: The storage account named <strong>shapeshopstorageaccount</strong> is already taken.</p> </blockquote> <p>This is really frustrating to me because, yes, <strong>shapeshopstorageaccount</strong> DOES EXIST! I created it for ME!</p> <p>So then, I think somehow my <strong>context</strong> does not associate properly with my <strong>subscription</strong>. So to check I type in :</p> <pre><code>az storage account list </code></pre> <p>...and my <strong>shapeshopstorageaccount</strong> is listed in the returned JSON. So it <em>seems</em> like the association between my storage account and subscription exists.</p> <p>Why is azure (or docker-compose) not associating the declared volume in my YML file with the azure storage that I created??</p>
[ { "answer_id": 74413517, "author": "Bushmaster", "author_id": 15415267, "author_profile": "https://Stackoverflow.com/users/15415267", "pm_score": 0, "selected": false, "text": "mask=df.sort_values('score').groupby('person').tail(1).rename(columns={'Job type':'Higest_score'})\n\nfinal=df.merge(mask[['person','Higest_score']],how='left')\nfinal\n'''\n person score Job type Higest_score\n0 person 1 6.5 job 1 job 1\n1 person 1 4.3 job 2 job 1\n2 person 2 1.2 job 1 job 3\n3 person 2 3.4 job 2 job 3\n4 person 2 4.3 job 3 job 3\n\n'''\n" }, { "answer_id": 74413573, "author": "Panda Kim", "author_id": 20430449, "author_profile": "https://Stackoverflow.com/users/20430449", "pm_score": 0, "selected": false, "text": "df.groupby('person')['score'].transform(lambda x:df.loc[x.idxmax(), 'Job type'])\n" }, { "answer_id": 74413576, "author": "ouroboros1", "author_id": 18470692, "author_profile": "https://Stackoverflow.com/users/18470692", "pm_score": 2, "selected": false, "text": "df.groupby" }, { "answer_id": 74413738, "author": "Алексей Р", "author_id": 15035314, "author_profile": "https://Stackoverflow.com/users/15035314", "pm_score": 0, "selected": false, "text": "merge()" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022330/" ]
74,413,459
<pre><code>const { generateNum } = require(&quot;./generate_num&quot;) Cypress.Commands.add('NewUserRegister', () =&gt; { const { userName, email, password} = generateNum(); cy.get(':nth-child(3) &gt; .nav-link').should('contain.text', 'Sign up').click() cy.get(':nth-child(1) &gt; .form-control').type(userName) cy.get(':nth-child(2) &gt; .form-control').type(email) cy.get(':nth-child(3) &gt; .form-control').type(password) cy.get('.btn').should('contain.text', 'Sign in').click() }); </code></pre> <p>I'm trying to create a custom command that will login to a user's page using this command's credentials. I have no idea how to do it. The data should be typed in this fields</p> <pre><code> cy.get(':nth-child(1) &gt; .form-control').type(?????????) cy.get(':nth-child(2) &gt; .form-control').type(?????????) </code></pre> <p>So i did this</p> <pre><code>const { generateNum } = require(&quot;./generate_num&quot;) Cypress.Commands.add('NewUserRegister', () =&gt; { const { userName, email, password} = generateNum(); cy.get(':nth-child(3) &gt; .nav-link').should('contain.text', 'Sign up').click() cy.get(':nth-child(1) &gt; .form-control').type(userName) cy.get(':nth-child(2) &gt; .form-control').type(email) cy.get(':nth-child(3) &gt; .form-control').type(password) cy.get('.btn').should('contain.text', 'Sign in').click() return cy.wrap(userName, email, password) }); </code></pre> <p>And this</p> <pre><code>it('log in register user', () =&gt; { cy.then(data =&gt; { cy.get(':nth-child(2) &gt; .nav-link').should('contain.text', 'Sign in').click() cy.get(':nth-child(1) &gt; .form-control').type(data.email) cy.get(':nth-child(2) &gt; .form-control').type(data.password) cy.get('.btn').should('contain.text', 'Sign in').click() }) </code></pre> <p>TypeError Cannot read properties of undefined (reading 'email')</p>
[ { "answer_id": 74415687, "author": "Grainger", "author_id": 20487878, "author_profile": "https://Stackoverflow.com/users/20487878", "pm_score": 2, "selected": false, "text": "return cy.wrap({userName, email, password})\n" }, { "answer_id": 74416474, "author": "Jared", "author_id": 20479451, "author_profile": "https://Stackoverflow.com/users/20479451", "pm_score": 1, "selected": true, "text": "const { generateNum } = require(\"./generate_num\");\n\nCypress.Commands.add('NewUserRegister', () => {\nconst {userName, email, password} = generateNum() \ncy.visit('/')\nconst user = ({userName, email, password})\ncy.get(':nth-child(3) > .nav-link').should('contain.text', 'Sign up').click();\ncy.get(':nth-child(1) > .form-control').type(userName);\ncy.get(':nth-child(2) > .form-control').type(email);\ncy.get(':nth-child(3) > .form-control').type(password);\ncy.get('.btn').should('contain.text', 'Sign in').click();\ncy.get(':nth-child(3) > .nav-link').should('contain.text', 'Settings').click();\ncy.get('.btn-outline-danger').should('contain.text', 'Or click here to logout').click()\n.then(response => ({...user}))\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20479451/" ]
74,413,505
<p>I want to do strict matching on a text file so that it only returns the patterns I have anded. So for example in a file:</p> <pre><code>xyz xy yx zyx </code></pre> <p>I want to run a command similar to:</p> <pre><code>awk '/x/ &amp;&amp; /y/' filename.txt </code></pre> <p>and I would like it to return only the lines.</p> <pre><code>yx xy </code></pre> <p>and ignore the others because although they do contain an x and a y, they also have a z so they are ignored.</p> <p>Is this possible in awk?</p>
[ { "answer_id": 74413518, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 1, "selected": false, "text": "/x/ && /y/" }, { "answer_id": 74413986, "author": "Dave Pritlove", "author_id": 2005666, "author_profile": "https://Stackoverflow.com/users/2005666", "pm_score": 0, "selected": false, "text": "/x/&&/y/" }, { "answer_id": 74414123, "author": "Ed Morton", "author_id": 1745001, "author_profile": "https://Stackoverflow.com/users/1745001", "pm_score": 1, "selected": false, "text": "$ awk '/^[xy]+$/' file\nxy\nyx\n" }, { "answer_id": 74414513, "author": "markp-fuso", "author_id": 7366100, "author_profile": "https://Stackoverflow.com/users/7366100", "pm_score": 1, "selected": true, "text": "x" }, { "answer_id": 74414714, "author": "dawg", "author_id": 298607, "author_profile": "https://Stackoverflow.com/users/298607", "pm_score": 0, "selected": false, "text": "awk -v set='xy' '\n\nfunction cmp(s1, s2) {\n # turns s1 and s2 into associative arrays to do a set equality comparison\n # cmp(\"xy\", \"xyxyxyxy\") returns 1; cmp(\"xy\", \"xyz\") returns 0\n split(\"\", a1); split(\"\", a2) # clear the arrays from last use\n split(s1, tmp, \"\"); for (i in tmp) a1[tmp[i]]\n split(s2, tmp, \"\"); for (i in tmp) a2[tmp[i]]\n if (length(a1) != length(a2)) return 0\n for (e in a1) if (!(e in a2)) return 0\n \n return 1\n }\n\ncmp(set, $1)' file\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12924562/" ]
74,413,601
<p>So I've a 2D-array looking like this:</p> <pre><code>[[1 0] [2 0] [3 0] [4 0] ... </code></pre> <p>and I want to save it to a csvfile, I know that I must use to_csv to do so.</p> <p>So I tried doing : np.savetxt(&quot;file.csv&quot;,array,delimiter=',',fmt='%d,%d'), %d is to store data as int not as the default format But my csv file only contains the first column and not the column of zero.</p>
[ { "answer_id": 74413518, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 1, "selected": false, "text": "/x/ && /y/" }, { "answer_id": 74413986, "author": "Dave Pritlove", "author_id": 2005666, "author_profile": "https://Stackoverflow.com/users/2005666", "pm_score": 0, "selected": false, "text": "/x/&&/y/" }, { "answer_id": 74414123, "author": "Ed Morton", "author_id": 1745001, "author_profile": "https://Stackoverflow.com/users/1745001", "pm_score": 1, "selected": false, "text": "$ awk '/^[xy]+$/' file\nxy\nyx\n" }, { "answer_id": 74414513, "author": "markp-fuso", "author_id": 7366100, "author_profile": "https://Stackoverflow.com/users/7366100", "pm_score": 1, "selected": true, "text": "x" }, { "answer_id": 74414714, "author": "dawg", "author_id": 298607, "author_profile": "https://Stackoverflow.com/users/298607", "pm_score": 0, "selected": false, "text": "awk -v set='xy' '\n\nfunction cmp(s1, s2) {\n # turns s1 and s2 into associative arrays to do a set equality comparison\n # cmp(\"xy\", \"xyxyxyxy\") returns 1; cmp(\"xy\", \"xyz\") returns 0\n split(\"\", a1); split(\"\", a2) # clear the arrays from last use\n split(s1, tmp, \"\"); for (i in tmp) a1[tmp[i]]\n split(s2, tmp, \"\"); for (i in tmp) a2[tmp[i]]\n if (length(a1) != length(a2)) return 0\n for (e in a1) if (!(e in a2)) return 0\n \n return 1\n }\n\ncmp(set, $1)' file\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20480762/" ]
74,413,619
<p>I have a poorly formatted LaTeX which needs to be formatted in specific manner to render in Jupyter Notebook correctly:</p> <pre class="lang-py prettyprint-override"><code># Supporting Libraries: from qiskit.visualization import array_to_latex from IPython.display import display, Markdown # Unsuitable LaTeX latex_baad = '$QFT = \\frac{1}{\\sqrt{32}} \n\n\\begin{bmatrix}\n0 \\\\\n -1 \\\\\n \\end{bmatrix}\n \\otimes \n\n\\begin{bmatrix}\n0 \\\\\n \\tfrac{1}{\\sqrt{2}}(1 - i) \\\\\n \\end{bmatrix}\n \\otimes \n\n\\begin{bmatrix}\n0 \\\\\n -0.92388 + 0.38268i \\\\\n \\end{bmatrix}\n \\otimes \n\n\\begin{bmatrix}\n0 \\\\\n -0.19509 - 0.98079i \\\\\n \\end{bmatrix}\n$' # Suitable LaTeX latex_good = r'$QFT = \frac{1}{ \sqrt{32}} \begin{bmatrix} 0 \\ -1 \end{bmatrix} \otimes \begin{bmatrix} 0 \\ \tfrac{1}{ \sqrt{2}}(1 - i) \end{bmatrix} \otimes \begin{bmatrix} 0 \\ -0.92388 + 0.38268i \end{bmatrix} \otimes \begin{bmatrix} 0 \\ -0.19509 - 0.98079i \end{bmatrix}$' display(Markdown(latex_good)) </code></pre>
[ { "answer_id": 74413518, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 1, "selected": false, "text": "/x/ && /y/" }, { "answer_id": 74413986, "author": "Dave Pritlove", "author_id": 2005666, "author_profile": "https://Stackoverflow.com/users/2005666", "pm_score": 0, "selected": false, "text": "/x/&&/y/" }, { "answer_id": 74414123, "author": "Ed Morton", "author_id": 1745001, "author_profile": "https://Stackoverflow.com/users/1745001", "pm_score": 1, "selected": false, "text": "$ awk '/^[xy]+$/' file\nxy\nyx\n" }, { "answer_id": 74414513, "author": "markp-fuso", "author_id": 7366100, "author_profile": "https://Stackoverflow.com/users/7366100", "pm_score": 1, "selected": true, "text": "x" }, { "answer_id": 74414714, "author": "dawg", "author_id": 298607, "author_profile": "https://Stackoverflow.com/users/298607", "pm_score": 0, "selected": false, "text": "awk -v set='xy' '\n\nfunction cmp(s1, s2) {\n # turns s1 and s2 into associative arrays to do a set equality comparison\n # cmp(\"xy\", \"xyxyxyxy\") returns 1; cmp(\"xy\", \"xyz\") returns 0\n split(\"\", a1); split(\"\", a2) # clear the arrays from last use\n split(s1, tmp, \"\"); for (i in tmp) a1[tmp[i]]\n split(s2, tmp, \"\"); for (i in tmp) a2[tmp[i]]\n if (length(a1) != length(a2)) return 0\n for (e in a1) if (!(e in a2)) return 0\n \n return 1\n }\n\ncmp(set, $1)' file\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1176573/" ]
74,413,626
<p>I have some number of lines in data for input:</p> <pre><code>data = sys.stdin.readlines() </code></pre> <p>Find out the number of lines:</p> <pre><code>l = len(data) </code></pre> <p>How can I split this data into variables? For example I have the following input:</p> <pre><code>1 0 2 2 0 0 1 1 0 1 1 0 </code></pre> <p>First come 2 numbers - n, m</p> <p>Then m lines with 4 values - x1, y1, x2, y2</p> <p>I tried to do this:</p> <pre><code>for _ in range(l): n, m = map(int, data.readline().split()) some_list = [] for _ in range(m): x1, y1, x2, y2 = map(int, data.readline().split()) some_list.append([x1, y1, x2, y2]) some_function_with_given_part_of_data() </code></pre> <p>But it doesn't work correctly.</p>
[ { "answer_id": 74413775, "author": "Dean Van Greunen", "author_id": 6651840, "author_profile": "https://Stackoverflow.com/users/6651840", "pm_score": 2, "selected": true, "text": "data = sys.stdin.readlines()\nindexer = 0\nwhile indexer < len(data) - 1:\n n, m = map(int, data[indexer].split(\" \"))\n indexer = indexer + 1\n some_list = []\n for _ in range(m):\n x1, y1, x2, y2 = map(int, data[indexer].split(\" \"))\n some_list.append([x1, y1, x2, y2])\n indexer = indexer + 1\n print(some_list)\n" }, { "answer_id": 74413791, "author": "S.B", "author_id": 13944524, "author_profile": "https://Stackoverflow.com/users/13944524", "pm_score": 0, "selected": false, "text": "input()" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20145092/" ]
74,413,628
<p>I have a dataframe which has column as follows:</p> <pre><code>|REGION/CATEGORY| |--|-| |NORTHERN REGION| |THERMAL| |HYDRO| |NUCLEAR| |WESTERN REGION| |THERMAL| |HYDRO| |NUCLEAR| |SOUTHERN REGION| |THERMAL| |HYDRO| |NUCLEAR| |EASTERN REGION| |THERMAL| |HYDRO| |NORTH EASTERN REGION| |THERMAL| |HYDRO| |ALL INDIA REGION| |THERMAL| |HYDRO| |NUCLEAR| </code></pre> <p>I want to split the column into two different columns in the dataframe i.e.Region and Category as column name.</p> <pre><code>REGION = ['NORTHERN REGION','WESTERN REGION','SOUTHERN REGION','EASTERN REGION','NORTH EASTERN REGION'] CATEGORY = ['THERMAL','NUCLEAR','HYDRO'] </code></pre> <p>How can I write an if else statement so that I can get the following as desired output:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>REGION</th> <th>CATEGORY</th> </tr> </thead> <tbody> <tr> <td>11</td> <td>NORTHERN REGION</td> <td>THERMAL</td> </tr> <tr> <td>12</td> <td>NORTHERN REGION</td> <td>NUCLEAR</td> </tr> <tr> <td>13</td> <td>NORTHERN REGION</td> <td>HYDRO</td> </tr> <tr> <td>14</td> <td>WESTERN REGION</td> <td>THERMAL</td> </tr> <tr> <td>15</td> <td>WESTERN REGION</td> <td>NUCLEAR</td> </tr> <tr> <td>16</td> <td>WESTERN REGION</td> <td>HYDRO</td> </tr> </tbody> </table> </div> <pre><code>for df['REGION'] in df: if df['REGION'] == 'REGION': df['REGION'] = df['REGION'].append('REGION') elif df['CATEGORY'] == CATEGORY: df['CATEGORY'] = df['CATEGORY'].append('CATEGORY') </code></pre> <p>I tried to append it to the columns after splitting</p>
[ { "answer_id": 74413775, "author": "Dean Van Greunen", "author_id": 6651840, "author_profile": "https://Stackoverflow.com/users/6651840", "pm_score": 2, "selected": true, "text": "data = sys.stdin.readlines()\nindexer = 0\nwhile indexer < len(data) - 1:\n n, m = map(int, data[indexer].split(\" \"))\n indexer = indexer + 1\n some_list = []\n for _ in range(m):\n x1, y1, x2, y2 = map(int, data[indexer].split(\" \"))\n some_list.append([x1, y1, x2, y2])\n indexer = indexer + 1\n print(some_list)\n" }, { "answer_id": 74413791, "author": "S.B", "author_id": 13944524, "author_profile": "https://Stackoverflow.com/users/13944524", "pm_score": 0, "selected": false, "text": "input()" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13277504/" ]
74,413,639
<p>I'm having trouble passing a variable that stores a certain value to <code>with()</code>, it returns what I want, but it returns the following message.</p> <p><code>[{&quot;name&quot;:&quot;Ryu&quot;}] won updates in your informations.</code> rather then <code>Ryu won updates in your informations.</code></p> <pre><code> public function update(FighterRequest $request, $id) { $validations = $request-&gt;validated(); FighterModel::where('id',$id)-&gt;update($validations); $name_fighter = DB::table('fighters')-&gt;select('name')-&gt;where('id','=',$id)-&gt;get(); return redirect('fighter')-&gt;with('success-update',&quot;$name_fighter won updates in your informations.&quot;); } </code></pre>
[ { "answer_id": 74413775, "author": "Dean Van Greunen", "author_id": 6651840, "author_profile": "https://Stackoverflow.com/users/6651840", "pm_score": 2, "selected": true, "text": "data = sys.stdin.readlines()\nindexer = 0\nwhile indexer < len(data) - 1:\n n, m = map(int, data[indexer].split(\" \"))\n indexer = indexer + 1\n some_list = []\n for _ in range(m):\n x1, y1, x2, y2 = map(int, data[indexer].split(\" \"))\n some_list.append([x1, y1, x2, y2])\n indexer = indexer + 1\n print(some_list)\n" }, { "answer_id": 74413791, "author": "S.B", "author_id": 13944524, "author_profile": "https://Stackoverflow.com/users/13944524", "pm_score": 0, "selected": false, "text": "input()" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20338917/" ]
74,413,649
<p>I have a dictionary: where 0 and 1 are two index and the other numbers inside the two dictionaries are the frequency of each word in a previous list of strings</p> <p>letter_positions={0: {'l': 1, 'y': 2, 'm': 1, 'r': 2}, 1: {'t': 2, 'e': 1, 'n': 1, 's': 3}}</p> <p>I get that by a function that return a dictionary with the most frequent character of a string by index.</p> <p>Now I'm using this function to get the most frequent character for each index:</p> <pre><code>final_dict = {} for idx, counts in letter_positions.items(): most_popular = max(counts.items(), key=lambda v: v[1]) final_dict[idx] = most_popular[0][0] </code></pre> <p>The problem is that in the index 0 of the dictionary the most frequent characters are 'y' and 'r', my code return me 'y' in the final_dict dictionary, but I want to get the lowest alphabetic character 'r'.</p> <p>How can I edit my code or what do I have to add here</p> <pre><code> most_popular = max(counts.items(), key=lambda v: v[1]) </code></pre> <p>to perform my need? thanks</p>
[ { "answer_id": 74413775, "author": "Dean Van Greunen", "author_id": 6651840, "author_profile": "https://Stackoverflow.com/users/6651840", "pm_score": 2, "selected": true, "text": "data = sys.stdin.readlines()\nindexer = 0\nwhile indexer < len(data) - 1:\n n, m = map(int, data[indexer].split(\" \"))\n indexer = indexer + 1\n some_list = []\n for _ in range(m):\n x1, y1, x2, y2 = map(int, data[indexer].split(\" \"))\n some_list.append([x1, y1, x2, y2])\n indexer = indexer + 1\n print(some_list)\n" }, { "answer_id": 74413791, "author": "S.B", "author_id": 13944524, "author_profile": "https://Stackoverflow.com/users/13944524", "pm_score": 0, "selected": false, "text": "input()" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20485030/" ]
74,413,742
<p>I am trying to filter an array of objects based on user input.</p> <p>I wish filter based on the values of certain keys within the object. However, not all the objects have all keys inside them. This means when I check it throws an error.</p> <p>How do I ignore if a particular object does not have one of the keys inside it and continues to output the matching objects?</p> <p>Here is some sample data.</p> <pre><code>const data = [ { name: &quot;John Miller&quot;, age: 33, location: &quot;Chicago&quot;, address: '1 help street' }, { name: &quot;Jane Doe&quot;, age: 78, address: '1 help me please lane' }, { name: &quot;Jamie Stevens&quot;, location: &quot;San Diego&quot;, age: 32 } ] </code></pre> <p>The second object does not have 'location' as a key and the third object does not have 'address' as a key.</p> <pre><code>const handleSearch = (query) =&gt; { const keys = ['name', 'location', 'address'] const filter = data.filter((row) =&gt; ( keys.some((key) =&gt; (row[key].toLowerCase().includes(query)) ))) setFilteredData(filter) } </code></pre> <p>Thank you,</p>
[ { "answer_id": 74413810, "author": "Neil Girardi", "author_id": 1500241, "author_profile": "https://Stackoverflow.com/users/1500241", "pm_score": 3, "selected": true, "text": "const handleSearch = (query) => {\n const keys = ['name', 'location', 'address']\n const filter = data.filter((row) => (\n keys.some((key) => {\n const k = row?.[key] ?? ''\n return (k.toLowerCase().includes(query))\n }\n )))\n setFilteredData(filter)\n}\n" }, { "answer_id": 74413855, "author": "Amila Senadheera", "author_id": 8510405, "author_profile": "https://Stackoverflow.com/users/8510405", "pm_score": 1, "selected": false, "text": "const data = [\n {\n name: \"John Miller\",\n age: 33,\n location: \"Chicago\",\n address: \"1 help street\",\n },\n\n {\n name: \"Jane Doe\",\n age: 78,\n address: \"1 help me please lane\",\n },\n\n {\n name: \"Jamie Stevens\",\n location: \"San Diego\",\n age: 32,\n },\n];\n\nconst handleSearch = (query) => {\n const keys = [\"name\", \"location\", \"address\"];\n const filtered = data.filter((row) =>\n keys.some((key) => { \n return row[key]?.toLowerCase().includes(query.toLowerCase())})\n );\n console.log(filtered);\n};\n\nhandleSearch(\"Chicago\")" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12716872/" ]
74,413,747
<p>I am trying to make an HTTP call to a server to get its HTML contents everything is working fine on other android versions. But in android 6 when the app is calling HTMLunit it crashes.</p> <p>I know it has to do with something that works on API above 23. but not on the 23.. I tried many things but I sill can't fix it...</p> <p><strong>Why it's important to run the app on android 6:</strong></p> <p>A big number of my users is using android 6 and 5</p> <p><strong>The error:</strong></p> <pre><code>FATAL EXCEPTION: Thread-9255 Process: bd.maruf.myapplication, PID: 7773 java.lang.NoClassDefFoundError: java.util.function.Supplier at libcore.reflect.InternalNames.getClass(InternalNames.java:55) at java.lang.Class.getDexCacheType(Class.java:476) at java.lang.reflect.Method.getReturnType(Method.java:183) at java.lang.Class.getDeclaredMethods(Class.java:678) at com.gargoylesoftware.htmlunit.javascript.configuration.AbstractJavaScriptConfiguration.process(AbstractJavaScriptConfiguration.java:212) at com.gargoylesoftware.htmlunit.javascript.configuration.AbstractJavaScriptConfiguration.getClassConfiguration(AbstractJavaScriptConfiguration.java:193) at com.gargoylesoftware.htmlunit.javascript.configuration.AbstractJavaScriptConfiguration.&lt;init&gt;(AbstractJavaScriptConfiguration.java:67) at com.gargoylesoftware.htmlunit.javascript.configuration.JavaScriptConfiguration.&lt;init&gt;(JavaScriptConfiguration.java:685) at com.gargoylesoftware.htmlunit.javascript.configuration.JavaScriptConfiguration.getInstance(JavaScriptConfiguration.java:701) at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.&lt;init&gt;(JavaScriptEngine.java:161) at com.gargoylesoftware.htmlunit.WebClient.&lt;init&gt;(WebClient.java:326) at com.gargoylesoftware.htmlunit.WebClient.&lt;init&gt;(WebClient.java:275) at com.gargoylesoftware.htmlunit.WebClient.&lt;init&gt;(WebClient.java:265) at com.gargoylesoftware.htmlunit.WebClient.&lt;init&gt;(WebClient.java:257) at bd.maruf.myapplication.MainActivity.main(MainActivity.kt:32) at bd.maruf.myapplication.MainActivity.onCreate$lambda$1$lambda$0(MainActivity.kt:22) at bd.maruf.myapplication.MainActivity.$r8$lambda$VtPJx1mT1BVGpp5vWQWqcx_e4kM(MainActivity.kt) at bd.maruf.myapplication.MainActivity$$ExternalSyntheticLambda2.run(D8$$SyntheticClass) at java.lang.Thread.run(Thread.java:818) Caused by: java.lang.ClassNotFoundException: Didn't find class &quot;java.util.function.Supplier&quot; on path: DexPathList[[zip file &quot;/data/app/bd.maruf.myapplication-1/base.apk&quot;],nativeLibraryDirectories=[/data/app/bd.maruf.myapplication-1/lib/arm, /vendor/lib, /system/lib]] at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56) at java.lang.ClassLoader.loadClass(ClassLoader.java:511) at java.lang.ClassLoader.loadClass(ClassLoader.java:469) at libcore.reflect.InternalNames.getClass(InternalNames.java:53) at java.lang.Class.getDexCacheType(Class.java:476)  at java.lang.reflect.Method.getReturnType(Method.java:183)  at java.lang.Class.getDeclaredMethods(Class.java:678)  at com.gargoylesoftware.htmlunit.javascript.configuration.AbstractJavaScriptConfiguration.process(AbstractJavaScriptConfiguration.java:212)  at com.gargoylesoftware.htmlunit.javascript.configuration.AbstractJavaScriptConfiguration.getClassConfiguration(AbstractJavaScriptConfiguration.java:193)  at com.gargoylesoftware.htmlunit.javascript.configuration.AbstractJavaScriptConfiguration.&lt;init&gt;(AbstractJavaScriptConfiguration.java:67)  at com.gargoylesoftware.htmlunit.javascript.configuration.JavaScriptConfiguration.&lt;init&gt;(JavaScriptConfiguration.java:685)  at com.gargoylesoftware.htmlunit.javascript.configuration.JavaScriptConfiguration.getInstance(JavaScriptConfiguration.java:701)  at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.&lt;init&gt;(JavaScriptEngine.java:161)  at com.gargoylesoftware.htmlunit.WebClient.&lt;init&gt;(WebClient.java:326)  at com.gargoylesoftware.htmlunit.WebClient.&lt;init&gt;(WebClient.java:275)  at com.gargoylesoftware.htmlunit.WebClient.&lt;init&gt;(WebClient.java:265)  at com.gargoylesoftware.htmlunit.WebClient.&lt;init&gt;(WebClient.java:257)  at bd.maruf.myapplication.MainActivity.main(MainActivity.kt:32)  at bd.maruf.myapplication.MainActivity.onCreate$lambda$1$lambda$0(MainActivity.kt:22)  at bd.maruf.myapplication.MainActivity.$r8$lambda$VtPJx1mT1BVGpp5vWQWqcx_e4kM(MainActivity.kt)  at bd.maruf.myapplication.MainActivity$$ExternalSyntheticLambda2.run(D8$$SyntheticClass)  at java.lang.Thread.run(Thread.java:818)  Suppressed: java.lang.ClassNotFoundException: java.util.function.Supplier at java.lang.Class.classForName(Native Method) at java.lang.BootClassLoader.findClass(ClassLoader.java:781) at java.lang.BootClassLoader.loadClass(ClassLoader.java:841) at java.lang.ClassLoader.loadClass(ClassLoader.java:504) ... 20 more Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available 2022-11-12 18:11:50.861 7773-7807 Surface bd.maruf.myapplication D Surface::disconnect(this=0xaddb7b00,api=1) </code></pre> <p><strong>what I have tried :</strong></p> <ol> <li><p>cleaning and rebuilding that project</p> </li> <li><p>adding:</p> <pre><code>defaultConfig { multiDexEnabled true} </code></pre> <pre><code>dependencies {implementation 'com.android.support:multidex:1.0.3' </code></pre> </li> </ol> <p>3. deleting .gradel and .idea file</p>
[ { "answer_id": 74413810, "author": "Neil Girardi", "author_id": 1500241, "author_profile": "https://Stackoverflow.com/users/1500241", "pm_score": 3, "selected": true, "text": "const handleSearch = (query) => {\n const keys = ['name', 'location', 'address']\n const filter = data.filter((row) => (\n keys.some((key) => {\n const k = row?.[key] ?? ''\n return (k.toLowerCase().includes(query))\n }\n )))\n setFilteredData(filter)\n}\n" }, { "answer_id": 74413855, "author": "Amila Senadheera", "author_id": 8510405, "author_profile": "https://Stackoverflow.com/users/8510405", "pm_score": 1, "selected": false, "text": "const data = [\n {\n name: \"John Miller\",\n age: 33,\n location: \"Chicago\",\n address: \"1 help street\",\n },\n\n {\n name: \"Jane Doe\",\n age: 78,\n address: \"1 help me please lane\",\n },\n\n {\n name: \"Jamie Stevens\",\n location: \"San Diego\",\n age: 32,\n },\n];\n\nconst handleSearch = (query) => {\n const keys = [\"name\", \"location\", \"address\"];\n const filtered = data.filter((row) =>\n keys.some((key) => { \n return row[key]?.toLowerCase().includes(query.toLowerCase())})\n );\n console.log(filtered);\n};\n\nhandleSearch(\"Chicago\")" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15793557/" ]
74,413,748
<p>My data table <code>comb</code> (<code>dput</code> output below) has the structure below. I want to dcast it like this</p> <pre><code>comb_wide &lt;- dcast(comb, scenarios + qName + hemName ~ PWC_cutoff, value.var = sum) </code></pre> <p>R returns this error message</p> <pre><code>Error in setattr(ans, &quot;names&quot;, c(lhsnames, allcols)) : 'names' attribute [7] must be the same length as the vector [3] </code></pre> <p>I can't figure out what attribute 7 and vector 3 refer to.</p> <pre><code>&gt; str(comb) Classes ‘data.table’ and 'data.frame': 96 obs. of 5 variables: $ scenarios : chr &quot;historical_1991_2010&quot; &quot;ssp126_2041_2060&quot; &quot;ssp126_2081_2100&quot; &quot;ssp585_2041_2060&quot; ... $ qName : chr &quot;q1&quot; &quot;q1&quot; &quot;q1&quot; &quot;q1&quot; ... $ hemName : Factor w/ 2 levels &quot;NH&quot;,&quot;SH&quot;: 1 1 1 1 1 1 1 1 1 1 ... $ sum : num 0 0 0 0 0 ... $ PWC_cutoff: num 20 20 20 20 20 20 40 40 40 40 ... - attr(*, &quot;.internal.selfref&quot;)=&lt;externalptr&gt; </code></pre> <p>dput output</p> <pre><code>structure(list(scenarios = c(&quot;historical_1991_2010&quot;, &quot;ssp126_2041_2060&quot;, &quot;ssp126_2081_2100&quot;, &quot;ssp585_2041_2060&quot;, &quot;ssp585_2081_2100&quot;, &quot;aglabor&quot;, &quot;historical_1991_2010&quot;, &quot;ssp126_2041_2060&quot;, &quot;ssp126_2081_2100&quot;, &quot;ssp585_2041_2060&quot;, &quot;ssp585_2081_2100&quot;, &quot;aglabor&quot;, &quot;historical_1991_2010&quot;, &quot;ssp126_2041_2060&quot;, &quot;ssp126_2081_2100&quot;, &quot;ssp585_2041_2060&quot;, &quot;ssp585_2081_2100&quot;, &quot;aglabor&quot;, &quot;historical_1991_2010&quot;, &quot;ssp126_2041_2060&quot;, &quot;ssp126_2081_2100&quot;, &quot;ssp585_2041_2060&quot;, &quot;ssp585_2081_2100&quot;, &quot;aglabor&quot;, &quot;historical_1991_2010&quot;, &quot;ssp126_2041_2060&quot;, &quot;ssp126_2081_2100&quot;, &quot;ssp585_2041_2060&quot;, &quot;ssp585_2081_2100&quot;, &quot;aglabor&quot;, &quot;historical_1991_2010&quot;, &quot;ssp126_2041_2060&quot;, &quot;ssp126_2081_2100&quot;, &quot;ssp585_2041_2060&quot;, &quot;ssp585_2081_2100&quot;, &quot;aglabor&quot;, &quot;historical_1991_2010&quot;, &quot;ssp126_2041_2060&quot;, &quot;ssp126_2081_2100&quot;, &quot;ssp585_2041_2060&quot;, &quot;ssp585_2081_2100&quot;, &quot;aglabor&quot;, &quot;historical_1991_2010&quot;, &quot;ssp126_2041_2060&quot;, &quot;ssp126_2081_2100&quot;, &quot;ssp585_2041_2060&quot;, &quot;ssp585_2081_2100&quot;, &quot;aglabor&quot;, &quot;historical_1991_2010&quot;, &quot;ssp126_2041_2060&quot;, &quot;ssp126_2081_2100&quot;, &quot;ssp585_2041_2060&quot;, &quot;ssp585_2081_2100&quot;, &quot;aglabor&quot;, &quot;historical_1991_2010&quot;, &quot;ssp126_2041_2060&quot;, &quot;ssp126_2081_2100&quot;, &quot;ssp585_2041_2060&quot;, &quot;ssp585_2081_2100&quot;, &quot;aglabor&quot;, &quot;historical_1991_2010&quot;, &quot;ssp126_2041_2060&quot;, &quot;ssp126_2081_2100&quot;, &quot;ssp585_2041_2060&quot;, &quot;ssp585_2081_2100&quot;, &quot;aglabor&quot;, &quot;historical_1991_2010&quot;, &quot;ssp126_2041_2060&quot;, &quot;ssp126_2081_2100&quot;, &quot;ssp585_2041_2060&quot;, &quot;ssp585_2081_2100&quot;, &quot;aglabor&quot;, &quot;historical_1991_2010&quot;, &quot;ssp126_2041_2060&quot;, &quot;ssp126_2081_2100&quot;, &quot;ssp585_2041_2060&quot;, &quot;ssp585_2081_2100&quot;, &quot;aglabor&quot;, &quot;historical_1991_2010&quot;, &quot;ssp126_2041_2060&quot;, &quot;ssp126_2081_2100&quot;, &quot;ssp585_2041_2060&quot;, &quot;ssp585_2081_2100&quot;, &quot;aglabor&quot;, &quot;historical_1991_2010&quot;, &quot;ssp126_2041_2060&quot;, &quot;ssp126_2081_2100&quot;, &quot;ssp585_2041_2060&quot;, &quot;ssp585_2081_2100&quot;, &quot;aglabor&quot;, &quot;historical_1991_2010&quot;, &quot;ssp126_2041_2060&quot;, &quot;ssp126_2081_2100&quot;, &quot;ssp585_2041_2060&quot;, &quot;ssp585_2081_2100&quot;, &quot;aglabor&quot;), qName = c(&quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q1&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;, &quot;q3&quot;), hemName = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), levels = c(&quot;NH&quot;, &quot;SH&quot;), class = &quot;factor&quot;), sum = c(0, 0, 0, 0, 0, 746051, 0, 0, 0, 0, 35, 746051, 0, 141, 341, 598, 25672, 746051, 50171, 72535, 75671, 82293, 200119, 746051, 0, 0, 0, 0, 0, 137649, 0, 0, 0, 0, 0, 137649, 0, 0, 0, 7, 26595, 137649, 39501, 54149, 54192, 62361, 92355, 137649, 0, 0, 0, 0, 0, 746051, 0, 0, 0, 0, 28991, 746051, 3909, 63236, 75858, 99751, 341094, 746051, 365996, 462080, 464957, 488522, 569331, 746051, 0, 0, 0, 0, 0, 137649, 0, 0, 0, 0, 0, 137649, 0, 1, 2, 110, 8023, 137649, 14720, 18365, 18447, 21514, 35848, 137649), PWC_cutoff = c(20, 20, 20, 20, 20, 20, 40, 40, 40, 40, 40, 40, 60, 60, 60, 60, 60, 60, 80, 80, 80, 80, 80, 80, 20, 20, 20, 20, 20, 20, 40, 40, 40, 40, 40, 40, 60, 60, 60, 60, 60, 60, 80, 80, 80, 80, 80, 80, 20, 20, 20, 20, 20, 20, 40, 40, 40, 40, 40, 40, 60, 60, 60, 60, 60, 60, 80, 80, 80, 80, 80, 80, 20, 20, 20, 20, 20, 20, 40, 40, 40, 40, 40, 40, 60, 60, 60, 60, 60, 60, 80, 80, 80, 80, 80, 80)), row.names = c(NA, -96L ), class = c(&quot;data.table&quot;, &quot;data.frame&quot;), .internal.selfref = &lt;pointer: 0x13783aee0&gt;) </code></pre>
[ { "answer_id": 74413810, "author": "Neil Girardi", "author_id": 1500241, "author_profile": "https://Stackoverflow.com/users/1500241", "pm_score": 3, "selected": true, "text": "const handleSearch = (query) => {\n const keys = ['name', 'location', 'address']\n const filter = data.filter((row) => (\n keys.some((key) => {\n const k = row?.[key] ?? ''\n return (k.toLowerCase().includes(query))\n }\n )))\n setFilteredData(filter)\n}\n" }, { "answer_id": 74413855, "author": "Amila Senadheera", "author_id": 8510405, "author_profile": "https://Stackoverflow.com/users/8510405", "pm_score": 1, "selected": false, "text": "const data = [\n {\n name: \"John Miller\",\n age: 33,\n location: \"Chicago\",\n address: \"1 help street\",\n },\n\n {\n name: \"Jane Doe\",\n age: 78,\n address: \"1 help me please lane\",\n },\n\n {\n name: \"Jamie Stevens\",\n location: \"San Diego\",\n age: 32,\n },\n];\n\nconst handleSearch = (query) => {\n const keys = [\"name\", \"location\", \"address\"];\n const filtered = data.filter((row) =>\n keys.some((key) => { \n return row[key]?.toLowerCase().includes(query.toLowerCase())})\n );\n console.log(filtered);\n};\n\nhandleSearch(\"Chicago\")" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5943539/" ]
74,413,762
<p>I have this problem where I am asked to multiply BX by 42 without using any <code>mul</code> or <code>div</code> instructions, presumably by using <code>shl</code> or <code>shr</code>. It is also required to do it in 5 lines.</p> <p>How do you do such a thing ?</p> <p>I didn't try anything, but the above requirement was to multiply BX by 32 in 1 line, so I just used <code>SHL BX, 5</code>.</p>
[ { "answer_id": 74413810, "author": "Neil Girardi", "author_id": 1500241, "author_profile": "https://Stackoverflow.com/users/1500241", "pm_score": 3, "selected": true, "text": "const handleSearch = (query) => {\n const keys = ['name', 'location', 'address']\n const filter = data.filter((row) => (\n keys.some((key) => {\n const k = row?.[key] ?? ''\n return (k.toLowerCase().includes(query))\n }\n )))\n setFilteredData(filter)\n}\n" }, { "answer_id": 74413855, "author": "Amila Senadheera", "author_id": 8510405, "author_profile": "https://Stackoverflow.com/users/8510405", "pm_score": 1, "selected": false, "text": "const data = [\n {\n name: \"John Miller\",\n age: 33,\n location: \"Chicago\",\n address: \"1 help street\",\n },\n\n {\n name: \"Jane Doe\",\n age: 78,\n address: \"1 help me please lane\",\n },\n\n {\n name: \"Jamie Stevens\",\n location: \"San Diego\",\n age: 32,\n },\n];\n\nconst handleSearch = (query) => {\n const keys = [\"name\", \"location\", \"address\"];\n const filtered = data.filter((row) =>\n keys.some((key) => { \n return row[key]?.toLowerCase().includes(query.toLowerCase())})\n );\n console.log(filtered);\n};\n\nhandleSearch(\"Chicago\")" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15363079/" ]
74,413,770
<p>I'm dealing with a csv that repeats its headers name within each rows:</p> <pre><code>player: John Doe ; level: 45 ; last_login: 7854414174 ; coins: 7600 player: Anckx Uj ; level: 471 ; last_login: 7854418847 ; coins: 684111 </code></pre> <p>I'd like to know how I can only select the values when importing it using pandas so that the output looks like this:</p> <pre><code>Player level last_login coins John Doe 45 7854414174 7600 Anckx Uj 471 7854418847 684111 </code></pre> <p>I tried adding the header parameter as I thought it would filter out the repeating in the rows, without success.</p> <ul> <li><code>import pandas as pd df = pd.read_csv('base.txt', sep=';', header=None, names=['player', 'level', 'last_login', 'coins']</code> returns me exactly the same thing as the csv (without the delimiter)</li> </ul> <p>*Any help would be appreciated</p>
[ { "answer_id": 74413810, "author": "Neil Girardi", "author_id": 1500241, "author_profile": "https://Stackoverflow.com/users/1500241", "pm_score": 3, "selected": true, "text": "const handleSearch = (query) => {\n const keys = ['name', 'location', 'address']\n const filter = data.filter((row) => (\n keys.some((key) => {\n const k = row?.[key] ?? ''\n return (k.toLowerCase().includes(query))\n }\n )))\n setFilteredData(filter)\n}\n" }, { "answer_id": 74413855, "author": "Amila Senadheera", "author_id": 8510405, "author_profile": "https://Stackoverflow.com/users/8510405", "pm_score": 1, "selected": false, "text": "const data = [\n {\n name: \"John Miller\",\n age: 33,\n location: \"Chicago\",\n address: \"1 help street\",\n },\n\n {\n name: \"Jane Doe\",\n age: 78,\n address: \"1 help me please lane\",\n },\n\n {\n name: \"Jamie Stevens\",\n location: \"San Diego\",\n age: 32,\n },\n];\n\nconst handleSearch = (query) => {\n const keys = [\"name\", \"location\", \"address\"];\n const filtered = data.filter((row) =>\n keys.some((key) => { \n return row[key]?.toLowerCase().includes(query.toLowerCase())})\n );\n console.log(filtered);\n};\n\nhandleSearch(\"Chicago\")" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20144376/" ]
74,413,779
<p>Can someone tell me what I'm doing wrong here? The 1st function(all_products) renders in template perfectly, but the last 2 does not.</p> <p><strong>models.py</strong></p> <pre><code># TABLE BRAND class Brand(models.Model): name = models.CharField(max_length = 50) # TABLE PRODUCT class Product(models.Model): title = models.CharField(max_length = 100) brand = models.ForeignKey(Brand, on_delete = models.CASCADE) image = models.ImageField(null = False, blank = False, upload_to =&quot;images/&quot;,) price = models.DecimalField(max_digits = 100, decimal_places = 2, ) created = models.DateTimeField(auto_now_add = True ) </code></pre> <p><strong>the functions in the views.py</strong></p> <pre><code>def all_products(request): products = Product.objects.all() return render(request, 'store/home.html', {'products': products}) def newest_products(request): sixNewestProduct = Product.objects.all().order_by('-created')[:6] return render(request, 'store/home.html', {'sixNewestProduct': sixNewestProduct}) </code></pre> <p><strong>urls.py</strong></p> <pre><code>from django.urls import path from . import views urlpatterns = [ path('', views.all_products, name= 'all_products'), path('', views.newest_products, name= 'newest_products'), path('', views.newest_discount, name= 'newest_discount'), ] </code></pre> <p><strong>the template part look like this:</strong></p> <pre><code> {% for new in sixNewestProduct %} &lt;a href=&quot;#&quot; class=&quot;&quot;&gt; &lt;div class=&quot;newProduct&quot;&gt; &lt;img src=&quot;{{new.image.url}}&quot; alt=&quot;&quot;&gt; &lt;/div&gt; &lt;h5&gt;{{new.brand.name}}&lt;/h5&gt; &lt;h4&gt;{{new.title}}&lt;/h4&gt; &lt;p&gt;{{new.price}} GNF&lt;/p&gt; &lt;/a&gt; {% endfor %} </code></pre>
[ { "answer_id": 74413860, "author": "Mahammadhusain kadiwala", "author_id": 19205926, "author_profile": "https://Stackoverflow.com/users/19205926", "pm_score": 2, "selected": true, "text": "from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.all_products, name= 'all_products'), \n path('newest_products/', views.newest_products, name= 'newest_products'), \n path('newest_discount/', views.newest_discount, name= 'newest_discount'), \n]\n" }, { "answer_id": 74413884, "author": "Zkh", "author_id": 19235697, "author_profile": "https://Stackoverflow.com/users/19235697", "pm_score": 0, "selected": false, "text": "from django.urls import path\nfrom . import views\n\nurlpatterns = [\n # Django will always match this '' to the view `all_products`\n path('', views.all_products, name= 'all_products'), \n path('newest_products/', views.newest_products, name= 'newest_products'), \n path('newest_discount/', views.newest_discount, name= 'newest_discount'), \n]\n\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20486026/" ]
74,413,793
<p>Is there any data types of nothing available in javascript? I mean like not the null or undefined or 'empty string' but pure nothing. For example, i want to print a variable to console; <code>console.log(variable)</code> it should prints nothing. Is there something like that? Because i needed in do operations in array. Like <code>[x === true ? &quot;Script&quot;: `!this should be nothing not empty string but nothing!`]</code> if i print that array i want to see just empty array not null or undefined in that array.</p>
[ { "answer_id": 74413830, "author": "Bergi", "author_id": 1048572, "author_profile": "https://Stackoverflow.com/users/1048572", "pm_score": 2, "selected": false, "text": "undefined" }, { "answer_id": 74413837, "author": "LeoDog896", "author_id": 7589775, "author_profile": "https://Stackoverflow.com/users/7589775", "pm_score": 2, "selected": true, "text": "undefined" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20127250/" ]
74,413,822
<p>On request 1, the values ​​(animal, celebrity, dev...) are extracted and saved in a variable to be used later. In request 2 I want to use these extracted values, but randomly.</p> <p>I'm not having success doing this.</p> <p><strong>URL where I extract the values ​​and save them in a variable:</strong> <a href="https://api.chucknorris.io/jokes/categories" rel="nofollow noreferrer">https://api.chucknorris.io/jokes/categories</a></p> <p><strong>URL where I want to use the values ​​randomly:</strong> <a href="https://api.chucknorris.io/jokes/random?category=%7Bcategory%7D" rel="nofollow noreferrer">https://api.chucknorris.io/jokes/random?category={category}</a></p> <p><strong>I extract the values ​​with json extractor and save in the &quot;category&quot; variable, this works very well.</strong></p> <p><a href="https://i.stack.imgur.com/T23OO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/T23OO.png" alt="category" /></a></p> <p><strong>I want to use the randomly extracted values ​​in the next call!</strong></p> <p><a href="https://i.stack.imgur.com/7j71F.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7j71F.png" alt="erro" /></a> <a href="https://i.stack.imgur.com/h15hJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/h15hJ.png" alt="erro2" /></a></p>
[ { "answer_id": 74413830, "author": "Bergi", "author_id": 1048572, "author_profile": "https://Stackoverflow.com/users/1048572", "pm_score": 2, "selected": false, "text": "undefined" }, { "answer_id": 74413837, "author": "LeoDog896", "author_id": 7589775, "author_profile": "https://Stackoverflow.com/users/7589775", "pm_score": 2, "selected": true, "text": "undefined" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3585595/" ]
74,413,825
<p>When I try to open the localhost I see ( <strong>Not Found</strong></p> <p><strong>The requested URL was not found on this server.</strong> ) and after checking the Apache(error.log) on xampp I found this message ( <strong><a href="http://www.example.com:443:0" rel="nofollow noreferrer">www.example.com:443:0</a> server certificate does NOT include an ID which matches the server name</strong> )</p> <p>at first, I made sure that the Apache server was actually running, after that, I looked for some answers, and <strong>kinsta.com</strong> recommended adding ( <strong>ServerName localhost: port number</strong> ) to <strong>httpd-ssl.conf</strong> file, but I still get the same error, I have changed the port number many times but still, have the same issue.</p> <p>this is my first time working with xampp and PHP, any ideas?</p>
[ { "answer_id": 74413830, "author": "Bergi", "author_id": 1048572, "author_profile": "https://Stackoverflow.com/users/1048572", "pm_score": 2, "selected": false, "text": "undefined" }, { "answer_id": 74413837, "author": "LeoDog896", "author_id": 7589775, "author_profile": "https://Stackoverflow.com/users/7589775", "pm_score": 2, "selected": true, "text": "undefined" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19175796/" ]
74,413,835
<p>I have got an array of objects where different objects has time slot, if there are consecutive time slot then I want to merge it as one and keep other the same and later the final result has to be sort as well, for better understanding please look at the input and output I want.</p> <p>Input:</p> <pre><code> const timeArray = [ { timeValue: &quot;10:00am-11:00am&quot; }, { timeValue: &quot;11:00am-12:00pm&quot; }, { timeValue: &quot;12:00pm-1:00pm&quot; }, { timeValue: &quot;3:00pm-4:00pm&quot; }, { timeValue: &quot;4:00pm-5:00pm&quot; }, { timeValue: &quot;5:00pm-6:00pm&quot; }, { timeValue: &quot;10:00pm-11:00pm&quot; }, { timeValue: &quot;7:00pm-8:00pm&quot; }, { timeValue: &quot;8:00pm-9:00pm&quot; } ]; </code></pre> <p>Output: I want</p> <pre><code> const new = [ { timeValue: &quot;10:00am-1:00pm&quot; }, { timeValue: &quot;3:00pm-6:00pm&quot; }, { timeValue: &quot;7:00pm-9:00pm&quot; }, { timeValue: &quot;10:00pm-11:00pm&quot; } ]; </code></pre> <p>What I did I just aligned the consecutive time slot I have trying from hours I got no clue, Please help I will be very thankful</p>
[ { "answer_id": 74467648, "author": "Calebe Navarro", "author_id": 16248086, "author_profile": "https://Stackoverflow.com/users/16248086", "pm_score": 1, "selected": false, "text": "const timeArray = [{\n timeValue: \"10:00am-11:00am\"\n },\n {\n timeValue: \"11:00am-12:00pm\"\n },\n {\n timeValue: \"12:00pm-1:00pm\"\n },\n\n {\n timeValue: \"3:00pm-4:00pm\"\n },\n {\n timeValue: \"4:00pm-5:00pm\"\n },\n {\n timeValue: \"5:00pm-6:00pm\"\n },\n {\n timeValue: \"10:00pm-11:00pm\"\n },\n {\n timeValue: \"7:00pm-8:00pm\"\n },\n {\n timeValue: \"8:00pm-9:00pm\"\n }\n];\n\nconst recursiveFunction = (timeArray, stop) => {\n if (!stop) {\n return timeArray;\n }\n const output = [];\n let isLastAdd = false;\n let isHaveSome = false;\n\n for (let i = 1; i < timeArray.length; i++) {\n\n const currentTimeValue = timeArray[i].timeValue;\n const arrayCurrent = currentTimeValue.split(\"-\");\n const currentFirTime = Number(arrayCurrent[0].split(\":\")[0]);\n const currentSecTime = Number(arrayCurrent[1].split(\":\")[0]);\n const currentSufixo = currentTimeValue.split(\"-\")[0].split(\":\")[1];\n\n\n const prevTimeValue = timeArray[i - 1].timeValue;\n const arrayPrev = prevTimeValue.split(\"-\");\n const prevFirTime = Number(arrayPrev[0].split(\":\")[0]);\n const prevSecTime = Number(arrayPrev[1].split(\":\")[0]);\n const prevSufixo = prevTimeValue.split(\"-\")[1].split(\":\")[1];\n\n\n\n if (prevSecTime === currentFirTime) {\n output.push({\n timeValue: `${prevFirTime}:${prevSufixo}-${currentSecTime}:${currentSufixo}`\n });\n i++;\n\n if (!(i < timeArray.length)) {\n isLastAdd = true;\n } else {\n isLastAdd = false;\n }\n isHaveSome = true;\n\n } else {\n output.push({\n timeValue: prevTimeValue\n });\n isLastAdd = false;\n }\n\n }\n if (!isLastAdd) {\n output.push(timeArray.at(-1));\n }\n return recursiveFunction(output, isHaveSome);\n}\n\nconst result = recursiveFunction(timeArray, true);\nconsole.log(result);\nresult.sort((a, b) => a.timeValue.split(\"-\")[1].split(\":\")[0] - b.timeValue.split(\"-\")[1].split(\":\")[0]);\nconsole.log(result);" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18966561/" ]
74,413,840
<p>So I've currently made a progress so far that I can get how many times letters (a-e-i-o-u) have been written in the sentence which was taken as an input. Also if there's any &quot;the&quot; in the sentence we should count them too. and at the end we should get something like this: e.g: input: <code>Why little Dora herself came crying loud</code> output:</p> <pre><code>a ** e **** i ** o ** u * zero (mentions how many times &quot;the&quot; was used) </code></pre> <p>I couldn't get to find how to put (*) as in times that letter was used in the sentence but I could just take them out as numbers.</p> <pre><code>allowed_chars = set(&quot;abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ &quot;) string = input() validation = set((string)) if validation.issubset(allowed_chars): pass else: print(&quot;error&quot;) a = &quot;a&quot; A = &quot;A&quot; e = &quot;e&quot; E = &quot;E&quot; i = &quot;i&quot; I = &quot;I&quot; o = &quot;o&quot; O = &quot;O&quot; u = &quot;u&quot; U = &quot;U&quot; acount = 0 ecount = 0 icount = 0 ocount = 0 ucount = 0 for v in string: if(v==a or v==A): acount = acount + 1 if (v==e or v==E): ecount = ecount + 1 if (v==i or v==I): icount = icount + 1 if (v==o or v==O): ocount = ocount + 1 if (v==u or v==U): ucount = ucount + 1 print(acount,ecount,icount,ocount,ucount) word = &quot;the&quot; words = string.split() thecount = 0 for w in words: if w == word: thecount += 1 print(thecount) </code></pre> <p>sample input for this code: <code>this is a test count the vowels and how many the Is in the sentence</code> output:</p> <pre><code>3 8 4 3 1 3 </code></pre> <p>I want to have them like this:</p> <pre><code>a *** e ******** i **** o *** u * 3 </code></pre> <p>(and if there was no &quot;the&quot; just print &quot;zero&quot;)</p>
[ { "answer_id": 74467648, "author": "Calebe Navarro", "author_id": 16248086, "author_profile": "https://Stackoverflow.com/users/16248086", "pm_score": 1, "selected": false, "text": "const timeArray = [{\n timeValue: \"10:00am-11:00am\"\n },\n {\n timeValue: \"11:00am-12:00pm\"\n },\n {\n timeValue: \"12:00pm-1:00pm\"\n },\n\n {\n timeValue: \"3:00pm-4:00pm\"\n },\n {\n timeValue: \"4:00pm-5:00pm\"\n },\n {\n timeValue: \"5:00pm-6:00pm\"\n },\n {\n timeValue: \"10:00pm-11:00pm\"\n },\n {\n timeValue: \"7:00pm-8:00pm\"\n },\n {\n timeValue: \"8:00pm-9:00pm\"\n }\n];\n\nconst recursiveFunction = (timeArray, stop) => {\n if (!stop) {\n return timeArray;\n }\n const output = [];\n let isLastAdd = false;\n let isHaveSome = false;\n\n for (let i = 1; i < timeArray.length; i++) {\n\n const currentTimeValue = timeArray[i].timeValue;\n const arrayCurrent = currentTimeValue.split(\"-\");\n const currentFirTime = Number(arrayCurrent[0].split(\":\")[0]);\n const currentSecTime = Number(arrayCurrent[1].split(\":\")[0]);\n const currentSufixo = currentTimeValue.split(\"-\")[0].split(\":\")[1];\n\n\n const prevTimeValue = timeArray[i - 1].timeValue;\n const arrayPrev = prevTimeValue.split(\"-\");\n const prevFirTime = Number(arrayPrev[0].split(\":\")[0]);\n const prevSecTime = Number(arrayPrev[1].split(\":\")[0]);\n const prevSufixo = prevTimeValue.split(\"-\")[1].split(\":\")[1];\n\n\n\n if (prevSecTime === currentFirTime) {\n output.push({\n timeValue: `${prevFirTime}:${prevSufixo}-${currentSecTime}:${currentSufixo}`\n });\n i++;\n\n if (!(i < timeArray.length)) {\n isLastAdd = true;\n } else {\n isLastAdd = false;\n }\n isHaveSome = true;\n\n } else {\n output.push({\n timeValue: prevTimeValue\n });\n isLastAdd = false;\n }\n\n }\n if (!isLastAdd) {\n output.push(timeArray.at(-1));\n }\n return recursiveFunction(output, isHaveSome);\n}\n\nconst result = recursiveFunction(timeArray, true);\nconsole.log(result);\nresult.sort((a, b) => a.timeValue.split(\"-\")[1].split(\":\")[0] - b.timeValue.split(\"-\")[1].split(\":\")[0]);\nconsole.log(result);" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20483700/" ]
74,413,851
<pre><code> </code></pre> <pre><code> &quot;current&quot;: { &quot;observation_time&quot;: &quot;03:38 PM&quot;, &quot;temperature&quot;: 18, &quot;weather_code&quot;: 113, &quot;weather_icons&quot;: [ &quot;https://assets.weatherstack.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png&quot; ], &quot;weather_descriptions&quot;: [ &quot;Sunny&quot; ], &quot;wind_speed&quot;: 0, &quot;wind_degree&quot;: 345, &quot;wind_dir&quot;: &quot;NNW&quot;, &quot;pressure&quot;: 1011, &quot;precip&quot;: 0, &quot;humidity&quot;: 58, &quot;cloudcover&quot;: 0, &quot;feelslike&quot;: 18, &quot;uv_index&quot;: 5, &quot;visibility&quot;: 16 }, &quot;forecast&quot;: { &quot;2019-09-07&quot;: { &quot;date&quot;: &quot;2019-09-07&quot;, &quot;date_epoch&quot;: 1567814400, &quot;astro&quot;: { &quot;sunrise&quot;: &quot;06:28 AM&quot;, &quot;sunset&quot;: &quot;07:19 PM&quot;, &quot;moonrise&quot;: &quot;03:33 PM&quot;, &quot;moonset&quot;: &quot;12:17 AM&quot;, &quot;moon_phase&quot;: &quot;First Quarter&quot;, &quot;moon_illumination&quot;: 54 }, &quot;mintemp&quot;: 17, &quot;maxtemp&quot;: 25, &quot;avgtemp&quot;: 21, &quot;totalsnow&quot;: 0, &quot;sunhour&quot;: 10.3, &quot;uv_index&quot;: 5, &lt;!-- end snippet --&gt; </code></pre> <p>I want to display sunrise and sunset and also the sunhour under the forecast object, So far i have tried {forecast[&quot;2019-09-07&quot;].astro.sunrise} but it's still not working, Please what how else do i call it from the api?? Thanks in advance.</p>
[ { "answer_id": 74467648, "author": "Calebe Navarro", "author_id": 16248086, "author_profile": "https://Stackoverflow.com/users/16248086", "pm_score": 1, "selected": false, "text": "const timeArray = [{\n timeValue: \"10:00am-11:00am\"\n },\n {\n timeValue: \"11:00am-12:00pm\"\n },\n {\n timeValue: \"12:00pm-1:00pm\"\n },\n\n {\n timeValue: \"3:00pm-4:00pm\"\n },\n {\n timeValue: \"4:00pm-5:00pm\"\n },\n {\n timeValue: \"5:00pm-6:00pm\"\n },\n {\n timeValue: \"10:00pm-11:00pm\"\n },\n {\n timeValue: \"7:00pm-8:00pm\"\n },\n {\n timeValue: \"8:00pm-9:00pm\"\n }\n];\n\nconst recursiveFunction = (timeArray, stop) => {\n if (!stop) {\n return timeArray;\n }\n const output = [];\n let isLastAdd = false;\n let isHaveSome = false;\n\n for (let i = 1; i < timeArray.length; i++) {\n\n const currentTimeValue = timeArray[i].timeValue;\n const arrayCurrent = currentTimeValue.split(\"-\");\n const currentFirTime = Number(arrayCurrent[0].split(\":\")[0]);\n const currentSecTime = Number(arrayCurrent[1].split(\":\")[0]);\n const currentSufixo = currentTimeValue.split(\"-\")[0].split(\":\")[1];\n\n\n const prevTimeValue = timeArray[i - 1].timeValue;\n const arrayPrev = prevTimeValue.split(\"-\");\n const prevFirTime = Number(arrayPrev[0].split(\":\")[0]);\n const prevSecTime = Number(arrayPrev[1].split(\":\")[0]);\n const prevSufixo = prevTimeValue.split(\"-\")[1].split(\":\")[1];\n\n\n\n if (prevSecTime === currentFirTime) {\n output.push({\n timeValue: `${prevFirTime}:${prevSufixo}-${currentSecTime}:${currentSufixo}`\n });\n i++;\n\n if (!(i < timeArray.length)) {\n isLastAdd = true;\n } else {\n isLastAdd = false;\n }\n isHaveSome = true;\n\n } else {\n output.push({\n timeValue: prevTimeValue\n });\n isLastAdd = false;\n }\n\n }\n if (!isLastAdd) {\n output.push(timeArray.at(-1));\n }\n return recursiveFunction(output, isHaveSome);\n}\n\nconst result = recursiveFunction(timeArray, true);\nconsole.log(result);\nresult.sort((a, b) => a.timeValue.split(\"-\")[1].split(\":\")[0] - b.timeValue.split(\"-\")[1].split(\":\")[0]);\nconsole.log(result);" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19343185/" ]
74,413,865
<pre><code>def vowels(list): res = [] for word in list: vowel_n = 0 for x in word: if x in 'aeiou': vowel_n+=1 if vowel_n== 2: res.append(word) return res print(vowels(['tragedy', 'proof', 'dog', 'bug', 'blastoderm'])) </code></pre> <blockquote> <p>Result: ['tragedy']</p> </blockquote> <p>I'm expecting to show all characters that only have 2 vowels</p>
[ { "answer_id": 74413931, "author": "Harun Yilmaz", "author_id": 1331040, "author_profile": "https://Stackoverflow.com/users/1331040", "pm_score": 1, "selected": true, "text": "if vowel_n== 2:" }, { "answer_id": 74413981, "author": "Cobra", "author_id": 17580381, "author_profile": "https://Stackoverflow.com/users/17580381", "pm_score": 2, "selected": false, "text": "VSET = {'a', 'e', 'i', 'o', 'u'}\n\ndef vowels(lst):\n res = []\n for word in map(str.lower, lst):\n if sum(c in VSET for c in word) == 2:\n res.append(word)\n return res\n\nprint(vowels(['tragedy', 'proof', 'dog', 'bug', 'blastoderm']))\n" }, { "answer_id": 74414094, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 0, "selected": false, "text": "[letter for letter in word if letter in \"aeiou\"]" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20486342/" ]
74,413,867
<p>I would like to iterate over a html collection return by the getElementByClassName function. I would like to use the setAttribute method to add &quot;table-info&quot; to the class attribute of the elements within the collection.</p> <p>My problem is that not all elements are modified, to be specific, only the 1st element of the collection does not change its class. It is especially confusing for me that if I hardcode the for-loop, the result I wanted is still not achieved. <a href="https://i.stack.imgur.com/uWYFT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uWYFT.png" alt="enter image description here" /></a></p> <pre><code></code></pre> <pre><code>&lt;head&gt; &lt;meta charset=&quot;utf-8&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;initial-scale=1, width=device-width&quot;&gt; &lt;link crossorigin=&quot;anonymous&quot; href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css&quot; integrity=&quot;sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3&quot; rel=&quot;stylesheet&quot;&gt; &lt;script crossorigin=&quot;anonymous&quot; src=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js&quot; integrity=&quot;sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p&quot;&gt;&lt;/script&gt; &lt;link href=&quot;/static/favicon.ico&quot; rel=&quot;icon&quot;&gt; &lt;link href=&quot;/static/styles.css&quot; rel=&quot;stylesheet&quot;&gt; &lt;title&gt;Country comparison: {% block title %}{% endblock %}&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div&gt; &lt;table class=&quot;table&quot;&gt; &lt;tbody&gt; &lt;thead&gt; &lt;th&gt;Country&lt;/th&gt; &lt;th&gt;Currency&lt;/th&gt; &lt;th&gt;GDP&lt;/th&gt; &lt;th class=&quot;bar&quot;&gt;Unenployment Rate&lt;/th&gt; &lt;th class=&quot;bar&quot;&gt;Inflation Rate&lt;/th&gt; &lt;th class=&quot;bar&quot;&gt;Interest Rate&lt;/th&gt; &lt;th&gt;Balance of Trade&lt;/th&gt; &lt;th&gt;Consumer Confidence&lt;/th&gt; &lt;script&gt; myFunction() function myFunction() { const foo = document.getElementsByClassName(&quot;bar&quot;) foo[0].setAttribute(&quot;class&quot;, &quot;table-info&quot;); foo[1].setAttribute(&quot;class&quot;, &quot;table-info&quot;); foo[2].setAttribute(&quot;class&quot;, &quot;table-info&quot;); } &lt;/script&gt; &lt;/thead&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;/body&gt; </code></pre> <pre><code></code></pre> <p>I tried querySelectorAll() without success and also tried moving the script tag to other locations in without success.</p> <p>My goal is to have the elements of the table receive their class before the page loads because Bootstrap will then color the fields of my table successfully.</p>
[ { "answer_id": 74414022, "author": "James", "author_id": 535480, "author_profile": "https://Stackoverflow.com/users/535480", "pm_score": 1, "selected": false, "text": "bar" }, { "answer_id": 74414033, "author": "Moudi", "author_id": 16402009, "author_profile": "https://Stackoverflow.com/users/16402009", "pm_score": 0, "selected": false, "text": "<script>\n function myFunction() {\n var bars = document.querySelectorAll(\".bar\");\n for (var i = 0; i < bars.length; i++) {\n bars[i].className = \"table-info\";\n }\n }\n myFunction()\n </script>\n" }, { "answer_id": 74414134, "author": "Kurohige", "author_id": 2314347, "author_profile": "https://Stackoverflow.com/users/2314347", "pm_score": 1, "selected": false, "text": "myFunction()\nfunction myFunction() {\n const foo = document.getElementsByClassName(\"bar\")\n foo[0].setAttribute(\"class\", \"bar table-info\");\n foo[1].setAttribute(\"class\", \"bar table-info\");\n foo[2].setAttribute(\"class\", \"bar table-info\");\n}\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20357950/" ]
74,413,875
<p>I'm trying to fetch from a table on another sheet, the IDs that have 2 values in common.</p> <p>At tab <code>Base</code>&quot; I have <code>Name</code> and <code>Date</code>, and would like to have on <code>Lookup</code> the <code>ID</code>'s from tab <code>To be fetched</code> that match both <code>Name</code> and <code>Date</code>. Marked in green are the matching values I'm talking about.</p> <p><a href="https://i.stack.imgur.com/gBktq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gBktq.png" alt="Tab Base" /></a></p> <p>This is in tab <code>To be fetched</code> <a href="https://i.stack.imgur.com/9XaNi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9XaNi.png" alt="Tab To be fetched" /></a></p> <p>I was trying with this formula but it's not working. Even if it would, I think it would probably retrieve the 1st match, not all matches but it was a start, I guess.</p> <pre><code>=ArrayFormula(VLOOKUP($A$2:$A&quot; &quot;&amp;$B$2:$B,{'To be fetched'!$A$2:$A&amp;&quot; &quot;&amp;'To be fetched'!$C$2:$C,'To be fetched'!$D$2:$D},3,false)) </code></pre> <p>But I don't know nor why doesn't it work at all nor how to fully achieve the intended result.</p> <p><a href="https://docs.google.com/spreadsheets/d/1Y9iciU_aoM7KW5ywqZ_oQQ0XfdHB1nmmKewzxUIEfVM/edit#gid=0" rel="nofollow noreferrer">This</a> is the example google sheet.</p>
[ { "answer_id": 74414181, "author": "doubleunary", "author_id": 13045193, "author_profile": "https://Stackoverflow.com/users/13045193", "pm_score": 1, "selected": false, "text": "filter()" }, { "answer_id": 74415351, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 3, "selected": true, "text": "=IFERROR(BYROW(A2:INDEX(A2:A, COUNTA(A2:A)), \n LAMBDA(x, TEXTJOIN(\", \", 1, FILTER('To be fetched'!D:D, \n 'To be fetched'!C:C=OFFSET(x,,1), 'To be fetched'!A:A=x)))))\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11886740/" ]
74,413,924
<p>I have a data like this:</p> <pre class="lang-js prettyprint-override"><code>[ { id: &quot;1&quot;, parent: null }, { id: &quot;2&quot;, parent: null }, { id: &quot;3&quot;, parent: &quot;1&quot; }, { id: &quot;4&quot;, parent: &quot;3&quot; }, ] </code></pre> <p>And I want to convert it to a tree with a specific maximum depth. There are a few ways to convert an array to a tree, for example <a href="https://www.npmjs.com/package/performant-array-to-tree" rel="nofollow noreferrer">this package</a> but the problem is they go all the way trough and create a deeply nested tree:</p> <pre class="lang-js prettyprint-override"><code>[ { data: { id: &quot;1&quot;, parent: null }, children: [ { data: { id: &quot;3&quot;, parent: &quot;1&quot; } children: [ { id: &quot;4&quot;, parent: &quot;3&quot; } ] } ] }, { data: { id: &quot;2&quot;, parent: null } } ] </code></pre> <p>I don't want the depth of the tree be more than a specific amount, let say 1:</p> <pre class="lang-js prettyprint-override"><code>[ { data: { id: &quot;1&quot;, parent: null }, children: [ { data: { id: &quot;3&quot;, parent: &quot;1&quot; } }, { data: { id: &quot;4&quot;, parent: &quot;3&quot; } } ] }, { data: { id: &quot;2&quot;, parent: null } } ] </code></pre> <p>One way is to first create the deeply nested object and then flatten the parts that I don't want to be nested, but it might change the order of items + it's inefficient. I've had a couple of tries to create an algorithm myself but I'm not generally good at these type of stuff. I would appreciate some help. Idea, example, anything could be useful.</p>
[ { "answer_id": 74414300, "author": "Robby Cornelissen", "author_id": 3558960, "author_profile": "https://Stackoverflow.com/users/3558960", "pm_score": 2, "selected": true, "text": "const treeify = (nodes, depth) => {\n const index = Object.fromEntries(\n nodes.map(node => [node.id, { ...node }])\n );\n const ancestry = function*(id) {\n if (id) {\n yield id;\n yield* ancestry(index[id].parent);\n }\n }\n \n nodes.forEach(node => {\n const [ancestor] = [...ancestry(node.parent)].slice(-depth);\n \n if (ancestor) {\n index[ancestor].children = index[ancestor].children || [];\n index[ancestor].children.push(index[node.id]);\n }\n });\n \n return Object.values(index).filter(node => !node.parent);\n}\n\nconst data = [\n { id: \"1\", parent: null }, { id: \"2\", parent: null},\n { id: \"3\", parent: \"1\" }, { id: \"4\", parent: \"3\" }\n];\n\nconsole.log(treeify(data, 1));" }, { "answer_id": 74414568, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 0, "selected": false, "text": "const d = [{id:\"1\",parent:null},{id:\"2\",parent:null},\n {id:\"3\",parent:\"1\"},{id:\"4\",parent:\"3\"}];\n\nconst f = (depth, p=null) => d.filter(i => i.parent===p).map(i => depth>0 ?\n {data:i, children: f(depth-1, i.id)} : [{data:i}, ...f(0,i.id).flat()]);\n\nconsole.log(f(1));" }, { "answer_id": 74414886, "author": "trincot", "author_id": 5459839, "author_profile": "https://Stackoverflow.com/users/5459839", "pm_score": 0, "selected": false, "text": "find" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16225339/" ]
74,413,926
<p>I am looking for a way to make <code>split(A, B, L)</code> to exhaustively enumerate a B-elements list L such that sum of L's elements equals to A.</p> <h3>Example</h3> <pre><code>?- split(s(s(s(s(0)))), s(s(s(0))), L) % splitting 3 to 4 natural numbers L = [0, 0, 0, s(s(s(0)))]; L = [0, 0, s(0), s(s(0))]; L = [0, 0, s(s(0)), s(0)]; L = [0, 0, s(s(s(0))), 0]; ... L = [s(0), 0, 0, s(s(0))]; ... L = [s(s(s(0))), 0, 0, 0]; false. </code></pre> <p>My idea was to extend a list from smaller ones; for example, if <code>split(3, B, [e1, e2, e3])</code> is true, <code>split(4, B+a, [a, e1, e2, e3])</code> is also true (the inline code is not accurate; I used to convey my idea).</p> <p>Thus I wrote a code as follows.</p> <pre><code>split(0, 0, []). split(s(0), B, [B]). split(s(A), X, [Y|L]) :- split(A, B, L), add(Y, B, X). </code></pre> <p>Where</p> <pre><code>add(0, B, B). add(s(A), B, s(C)) :- add(A, B, C). </code></pre> <p>However, when I run this code, the program doesn't stop and fails.<br /> How should I fix it? Any advices would help.</p>
[ { "answer_id": 74414300, "author": "Robby Cornelissen", "author_id": 3558960, "author_profile": "https://Stackoverflow.com/users/3558960", "pm_score": 2, "selected": true, "text": "const treeify = (nodes, depth) => {\n const index = Object.fromEntries(\n nodes.map(node => [node.id, { ...node }])\n );\n const ancestry = function*(id) {\n if (id) {\n yield id;\n yield* ancestry(index[id].parent);\n }\n }\n \n nodes.forEach(node => {\n const [ancestor] = [...ancestry(node.parent)].slice(-depth);\n \n if (ancestor) {\n index[ancestor].children = index[ancestor].children || [];\n index[ancestor].children.push(index[node.id]);\n }\n });\n \n return Object.values(index).filter(node => !node.parent);\n}\n\nconst data = [\n { id: \"1\", parent: null }, { id: \"2\", parent: null},\n { id: \"3\", parent: \"1\" }, { id: \"4\", parent: \"3\" }\n];\n\nconsole.log(treeify(data, 1));" }, { "answer_id": 74414568, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 0, "selected": false, "text": "const d = [{id:\"1\",parent:null},{id:\"2\",parent:null},\n {id:\"3\",parent:\"1\"},{id:\"4\",parent:\"3\"}];\n\nconst f = (depth, p=null) => d.filter(i => i.parent===p).map(i => depth>0 ?\n {data:i, children: f(depth-1, i.id)} : [{data:i}, ...f(0,i.id).flat()]);\n\nconsole.log(f(1));" }, { "answer_id": 74414886, "author": "trincot", "author_id": 5459839, "author_profile": "https://Stackoverflow.com/users/5459839", "pm_score": 0, "selected": false, "text": "find" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20484227/" ]
74,413,954
<p>I want to print out only the value without any brackets or commas or parenthesis. I am using MySQL with python with mysql.connector.</p> <p>When I run this code I get &quot;('esrvgf',)&quot;. But I want to just get &quot;esrvg&quot;.</p> <p><a href="https://i.stack.imgur.com/SsD8d.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SsD8d.png" alt="enter image description here" /></a></p> <pre><code>import mysql.connector mydb = mysql.connector.connect( host=&quot;localhost&quot;, user=&quot;root&quot;, password=&quot;password&quot;, database =&quot;mydatabase&quot; ) cursor = mydb.cursor() sql = &quot;select nick from users where ipaddress = '192.168.1.4'&quot; cursor.execute(sql) myresult = cursor.fetchall() for x in myresult: print(x) </code></pre>
[ { "answer_id": 74413967, "author": "Michael M.", "author_id": 13376511, "author_profile": "https://Stackoverflow.com/users/13376511", "pm_score": 2, "selected": true, "text": "cursor.fetchall()" }, { "answer_id": 74413984, "author": "Celius Stingher", "author_id": 11897007, "author_profile": "https://Stackoverflow.com/users/11897007", "pm_score": 0, "selected": false, "text": "for x in myresult:\n for y in x:\n print(x)\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15179155/" ]
74,413,957
<p>I'm trying to find a regex to match the questions in a PDF textbook. The questions take the following structure:</p> <pre class="lang-none prettyprint-override"><code>1. What does cabotage refer to? a. Domestic air services within a state b. An international air carrier c. A flight above territorial waters d. Crop spraying 2. The Convention signed by the states relating to damage caused by foreign aircraft to persons and property on the ground is: a. the Tokyo convention b. the Rome convention c. the Warsaw convention d. the Paris convention. </code></pre> <p>I've tried modifying the one given here <a href="https://stackoverflow.com/questions/17351337/using-regular-expression-to-match-multiple-choice">Using Regular expression to match Multiple choice?</a> but I cannot get it to work across the newline character. Closest I got was <code>\(\d+\.[^\n+]+\n(?:[ \t]*[a-zA-Z]\.[^\n]+\n)+[\s]*)\</code> which works but not for multi-line questions.</p>
[ { "answer_id": 74414107, "author": "Poul Bak", "author_id": 5741643, "author_profile": "https://Stackoverflow.com/users/5741643", "pm_score": 1, "selected": false, "text": "?" }, { "answer_id": 74414182, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 3, "selected": true, "text": "[ \\t]*[a-zA-Z]\\." }, { "answer_id": 74414353, "author": "Basant Khatiyan", "author_id": 12623421, "author_profile": "https://Stackoverflow.com/users/12623421", "pm_score": 2, "selected": false, "text": "/(\\d+\\.)((.*\\n)(?!\\d+\\.).*)*/g\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13491619/" ]
74,413,978
<p>I've the following data frame (df).</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>GovKeepSecure</th> <th>BankKeepSecure</th> <th>OtherKeepSecure</th> <th>Secure</th> </tr> </thead> <tbody> <tr> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> </tr> <tr> <td>No</td> <td>No</td> <td>Yes</td> <td>No</td> </tr> <tr> <td>No</td> <td>Neutral</td> <td>Yes</td> <td>Neutral</td> </tr> </tbody> </table> </div> <p>I'm looking to write a python function that evaluates the first 3 columns, and returns the value that occurs more than 2 times in the &quot;Secure&quot;/4th column.</p> <p>For example, if there's 2 or more of &quot;No&quot;s in the first 3 columns (in the same row), than the value in the &quot;Secure&quot; column results in &quot;No.&quot; If such a condition isn't fulfilled, then the &quot;Secure&quot; column defaults to &quot;Neutral.&quot;</p> <p>I was wondering how we'd go about creating such a function.</p> <p>Here's the approach I'm trying to develop.</p> <pre><code>import pandas as pd def secure(row): if row[&quot;GovKeepSecure&quot;, &quot;BankKeepSecure&quot;, OtherKeepSecure] == [&quot;Yes&quot;, &quot;Yes&quot;, &quot;Yes&quot;]: return &quot;Yes&quot; if row[&quot;GovKeepSecure&quot;, &quot;BankKeepSecure&quot;, OtherKeepSecure] == [&quot;Yes&quot;, &quot;Yes&quot;, &quot;No&quot;]: return &quot;Yes&quot; -------------------------------------------------------------------------------------(etc.) df[&quot;Secure&quot;] = df.apply(lambda row: secure(row), axis=1) </code></pre> <p>Do let me know if there's a better way. Thanks so much!</p>
[ { "answer_id": 74414107, "author": "Poul Bak", "author_id": 5741643, "author_profile": "https://Stackoverflow.com/users/5741643", "pm_score": 1, "selected": false, "text": "?" }, { "answer_id": 74414182, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 3, "selected": true, "text": "[ \\t]*[a-zA-Z]\\." }, { "answer_id": 74414353, "author": "Basant Khatiyan", "author_id": 12623421, "author_profile": "https://Stackoverflow.com/users/12623421", "pm_score": 2, "selected": false, "text": "/(\\d+\\.)((.*\\n)(?!\\d+\\.).*)*/g\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74413978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19973686/" ]
74,414,001
<p>Consider i have a list of lists like below</p> <pre><code>mylist = [(1, &quot;Laprovitola&quot;, &quot;Italy&quot;)] </code></pre> <p>Imagine i have 1000 sublists. I'd like to make a format of</p> <pre><code> mydict = [{ &quot;ID&quot;: &quot;1&quot;, &quot;Name&quot;: &quot;Laprovitola&quot;, &quot;CountryOfResidence&quot;: &quot;Italy&quot;} ] </code></pre> <p>etc... The dict should have 8 values in total ID name country and more. any solution on this?</p> <p>I have tried the previous solution but have not worked on my hard-coded Dict.</p>
[ { "answer_id": 74414107, "author": "Poul Bak", "author_id": 5741643, "author_profile": "https://Stackoverflow.com/users/5741643", "pm_score": 1, "selected": false, "text": "?" }, { "answer_id": 74414182, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 3, "selected": true, "text": "[ \\t]*[a-zA-Z]\\." }, { "answer_id": 74414353, "author": "Basant Khatiyan", "author_id": 12623421, "author_profile": "https://Stackoverflow.com/users/12623421", "pm_score": 2, "selected": false, "text": "/(\\d+\\.)((.*\\n)(?!\\d+\\.).*)*/g\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14762650/" ]
74,414,003
<p>I have a dataframe with two columns called df['job_title'], df['job_industry_category'], I have a dictonary_of_jobs where there's for every job_title appended a value that's a list of every job category where the job title appears, as follows:</p> <pre><code>dictonary_of_jobs = {'Tax Accountant' : ['Health', 'Financial Services', 'Property', 'IT'], 'Office Assistant': ['Financial Services', 'Property', 'Manufacturing']} data = [['Tax Accountant', np.nan], ['Office Assistant', np.nan], ['Tax Accountant', np.nan]] df = pd.DataFrame(data, columns=['job_title', 'job_category']) </code></pre> <p>I would like to choose randomly a job category from dictonary and replace that value in my dataframe, where df['job_industry_category'] all consists of Nan values, but nothing's changed. I tried the .replace method and .at method, Why is that?</p> <pre><code>for w,z in zip(df['job_title'], df['job_industry_category']): for x,y in dictonary_of_jobs.items(): if w == x: #df.at[z,'job_category'] = random.choice(y) df['job_title'].replace(z, random.choice(y)) </code></pre> <p>I expected to have a value from dictonary, but nothing happened.</p>
[ { "answer_id": 74414107, "author": "Poul Bak", "author_id": 5741643, "author_profile": "https://Stackoverflow.com/users/5741643", "pm_score": 1, "selected": false, "text": "?" }, { "answer_id": 74414182, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 3, "selected": true, "text": "[ \\t]*[a-zA-Z]\\." }, { "answer_id": 74414353, "author": "Basant Khatiyan", "author_id": 12623421, "author_profile": "https://Stackoverflow.com/users/12623421", "pm_score": 2, "selected": false, "text": "/(\\d+\\.)((.*\\n)(?!\\d+\\.).*)*/g\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20486350/" ]
74,414,004
<p>I work with a database and I want to display it on the view. After debugging it seems that my model is empty. I created a similar project before where it worked fine but I don't find the problem in my code.</p> <p>How can I fix it?</p> <p>My class:</p> <pre><code>namespace Persons.Data { public class Person { public int Id { get; get; } [Required] public string LastName { get; set; } [Required] public string FirstName { get; set; } } } </code></pre> <p>DbContext:</p> <pre><code>namespace Persons.Data { public class ApplicationDbContext : DbContext { public ApplicationDbContext([NotNullAttribute] DbContextOptions options) : base(options) { } public DbSet&lt;Person&gt; Persons { get; set; } } } </code></pre> <p>Controller:</p> <pre><code>namespace Persons.Controllers { public class PeopleController : Controller { private readonly ApplicationDbContext _context; public PeopleController(ApplicationDbContext context) { _context = context; } // GET: People public async Task&lt;IActionResult&gt; Index() { return View(await _context.Persons.ToListAsync()); } } } </code></pre> <p>My view:</p> <pre><code>@model IEnumerable&lt;Persons.Data.Person&gt; @{ ViewData[&quot;Title&quot;] = &quot;Index&quot;; } @foreach (var item in Model) { &lt;tr&gt; &lt;td&gt; @Html.DisplayFor(modelItem =&gt; item.LastName) &lt;/td&gt; &lt;td&gt; @Html.DisplayFor(modelItem =&gt; item.FirstName) &lt;/td&gt; &lt;/tr&gt; } </code></pre>
[ { "answer_id": 74414107, "author": "Poul Bak", "author_id": 5741643, "author_profile": "https://Stackoverflow.com/users/5741643", "pm_score": 1, "selected": false, "text": "?" }, { "answer_id": 74414182, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 3, "selected": true, "text": "[ \\t]*[a-zA-Z]\\." }, { "answer_id": 74414353, "author": "Basant Khatiyan", "author_id": 12623421, "author_profile": "https://Stackoverflow.com/users/12623421", "pm_score": 2, "selected": false, "text": "/(\\d+\\.)((.*\\n)(?!\\d+\\.).*)*/g\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14344653/" ]
74,414,013
<p>I have dictionaries within a list like this:</p> <pre><code>[{'market': 'singapore', 'abbreviation': 'sg', 'indexId': 'STI', 'indexName': 'STRAITS TIMES INDEX'}, {'market': 'thailand', 'abbreviation': 'th', 'indexId': 'SET100', 'indexName': 'SET100 INDEX'}, {'market': 'turkey', 'abbreviation': 'tr', 'indexId': 'XUTEK', 'indexName': 'BIST TEKNOLOJI'}, {'market': 'thailand', 'abbreviation': 'th', 'indexId': 'SET50', 'indexName': 'SET50 INDEX'}] </code></pre> <p>The desired results should look like this</p> <pre><code>[{'market', 'singapore', 'abbreviation', 'sg', 'indexId', 'STI', 'indexName', 'STRAITS TIMES INDEX'}, {'market', 'thailand', 'abbreviation', 'th', 'indexId', 'SET100', 'indexName', 'SET100 INDEX'}, {'market', 'turkey', 'abbreviation', 'tr', 'indexId', 'XUTEK', 'indexName', 'BIST TEKNOLOJI'}, {'market', 'thailand', 'abbreviation': 'th', 'indexId', 'SET50', 'indexName', 'SET50 INDEX'}] </code></pre> <p>How can I possibly remove the &quot;:&quot; within this list of dictionaries? I know I can use the <code>re.sub()</code> function, but I don't know how to apply it in this scenario.</p>
[ { "answer_id": 74414079, "author": "Amir reza Riahi", "author_id": 12016688, "author_profile": "https://Stackoverflow.com/users/12016688", "pm_score": 0, "selected": false, "text": "dict" }, { "answer_id": 74414084, "author": "Michael M.", "author_id": 13376511, "author_profile": "https://Stackoverflow.com/users/13376511", "pm_score": 0, "selected": false, "text": "print()" }, { "answer_id": 74414158, "author": "S.B", "author_id": 13944524, "author_profile": "https://Stackoverflow.com/users/13944524", "pm_score": 2, "selected": false, "text": "re.sub()" }, { "answer_id": 74414211, "author": "Talha Tayyab", "author_id": 13086128, "author_profile": "https://Stackoverflow.com/users/13086128", "pm_score": 0, "selected": false, "text": "lst = [{'market': 'singapore', 'abbreviation': 'sg', 'indexId': 'STI', 'indexName': 'STRAITS TIMES INDEX'}, {'market': 'thailand', 'abbreviation': 'th', 'indexId': 'SET100', 'indexName': 'SET100 INDEX'}, {'market': 'turkey', 'abbreviation': 'tr', 'indexId': 'XUTEK', 'indexName': 'BIST TEKNOLOJI'}, {'market': 'thailand', 'abbreviation': 'th', 'indexId': 'SET50', 'indexName': 'SET50 INDEX'}]\n\nr = [{item for sublist in d.items() for item in sublist} for d in lst]\n\nprint(r)\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17899270/" ]
74,414,045
<p>I'm reasonably new to Kotlin and android as a whole. I'm trying to figure out a way to take input through an EditText and add it to an array by pressing a button to accept the values but I can't seem to figure it out. I have been trialing many options and nothing seems to work for me. Below I have pasted my current code. Any Help would be very appreciated because i'm stuck at the moment. Thanks in advance!</p> <pre><code>class MainActivity2 : AppCompatActivity() { private lateinit var addnumber: EditText private lateinit var storednumber: TextView private lateinit var output: TextView private lateinit var addbutton: Button private lateinit var clearbutton: Button private lateinit var averagebutton: Button private lateinit var minmaxbutton: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main2) storednumber = findViewById(R.id.stored_tv) output = findViewById(R.id.answer2_tv) addbutton = findViewById(R.id.addNum_btn) clearbutton = findViewById(R.id.clear_btn) averagebutton = findViewById(R.id.average_btn) minmaxbutton = findViewById(R.id.minMax_btn) addbutton.setOnClickListener { val ed = findViewById&lt;View&gt;(R.id.et_addNum) as EditText var text = ed.text.toString() val arr = IntArray(text!!.length / 2) //Assuming no spaces and user is using one comma between numbers var i = 0 while (text != null &amp;&amp; text.length &gt; 0) { arr[i] = text.substring(0, 1).toInt() text = text.substring(text.indexOf(&quot;,&quot;) + 1) i++ } } } } </code></pre>
[ { "answer_id": 74414079, "author": "Amir reza Riahi", "author_id": 12016688, "author_profile": "https://Stackoverflow.com/users/12016688", "pm_score": 0, "selected": false, "text": "dict" }, { "answer_id": 74414084, "author": "Michael M.", "author_id": 13376511, "author_profile": "https://Stackoverflow.com/users/13376511", "pm_score": 0, "selected": false, "text": "print()" }, { "answer_id": 74414158, "author": "S.B", "author_id": 13944524, "author_profile": "https://Stackoverflow.com/users/13944524", "pm_score": 2, "selected": false, "text": "re.sub()" }, { "answer_id": 74414211, "author": "Talha Tayyab", "author_id": 13086128, "author_profile": "https://Stackoverflow.com/users/13086128", "pm_score": 0, "selected": false, "text": "lst = [{'market': 'singapore', 'abbreviation': 'sg', 'indexId': 'STI', 'indexName': 'STRAITS TIMES INDEX'}, {'market': 'thailand', 'abbreviation': 'th', 'indexId': 'SET100', 'indexName': 'SET100 INDEX'}, {'market': 'turkey', 'abbreviation': 'tr', 'indexId': 'XUTEK', 'indexName': 'BIST TEKNOLOJI'}, {'market': 'thailand', 'abbreviation': 'th', 'indexId': 'SET50', 'indexName': 'SET50 INDEX'}]\n\nr = [{item for sublist in d.items() for item in sublist} for d in lst]\n\nprint(r)\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19506039/" ]
74,414,057
<p>I will try the share data using local storage. but I want to that shared data visible all that web page users.</p> <p>Mainly I was try to some variable upload the one html page local storage and I try to get that value another web page and I want to make condition in use that variable. But problem is I will use the local storage all details are visible only me. I want to visible that data in all users.</p>
[ { "answer_id": 74414199, "author": "Nusrat Jahan", "author_id": 20315115, "author_profile": "https://Stackoverflow.com/users/20315115", "pm_score": 0, "selected": false, "text": "https://test.com/hello?name=roger&age=20\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20486204/" ]
74,414,067
<p>I'm learning next and react, I'm creating a project. I created two components &quot;form.js&quot; and &quot;feedback.js&quot;, in the main page &quot;index.js&quot; I import &quot;form.js&quot;, but I would like that when you press the button to send the data to the db, the component &quot;form .js &quot;is replaced with the component&quot; feedback.js &quot;, what can I do? thank you</p> <p>file form.js:</p> <pre><code>import styles from '../styles/Home.module.css' export default function Form(){ return( &lt;&gt; &lt;form method='POST' action=&quot;&quot;&gt; &lt;label&gt;Name&lt;/label&gt; &lt;input type=&quot;text&quot; name=&quot;Name&quot; pattern=&quot;[A-Za-z]+&quot; title=&quot;Your name&quot;&gt;&lt;/input&gt; &lt;label&gt;Surname&lt;/label&gt; &lt;input type=&quot;text&quot; name=&quot;Surname&quot; pattern=&quot;[A-Za-z]+&quot; title=&quot;Your surname&quot;&gt;&lt;/input&gt; &lt;label&gt;Email&lt;/label&gt; &lt;input type=&quot;email&quot; name=&quot;email&quot; pattern=&quot;[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$&quot; &gt;&lt;/input&gt; &lt;button className={styles.btn} type=&quot;submit&quot;&gt;Send&lt;/button&gt; &lt;/form&gt; &lt;/&gt; ) } </code></pre> <p>file feedback.js:</p> <pre><code>import styles from '../styles/Home.module.css' export default function SuccesForm(){ return( &lt;&gt; &lt;h3&gt;Form sent successfully&lt;/h3&gt; &lt;/&gt; ) } </code></pre> <p>file index.js:</p> <pre><code>import Head from 'next/head' import Image from 'next/image' import styles from '../styles/Home.module.css' import Form from '../components/form' import Feedback from '../components/feedback' export default function Home({utenti}) { return ( &lt;&gt; &lt;header className={styles.header}&gt; &lt;a&gt;&lt;h1&gt;LOGO&lt;/h1&gt;&lt;/a&gt; &lt;/header&gt; &lt;div className={styles.hero}&gt; &lt;div className={styles.sectionSX}&gt; &lt;h3&gt;Hello&lt;/h3&gt; &lt;/div&gt; &lt;div className={styles.sectionDX}&gt; &lt;Form&gt;&lt;/Form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/&gt; ) } </code></pre>
[ { "answer_id": 74414199, "author": "Nusrat Jahan", "author_id": 20315115, "author_profile": "https://Stackoverflow.com/users/20315115", "pm_score": 0, "selected": false, "text": "https://test.com/hello?name=roger&age=20\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16593935/" ]
74,414,096
<p>WHAT IS WRONG IN THIS CODE? MY PC SHOWS NO OUTPUT WHEN C and D ARE LARGER NUMBERS?</p> <pre><code>a=int(input(&quot;ent a no.&quot;)) b=int(input(&quot;ent a no.&quot;)) c=int(input(&quot;ent a no.&quot;)) d=int(input(&quot;ent a no.&quot;)) if a&gt;b: if a&gt;c: if a&gt;d: print(&quot; a is greater&quot;) elif b&gt;a: if b&gt;c: if b&gt;d: print(&quot;b is greater&quot;) elif c&gt;a: if c&gt;b: if c&gt;d: print (&quot;c bada hai bc&quot;) else: print(&quot;d is greater&quot;) </code></pre> <p>This program shows output when A and B variables have larger number but do not show any output when D and C have larger numbers respectively?</p>
[ { "answer_id": 74414199, "author": "Nusrat Jahan", "author_id": 20315115, "author_profile": "https://Stackoverflow.com/users/20315115", "pm_score": 0, "selected": false, "text": "https://test.com/hello?name=roger&age=20\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19867111/" ]
74,414,149
<p>I have an array of numbers should return true if 2 adjacent numbers divide by 10.</p> <p>For now, my code return always <code>false</code>.</p> <p><em>My attempt:</em></p> <pre><code>public static boolean divideByTen(int arr[], int num) { int i = num - 1; if (i &gt; 0) { divideByTen(arr, num - 1); if (arr[i] + arr[i - 1] % 10 == 0) return true; } return false; } </code></pre>
[ { "answer_id": 74414199, "author": "Nusrat Jahan", "author_id": 20315115, "author_profile": "https://Stackoverflow.com/users/20315115", "pm_score": 0, "selected": false, "text": "https://test.com/hello?name=roger&age=20\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19213415/" ]
74,414,152
<p>So I tried to consume the API and I keep getting this error type '(dynamic) =&gt; Category' is not a subtype of type '(String, dynamic) =&gt; MapEntry&lt;dynamic, dynamic&gt;' of 'transform'</p> <p>This is my category model</p> <pre><code>import 'dart:convert'; List&lt;Category&gt; categoryFromJson(String str) =&gt; List&lt;Category&gt;.from(json.decode(str).map((x) =&gt; Category.fromJson(x))); // I get the error here String categoryToJson(List&lt;Category&gt; data) =&gt; json.encode(List&lt;dynamic&gt;.from(data.map((x) =&gt; x.toJson()))); class Category { Category({ required this.id, required this.name, required this.icon, }); int id; String name; String icon; factory Category.fromJson(Map&lt;String, dynamic&gt; json) =&gt; Category( id: json[&quot;id&quot;], name: json[&quot;name&quot;], icon: json[&quot;icon&quot;], ); Map&lt;String, dynamic&gt; toJson() =&gt; { &quot;id&quot;: id, &quot;name&quot;: name, &quot;icon&quot;: icon, }; } </code></pre> <p>This is my category repository. more like services</p> <pre><code>import 'package:elibrary/services/requests.dart'; import 'package:elibrary/services/endpoints.dart'; import 'package:get/get.dart'; class CategoryRepository extends GetxService { ApiClient apiClient = ApiClient(); Future&lt;Response&gt; getCategories() async { return await apiClient.getRequest(ProjectConstants.CATEGORY_URI); } } </code></pre> <p>This is the category controller</p> <pre><code>import 'dart:io'; import 'package:elibrary/model/categories.dart'; import 'package:elibrary/services/repository/category_repository.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; class CategoryController extends GetxController { CategoryRepository categoryRepository = CategoryRepository(); RxList&lt;Category&gt; categoryList = &lt;Category&gt;[].obs; RxBool isLoading = false.obs; @override void onInit() { super.onInit(); getCategoryList(); } Future&lt;void&gt; getCategoryList() async { isLoading(true); try { Response categoryResponse = await categoryRepository.getCategories(); if (categoryResponse.statusCode == 200) { categoryList.assignAll( categoryFromJson(categoryResponse.bodyString ?? ''), ); } else { debugPrint(categoryResponse.bodyString ?? ''); debugPrint( categoryResponse.statusText.toString(), ); } } on SocketException { GetSnackBar( message: &quot;No Internet Connectivity&quot;, duration: Duration(seconds: 5), ).show(); } catch (e) { debugPrint( e.toString(), ); } finally { isLoading(false); } } SnackbarController showErrorMessage( Response&lt;dynamic&gt; categoryResponse, String message) { return Get.snackbar( &quot;Error Occurred&quot;, categoryResponse.statusText.toString(), snackPosition: SnackPosition.BOTTOM, colorText: Colors.white, backgroundColor: Colors.red, ); } } </code></pre> <p>I tried to use for in loop by doing it this way</p> <p>by changing this</p> <pre><code>List&lt;Category&gt; categoryFromJson(String str) =&gt; List&lt;Category&gt;.from(json.decode(str).map((x) =&gt; Category.fromJson(x))); </code></pre> <p>to this</p> <pre><code>List&lt;Category&gt; categoryFromJson(String str) =&gt; [ for (Map&lt;String, dynamic&gt; x in json.decode(str)) Category.fromJson(x), ]; </code></pre> <p>But it give me this error</p> <pre><code>type '_InternalLinkedHashMap&lt;String, dynamic&gt;' is not a subtype of type 'Iterable&lt;dynamic&gt;' </code></pre> <p>I have read this <a href="https://stackoverflow.com/questions/63331381/unhandled-exception-type-dynamic-welcome-is-not-a-subtype-of-type-stri?rq=1">Unhandled Exception</a></p> <p>I have read this too <a href="https://stackoverflow.com/questions/71597717/exception-has-occurred-typeerrortype-dynamic-patient-is-not-a-subtype-of">Exception has occurred</a></p> <p>I have again this also <a href="https://stackoverflow.com/questions/70903869/flutter-typeerror-type-dynamic-categorys-is-not-a-subtype-of-type-str">flutter _TypeError</a></p>
[ { "answer_id": 74414238, "author": "Mahendra Raj", "author_id": 7053203, "author_profile": "https://Stackoverflow.com/users/7053203", "pm_score": 1, "selected": false, "text": "List<Category> categoryFromJson(String str) => List<Category>.from(json.decode(str).map((x) => Category.fromJson(x)));\n" }, { "answer_id": 74414293, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 3, "selected": true, "text": "List<Category> categoryFromJson(String str) => (json.decode(str)[\"data\"] as List<Map<String, dynamic>>).map((x) => Category.fromJson(x)).toList();\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11439544/" ]