qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,580,710
<p>In Dart, when two or more tasks are waiting on the same Future, when the Future completes, do the tasks get notified/run in the order that they did the await i.e. the first to do an await is the first to run.</p> <p>Is this code guaranteed to output 2</p> <pre><code>int res = 0; Future&lt;void&gt; foo1 () async { await Future.delayed(Duration(seconds: 2)); res = 2; } void main() async { await foo1(); print(res); } </code></pre> <p>and what about this code, slightly less obvious</p> <pre><code>int res = 0; Future&lt;void&gt; foo1 () async { await Future.delayed(Duration(seconds: 2)); } Future&lt;void&gt; foo2 (Future&lt;void&gt; f1) async { await f1; res = 2; } Future&lt;void&gt; foo3 (Future&lt;void&gt; f1) async { await f1; res = 3; } void main() async { res = 0; Future&lt;void&gt; f1 = foo1(); foo3(f1); foo2(f1); await f1; print(res); } </code></pre>
[ { "answer_id": 74580757, "author": "Ska Lee", "author_id": 14695961, "author_profile": "https://Stackoverflow.com/users/14695961", "pm_score": 0, "selected": false, "text": "int res = 0;\n\nFuture<void> foo1() async {\n await Future.delayed(const Duration(seconds: 2));\n print('foo1 method res 1: $res');\n res = 2;\n print('foo1 method res 2: $res');\n}\n\nvoid main() async {\n await foo1();\n print('last res: $res');\n}\n foo1 method res 1: 0\nfoo1 method res 2: 2\nlast res: 2\n" }, { "answer_id": 74582040, "author": "lrn", "author_id": 2156621, "author_profile": "https://Stackoverflow.com/users/2156621", "pm_score": 3, "selected": true, "text": "dart:async f1 2 3 0" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74580710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10818491/" ]
74,580,716
<p>My code is fine, but there is an outstanding exception.</p> <pre><code>#include &lt;iostream&gt; using namespace std; class Book { public: string title; string ISBN; double price; Book(string title_B, string ISBN_B, double price_B ) : title{title_B}, ISBN{ISBN_B}, price{price_B} {} void ShowBookInfo() { cout &lt;&lt; &quot;Title: &quot; &lt;&lt; title &lt;&lt; endl; cout &lt;&lt; &quot;ISBN: &quot; &lt;&lt; ISBN &lt;&lt; endl; cout &lt;&lt; &quot;Price(USD): &quot; &lt;&lt; price &lt;&lt; endl; } }; class EBook : public Book { public: string DRMKey; string format; EBook(string title_B, string ISBN_B, double price_B, string DRMKey_B, const string&amp; format_B = &quot;Kindle&quot;) : Book{ title , ISBN , price }, DRMKey{ DRMKey_B }, format{ format_B } {} void ShowEBookInfo() { cout &lt;&lt; &quot;Title: &quot; &lt;&lt; title &lt;&lt; endl; cout &lt;&lt; &quot;ISBN: &quot; &lt;&lt; ISBN &lt;&lt; endl; cout &lt;&lt; &quot;Price(USD): &quot; &lt;&lt; price &lt;&lt; endl; cout &lt;&lt; &quot;DRMKey: &quot; &lt;&lt; DRMKey &lt;&lt; endl; cout &lt;&lt; &quot;Format: &quot; &lt;&lt; format &lt;&lt; endl; } }; int main() { Book book(&quot;Modern C++ Programming Cookbook&quot;, &quot;1800208987&quot;, 49.99); book.ShowBookInfo(); cout &lt;&lt; endl; EBook ebook(&quot;Modern C++ Programming Cookbook(ebook)&quot;, &quot;1800208987&quot;, 34.99, &quot;dkb34x!@*~&quot;); ebook.ShowEBookInfo(); return 0; } </code></pre> <p>When the F10 shortcut key is used to execute code line by line. An error occurs when an unprocessed exception occurs in the &quot;EBookbook(~~);&quot; position. What's the problem?</p> <p><strong>Output</strong></p> <blockquote> <p>Title: Modern C++ Programming Cookbook<br /> ISBN: 1800208987<br /> Price(USD): 49.99</p> </blockquote> <p><strong>Expected</strong></p> <blockquote> <p>Title: Modern C++ Programming Cookbook<br /> ISBN: 1800208987<br /> Price(USD): 49.99<br /> Title: Modern C++ Programming Cookbook(ebook)<br /> ISBN: 1800208987<br /> Price(USD): 34.99<br /> DRMKey: dkb34x!@*~<br /> Format: Kindle</p> </blockquote>
[ { "answer_id": 74580757, "author": "Ska Lee", "author_id": 14695961, "author_profile": "https://Stackoverflow.com/users/14695961", "pm_score": 0, "selected": false, "text": "int res = 0;\n\nFuture<void> foo1() async {\n await Future.delayed(const Duration(seconds: 2));\n print('foo1 method res 1: $res');\n res = 2;\n print('foo1 method res 2: $res');\n}\n\nvoid main() async {\n await foo1();\n print('last res: $res');\n}\n foo1 method res 1: 0\nfoo1 method res 2: 2\nlast res: 2\n" }, { "answer_id": 74582040, "author": "lrn", "author_id": 2156621, "author_profile": "https://Stackoverflow.com/users/2156621", "pm_score": 3, "selected": true, "text": "dart:async f1 2 3 0" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74580716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
74,580,745
<p>I have a class with list of class members (variabls), each assigned to its own value.</p> <pre><code>class PacketType: HEARTBEAT = 0xF0 DEBUG = 0xFC ECHO = 0xFF @staticmethod def get_name(value): # Get variable name from value # Print the variable in string format return ??? </code></pre> <p>If I call <code>PacketType.get_name(0xF0)</code>, I'd like to get return as <code>&quot;HEARTBEAT&quot;</code>. Does python allow this, or is the only way to make list of <code>if-elif</code> for each possible value?</p>
[ { "answer_id": 74580784, "author": "Aiq0", "author_id": 19880397, "author_profile": "https://Stackoverflow.com/users/19880397", "pm_score": 1, "selected": false, "text": "class PacketType:\n packets = {\n 0xF0: 'HEARTHBEAT',\n 0XFC: 'DEBUG',\n 0XFF: 'ECHO'\n }\n\n @classmethod\n def get_name(cls, value):\n return cls.packets[value]\n" }, { "answer_id": 74580788, "author": "balderman", "author_id": 415016, "author_profile": "https://Stackoverflow.com/users/415016", "pm_score": 3, "selected": true, "text": "class PacketType:\n HEARTBEAT = 0xF0\n DEBUG = 0xFC\n ECHO = 0xFF\n\n @staticmethod\n def get_name(value):\n for k, v in PacketType.__dict__.items():\n if v == value:\n return k\n return None\n\n\nprint(PacketType.get_name(0xFF))\n ECHO\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74580745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3716664/" ]
74,580,747
<p>I have three lists as follows.</p> <p><code>A = [1, 2, 3]; B = [[3, 4, 5], [4, 5, 6], [4, 5, 7], [7, 4, 3]]; C = [[2, 3, 1], [2, 3, 3], [2, 4, 5], [4, 5, 6], [7, 3, 1]]</code></p> <p>I want to create another list containing all the above inner lists starting from A to C.</p> <p>Desired = [elements of A, elements of B, elements of C] just like this.</p> <p><code>Desired = [[1, 2, 3], [3, 4, 5], [4, 5, 6], [4, 5, 7], [7, 4, 3], [2, 3, 1], [2, 3, 3], [2, 4, 5], [4, 5, 6], [7, 3, 1]]</code></p>
[ { "answer_id": 74580932, "author": "ScottC", "author_id": 20174226, "author_profile": "https://Stackoverflow.com/users/20174226", "pm_score": 2, "selected": false, "text": "inner_list A = [1, 2, 3]; \nB = [[3, 4, 5], [4, 5, 6], [4, 5, 7], [7, 4, 3]]; \nC = [[2, 3, 1], [2, 3, 3], [2, 4, 5], [4, 5, 6], [7, 3, 1]]\n\ndesired = []\n\nfor outer_list in (A,B,C):\n list_state = False\n for inner_list in outer_list:\n if isinstance(inner_list, list):\n desired.append(inner_list)\n else:\n list_state = True\n \n # Add outer_list only if the inner_list was not a list\n if list_state:\n desired.append(outer_list)\n \nprint(desired)\n [[1, 2, 3], [3, 4, 5], [4, 5, 6], [4, 5, 7], [7, 4, 3], [2, 3, 1], [2, 3, 3], [2, 4, 5], [4, 5, 6], [7, 3, 1]]\n" }, { "answer_id": 74581297, "author": "Jethy11", "author_id": 20440485, "author_profile": "https://Stackoverflow.com/users/20440485", "pm_score": 1, "selected": false, "text": "A = [1, 2, 3]\nB = [[3, 4, 5], [4, 5, 6], [4, 5, 7], [7, 4, 3]]\nC = [[2, 3, 1], [2, 3, 3], [2, 4, 5], [4, 5, 6], [7, 3, 1]]\nlistt = [ 'A', 'B', 'C' ]\ndes = []\n\nfor i in listt:\n if type((globals()[i])[0]) != list:\n globals()[i] = [[i for i in globals()[i]]] #turns into nested list if not (line 7-9)\n\nfor i in (A,B,C):\n for x in i:\n des.append(x)\n\nprint(des)\n [[1, 2, 3], [3, 4, 5], [4, 5, 6], [4, 5, 7], [7, 4, 3], [2, 3, 1], [2, 3, 3], [2, 4, 5], [4, 5, 6], [7, 3, 1]]\n" }, { "answer_id": 74598441, "author": "Timus", "author_id": 14311263, "author_profile": "https://Stackoverflow.com/users/14311263", "pm_score": 3, "selected": true, "text": "B C A result = [A] + B + C\n result = [\n item\n for numbers in (A, B, C)\n for item in (numbers if isinstance(numbers[0], list) else [numbers])\n]\n itertools.groupby from itertools import groupby\n\nresult = []\nfor key, group in groupby(A + B + C, key=lambda item: isinstance(item, list)):\n if not key:\n group = [[*group]]\n result.extend(group)\n A B C [[1, 2, 3], [3, 4, 5], [4, 5, 6], [4, 5, 7], [7, 4, 3],\n [2, 3, 1], [2, 3, 3], [2, 4, 5], [4, 5, 6], [7, 3, 1]]\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74580747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16079133/" ]
74,580,752
<p>I'm using python3.8 and have a variable which can be <code>True</code>, <code>False</code> or <code>None</code>. For type-hinting this variable I know I can use <code>Union</code> for variables where they may have divergent types. But personally I don't prefer using <code>Union</code>. I think it's easier to use the newer python syntax <code>bool | None</code> but it's not available in <code>python3.8</code> (I think it's for 3.9 or 3.10). I want to know is it correct to use <code>bool or None</code> for this scenario? At first I thought it's wrong, because <code>bool or None</code> will be eventually executed and become <code>bool</code>.</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; bool or None &lt;class 'bool'&gt; </code></pre> <p>But pycharm's type checker didn't complain about it. Is this correct?</p>
[ { "answer_id": 74580932, "author": "ScottC", "author_id": 20174226, "author_profile": "https://Stackoverflow.com/users/20174226", "pm_score": 2, "selected": false, "text": "inner_list A = [1, 2, 3]; \nB = [[3, 4, 5], [4, 5, 6], [4, 5, 7], [7, 4, 3]]; \nC = [[2, 3, 1], [2, 3, 3], [2, 4, 5], [4, 5, 6], [7, 3, 1]]\n\ndesired = []\n\nfor outer_list in (A,B,C):\n list_state = False\n for inner_list in outer_list:\n if isinstance(inner_list, list):\n desired.append(inner_list)\n else:\n list_state = True\n \n # Add outer_list only if the inner_list was not a list\n if list_state:\n desired.append(outer_list)\n \nprint(desired)\n [[1, 2, 3], [3, 4, 5], [4, 5, 6], [4, 5, 7], [7, 4, 3], [2, 3, 1], [2, 3, 3], [2, 4, 5], [4, 5, 6], [7, 3, 1]]\n" }, { "answer_id": 74581297, "author": "Jethy11", "author_id": 20440485, "author_profile": "https://Stackoverflow.com/users/20440485", "pm_score": 1, "selected": false, "text": "A = [1, 2, 3]\nB = [[3, 4, 5], [4, 5, 6], [4, 5, 7], [7, 4, 3]]\nC = [[2, 3, 1], [2, 3, 3], [2, 4, 5], [4, 5, 6], [7, 3, 1]]\nlistt = [ 'A', 'B', 'C' ]\ndes = []\n\nfor i in listt:\n if type((globals()[i])[0]) != list:\n globals()[i] = [[i for i in globals()[i]]] #turns into nested list if not (line 7-9)\n\nfor i in (A,B,C):\n for x in i:\n des.append(x)\n\nprint(des)\n [[1, 2, 3], [3, 4, 5], [4, 5, 6], [4, 5, 7], [7, 4, 3], [2, 3, 1], [2, 3, 3], [2, 4, 5], [4, 5, 6], [7, 3, 1]]\n" }, { "answer_id": 74598441, "author": "Timus", "author_id": 14311263, "author_profile": "https://Stackoverflow.com/users/14311263", "pm_score": 3, "selected": true, "text": "B C A result = [A] + B + C\n result = [\n item\n for numbers in (A, B, C)\n for item in (numbers if isinstance(numbers[0], list) else [numbers])\n]\n itertools.groupby from itertools import groupby\n\nresult = []\nfor key, group in groupby(A + B + C, key=lambda item: isinstance(item, list)):\n if not key:\n group = [[*group]]\n result.extend(group)\n A B C [[1, 2, 3], [3, 4, 5], [4, 5, 6], [4, 5, 7], [7, 4, 3],\n [2, 3, 1], [2, 3, 3], [2, 4, 5], [4, 5, 6], [7, 3, 1]]\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74580752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12016688/" ]
74,580,787
<p>I am trying to update one table based on another in the most efficient way.</p> <p>Here is the table DDL of what I am trying to update</p> <p>Table1</p> <pre><code>CREATE TABLE `customersPrimary` ( `id` int NOT NULL AUTO_INCREMENT, `groupID` int NOT NULL, `IDInGroup` int NOT NULL, `name` varchar(200) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `address` varchar(200) COLLATE utf8mb4_unicode_ci DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `groupID-IDInGroup` (`groupID`,`IDInGroup`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci </code></pre> <p>Table2</p> <pre><code>CREATE TABLE `customersSecondary` ( `groupID` int NOT NULL, `IDInGroup` int NOT NULL, `name` varchar(200) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `address` varchar(200) COLLATE utf8mb4_unicode_ci DEFAULT NULL, PRIMARY KEY (`groupID`,`IDInGroup`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci </code></pre> <p>Both the tables are practically identical but customersSecondary table is a staging table for the other by design. The big difference is primary keys. Table 1 has an auto incrementing primary key, table 2 has a composite primary key.</p> <p>In both tables the combination of groupID and IDInGroup are unique.</p> <p>Here is the query I want to optimize</p> <pre><code>UPDATE customersPrimary INNER JOIN customersSecondary ON (customersPrimary.groupID = customersSecondary.groupID AND customersPrimary.IDInGroup = customersSecondary.IDInGroup) SET customersPrimary.name = customersSecondary.name, customersPrimary.address = customersSecondary.address </code></pre> <p>This query works but scans EVERY row in customersSecondary.</p> <p>Adding</p> <pre><code>WHERE customersPrimary.groupID = (groupID) </code></pre> <p>Cuts it down significantly to the number of rows with the GroupID in customersSecondary. But this is still often far larger than the number of rows being updated since the groupID can be large. I think the <code>WHERE</code> needs improvement.</p> <p>I can control table structure and add indexes. I will have to keep both tables.</p> <p>Any suggestions would be helpful.</p>
[ { "answer_id": 74582351, "author": "nnichols", "author_id": 1191247, "author_profile": "https://Stackoverflow.com/users/1191247", "pm_score": 2, "selected": true, "text": "customersSecondary updatedAt ALTER TABLE `customersPrimary`\n ADD COLUMN `updatedAt` DATETIME NOT NULL DEFAULT '2000-01-01 00:00:00',\n ADD INDEX `idx_customer_primary_updated` (`updatedAt`);\n\nALTER TABLE `customersSecondary`\n ADD COLUMN `updatedAt` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n ADD INDEX `idx_customer_secondary_updated` (`updatedAt`);\n updatedAt UPDATE customersPrimary cp\nINNER JOIN customersSecondary cs\n ON cp.groupID = cs.groupID\n AND cp.IDInGroup = cs.IDInGroup\n AND cp.updatedAt < cs.updatedAt\nSET\n cp.name = cs.name, \n cp.address = cs.address,\n cp.updatedAt = cs.updatedAt\nWHERE cs.updatedAt > :last_query_run_time;\n :last_query_run_time NOW() - INTERVAL 65 MINUTE SELECT MAX(updatedAt) FROM customersPrimary UPDATE customersPrimary cp\nINNER JOIN (SELECT MAX(updatedAt) maxUpdatedAt FROM customersPrimary) t\nINNER JOIN customersSecondary cs\n ON cp.groupID = cs.groupID\n AND cp.IDInGroup = cs.IDInGroup\n AND cp.updatedAt < cs.updatedAt\nSET\n cp.name = cs.name, \n cp.address = cs.address,\n cp.updatedAt = cs.updatedAt\nWHERE cs.updatedAt > t.maxUpdatedAt;\n" }, { "answer_id": 74594244, "author": "Rick James", "author_id": 1766831, "author_profile": "https://Stackoverflow.com/users/1766831", "pm_score": 0, "selected": false, "text": "UPDATE primary\n SET ...\n JOIN ( SELECT ...\n FROM secondary\n LEFT JOIN primary\n WHERE primary... IS NULL )\n ON ...\n secondary TRUNCATE TABLE secondary" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74580787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14746212/" ]
74,580,799
<p>I have two objects.</p> <pre><code>object_1 = [{January:50},{February:20},{April:10}, {May:22}] object_2 = [{January:40},{March:10},{April:5}] </code></pre> <p>I want the following result</p> <pre><code>object_result = [{January:90},{February:20},{March:10},{April:15},{May:22}] </code></pre> <p>Which means, if same key exists in both objects; add two values. Final object should consists of all the keys of the objects. How can I achieve this in JS? Is there a way to sort same as mentioned? (Sorting is not compulsory)</p>
[ { "answer_id": 74581251, "author": "Daniel", "author_id": 20605350, "author_profile": "https://Stackoverflow.com/users/20605350", "pm_score": 0, "selected": false, "text": "function overlyComplicatedFunction(){\n //I renamed these because they're arrays, not objects\n let array_1 = [{January:50},{February:20},{April:10},{May:22}]\n let array_2 = [{January:40},{March:10},{April:5}] \n\n /*\n initialize two empty objects that will become what array_1 & array_2 are normally \n structured like\n */\n let object_1 = {}, object_2 = {} \n\n /*\n These are called \"anonymous functions\" if you want to look that up & learn more \n about them. In these functions, each object inside array_1 is \"assigned\" to object_1, \n and each object inside array_2 is \"assigned\" to object_2, which is essentially \n merging each together. Now we have normal objects to work with!\n */\n anon = (array_1).forEach(x => Object.assign(object_1,x))\n anon = (array_2).forEach(x => Object.assign(object_2,x))\n\n //uncomment the line below if you want to see how the objects are supposed to look\n //console.log(object_1,object_2)\n\n /*\n The following function takes any number of objects as an input and reduces them\n together, combining like keys where possible\n */\n function sum(...objects){\n return objects.reduce((a, b) => {\n for(let j in b)if(b.hasOwnProperty(j))a[j] = (a[j] || 0) + b[j]\n return a\n }, {})\n }\n\n /*\n Here we call the sum function defined above, using our two normal objects, and stick \n it inside an array so it matches the format you're looking for in the end\n */\n let sumArray = [sum(object_1,object_2)]\n\n /*\n The following function converts an object with multiple keys into multiple objects \n with 1 key each, which will match the format of the original inputs\n */\n let object_result = Object.keys(sumArray[0]).map(function (k){\n let tempObject = {}\n tempObject[k] = sumArray[0][k]\n return tempObject\n })\n\n //This provides the weird answer you're looking for. Good luck!\n console.log(object_result)\n}\n" }, { "answer_id": 74581697, "author": "D.Dimitrioglo", "author_id": 4226289, "author_profile": "https://Stackoverflow.com/users/4226289", "pm_score": 1, "selected": false, "text": "let object_1 = [{January:50},{February:20},{April:10}, {May:22}]\nlet object_2 = [{January:40},{March:10},{April:5}]\n\nlet obj = [...object_1, ...object_2].reduce((acc, item) => {\n const [month, value] = Object.entries(item).at(0);\n \n if (!acc.hasOwnProperty(month)) {\n acc[month] = 0;\n }\n \n acc[month] += value;\n \n return acc;\n}, {});\n\nlet object_result = Object.entries(obj).map(([month, value]) => ({ [month]: value })));\n\n// [{\"January\":90},{\"February\":20},{\"April\":15},{\"May\":22},{\"March\":10}]\n objects_list let const const objects_list = [{}, ...] const monthlyStats = { Jan: 0, Feb: 0, ... } lowerCamelCase" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74580799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17257702/" ]
74,580,848
<p>I created a DynamoDB table and was running the following command in the CLI</p> <pre><code>aws dynamodb put-item \ --table-name NBATeams \ --item '{&quot;Team&quot;: {&quot;S&quot;: &quot;Team Name&quot;},&quot;Title&quot;: {&quot;S&quot;: &quot;Suns&quot;}}' \ --region us-east-1 </code></pre> <p>but I keep getting &quot;An error occurred (ValidationException) when calling the PutItem operation: One or more parameter values were invalid: Missing the key Team Name in the item&quot; Not sure What am I missing since my partition key is City.</p> <pre><code>aws dynamodb put-item \ --table-name NBATeams \ --item '{&quot;Team&quot;: {&quot;S&quot;: &quot;Team Name&quot;},&quot;Title&quot;: {&quot;S&quot;: &quot;Suns&quot;}}' \ --region us-east-1 </code></pre>
[ { "answer_id": 74581251, "author": "Daniel", "author_id": 20605350, "author_profile": "https://Stackoverflow.com/users/20605350", "pm_score": 0, "selected": false, "text": "function overlyComplicatedFunction(){\n //I renamed these because they're arrays, not objects\n let array_1 = [{January:50},{February:20},{April:10},{May:22}]\n let array_2 = [{January:40},{March:10},{April:5}] \n\n /*\n initialize two empty objects that will become what array_1 & array_2 are normally \n structured like\n */\n let object_1 = {}, object_2 = {} \n\n /*\n These are called \"anonymous functions\" if you want to look that up & learn more \n about them. In these functions, each object inside array_1 is \"assigned\" to object_1, \n and each object inside array_2 is \"assigned\" to object_2, which is essentially \n merging each together. Now we have normal objects to work with!\n */\n anon = (array_1).forEach(x => Object.assign(object_1,x))\n anon = (array_2).forEach(x => Object.assign(object_2,x))\n\n //uncomment the line below if you want to see how the objects are supposed to look\n //console.log(object_1,object_2)\n\n /*\n The following function takes any number of objects as an input and reduces them\n together, combining like keys where possible\n */\n function sum(...objects){\n return objects.reduce((a, b) => {\n for(let j in b)if(b.hasOwnProperty(j))a[j] = (a[j] || 0) + b[j]\n return a\n }, {})\n }\n\n /*\n Here we call the sum function defined above, using our two normal objects, and stick \n it inside an array so it matches the format you're looking for in the end\n */\n let sumArray = [sum(object_1,object_2)]\n\n /*\n The following function converts an object with multiple keys into multiple objects \n with 1 key each, which will match the format of the original inputs\n */\n let object_result = Object.keys(sumArray[0]).map(function (k){\n let tempObject = {}\n tempObject[k] = sumArray[0][k]\n return tempObject\n })\n\n //This provides the weird answer you're looking for. Good luck!\n console.log(object_result)\n}\n" }, { "answer_id": 74581697, "author": "D.Dimitrioglo", "author_id": 4226289, "author_profile": "https://Stackoverflow.com/users/4226289", "pm_score": 1, "selected": false, "text": "let object_1 = [{January:50},{February:20},{April:10}, {May:22}]\nlet object_2 = [{January:40},{March:10},{April:5}]\n\nlet obj = [...object_1, ...object_2].reduce((acc, item) => {\n const [month, value] = Object.entries(item).at(0);\n \n if (!acc.hasOwnProperty(month)) {\n acc[month] = 0;\n }\n \n acc[month] += value;\n \n return acc;\n}, {});\n\nlet object_result = Object.entries(obj).map(([month, value]) => ({ [month]: value })));\n\n// [{\"January\":90},{\"February\":20},{\"April\":15},{\"May\":22},{\"March\":10}]\n objects_list let const const objects_list = [{}, ...] const monthlyStats = { Jan: 0, Feb: 0, ... } lowerCamelCase" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74580848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20605307/" ]
74,580,871
<p>I'm trying to launch <strong>Tor</strong> browser via <code>puppeteer-sharp</code>. I am using <code>.net core 3.1</code> console application and latest version of <code>puppeteer-sharp</code>. So far the given the executable path console application launches the Tor Browser with an exception.</p> <pre><code>using PuppeteerSharp; using System.Threading; using System.Threading.Tasks; namespace puppeteer_tor { internal class Program { static async Task Main(string[] args) { string enableAutomation = &quot;--enable-automation&quot;; string noSandBox = &quot;--no-sandbox&quot;; string disableSetUidSandBox = &quot;--disable-setuid-sandbox&quot;; string[] argumentsWithoutExtension = new string[] { &quot;C:\\Users\\selaka.nanayakkara\\Desktop\\Tor Browser\\Browser\\TorBrowser\\Data\\profile.default&quot;, &quot;--proxy-server=socks5://127.0.0.1:9050&quot;, &quot;--disable-gpu&quot;, &quot;--disable-dev-shm-usage&quot;, enableAutomation, disableSetUidSandBox, noSandBox }; var options = new LaunchOptions { Headless = false, ExecutablePath = @&quot;C:\Users\selaka.nanayakkara\Desktop\Tor Browser\Browser\firefox.exe&quot;, Args = argumentsWithoutExtension }; using (var browser = await Puppeteer.LaunchAsync(options)) { Thread.Sleep(5000); var page = await browser.NewPageAsync(); await page.GoToAsync(&quot;https://check.torproject.org/&quot;); var element = await page.WaitForSelectorAsync(&quot;h1&quot;); var text = element.ToString(); } } } } </code></pre> <p>The browser launches with an issue and gives me the exception of :</p> <blockquote> <p>Failed to launch browser!</p> </blockquote> <p>With the below screen of the Tor browser :</p> <p><a href="https://i.stack.imgur.com/czz05.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/czz05.png" alt="enter image description here" /></a></p> <p>Your help is much appreciated in the above issue. Thanks in advance.</p> <p>Please find the attach code base <a href="https://github.com/SelakaKithmal/puppeteer-tor/blob/master/Program.cs" rel="nofollow noreferrer">here</a>.</p>
[ { "answer_id": 74581251, "author": "Daniel", "author_id": 20605350, "author_profile": "https://Stackoverflow.com/users/20605350", "pm_score": 0, "selected": false, "text": "function overlyComplicatedFunction(){\n //I renamed these because they're arrays, not objects\n let array_1 = [{January:50},{February:20},{April:10},{May:22}]\n let array_2 = [{January:40},{March:10},{April:5}] \n\n /*\n initialize two empty objects that will become what array_1 & array_2 are normally \n structured like\n */\n let object_1 = {}, object_2 = {} \n\n /*\n These are called \"anonymous functions\" if you want to look that up & learn more \n about them. In these functions, each object inside array_1 is \"assigned\" to object_1, \n and each object inside array_2 is \"assigned\" to object_2, which is essentially \n merging each together. Now we have normal objects to work with!\n */\n anon = (array_1).forEach(x => Object.assign(object_1,x))\n anon = (array_2).forEach(x => Object.assign(object_2,x))\n\n //uncomment the line below if you want to see how the objects are supposed to look\n //console.log(object_1,object_2)\n\n /*\n The following function takes any number of objects as an input and reduces them\n together, combining like keys where possible\n */\n function sum(...objects){\n return objects.reduce((a, b) => {\n for(let j in b)if(b.hasOwnProperty(j))a[j] = (a[j] || 0) + b[j]\n return a\n }, {})\n }\n\n /*\n Here we call the sum function defined above, using our two normal objects, and stick \n it inside an array so it matches the format you're looking for in the end\n */\n let sumArray = [sum(object_1,object_2)]\n\n /*\n The following function converts an object with multiple keys into multiple objects \n with 1 key each, which will match the format of the original inputs\n */\n let object_result = Object.keys(sumArray[0]).map(function (k){\n let tempObject = {}\n tempObject[k] = sumArray[0][k]\n return tempObject\n })\n\n //This provides the weird answer you're looking for. Good luck!\n console.log(object_result)\n}\n" }, { "answer_id": 74581697, "author": "D.Dimitrioglo", "author_id": 4226289, "author_profile": "https://Stackoverflow.com/users/4226289", "pm_score": 1, "selected": false, "text": "let object_1 = [{January:50},{February:20},{April:10}, {May:22}]\nlet object_2 = [{January:40},{March:10},{April:5}]\n\nlet obj = [...object_1, ...object_2].reduce((acc, item) => {\n const [month, value] = Object.entries(item).at(0);\n \n if (!acc.hasOwnProperty(month)) {\n acc[month] = 0;\n }\n \n acc[month] += value;\n \n return acc;\n}, {});\n\nlet object_result = Object.entries(obj).map(([month, value]) => ({ [month]: value })));\n\n// [{\"January\":90},{\"February\":20},{\"April\":15},{\"May\":22},{\"March\":10}]\n objects_list let const const objects_list = [{}, ...] const monthlyStats = { Jan: 0, Feb: 0, ... } lowerCamelCase" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74580871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4672460/" ]
74,580,875
<p>I am processing a list to output its items in chunks separated by blank rows as follows. But the result is not working when there are similar items, as shown with the arrows.</p> <p><a href="https://i.stack.imgur.com/8sAuA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8sAuA.jpg" alt="enter image description here" /></a></p> <p>The formula I'm using is <code>=query(filter(flatten({if(COUNTIFS($A$1:$A,$A$1:$A,ROW($A$1:$A),&quot;&lt;=&quot;&amp;ROW($A$1:$A))=1,&quot; &quot;,),A1:A}),flatten({if(COUNTIFS($A$1:$A,$A$1:$A,ROW($A$1:$A),&quot;&lt;=&quot;&amp;ROW($A$1:$A))=1,&quot; &quot;,),A1:A})&lt;&gt;&quot;&quot;),&quot;offset 1&quot;,0)</code></p> <p>I need some help with it, to get the repeated chunks right too, so that the desired result is following. I've tried tweaking the <code>COUNTIF</code> conditions but am struggling.</p> <h3>Desired result</h3> <p><a href="https://i.stack.imgur.com/PssqX.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PssqX.jpg" alt="enter image description here" /></a></p>
[ { "answer_id": 74581251, "author": "Daniel", "author_id": 20605350, "author_profile": "https://Stackoverflow.com/users/20605350", "pm_score": 0, "selected": false, "text": "function overlyComplicatedFunction(){\n //I renamed these because they're arrays, not objects\n let array_1 = [{January:50},{February:20},{April:10},{May:22}]\n let array_2 = [{January:40},{March:10},{April:5}] \n\n /*\n initialize two empty objects that will become what array_1 & array_2 are normally \n structured like\n */\n let object_1 = {}, object_2 = {} \n\n /*\n These are called \"anonymous functions\" if you want to look that up & learn more \n about them. In these functions, each object inside array_1 is \"assigned\" to object_1, \n and each object inside array_2 is \"assigned\" to object_2, which is essentially \n merging each together. Now we have normal objects to work with!\n */\n anon = (array_1).forEach(x => Object.assign(object_1,x))\n anon = (array_2).forEach(x => Object.assign(object_2,x))\n\n //uncomment the line below if you want to see how the objects are supposed to look\n //console.log(object_1,object_2)\n\n /*\n The following function takes any number of objects as an input and reduces them\n together, combining like keys where possible\n */\n function sum(...objects){\n return objects.reduce((a, b) => {\n for(let j in b)if(b.hasOwnProperty(j))a[j] = (a[j] || 0) + b[j]\n return a\n }, {})\n }\n\n /*\n Here we call the sum function defined above, using our two normal objects, and stick \n it inside an array so it matches the format you're looking for in the end\n */\n let sumArray = [sum(object_1,object_2)]\n\n /*\n The following function converts an object with multiple keys into multiple objects \n with 1 key each, which will match the format of the original inputs\n */\n let object_result = Object.keys(sumArray[0]).map(function (k){\n let tempObject = {}\n tempObject[k] = sumArray[0][k]\n return tempObject\n })\n\n //This provides the weird answer you're looking for. Good luck!\n console.log(object_result)\n}\n" }, { "answer_id": 74581697, "author": "D.Dimitrioglo", "author_id": 4226289, "author_profile": "https://Stackoverflow.com/users/4226289", "pm_score": 1, "selected": false, "text": "let object_1 = [{January:50},{February:20},{April:10}, {May:22}]\nlet object_2 = [{January:40},{March:10},{April:5}]\n\nlet obj = [...object_1, ...object_2].reduce((acc, item) => {\n const [month, value] = Object.entries(item).at(0);\n \n if (!acc.hasOwnProperty(month)) {\n acc[month] = 0;\n }\n \n acc[month] += value;\n \n return acc;\n}, {});\n\nlet object_result = Object.entries(obj).map(([month, value]) => ({ [month]: value })));\n\n// [{\"January\":90},{\"February\":20},{\"April\":15},{\"May\":22},{\"March\":10}]\n objects_list let const const objects_list = [{}, ...] const monthlyStats = { Jan: 0, Feb: 0, ... } lowerCamelCase" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74580875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10735100/" ]
74,580,876
<p>There are 2 strings in groovy files :1) 01xx01xx01 and 2) 0101010111 and I want to compare only non-x elements. eg only compare 010101 with 010111 (ignore &quot;x&quot;). The following scripts were created by me (written in groovy). It works but needs many lines of code. Are there any other ways to do it?</p> <pre><code>a=&quot;01xx01xx01&quot; b=&quot;0101010111&quot; def compareStrings(String a,String b){ i=0 while (i&lt;a.length){ if (a[i] ==&quot;X&quot; || b[i]==&quot;X&quot;){ i+=1} else if (a[i]!=b[i]){ return &quot;Not Similar&quot;} else{ i+=1} return &quot;Similar&quot; } } def result = compareStrings(str1,str2) println(result) </code></pre>
[ { "answer_id": 74581150, "author": "Yash Mehta", "author_id": 20172954, "author_profile": "https://Stackoverflow.com/users/20172954", "pm_score": 1, "selected": false, "text": "def compare_strings(string1,string2):\n # Edge case:- When both strings have different length\n if len(string1)!=len(string2):\n return \"Not similar\"\n length=len(string1)\n i=0\n while i<length: #You can apply for loop also the edge case of different length is checked above. so there will be no error of index out of range\n if a[i]==\"x\" or b[i]==\"x\":\n i+=1\n elif a[i]!=b[i]:\n return \"Not Similar\"\n else:\n i+=1\n return \"Similar\"\n# Comparisons of two strings Test Case 1 Same Length Not similar\na=\"01xx01xx01\" \nb=\"0101010111\" \nprint(compare_strings(a,b))\n# Comparisons of two strings Test Case 2 Same Length similar\na=\"01xx01xx01\" \nb=\"0101010001\"\nprint(compare_strings(a,b))\n# Comparisons of two strings Test Case 3 Different Length\na=\"01xx01xx01\" \nb=\"0101010\"\nprint(compare_strings(a,b))\n Not Similar\nSimilar\nNot similar\n" }, { "answer_id": 74581194, "author": "balderman", "author_id": 415016, "author_profile": "https://Stackoverflow.com/users/415016", "pm_score": -1, "selected": true, "text": "println \"str match\"\n\ndef str1 = '01xx01xx01'\ndef str2 = '0101010111'\ndef str3 = '01xx01xx01'\n\ndef sameStringsIgnoreX(str1,str2) {\n def temp1 = str1.replaceAll('x','')\n def temp2 = str2.replaceAll('x','')\n temp1 == temp2\n\n}\n\ndef sameStrings = sameStringsIgnoreX(str1,str2)\nprintln(sameStrings)\n\nsameStrings = sameStringsIgnoreX(str1,str3)\nprintln(sameStrings)\n str match\nfalse\ntrue\n" }, { "answer_id": 74585254, "author": "tim_yates", "author_id": 6509, "author_profile": "https://Stackoverflow.com/users/6509", "pm_score": 1, "selected": false, "text": "boolean sameStringsIgnoreX(String a, String b) {\n [a, b]*.toList().transpose().findAll { 'x' !in it }.every { it[0] == it[1] }\n}\n\ndef str1 = '01xx01xx01'\ndef str2 = '0101010111'\ndef str3 = '01xx01xx01'\n\n\ndef sameStrings = sameStringsIgnoreX(str1,str2)\nprintln(sameStrings)\n\nsameStrings = sameStringsIgnoreX(str1,str3)\nprintln(sameStrings)\n" }, { "answer_id": 74588864, "author": "Liu Xu", "author_id": 9960443, "author_profile": "https://Stackoverflow.com/users/9960443", "pm_score": 0, "selected": false, "text": "a=\"01xx01xx01\"\nb=\"0101010111\"\ndef compareStrings(String a,String b){\n i=0\n while (i<a.length){\n if (a[i] ==\"X\" || b[i]==\"X\"){\n i+=1}\n else if (a[i]!=b[i]){\n return \"Not Similar\"}\n else{\n i+=1}\n return \"Similar\"\n }\n}\ndef result = compareStrings(str1,str2) \nprintln(result) \n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74580876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9960443/" ]
74,580,903
<p>I'm working with Laravel 9 and I have used this column at <code>users</code> table for storing user mobile phone number:</p> <pre><code>$table-&gt;integer('usr_mobile_phone'); </code></pre> <p>And at the factor, I tried this to fill out this column:</p> <pre><code>public function definition() { $fs = '091'; $ch = '1234567890'; $str = $fs.str_shuffle($ch); return [ 'usr_mobile_phone' =&gt; $str ... ]; } </code></pre> <p>But when I run <strong><code>php artisan db:seed</code></strong>, I get this error:</p> <h2><strong>SQLSTATE[22003]: Numeric value out of range: 1264 Out of range value for column 'usr_mobile_phone' at row 1</strong></h2> <p>So what's going wrong here?</p> <p>How can I store the number properly at the user's mobile phone number column in the DB?</p>
[ { "answer_id": 74581150, "author": "Yash Mehta", "author_id": 20172954, "author_profile": "https://Stackoverflow.com/users/20172954", "pm_score": 1, "selected": false, "text": "def compare_strings(string1,string2):\n # Edge case:- When both strings have different length\n if len(string1)!=len(string2):\n return \"Not similar\"\n length=len(string1)\n i=0\n while i<length: #You can apply for loop also the edge case of different length is checked above. so there will be no error of index out of range\n if a[i]==\"x\" or b[i]==\"x\":\n i+=1\n elif a[i]!=b[i]:\n return \"Not Similar\"\n else:\n i+=1\n return \"Similar\"\n# Comparisons of two strings Test Case 1 Same Length Not similar\na=\"01xx01xx01\" \nb=\"0101010111\" \nprint(compare_strings(a,b))\n# Comparisons of two strings Test Case 2 Same Length similar\na=\"01xx01xx01\" \nb=\"0101010001\"\nprint(compare_strings(a,b))\n# Comparisons of two strings Test Case 3 Different Length\na=\"01xx01xx01\" \nb=\"0101010\"\nprint(compare_strings(a,b))\n Not Similar\nSimilar\nNot similar\n" }, { "answer_id": 74581194, "author": "balderman", "author_id": 415016, "author_profile": "https://Stackoverflow.com/users/415016", "pm_score": -1, "selected": true, "text": "println \"str match\"\n\ndef str1 = '01xx01xx01'\ndef str2 = '0101010111'\ndef str3 = '01xx01xx01'\n\ndef sameStringsIgnoreX(str1,str2) {\n def temp1 = str1.replaceAll('x','')\n def temp2 = str2.replaceAll('x','')\n temp1 == temp2\n\n}\n\ndef sameStrings = sameStringsIgnoreX(str1,str2)\nprintln(sameStrings)\n\nsameStrings = sameStringsIgnoreX(str1,str3)\nprintln(sameStrings)\n str match\nfalse\ntrue\n" }, { "answer_id": 74585254, "author": "tim_yates", "author_id": 6509, "author_profile": "https://Stackoverflow.com/users/6509", "pm_score": 1, "selected": false, "text": "boolean sameStringsIgnoreX(String a, String b) {\n [a, b]*.toList().transpose().findAll { 'x' !in it }.every { it[0] == it[1] }\n}\n\ndef str1 = '01xx01xx01'\ndef str2 = '0101010111'\ndef str3 = '01xx01xx01'\n\n\ndef sameStrings = sameStringsIgnoreX(str1,str2)\nprintln(sameStrings)\n\nsameStrings = sameStringsIgnoreX(str1,str3)\nprintln(sameStrings)\n" }, { "answer_id": 74588864, "author": "Liu Xu", "author_id": 9960443, "author_profile": "https://Stackoverflow.com/users/9960443", "pm_score": 0, "selected": false, "text": "a=\"01xx01xx01\"\nb=\"0101010111\"\ndef compareStrings(String a,String b){\n i=0\n while (i<a.length){\n if (a[i] ==\"X\" || b[i]==\"X\"){\n i+=1}\n else if (a[i]!=b[i]){\n return \"Not Similar\"}\n else{\n i+=1}\n return \"Similar\"\n }\n}\ndef result = compareStrings(str1,str2) \nprintln(result) \n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74580903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17730693/" ]
74,580,958
<p><em>First of all, this is the first time I create a Bukkit plugin.</em></p> <p>Basically, when someone does a certain action with a block and checks certain conditions, I would like it to <strong>emit a redstone signal</strong> (the block). The code is executed in the Bukkit <strong>PlayerInteractEvent</strong>. Except that after a lot of research, I still haven't found a single (working) solution, neither on the forums, nor in the documentation.</p> <p>I don't know how to <strong>tell Minecraft that this block can emit redstone</strong> (<em>if it needs it</em>). If I don't say anything stupid, it was created with a <strong>dynamX pack</strong> (the mod that contains the block).</p> <p>I already looked at this solution: <a href="https://stackoverflow.com/questions/40376835/bukkit-set-a-block-powered">Bukkit: Set a block powered</a>, but it doesn't match my expectations and doesn't work.</p> <p>So I was wondering if it was possible to <strong>emit a redstone signal on a specific block</strong> with <strong>Bukkit 1.12.2</strong>, or at a <strong>specific coordinate</strong>. This would solve all the problems related to this.</p> <p>I thank you in advance.</p>
[ { "answer_id": 74581150, "author": "Yash Mehta", "author_id": 20172954, "author_profile": "https://Stackoverflow.com/users/20172954", "pm_score": 1, "selected": false, "text": "def compare_strings(string1,string2):\n # Edge case:- When both strings have different length\n if len(string1)!=len(string2):\n return \"Not similar\"\n length=len(string1)\n i=0\n while i<length: #You can apply for loop also the edge case of different length is checked above. so there will be no error of index out of range\n if a[i]==\"x\" or b[i]==\"x\":\n i+=1\n elif a[i]!=b[i]:\n return \"Not Similar\"\n else:\n i+=1\n return \"Similar\"\n# Comparisons of two strings Test Case 1 Same Length Not similar\na=\"01xx01xx01\" \nb=\"0101010111\" \nprint(compare_strings(a,b))\n# Comparisons of two strings Test Case 2 Same Length similar\na=\"01xx01xx01\" \nb=\"0101010001\"\nprint(compare_strings(a,b))\n# Comparisons of two strings Test Case 3 Different Length\na=\"01xx01xx01\" \nb=\"0101010\"\nprint(compare_strings(a,b))\n Not Similar\nSimilar\nNot similar\n" }, { "answer_id": 74581194, "author": "balderman", "author_id": 415016, "author_profile": "https://Stackoverflow.com/users/415016", "pm_score": -1, "selected": true, "text": "println \"str match\"\n\ndef str1 = '01xx01xx01'\ndef str2 = '0101010111'\ndef str3 = '01xx01xx01'\n\ndef sameStringsIgnoreX(str1,str2) {\n def temp1 = str1.replaceAll('x','')\n def temp2 = str2.replaceAll('x','')\n temp1 == temp2\n\n}\n\ndef sameStrings = sameStringsIgnoreX(str1,str2)\nprintln(sameStrings)\n\nsameStrings = sameStringsIgnoreX(str1,str3)\nprintln(sameStrings)\n str match\nfalse\ntrue\n" }, { "answer_id": 74585254, "author": "tim_yates", "author_id": 6509, "author_profile": "https://Stackoverflow.com/users/6509", "pm_score": 1, "selected": false, "text": "boolean sameStringsIgnoreX(String a, String b) {\n [a, b]*.toList().transpose().findAll { 'x' !in it }.every { it[0] == it[1] }\n}\n\ndef str1 = '01xx01xx01'\ndef str2 = '0101010111'\ndef str3 = '01xx01xx01'\n\n\ndef sameStrings = sameStringsIgnoreX(str1,str2)\nprintln(sameStrings)\n\nsameStrings = sameStringsIgnoreX(str1,str3)\nprintln(sameStrings)\n" }, { "answer_id": 74588864, "author": "Liu Xu", "author_id": 9960443, "author_profile": "https://Stackoverflow.com/users/9960443", "pm_score": 0, "selected": false, "text": "a=\"01xx01xx01\"\nb=\"0101010111\"\ndef compareStrings(String a,String b){\n i=0\n while (i<a.length){\n if (a[i] ==\"X\" || b[i]==\"X\"){\n i+=1}\n else if (a[i]!=b[i]){\n return \"Not Similar\"}\n else{\n i+=1}\n return \"Similar\"\n }\n}\ndef result = compareStrings(str1,str2) \nprintln(result) \n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74580958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12554903/" ]
74,580,988
<p>I was using a yes/no loop to make an infinite loop which would end when user enters no or No but the program was not working properly. I know the what the error is but i don't know why is it occuring like this. Can anyone tell how to fix the error without changing my initial program</p> <p>when i use this code it works but when i use if a=='yes' or 'Yes' and elif a=='no' or 'No' in the somehow the output shows the print statement of the if statement even when i enter no.</p> <p>My program without the OR condition</p> <pre><code>while True: a = input(&quot;Enter yes/no to continue&quot;) if a=='yes': print(&quot;enter the program&quot;) elif a=='no': print(&quot;EXIT&quot;) break else: print(&quot;Enter either yes/no&quot;) </code></pre> <p>My initial program with OR condition</p> <pre><code>while True: a = input(&quot;Enter yes/no to continue&quot;) if a=='yes' or 'Yes': print(&quot;enter the program&quot;) elif a=='no' or 'No': print(&quot;EXIT&quot;) break else: print(&quot;Enter either yes/no&quot;) </code></pre>
[ { "answer_id": 74581150, "author": "Yash Mehta", "author_id": 20172954, "author_profile": "https://Stackoverflow.com/users/20172954", "pm_score": 1, "selected": false, "text": "def compare_strings(string1,string2):\n # Edge case:- When both strings have different length\n if len(string1)!=len(string2):\n return \"Not similar\"\n length=len(string1)\n i=0\n while i<length: #You can apply for loop also the edge case of different length is checked above. so there will be no error of index out of range\n if a[i]==\"x\" or b[i]==\"x\":\n i+=1\n elif a[i]!=b[i]:\n return \"Not Similar\"\n else:\n i+=1\n return \"Similar\"\n# Comparisons of two strings Test Case 1 Same Length Not similar\na=\"01xx01xx01\" \nb=\"0101010111\" \nprint(compare_strings(a,b))\n# Comparisons of two strings Test Case 2 Same Length similar\na=\"01xx01xx01\" \nb=\"0101010001\"\nprint(compare_strings(a,b))\n# Comparisons of two strings Test Case 3 Different Length\na=\"01xx01xx01\" \nb=\"0101010\"\nprint(compare_strings(a,b))\n Not Similar\nSimilar\nNot similar\n" }, { "answer_id": 74581194, "author": "balderman", "author_id": 415016, "author_profile": "https://Stackoverflow.com/users/415016", "pm_score": -1, "selected": true, "text": "println \"str match\"\n\ndef str1 = '01xx01xx01'\ndef str2 = '0101010111'\ndef str3 = '01xx01xx01'\n\ndef sameStringsIgnoreX(str1,str2) {\n def temp1 = str1.replaceAll('x','')\n def temp2 = str2.replaceAll('x','')\n temp1 == temp2\n\n}\n\ndef sameStrings = sameStringsIgnoreX(str1,str2)\nprintln(sameStrings)\n\nsameStrings = sameStringsIgnoreX(str1,str3)\nprintln(sameStrings)\n str match\nfalse\ntrue\n" }, { "answer_id": 74585254, "author": "tim_yates", "author_id": 6509, "author_profile": "https://Stackoverflow.com/users/6509", "pm_score": 1, "selected": false, "text": "boolean sameStringsIgnoreX(String a, String b) {\n [a, b]*.toList().transpose().findAll { 'x' !in it }.every { it[0] == it[1] }\n}\n\ndef str1 = '01xx01xx01'\ndef str2 = '0101010111'\ndef str3 = '01xx01xx01'\n\n\ndef sameStrings = sameStringsIgnoreX(str1,str2)\nprintln(sameStrings)\n\nsameStrings = sameStringsIgnoreX(str1,str3)\nprintln(sameStrings)\n" }, { "answer_id": 74588864, "author": "Liu Xu", "author_id": 9960443, "author_profile": "https://Stackoverflow.com/users/9960443", "pm_score": 0, "selected": false, "text": "a=\"01xx01xx01\"\nb=\"0101010111\"\ndef compareStrings(String a,String b){\n i=0\n while (i<a.length){\n if (a[i] ==\"X\" || b[i]==\"X\"){\n i+=1}\n else if (a[i]!=b[i]){\n return \"Not Similar\"}\n else{\n i+=1}\n return \"Similar\"\n }\n}\ndef result = compareStrings(str1,str2) \nprintln(result) \n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74580988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20605317/" ]
74,581,016
<p>I view my git logs in CMD which has a custom format,</p> <pre><code>git log --date=format:'%d %b %I:%M%p' --pretty=format:&quot;%C(Yellow)%h%Creset %cd%Cgreen%d %Creset%s&quot; -10 </code></pre> <p>now I have to copy this command every time from my notepad so I was thinking if I can create a custom cmd command that will run the above command.</p> <p>for eg. I would just write</p> <pre><code>showlog </code></pre> <p>and it will execute my command.</p> <p>I tried creating a bat file and found this <a href="https://stackoverflow.com/questions/5181709/custom-commands-in-windows-command-prompt">command</a>.</p> <pre><code>start cmd.exe @cmd /k &quot;git log --oneline -10&quot; </code></pre> <p>but it opened a new window I would like this to execute in the same window like other git commands</p> <p>So I want to know</p> <ol> <li>how exactly it is done within the same window?</li> <li>where can I learn more about this?</li> </ol>
[ { "answer_id": 74581385, "author": "Anders", "author_id": 3501, "author_profile": "https://Stackoverflow.com/users/3501", "pm_score": 3, "selected": true, "text": "start cmd @echo off\nmy command and parameters here\n @echo off\ngit log --date=format:'%d %b %I:%M%p' --pretty=format:\"%C(Yellow)%h%Creset %cd%Cgreen%d %Creset%s\" -10\n %% @echo off" }, { "answer_id": 74583887, "author": "Lazy Badger", "author_id": 960558, "author_profile": "https://Stackoverflow.com/users/960558", "pm_score": 1, "selected": false, "text": "git showlog git config --global alias.showlog 'git log <FULL TAIL OF YOUR COMMAND HERE>'\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11933249/" ]
74,581,024
<p>I have a lot of namespaces and I want to get all pods from a sub-list of namespaces.</p> <p>For getting all the pods from all namespace the command is:</p> <pre><code>kubectl get pods --all-namespaces </code></pre> <p>To get all pods from a spesific namespace the command is:</p> <pre><code>kubectl get pods -n namespace-name </code></pre> <p>However I can't find a way to get all pods from a list of namespaces, something like:</p> <pre><code>kubectl get pods -n namespace-name1, namespace-name2, namespace-name3 </code></pre> <p>what is the right command for that?</p>
[ { "answer_id": 74581117, "author": "user2311578", "author_id": 2311578, "author_profile": "https://Stackoverflow.com/users/2311578", "pm_score": 2, "selected": false, "text": "kubectl get pods -A | egrep '^(namespace-name1|namespace-name2|namespace-name3)'\n kubectl ^" }, { "answer_id": 74584194, "author": "DazWilkin", "author_id": 609290, "author_profile": "https://Stackoverflow.com/users/609290", "pm_score": 1, "selected": false, "text": "for NAMESPACE in \"namespace-1\" \"namespace-2\"\ndo\n kubectl get pods \\\n --namespace=${NAMESPACE} \\\n --output=name\ndone\n NAMESPACE=$(\n \"namespace-1\"\n \"namespace-2\"\n)\nfor NAMESPACE in \"${NAMESPACES[@]}\"\ndo\n kubectl get pods \\\n --namespace=${NAMESPACE} \\\n --output=name\ndone\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12557235/" ]
74,581,042
<p>complete bash noob here. Had the following command (1.) and it worked as expected but it seemed a bit naive for what I needed:</p> <ol> <li>Essentially generating a wordlist from a messy input file with tab delimiters</li> </ol> <pre class="lang-bash prettyprint-override"><code>cat users.txt | tee &gt;(cut -f 1 &gt;&gt; cut_out.txt) &gt;(cut -f 2 &gt;&gt; cut_out.txt) &gt;(cut -f 3 &gt;&gt; cut_out.txt) &gt;(cut -f 4 &gt;&gt; cut_out.txt) </code></pre> <p>Output:</p> <pre><code>W Humphrey SummersW FoxxR noreply DaibaN PeanutbutterM PetersJ DaviesJ BlaireJ GongoH MurphyF JeffersD HorsemanB ... </code></pre> <ol start="2"> <li>Thought I could cut down on the ridiculous command above with the following</li> </ol> <pre class="lang-bash prettyprint-override"><code>cat users.txt | for i in {1..4}; do cut -f $i &gt;&gt; cut_out.txt; done </code></pre> <p>Output:</p> <pre><code>HumphreyW </code></pre> <p>The command above only returned a single word from the list and some white-space.</p> <ol start="3"> <li>The solution. I knew that I could get it working logically by simply looping the entire command instead, this did exactly what I wanted but just wanted to know why the command above (2.) returned an almost empty file?</li> </ol> <pre class="lang-bash prettyprint-override"><code>for i in {1..4}; do cat users.txt | cut -f $i &gt;&gt; cut_out.txt; done </code></pre> <p>Have a solution, more-so wanted an explanation because I am dumb and still learning about I/O in bash. Cheers.</p>
[ { "answer_id": 74581117, "author": "user2311578", "author_id": 2311578, "author_profile": "https://Stackoverflow.com/users/2311578", "pm_score": 2, "selected": false, "text": "kubectl get pods -A | egrep '^(namespace-name1|namespace-name2|namespace-name3)'\n kubectl ^" }, { "answer_id": 74584194, "author": "DazWilkin", "author_id": 609290, "author_profile": "https://Stackoverflow.com/users/609290", "pm_score": 1, "selected": false, "text": "for NAMESPACE in \"namespace-1\" \"namespace-2\"\ndo\n kubectl get pods \\\n --namespace=${NAMESPACE} \\\n --output=name\ndone\n NAMESPACE=$(\n \"namespace-1\"\n \"namespace-2\"\n)\nfor NAMESPACE in \"${NAMESPACES[@]}\"\ndo\n kubectl get pods \\\n --namespace=${NAMESPACE} \\\n --output=name\ndone\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20605433/" ]
74,581,060
<p>C++23 adds some &quot;monadic-style&quot; functionality regarding optionals, as methods of <code>optional&lt;T&gt;</code>:</p> <p><a href="https://en.cppreference.com/w/cpp/utility/optional/and_then" rel="noreferrer"><code>optional&lt;T&gt;::and_then()</code></a> (and ignoring qualifiers of <code>this</code>):</p> <blockquote> <pre><code>template&lt;class F&gt; constexpr auto and_then(F&amp;&amp; f); </code></pre> <p>Returns the result of invocation of f on the contained value if it exists. Otherwise, returns an empty value of the return type.</p> </blockquote> <p><a href="https://en.cppreference.com/w/cpp/utility/optional/transform" rel="noreferrer"><code>optional&lt;T&gt;::transform()</code></a> (and ignoring qualifiers of <code>this</code>):</p> <blockquote> <pre><code>template&lt;class F&gt; constexpr auto transform(F&amp;&amp; f); </code></pre> <p>Returns an <code>std::optional</code> that contains the result of invocation of <code>f</code> on the contained value if <code>*this</code> contains a value. Otherwise, returns an empty <code>std::optional</code> of such type.</p> </blockquote> <p>So, aren't these two functions doing the same thing?</p>
[ { "answer_id": 74581061, "author": "einpoklum", "author_id": 1593077, "author_profile": "https://Stackoverflow.com/users/1593077", "pm_score": 2, "selected": false, "text": "transform() and_then() transform() T2 foo(T1 x) and_then() optional<T2> bar(T1 x) my_optional.transform(foo) my_optional.and_then(bar) optional<T2>" }, { "answer_id": 74585064, "author": "n. m.", "author_id": 775806, "author_profile": "https://Stackoverflow.com/users/775806", "pm_score": 1, "selected": false, "text": "and_then bind flatmap >>= transform map map bind std::optional std::optional" }, { "answer_id": 74588287, "author": "Tom Huntington", "author_id": 11998382, "author_profile": "https://Stackoverflow.com/users/11998382", "pm_score": 0, "selected": false, "text": "and_then T -> std::optional<U> transform transform std::optional<std::optional<U>> and_then std::optional<std::optional<U>> std::optional<U> transform flatten range<range<U>> future<future<U>>" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1593077/" ]
74,581,136
<p>I would like to do the same in python pandas as shown on the picture.</p> <p><a href="https://i.stack.imgur.com/ZsHLT.png" rel="nofollow noreferrer">pandas image</a></p> <p>This is sum function where the first cell is fixed and the formula calculates &quot;<strong>continuous sum</strong>&quot;.</p> <p>I tried to create pandas data frame however I did not manage to do this exactly.</p>
[ { "answer_id": 74581061, "author": "einpoklum", "author_id": 1593077, "author_profile": "https://Stackoverflow.com/users/1593077", "pm_score": 2, "selected": false, "text": "transform() and_then() transform() T2 foo(T1 x) and_then() optional<T2> bar(T1 x) my_optional.transform(foo) my_optional.and_then(bar) optional<T2>" }, { "answer_id": 74585064, "author": "n. m.", "author_id": 775806, "author_profile": "https://Stackoverflow.com/users/775806", "pm_score": 1, "selected": false, "text": "and_then bind flatmap >>= transform map map bind std::optional std::optional" }, { "answer_id": 74588287, "author": "Tom Huntington", "author_id": 11998382, "author_profile": "https://Stackoverflow.com/users/11998382", "pm_score": 0, "selected": false, "text": "and_then T -> std::optional<U> transform transform std::optional<std::optional<U>> and_then std::optional<std::optional<U>> std::optional<U> transform flatten range<range<U>> future<future<U>>" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20557036/" ]
74,581,153
<p>I have the following (working) function in JavaScript:</p> <pre class="lang-js prettyprint-override"><code>function solve(strArr) { return strArr.reduce(function ([x, y], curr) { switch (curr) { case 'up': return [x, y + 1] case 'down': return [x, y - 1] case 'left': return [x - 1, y] case 'right': return [x + 1, y] } }, [0, 0]) } </code></pre> <p>I'm trying to rewrite it using TypeScript as:</p> <pre><code>function solve(strArr: string[]): number[] { return strArr.reduce(([x, y]: number[], curr: string) =&gt; { switch (curr) { case 'up': return [x, y + 1] case 'down': return [x, y - 1] case 'left': return [x - 1, y] case 'right': return [x + 1, y] } }, [0,0]) } </code></pre> <p>but I'm getting the <code>Type 'string' is not assignable to type 'number[]'.</code> error, which I know refers to the accumulator, but don't know how to solve.</p> <p>As per <a href="https://stackoverflow.com/questions/74581153/rewriting-function-in-typescript#comment131647782_74581153">Rajesh's suggestion</a>, changing the type of <code>strArr</code> to <code>any</code> solves the issue, but giving it the specific type I'm using with the function doesn't work; why?</p>
[ { "answer_id": 74581228, "author": "TmTron", "author_id": 1041641, "author_profile": "https://Stackoverflow.com/users/1041641", "pm_score": 1, "selected": false, "text": "function solve(strArr:string[]) {\n return strArr.reduce(([x, y], curr) => {\n switch (curr) {\n case 'up': return [x, y + 1]\n case 'down': return [x, y - 1]\n case 'left': return [x - 1, y]\n case 'right': return [x + 1, y]\n // maybe throw an error instead\n default: return [x, y];\n }\n }, [0,0])\n}\n number[] | undefined" }, { "answer_id": 74581248, "author": "Rajesh Kanna", "author_id": 15656258, "author_profile": "https://Stackoverflow.com/users/15656258", "pm_score": -1, "selected": true, "text": "default : return []" }, { "answer_id": 74581258, "author": "Roberto Zvjerković", "author_id": 7436489, "author_profile": "https://Stackoverflow.com/users/7436489", "pm_score": 2, "selected": false, "text": "type Direction = 'up' | 'down' | 'left' | 'right'\n\nfunction solve(strArr: Direction[]) {\n return strArr.reduce(([x, y], curr) => {\n switch (curr) {\n case 'up': return [x, y + 1]\n case 'down': return [x, y - 1]\n case 'left': return [x - 1, y]\n case 'right': return [x + 1, y]\n }\n }, [0,0])\n}\n" }, { "answer_id": 74581356, "author": "Yukulélé", "author_id": 806169, "author_profile": "https://Stackoverflow.com/users/806169", "pm_score": 0, "selected": false, "text": "array.reduce() type Direction = 'up' | 'down' | 'left' | 'right'\nfunction solve(directions: Direction[]): [number, number] {\n let x = 0\n let y = 0\n for (const direction of directions) {\n switch (direction) {\n case 'up': y++; break\n case 'down': y--; break\n case 'left': x--; break\n case 'right': x++; break\n }\n }\n return [x, y]\n}\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2140071/" ]
74,581,239
<p>I'm trying to make a neural network (using YT guide, but I had to change data input code) and I need the batched dataset for the train function to work properly (idk why, not event sure on it). But when I try to convert a train data list to Dataset using tensorflow.data.Dataset.from_tensor_slices(train_data)) I receive a error message:</p> <pre><code>InvalidArgumentError {{function_node __wrapped__Pack_N_3_device_/job:localhost/replica:0/task:0/device:GPU:0}} Shapes of all inputs must match: values[0].shape = [105,105,3] != values[2].shape = [1] [Op:Pack] name: 0 </code></pre> <p>The train_data list consists of 560 lists, each with 3 elements inside:</p> <pre><code>&lt;tf.Tensor: shape=(105, 105, 3), dtype=float32, numpy = array([[[&quot;105x105 3-dimensional image with my face&quot;]]]. dtype=float32)&gt; &lt;tf.Tensor: shape=(105, 105, 3), dtype=float32, numpy = array([[[&quot;different image with the same properties&quot;]]] dtype=float32)&gt; &lt;tf.Tensor: shape=(1,), dtype=float32, numpy=array([&quot;1. or 0. (float), a label, showing if these pictures are actually the pictures of the same person&quot;], dtype=float32)&gt; </code></pre> <p>I am pretty sure that all of the shapes in the train_data list are exactly as described.</p> <p>Some data about shapes using .shape method</p> <pre><code>train_data.shape #&quot;AttributeError: 'list' object has no attribute 'shape'&quot; - main list train_data[0].shape #&quot;AttributeError: 'list' object has no attribute 'shape'&quot; - sublist, with 3 elements train_data[0][0].shape #&quot;TensorShape([105, 105, 3])&quot; - first image train_data[0][0][0].shape #&quot;TensorShape([105, 3])&quot; - first row of image pixels, ig train_data[0][0][0][0].shape #&quot;TensorShape([3])&quot; - pixel in the left upper corner </code></pre> <p>That's what I tried to do: The label of the image pairs (1. or 0.) was previosly just an integer. Then, I received an error saying that everything here should be the same type of float32. Then, I tried to convert it to tensor, but it changed nothing except the last part of the current error message, it used to say &quot;values[2].shape = []&quot; before.</p> <p>I really have no idea what could lead to the error. I don't have any Tensorflow usage experience.</p> <p>sorry if my engrish is bad</p> <p>Edit: here is the code that takes the images out of certain directory. May cause eye bleeding</p> <pre><code>for i in os.listdir(&quot;t&quot;): for ii in os.listdir(os.path.join(&quot;t&quot;, i)): td.append([ [ tensorflow.expand_dims( tensorflow.io.decode_jpeg( tensorflow.io.read_file(os.path.join(&quot;t&quot;, i, ii) + &quot;\\&quot; + os.listdir(os.path.join(&quot;t&quot;, i, ii))[0])) / 255, 0), tensorflow.expand_dims( tensorflow.io.decode_jpeg( tensorflow.io.read_file(os.path.join(&quot;t&quot;, i, ii) + &quot;\\2.jpeg&quot;)) / 255, 0)], tensorflow.convert_to_tensor( float( os.listdir(os.path.join(&quot;t&quot;, i, ii))[0][0] ) ) ]) </code></pre> <p>I added some spaces in order to make it a bit more readable. td = train_data. Yea, I could've messed something up there.</p> <p>Edit 2: Answering Mohammad's question, there is the output data shape of the code they gave me:</p> <pre><code>td.shape #AttributeError: 'list' object has no attribute 'shape' - main list td[0].shape #AttributeError: 'list' object has no attribute 'shape' - sublist, with a list and a label td[0][0].shape #AttributeError: 'list' object has no attribute 'shape' - subsublist, with 2 images td[0][1].shape #TensorShape([]) - label td[0][0][0].shape #TensorShape([1, 105, 105, 3]) - first image td[0][0][1].shape #TensorShape([1, 105, 105, 3]) - second image </code></pre> <p>It can be shown as:</p> <pre><code>train_data = [ [[x1, x2], y], [[x1, x2], y], ... ] </code></pre>
[ { "answer_id": 74581285, "author": "Mohammad Ahmed", "author_id": 7746219, "author_profile": "https://Stackoverflow.com/users/7746219", "pm_score": 1, "selected": true, "text": "x1 = tf.random.normal((105, 105, 3))\nx2 = tf.random.normal((105, 105, 3))\ny = tf.random.normal((1,))\n\ntrain_list = [[[x1,x2] , y] , [[x1,x2] , y] , [[x1,x2] , y] , [[x1,x2] , y]]\n\nx1 = [train_list[x][:1][0][0] for x in range(len(train_list))]\nx2 = [train_list[x][:1][0][1] for x in range(len(train_list))]\ny = [train_list[x][1:] for x in range(len(train_list))]\n\ntf.data.Dataset.from_tensor_slices(((x1 , x2) , y))\n <TensorSliceDataset element_spec=((TensorSpec(shape=(105, 105, 3), dtype=tf.float32, name=None), TensorSpec(shape=(105, 105, 3), dtype=tf.float32, name=None)), TensorSpec(shape=(1, 1), dtype=tf.float32, name=None))>\n Or Change the Code when you are Loading Images and Labels from Disks x1 = []\nx2 = []\ny = []\nfor i in os.listdir(\"t\"):\n for ii in os.listdir(os.path.join(\"t\", i)):\n x1.append(\n tensorflow.expand_dims(\n tensorflow.io.decode_jpeg(\n tensorflow.io.read_file(os.path.join(\"t\", i, ii) + \"\\\\\" + os.listdir(os.path.join(\"t\", i, ii))[0])) / 255, 0))\n x2.append(tensorflow.expand_dims(\n tensorflow.io.decode_jpeg(\n tensorflow.io.read_file(os.path.join(\"t\", i, ii) + \"\\\\2.jpeg\")) / 255, 0)\n )\n y.append(tensorflow.convert_to_tensor(\n float(\n os.listdir(os.path.join(\"t\", i, ii))[0][0]\n )\n ))\n tf.data.Dataset.from_tensor_slices(((x1 , x2) , y))\n" }, { "answer_id": 74581762, "author": "V.M", "author_id": 8143158, "author_profile": "https://Stackoverflow.com/users/8143158", "pm_score": 1, "selected": false, "text": "x1 = tf.random.normal((105,105,3))\nx2 = tf.random.normal((105,105,3))\ny = tf.random.normal((1,))\n\narray_list = [[x1, x2, y]] * 560\ntf.data.Dataset.from_tensor_slices(array_list)\n#InvalidArgumentError ... values[0].shape = [105,105,3] != values[2].shape = [1]\n #flatten to a single list\nflatten_list = sum(array_list, [])\n\n#Separate features and labels \nX = tf.squeeze(tf.stack(flatten_list[::3]))\ny = tf.squeeze(tf.stack(flatten_list[2::3]))\n\n#construct dataset iterator\nds = tf.data.Dataset.from_tensor_slices((X, y))\nfor data in ds.take(1):\n print(data)\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17579568/" ]
74,581,247
<p>Suppose I have 3 buttons:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.all-buttons{ display:flex; width: 100% } .bttn{ width: 33% border: none; background-color: blue; padding: 20px 20px; color: white; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt; &lt;head&gt;&lt;title&gt;yes&lt;/title&gt;&lt;/head&gt; &lt;body&gt; &lt;div class="all-buttons"&gt; &lt;button class="bttn"&gt;BUTTON1&lt;/button&gt; &lt;button class="bttn"&gt;BUTTON2&lt;/button&gt; &lt;button class="bttn"&gt;BUTTON3&lt;/button&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>As of my understanding I can use JavaScript <code>const buttons = document.querySelectorAll('bttn');</code> which will create an array with every element with the class <code>'bttn'</code>. How do I change the style of a button? For example, say I want to change the background-color of Button2 if I click on it. How do I get Button2 using classes in javascript? I have tried this:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const buttons = document.querySelectorAll('link'); Array.from(buttons).forEach(el =&gt; { el.addEventListener('click', function(event) { //code }); });</code></pre> </div> </div> </p> <p>My end goal is to create a drop-down menu for each of the buttons but I would like to avoid adding an id for each button. Any input is appreciated.</p>
[ { "answer_id": 74581263, "author": "Emre", "author_id": 6468955, "author_profile": "https://Stackoverflow.com/users/6468955", "pm_score": 1, "selected": false, "text": "const buttons = document.querySelectorAll('.bttn'); // You must declare element's type; class (.) or id (#).\n\nArray.from(buttons).forEach(el => {\n el.addEventListener('click', function(event) {\n el.style.color = \"red\"; // Added the line for changing the style of the button.\n });\n}); <button class=\"bttn\">BUTTON1</button>\n<button class=\"bttn\">BUTTON2</button>\n<button class=\"bttn\">BUTTON3</button>" }, { "answer_id": 74581273, "author": "Amirhossein", "author_id": 11342834, "author_profile": "https://Stackoverflow.com/users/11342834", "pm_score": 3, "selected": true, "text": "const buttons = document.getElementsByClassName('bttn');\n const buttons = document.querySelectorAll('.bttn');\n element.style.backgroundColor = 'blue';\n const buttons = document.querySelectorAll('.bttn');\n\nArray.from(buttons).forEach(el => {\n el.addEventListener('click', function(event) {\n el.style.backgroundColor = \"blue\";\n });\n});\n" }, { "answer_id": 74581282, "author": "Mina", "author_id": 11887902, "author_profile": "https://Stackoverflow.com/users/11887902", "pm_score": 2, "selected": false, "text": "document.querySelectorAll('bttn'); .bttn bttn . document.querySelectorAll('.bttn'); forEach button addEventListener click style classList const buttons = document.querySelectorAll('.bttn');\n\nbuttons.forEach(button => {\n button.addEventListener('click', () => {\n button.classList.toggle('red');\n })\n}) .all-buttons{\n display:flex;\n width: 100%\n }\n .bttn{\n width: 33%\n border: none;\n background-color: blue;\n padding: 20px 20px;\ncolor: white;\n }\n\n.red {\n background-color: red;\n} <html>\n<head><title>yes</title></head>\n<body>\n<div class=\"all-buttons\">\n <button class=\"bttn\">BUTTON1</button>\n <button class=\"bttn\">BUTTON2</button>\n <button class=\"bttn\">BUTTON3</button>\n</div>\n</body>\n</html>" }, { "answer_id": 74581377, "author": "MAYUR SANCHETI", "author_id": 12238257, "author_profile": "https://Stackoverflow.com/users/12238257", "pm_score": 1, "selected": false, "text": "const nodeList = document.querySelectorAll(\".dropbtn\");\n const submenuList = document.querySelectorAll(\".dropdown-content\");\n\n //alert(nodeList.length);\n for (let i = 0; i < nodeList.length; i++) {\n \n nodeList[i].addEventListener('click', function(event) {\n submenuList[i].classList.toggle(\"show\");\n \n });\n \n \n } .dropbtn {\n background-color: #3498DB;\n color: white;\n padding: 16px;\n font-size: 16px;\n border: none;\n cursor: pointer;\n}\n\n\n.dropbtn:hover, .dropbtn:focus {\n background-color: #2980B9;\n}\n\n\n.dropdown {\n position: relative;\n display: inline-block;\n}\n\n\n.dropdown-content {\n display: none;\n position: absolute;\n background-color: #f1f1f1;\n min-width: 160px;\n box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);\n z-index: 1;\n}\n\n\n.dropdown-content a {\n color: black;\n padding: 12px 16px;\n text-decoration: none;\n display: block;\n}\n\n\n.dropdown-content a:hover {background-color: #ddd}\n\n.show {display:block;} <div class=\"dropdown\">\n <button class=\"dropbtn\">Dropdown</button>\n <div class=\"dropdown-content\">\n <a href=\"#\">Link 1</a>\n <a href=\"#\">Link 2</a>\n <a href=\"#\">Link 3</a>\n </div>\n </div>\n\n <div class=\"dropdown\">\n <button class=\"dropbtn\">Dropdown</button>\n <div class=\"dropdown-content\">\n <a href=\"#\">Link- 1</a>\n <a href=\"#\">Link- 2</a>\n <a href=\"#\">Link- 3</a>\n </div>\n </div>" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19217750/" ]
74,581,249
<p>When deserializing a string, the curly braces are duplicating and this is disturbing the reading of some fields. I've tried everything, but I can't serialize correctly, without duplicate curly braces.</p> <p>I already tried to do it like this:</p> <pre><code>dynamic values = JsonConvert.DeserializeObject&lt;dynamic&gt;(storedEvent.Data); </code></pre> <p>The storedEvent.Data property is of type string and contains this information:</p> <pre><code>&quot;{\&quot;PaisId\&quot;:31,\&quot;PaisDivisaoAdministrativaNivelRemovedEventList\&quot;:[{\&quot;Id\&quot;:6,\&quot;PaisId\&quot;:31,\&quot;PaisNomePtBr\&quot;:\&quot;\&quot;,\&quot;PaisDivisaoAdministrativaTipoId\&quot;:5,\&quot;PaisDivisaoAdministrativaTipoNome\&quot;:\&quot;Município\&quot;,\&quot;PaisDivisaoAdministrativaTipoOrigemId\&quot;:5,\&quot;Timestamp\&quot;:\&quot;2022-11-24T20:16:15.6020289-03:00\&quot;,\&quot;MessageType\&quot;:\&quot;PaisDivisaoAdministrativaNivelRemovedEvent\&quot;,\&quot;AggregateId\&quot;:6},{\&quot;Id\&quot;:5,\&quot;PaisId\&quot;:31,\&quot;PaisNomePtBr\&quot;:\&quot;\&quot;,\&quot;PaisDivisaoAdministrativaTipoId\&quot;:1,\&quot;PaisDivisaoAdministrativaTipoNome\&quot;:\&quot;Estado\&quot;,\&quot;PaisDivisaoAdministrativaTipoOrigemId\&quot;:null,\&quot;Timestamp\&quot;:\&quot;2022-11-24T20:16:15.6580242-03:00\&quot;,\&quot;MessageType\&quot;:\&quot;PaisDivisaoAdministrativaNivelRemovedEvent\&quot;,\&quot;AggregateId\&quot;:5}],\&quot;Timestamp\&quot;:\&quot;2022-11-24T20:16:16.1892039-03:00\&quot;,\&quot;MessageType\&quot;:\&quot;PaisDivisaoAdministrativaNivelHierarquiasRemovedEvent\&quot;,\&quot;AggregateId\&quot;:31}&quot; </code></pre> <p>Result obtained (Duplicate curly braces):</p> <pre><code>{{ &quot;PaisId&quot;: 31, &quot;PaisDivisaoAdministrativaNivelRemovedEventList&quot;: [ { &quot;Id&quot;: 6, &quot;PaisId&quot;: 31, &quot;PaisNomePtBr&quot;: &quot;&quot;, &quot;PaisDivisaoAdministrativaTipoId&quot;: 5, &quot;PaisDivisaoAdministrativaTipoNome&quot;: &quot;Município&quot;, &quot;PaisDivisaoAdministrativaTipoOrigemId&quot;: 5, &quot;Timestamp&quot;: &quot;2022-11-24T20:16:15.6020289-03:00&quot;, &quot;MessageType&quot;: &quot;PaisDivisaoAdministrativaNivelRemovedEvent&quot;, &quot;AggregateId&quot;: 6 }, { &quot;Id&quot;: 5, &quot;PaisId&quot;: 31, &quot;PaisNomePtBr&quot;: &quot;&quot;, &quot;PaisDivisaoAdministrativaTipoId&quot;: 1, &quot;PaisDivisaoAdministrativaTipoNome&quot;: &quot;Estado&quot;, &quot;PaisDivisaoAdministrativaTipoOrigemId&quot;: null, &quot;Timestamp&quot;: &quot;2022-11-24T20:16:15.6580242-03:00&quot;, &quot;MessageType&quot;: &quot;PaisDivisaoAdministrativaNivelRemovedEvent&quot;, &quot;AggregateId&quot;: 5 } ], &quot;Timestamp&quot;: &quot;2022-11-24T20:16:16.1892039-03:00&quot;, &quot;MessageType&quot;: &quot;PaisDivisaoAdministrativaNivelHierarquiasRemovedEvent&quot;, &quot;AggregateId&quot;: 31 }} </code></pre> <p>Expected:</p> <pre><code>{ &quot;PaisId&quot;: 31, &quot;PaisDivisaoAdministrativaNivelRemovedEventList&quot;: [ { &quot;Id&quot;: 6, &quot;PaisId&quot;: 31, &quot;PaisNomePtBr&quot;: &quot;&quot;, &quot;PaisDivisaoAdministrativaTipoId&quot;: 5, &quot;PaisDivisaoAdministrativaTipoNome&quot;: &quot;Município&quot;, &quot;PaisDivisaoAdministrativaTipoOrigemId&quot;: 5, &quot;Timestamp&quot;: &quot;2022-11-24T20:16:15.6020289-03:00&quot;, &quot;MessageType&quot;: &quot;PaisDivisaoAdministrativaNivelRemovedEvent&quot;, &quot;AggregateId&quot;: 6 }, { &quot;Id&quot;: 5, &quot;PaisId&quot;: 31, &quot;PaisNomePtBr&quot;: &quot;&quot;, &quot;PaisDivisaoAdministrativaTipoId&quot;: 1, &quot;PaisDivisaoAdministrativaTipoNome&quot;: &quot;Estado&quot;, &quot;PaisDivisaoAdministrativaTipoOrigemId&quot;: null, &quot;Timestamp&quot;: &quot;2022-11-24T20:16:15.6580242-03:00&quot;, &quot;MessageType&quot;: &quot;PaisDivisaoAdministrativaNivelRemovedEvent&quot;, &quot;AggregateId&quot;: 5 } ], &quot;Timestamp&quot;: &quot;2022-11-24T20:16:16.1892039-03:00&quot;, &quot;MessageType&quot;: &quot;PaisDivisaoAdministrativaNivelHierarquiasRemovedEvent&quot;, &quot;AggregateId&quot;: 31 } </code></pre> <p>Does anyone know of a solution?</p>
[ { "answer_id": 74581263, "author": "Emre", "author_id": 6468955, "author_profile": "https://Stackoverflow.com/users/6468955", "pm_score": 1, "selected": false, "text": "const buttons = document.querySelectorAll('.bttn'); // You must declare element's type; class (.) or id (#).\n\nArray.from(buttons).forEach(el => {\n el.addEventListener('click', function(event) {\n el.style.color = \"red\"; // Added the line for changing the style of the button.\n });\n}); <button class=\"bttn\">BUTTON1</button>\n<button class=\"bttn\">BUTTON2</button>\n<button class=\"bttn\">BUTTON3</button>" }, { "answer_id": 74581273, "author": "Amirhossein", "author_id": 11342834, "author_profile": "https://Stackoverflow.com/users/11342834", "pm_score": 3, "selected": true, "text": "const buttons = document.getElementsByClassName('bttn');\n const buttons = document.querySelectorAll('.bttn');\n element.style.backgroundColor = 'blue';\n const buttons = document.querySelectorAll('.bttn');\n\nArray.from(buttons).forEach(el => {\n el.addEventListener('click', function(event) {\n el.style.backgroundColor = \"blue\";\n });\n});\n" }, { "answer_id": 74581282, "author": "Mina", "author_id": 11887902, "author_profile": "https://Stackoverflow.com/users/11887902", "pm_score": 2, "selected": false, "text": "document.querySelectorAll('bttn'); .bttn bttn . document.querySelectorAll('.bttn'); forEach button addEventListener click style classList const buttons = document.querySelectorAll('.bttn');\n\nbuttons.forEach(button => {\n button.addEventListener('click', () => {\n button.classList.toggle('red');\n })\n}) .all-buttons{\n display:flex;\n width: 100%\n }\n .bttn{\n width: 33%\n border: none;\n background-color: blue;\n padding: 20px 20px;\ncolor: white;\n }\n\n.red {\n background-color: red;\n} <html>\n<head><title>yes</title></head>\n<body>\n<div class=\"all-buttons\">\n <button class=\"bttn\">BUTTON1</button>\n <button class=\"bttn\">BUTTON2</button>\n <button class=\"bttn\">BUTTON3</button>\n</div>\n</body>\n</html>" }, { "answer_id": 74581377, "author": "MAYUR SANCHETI", "author_id": 12238257, "author_profile": "https://Stackoverflow.com/users/12238257", "pm_score": 1, "selected": false, "text": "const nodeList = document.querySelectorAll(\".dropbtn\");\n const submenuList = document.querySelectorAll(\".dropdown-content\");\n\n //alert(nodeList.length);\n for (let i = 0; i < nodeList.length; i++) {\n \n nodeList[i].addEventListener('click', function(event) {\n submenuList[i].classList.toggle(\"show\");\n \n });\n \n \n } .dropbtn {\n background-color: #3498DB;\n color: white;\n padding: 16px;\n font-size: 16px;\n border: none;\n cursor: pointer;\n}\n\n\n.dropbtn:hover, .dropbtn:focus {\n background-color: #2980B9;\n}\n\n\n.dropdown {\n position: relative;\n display: inline-block;\n}\n\n\n.dropdown-content {\n display: none;\n position: absolute;\n background-color: #f1f1f1;\n min-width: 160px;\n box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);\n z-index: 1;\n}\n\n\n.dropdown-content a {\n color: black;\n padding: 12px 16px;\n text-decoration: none;\n display: block;\n}\n\n\n.dropdown-content a:hover {background-color: #ddd}\n\n.show {display:block;} <div class=\"dropdown\">\n <button class=\"dropbtn\">Dropdown</button>\n <div class=\"dropdown-content\">\n <a href=\"#\">Link 1</a>\n <a href=\"#\">Link 2</a>\n <a href=\"#\">Link 3</a>\n </div>\n </div>\n\n <div class=\"dropdown\">\n <button class=\"dropbtn\">Dropdown</button>\n <div class=\"dropdown-content\">\n <a href=\"#\">Link- 1</a>\n <a href=\"#\">Link- 2</a>\n <a href=\"#\">Link- 3</a>\n </div>\n </div>" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15291518/" ]
74,581,270
<p>I'm trying to make a card with some elements. However it is hard to locate elements in right place with multiple rows and columns. I tried with mainAxisAlignment, crossAxisAlignment, SizedBox, Expanded and so on. Especially using Expanded make my widget disappear unlike my expectation. How can I locate element to right place?</p> <p><a href="https://i.stack.imgur.com/7Nw4e.png" rel="nofollow noreferrer">What I did</a> <a href="https://i.stack.imgur.com/tjBf6.png" rel="nofollow noreferrer">What I want</a></p> <pre><code>child: Container( padding: EdgeInsets.all(10), child: Column( children:[ Text('1'), Container( child: Row( children:[ ClipRRect( borderRadius: BorderRadius.circular(50), child: Container( width: 70, height: 70, color: Color(0xffD9D9D9), ), ), Column( children:[ Row( children:[ Text('2'), Text('3'), Text('4'), ], ), Row( children:[ Text('5'), Text('6') ] ), Row( children:[ Text('7'), Text('8'), Text('9'), Text('10'), ], ), ], ), ], ), ), ], ), ), </code></pre>
[ { "answer_id": 74581263, "author": "Emre", "author_id": 6468955, "author_profile": "https://Stackoverflow.com/users/6468955", "pm_score": 1, "selected": false, "text": "const buttons = document.querySelectorAll('.bttn'); // You must declare element's type; class (.) or id (#).\n\nArray.from(buttons).forEach(el => {\n el.addEventListener('click', function(event) {\n el.style.color = \"red\"; // Added the line for changing the style of the button.\n });\n}); <button class=\"bttn\">BUTTON1</button>\n<button class=\"bttn\">BUTTON2</button>\n<button class=\"bttn\">BUTTON3</button>" }, { "answer_id": 74581273, "author": "Amirhossein", "author_id": 11342834, "author_profile": "https://Stackoverflow.com/users/11342834", "pm_score": 3, "selected": true, "text": "const buttons = document.getElementsByClassName('bttn');\n const buttons = document.querySelectorAll('.bttn');\n element.style.backgroundColor = 'blue';\n const buttons = document.querySelectorAll('.bttn');\n\nArray.from(buttons).forEach(el => {\n el.addEventListener('click', function(event) {\n el.style.backgroundColor = \"blue\";\n });\n});\n" }, { "answer_id": 74581282, "author": "Mina", "author_id": 11887902, "author_profile": "https://Stackoverflow.com/users/11887902", "pm_score": 2, "selected": false, "text": "document.querySelectorAll('bttn'); .bttn bttn . document.querySelectorAll('.bttn'); forEach button addEventListener click style classList const buttons = document.querySelectorAll('.bttn');\n\nbuttons.forEach(button => {\n button.addEventListener('click', () => {\n button.classList.toggle('red');\n })\n}) .all-buttons{\n display:flex;\n width: 100%\n }\n .bttn{\n width: 33%\n border: none;\n background-color: blue;\n padding: 20px 20px;\ncolor: white;\n }\n\n.red {\n background-color: red;\n} <html>\n<head><title>yes</title></head>\n<body>\n<div class=\"all-buttons\">\n <button class=\"bttn\">BUTTON1</button>\n <button class=\"bttn\">BUTTON2</button>\n <button class=\"bttn\">BUTTON3</button>\n</div>\n</body>\n</html>" }, { "answer_id": 74581377, "author": "MAYUR SANCHETI", "author_id": 12238257, "author_profile": "https://Stackoverflow.com/users/12238257", "pm_score": 1, "selected": false, "text": "const nodeList = document.querySelectorAll(\".dropbtn\");\n const submenuList = document.querySelectorAll(\".dropdown-content\");\n\n //alert(nodeList.length);\n for (let i = 0; i < nodeList.length; i++) {\n \n nodeList[i].addEventListener('click', function(event) {\n submenuList[i].classList.toggle(\"show\");\n \n });\n \n \n } .dropbtn {\n background-color: #3498DB;\n color: white;\n padding: 16px;\n font-size: 16px;\n border: none;\n cursor: pointer;\n}\n\n\n.dropbtn:hover, .dropbtn:focus {\n background-color: #2980B9;\n}\n\n\n.dropdown {\n position: relative;\n display: inline-block;\n}\n\n\n.dropdown-content {\n display: none;\n position: absolute;\n background-color: #f1f1f1;\n min-width: 160px;\n box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);\n z-index: 1;\n}\n\n\n.dropdown-content a {\n color: black;\n padding: 12px 16px;\n text-decoration: none;\n display: block;\n}\n\n\n.dropdown-content a:hover {background-color: #ddd}\n\n.show {display:block;} <div class=\"dropdown\">\n <button class=\"dropbtn\">Dropdown</button>\n <div class=\"dropdown-content\">\n <a href=\"#\">Link 1</a>\n <a href=\"#\">Link 2</a>\n <a href=\"#\">Link 3</a>\n </div>\n </div>\n\n <div class=\"dropdown\">\n <button class=\"dropbtn\">Dropdown</button>\n <div class=\"dropdown-content\">\n <a href=\"#\">Link- 1</a>\n <a href=\"#\">Link- 2</a>\n <a href=\"#\">Link- 3</a>\n </div>\n </div>" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19358943/" ]
74,581,276
<p>We have a kubebuilder controller which is working as expected, now we need to create a webhooks ,</p> <p>I follow the tutorial <a href="https://book.kubebuilder.io/reference/markers/webhook.html" rel="nofollow noreferrer">https://book.kubebuilder.io/reference/markers/webhook.html</a> and now I want to run &amp; debug it locally, however not sure what to do regard the certificate, is there a simple way to create it , any example will be very helpful.</p> <p>BTW i've installed <a href="https://cert-manager.io/docs/installation/helm/" rel="nofollow noreferrer">cert-manager</a> and apply the following sample yaml but not sure what to do next ...</p> <p>I need <strong>the simplest solution</strong> that I be able to run and debug the <code>webhook</code>s <strong>locally</strong> as Im doing already with the controller (Before using webhooks),</p> <p><a href="https://book.kubebuilder.io/cronjob-tutorial/running.html" rel="nofollow noreferrer">https://book.kubebuilder.io/cronjob-tutorial/running.html</a></p> <p>Cert-manager</p> <p>I've created the following inside my cluster</p> <pre><code>apiVersion: cert-manager.io/v1 kind: Certificate metadata: name: example-com namespace: test spec: # Secret names are always required. secretName: example-com-tls # secretTemplate is optional. If set, these annotations and labels will be # copied to the Secret named example-com-tls. These labels and annotations will # be re-reconciled if the Certificate's secretTemplate changes. secretTemplate # is also enforced, so relevant label and annotation changes on the Secret by a # third party will be overwriten by cert-manager to match the secretTemplate. secretTemplate: annotations: my-secret-annotation-1: &quot;foo&quot; my-secret-annotation-2: &quot;bar&quot; labels: my-secret-label: foo duration: 2160h # 90d renewBefore: 360h # 15d subject: organizations: - jetstack # The use of the common name field has been deprecated since 2000 and is # discouraged from being used. commonName: example.com isCA: false privateKey: algorithm: RSA encoding: PKCS1 size: 2048 usages: - server auth - client auth # At least one of a DNS Name, URI, or IP address is required. dnsNames: - example.com - www.example.com uris: - spiffe://cluster.local/ns/sandbox/sa/example ipAddresses: - 192.168.0.5 # Issuer references are always required. issuerRef: name: ca-issuer # We can reference ClusterIssuers by changing the kind here. # The default value is Issuer (i.e. a locally namespaced Issuer) kind: Issuer # This is optional since cert-manager will default to this value however # if you are using an external issuer, change this to that issuer group. group: cert-manager.io </code></pre> <p>Still not sure how to sync it with the kubebuilder to work locally</p> <p>as when I run the operator in debug mode I got the following error:</p> <p><code>setup problem running manager {&quot;error&quot;: &quot;open /var/folders/vh/_418c55133sgjrwr7n0d7bl40000gn/T/k8s-webhook-server/serving-certs/tls.crt: no such file or directory&quot;} </code></p> <p><strong>What I need is the <strong>simplest way</strong> to run webhooks <strong>locally</strong></strong></p>
[ { "answer_id": 74581263, "author": "Emre", "author_id": 6468955, "author_profile": "https://Stackoverflow.com/users/6468955", "pm_score": 1, "selected": false, "text": "const buttons = document.querySelectorAll('.bttn'); // You must declare element's type; class (.) or id (#).\n\nArray.from(buttons).forEach(el => {\n el.addEventListener('click', function(event) {\n el.style.color = \"red\"; // Added the line for changing the style of the button.\n });\n}); <button class=\"bttn\">BUTTON1</button>\n<button class=\"bttn\">BUTTON2</button>\n<button class=\"bttn\">BUTTON3</button>" }, { "answer_id": 74581273, "author": "Amirhossein", "author_id": 11342834, "author_profile": "https://Stackoverflow.com/users/11342834", "pm_score": 3, "selected": true, "text": "const buttons = document.getElementsByClassName('bttn');\n const buttons = document.querySelectorAll('.bttn');\n element.style.backgroundColor = 'blue';\n const buttons = document.querySelectorAll('.bttn');\n\nArray.from(buttons).forEach(el => {\n el.addEventListener('click', function(event) {\n el.style.backgroundColor = \"blue\";\n });\n});\n" }, { "answer_id": 74581282, "author": "Mina", "author_id": 11887902, "author_profile": "https://Stackoverflow.com/users/11887902", "pm_score": 2, "selected": false, "text": "document.querySelectorAll('bttn'); .bttn bttn . document.querySelectorAll('.bttn'); forEach button addEventListener click style classList const buttons = document.querySelectorAll('.bttn');\n\nbuttons.forEach(button => {\n button.addEventListener('click', () => {\n button.classList.toggle('red');\n })\n}) .all-buttons{\n display:flex;\n width: 100%\n }\n .bttn{\n width: 33%\n border: none;\n background-color: blue;\n padding: 20px 20px;\ncolor: white;\n }\n\n.red {\n background-color: red;\n} <html>\n<head><title>yes</title></head>\n<body>\n<div class=\"all-buttons\">\n <button class=\"bttn\">BUTTON1</button>\n <button class=\"bttn\">BUTTON2</button>\n <button class=\"bttn\">BUTTON3</button>\n</div>\n</body>\n</html>" }, { "answer_id": 74581377, "author": "MAYUR SANCHETI", "author_id": 12238257, "author_profile": "https://Stackoverflow.com/users/12238257", "pm_score": 1, "selected": false, "text": "const nodeList = document.querySelectorAll(\".dropbtn\");\n const submenuList = document.querySelectorAll(\".dropdown-content\");\n\n //alert(nodeList.length);\n for (let i = 0; i < nodeList.length; i++) {\n \n nodeList[i].addEventListener('click', function(event) {\n submenuList[i].classList.toggle(\"show\");\n \n });\n \n \n } .dropbtn {\n background-color: #3498DB;\n color: white;\n padding: 16px;\n font-size: 16px;\n border: none;\n cursor: pointer;\n}\n\n\n.dropbtn:hover, .dropbtn:focus {\n background-color: #2980B9;\n}\n\n\n.dropdown {\n position: relative;\n display: inline-block;\n}\n\n\n.dropdown-content {\n display: none;\n position: absolute;\n background-color: #f1f1f1;\n min-width: 160px;\n box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);\n z-index: 1;\n}\n\n\n.dropdown-content a {\n color: black;\n padding: 12px 16px;\n text-decoration: none;\n display: block;\n}\n\n\n.dropdown-content a:hover {background-color: #ddd}\n\n.show {display:block;} <div class=\"dropdown\">\n <button class=\"dropbtn\">Dropdown</button>\n <div class=\"dropdown-content\">\n <a href=\"#\">Link 1</a>\n <a href=\"#\">Link 2</a>\n <a href=\"#\">Link 3</a>\n </div>\n </div>\n\n <div class=\"dropdown\">\n <button class=\"dropbtn\">Dropdown</button>\n <div class=\"dropdown-content\">\n <a href=\"#\">Link- 1</a>\n <a href=\"#\">Link- 2</a>\n <a href=\"#\">Link- 3</a>\n </div>\n </div>" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11154975/" ]
74,581,314
<p>I have mapped a field <strong><code>userEmailid</code></strong> in JOLT but that field is not showing put in the output.</p> <p>Main Snippet :</p> <pre class="lang-json prettyprint-override"><code>&quot;WG_REQUESTOR_EMAIL&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities. integrationEntity.integrationEntityDetails.poDetails.items.item.requesterDetails. userEmailId&quot;, </code></pre> <p>Input :</p> <pre class="lang-json prettyprint-override"><code>{ &quot;PURCHASE_ORDER_DISPATCH&quot;: { &quot;MsgData&quot;: { &quot;Transaction&quot;: { &quot;PO_POD_HDR_EVW1&quot;: { &quot;WG_ADDR_SEQ_NUM&quot;: 1, &quot;WG_PO_CNTCT_EMAIL&quot;: &quot;PeggyMeincke@westfieldgrp.com&quot;, &quot;WG_REQUESTOR_EMAIL&quot;: &quot;ZacharyEngels@westfieldgrp.com&quot;, &quot;WG_REQ_FIRST_NAME&quot;: &quot;Zachary&quot;, &quot;WG_REQ_LAST_NAME&quot;: &quot;Engels&quot;, &quot;WG_DELIVER_TO&quot;: &quot;ZacharyEngels@westfieldgrp.com&quot;, &quot;BUSINESS_UNIT&quot;: &quot;OFIC&quot;, &quot;PO_ID&quot;: 25052, &quot;VENDOR_SETID&quot;: &quot;WCOS&quot;, &quot;VENDOR_ID&quot;: 35958, &quot;VNDR_LOC&quot;: 1, &quot;PO_DT&quot;: &quot;2020-01-24&quot;, &quot;DB_NUMBER_BU&quot;: &quot;&quot;, &quot;DESCR_BU&quot;: &quot;OhioFarmersInsuranceCo&quot;, &quot;ADDRESS1_BU&quot;: &quot;WESTFIELDCOMPANIES&quot;, &quot;ADDRESS2_BU&quot;: &quot;HOMEOFFICE&quot;, &quot;ADDRESS3_BU&quot;: &quot;1PARKCIRCLE&quot;, &quot;ADDRESS4_BU&quot;: &quot;&quot;, &quot;CITY_BU&quot;: &quot;WESTFIELDCENTER&quot;, &quot;STATE_BU&quot;: &quot;OH&quot;, &quot;POSTAL_BU&quot;: &quot;44251-5001&quot;, &quot;COUNTRY_BU&quot;: &quot;USA&quot;, &quot;ADDRESS1_BILL&quot;: &quot;&quot;, &quot;ADDRESS2_BILL&quot;: &quot;&quot;, &quot;ADDRESS3_BILL&quot;: &quot;&quot;, &quot;ADDRESS4_BILL&quot;: &quot;&quot;, &quot;CITY_BILL&quot;: &quot;&quot;, &quot;STATE_BILL&quot;: &quot;&quot;, &quot;POSTAL_BILL&quot;: &quot;&quot;, &quot;COUNTRY_BILL&quot;: &quot;&quot;, &quot;CURRENCY_CD&quot;: &quot;USD&quot;, &quot;TAX_EXEMPT_ID&quot;: &quot;&quot;, &quot;STD_ID_NUM_VNDR&quot;: &quot;&quot;, &quot;NAME1_VNDR&quot;: &quot;AMAZONCAPITALSERVICESINC&quot;, &quot;ADDRESS1_VNDR&quot;: &quot;410TERRYAVEN&quot;, &quot;ADDRESS2_VNDR&quot;: &quot;&quot;, &quot;ADDRESS3_VNDR&quot;: &quot;&quot;, &quot;ADDRESS4_VNDR&quot;: &quot;&quot;, &quot;CITY_VNDR&quot;: &quot;SEATTLE&quot;, &quot;STATE_VNDR&quot;: &quot;WA&quot;, &quot;POSTAL_VNDR&quot;: 98109, &quot;COUNTRY_VNDR&quot;: &quot;USA&quot;, &quot;PYMNT_TERMS_CD&quot;: &quot;NET30&quot;, &quot;DESCR50_PAY&quot;: &quot;Net30&quot;, &quot;BUYER_ID&quot;: 1083, &quot;PO_AMT_TTL&quot;: 14.99, &quot;TEXT254_CC1&quot;: &quot;&quot;, &quot;TEXT254_CC2&quot;: &quot;&quot;, &quot;VNDR_UPN_FLG&quot;: &quot;N&quot;, &quot;STD_ID_NUM_VNDRGLN&quot;: &quot;&quot;, &quot;STD_ID_NUM_BILLTO&quot;: &quot;&quot;, &quot;ATTN_TO&quot;: &quot;ZacharyEngels&quot;, &quot;PO_POD_LN_EVW1&quot;: { &quot;WG_REQ_ID&quot;: 25694, &quot;WG_CATEGORY_CD&quot;: &quot;FSSUP&quot;, &quot;WG_ITEM_TYPE&quot;: 0, &quot;WG_ACCOUNT&quot;: 641100, &quot;WG_DEPT_ID&quot;: 30400, &quot;WG_PRODUCT&quot;: &quot;&quot;, &quot;BUSINESS_UNIT&quot;: &quot;OFIC&quot;, &quot;PO_ID&quot;: 25052, &quot;WG_ASSET_GROUP&quot;: &quot;&quot;, &quot;WG_CAPITALIZE&quot;: &quot;NO&quot;, &quot;WG_PROFILE_ID&quot;: &quot;&quot;, &quot;WG_SPLIT_TYPE&quot;: 1, &quot;WG_ASSET_LOC&quot;: &quot;HOME&quot;, &quot;WG_PROJECT&quot;: &quot;&quot;, &quot;VENDOR_SETID&quot;: &quot;WCOS&quot;, &quot;VENDOR_ID&quot;: 35958, &quot;VNDR_LOC&quot;: 1, &quot;LINE_NBR&quot;: 1, &quot;INV_ITEM_ID&quot;: &quot;&quot;, &quot;DESCR254_MIXED&quot;: &quot;147-1518156-3620845,1GreenMountainCoffeeRoastersCaramelVanillaCreamKeurigSingle-ServeK-CupPods,LightRoastCoffee,32Count&quot;, &quot;UNIT_OF_MEASURE&quot;: &quot;EA&quot;, &quot;ITM_ID_VNDR&quot;: &quot;B0798CX2Q9&quot;, &quot;INV_ITEM_WEIGHT&quot;: 0, &quot;INV_ITEM_HEIGHT&quot;: 0, &quot;INV_ITEM_VOLUME&quot;: 0, &quot;INV_ITEM_LENGTH&quot;: 0, &quot;INV_ITEM_WIDTH&quot;: 0, &quot;VNDR_CATALOG_ID&quot;: &quot;&quot;, &quot;MFG_ID&quot;: &quot;&quot;, &quot;MFG_ITM_ID&quot;: 5000196305, &quot;CNTRCT_ID&quot;: &quot;&quot;, &quot;VERSION_NBR&quot;: 0, &quot;CNTRCT_LINE_NBR&quot;: 0, &quot;CAT_LINE_NBR&quot;: 0, &quot;RELEASE_NBR&quot;: 0, &quot;CANCEL_STATUS&quot;: &quot;A&quot;, &quot;UPN_ID&quot;: &quot;&quot;, &quot;PO_POD_SHP_EVW1&quot;: { &quot;WG_SHIP_ADDR_TYPE&quot;: 0, &quot;WG_CUST_ADDR_CODE&quot;: &quot;OFIC&quot;, &quot;BUSINESS_UNIT&quot;: &quot;OFIC&quot;, &quot;PO_ID&quot;: 25052, &quot;VENDOR_SETID&quot;: &quot;WCOS&quot;, &quot;VENDOR_ID&quot;: 35958, &quot;VNDR_LOC&quot;: 1, &quot;LINE_NBR&quot;: 1, &quot;SCHED_NBR&quot;: 1, &quot;DUE_DT&quot;: &quot;2020-01-29&quot;, &quot;SHIPTO_ID&quot;: &quot;OFIC&quot;, &quot;DESCR_SHIPTO&quot;: &quot;OHIOFARMERSINSURANCECOMPANY&quot;, &quot;ADDRESS1_SHIPTO&quot;: &quot;OHIOFARMERSINSURANCECOMPANY&quot;, &quot;ADDRESS2_SHIPTO&quot;: &quot;1PARKCIRCLE&quot;, &quot;ADDRESS3_SHIPTO&quot;: &quot;POBOX5001&quot;, &quot;ADDRESS4_SHIPTO&quot;: &quot;&quot;, &quot;CITY_SHIPTO&quot;: &quot;WESTFIELDCENTER&quot;, &quot;STATE_SHIPTO&quot;: &quot;OH&quot;, &quot;POSTAL_SHIPTO&quot;: &quot;44251-5001&quot;, &quot;COUNTRY_SHIPTO&quot;: &quot;USA&quot;, &quot;PRICE_PO&quot;: 14.99, &quot;FREIGHT_TERMS&quot;: &quot;FOBDEST&quot;, &quot;QTY_PO&quot;: 1, &quot;SHIP_TYPE_ID&quot;: &quot;BEST_WAY&quot;, &quot;CANCEL_STATUS&quot;: &quot;A&quot;, &quot;ATTN_TO&quot;: &quot;&quot;, &quot;STD_ID_NUM_SHIPTO&quot;: &quot;&quot; }, &quot;PSCAMA&quot;: { &quot;AUDIT_ACTN&quot;: &quot;A&quot; } }, &quot;PSCAMA&quot;: { &quot;AUDIT_ACTN&quot;: &quot;A&quot; } }, &quot;PSCAMA&quot;: { &quot;LANGUAGE_CD&quot;: &quot;ENG&quot;, &quot;AUDIT_ACTN&quot;: &quot;A&quot;, &quot;BASE_LANGUAGE_CD&quot;: &quot;ENG&quot;, &quot;MSG_SEQ_FLG&quot;: &quot;&quot;, &quot;PROCESS_INSTANCE&quot;: 1199010, &quot;PUBLISH_RULE_ID&quot;: &quot;WG_MAIN_RULE&quot;, &quot;MSGNODENAME&quot;: &quot;&quot; } } } } } </code></pre> <p>JOLT Spec :</p> <pre class="lang-json prettyprint-override"><code>[ { &quot;operation&quot;: &quot;shift&quot;, &quot;spec&quot;: { &quot;#UPSERT&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityHeader.action&quot;, &quot;*&quot;: { &quot;*&quot;: { &quot;*&quot;: { &quot;*&quot;: { &quot;PO_ID&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.externalId&quot;, &quot;#APPROVED&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.status&quot;, &quot;PO_AMT_TTL&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.grossTotalAmount&quot;, &quot;WG_REQUESTOR_EMAIL&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.requesterDetails.userEmailId&quot;, &quot;*&quot;: { &quot;WG_REQ_ID&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.poDescription&quot;, &quot;#STANDARD&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.poType&quot;, &quot;*&quot;: { &quot;FREIGHT_TERMS&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.deliveryTermCode&quot; } } } } } } } }, { &quot;operation&quot;: &quot;shift&quot;, &quot;spec&quot;: { &quot;*&quot;: { &quot;*&quot;: { &quot;*&quot;: { &quot;integrationEntityHeader&quot;: &quot;&amp;3.&amp;2.&amp;1.&amp;&quot;, &quot;integrationEntityDetails&quot;: { &quot;*&quot;: { &quot;externalId&quot;: &quot;&amp;5.&amp;4.&amp;3.&amp;2.&amp;1.&amp;&quot;, &quot;status&quot;: &quot;&amp;5.&amp;4.&amp;3.&amp;2.&amp;1.&amp;&quot;, &quot;poHeader&quot;: &quot;&amp;5.&amp;4.&amp;3.&amp;2.&amp;1.&amp;&quot; } } } } } } }, { &quot;operation&quot;: &quot;cardinality&quot;, &quot;spec&quot;: { &quot;*&quot;: { &quot;*&quot;: { &quot;*&quot;: { &quot;*&quot;: { &quot;*&quot;: { &quot;status&quot;: &quot;ONE&quot;, &quot;poHeader&quot;: { &quot;*&quot;: &quot;ONE&quot; } } } } } } } } ] </code></pre> <p>Output :</p> <pre class="lang-json prettyprint-override"><code>{ &quot;integration-inbound:IntegrationDetails&quot;: { &quot;integrationEntities&quot;: { &quot;integrationEntity&quot;: { &quot;integrationEntityHeader&quot;: { &quot;action&quot;: &quot;UPSERT&quot; }, &quot;integrationEntityDetails&quot;: { &quot;poDetails&quot;: { &quot;externalId&quot;: 25052, &quot;status&quot;: &quot;APPROVED&quot;, &quot;poHeader&quot;: { &quot;poType&quot;: &quot;STANDARD&quot;, &quot;grossTotalAmount&quot;: 14.99, &quot;poDescription&quot;: 25694, &quot;deliveryTermCode&quot;: &quot;FOBDEST&quot; } } } } } } } </code></pre>
[ { "answer_id": 74581263, "author": "Emre", "author_id": 6468955, "author_profile": "https://Stackoverflow.com/users/6468955", "pm_score": 1, "selected": false, "text": "const buttons = document.querySelectorAll('.bttn'); // You must declare element's type; class (.) or id (#).\n\nArray.from(buttons).forEach(el => {\n el.addEventListener('click', function(event) {\n el.style.color = \"red\"; // Added the line for changing the style of the button.\n });\n}); <button class=\"bttn\">BUTTON1</button>\n<button class=\"bttn\">BUTTON2</button>\n<button class=\"bttn\">BUTTON3</button>" }, { "answer_id": 74581273, "author": "Amirhossein", "author_id": 11342834, "author_profile": "https://Stackoverflow.com/users/11342834", "pm_score": 3, "selected": true, "text": "const buttons = document.getElementsByClassName('bttn');\n const buttons = document.querySelectorAll('.bttn');\n element.style.backgroundColor = 'blue';\n const buttons = document.querySelectorAll('.bttn');\n\nArray.from(buttons).forEach(el => {\n el.addEventListener('click', function(event) {\n el.style.backgroundColor = \"blue\";\n });\n});\n" }, { "answer_id": 74581282, "author": "Mina", "author_id": 11887902, "author_profile": "https://Stackoverflow.com/users/11887902", "pm_score": 2, "selected": false, "text": "document.querySelectorAll('bttn'); .bttn bttn . document.querySelectorAll('.bttn'); forEach button addEventListener click style classList const buttons = document.querySelectorAll('.bttn');\n\nbuttons.forEach(button => {\n button.addEventListener('click', () => {\n button.classList.toggle('red');\n })\n}) .all-buttons{\n display:flex;\n width: 100%\n }\n .bttn{\n width: 33%\n border: none;\n background-color: blue;\n padding: 20px 20px;\ncolor: white;\n }\n\n.red {\n background-color: red;\n} <html>\n<head><title>yes</title></head>\n<body>\n<div class=\"all-buttons\">\n <button class=\"bttn\">BUTTON1</button>\n <button class=\"bttn\">BUTTON2</button>\n <button class=\"bttn\">BUTTON3</button>\n</div>\n</body>\n</html>" }, { "answer_id": 74581377, "author": "MAYUR SANCHETI", "author_id": 12238257, "author_profile": "https://Stackoverflow.com/users/12238257", "pm_score": 1, "selected": false, "text": "const nodeList = document.querySelectorAll(\".dropbtn\");\n const submenuList = document.querySelectorAll(\".dropdown-content\");\n\n //alert(nodeList.length);\n for (let i = 0; i < nodeList.length; i++) {\n \n nodeList[i].addEventListener('click', function(event) {\n submenuList[i].classList.toggle(\"show\");\n \n });\n \n \n } .dropbtn {\n background-color: #3498DB;\n color: white;\n padding: 16px;\n font-size: 16px;\n border: none;\n cursor: pointer;\n}\n\n\n.dropbtn:hover, .dropbtn:focus {\n background-color: #2980B9;\n}\n\n\n.dropdown {\n position: relative;\n display: inline-block;\n}\n\n\n.dropdown-content {\n display: none;\n position: absolute;\n background-color: #f1f1f1;\n min-width: 160px;\n box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);\n z-index: 1;\n}\n\n\n.dropdown-content a {\n color: black;\n padding: 12px 16px;\n text-decoration: none;\n display: block;\n}\n\n\n.dropdown-content a:hover {background-color: #ddd}\n\n.show {display:block;} <div class=\"dropdown\">\n <button class=\"dropbtn\">Dropdown</button>\n <div class=\"dropdown-content\">\n <a href=\"#\">Link 1</a>\n <a href=\"#\">Link 2</a>\n <a href=\"#\">Link 3</a>\n </div>\n </div>\n\n <div class=\"dropdown\">\n <button class=\"dropbtn\">Dropdown</button>\n <div class=\"dropdown-content\">\n <a href=\"#\">Link- 1</a>\n <a href=\"#\">Link- 2</a>\n <a href=\"#\">Link- 3</a>\n </div>\n </div>" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20530341/" ]
74,581,325
<p>I do not know where to put the function</p> <pre><code>setTimeout('history.go(0);', 10000) </code></pre> <p>how do I code on a page?</p>
[ { "answer_id": 74581500, "author": "tacoshy", "author_id": 14072420, "author_profile": "https://Stackoverflow.com/users/14072420", "pm_score": 0, "selected": false, "text": "window.location.reload() setTimeout(function () {\n window.location.reload();\n}, 10000);\n" }, { "answer_id": 74581534, "author": "JoSSte", "author_id": 1725871, "author_profile": "https://Stackoverflow.com/users/1725871", "pm_score": 1, "selected": false, "text": "<html>\n <head>\n <script>\n setTimeout('history.go(0);', 10000) \n </script>\n <head>\n <body>\n ..\n </body>\n</html>\n <html>\n\n<head>\n <script>\n //console.info('initial load');\n addEventListener('DOMContentLoaded', function () {\n setTimeout(function () {\n //console.info('reloading');\n window.location.reload();\n }, 10000);\n })\n </script>\n\n <head>\n\n <body>\n my body\n </body>\n\n</html>" }, { "answer_id": 74581907, "author": "tatactic", "author_id": 1247977, "author_profile": "https://Stackoverflow.com/users/1247977", "pm_score": 1, "selected": false, "text": "<meta http-equiv=\"refresh\" content=\"10\">\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20605811/" ]
74,581,337
<p>I have two array of objects in which if property <code>grp</code> from arrobj1 is</p> <p>same as <code>SERVICE</code> and <code>ISACTIVE is true</code> from arrobj2, then return array of object using</p> <p>javascript</p> <pre><code>Tried let result = arrobj1.filter(e=&gt; arrobj2.some(i=&gt; i.ISACTIVE===true &amp;&amp; e.grp === i.SERVICE); ); var arrobj1=[ { id:&quot;SetupFS&quot;, grp:&quot;fs&quot;, title: &quot;xxx&quot; }, { id:&quot;ExtendFS&quot;, grp:&quot;fs&quot;, title: &quot;yyy&quot; }, { id:&quot;RebootServer&quot;, grp:&quot;os&quot;, title: &quot;yyy&quot; }, ] var arrobj2=[ {id:1, ISACTIVE:true, TASK:'SetupFS', SERVICE: &quot;fs&quot; }, {id:2, ISACTIVE:false, TASK:'RebootServer', SERVICE:&quot;os&quot; }, {id:3, ISACTIVE:false, TASK:'ExtendFS', SERVICE: &quot;fs&quot; }, ] </code></pre> <pre><code>Expected Result [ { id:&quot;SetupFS&quot;, grp:&quot;fs&quot;, title: &quot;xxx&quot; } ] </code></pre>
[ { "answer_id": 74581446, "author": "Mina", "author_id": 11887902, "author_profile": "https://Stackoverflow.com/users/11887902", "pm_score": 1, "selected": false, "text": "filter index arrobj1 grp SERVICE arrobj2 var arrobj1=[\n {\n id:\"SetupFS\",\n grp:\"fs\",\n title: \"xxx\"\n },\n {\n id:\"ExtendFS\",\n grp:\"fs\",\n title: \"yyy\"\n },\n {\n id:\"RebootServer\",\n grp:\"os\",\n title: \"yyy\"\n },\n]\n\nvar arrobj2=[\n{id:1, ISACTIVE:true, TASK:'SetupFS', SERVICE: \"fs\" }, \n{id:2, ISACTIVE:false, TASK:'RebootServer', SERVICE:\"os\" }, \n{id:3, ISACTIVE:false, TASK:'ExtendFS', SERVICE: \"fs\" }, \n]\n\nlet result = arrobj2.filter((item, i) => \n item.SERVICE === arrobj1[i].grp\n);\n\nconsole.log(result)" }, { "answer_id": 74581661, "author": "Azzy", "author_id": 2122822, "author_profile": "https://Stackoverflow.com/users/2122822", "pm_score": 0, "selected": false, "text": "// gets two results wit the equals\nlet filteredList = [];\nfor (const item of arrobj1) {\n // include TASK === item.id to get the expected answer\n const inArray = arrobj2.find(e => e.ISACTIVE && e.TASK === item.id && e.SERVICE === item.grp);\n if (inArray) {\n filteredList.push(item)\n }\n}\n\nconsole.log(filteredList)\n 0: Object\n id: \"SetupFS\"\n grp: \"fs\"\n title: \"xxx\"\n1: Object\n id: \"ExtendFS\"\n grp: \"fs\"\n title: \"yyy\"\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20605073/" ]
74,581,355
<p>I am trying to read the a particular csv (plane-data.csv) but the entire df is in object type. I require 'year' to be in integer type so that I can perform calculations.</p> <p>Please take look at my <a href="https://i.stack.imgur.com/onDYM.png" rel="nofollow noreferrer">screenshot</a></p> <p>My dataset is from <a href="https://dataverse.harvard.edu/file.xhtml?persistentId=doi:10.7910/DVN/HG7NV7/XXSL8A&amp;version=1.0" rel="nofollow noreferrer">plane-data.csv link</a></p> <p>Would really love to have some help, I have been searching the entire internet for 6 hours with no progress. Thank you !</p> <p>Initially, I tried</p> <pre><code>import pandas as pd df = pd.read_csv('plane-data.csv') columns = ['type', 'manufacturer', 'issue_date', 'model', 'status', 'aircraft_type', 'engine_type'] df.drop(columns, axis=1, inplace=True) df.dropna(inplace=True) df['year'] = df['year'].astype(int) </code></pre> <p>and got</p> <pre><code>ValueError: invalid literal for int() with base 10: 'None' </code></pre> <p>Which I have found to be the result of NaN values.</p> <p>I have cleared all nullvalues and tried using</p> <pre><code>df['year'] = df['year'].astype(str).astype('Int64') </code></pre> <p>from other SO posts that seems to work for them not for me. I got</p> <pre><code>TypeError: object cannot be converted to an IntegerDtype </code></pre>
[ { "answer_id": 74581446, "author": "Mina", "author_id": 11887902, "author_profile": "https://Stackoverflow.com/users/11887902", "pm_score": 1, "selected": false, "text": "filter index arrobj1 grp SERVICE arrobj2 var arrobj1=[\n {\n id:\"SetupFS\",\n grp:\"fs\",\n title: \"xxx\"\n },\n {\n id:\"ExtendFS\",\n grp:\"fs\",\n title: \"yyy\"\n },\n {\n id:\"RebootServer\",\n grp:\"os\",\n title: \"yyy\"\n },\n]\n\nvar arrobj2=[\n{id:1, ISACTIVE:true, TASK:'SetupFS', SERVICE: \"fs\" }, \n{id:2, ISACTIVE:false, TASK:'RebootServer', SERVICE:\"os\" }, \n{id:3, ISACTIVE:false, TASK:'ExtendFS', SERVICE: \"fs\" }, \n]\n\nlet result = arrobj2.filter((item, i) => \n item.SERVICE === arrobj1[i].grp\n);\n\nconsole.log(result)" }, { "answer_id": 74581661, "author": "Azzy", "author_id": 2122822, "author_profile": "https://Stackoverflow.com/users/2122822", "pm_score": 0, "selected": false, "text": "// gets two results wit the equals\nlet filteredList = [];\nfor (const item of arrobj1) {\n // include TASK === item.id to get the expected answer\n const inArray = arrobj2.find(e => e.ISACTIVE && e.TASK === item.id && e.SERVICE === item.grp);\n if (inArray) {\n filteredList.push(item)\n }\n}\n\nconsole.log(filteredList)\n 0: Object\n id: \"SetupFS\"\n grp: \"fs\"\n title: \"xxx\"\n1: Object\n id: \"ExtendFS\"\n grp: \"fs\"\n title: \"yyy\"\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20517034/" ]
74,581,359
<p>I have the following <code>df</code>:</p> <pre><code>df = pd.DataFrame({ 'Q0_0': [&quot;India&quot;, &quot;Algeria&quot;, &quot;India&quot;, &quot;U.S.A&quot;, &quot;Morocco&quot;, &quot;Tunisia&quot;, &quot;U.S.A&quot;, &quot;France&quot;, &quot;Russia&quot;, &quot;Algeria&quot;], 'Q1_1': [np.random.randint(1,100) for i in range(10)], 'Q1_2': np.random.random(10), 'Q1_3': np.random.randint(2, size=10), 'Q2_1': [np.random.randint(1,100) for i in range(10)], 'Q2_2': np.random.random(10), 'Q2_3': np.random.randint(2, size=10) }) </code></pre> <p>It has following display:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>Q0_0</th> <th>Q1_1</th> <th>Q1_2</th> <th>Q1_3</th> <th>Q2_1</th> <th>Q2_2</th> <th>Q2_3</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>India</td> <td>21</td> <td>0.326856</td> <td>0</td> <td>51</td> <td>0.520506</td> <td>0</td> </tr> <tr> <td>1</td> <td>Algeria</td> <td>7</td> <td>0.504580</td> <td>1</td> <td>43</td> <td>0.953744</td> <td>1</td> </tr> <tr> <td>2</td> <td>India</td> <td>67</td> <td>0.327273</td> <td>1</td> <td>34</td> <td>0.840453</td> <td>1</td> </tr> <tr> <td>3</td> <td>U.S.A</td> <td>49</td> <td>0.056478</td> <td>0</td> <td>67</td> <td>0.309559</td> <td>1</td> </tr> <tr> <td>4</td> <td>Morocco</td> <td>71</td> <td>0.743913</td> <td>1</td> <td>76</td> <td>0.240706</td> <td>1</td> </tr> <tr> <td>5</td> <td>Tunisia</td> <td>31</td> <td>0.060707</td> <td>1</td> <td>78</td> <td>0.576598</td> <td>0</td> </tr> <tr> <td>6</td> <td>U.S.A</td> <td>25</td> <td>0.588239</td> <td>1</td> <td>61</td> <td>0.133856</td> <td>1</td> </tr> <tr> <td>7</td> <td>France</td> <td>99</td> <td>0.991723</td> <td>0</td> <td>85</td> <td>0.274825</td> <td>1</td> </tr> <tr> <td>8</td> <td>Russia</td> <td>9</td> <td>0.846950</td> <td>1</td> <td>61</td> <td>0.279948</td> <td>1</td> </tr> <tr> <td>9</td> <td>Algeria</td> <td>79</td> <td>0.176326</td> <td>1</td> <td>78</td> <td>0.881051</td> <td>1</td> </tr> </tbody> </table> </div> <p>I need to change countries other than <code>India</code> and <code>U.S.A</code> to <code>Òther</code> in column <code>Q0_0</code>.</p> <p><strong>Desired output</strong></p> <pre><code>Q0_0 Q1_1 Q1_2 Q1_3 Q2_1 Q2_2 Q2_3 0 India 21 0.326856 0 51 0.520506 0 1 Other 7 0.504580 1 43 0.953744 1 2 India 67 0.327273 1 34 0.840453 1 3 U.S.A 49 0.056478 0 67 0.309559 1 4 Other 71 0.743913 1 76 0.240706 1 5 Other 31 0.060707 1 78 0.576598 0 6 U.S.A 25 0.588239 1 61 0.133856 1 7 Other 99 0.991723 0 85 0.274825 1 8 Other 9 0.846950 1 61 0.279948 1 9 Other 79 0.176326 1 78 0.881051 1 </code></pre> <p>I tried to use <code>pandas.series.str.replace()</code> but it didn't work.</p> <p>Any help from your side will be highly appreciated, thanks.</p>
[ { "answer_id": 74581394, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": 2, "selected": true, "text": "pandas.Series.mask pandas.Series.fillna df[\"Q0_0\"]= df[\"Q0_0\"].mask(~df[\"Q0_0\"].isin([\"India\", \"U.S.A\"])).fillna(\"Other\")\n print(df)\n\n Q0_0 Q1_1 Q1_2 Q1_3 Q2_1 Q2_2 Q2_3\n0 India 43 0.681795 0 36 0.772289 0\n1 Other 85 0.695352 1 14 0.989219 1\n2 India 69 0.684015 1 85 0.687373 0\n3 U.S.A 10 0.175235 1 52 0.825989 1\n4 Other 90 0.998192 0 59 0.482667 0\n5 Other 27 0.723308 0 90 0.054042 1\n6 U.S.A 38 0.973819 0 69 0.536380 1\n7 Other 10 0.815710 1 2 0.134707 1\n8 Other 38 0.238863 1 1 0.872125 1\n9 Other 96 0.078010 0 84 0.650347 0\n" }, { "answer_id": 74581401, "author": "DataFlo_w", "author_id": 16862959, "author_profile": "https://Stackoverflow.com/users/16862959", "pm_score": 0, "selected": false, "text": "df['Q0_0'] = df['Q0_0'].str.replace('Algeria', 'Other')\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15852600/" ]
74,581,367
<p>In the example below pine script converts str.tonumber('15min') correctly to 15.00 as it should. However if we provide the argument as a function parameter it fails to convert. Bug has been reported.</p> <pre><code>//@version=5 indicator(&quot;My script&quot;, &quot;m&quot;, true) convert() =&gt; foo = '15min' str.tostring(str.tonumber(foo)) convert(simple string foo) =&gt; str.tostring(str.tonumber(foo)) if barstate.islast label.new(bar_index, high * 1.001, 'Correct result: ' + convert()) // result correctly 15 foo = '15min' label.new(bar_index, high, 'Inconsistent result: ' + convert(foo)) // result NaN </code></pre>
[ { "answer_id": 74581394, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": 2, "selected": true, "text": "pandas.Series.mask pandas.Series.fillna df[\"Q0_0\"]= df[\"Q0_0\"].mask(~df[\"Q0_0\"].isin([\"India\", \"U.S.A\"])).fillna(\"Other\")\n print(df)\n\n Q0_0 Q1_1 Q1_2 Q1_3 Q2_1 Q2_2 Q2_3\n0 India 43 0.681795 0 36 0.772289 0\n1 Other 85 0.695352 1 14 0.989219 1\n2 India 69 0.684015 1 85 0.687373 0\n3 U.S.A 10 0.175235 1 52 0.825989 1\n4 Other 90 0.998192 0 59 0.482667 0\n5 Other 27 0.723308 0 90 0.054042 1\n6 U.S.A 38 0.973819 0 69 0.536380 1\n7 Other 10 0.815710 1 2 0.134707 1\n8 Other 38 0.238863 1 1 0.872125 1\n9 Other 96 0.078010 0 84 0.650347 0\n" }, { "answer_id": 74581401, "author": "DataFlo_w", "author_id": 16862959, "author_profile": "https://Stackoverflow.com/users/16862959", "pm_score": 0, "selected": false, "text": "df['Q0_0'] = df['Q0_0'].str.replace('Algeria', 'Other')\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15348203/" ]
74,581,383
<p>I'm new to rust and trying to understand the borrowing principle.</p> <p>I have the following code:</p> <pre class="lang-rs prettyprint-override"><code>fn main() { let number_list = vec![34, 50, 25, 100, 65]; let largest_nbr = &amp;number_list[0]; println!(&quot;The largest number is {}&quot;, largest_nbr); let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8]; println!(&quot;The largest number is {}&quot;, largest_nbr); } </code></pre> <p>When I execute <code>cargo run</code> I get this result:</p> <pre><code>&gt; The largest number is 34 &gt; The largest number is 34 </code></pre> <p>I expected the second line to say <code>102</code> is the largest number because <code>largest_nbr</code> borrows from <code>number_list</code>, so the pointer is showing at the storage of <code>number_list</code>. When the value of <code>number_list</code> changes, shouldn't the value of <code>largest_nbr</code> also change?</p>
[ { "answer_id": 74581475, "author": "Finomnis", "author_id": 2902833, "author_profile": "https://Stackoverflow.com/users/2902833", "pm_score": 4, "selected": true, "text": "let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8];\n number_list number_list largest_nbr let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8] let largest_nbr fn main() {\n let mut number_list = vec![34, 50, 25, 100, 65];\n\n let largest_nbr = &number_list[0];\n\n println!(\"The largest number is {}\", largest_nbr);\n\n number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8];\n\n println!(\"The largest number is {}\", largest_nbr);\n}\n error[E0506]: cannot assign to `number_list` because it is borrowed\n --> src/main.rs:8:5\n |\n4 | let largest_nbr = &number_list[0];\n | ----------- borrow of `number_list` occurs here\n...\n8 | number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8];\n | ^^^^^^^^^^^ assignment to borrowed `number_list` occurs here\n9 |\n10 | println!(\"The largest number is {}\", largest_nbr);\n | ----------- borrow later used here\n" }, { "answer_id": 74581522, "author": "Miiao", "author_id": 20028181, "author_profile": "https://Stackoverflow.com/users/20028181", "pm_score": -1, "selected": false, "text": "number_list number_list largest_number Vec Vec" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9229256/" ]
74,581,411
<p>Could someone tell me how I can solve this problem? I have two arrays in array 1 change values, array 2 has to synchronize with the first one, but without losing the value positions. I have tried with <code>difference(from:)</code> but it reorders the values of array 2. Here as it should be, thank you very much for your help.</p> <pre class="lang-swift prettyprint-override"><code>let array1 = [&quot;01&quot;, &quot;06&quot;, &quot;17&quot;, &quot;22&quot;, &quot;33&quot;, &quot;45&quot;, &quot;04&quot;] var array2 = [&quot;04&quot;, &quot;17&quot;, &quot;22&quot;, &quot;10&quot;, &quot;01&quot;, &quot;34&quot;] // ... // Result var array2 = [&quot;04&quot;, &quot;17&quot;, &quot;22&quot;, &quot;01&quot;, &quot;06&quot;, &quot;33&quot;, &quot;45&quot;] </code></pre> <p>The order of the values in array 2 must remain the same, delete those missing from array 1 and add those missing from array 1 to the end of array 2.</p>
[ { "answer_id": 74581475, "author": "Finomnis", "author_id": 2902833, "author_profile": "https://Stackoverflow.com/users/2902833", "pm_score": 4, "selected": true, "text": "let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8];\n number_list number_list largest_nbr let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8] let largest_nbr fn main() {\n let mut number_list = vec![34, 50, 25, 100, 65];\n\n let largest_nbr = &number_list[0];\n\n println!(\"The largest number is {}\", largest_nbr);\n\n number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8];\n\n println!(\"The largest number is {}\", largest_nbr);\n}\n error[E0506]: cannot assign to `number_list` because it is borrowed\n --> src/main.rs:8:5\n |\n4 | let largest_nbr = &number_list[0];\n | ----------- borrow of `number_list` occurs here\n...\n8 | number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8];\n | ^^^^^^^^^^^ assignment to borrowed `number_list` occurs here\n9 |\n10 | println!(\"The largest number is {}\", largest_nbr);\n | ----------- borrow later used here\n" }, { "answer_id": 74581522, "author": "Miiao", "author_id": 20028181, "author_profile": "https://Stackoverflow.com/users/20028181", "pm_score": -1, "selected": false, "text": "number_list number_list largest_number Vec Vec" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8563421/" ]
74,581,448
<p>I'm wondering if it is possible to target the last element of a particular type in CSS, knowing that there is no hierarchy so I can't use: the last-child CSS selector.</p> <p>I want to apply a red font color to the last <code>&lt;p&gt;</code> tag following each <code>&lt;h1&gt;</code> tag.</p> <p>The HTML is composed of one <code>&lt;h1&gt;</code> tag followed by multiple (number may vary) <code>&lt;h1&gt;</code> tags, as shown in the code below</p> <p>I want to do this only with CSS! (no JS or SCSS ...)</p> <pre><code>&lt;body&gt; &lt;h1&gt;hhhhhhhhh&lt;/h1&gt; &lt;p&gt;ppppp&lt;/p&gt; &lt;p&gt;ppppp&lt;/p&gt; &lt;h1&gt;hhhhhhhhh&lt;/h1&gt; &lt;p&gt;ppppp&lt;/p&gt; &lt;p&gt;ppppp&lt;/p&gt; &lt;p&gt;ppppp&lt;/p&gt; &lt;h1&gt;hhhhhhhhh&lt;/h1&gt; &lt;p&gt;ppppp&lt;/p&gt; &lt;p&gt;ppppp&lt;/p&gt; &lt;p&gt;ppppp&lt;/p&gt; &lt;p&gt;ppppp&lt;/p&gt; </code></pre> <p>I tried :</p> <pre><code>h1 ~ p:last-of-type { color: red; } </code></pre> <p>but then it only selects the very last p, which is logical and understandable</p> <p>I also tried this :</p> <pre><code>h1 ~ p:nth-last-of-type(3n) { color: blue; } </code></pre> <p>it works only when I have 3 'p' tags in each 'h1' tag</p>
[ { "answer_id": 74581475, "author": "Finomnis", "author_id": 2902833, "author_profile": "https://Stackoverflow.com/users/2902833", "pm_score": 4, "selected": true, "text": "let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8];\n number_list number_list largest_nbr let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8] let largest_nbr fn main() {\n let mut number_list = vec![34, 50, 25, 100, 65];\n\n let largest_nbr = &number_list[0];\n\n println!(\"The largest number is {}\", largest_nbr);\n\n number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8];\n\n println!(\"The largest number is {}\", largest_nbr);\n}\n error[E0506]: cannot assign to `number_list` because it is borrowed\n --> src/main.rs:8:5\n |\n4 | let largest_nbr = &number_list[0];\n | ----------- borrow of `number_list` occurs here\n...\n8 | number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8];\n | ^^^^^^^^^^^ assignment to borrowed `number_list` occurs here\n9 |\n10 | println!(\"The largest number is {}\", largest_nbr);\n | ----------- borrow later used here\n" }, { "answer_id": 74581522, "author": "Miiao", "author_id": 20028181, "author_profile": "https://Stackoverflow.com/users/20028181", "pm_score": -1, "selected": false, "text": "number_list number_list largest_number Vec Vec" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18153178/" ]
74,581,464
<p>I am trying to create a simple java program for a chess tournament, which will save game results in an array. Results will be stored according to users choice, they may be input from keyboard, or using results that are already in the array, OR generate random sequence of numbers 1.0, 0.0, 0.5. (win, loss, draw)</p> <p>So far I know how to generate random numbers in a specific range, using java.util.Random;</p> <pre><code>public static void main(String[] args) { double a[][] = {{0.5, 0.5, 0.5, 0.5, 0.5}, {0, 1, 0, 1, 1}, {0.5, 1, 0.5, 0.5, 0}, {0, 0.5, 0, 0.5, 0}, {1, 1, 1, 1, 1}, {0, 0, 0, 0.5, 0.5}, {0, 0.5, 0, 0, 1}}; int i, j; int ch; System.out.print(&quot;mode (1, 2 or 3): &quot;); Scanner sc = new Scanner(System.in); ch = sc.nextInt(); Random rnd = new Random(); switch (ch) { case 1 -&gt; { for (i=0; i&lt;a.length ;i++) { for (j=0; j&lt;a[i].length; j++) { a[i][j] = sc.nextDouble(); } } } case 2 -&gt; { for (i=0; i&lt;a.length; i++) { for (j=0; j&lt;a[i].length; j++) { a[i][j] = rnd.nextDouble(); } } } case 3 -&gt; { for (i=0; i&lt;a.length; i++) { for (j=0; j&lt;a[i].length; j++) { a[i][j] = a[i][j]; } } } default -&gt; { System.out.println(&quot;mode error&quot;); sc.close(); return; } } sc.close(); for (i=0; i&lt;a.length; ++i) { for (j=0; j&lt;a[i].length; ++j) { System.out.printf(&quot;%.1f&quot; + &quot; &quot;, a[i][j]); } System.out.println(); } </code></pre> <p>so case 2 of switch statement is giving me issues, since it gives an output of random numbers in a range of 0 to 1, but game results must be stored in values of 1.0, 0.5, and 0.0</p>
[ { "answer_id": 74581541, "author": "azro", "author_id": 7212686, "author_profile": "https://Stackoverflow.com/users/7212686", "pm_score": 2, "selected": true, "text": "nextInt(bound) 0, 1, 2 case 2 -> {\n for (i = 0; i < a.length; i++) {\n for (j = 0; j < a[i].length; j++) {\n a[i][j] = rnd.nextInt(3) / 2.0;\n }\n }\n}\n case 3 case 3 -> System.out.println(\"Nothing to do\");\n" }, { "answer_id": 74581551, "author": "JustAnotherDeveloper", "author_id": 14071914, "author_profile": "https://Stackoverflow.com/users/14071914", "pm_score": 0, "selected": false, "text": "float[] valuesArray = {1.0,0.0,0.5};\n public int getRandomNumber(int min, int max) {\n return (int) ((Math.random() * (max - min)) + min);\n}\n int myIndex = getRandomNumber(0, 2); valuesArray" }, { "answer_id": 74581565, "author": "Levi", "author_id": 19608895, "author_profile": "https://Stackoverflow.com/users/19608895", "pm_score": 2, "selected": false, "text": " import java.util.Random;\n public static Double RandomGenerator() {\n Double[] arr = new Double[] { 0.0 , 0.5, 1.0 };\n Random rnd = new Random();\n Double result = arr[rnd.nextInt(arr.length)];\n return result;\n }\n}\n { for (i=0; i<a.length; i++) {\n for (j=0; j<a[i].length; j++) {\n a[i][j] = RandomGenerator();\n }\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20222483/" ]
74,581,468
<p>I downloaded a laravel project online from <a href="https://itsourcecode.com/free-projects/laravel/online-crime-reporting-system-project-in-laravel-with-source-code/" rel="nofollow noreferrer">link</a> I ran the command is <em><strong>composer update</strong></em> and <em><strong>composer install</strong></em>. The error i'm seeing is:</p> <blockquote> <p>In ProviderRepository.php line 208:</p> <p>Class &quot;Collective\Html\HtmlServiceProvider&quot; not found</p> <p>Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1</p> </blockquote> <p>After deleting vendor file and running <em><strong>composer install</strong></em> and <em><strong>composer update</strong></em> im getting this</p> <blockquote> <p>PHP Fatal error: Declaration of App\Providers\EventServiceProvider::boot(Illuminate\Contracts\Events\Dispatcher $events) must be compatible with Illuminate\Foundation\Support\Providers\EventServiceProvider::boot() in C:\xampp\htdocs\ZAlert\app\Providers\EventServiceProvider.php on line 27 In EventServiceProvider.php line 27:</p> <p>Declaration of App\Providers\EventServiceProvider::boot(Illuminate\Contracts\Events\Dispatcher $events) must be compatible with Illuminate\Foundation\Support\Providers\EventServiceProvider::boot()</p> <p>Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 255</p> </blockquote> <p>I was expecting this to run in laravel 9</p>
[ { "answer_id": 74581541, "author": "azro", "author_id": 7212686, "author_profile": "https://Stackoverflow.com/users/7212686", "pm_score": 2, "selected": true, "text": "nextInt(bound) 0, 1, 2 case 2 -> {\n for (i = 0; i < a.length; i++) {\n for (j = 0; j < a[i].length; j++) {\n a[i][j] = rnd.nextInt(3) / 2.0;\n }\n }\n}\n case 3 case 3 -> System.out.println(\"Nothing to do\");\n" }, { "answer_id": 74581551, "author": "JustAnotherDeveloper", "author_id": 14071914, "author_profile": "https://Stackoverflow.com/users/14071914", "pm_score": 0, "selected": false, "text": "float[] valuesArray = {1.0,0.0,0.5};\n public int getRandomNumber(int min, int max) {\n return (int) ((Math.random() * (max - min)) + min);\n}\n int myIndex = getRandomNumber(0, 2); valuesArray" }, { "answer_id": 74581565, "author": "Levi", "author_id": 19608895, "author_profile": "https://Stackoverflow.com/users/19608895", "pm_score": 2, "selected": false, "text": " import java.util.Random;\n public static Double RandomGenerator() {\n Double[] arr = new Double[] { 0.0 , 0.5, 1.0 };\n Random rnd = new Random();\n Double result = arr[rnd.nextInt(arr.length)];\n return result;\n }\n}\n { for (i=0; i<a.length; i++) {\n for (j=0; j<a[i].length; j++) {\n a[i][j] = RandomGenerator();\n }\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19846182/" ]
74,581,492
<p>I have a string like,</p> <pre><code>const string = &quot;DEVICE_SIZE IN ('036','048','060','070') AND DEVICE_VOLTAGE IN ('1','3') AND NOT DEVICE_DISCHARGE_AIR IN ('S') AND NOT DEVICE_REFRIGERANT_CIRCUIT IN ('H','C')&quot;; </code></pre> <p>From this, I need to map the respective key and value like, <code>DEVICE_SIZE: [&quot;036&quot;, &quot;048&quot;, &quot;060&quot;, &quot;070&quot;]</code></p> <p><strong>Current Result:</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> const string = "DEVICE_SIZE IN ('036','048','060','070') AND DEVICE_VOLTAGE IN ('1','3') AND NOT DEVICE_DISCHARGE_AIR IN ('S') AND NOT DEVICE_REFRIGERANT_CIRCUIT IN ('H','C')"; const res = string.split('IN '); const regExp = /\(([^)]+)\)/; const Y = 'AND'; const data = res.map((item) =&gt; { if (regExp.exec(item)) { return { [item.slice(item.indexOf(Y) + Y.length)]: regExp.exec(item)[1], }; } }); console.log('data ', data);</code></pre> </div> </div> </p> <p><strong>Expected Result:</strong></p> <pre><code>[ { &quot;DEVICE_SIZE&quot;: [&quot;036&quot;, &quot;048&quot;, &quot;060&quot;, &quot;070&quot;] }, { &quot;DEVICE_VOLTAGE&quot;: [&quot;1&quot;, &quot;3&quot;] }, { &quot;NOT DEVICE_DISCHARGE_AIR&quot;: [&quot;s&quot;] }, { &quot;NOT DEVICE_REFRIGERANT_CIRCUIT&quot;: [&quot;H&quot;, &quot;C&quot;] }, ]; </code></pre> <p>I couldn't get the exact result based on my try in the current result. Could you please kindly help me to achieve the above given expected result?</p> <p><strong>Note</strong>: I am trying the above to achieve the end result mentioned in my previous question <a href="https://stackoverflow.com/questions/74580671/how-to-get-valid-object-from-the-string-matching-respective-array">How to get valid object from the string matching respective array?</a></p>
[ { "answer_id": 74581629, "author": "Cedric", "author_id": 5618266, "author_profile": "https://Stackoverflow.com/users/5618266", "pm_score": 0, "selected": false, "text": "Object.fromEntries [string, any] const data = Object.fromEntries(res.map((item) => {\n if (regExp.exec(item)) {\n return [item.slice(item.indexOf(Y) + Y.length).trim(), regExp.exec(item)[1].split(',').map(value => value.slice(1, -1))];\n }\n return undefined;\n}).filter(Boolean));\n" }, { "answer_id": 74581695, "author": "Amila Senadheera", "author_id": 8510405, "author_profile": "https://Stackoverflow.com/users/8510405", "pm_score": 1, "selected": false, "text": "AND IN const string =\n \"DEVICE_SIZE IN ('036','048','060','070') AND DEVICE_VOLTAGE IN ('1','3') AND NOT DEVICE_DISCHARGE_AIR IN ('S') AND NOT DEVICE_REFRIGERANT_CIRCUIT IN ('H','C')\";\n\nconst output = string\n .split(\"AND\")\n .map((item) => item.split(\"IN\").map((text) => text.trim()))\n .map(([key, value]) => ({\n [key]: value.replace(/[\\(\\)\\']/g, \"\").split(\",\"),\n }));\n\nconsole.log(output);" }, { "answer_id": 74581931, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 3, "selected": true, "text": "((?:\\bNOT\\s+)?\\w+)\\s+IN\\s+\\('([^()]*)'\\)\n ( (?:\\bNOT\\s+)? \\w+ ) \\s+IN\\s+ \\(' (' ([^()]*) ( ) '\\) ') ',' const regex = /((?:\\bNOT\\s+)?\\w+)\\s+IN\\s+\\('([^()]*)'\\)/g;\nconst string = \"DEVICE_SIZE IN ('036','048','060','070') AND DEVICE_VOLTAGE IN ('1','3') AND NOT DEVICE_DISCHARGE_AIR IN ('S') AND NOT DEVICE_REFRIGERANT_CIRCUIT IN ('H','C')\";\nconst data = Array.from(\n string.matchAll(regex), m =>\n ({\n [m[1]]: m[2].split(\"','\")\n })\n);\nconsole.log(data);" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15916627/" ]
74,581,496
<p>I'm trying to get data of an authenticated user using the token, I'm using postman to send a get request and get the data I need but I'm receiving a response</p> <blockquote> <p>&quot;detail&quot;: &quot;Authentication credentials were not provided.&quot;</p> </blockquote> <p>this is the view `</p> <pre><code>class ReceiveMessagesView(viewsets.ModelViewSet): serializer_class = MessageSerializer permission_classes = [permissions.IsAuthenticated] http_method_names = ['get', 'post'] def get_queryset(self): user = self.request.user queryset = Message.objects.filter(receiver=user) return queryset` </code></pre> <p>settings</p> <pre><code>REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } </code></pre> <p>urls</p> <pre><code>router = routers.DefaultRouter() router.register('', views.ReceiveMessagesView, basename='receive_messages') urlpatterns = [ path('', include(router.urls)) ] </code></pre> <p>serializer</p> <pre><code>class MessageSerializer(serializers.ModelSerializer): class Meta: model = Message fields = [ 'sender', 'receiver', 'subject', 'msg', 'creation_date', ] </code></pre> <p>In the postman request I'm sending in Authorization the key as &quot;Token&quot; and the value as the user I want data about's token</p> <p>I am trying to send an authorized get request and received an authorized user's data btw if I'm trying to print the user instance and the token when I get to the view (with self.request.user and self.request.auth)I get the correct instance user but for the token I get None</p>
[ { "answer_id": 74581629, "author": "Cedric", "author_id": 5618266, "author_profile": "https://Stackoverflow.com/users/5618266", "pm_score": 0, "selected": false, "text": "Object.fromEntries [string, any] const data = Object.fromEntries(res.map((item) => {\n if (regExp.exec(item)) {\n return [item.slice(item.indexOf(Y) + Y.length).trim(), regExp.exec(item)[1].split(',').map(value => value.slice(1, -1))];\n }\n return undefined;\n}).filter(Boolean));\n" }, { "answer_id": 74581695, "author": "Amila Senadheera", "author_id": 8510405, "author_profile": "https://Stackoverflow.com/users/8510405", "pm_score": 1, "selected": false, "text": "AND IN const string =\n \"DEVICE_SIZE IN ('036','048','060','070') AND DEVICE_VOLTAGE IN ('1','3') AND NOT DEVICE_DISCHARGE_AIR IN ('S') AND NOT DEVICE_REFRIGERANT_CIRCUIT IN ('H','C')\";\n\nconst output = string\n .split(\"AND\")\n .map((item) => item.split(\"IN\").map((text) => text.trim()))\n .map(([key, value]) => ({\n [key]: value.replace(/[\\(\\)\\']/g, \"\").split(\",\"),\n }));\n\nconsole.log(output);" }, { "answer_id": 74581931, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 3, "selected": true, "text": "((?:\\bNOT\\s+)?\\w+)\\s+IN\\s+\\('([^()]*)'\\)\n ( (?:\\bNOT\\s+)? \\w+ ) \\s+IN\\s+ \\(' (' ([^()]*) ( ) '\\) ') ',' const regex = /((?:\\bNOT\\s+)?\\w+)\\s+IN\\s+\\('([^()]*)'\\)/g;\nconst string = \"DEVICE_SIZE IN ('036','048','060','070') AND DEVICE_VOLTAGE IN ('1','3') AND NOT DEVICE_DISCHARGE_AIR IN ('S') AND NOT DEVICE_REFRIGERANT_CIRCUIT IN ('H','C')\";\nconst data = Array.from(\n string.matchAll(regex), m =>\n ({\n [m[1]]: m[2].split(\"','\")\n })\n);\nconsole.log(data);" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15784054/" ]
74,581,568
<pre><code>Trade Date Options Class Underlying Product Type Volume 0 2022-01-03 A A S 14 1 2022-01-03 A A S 3 2 2022-01-03 A A S 42 3 2022-01-03 A A S 10 4 2022-01-03 AA AA S 1924 print(df.groupby('Trade Date','Underlying').sum()) </code></pre> <p>How do combine all the similar dates together based on a particular underlying?</p> <p>For example in the above example i will get a single line of 2022-01-03 for A with the sum of its volume</p> <p>I tried using:</p> <pre><code>print(df.groupby('Trade Date','Underlying').sum()) </code></pre>
[ { "answer_id": 74581629, "author": "Cedric", "author_id": 5618266, "author_profile": "https://Stackoverflow.com/users/5618266", "pm_score": 0, "selected": false, "text": "Object.fromEntries [string, any] const data = Object.fromEntries(res.map((item) => {\n if (regExp.exec(item)) {\n return [item.slice(item.indexOf(Y) + Y.length).trim(), regExp.exec(item)[1].split(',').map(value => value.slice(1, -1))];\n }\n return undefined;\n}).filter(Boolean));\n" }, { "answer_id": 74581695, "author": "Amila Senadheera", "author_id": 8510405, "author_profile": "https://Stackoverflow.com/users/8510405", "pm_score": 1, "selected": false, "text": "AND IN const string =\n \"DEVICE_SIZE IN ('036','048','060','070') AND DEVICE_VOLTAGE IN ('1','3') AND NOT DEVICE_DISCHARGE_AIR IN ('S') AND NOT DEVICE_REFRIGERANT_CIRCUIT IN ('H','C')\";\n\nconst output = string\n .split(\"AND\")\n .map((item) => item.split(\"IN\").map((text) => text.trim()))\n .map(([key, value]) => ({\n [key]: value.replace(/[\\(\\)\\']/g, \"\").split(\",\"),\n }));\n\nconsole.log(output);" }, { "answer_id": 74581931, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 3, "selected": true, "text": "((?:\\bNOT\\s+)?\\w+)\\s+IN\\s+\\('([^()]*)'\\)\n ( (?:\\bNOT\\s+)? \\w+ ) \\s+IN\\s+ \\(' (' ([^()]*) ( ) '\\) ') ',' const regex = /((?:\\bNOT\\s+)?\\w+)\\s+IN\\s+\\('([^()]*)'\\)/g;\nconst string = \"DEVICE_SIZE IN ('036','048','060','070') AND DEVICE_VOLTAGE IN ('1','3') AND NOT DEVICE_DISCHARGE_AIR IN ('S') AND NOT DEVICE_REFRIGERANT_CIRCUIT IN ('H','C')\";\nconst data = Array.from(\n string.matchAll(regex), m =>\n ({\n [m[1]]: m[2].split(\"','\")\n })\n);\nconsole.log(data);" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4387555/" ]
74,581,601
<p>When a virtual thread is blocked due to synchronized call, it's yielding, so the scheduler will unmount it from related Carrier thread.</p> <p>I was wondering, how does a virtual thread know that it's currently at wait state and it's time to yield?</p>
[ { "answer_id": 74582850, "author": "pveentjer", "author_id": 2245707, "author_profile": "https://Stackoverflow.com/users/2245707", "pm_score": 0, "selected": false, "text": " public static void parkNanos(Object blocker, long nanos) {\n if (nanos > 0) {\n Thread t = Thread.currentThread();\n setBlocker(t, blocker);\n try {\n if (t.isVirtual()) {\n VirtualThreads.park(nanos);<====\n } else {\n U.park(false, nanos);\n }\n } finally {\n setBlocker(t, null);\n }\n }\n }\n" }, { "answer_id": 74583382, "author": "Mike Nakis", "author_id": 773113, "author_profile": "https://Stackoverflow.com/users/773113", "pm_score": 2, "selected": false, "text": "synchronized ReentrantLock CountdownLatch Sleep() Thread" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20606075/" ]
74,581,623
<pre><code>var transporter = nodemailer.createTransport({ name:&quot;www.rolester.com&quot;, service:&quot;smtp&quot;, port: 27017, auth: { user: &quot;aladi09@rolester.com&quot;, pass: &quot;alandiv09&quot; } </code></pre> <p>when i try this code i get his error</p> <pre><code>Error: Greeting never received </code></pre> <p>and when i change the port to my domain email port which is 587 i get this error</p> <pre><code>Error: connect ECONNREFUSED 127.0.0.1:587 </code></pre> <p>and when i try to turn secure to true like that .<code>secure : true</code></p> <p>i get this error</p> <pre><code>[Error: 68390000:error:0A00010B:SSL routines:ssl3_get_record:wrong version number:c:\ws\deps\openssl\openssl\ssl\record\ssl3_record.c:355: </code></pre> <p>] any solution ???</p>
[ { "answer_id": 74582850, "author": "pveentjer", "author_id": 2245707, "author_profile": "https://Stackoverflow.com/users/2245707", "pm_score": 0, "selected": false, "text": " public static void parkNanos(Object blocker, long nanos) {\n if (nanos > 0) {\n Thread t = Thread.currentThread();\n setBlocker(t, blocker);\n try {\n if (t.isVirtual()) {\n VirtualThreads.park(nanos);<====\n } else {\n U.park(false, nanos);\n }\n } finally {\n setBlocker(t, null);\n }\n }\n }\n" }, { "answer_id": 74583382, "author": "Mike Nakis", "author_id": 773113, "author_profile": "https://Stackoverflow.com/users/773113", "pm_score": 2, "selected": false, "text": "synchronized ReentrantLock CountdownLatch Sleep() Thread" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11911399/" ]
74,581,664
<p>I have created a <code>System.Timers.Timer</code> and im quite new to it. So I have used the Windows Forms Timer before and now I want to use this timer for a console application.<br /> My problem is that my timer is not stopping after one <code>OnTimeEvent()</code> and I don't know why.</p> <pre><code>class SortingSysFinal { private static System.Timers.Timer aTimer; public static void Main(String[] args) { System.Timers.Timer aTimer = new System.Timers.Timer(); aTimer.Elapsed += OnTimedEvent; aTimer.Interval = 1000; aTimer.Enabled = true; Console.Read(); } private static void OnTimedEvent(object source, ElapsedEventArgs e) { Console.WriteLine(&quot;The Elapsed event was raised at {0:HH:mm:ss.fff}&quot;, e.SignalTime); aTimer.Stop(); } } </code></pre>
[ { "answer_id": 74581799, "author": "wohlstad", "author_id": 18519921, "author_profile": "https://Stackoverflow.com/users/18519921", "pm_score": 3, "selected": true, "text": "Main System.Timers.Timer aTimer = new System.Timers.Timer();\n Timer aTimer OnTimedEvent aTimer.Stop() aTimer null aTimer = new System.Timers.Timer();\n System.Timers.Timer Elapsed Stop() System.Threading.Timer" }, { "answer_id": 74582092, "author": "Okke Hendriks", "author_id": 811059, "author_profile": "https://Stackoverflow.com/users/811059", "pm_score": 0, "selected": false, "text": "AutoReset false true" }, { "answer_id": 74582210, "author": "Theodor Zoulias", "author_id": 11178549, "author_profile": "https://Stackoverflow.com/users/11178549", "pm_score": 1, "selected": false, "text": "NullReferenceException aTimer.Stop();\n aTimer Main new System.Timers.Timer() _ _timer object source var timer = (System.Timers.Timer)source; Elapsed try { /*...*/ } catch { } System.Timers.Timer Elapsed Stop Stop lock System.Timers.Timer System.Threading.Timer System.Threading.Timer System.Timers.Timer" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14170108/" ]
74,581,666
<p>I have two entities-</p> <ol> <li>User</li> <li>Category<br /> There is a <strong>@ManyToMany relationship</strong> between the two entities. My code, to create this relationship is-<br /> 1.<strong>User.java</strong></li> </ol> <pre><code>@ManyToMany(cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH }, fetch = FetchType.LAZY) @JoinTable(name = &quot;enrolled&quot;, joinColumns = @JoinColumn( name = &quot;user&quot;, referencedColumnName = &quot;userid&quot;), inverseJoinColumns = @JoinColumn( name = &quot;category&quot;, referencedColumnName = &quot;category_id&quot;)) List&lt;Category&gt; enrolledCategories=new ArrayList&lt;&gt;(); </code></pre> <p>2.<strong>Category.java</strong></p> <pre><code> @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name=&quot;category_id&quot;) private Long categoryId; @Column(name=&quot;title&quot;,nullable = false,unique = true) private String title; @Column(name=&quot;descprition&quot;,nullable = false) private String description; </code></pre> <p>Code to delete the category is in <strong>CategoryServiceImpl-</strong></p> <pre><code> @Override public void deleteCategory(String categoryId) { Optional&lt;Category&gt; category=this.categoryRepository.findById(Long.parseLong(categoryId)); if(category.isPresent()){ this.categoryRepository.deleteById(Long.parseLong(categoryId)); } else throw new ResourceNotFoundException(&quot;Category&quot;, &quot;category id&quot;, categoryId); } </code></pre> <p>The code creates a table named <strong>enrolled-</strong> <a href="https://i.stack.imgur.com/Hiwdn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Hiwdn.png" alt="Entity Relationship between Category and User via Many to Many relationship" /></a> <a href="https://i.stack.imgur.com/6Xpli.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6Xpli.png" alt="Table entries" /></a><br /> <strong>Problem-</strong> When I try to delete the category using this method, I get the following error-</p> <pre><code>2022-11-26 16:06:26.137 ERROR 20808 --- [nio-8086-exec-9] o.a.c.c.C.[.[.[/]. [dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause java.sql.SQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`assessment_portal`.`enrolled`, CONSTRAINT `FKn8uund92met1kb1iduidshdje` FOREIGN KEY (`category`) REFERENCES `category` (`category_id`)) at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117) ~[mysql-connector-j-8.0.31.jar:8.0.31] </code></pre> <p>Please help me find the correct method to delete the category entity, without deleting the user.</p>
[ { "answer_id": 74582529, "author": "muhammed ozbilici", "author_id": 2165146, "author_profile": "https://Stackoverflow.com/users/2165146", "pm_score": 1, "selected": false, "text": "cascade = CascadeType.REMOVE @ManyToMany SET FOREIGN_KEY_CHECKS=0; /* disable */ \n\nSET FOREIGN_KEY_CHECKS=1; /* enable */ \n" }, { "answer_id": 74583782, "author": "Melih Bağçeli", "author_id": 19463436, "author_profile": "https://Stackoverflow.com/users/19463436", "pm_score": 0, "selected": false, "text": "@ManyToMany(cascade = {PERSIST, DETACH})\n@JoinTable(name = \"enrolled\",\n inverseJoinColumns = @JoinColumn(\n name = \"user\",\n referencedColumnName = \"userid\"),\n joinColumns = @JoinColumn(\n name = \"category\",\n referencedColumnName = \"category_id\"))\nprivate Set<User> users = new HashSet<>();\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19580540/" ]
74,581,669
<p>I have successfully used recursion to find a key to a variable I want to change in an API reponse json.</p> <p>The recursion returns the key the equivilant is like this:</p> <pre><code>obj_key = &quot;obj['key1']['key2'][1]['key3'][4]['key4'][0]&quot; </code></pre> <p>if I eval this:</p> <pre><code>eval(obj_key) </code></pre> <p>I get the value no problem.</p> <p>Now I want to change the value if it isn't what I want it to be. I can't figure this out and only get syntax error with every attempt .... all attempts are some form of:</p> <pre><code>eval(obj_key + ' = &quot;my_new_value&quot;') </code></pre> <p>I have slept on this one thinking it would come to me in a day or two (sometimes this works) but alas no epiphany for me. Thanks for any help!</p>
[ { "answer_id": 74581737, "author": "Oguz Hanoglu", "author_id": 12579308, "author_profile": "https://Stackoverflow.com/users/12579308", "pm_score": 1, "selected": false, "text": "eval(\"y=12\") #SyntaxError: invalid syntax\n exec(\"y=12\")\nprint(y) #12\n" }, { "answer_id": 74581752, "author": "Dan Getz", "author_id": 3004881, "author_profile": "https://Stackoverflow.com/users/3004881", "pm_score": 1, "selected": true, "text": "eval \"obj['key1']['key2'][1]['key3'][4]['key4'][0]\"\n obj\n ['key1', 'key2', 1, 'key3', 4, 'key4', 0]\n def my_get(obj, keys): # TODO better name\n for key in keys:\n obj = obj[key]\n return obj\n def my_set(obj, keys, value): # TODO better name\n last_obj = my_get(obj, keys[:-1]) # get the last dict or list, by skipping the last key\n last_obj[keys[-1]] = value # now set the value using the last key\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20606129/" ]
74,581,672
<p>I have two files one is file1.csv and another one is file2.csv I have put file1 data in one dataframe and when second file file2.csv will arrive then I have to write a code in such a way that if second file data matches in first file data on basis of year and month columns then delete the data from file1 dataframe as it is old data and insert new file2 data in file1 dataframe</p> <p><strong>File1.csv</strong></p> <p>year month Amount</p> <p>2022 Aug 12</p> <p>2022 Oct 10</p> <p>2021 Jan 20</p> <p>2020 March 30</p> <p><strong>file2.csv</strong></p> <p>year month Amount</p> <p>2022 Jan 220</p> <p>2022 Feb 130</p> <p>2022 Oct 100</p> <p><strong>final output</strong></p> <p>year month Amount</p> <p>2022 Aug 12</p> <p>2022 Oct 100</p> <p>2021 Jan 20</p> <p>2020 March 30</p> <p>2022 Feb 130</p> <p>2022 Jan 220</p> <p>I have been trying if exists condition in pyspark but it is not working</p>
[ { "answer_id": 74581937, "author": "Bartosz Gajda", "author_id": 6870955, "author_profile": "https://Stackoverflow.com/users/6870955", "pm_score": 0, "selected": false, "text": "LEFT file2.csv file1.csv when-otherwise year-month file2.csv file1.csv when-otherwise" }, { "answer_id": 74584782, "author": "Banu", "author_id": 7241100, "author_profile": "https://Stackoverflow.com/users/7241100", "pm_score": 2, "selected": true, "text": " from pyspark.sql.functions import *\n from pyspark.sql.window import *\n\n data1 = [\n (2022, 'Aug', 12),\n (2022, 'Oct', 10),\n (2021, 'Jan', 20),\n (2020, 'March', 30)]\n\n data2 = [\n (2022, 'Jan', 220),\n (2022, 'Feb', 130),\n (2022, 'Oct', 100)]\n\n df_main = spark.createDataFrame(data1,schema = ['year', 'month', 'Amount'])\n df_incremental = spark.createDataFrame(data2,schema = ['year', 'month', 'Amount'])\n df_merge = df_incremental.unionAll(df_main)\n\n windowSpec = Window.partitionBy('year', 'month').orderBy('year', 'month')\n df_merge = df_merge.withColumn(\"_row_number\", row_number().over(windowSpec))\n df_merge = df_merge.where(df_merge._row_number == 1).drop(\"_row_number\")\n\n df_merge.show()\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13060536/" ]
74,581,673
<p>It is visible if i comment part where i set my ViewControllers.<br /> It is like been superimposed by other ViewControllers. Cause it works but i can't see it. When i tap bottom parts of screen color of screen changes to colors which i assign to controllers.</p> <p><a href="https://i.stack.imgur.com/e4qCl.png" rel="nofollow noreferrer">My run</a></p> <pre><code>import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard let windowScene = (scene as? UIWindowScene) else { return } window = UIWindow() window?.windowScene = windowScene window?.rootViewController = MusicTabBarController() window?.makeKeyAndVisible() } } </code></pre> <pre><code>class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .blue } } </code></pre> <pre><code>class SearchViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .orange } } </code></pre> <p>these are my SceneDelegate and ViewControllers codes, code of my main controller is on the screenshot</p>
[ { "answer_id": 74581937, "author": "Bartosz Gajda", "author_id": 6870955, "author_profile": "https://Stackoverflow.com/users/6870955", "pm_score": 0, "selected": false, "text": "LEFT file2.csv file1.csv when-otherwise year-month file2.csv file1.csv when-otherwise" }, { "answer_id": 74584782, "author": "Banu", "author_id": 7241100, "author_profile": "https://Stackoverflow.com/users/7241100", "pm_score": 2, "selected": true, "text": " from pyspark.sql.functions import *\n from pyspark.sql.window import *\n\n data1 = [\n (2022, 'Aug', 12),\n (2022, 'Oct', 10),\n (2021, 'Jan', 20),\n (2020, 'March', 30)]\n\n data2 = [\n (2022, 'Jan', 220),\n (2022, 'Feb', 130),\n (2022, 'Oct', 100)]\n\n df_main = spark.createDataFrame(data1,schema = ['year', 'month', 'Amount'])\n df_incremental = spark.createDataFrame(data2,schema = ['year', 'month', 'Amount'])\n df_merge = df_incremental.unionAll(df_main)\n\n windowSpec = Window.partitionBy('year', 'month').orderBy('year', 'month')\n df_merge = df_merge.withColumn(\"_row_number\", row_number().over(windowSpec))\n df_merge = df_merge.where(df_merge._row_number == 1).drop(\"_row_number\")\n\n df_merge.show()\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20606095/" ]
74,581,693
<p>Suppose, we've below demo datasets:</p> <pre><code>var demoDatasets = new DataTable { Columns = { { &quot;ID&quot;, typeof(int) }, { &quot;Name&quot;, typeof(string) }, { &quot;Address&quot;, typeof(string) } }, Rows = { { 1, &quot;A&quot;, &quot;AddressA1&quot; }, { 2, &quot;B&quot;, &quot;AddressB1&quot; }, { 3, &quot;C&quot;, &quot;AddressC1&quot; } } }; </code></pre> <p>Now, I want transfer this <em>DataTable</em> into a <em>Dictionary List</em> corresponds with both columns and rows.</p>
[ { "answer_id": 74581937, "author": "Bartosz Gajda", "author_id": 6870955, "author_profile": "https://Stackoverflow.com/users/6870955", "pm_score": 0, "selected": false, "text": "LEFT file2.csv file1.csv when-otherwise year-month file2.csv file1.csv when-otherwise" }, { "answer_id": 74584782, "author": "Banu", "author_id": 7241100, "author_profile": "https://Stackoverflow.com/users/7241100", "pm_score": 2, "selected": true, "text": " from pyspark.sql.functions import *\n from pyspark.sql.window import *\n\n data1 = [\n (2022, 'Aug', 12),\n (2022, 'Oct', 10),\n (2021, 'Jan', 20),\n (2020, 'March', 30)]\n\n data2 = [\n (2022, 'Jan', 220),\n (2022, 'Feb', 130),\n (2022, 'Oct', 100)]\n\n df_main = spark.createDataFrame(data1,schema = ['year', 'month', 'Amount'])\n df_incremental = spark.createDataFrame(data2,schema = ['year', 'month', 'Amount'])\n df_merge = df_incremental.unionAll(df_main)\n\n windowSpec = Window.partitionBy('year', 'month').orderBy('year', 'month')\n df_merge = df_merge.withColumn(\"_row_number\", row_number().over(windowSpec))\n df_merge = df_merge.where(df_merge._row_number == 1).drop(\"_row_number\")\n\n df_merge.show()\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13861641/" ]
74,581,748
<p>How to express the below in typescript?</p> <pre><code>type LanguageName = &quot;javascript&quot; | &quot;typescript&quot; | &quot;java&quot; | &quot;csharp&quot; type LanguageToWasmMap = { [key in LanguageName]: Exclude&lt;LanguageName, key&gt; } //I want the below to not throw error const languageNameToWasmNameMap: LanguageToWasmMap = { &quot;javascript&quot; : &quot;typescript&quot; } //I want the below to throw error const languageNameToWasmNameMapWithUndefined: LanguageToWasmMap = { &quot;javascript&quot; : undefined } </code></pre> <p>Typescript playground : <a href="https://www.typescriptlang.org/play?#code/AQ4FwTwBwU2AZAhgOwOYFdGpgOUQWzgF5gAiAK0QDdEBnAYwCcBLKMU4AHzMlgZbYduFaoiFl6tABaJGUUgChQwJaF5wkaTNgAqAewDqdfAFlEUYCQDeq5QG0A1jAjBmyBCgxZcBGAF0ALmAAUQAPegAbdAATGAAeTS9sPEIAGmAnCAA%20W2AAX1zcgHoigElgAHcUMHApOAAjGAi9CvA9YGQ9GrApRhbgGEY%20xlz6PWRaGojPbR9CfSNafBSYMyggxNmF4zXLYBtlEBEaflZ2YCDSdVPBXILlYrLK6tqGpv6wdp6%201sHh0fGk2A0y03hW2yWKzWBmYPQAqshYgAzNwwaIbGbeCGmcx7A6HY50JhnDhBdCImAo5Bou7AIA" rel="nofollow noreferrer">Click Here</a></p> <p>On thinking further, it makes sense to make the LanguageToWasmMap to be Optional as that it what it implies and do a runtime check for undefined.</p>
[ { "answer_id": 74581766, "author": "nullptr", "author_id": 9549012, "author_profile": "https://Stackoverflow.com/users/9549012", "pm_score": 2, "selected": true, "text": "Partial type LanguageName = \"javascript\" | \"typescript\" | \"java\" | \"csharp\"\n \n type LanguageToWasmMap = {\n [key in LanguageName]: Exclude<LanguageName, key>\n }\n \n //I want the below to not throw error\n const languageNameToWasmNameMap: Partial<LanguageToWasmMap> = {\n \"javascript\" : \"typescript\"\n }\n \n //I want the below to throw error\n const languageNameToWasmNameMapWithUndefined: LanguageToWasmMap = {\n \"javascript\" : undefined\n } \n\n" }, { "answer_id": 74581779, "author": "Dimava", "author_id": 5734961, "author_profile": "https://Stackoverflow.com/users/5734961", "pm_score": 0, "selected": false, "text": "exactOptionalPropertyTypes=true underfined type LanguageName = \"javascript\" | \"typescript\" | \"java\" | \"csharp\"\n\ntype LanguageToWasmMap = {\n [key in LanguageName]?: Exclude<LanguageName, key> | never\n}\n\n//I want the below to not throw error\nconst languageNameToWasmNameMap: LanguageToWasmMap = {\n \"javascript\": \"typescript\"\n}\n\n//I want the below to throw error\nconst languageNameToWasmNameMapWithUndefined: LanguageToWasmMap = {\n \"javascript\": undefined\n} \n" }, { "answer_id": 74581780, "author": "Ramesh", "author_id": 30594, "author_profile": "https://Stackoverflow.com/users/30594", "pm_score": 0, "selected": false, "text": "as type LanguageName = \"javascript\" | \"typescript\" | \"java\" | \"csharp\"\n\ntype LanguageToWasmMap = {\n [key in LanguageName]: Exclude<LanguageName, key>\n}\n\n//I want the below to not throw error\nconst languageNameToWasmNameMap = {\n \"javascript\" : \"typescript\"\n} as LanguageToWasmMap\n\n//I want the below to throw error\nconst languageNameToWasmNameMapWithUndefined = {\n \"javascript\" : undefined\n} as LanguageToWasmMap\n" }, { "answer_id": 74581941, "author": "Roberto Zvjerković", "author_id": 7436489, "author_profile": "https://Stackoverflow.com/users/7436489", "pm_score": 0, "selected": false, "text": " type LanguageName = \"javascript\" | \"typescript\" | \"java\" | \"csharp\"\n \n type LanguageToWasmMap<K extends LanguageName = LanguageName> = {\n [key in K]: Exclude<LanguageName, key>\n }\n \n //I want the below to not throw error\n const languageNameToWasmNameMap: LanguageToWasmMap<\"javascript\"> = {\n \"javascript\" : \"typescript\"\n }\n \n //I want the below to throw error\n const languageNameToWasmNameMapWithUndefined: LanguageToWasmMap = {\n \"javascript\" : undefined\n } \n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30594/" ]
74,581,767
<p>Hi I am getting two array of objects from APi and trying to render in a table, using spread operator i am combining the two arrays and binding but the problem is in table it is rendering two times how to combine the two arrays and print as one value in table for one email Id as emailid is unique in both the arrays.</p> <p>Below is the code and attached link of stackblitz:</p> <pre><code>export default function App() { const [allData, setAllData] = useState([]); let data = { status: 'success', Candidates: [ { Recruiter: 'Pradeep', Email: 'Pradeep@gmail.com', Total: 11, Hired: 2, interviewscheduled: 0, clientsubmitted: 1, Withdrawn: 0, Onhold: 5, inprocess: 0, Rejected: 1, Available: 0, tobeupdated: 2, }, { Recruiter: 'Sudhir', Email: 'sudhir@gmail.com', Total: 6, Hired: 1, interviewscheduled: 0, clientsubmitted: 1, Withdrawn: 0, Onhold: 1, inprocess: 0, Rejected: 0, Available: 0, tobeupdated: 3, }, ], Jobopenings: [ { Recruiter: 'Pradeep', Email: 'Pradeep@gmail.com', jobopeningTotal: 4, }, { Recruiter: 'Sudhir', Email: 'sudhir@gmail.com', jobopeningTotal: 7, }, { Recruiter: 'Marry Scott', Email: 'marrys@hsc.com', jobopeningTotal: 1, }, ], }; useEffect(() =&gt; { let data1 = [...data.Candidates, ...data.Jobopenings]; setAllData(data1); }, []); return ( &lt;div&gt; &lt;table class=&quot;table table-bordered rounded&quot;&gt; &lt;thead&gt; &lt;tr&gt; &lt;th scope=&quot;col&quot;&gt;Recruiter Name&lt;/th&gt; &lt;th scope=&quot;col&quot;&gt;Job Openings&lt;/th&gt; &lt;th scope=&quot;col&quot;&gt;Hired Candidates&lt;/th&gt; &lt;th scope=&quot;col&quot;&gt;Candidates&lt;/th&gt; &lt;th scope=&quot;col&quot;&gt;Clients' Submissions&lt;/th&gt; &lt;th scope=&quot;col&quot;&gt;Interviews Scheduled&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; {allData?.map((eachItem, index) =&gt; { return ( &lt;tbody&gt; &lt;tr key={eachItem.Email}&gt; &lt;td scope=&quot;row&quot;&gt;{eachItem.Recruiter}&lt;/td&gt; &lt;td&gt;{eachItem.jobopeningTotal}&lt;/td&gt; &lt;td&gt;{eachItem.Hired}&lt;/td&gt; &lt;td&gt;{eachItem.Total}&lt;/td&gt; &lt;td&gt;{eachItem.clientsubmitted}&lt;/td&gt; &lt;td&gt;{eachItem.interviewscheduled}&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; ); })} &lt;/table&gt; &lt;/div&gt; ); } </code></pre> <p><a href="https://stackblitz.com/edit/react-vzlp1c?file=src%2FApp.js,src%2Fstyle.css" rel="nofollow noreferrer">https://stackblitz.com/edit/react-vzlp1c?file=src%2FApp.js,src%2Fstyle.css</a></p>
[ { "answer_id": 74582488, "author": "Shayaan Farooqi", "author_id": 10905161, "author_profile": "https://Stackoverflow.com/users/10905161", "pm_score": 0, "selected": false, "text": "Keys useEffect(() => {\n function merge(arrayOne, arrayTwo, key) {\n let result = [...arrayOne];\n arrayTwo.forEach((entryTwo) => {\n let existing = result.find((entry) => entry[key] === entryTwo[key]);\n if (existing) {\n Object.assign(existing, entryTwo);\n return;\n }\n result.push(entryTwo);\n });\n return result;\n }\n setAllData(merge(data.Candidates, data.Jobopenings, 'Email'));\n }, []);\n" }, { "answer_id": 74582587, "author": "Yosvel Quintero", "author_id": 1932552, "author_profile": "https://Stackoverflow.com/users/1932552", "pm_score": 2, "selected": true, "text": "obj1 data.Candidates data.Jobopenings Email useEffect(() => {\n const obj1 = [...data.Candidates, ...data.Jobopenings]\n .map((o) => ({\n Email: o.Email,\n Recruiter: o.Recruiter,\n jobopeningTotal: o.jobopeningTotal || 0,\n Hired: o.Hired || 0,\n Total: o.Total || 0,\n clientsubmitted: o.clientsubmitted || 0,\n interviewscheduled: o.interviewscheduled || 0,\n }))\n .reduce((a, c) => {\n a[c.Email] = a[c.Email] || {\n Email: c.Email,\n Recruiter: c.Recruiter,\n jobopeningTotal: 0,\n Hired: 0,\n Total: 0,\n clientsubmitted: 0,\n interviewscheduled: 0,\n };\n a[c.Email].jobopeningTotal += c.jobopeningTotal;\n a[c.Email].Hired += c.Hired;\n a[c.Email].clientsubmitted += c.clientsubmitted;\n a[c.Email].interviewscheduled += c.interviewscheduled;\n a[c.Email].Total += c.Total;\n return a;\n }, {});\n const data1 = Object.values(obj1);\n\n setAllData(data1);\n}, []);\n" }, { "answer_id": 74582816, "author": "NAZIR HUSSAIN", "author_id": 20587701, "author_profile": "https://Stackoverflow.com/users/20587701", "pm_score": 0, "selected": false, "text": "let result = _.unionBy(data.Candidates, data.Jobopenings, \"Email\")\nresult =result.map((item,index)=>{ \nreturn {...item, jobopeningTotal:_.find(data.Jobopenings,{Email:item.Email}).jobopeningTotal }\n})\n\nconsole.log(\"Your desired output\",result);\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19614803/" ]
74,581,857
<p>I'm trying to fetch data from an api.</p> <p>So far I have tried to fetch data using an api. I have been using this website: <a href="https://www.geeksforgeeks.org/how-to-use-the-javascript-fetch-api-to-get-data/" rel="nofollow noreferrer">https://www.geeksforgeeks.org/how-to-use-the-javascript-fetch-api-to-get-data/</a> It currently console.logs my array but it does not show up in the table rows that i have created. I think i might have created the rows wrong in my html, but i cant figure how they should have been set up otherwise. Please show a small example or what to google if that is what is wrong.</p> <pre><code>The current error message i get is Uncaught (in promise) TypeError: data.list is not iterable at show (news.js:37:21) at getapi (news.js:17:2) </code></pre> <p>My javascript looks like this:</p> <pre><code> // api url const api_url = &quot;https:newsapi.org/v2/top-headlines?sources=techcrunch&amp;apiKey=xxxxxxxxx&quot;; // Defining async function async function getapi(url) { // Storing response const response = await fetch(url); // Storing data in form of JSON var data = await response.json(); console.log(data); if (response) { hideloader(); } show(data); } // Calling that async function getapi(api_url); // Function to hide the loader function hideloader() { document.getElementById('loading').style.display = 'none'; } // Function to define innerHTML for HTML table function show(data) { let tab = `&lt;tr&gt; &lt;th&gt;Author&lt;/th&gt; &lt;th&gt;Title&lt;/th&gt; &lt;th&gt;Description&lt;/th&gt; &lt;th&gt;Url&lt;/th&gt; &lt;/tr&gt;`; // Loop to access all rows for (let r of data.list) { tab += `&lt;tr&gt; &lt;td&gt;${r.author}&lt;/td&gt; &lt;td&gt;${r.title}&lt;/td&gt; &lt;td&gt;${r.description}&lt;/td&gt; &lt;td&gt;${r.url}&lt;/td&gt; &lt;/tr&gt;`; } // Setting innerHTML as tab variable document.getElementById(&quot;news&quot;).innerHTML = tab; } &lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;script src=&quot;news.js&quot;&gt;&lt;/script&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;test.css&quot; /&gt; &lt;meta charset=&quot;UTF-8&quot; /&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt; &lt;title&gt;Document&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;!-- Here a loader is created which loads till response comes --&gt; &lt;div class=&quot;d-flex justify-content-center&quot;&gt; &lt;div class=&quot;spinner-border&quot; role=&quot;status&quot; id=&quot;loading&quot;&gt; &lt;span class=&quot;sr-only&quot;&gt;Loading...&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;h1&gt;News&lt;/h1&gt; &lt;!-- table for showing data --&gt; &lt;table id=&quot;news&quot;&gt;&lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 74583303, "author": "DataFace", "author_id": 10761390, "author_profile": "https://Stackoverflow.com/users/10761390", "pm_score": 2, "selected": false, "text": "// api url\nconst api_url = 'https://jsonplaceholder.typicode.com/comments';\n\n// Defining async function\nasync function getapi(url) {\n await fetch(url)\n .then((response) => response.json())\n .then((data) => {\n console.log(data)\n hideloader();\n show(data)\n });\n}\n\n// Calling that async function\ngetapi(api_url);\n\n// Function to hide the loader\nfunction hideloader() {\n document.getElementById('loading').style.display = 'none';\n}\n\n// Function to define innerHTML for HTML table\nfunction show(data) {\n let tab =\n `<tr>\n <th>id</th>\n <th>Name</th>\n <th>Body</th>\n <th>Email</th>\n </tr>`;\n \n // Loop to access all rows\n for (let r of data) {\n tab += `<tr>\n <td>${r.id}</td>\n <td>${r.name}</td>\n <td>${r.body}</td>\n <td>${r.email}</td>\n </tr>`;\n }\n // Setting innerHTML as tab variable\n document.getElementById(\"news\").innerHTML = tab;\n} <!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <script src=\"news.js\"></script>\n <link rel=\"stylesheet\" href=\"test.css\" />\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" \n content=\"width=device-width, initial-scale=1.0\" />\n <title>Document</title>\n </head>\n <body>\n <!-- Here a loader is created which \n loads till response comes -->\n <div class=\"d-flex justify-content-center\">\n <div class=\"spinner-border\" \n role=\"status\" id=\"loading\">\n <span class=\"sr-only\">Loading...</span>\n </div>\n </div>\n <h1>News</h1>\n <!-- table for showing data -->\n <table id=\"news\"></table>\n </body>\n</html>" }, { "answer_id": 74600629, "author": "D0ctorheese", "author_id": 20088801, "author_profile": "https://Stackoverflow.com/users/20088801", "pm_score": 1, "selected": true, "text": "const url = \"xxxxxxx\"\n fetch(url)\n .then((response) => response.json()) \n .then((data) => {\n console.log(data)\n\n let title = document.getElementById(\"title\");\n title.innerText = data.articles[0].title;\n\n let title1 = document.getElementById(\"title1\");\n title1.innerText = data.articles[1].title;\n\n let title2 = document.getElementById(\"title2\");\n title2.innerText = data.articles[2].title;\n\n let title3 = document.getElementById(\"title3\");\n title3.innerText = data.articles[3].title;\n\n let title4 = document.getElementById(\"title4\");\n title4.innerText = data.articles[4].title;\n\n let title5 = document.getElementById(\"title5\");\n title5.innerText = data.articles[5].title;\n });\n <p id=\"title1\"></p>\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20088801/" ]
74,581,861
<ul> <li>I have a variable which contains a map of widget in initState.</li> <li>One of this widget inside my variable is a gestureDetector who onTap change the value of a variable to change the animation of his child AnimatedAlign.</li> </ul> <p>My problem is that when I active the onTap my animatedAlign stay static.</p> <p>How should I do to be able to toogle the value of selected ?</p> <pre><code>import 'dart:developer'; import 'package:flutter/material.dart'; class HomeScreen extends StatefulWidget { const HomeScreen({Key? key}) : super(key: key); @override State&lt;HomeScreen&gt; createState() =&gt; _HomeScreenState(); } class _HomeScreenState extends State&lt;HomeScreen&gt; { late Map&lt;String, Map&lt;String, List&lt;Widget&gt;&gt;&gt; data; bool selected = false; @override void initState() { // TODO: implement initState data = { &quot;Animation and motion widgets&quot;: { &quot;AnimatedAlign&quot;: [ GestureDetector( onTap: () { setState(() { selected = !selected; }); log('$selected inside data'); }, child: Center( child: Container( width: 250.0, height: 250.0, color: Colors.red, child: AnimatedAlign( alignment: selected ? Alignment.topRight : Alignment.bottomLeft, duration: const Duration(seconds: 1), curve: Curves.easeInCirc, child: const FlutterLogo(size: 50.0), ), ), ), ) ], }, &quot;Animation and motion widgets2&quot;: { &quot;2widget1&quot;: [const Text('2widget1')], &quot;2widget2&quot;: [const Text('2widget2')] } }; super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Widget catalog'), ), body: PageView( children: _getCategories(), ), ); } List&lt;Widget&gt; _getCategories() { List&lt;Widget&gt; categories = []; for (int i = 0; i &lt; data.length; i++) { categories.add( PageView( scrollDirection: Axis.vertical, children: getWidgets(i), ), ); } return categories; } List&lt;Widget&gt; getWidgets(i) { List&lt;Widget&gt; widgetPage = []; widgetPage.add(Container( color: Colors.red, child: Center( child: Text(data.keys.toList()[i]), ), )); data[data.keys.toList()[i]]!.forEach((key, value) { widgetPage.add(Container( color: Colors.blue, child: Padding( padding: const EdgeInsets.only(top: 20.0), child: Column( children: [ Center(child: Text(key)), Padding( padding: const EdgeInsets.all(20.0), child: Column( children: value, ), ), ], ), ), )); }); return widgetPage; } } </code></pre>
[ { "answer_id": 74582358, "author": "Shahood ul Hassan", "author_id": 7983864, "author_profile": "https://Stackoverflow.com/users/7983864", "pm_score": 2, "selected": true, "text": "setState() build() initState() StatefulWidget HomeScreen AnimatedAlign initState() setState() AnimatedAlign data data build() initState()" }, { "answer_id": 74582394, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 0, "selected": false, "text": " Map<String, Map<String, List<Widget>>> data() => {\n \"Animation and motion widgets\": {\n data data()" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20605896/" ]
74,581,868
<p>So, I started making a program and now I require it to print anything I like if the number is between 1-100, How to I make the program realize that it needs to print it if the number's between 90 and 100?</p> <pre><code>#This is a sample code F2 = int(input()) if F2 == range(90 , 100): print(&quot;A&quot;) else: print(&quot;BRUH&quot;) </code></pre> <p>I'm really new to this, I'll be very thankful if someone could help me</p>
[ { "answer_id": 74581965, "author": "solac34", "author_id": 20554831, "author_profile": "https://Stackoverflow.com/users/20554831", "pm_score": 2, "selected": false, "text": "if F2 in range(90,101): #last number is not included in range(101 won't be included)\n print('A')\n f2 = range(90,100)\nprint(f2)\n" }, { "answer_id": 74581983, "author": "raiyan22", "author_id": 9550867, "author_profile": "https://Stackoverflow.com/users/9550867", "pm_score": 1, "selected": false, "text": "#This is a sample code\nF2 = int(input())\nif F2 >=90 and F2 <=100:\n print(\"A\")\nelse:\n print(\"BRUH\")\n" }, { "answer_id": 74582060, "author": "Arifa Chan", "author_id": 19574157, "author_profile": "https://Stackoverflow.com/users/19574157", "pm_score": 1, "selected": false, "text": "in == print(\"A\" if (F2 := int(input())) in range(90,101) else \"BRUH\")\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20042225/" ]
74,581,875
<p>I'm looking to add the Firestore ID to the DocumentData, so that I can easily utilize the ID when referring to rows in a table, without having to use document.data().property everytime I call a property of a document. Instead, I want to be able to call document.id.... document.property... and so on.</p> <p>Is there an easy way to do this? Possibly with a Cloud Function that adds the auto-generated ID to the document data?</p> <p>Thanks!</p> <hr /> <p>Example:</p> <pre><code>export const getSpaces = async () =&gt; { const spaceDocs = await getDocs(spacesCollection) spaceDocs.docs.forEach((spaceDoc) =&gt; { const spaceID = spaceDoc.id const spaceData = spaceDoc.data() console.log(spaceID) spaces.value.push(spaceData) }) } </code></pre> <p>Now, the spaces array has objects containing the data of the documents. But, I loose the ability to reference the ID of a document.</p> <p>Alternatively, I can add the entire document to the array, but following that, I'll have to access the properties by always including the data() in between. I.e. space.data().name</p> <p>I'm certain, theres a better way</p>
[ { "answer_id": 74581965, "author": "solac34", "author_id": 20554831, "author_profile": "https://Stackoverflow.com/users/20554831", "pm_score": 2, "selected": false, "text": "if F2 in range(90,101): #last number is not included in range(101 won't be included)\n print('A')\n f2 = range(90,100)\nprint(f2)\n" }, { "answer_id": 74581983, "author": "raiyan22", "author_id": 9550867, "author_profile": "https://Stackoverflow.com/users/9550867", "pm_score": 1, "selected": false, "text": "#This is a sample code\nF2 = int(input())\nif F2 >=90 and F2 <=100:\n print(\"A\")\nelse:\n print(\"BRUH\")\n" }, { "answer_id": 74582060, "author": "Arifa Chan", "author_id": 19574157, "author_profile": "https://Stackoverflow.com/users/19574157", "pm_score": 1, "selected": false, "text": "in == print(\"A\" if (F2 := int(input())) in range(90,101) else \"BRUH\")\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16479677/" ]
74,581,879
<p>I want to insert data from the database into an array that can be increased in number. So maybe you can use a loop but the data is stacked, not added and returns the last data</p> <p>i am trying to use for with $i++ to generate $variable.$i. that's what I was expecting but I don't understand how to run it</p> <pre><code>for ($i = 1; $i &lt; $sumjnssuara; $i++){ $koleksi = []; ${&quot;suwara{$i}&quot;} = DB::table('suara')-&gt;where('suara','Suara '.$i)-&gt;pluck('jml_suara')-&gt;sum(); array_push($koleksi, ${&quot;suwara{$i}&quot;}); } </code></pre> <p>the problem might be solved if $suwara1++ and makes the $koleksi array grow</p>
[ { "answer_id": 74581965, "author": "solac34", "author_id": 20554831, "author_profile": "https://Stackoverflow.com/users/20554831", "pm_score": 2, "selected": false, "text": "if F2 in range(90,101): #last number is not included in range(101 won't be included)\n print('A')\n f2 = range(90,100)\nprint(f2)\n" }, { "answer_id": 74581983, "author": "raiyan22", "author_id": 9550867, "author_profile": "https://Stackoverflow.com/users/9550867", "pm_score": 1, "selected": false, "text": "#This is a sample code\nF2 = int(input())\nif F2 >=90 and F2 <=100:\n print(\"A\")\nelse:\n print(\"BRUH\")\n" }, { "answer_id": 74582060, "author": "Arifa Chan", "author_id": 19574157, "author_profile": "https://Stackoverflow.com/users/19574157", "pm_score": 1, "selected": false, "text": "in == print(\"A\" if (F2 := int(input())) in range(90,101) else \"BRUH\")\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19822838/" ]
74,581,893
<p>I am testing <code>React.useEffect</code> and noticed an interesting behavior that I can't explain. When I run the code below and click on the button a few times, I see the following output which is missing the useEffect console for count = 1</p> <pre><code>import React from 'react'; export function App(props) { const [count, setCount] = React.useState(0) console.log('ran app') React.useEffect(() =&gt; { console.log(&quot;ran effect&quot;, count) }, [count &lt; 2]) return ( &lt;div className='App'&gt; &lt;button onClick={() =&gt; setCount(count + 1)}&gt;click&lt;/button&gt; &lt;h3&gt;{count}&lt;/h3&gt; &lt;/div&gt; ); } </code></pre> <pre><code>ran app ran effect 0 ran app // this is where I expect to see ran effect for count = 1 but I don't ran app ran effect 2 ran app ran app </code></pre> <p>However if I remove the expression <code>count&lt;2</code> from the dependencies, I see <code>ran useeffect</code> for <code>count = 1</code> as well.</p>
[ { "answer_id": 74581965, "author": "solac34", "author_id": 20554831, "author_profile": "https://Stackoverflow.com/users/20554831", "pm_score": 2, "selected": false, "text": "if F2 in range(90,101): #last number is not included in range(101 won't be included)\n print('A')\n f2 = range(90,100)\nprint(f2)\n" }, { "answer_id": 74581983, "author": "raiyan22", "author_id": 9550867, "author_profile": "https://Stackoverflow.com/users/9550867", "pm_score": 1, "selected": false, "text": "#This is a sample code\nF2 = int(input())\nif F2 >=90 and F2 <=100:\n print(\"A\")\nelse:\n print(\"BRUH\")\n" }, { "answer_id": 74582060, "author": "Arifa Chan", "author_id": 19574157, "author_profile": "https://Stackoverflow.com/users/19574157", "pm_score": 1, "selected": false, "text": "in == print(\"A\" if (F2 := int(input())) in range(90,101) else \"BRUH\")\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5601401/" ]
74,581,902
<p>How can I create a keybinding in Dr Racket to duplicate selected lines?</p> <pre><code>#lang s-exp framework/keybinding-lang (keybinding &quot;m:d&quot; (λ (editor evt) ...)) </code></pre>
[ { "answer_id": 74581965, "author": "solac34", "author_id": 20554831, "author_profile": "https://Stackoverflow.com/users/20554831", "pm_score": 2, "selected": false, "text": "if F2 in range(90,101): #last number is not included in range(101 won't be included)\n print('A')\n f2 = range(90,100)\nprint(f2)\n" }, { "answer_id": 74581983, "author": "raiyan22", "author_id": 9550867, "author_profile": "https://Stackoverflow.com/users/9550867", "pm_score": 1, "selected": false, "text": "#This is a sample code\nF2 = int(input())\nif F2 >=90 and F2 <=100:\n print(\"A\")\nelse:\n print(\"BRUH\")\n" }, { "answer_id": 74582060, "author": "Arifa Chan", "author_id": 19574157, "author_profile": "https://Stackoverflow.com/users/19574157", "pm_score": 1, "selected": false, "text": "in == print(\"A\" if (F2 := int(input())) in range(90,101) else \"BRUH\")\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3575062/" ]
74,581,911
<p>I would like to call HTTP request with method GET to get an ID. I call the request from Angular 14 and i take 200 response, but it's red color.</p> <p><a href="https://i.stack.imgur.com/P8irf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/P8irf.png" alt="Response for GET request" /></a></p> <p>I have the response body, but Angular treats the response as false.</p> <p><a href="https://i.stack.imgur.com/fghV3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fghV3.png" alt="Content response for GET request" /></a></p> <p>And i have this message in the navigator console.</p> <p><a href="https://i.stack.imgur.com/rge7J.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rge7J.png" alt="Error message for GET request" /></a></p> <p>Translate --&gt; &quot;Reason: CORS header 'Access-Control-Allow-Origin' does not match&quot;</p> <p>My server is in Springboot, this is my controller :</p> <pre><code>@CrossOrigin(origins = &quot;*&quot;) @GetMapping(&quot;/api/user/exist/{username}&quot;) public long getMemberIdIfUserExist(@PathVariable final String username) { return accountService.getMemberIdIfUserExist(username); } </code></pre> <p>And i add this in my security config: <code>http.cors();</code></p> <p>My Angular app is in docker container with Nginx:</p> <pre><code>FROM node:18.12.1-alpine3.16 AS build WORKDIR /dist/src/app RUN npm cache clean --force COPY . . RUN npm install RUN npm run build --omit=dev FROM nginx:1.23.2-alpine AS ngi COPY --from=build /dist/src/app/dist/ng-app /usr/share/nginx/html COPY /nginx-main.conf /etc/nginx/nginx.conf EXPOSE 80 </code></pre> <p>The Angular call :</p> <pre><code>ifRegistred(facebookId: string): Observable&lt;number&gt; { console.error('function :: ifRegistred'); let url = 'https://api.app.com/ws/api/user/exist/'+facebookId; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; return this.http.get&lt;number&gt;(url, httpOptions).pipe( tap(memberId =&gt; { console.error('function :: ifRegistred -&gt; success'); }), catchError((error) =&gt; { console.error('function :: ifRegistred -&gt; failed'); this.httpError(error); return of(0); }) ); } </code></pre> <p>And the traefik labels : (i am using v1.7)</p> <pre><code>- &quot;traefik.frontend.headers.customResponseHeaders=Access-Control-Allow-Origin:*||Access-Control-Allow-Methods:GET,POST,OPTIONS||Access-Control-Allow-Headers:DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range||Access-Control-Expose-Headers:Content-Length,Content-Range&quot; </code></pre> <p>I need help !</p>
[ { "answer_id": 74581977, "author": "Quentin", "author_id": 19068, "author_profile": "https://Stackoverflow.com/users/19068", "pm_score": 1, "selected": false, "text": "Access-Control-Allow-Origin: *, * Access-Control-Allow-Origin: * * * Access-Control-Allow-Origin" }, { "answer_id": 74599293, "author": "NAD", "author_id": 12627958, "author_profile": "https://Stackoverflow.com/users/12627958", "pm_score": -1, "selected": false, "text": "http.cors(); @CrossOrigin(origins = \"*\")" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12627958/" ]
74,581,912
<p>I have the following list:</p> <p><code>lst = ['L38A', '38', 'L', 'A', '-6.7742', '-3.5671', '0.00226028', '0.4888', 'L38C', '38', 'L', 'C', '-7.7904', '-6.6306', '0.0', '0.4888', 'L38D', '38', 'L', 'D', '-6.3475', '-3.0068', '0.00398551', '0.4888', 'L38E', '38', 'L', 'E', '-6.4752', '-3.4645', '0.00250913', '0.4888']</code></p> <p>I'm looking to extract the first element (posiiton 0) in the list ('L38A') and the 5th element (position 4) (-6.7742) multiple times:</p> <p>Desired output <code>[('L38A','-6.7742'), ('L38C','-7.7904'), ('L38D','-6.3475')...('L38E','-6.4752')]</code></p> <p>I have tried: <code>lst[::5]</code></p>
[ { "answer_id": 74581977, "author": "Quentin", "author_id": 19068, "author_profile": "https://Stackoverflow.com/users/19068", "pm_score": 1, "selected": false, "text": "Access-Control-Allow-Origin: *, * Access-Control-Allow-Origin: * * * Access-Control-Allow-Origin" }, { "answer_id": 74599293, "author": "NAD", "author_id": 12627958, "author_profile": "https://Stackoverflow.com/users/12627958", "pm_score": -1, "selected": false, "text": "http.cors(); @CrossOrigin(origins = \"*\")" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11586653/" ]
74,581,914
<p>I am new at coding but it feels like I am stuck on some stupid level thing!!! I want my dynamic text on center of my page and slightly top of my button. But long text just overlapping my button. I want both of them to adjust in screen and stay in completely center of page no matter how long the text is. <strong>See this</strong> <a href="https://i.stack.imgur.com/VfjPb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VfjPb.png" alt="enter image description here" /></a></p> <p>And small text starts from left which I also want to be in center. <strong>See this</strong><a href="https://i.stack.imgur.com/7G0tV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7G0tV.png" alt="enter image description here" /></a></p> <p>Here is my code</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;script&gt; const arr = [ { title: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book." }, { title: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.' }, { title: "Name2" }, { title: "Name3" }, { title: "Name4" } ]; function onClickHandler() { const ul = document.getElementsByTagName('ul')[0]; const item = arr[Math.floor(Math.random() * arr.length)]; ul.innerHTML = ` &lt;p style= "position: absolute; text-align: center; top: 42%; "&gt; ${item.title} &lt;/p&gt;`; } &lt;/script&gt; &lt;title&gt; Random Site&lt;/title&gt; &lt;body&gt; &lt;button onclick="onClickHandler()" style= " position: absolute; top: 50%; left: 50%;"&gt;Button&lt;/button&gt; &lt;ul&gt;&lt;/ul&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74582029, "author": "pier farrugia", "author_id": 19996700, "author_profile": "https://Stackoverflow.com/users/19996700", "pm_score": 0, "selected": false, "text": "const arr = [{\n title: \"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.\"\n },\n {\n title: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.'\n },\n {\n title: \"Name2\"\n },\n {\n title: \"Name3\"\n },\n {\n title: \"Name4\"\n }\n];\n\nfunction onClickHandler() {\n const ul = document.getElementsByTagName('ul')[0];\n const item = arr[Math.floor(Math.random() * arr.length)];\n ul.innerHTML = `<p>${item.title}</p>`;\n} button {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n}\n\np {\n position: absolute;\n text-align: center;\n bottom: 50%;\n} <button onclick=\"onClickHandler()\">Button</button>\n<ul></ul>" }, { "answer_id": 74582076, "author": "Xiduzo", "author_id": 4655177, "author_profile": "https://Stackoverflow.com/users/4655177", "pm_score": 2, "selected": true, "text": "ul style=\"padding: 0;\" ul <html>\n\n<head>\n <script>\n const arr = [\n { title: \"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.\" },\n { title: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.' },\n { title: \"Name2\" },\n { title: \"Name3\" },\n { title: \"Name4\" }\n ];\n\n function onClickHandler() {\n const ul = document.getElementsByTagName('ul')[0];\n const item = arr[Math.floor(Math.random() * arr.length)];\n ul.innerHTML = `\n <p>\n ${item.title}\n </p>`;\n }\n </script>\n <title> Random Site</title>\n\n<body style=\"display: flex; flex-direction: column-reverse; justify-content: center; align-items:center; height: 100vh; marign: 0; padding: 10px;\">\n <button onclick=\"onClickHandler()\">Button</button>\n <ul style=\"padding: 0;\"></ul>\n</body>\n\n</html>" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74581914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14466362/" ]
74,582,063
<p>I have this data (original data has more rows) below :</p> <pre><code>structure(list(ID = 1:41, X1 = c(1921498, 2519663, 2519663, 107388, 2519663, 52211, 2519663, 62831, 62831, 62831, 62831, 62831, 62831, 62831, 4225203351, 4225203351, 4225203351, 4225203351, 4225203351, 4225203351, 4225203351, 171231, 171231, 171231, 183111, 171231, 190461, 190461, 190461, 190461, 190461, 190461, 183041, 190461, 191151, 210321, 210321, 210321, 210321, 211051, 211051)), class = &quot;data.frame&quot;, row.names = c(NA, -41L)) </code></pre> <p>I'm trying to find a way to detect where a real change has happened. for example, I know in rows 4 and 6 no change happened because I went back to the value that I used often which is &quot;2519663&quot; then a real change happened in row 8 because I started using the value &quot;62831&quot; often. Then another change happened in row 15 because I started using the value &quot;4225203351&quot; and another one in row 22 because I started using the value &quot;171231&quot; but in row 25 I know no change happened because I used it the value &quot;183111&quot; one time and went back to &quot;171231&quot; again. and The change happened in row 27. another real change happened in row 36 because I don't use the value &quot;190461&quot; anymore. and the last change in my vector is in row 40:</p> <p><a href="https://i.stack.imgur.com/KTZm6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KTZm6.png" alt="enter image description here" /></a></p> <p>My final result should look like this:</p> <p><a href="https://i.stack.imgur.com/JeBpL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JeBpL.png" alt="enter image description here" /></a></p> <p>Thanks in advance !</p>
[ { "answer_id": 74582241, "author": "Vinícius Félix", "author_id": 9696037, "author_profile": "https://Stackoverflow.com/users/9696037", "pm_score": 0, "selected": false, "text": "library(dplyr)\ndf %>% \n mutate(\n var2 = c(0,diff(X1)),\n var2 = if_else(var2 == 0, \"No-change\",\"Change\")\n )\n\n ID X1 var2\n1 1 1921498 No-change\n2 2 2519663 Change\n3 3 2519663 No-change\n4 4 107388 Change\n5 5 2519663 Change\n6 6 52211 Change\n7 7 2519663 Change\n8 8 62831 Change\n9 9 62831 No-change\n10 10 62831 No-change\n11 11 62831 No-change\n12 12 62831 No-change\n13 13 62831 No-change\n14 14 62831 No-change\n15 15 4225203351 Change\n16 16 4225203351 No-change\n17 17 4225203351 No-change\n18 18 4225203351 No-change\n19 19 4225203351 No-change\n20 20 4225203351 No-change\n21 21 4225203351 No-change\n22 22 171231 Change\n23 23 171231 No-change\n24 24 171231 No-change\n25 25 183111 Change\n26 26 171231 Change\n27 27 190461 Change\n28 28 190461 No-change\n29 29 190461 No-change\n30 30 190461 No-change\n31 31 190461 No-change\n32 32 190461 No-change\n33 33 183041 Change\n34 34 190461 Change\n35 35 191151 Change\n36 36 210321 Change\n37 37 210321 No-change\n38 38 210321 No-change\n39 39 210321 No-change\n40 40 211051 Change\n41 41 211051 No-change\n" }, { "answer_id": 74582254, "author": "Rui Barradas", "author_id": 8245406, "author_profile": "https://Stackoverflow.com/users/8245406", "pm_score": 2, "selected": false, "text": "df1 <-\n structure(list(\n ID = 1:41, \n X1 = c(1921498, 2519663, 2519663, 107388, \n 2519663, 52211, 2519663, 62831, 62831, 62831, 62831, 62831, 62831, \n 62831, 4225203351, 4225203351, 4225203351, 4225203351, 4225203351, \n 4225203351, 4225203351, 171231, 171231, 171231, 183111, 171231, \n 190461, 190461, 190461, 190461, 190461, 190461, 183041, 190461, \n 191151, 210321, 210321, 210321, 210321, 211051, 211051)), \n class = \"data.frame\", row.names = c(NA, -41L))\n\nchanges <- function(x, col, newcol, thresh = 2L) {\n r <- rle(x[[col]])\n i <- r$lengths > thresh\n r$values[!i] <- \"no change\"\n rr <- inverse.rle(r)\n rr <- as.integer(factor(rr))\n j <- c(0, diff(rr)) != 0\n x[[newcol]] <- \"no change\"\n x[[newcol]][j] <- \"change\"\n x\n}\n\nchanges(df1, \"X1\", \"var3\")\n#> ID X1 var3\n#> 1 1 1921498 no change\n#> 2 2 2519663 no change\n#> 3 3 2519663 no change\n#> 4 4 107388 no change\n#> 5 5 2519663 no change\n#> 6 6 52211 no change\n#> 7 7 2519663 no change\n#> 8 8 62831 change\n#> 9 9 62831 no change\n#> 10 10 62831 no change\n#> 11 11 62831 no change\n#> 12 12 62831 no change\n#> 13 13 62831 no change\n#> 14 14 62831 no change\n#> 15 15 4225203351 change\n#> 16 16 4225203351 no change\n#> 17 17 4225203351 no change\n#> 18 18 4225203351 no change\n#> 19 19 4225203351 no change\n#> 20 20 4225203351 no change\n#> 21 21 4225203351 no change\n#> 22 22 171231 change\n#> 23 23 171231 no change\n#> 24 24 171231 no change\n#> 25 25 183111 change\n#> 26 26 171231 no change\n#> 27 27 190461 change\n#> 28 28 190461 no change\n#> 29 29 190461 no change\n#> 30 30 190461 no change\n#> 31 31 190461 no change\n#> 32 32 190461 no change\n#> 33 33 183041 change\n#> 34 34 190461 no change\n#> 35 35 191151 no change\n#> 36 36 210321 change\n#> 37 37 210321 no change\n#> 38 38 210321 no change\n#> 39 39 210321 no change\n#> 40 40 211051 change\n#> 41 41 211051 no change\n" }, { "answer_id": 74582669, "author": "zephryl", "author_id": 17303805, "author_profile": "https://Stackoverflow.com/users/17303805", "pm_score": 2, "selected": true, "text": "library(dplyr)\nlibrary(tidyr)\n\ndat %>%\n mutate(cur_X1 = ifelse(\n X1 == lead(X1) | X1 == lag(X1), \n X1, \n NA\n )) %>%\n fill(cur_X1, .direction = \"downup\") %>%\n mutate(\n var3 = replace_na(\n ifelse(cur_X1 != lag(cur_X1), \"Change\", \"No-change\"),\n \"No-change\"\n ),\n cur_X1 = NULL\n )\n ID X1 var3\n1 1 1921498 No-change\n2 2 2519663 No-change\n3 3 2519663 No-change\n4 4 107388 No-change\n5 5 2519663 No-change\n6 6 52211 No-change\n7 7 2519663 No-change\n8 8 62831 Change\n9 9 62831 No-change\n10 10 62831 No-change\n11 11 62831 No-change\n12 12 62831 No-change\n13 13 62831 No-change\n14 14 62831 No-change\n15 15 4225203351 Change\n16 16 4225203351 No-change\n17 17 4225203351 No-change\n18 18 4225203351 No-change\n19 19 4225203351 No-change\n20 20 4225203351 No-change\n21 21 4225203351 No-change\n22 22 171231 Change\n23 23 171231 No-change\n24 24 171231 No-change\n25 25 183111 No-change\n26 26 171231 No-change\n27 27 190461 Change\n28 28 190461 No-change\n29 29 190461 No-change\n30 30 190461 No-change\n31 31 190461 No-change\n32 32 190461 No-change\n33 33 183041 No-change\n34 34 190461 No-change\n35 35 191151 No-change\n36 36 210321 Change\n37 37 210321 No-change\n38 38 210321 No-change\n39 39 210321 No-change\n40 40 211051 Change\n41 41 211051 No-change\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12322285/" ]
74,582,094
<p>In a website having a &quot;Comment&quot; and &quot;reply to a comment&quot; system.<br> After each comment in the template, There's a &quot;Add a reply&quot; form which have a hidden input to carry the comment pk on its value attribute.</p> <ul> <li>How to prevent the end user from editing that hidden input value ?<br></li> <li>And If this is not possible, What would be the correct approach ?</li> </ul>
[ { "answer_id": 74582241, "author": "Vinícius Félix", "author_id": 9696037, "author_profile": "https://Stackoverflow.com/users/9696037", "pm_score": 0, "selected": false, "text": "library(dplyr)\ndf %>% \n mutate(\n var2 = c(0,diff(X1)),\n var2 = if_else(var2 == 0, \"No-change\",\"Change\")\n )\n\n ID X1 var2\n1 1 1921498 No-change\n2 2 2519663 Change\n3 3 2519663 No-change\n4 4 107388 Change\n5 5 2519663 Change\n6 6 52211 Change\n7 7 2519663 Change\n8 8 62831 Change\n9 9 62831 No-change\n10 10 62831 No-change\n11 11 62831 No-change\n12 12 62831 No-change\n13 13 62831 No-change\n14 14 62831 No-change\n15 15 4225203351 Change\n16 16 4225203351 No-change\n17 17 4225203351 No-change\n18 18 4225203351 No-change\n19 19 4225203351 No-change\n20 20 4225203351 No-change\n21 21 4225203351 No-change\n22 22 171231 Change\n23 23 171231 No-change\n24 24 171231 No-change\n25 25 183111 Change\n26 26 171231 Change\n27 27 190461 Change\n28 28 190461 No-change\n29 29 190461 No-change\n30 30 190461 No-change\n31 31 190461 No-change\n32 32 190461 No-change\n33 33 183041 Change\n34 34 190461 Change\n35 35 191151 Change\n36 36 210321 Change\n37 37 210321 No-change\n38 38 210321 No-change\n39 39 210321 No-change\n40 40 211051 Change\n41 41 211051 No-change\n" }, { "answer_id": 74582254, "author": "Rui Barradas", "author_id": 8245406, "author_profile": "https://Stackoverflow.com/users/8245406", "pm_score": 2, "selected": false, "text": "df1 <-\n structure(list(\n ID = 1:41, \n X1 = c(1921498, 2519663, 2519663, 107388, \n 2519663, 52211, 2519663, 62831, 62831, 62831, 62831, 62831, 62831, \n 62831, 4225203351, 4225203351, 4225203351, 4225203351, 4225203351, \n 4225203351, 4225203351, 171231, 171231, 171231, 183111, 171231, \n 190461, 190461, 190461, 190461, 190461, 190461, 183041, 190461, \n 191151, 210321, 210321, 210321, 210321, 211051, 211051)), \n class = \"data.frame\", row.names = c(NA, -41L))\n\nchanges <- function(x, col, newcol, thresh = 2L) {\n r <- rle(x[[col]])\n i <- r$lengths > thresh\n r$values[!i] <- \"no change\"\n rr <- inverse.rle(r)\n rr <- as.integer(factor(rr))\n j <- c(0, diff(rr)) != 0\n x[[newcol]] <- \"no change\"\n x[[newcol]][j] <- \"change\"\n x\n}\n\nchanges(df1, \"X1\", \"var3\")\n#> ID X1 var3\n#> 1 1 1921498 no change\n#> 2 2 2519663 no change\n#> 3 3 2519663 no change\n#> 4 4 107388 no change\n#> 5 5 2519663 no change\n#> 6 6 52211 no change\n#> 7 7 2519663 no change\n#> 8 8 62831 change\n#> 9 9 62831 no change\n#> 10 10 62831 no change\n#> 11 11 62831 no change\n#> 12 12 62831 no change\n#> 13 13 62831 no change\n#> 14 14 62831 no change\n#> 15 15 4225203351 change\n#> 16 16 4225203351 no change\n#> 17 17 4225203351 no change\n#> 18 18 4225203351 no change\n#> 19 19 4225203351 no change\n#> 20 20 4225203351 no change\n#> 21 21 4225203351 no change\n#> 22 22 171231 change\n#> 23 23 171231 no change\n#> 24 24 171231 no change\n#> 25 25 183111 change\n#> 26 26 171231 no change\n#> 27 27 190461 change\n#> 28 28 190461 no change\n#> 29 29 190461 no change\n#> 30 30 190461 no change\n#> 31 31 190461 no change\n#> 32 32 190461 no change\n#> 33 33 183041 change\n#> 34 34 190461 no change\n#> 35 35 191151 no change\n#> 36 36 210321 change\n#> 37 37 210321 no change\n#> 38 38 210321 no change\n#> 39 39 210321 no change\n#> 40 40 211051 change\n#> 41 41 211051 no change\n" }, { "answer_id": 74582669, "author": "zephryl", "author_id": 17303805, "author_profile": "https://Stackoverflow.com/users/17303805", "pm_score": 2, "selected": true, "text": "library(dplyr)\nlibrary(tidyr)\n\ndat %>%\n mutate(cur_X1 = ifelse(\n X1 == lead(X1) | X1 == lag(X1), \n X1, \n NA\n )) %>%\n fill(cur_X1, .direction = \"downup\") %>%\n mutate(\n var3 = replace_na(\n ifelse(cur_X1 != lag(cur_X1), \"Change\", \"No-change\"),\n \"No-change\"\n ),\n cur_X1 = NULL\n )\n ID X1 var3\n1 1 1921498 No-change\n2 2 2519663 No-change\n3 3 2519663 No-change\n4 4 107388 No-change\n5 5 2519663 No-change\n6 6 52211 No-change\n7 7 2519663 No-change\n8 8 62831 Change\n9 9 62831 No-change\n10 10 62831 No-change\n11 11 62831 No-change\n12 12 62831 No-change\n13 13 62831 No-change\n14 14 62831 No-change\n15 15 4225203351 Change\n16 16 4225203351 No-change\n17 17 4225203351 No-change\n18 18 4225203351 No-change\n19 19 4225203351 No-change\n20 20 4225203351 No-change\n21 21 4225203351 No-change\n22 22 171231 Change\n23 23 171231 No-change\n24 24 171231 No-change\n25 25 183111 No-change\n26 26 171231 No-change\n27 27 190461 Change\n28 28 190461 No-change\n29 29 190461 No-change\n30 30 190461 No-change\n31 31 190461 No-change\n32 32 190461 No-change\n33 33 183041 No-change\n34 34 190461 No-change\n35 35 191151 No-change\n36 36 210321 Change\n37 37 210321 No-change\n38 38 210321 No-change\n39 39 210321 No-change\n40 40 211051 Change\n41 41 211051 No-change\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15941405/" ]
74,582,097
<p>I am trying to calculate the number of digits in a random number, for example for number 5675, I am expecting a count value 4 as an output but instead of that , it's returning 1. I have tried to write the logic in a while loop until the condition satisfied. Below is my code.</p> <pre><code>class Solution(object): def calculate(self, num): count_no = 0 while num &gt; 0: num = num / 10 count_no += 1 return count_no if __name__ == &quot;__main__&quot;: p = Solution() no = 5675 print(p.calculate(no)) </code></pre>
[ { "answer_id": 74582115, "author": "Mehrdad Pedramfar", "author_id": 3744747, "author_profile": "https://Stackoverflow.com/users/3744747", "pm_score": 2, "selected": false, "text": "return count_no def calculate(self, num):\n count_no = 0\n while num > 0:\n num = num // 10\n count_no += 1\n\n return count_no\n / //" }, { "answer_id": 74582306, "author": "Sören", "author_id": 1707427, "author_profile": "https://Stackoverflow.com/users/1707427", "pm_score": 1, "selected": false, "text": "print(num) 5675\n567.5\n56.75\n5.675\n.5675\n / // calculate number_of_digits" }, { "answer_id": 74582381, "author": "Michele Bandini", "author_id": 20602385, "author_profile": "https://Stackoverflow.com/users/20602385", "pm_score": 1, "selected": false, "text": "counto_no // def countDigit(self,num:int) -> int:\n return len(str(num))\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20502753/" ]
74,582,100
<p>I want to find all prime numbers in a certain range. I do this with looping through the array with numbers. If a multiplier of the current number is found, then it will be removed from the array with the splice method. But some numbers will be removed like 7 and 11 which are actually prime number and some not like 8 which are not prime numbers. What is wrong in this program, I can not figure it out.</p> <pre><code>let list = []; for (let i = 2; i &lt;= 30; i++) { list.push(i); } let n = list.length - 1; for (let prim = 0; prim &lt;= n; prim++) { //multiplier is beginning at 1 for provide 2 from splice method for (let multiplier = 0; multiplier &lt;= n; multiplier++) { //if the currentNumber is divisible by &quot;prim&quot; then remove it from list if (list[multiplier] % list[prim] == 0) { list.splice(multiplier, 1); } } } console.log(list); </code></pre>
[ { "answer_id": 74582433, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "splice list list[multiplier] list[prim] let list = [];\nfor (let i = 2; i <= 30; i++) {\n list.push(i);\n}\n\nfor (let prim = 0; prim <list.length-1; prim++) {\n for (let multiplier = prim; multiplier <list.length; multiplier++) {\n if (list[multiplier] != list[prim] && list[multiplier] % list[prim] == 0) {\n list.splice(multiplier, 1);\n }\n }\n}\n\nconsole.log(list);" }, { "answer_id": 74582435, "author": "Nina Scholz", "author_id": 1447675, "author_profile": "https://Stackoverflow.com/users/1447675", "pm_score": 2, "selected": true, "text": "let list = [];\nfor (let i = 2; i <= 30; i++) list.push(i);\n\nfor (let prim = 0; prim < list.length - 1; prim++) {\n for (let multiplier = list.length - 1; multiplier > prim; multiplier--) {\n if (list[multiplier] % list[prim] == 0) list.splice(multiplier, 1);\n }\n console.log(...list)\n}\n\nconsole.log(list); .as-console-wrapper { max-height: 100% !important; top: 0; }" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20036187/" ]
74,582,130
<p>Is it possible to create at JTree without hardcoding every tree node but rather reading in from a xml file and getting the same output as following code will give:</p> <pre><code>import javax.swing.JFrame; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; public class test { test() { JFrame f = new JFrame(&quot;Swing&quot;); DefaultMutableTreeNode life = new DefaultMutableTreeNode(&quot;Life&quot;); DefaultMutableTreeNode plants = new DefaultMutableTreeNode(&quot;Plants&quot;); DefaultMutableTreeNode animals = new DefaultMutableTreeNode(&quot;Animals&quot;); DefaultMutableTreeNode cryptogamers = new DefaultMutableTreeNode(&quot;Cryptogamers&quot;); DefaultMutableTreeNode mammals = new DefaultMutableTreeNode(&quot;Mammals&quot;); JTree root = new JTree(life); life.add(plants); life.add(animals); plants.add(cryptogamers); animals.add(mammals); f.setSize(200, 200); f.add(root); f.setVisible(true); } public static void main(String[] args) { new test(); } } </code></pre> <p>I want to produce the same result but without hardcoding every node by using this XML file I created:</p> <pre><code>&lt;Biosphere name=&quot;Life&quot;&gt; &lt;Kingdom name=&quot;Plants&quot;&gt; &lt;Division name=&quot;Cryptogamers&quot;&gt; &lt;/Division&gt; &lt;/Kingdom&gt; &lt;Kingdom name=&quot;Animals&quot;&gt; &lt;Division name=&quot;Mammals&quot;&gt; &lt;/Division&gt; &lt;/Kingdom&gt; &lt;/Biosphere&gt; </code></pre>
[ { "answer_id": 74582433, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "splice list list[multiplier] list[prim] let list = [];\nfor (let i = 2; i <= 30; i++) {\n list.push(i);\n}\n\nfor (let prim = 0; prim <list.length-1; prim++) {\n for (let multiplier = prim; multiplier <list.length; multiplier++) {\n if (list[multiplier] != list[prim] && list[multiplier] % list[prim] == 0) {\n list.splice(multiplier, 1);\n }\n }\n}\n\nconsole.log(list);" }, { "answer_id": 74582435, "author": "Nina Scholz", "author_id": 1447675, "author_profile": "https://Stackoverflow.com/users/1447675", "pm_score": 2, "selected": true, "text": "let list = [];\nfor (let i = 2; i <= 30; i++) list.push(i);\n\nfor (let prim = 0; prim < list.length - 1; prim++) {\n for (let multiplier = list.length - 1; multiplier > prim; multiplier--) {\n if (list[multiplier] % list[prim] == 0) list.splice(multiplier, 1);\n }\n console.log(...list)\n}\n\nconsole.log(list); .as-console-wrapper { max-height: 100% !important; top: 0; }" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19952753/" ]
74,582,134
<p>I am trying to make something that uses the same concept as the image below;</p> <p><a href="https://i.stack.imgur.com/l7j0m.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l7j0m.jpg" alt="enter image description here" /></a></p> <p>An image like background with text overlaying it.</p> <p>I tried to make a card and give it a backgroundColor of the image, but I got an error;</p> <p><a href="https://i.stack.imgur.com/5R2jO.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5R2jO.jpg" alt="enter image description here" /></a></p> <p><strong>What I want to do is overlay some texts on an image</strong>, like the image above.</p> <p>So please how do I arrange this code. I need everything to be in a single composable because I need to populate it.</p> <p>Thanks for your understanding and assistance, In advance.</p> <p>Please, I'd happily provide any more info needed.</p>
[ { "answer_id": 74582193, "author": "z.y", "author_id": 19023745, "author_profile": "https://Stackoverflow.com/users/19023745", "pm_score": 2, "selected": false, "text": "Box Child Card Image Text contentAlignment Alignment.Center Image Color @Composable\nfun ImageWithTextInMiddle() {\n Card {\n Box(\n modifier = Modifier\n .height(100.dp)\n .fillMaxWidth(),\n contentAlignment = Alignment.Center\n ) {\n Image(\n // painterResource(successInfo.successInfoImageId)\n painterResource(R.drawable.img),\n contentDescription = \"\",\n contentScale = ContentScale.Crop,\n modifier = Modifier.fillMaxSize()\n )\n\n // will display in the middle of the image\n Text(\"Some Text In the middle\")\n }\n }\n}\n" }, { "answer_id": 74582347, "author": "Gabriele Mariotti", "author_id": 2016562, "author_profile": "https://Stackoverflow.com/users/2016562", "pm_score": 3, "selected": true, "text": "Box @Composable\nfun ImageAndText(\n modifier: Modifier = Modifier,\n painter: Painter,\n contentDescription: String,\n text: String \n) {\n val shape = RoundedCornerShape(8.dp)\n val height = 100.dp\n Box(\n modifier = modifier\n .height(height)\n .fillMaxWidth()\n .background(White, shape = shape),\n contentAlignment = Alignment.Center\n ) {\n Image(\n painter = painter,\n contentDescription = contentDescription,\n contentScale = ContentScale.Crop,\n modifier = Modifier\n .fillMaxSize()\n .clip(shape)\n )\n\n Text(\n text = text, \n color = White\n )\n\n }\n}\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15976878/" ]
74,582,137
<p>Trying to get all the branches under a project using GitLab API, but I can see only 20 branches are returned. How can I get the complete list of all the branches? I am using the following API.</p> <pre><code>curl --header &quot;PRIVATE-TOKEN: &lt;token&gt;&quot; &quot;https://gitlab.com/api/v4/projects/1521/repository/branches&quot; </code></pre>
[ { "answer_id": 74583939, "author": "Ashish Pratap", "author_id": 6172022, "author_profile": "https://Stackoverflow.com/users/6172022", "pm_score": 2, "selected": true, "text": "per_page https://gitlab.com/api/v4/projects/<Project_id>/repository/branches?per_page=50\n" }, { "answer_id": 74584128, "author": "Bouke", "author_id": 6864688, "author_profile": "https://Stackoverflow.com/users/6864688", "pm_score": 0, "selected": false, "text": "https://gitlab.com/api/v4/projects/2009901/repository/branches/?page=2\n\nhttps://gitlab.com/api/v4/projects/2009901/repository/branches/?per_page=100\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6172022/" ]
74,582,149
<p>I want to add username before each route..</p> <p>ex:</p> <pre><code>sam/productDashboard james/productDashboard </code></pre> <p>note - Username is getting from session.</p> <p>i tried like this. it doesn't work</p> <blockquote> <p>Route::get( session()-&gt;get('name').'/productDashboard',[ProductController::class,'ProductDashboard'])-&gt;name('productDashboard');</p> </blockquote>
[ { "answer_id": 74582211, "author": "Hosein Shendabadi", "author_id": 9671516, "author_profile": "https://Stackoverflow.com/users/9671516", "pm_score": 2, "selected": true, "text": "Route::get('{username}/productDashboard',[ProductController::class,'ProductDashboard'])->name('productDashboard');\n <a href=\"{{route('productDashboard',['username' => session()->get('name')])}}\">Link</>\n" }, { "answer_id": 74582228, "author": "Aian", "author_id": 5846385, "author_profile": "https://Stackoverflow.com/users/5846385", "pm_score": 0, "selected": false, "text": "Route::get('{username}/productDashboard',[ProductController::class,'ProductDashboard'])->name('productDashboard');\n\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13139569/" ]
74,582,161
<blockquote> <p>Write a recursive function to find the smallest element in a vector. We can not use loops but can use if statements. Using RECURSION is a must.</p> </blockquote> <p>I Could Not think of any solution, the main problem was if I define a function then I have to give it some value and if I do so then whenever recursion occur it will again reset the value of that variable.</p>
[ { "answer_id": 74582211, "author": "Hosein Shendabadi", "author_id": 9671516, "author_profile": "https://Stackoverflow.com/users/9671516", "pm_score": 2, "selected": true, "text": "Route::get('{username}/productDashboard',[ProductController::class,'ProductDashboard'])->name('productDashboard');\n <a href=\"{{route('productDashboard',['username' => session()->get('name')])}}\">Link</>\n" }, { "answer_id": 74582228, "author": "Aian", "author_id": 5846385, "author_profile": "https://Stackoverflow.com/users/5846385", "pm_score": 0, "selected": false, "text": "Route::get('{username}/productDashboard',[ProductController::class,'ProductDashboard'])->name('productDashboard');\n\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20248205/" ]
74,582,168
<p>below file is named index.ts</p> <pre><code>import { serve } from &quot;https://deno.land/std@0.166.0/http/server.ts&quot;; function handler(_req: Request): Response { return new Response(&quot;Hello, World!&quot;); } console.log(&quot;Listening on http://localhost:8000&quot;); serve(handler); </code></pre> <p>after running</p> <pre><code>deno run index.ts </code></pre> <p>I'm getting 404 error while downloading <a href="https://deno.land/std@$STD_VERSION/http/server.ts" rel="nofollow noreferrer">https://deno.land/std@$STD_VERSION/http/server.ts</a></p> <pre><code>Download https://deno.land/std@$STD_VERSION/http/server.ts Download https://deno.land/std@$STD_VERSION/http/server.ts error: Uncaught Error: Import 'https://deno.land/std@$STD_VERSION/http/server.ts' failed: 404 Not Found at unwrapResponse ($deno$/ops/dispatch_json.ts:43:11) </code></pre>
[ { "answer_id": 74582211, "author": "Hosein Shendabadi", "author_id": 9671516, "author_profile": "https://Stackoverflow.com/users/9671516", "pm_score": 2, "selected": true, "text": "Route::get('{username}/productDashboard',[ProductController::class,'ProductDashboard'])->name('productDashboard');\n <a href=\"{{route('productDashboard',['username' => session()->get('name')])}}\">Link</>\n" }, { "answer_id": 74582228, "author": "Aian", "author_id": 5846385, "author_profile": "https://Stackoverflow.com/users/5846385", "pm_score": 0, "selected": false, "text": "Route::get('{username}/productDashboard',[ProductController::class,'ProductDashboard'])->name('productDashboard');\n\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/340999/" ]
74,582,180
<p>I'm in trouble with maven projects inerithed.</p> <p>The projects should be built with:</p> <pre><code>mvn install -D module </code></pre> <p>and/or</p> <pre><code>mvn intall -D config </code></pre> <p>I've no more precise info about how to built the projects but these are the knowledge transfered.</p> <p>If i try to build the project with &quot;mvn install -D module&quot; the output is:</p> <pre><code>[INFO] Scanning for projects... [WARNING] [WARNING] Some problems were encountered while building the effective model for it.eng.auriga:AurigaWeb:war:1.0.5-AMA-WAVE2-SNAPSHOT [WARNING] 'build.plugins.plugin.(groupId:artifactId)' must be unique but found duplicate declaration of plugin org.apache.maven.plugins:maven-dependency-plugin @ line 1119, column 12 [WARNING] [WARNING] It is highly recommended to fix these problems because they threaten the stability of your build. [WARNING] [WARNING] For this reason, future Maven versions might no longer support building such malformed projects. [WARNING] [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building AurigaWeb 1.0.5-AMA-WAVE2-SNAPSHOT [INFO] ------------------------------------------------------------------------ [INFO] Downloading: https://repo.maven.apache.org/maven2/org/codehaus/mojo/gwt-maven-plugin/2.7.0/gwt-maven-plugin-2.7.0.pom [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 2.079 s [INFO] Finished at: 2022-11-26T13:14:13+01:00 [INFO] Final Memory: 10M/153M [INFO] ------------------------------------------------------------------------ [ERROR] Plugin org.codehaus.mojo:gwt-maven-plugin:2.7.0 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.codehaus.mojo:gwt-maven-plugin:jar:2.7.0: Could not transfer artifact org.codehaus.mojo:gwt-maven-plugin:pom:2.7.0 from/to central (https://repo.maven.apache.org/maven2): Received fatal alert: protocol_version -&gt; [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginResolutionException </code></pre> <p>while if I try to build the project with &quot;mvn intall -D config&quot; then the output is:</p> <pre><code>[INFO] Scanning for projects... [WARNING] [WARNING] Some problems were encountered while building the effective model for it.eng.auriga:AurigaWeb:war:1.0.5-AMA-WAVE2-SNAPSHOT [WARNING] 'build.plugins.plugin.(groupId:artifactId)' must be unique but found duplicate declaration of plugin org.apache.maven.plugins:maven-dependency-plugin @ line 1119, column 12 [WARNING] [WARNING] It is highly recommended to fix these problems because they threaten the stability of your build. [WARNING] [WARNING] For this reason, future Maven versions might no longer support building such malformed projects. [WARNING] [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building AurigaWeb 1.0.5-AMA-WAVE2-SNAPSHOT [INFO] ------------------------------------------------------------------------ [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 0.105 s [INFO] Finished at: 2022-11-26T13:19:43+01:00 [INFO] Final Memory: 5M/121M [INFO] ------------------------------------------------------------------------ [ERROR] Unknown lifecycle phase &quot;intall&quot;. You must specify a valid lifecycle phase or a goal in the format &lt;plugin-prefix&gt;:&lt;goal&gt; or &lt;plugin-group-id&gt;:&lt;plugin-artifact-id&gt;[:&lt;plugin-version&gt;]:&lt;goal&gt;. Available lifecycle phases are: validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy, pre-clean, clean, post-clean, pre-site, site, post-site, site-deploy. -&gt; [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/LifecyclePhaseNotFoundException </code></pre> <p>Then in both cases the build fails.</p> <p>Looking at the output of &quot;mvn install -D module&quot;, the Plugin org.codehaus.mojo:gwt-maven-plugin:2.7.0 is in the right path of local maven repository but it fails anyway.</p> <p>Looking at the output of &quot;mvn install -D config&quot; instead, seems that something is missing.</p> <p>Someone know how these options works?</p> <p>I have also missing artifacts errors in pom.xml also if the plugin are in the right path of local maven repository:</p> <pre><code>Missing artifact com.isomorphic.smartgwt.lgpl:smartgwt-skins:jar:12.0-p20190920 Missing artifact it.eng.utility:SezioneCache:jar:1.0.3 Missing artifact javax.media:jai-core:jar:1.1.3 </code></pre> <p>Someone know how I can remove these errors?</p> <p>Eclipse is Oxygen. Java version is 1.8 on OS. JDK compliance is 1.7. Installed JRE is 1.7.</p>
[ { "answer_id": 74582211, "author": "Hosein Shendabadi", "author_id": 9671516, "author_profile": "https://Stackoverflow.com/users/9671516", "pm_score": 2, "selected": true, "text": "Route::get('{username}/productDashboard',[ProductController::class,'ProductDashboard'])->name('productDashboard');\n <a href=\"{{route('productDashboard',['username' => session()->get('name')])}}\">Link</>\n" }, { "answer_id": 74582228, "author": "Aian", "author_id": 5846385, "author_profile": "https://Stackoverflow.com/users/5846385", "pm_score": 0, "selected": false, "text": "Route::get('{username}/productDashboard',[ProductController::class,'ProductDashboard'])->name('productDashboard');\n\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5422569/" ]
74,582,230
<p>I need to copy values on a crossing way , as on the below pictures:<br> I arranged my data as two rows (with values) and then <strong>a one blank row</strong> and so on.<br> I tried the below code , but the output result is incorrect. <br> In advance, thanks for your help. <br></p> <pre><code>Sub Copy_by_crossing() Dim ws As Worksheet, lastRow As Long, i As Long Set ws = ThisWorkbook.ActiveSheet lastRow = ws.Range(&quot;A&quot; &amp; ws.Rows.Count).End(xlUp).Row For i = 2 To lastRow If ws.Range(&quot;E&quot; &amp; i + 1).Value = &quot;&quot; Then ws.Range(&quot;E&quot; &amp; i + 1).Resize(, 4).Value = ws.Range(&quot;A&quot; &amp; i, &quot;D&quot; &amp; i).Value End If Next i End Sub </code></pre> <p><a href="https://i.stack.imgur.com/acrYC.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/acrYC.jpg" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/Mc9YF.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Mc9YF.jpg" alt="enter image description here" /></a></p>
[ { "answer_id": 74582660, "author": "Ron Rosenfeld", "author_id": 2872922, "author_profile": "https://Stackoverflow.com/users/2872922", "pm_score": 3, "selected": true, "text": "Option Explicit\nSub Copy_By_Crossing()\n Dim WS As Worksheet, rSrc As Range, rRes As Range\n Dim vSrc, vRes\n Dim I As Long, J As Long\n \n\n'work in VBA arrays for faster execution times\n \nSet WS = ThisWorkbook.Worksheets(\"Sheet1\")\nWith WS\n Set rSrc = Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp)).Resize(columnsize:=4)\n vSrc = rSrc\n Set rRes = rSrc.Offset(0, UBound(vSrc, 2))\n ReDim vRes(1 To UBound(vSrc, 1), 1 To UBound(vSrc, 2))\nEnd With\n\n'create results array\n'headers\nFor J = 1 To UBound(vSrc, 2)\n vRes(1, J) = vSrc(1, J)\nNext J\n\n'Reverse each pair of data\nFor I = 2 To UBound(vSrc, 1) Step 3\n For J = 1 To UBound(vSrc, 2)\n vRes(I + 1, J) = vSrc(I, J)\n vRes(I, J) = vSrc(I + 1, J)\n Next J\nNext I\n \n'Write back to the worksheet\nWith rRes\n .EntireColumn.Clear\n .Value = vRes\n .Style = \"Output\" 'This line may not work with non-english versions\n .EntireColumn.AutoFit\nEnd With\n\nEnd Sub\n" }, { "answer_id": 74605944, "author": "T.M.", "author_id": 6460297, "author_profile": "https://Stackoverflow.com/users/6460297", "pm_score": 0, "selected": false, "text": "LET E2 CHOOSE =LET(data,A2:A103,rep,3,cols,4,idx,IF(data & \"\" <>\"\",MOD(ROW(data)-1,rep),rep),CHOOSE(idx,OFFSET(data,1,,,cols),OFFSET(data,-1,,,cols),\"\"))\n LET =LET(\n data,A2:A103,\n rep,3,\n cols,4,\n idx,IF(data & \"\" <>\"\",MOD(ROW(data)-1,rep),rep),\n CHOOSE(idx,OFFSET(data,1,,,cols),OFFSET(data,-1,,,cols),\"\")\n )\n\n ChooseCols ChooseRows =CHOOSECOLS(CHOOSEROWS(A2:A3,{2,1}),{2,3,4})" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17797849/" ]
74,582,233
<p>I get this error when I run my flutter App. I've not been able to figure out why this error keeps occurring.</p> <p>Error:</p> <blockquote> <p>══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════ The following _CastError was thrown building RawGestureDetector-[LabeledGlobalKey#3c378](state: RawGestureDetectorState#d987a(gestures: , behavior: opaque)): Null check operator used on a null value</p> </blockquote> <p>My code:</p> <pre><code>import './quotes.dart'; import 'dart:math'; import '../constants.dart'; class HadithQuotes extends StatefulWidget { const HadithQuotes({Key? key}) : super(key: key); @override State&lt;HadithQuotes&gt; createState() =&gt; _HadithQuotesState(); } class _HadithQuotesState extends State&lt;HadithQuotes&gt; { String? text = &quot;&quot;; String? author = &quot;&quot;; setQuote() { int randomNumber = Random().nextInt(quotes.length); setState(() { text = quotes[randomNumber][&quot;text&quot;]!; author = quotes[randomNumber][&quot;author&quot;]!; notifylisteners(); }); } @override initState() { setQuote(); super.initState(); } @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.fromLTRB(20, 20, 20, 20), child: Container( alignment: Alignment.center, decoration: BoxDecoration( gradient: LinearGradient( colors: [ Colors.green.withOpacity(0.9), kGoodOrange, ], begin: Alignment.topLeft, end: Alignment.bottomRight, ), color: kGoodOrange, borderRadius: BorderRadius.circular(8) ), child: Padding( padding: const EdgeInsets.fromLTRB(10, 0, 10, 0), child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Padding( padding: const EdgeInsets.all(25.0), child: Text( text ?? '', textAlign: TextAlign.center, style: TextStyle( fontSize: 18, color: Colors.white, ), ), ), Padding( padding: const EdgeInsets.all(15.0), child: Text( author?? '', textAlign: TextAlign.center, style: TextStyle( fontSize: 18, color: Colors.white, ), ), ), Row( children: [ Column( children: [ TextButton( onPressed: setQuote, child: Image.asset( 'assets/images/next.png', width: 25, ), ), ], ), ], ), ], ) ], ), ) ), ); } void notifylisteners() {} } </code></pre>
[ { "answer_id": 74582278, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 0, "selected": false, "text": "! setState(() {\n text = quotes[randomNumber][\"text\"];\n author = quotes[randomNumber][\"author\"];\n notifylisteners();\n });\n" }, { "answer_id": 74582281, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 2, "selected": true, "text": "! null quotes[randomNumber][\"text\"] quotes[randomNumber][\"author\"] setState(() {\n text = quotes[randomNumber][\"text\"]!;\n author = quotes[randomNumber][\"author\"]!;\n notifylisteners();\n \n});\n setState(() {\n text = quotes[randomNumber][\"text\"] ?? \"\";\n author = quotes[randomNumber][\"author\"] ?? \"\";\n notifylisteners();\n \n});\n" }, { "answer_id": 74583715, "author": "Amit Bahadur", "author_id": 14562817, "author_profile": "https://Stackoverflow.com/users/14562817", "pm_score": 0, "selected": false, "text": " setState(() {\n text = quotes[randomNumber][\"text\"] ?? \"\";\n author = quotes[randomNumber][\"author\"] ?? \"\";\n notifylisteners();\n });\n setState(() {\n text = quotes[randomNumber][\"text\"] !=null ? quotes[randomNumber][\"text\"] : \"\";\n author = quotes[randomNumber][\"author\"] !=null ? quotes[randomNumber][\"author\"] : \"\";\n notifylisteners();\n });\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12912157/" ]
74,582,238
<p>In Python and Selenium, how do I find numeric characters in a text and put them in a variable? for example :</p> <p>text = Your verification code is: 5674</p> <p>I need to find the number 5674 from the text and put it in a variable.</p> <p>Result »» x = 5674</p> <hr /> <p>import re txt = &quot;Your verification code is: 5674&quot; x = is_digit(txt) print(x)</p> <p>x »»» 5674</p>
[ { "answer_id": 74582278, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 0, "selected": false, "text": "! setState(() {\n text = quotes[randomNumber][\"text\"];\n author = quotes[randomNumber][\"author\"];\n notifylisteners();\n });\n" }, { "answer_id": 74582281, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 2, "selected": true, "text": "! null quotes[randomNumber][\"text\"] quotes[randomNumber][\"author\"] setState(() {\n text = quotes[randomNumber][\"text\"]!;\n author = quotes[randomNumber][\"author\"]!;\n notifylisteners();\n \n});\n setState(() {\n text = quotes[randomNumber][\"text\"] ?? \"\";\n author = quotes[randomNumber][\"author\"] ?? \"\";\n notifylisteners();\n \n});\n" }, { "answer_id": 74583715, "author": "Amit Bahadur", "author_id": 14562817, "author_profile": "https://Stackoverflow.com/users/14562817", "pm_score": 0, "selected": false, "text": " setState(() {\n text = quotes[randomNumber][\"text\"] ?? \"\";\n author = quotes[randomNumber][\"author\"] ?? \"\";\n notifylisteners();\n });\n setState(() {\n text = quotes[randomNumber][\"text\"] !=null ? quotes[randomNumber][\"text\"] : \"\";\n author = quotes[randomNumber][\"author\"] !=null ? quotes[randomNumber][\"author\"] : \"\";\n notifylisteners();\n });\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20606690/" ]
74,582,253
<p>When I hover over bigger blocks (the blue ones) all the small block change to black at once.</p> <p>I want only to change the color of the small block inside the hovered blue block not all of them.</p> <p>Also, I know with CSS (pseudo-selector, <code>:hover</code>) can do the same but I want to do it with JS as I said this is not my main code.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const smallContainer = document.querySelectorAll(".small-container") const logoContainer = document.querySelectorAll(".logo-container") smallContainer.forEach((value) =&gt; { value.addEventListener("mouseover", () =&gt; { logoContainer.forEach((valuein) =&gt; { valuein.classList.remove("logo-container") valuein.classList.add("logo-container-animation") }) }) })</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.main-container { display: flex; width: 100%; height: 100vh; justify-content: space-between; } .small-container { height: 200px; width: 200px; background-color: blue; transition: all .5s; display: flex; align-items: center; justify-content: center; } .logo-container { height: 25px; width: 25px; background-color: rgb(255, 0, 0); } .logo-container-animation { background-color: rgb(0, 0, 0); height: 25px; width: 25px; transition: all 2s; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="main-container"&gt; &lt;div class="small-container"&gt;&lt;span class="logo-container"&gt;&lt;/span&gt;&lt;/div&gt; &lt;div class="small-container"&gt;&lt;span class="logo-container"&gt;&lt;/span&gt;&lt;/div&gt; &lt;div class="small-container"&gt;&lt;span class="logo-container"&gt;&lt;/span&gt;&lt;/div&gt; &lt;div class="small-container"&gt;&lt;span class="logo-container"&gt;&lt;/span&gt;&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74582278, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 0, "selected": false, "text": "! setState(() {\n text = quotes[randomNumber][\"text\"];\n author = quotes[randomNumber][\"author\"];\n notifylisteners();\n });\n" }, { "answer_id": 74582281, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 2, "selected": true, "text": "! null quotes[randomNumber][\"text\"] quotes[randomNumber][\"author\"] setState(() {\n text = quotes[randomNumber][\"text\"]!;\n author = quotes[randomNumber][\"author\"]!;\n notifylisteners();\n \n});\n setState(() {\n text = quotes[randomNumber][\"text\"] ?? \"\";\n author = quotes[randomNumber][\"author\"] ?? \"\";\n notifylisteners();\n \n});\n" }, { "answer_id": 74583715, "author": "Amit Bahadur", "author_id": 14562817, "author_profile": "https://Stackoverflow.com/users/14562817", "pm_score": 0, "selected": false, "text": " setState(() {\n text = quotes[randomNumber][\"text\"] ?? \"\";\n author = quotes[randomNumber][\"author\"] ?? \"\";\n notifylisteners();\n });\n setState(() {\n text = quotes[randomNumber][\"text\"] !=null ? quotes[randomNumber][\"text\"] : \"\";\n author = quotes[randomNumber][\"author\"] !=null ? quotes[randomNumber][\"author\"] : \"\";\n notifylisteners();\n });\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17620112/" ]
74,582,309
<pre><code>#Create a program that allows 2 players to throw a 6 sided dice and record the roll value 10 times. #The winner is the player with the highest total #This task must store the results in a 2D array #Extra: #Work out the average roll across the 10 throws per player and display the result #Frequency analysis broken down per player and per game from random import randint results = [[],[]] for i in range (2): player = [] total = 0 average = 0 #player enters their name name = input(f&quot;\nEnter your name player {i + 1}: &quot;) player.append(name) print(f&quot;Player {i + 1} it is your turn&quot;) for x in range(10): print(&quot;\nTo roll the die press any key&quot;) input() roll = randint(1,6) player.append(roll) print(&quot;You rolled a&quot;, roll) total += roll average = total/10 player.append(total) player.append(average) results.append(player) print(&quot;&quot;&quot;\nNAME R1 R2 R3 R4 R5 R6 R7 R8 R9 R10 TOTAL AVG&quot;&quot;&quot;) for i in results: for c in i: print(c,end = &quot; &quot;) print() </code></pre> <p>im not sure how to evenly space out the values so they are in line when they are printed.</p> <p>i tried adding spaces inbetween the values when printing but if one of the names or numbers are a different length then the whole row becomes unaligned with the column.</p>
[ { "answer_id": 74582348, "author": "solac34", "author_id": 20554831, "author_profile": "https://Stackoverflow.com/users/20554831", "pm_score": -1, "selected": false, "text": "diff = abs(len(results[2][0]) - len(results[3][0])) #abs = absolute value\n if len(results[2][0] ) > len(results[3][0]):\n results[3][0] = results[3][0] + \" \"*diff # add spaces much as difference between 2 names\nelse:\n results[2][0] = results[2][0] + \" \"*diff\n" }, { "answer_id": 74582524, "author": "Michele Bandini", "author_id": 20602385, "author_profile": "https://Stackoverflow.com/users/20602385", "pm_score": 1, "selected": false, "text": "print('%5s' % str(c))\n % s 5" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20307080/" ]
74,582,335
<p>I have the following pandas dataframe <code>df</code></p> <pre><code> time animal 0 0 cat 1 0 dog 2 1 hedgehog 3 1 cat 4 1 cat </code></pre> <p>I would like to</p> <ul> <li>group by time while counting how often an animal is withing the new group, like 2x cat at time 1.</li> <li>create a 2nd dimension for the count values then.</li> </ul> <p>like that:</p> <pre><code>animal cat dog hedgehog time 0 1 1 0 1 2 0 1 </code></pre> <p>Any ideas how to accomplish that?</p>
[ { "answer_id": 74582359, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 2, "selected": false, "text": "pd.crosstab print(pd.crosstab(df.time, df.animal))\n animal cat dog hedgehog\ntime \n0 1 1 0\n1 2 0 1\n" }, { "answer_id": 74582591, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": 2, "selected": true, "text": "pandas.crosstab seaborn.heatmap import pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nplt.figure(figsize=(4, 2))\n\nsns.heatmap(pd.crosstab(df[\"time\"], df[\"animal\"]), annot = True)\n\nplt.show()\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2974685/" ]
74,582,355
<p>I am modeling below problem in Z3. The aim is to find the path for Agent to reach the coin avoiding obstacles.</p> <pre><code>Initial_grid =[['T' 'T' 'T' 'T' 'T' 'T' 'T'] ['T' ' ' ' ' ' ' ' ' ' ' 'T'] ['T' ' ' 'A' 'O' ' ' 'O' 'T'] ['T' 'O' ' ' ' ' ' ' ' ' 'T'] ['T' ' ' ' ' 'O' 'O' 'C' 'T'] ['T' ' ' ' ' ' ' ' ' ' ' 'T'] ['T' 'T' 'T' 'T' 'T' 'T' 'T']] x, y = Ints('x y') x = agent_loc[0] y = agent_loc[1] xc, yc = Ints('xc yc') xc = coin_loc[0] yc = coin_loc[1] s = Solver() s.add(x,y = (Or(move_right(),move_left(),move_top(),move_bottom()))) solve(And (x = xc) (y = yc)) if s.check() == unsat: print('Problem not solvable') else: m = s.model() </code></pre> <p>I added constraint for movement function which returns x,y coordinates if the movement is valid (no obstacles and within boundary) and returns false otherwise. How can I model the movement constraint as the one in code gives error: <em>add() got an unexpected keyword argument 'y'</em>.</p>
[ { "answer_id": 74586050, "author": "alias", "author_id": 936310, "author_profile": "https://Stackoverflow.com/users/936310", "pm_score": 2, "selected": true, "text": "from z3 import *\n\nGrid = [ ['T', 'T', 'T', 'T', 'T', 'T', 'T']\n , ['T', ' ', ' ', ' ', ' ', ' ', 'T']\n , ['T', ' ', 'A', 'O', ' ', 'O', 'T']\n , ['T', 'O', ' ', ' ', ' ', ' ', 'T']\n , ['T', ' ', ' ', 'O', 'O', 'C', 'T']\n , ['T', ' ', ' ', ' ', ' ', ' ', 'T']\n , ['T', 'T', 'T', 'T', 'T', 'T', 'T']\n ]\n\nCell, (Wall, Empty, Agent, Obstacle, Coin) = EnumSort('Cell', ('Wall', 'Empty', 'Agent', 'Obstacle', 'Coin'))\n\ndef mkCell(c):\n if c == 'T':\n return Wall\n elif c == ' ':\n return Empty\n elif c == 'A':\n return Agent\n elif c == 'O':\n return Obstacle\n else:\n return Coin\n\ndef grid(x, y):\n result = Wall\n for i in range (len(Grid)):\n for j in range (len(Grid[0])):\n result = If(And(x == IntVal(i), y == IntVal(j)), mkCell(Grid[i][j]), result)\n return result\n\ndef validStart(x, y):\n return grid(x, y) == Agent\n\ndef validEnd(x, y):\n return grid(x, y) == Coin\n\ndef canMoveTo(x, y):\n n = grid(x, y)\n return Or(n == Empty, n == Coin, n == Agent)\n\ndef moveLeft(x, y):\n return [x, If(canMoveTo(x, y-1), y-1, y)]\n\ndef moveRight(x, y):\n return [x, If(canMoveTo(x, y+1), y+1, y)]\n\ndef moveUp(x, y):\n return [If(canMoveTo(x-1, y), x-1, x), y]\n\ndef moveDown(x, y):\n return [If(canMoveTo(x+1, y), x+1, x), y]\n\nDir, (Left, Right, Up, Down) = EnumSort('Dir', ('Left', 'Right', 'Up', 'Down'))\n\ndef move(d, x, y):\n xL, yL = moveLeft (x, y)\n xR, yR = moveRight(x, y)\n xU, yU = moveUp (x, y)\n xD, yD = moveDown (x, y)\n xN = If(d == Left, xL, If (d == Right, xR, If (d == Up, xU, xD)))\n yN = If(d == Left, yL, If (d == Right, yR, If (d == Up, yU, yD)))\n return [xN, yN]\n\ndef solves(seq, x, y):\n def walk(moves, curX, curY):\n if moves:\n nX, nY = move(moves[0], curX, curY)\n return walk(moves[1:], nX, nY)\n else:\n return [curX, curY]\n\n xL, yL = walk(seq, x, y)\n return And(validStart(x, y), validEnd(xL, yL))\n\npathLength = 0\n\nwhile(pathLength != 20):\n print(\"Trying to find a path of length:\", pathLength)\n\n s = Solver()\n seq = [Const('m' + str(i), Dir) for i in range(pathLength)]\n x, y = Ints('x y')\n s.add(solves(seq, x, y))\n\n if s.check() == sat:\n print(\"Found solution with length:\", pathLength)\n m = s.model()\n print(\" Start x:\", m[x])\n print(\" Start y:\", m[y])\n for move in seq:\n print(\" Move\", m[move])\n break\n else:\n pathLength += 1\n Trying to find a path of length: 0\nTrying to find a path of length: 1\nTrying to find a path of length: 2\nTrying to find a path of length: 3\nTrying to find a path of length: 4\nTrying to find a path of length: 5\nFound solution with length: 5\n Start x: 2\n Start y: 2\n Move Down\n Move Right\n Move Right\n Move Right\n Move Down\n" }, { "answer_id": 74590133, "author": "Axel Kemper", "author_id": 1911064, "author_profile": "https://Stackoverflow.com/users/1911064", "pm_score": 0, "selected": false, "text": "from z3 import *\n# 1 2 3 4 5 6 7\nGrid = [ ['T', 'T', 'T', 'T', 'T', 'T', 'T'] # 1\n , ['T', ' ', ' ', ' ', ' ', ' ', 'T'] # 2\n , ['T', ' ', 'A', 'O', ' ', 'O', 'T'] # 3\n , ['T', 'O', ' ', ' ', ' ', ' ', 'T'] # 4\n , ['T', ' ', ' ', 'O', 'O', 'C', 'T'] # 5\n , ['T', ' ', ' ', ' ', ' ', ' ', 'T'] # 6\n , ['T', 'T', 'T', 'T', 'T', 'T', 'T'] # 7\n ]\n\nrows = len(Grid)\nRows = range(rows)\ncols = len(Grid[0])\nCols = range(cols)\nInfinity = rows * cols + 1\n\ndeltaRow = [-1, 0, +1, 0]\ndeltaCol = [ 0, -1, 0, +1]\ndelta = ['up', 'left', 'down', 'right']\ndeltaInv = ['down', 'right', 'up', 'left'];\nDeltas = range(len(delta))\n\ns = Solver()\n\n# 2D array comprehension: \n# create matrix of path distances\n# https://stackoverflow.com/a/25345853/1911064\ndistances = [[Int('d'+str(r)+'_'+str(c)) for c in Cols] for r in Rows]\n\n# http://www.hakank.org/z3/z3_utils_hakank.py\n# v is the minimum value of x\ndef minimum(sol, v, x):\n sol.add(Or([v == x[i] for i in range(len(x))])) # v is an element in x)\n for i in range(len(x)):\n sol.add(v <= x[i]) # and it's the smallest\n\n# constraints for distances\nfor row in Rows:\n for col in Cols:\n # shorthands to reduce typing\n g = Grid[row][col]\n dist = distances[row][col]\n if (g == 'T') or (g == 'O'):\n # obstacles and walls cannot be part of the path\n s.add(dist == Infinity)\n elif g == 'A':\n # the path starts here\n s.add(dist == 0)\n else:\n # array index violations cannot happen\n # because the wall case is handled above\n minimum(s, dist, [distances[row + deltaRow[i]][col + deltaCol[i]] + 1 for i in Deltas])\n # remember the coin coordinates\n if g == 'C':\n rowCoin, colCoin = row, col\n # detect unreachable target as UNSAT\n s.add(dist < Infinity)\n \nif s.check() == sat:\n # show the resulting path\n m = s.model()\n row, col = rowCoin, colCoin\n # collect the path in reverse to\n # avoid dead-ends which don't reach the coin\n path = []\n dir = []\n while True:\n path.insert(0, [row, col])\n if Grid[row][col] == 'A':\n break\n neighborDistances = [m[distances[row+deltaRow[i]][col+deltaCol[i]]].as_long() \n for i in Deltas]\n best = neighborDistances.index(min(neighborDistances))\n # advance to the direction of the lowest distance\n row += deltaRow[best]\n col += deltaCol[best]\n dir.insert(0, best)\n\n print('start ' + ' [row ' + str(path[0][0]+1) + '; col ' + str(path[0][1]+1) + ']')\n for i in range(1, len(path)):\n print(deltaInv[dir[i-1]].ljust(6) + ' [row ' + str(path[i][0]+1) + '; col ' + str(path[i][1]+1) + ']')\nelse:\n print(\"No path found!\") \n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20592571/" ]
74,582,356
<p>This is my Program.cs:</p> <pre><code>int currentHp = 100; Potion potion = new Potion(10); Console.WriteLine(potion.ToString(currentHp)); </code></pre> <p>This is my class called Potion.cs</p> <pre><code>private int hpHeal; public Potion(int hpHeal) { HpHeal = hpHeal; } public int HpHeal { get { return hpHeal; } set { hpHeal = value; } } public override string ToString(int currentHp) { if (currentHp + hpHeal &gt; 100) { string result = &quot;&quot;; result += $&quot;You healed for {100 - currentHp} hp.\n&quot;; currentHp = 100; result += $&quot;Current health: {currentHp} hp.&quot;; return result; } else { string result = &quot;&quot;; currentHp += hpHeal; result += $&quot;You healed for{hpHeal} hp.\n&quot;; result += $&quot;Current health: {currentHp} hp.&quot;; return result; } } </code></pre> <p>The line <code>public override string ToString(int currentHp)</code> is underlined with an error <code>'Potion.ToString(int)': no suitable method found to override</code> and I don't know why... I'm currently learning how Classes work so don't judje me too hard.</p>
[ { "answer_id": 74582430, "author": "Jan Joneš", "author_id": 9080566, "author_profile": "https://Stackoverflow.com/users/9080566", "pm_score": 3, "selected": true, "text": "ToString Stringify override" }, { "answer_id": 74583712, "author": "vivek nuna", "author_id": 6527049, "author_profile": "https://Stackoverflow.com/users/6527049", "pm_score": 0, "selected": false, "text": "ToString GetCustomString int hpHeal; _hpHeal" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20252236/" ]
74,582,360
<p>I'm developing a discord bot using nextcord. When i'm registering slash command and deleting it later, it's also staying at discord command list.</p> <p>What can I do to delete non-existent slash commands or sync actual bot's command list with discord? P.S. All of my commands are in different cogs</p> <p>I was waiting about 4 hours for registering and sync slash commands by discord but to no avail.</p>
[ { "answer_id": 74582430, "author": "Jan Joneš", "author_id": 9080566, "author_profile": "https://Stackoverflow.com/users/9080566", "pm_score": 3, "selected": true, "text": "ToString Stringify override" }, { "answer_id": 74583712, "author": "vivek nuna", "author_id": 6527049, "author_profile": "https://Stackoverflow.com/users/6527049", "pm_score": 0, "selected": false, "text": "ToString GetCustomString int hpHeal; _hpHeal" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14655540/" ]
74,582,376
<p><strong>Context</strong></p> <p>Say that I have a <code>df</code> which includes multiple columns (<code>a1</code>,<code>a2</code>,<code>a3</code>,<code>a4</code>,<code>b1</code>,<code>b2</code>,<code>b3</code>,<code>b4</code>).</p> <p>I want to generate some new columns (<code>c1</code>,<code>c2</code>,<code>c3</code>,<code>c4</code>) base on the existed columns .</p> <p>Now, I can do this by creating it one by one.</p> <pre><code> df = data.frame(a1 = 1:2, a2 = 3:4, a3 = 5:6, a4 = 7:8, b1 = 1:2, b2 = 3:4, b3 = 5:6, b4 = 7:8) df %&gt;% mutate(c1 = a1 - b1, c2 = a2 - b2, c3 = a3 - b3, c4 = a4 - b4) </code></pre> <p><strong>Question</strong></p> <p>Is there a way that can produce <code>c1</code>, <code>c2</code>, <code>c3</code>, and <code>c4</code> all at once? Maybe using <code>across()</code>?</p> <p><strong>Reproducible code</strong></p> <pre><code>df = data.frame(a1 = 1:2, a2 = 3:4, a3 = 5:6, a4 = 7:8, b1 = 1:2, b2 = 3:4, b3 = 5:6, b4 = 7:8) df %&gt;% mutate(c1 = a1 - b1, c2 = a2 - b2, c3 = a3 - b3, c4 = a4 - b4) # Maybe the way like this, though it cannot run correctly df %&gt;% mutate(paste('c', 1:4) = paste('a', 1:4) - paste('b', 1:4)) </code></pre>
[ { "answer_id": 74582419, "author": "Vinícius Félix", "author_id": 9696037, "author_profile": "https://Stackoverflow.com/users/9696037", "pm_score": 2, "selected": false, "text": "across df <-\n data.frame(\n a1 = 1:2, a2 = 3:4, a3 = 5:6, a4 = 7:8,\n b1 = 1:2, b2 = 1:2, b3 = 5:6, b4 = 1:2\n )\n\nlibrary(stringr)\nlibrary(dplyr)\n\ndf %>% \n mutate(across(\n .cols = starts_with('a'),\n .fns = ~(. - get(str_replace(cur_column(), 'a', 'b'))),\n .names = \"{str_replace(.col, 'a', 'c')}\")\n )\n\n a1 a2 a3 a4 b1 b2 b3 b4 c1 c2 c3 c4\n1 1 3 5 7 1 1 5 1 0 2 0 6\n2 2 4 6 8 2 2 6 2 0 2 0 6\n" }, { "answer_id": 74582492, "author": "Ricardo Semião e Castro", "author_id": 13048728, "author_profile": "https://Stackoverflow.com/users/13048728", "pm_score": 2, "selected": false, "text": "purrr::map map_df(setNames(1:4, paste0(\"c\", 1:4)),\n ~ df[[paste0(\"a\", .x)]] - df[[paste0(\"b\", .x)]]) %>% \n cbind(df, .)\n map2_df(select(df, matches(\"a\")),\n select(df, matches(\"b\")),\n ~ .x - .y) %>%\n setNames(paste0(\"c\", 1:4)) %>%\n cbind(df, .)\n" }, { "answer_id": 74584370, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 3, "selected": true, "text": "base R df[paste0(\"c\", 1:4)] <- df[1:4]- df[5:8]\n dplyr across library(dplyr)\nlibrary(stringr)\ndf <- df %>% \n mutate(across(starts_with('a'), \n .names = \"{str_replace(.col, 'a', 'c')}\") - across(starts_with('b')))\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11636376/" ]
74,582,403
<p>I am trying to develop a rest API for a school project, my question is how can I find the correct version for the dialect? I don't really know a lot about the topic but i can understand that hibernate is included with the JPA dependency?? If not do I have to install it separately somehow? I can see that the compiler is auto-filling my property selection so I guess that hibernate comes with the dependecy.</p> <p>I am developing the project on Spring Boot with the following depndencies: Spring Web Spring JPA MySQL Driver</p> <p>I tried this hibernate property but I am getting an error</p> <pre><code>spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect </code></pre> <pre><code>Caused by: org.hibernate.boot.registry.selector.spi.StrategySelectionException: Unable to resolve name [org.hibernate.dialect.MySQL5InnoDBDialect] as strategy [org.hibernate.dialect.Dialect] at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.selectStrategyImplementor(StrategySelectorImpl.java:155) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final] at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveStrategy(StrategySelectorImpl.java:237) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final] at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveStrategy(StrategySelectorImpl.java:190) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final] at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.constructDialect(DialectFactoryImpl.java:96) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final] at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:59) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final] at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:244) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final] at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:36) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final] at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:119) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final] at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:255) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final] ... 31 common frames omitted Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [org.hibernate.dialect.MySQL5InnoDBDialect] at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:123) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final] at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.selectStrategyImplementor(StrategySelectorImpl.java:151) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final] ... 39 common frames omitted Caused by: java.lang.ClassNotFoundException: Could not load requested class : org.hibernate.dialect.MySQL5InnoDBDialect at org.hibernate.boot.registry.classloading.internal.AggregatedClassLoader.findClass(AggregatedClassLoader.java:210) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final] at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:588) ~[na:na] at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521) ~[na:na] at java.base/java.lang.Class.forName0(Native Method) ~[na:na] at java.base/java.lang.Class.forName(Class.java:495) ~[na:na] at java.base/java.lang.Class.forName(Class.java:474) ~[na:na] at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:120) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final] ... 40 common frames omitted </code></pre> <pre><code>This my pom.xml file &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;parent&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt; &lt;version&gt;3.0.0&lt;/version&gt; &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt; &lt;/parent&gt; &lt;groupId&gt;com.example&lt;/groupId&gt; &lt;artifactId&gt;SecureSoftwareDevProject&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;name&gt;SecureSoftwareDevProject&lt;/name&gt; &lt;description&gt;SecureSoftwareDevProject&lt;/description&gt; &lt;properties&gt; &lt;java.version&gt;17&lt;/java.version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.h2database&lt;/groupId&gt; &lt;artifactId&gt;h2&lt;/artifactId&gt; &lt;scope&gt;runtime&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.mysql&lt;/groupId&gt; &lt;artifactId&gt;mysql-connector-j&lt;/artifactId&gt; &lt;scope&gt;runtime&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.projectlombok&lt;/groupId&gt; &lt;artifactId&gt;lombok&lt;/artifactId&gt; &lt;optional&gt;true&lt;/optional&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;excludes&gt; &lt;exclude&gt; &lt;groupId&gt;org.projectlombok&lt;/groupId&gt; &lt;artifactId&gt;lombok&lt;/artifactId&gt; &lt;/exclude&gt; &lt;/excludes&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p>I am running MySQL server 8.0.31</p>
[ { "answer_id": 74582515, "author": "Mark Rotteveel", "author_id": 466862, "author_profile": "https://Stackoverflow.com/users/466862", "pm_score": 2, "selected": true, "text": "org.hibernate.dialect.MySQLDialect InnoDB org.hibernate.dialect.MySQL8Dialect" }, { "answer_id": 74582523, "author": "Mohsen R. Agdam", "author_id": 8466720, "author_profile": "https://Stackoverflow.com/users/8466720", "pm_score": 0, "selected": false, "text": "application.properties spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL8Dialect\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18763441/" ]
74,582,411
<p>I get Null Pointer Exception when running the code below:</p> <pre class="lang-java prettyprint-override"><code>public class Engine{ private String name = null; private Mercedes m = null; private Engine() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public Mercedes getM() { return m; } public void setM(Mercedes m) { this.m = m; } public static EngineBuilder builder() { return new EngineBuilder(); } public static class EngineBuilder { private Engine e = null; public EngineBuilder builder() { e = new Engine(); return this; } public Engine build() { return this.e; } public EngineBuilder setName(String name) { this.e.setName(name); return this; } public EngineBuilder setM(Mercedes m) { this.e.setM(m); return this; } } public static void main(String[] args) { EngineBuilder builder = Engine.builder(); builder.setName(&quot;test&quot;); Engine e = builder.build(); } } } </code></pre> <p>I expected the Builder pattern would work, but I got</p> <blockquote> <p>&quot;Exception in thread &quot;main&quot; java.lang.NullPointerException: Cannot invoke &quot;Engine.setName(String)&quot; because &quot;this.e&quot; is null&quot;</p> </blockquote>
[ { "answer_id": 74582515, "author": "Mark Rotteveel", "author_id": 466862, "author_profile": "https://Stackoverflow.com/users/466862", "pm_score": 2, "selected": true, "text": "org.hibernate.dialect.MySQLDialect InnoDB org.hibernate.dialect.MySQL8Dialect" }, { "answer_id": 74582523, "author": "Mohsen R. Agdam", "author_id": 8466720, "author_profile": "https://Stackoverflow.com/users/8466720", "pm_score": 0, "selected": false, "text": "application.properties spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL8Dialect\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16560060/" ]
74,582,418
<p>I'm building social network app using nodejs and mongodb. Now in my user schema i have an array of ids of users who are following certain user and ids of users who are followed by certain user. When i delete the user i want to delete his id from all arrays inside of users who are following him. So that if he deletes his accont he is not going to be followed by any user anymore</p> <pre><code> following: [{ type: mongoose.Schema.ObjectId, ref: &quot;User&quot; }], followers: [{ type: mongoose.Schema.ObjectId, ref: &quot;User&quot; }], </code></pre>
[ { "answer_id": 74582515, "author": "Mark Rotteveel", "author_id": 466862, "author_profile": "https://Stackoverflow.com/users/466862", "pm_score": 2, "selected": true, "text": "org.hibernate.dialect.MySQLDialect InnoDB org.hibernate.dialect.MySQL8Dialect" }, { "answer_id": 74582523, "author": "Mohsen R. Agdam", "author_id": 8466720, "author_profile": "https://Stackoverflow.com/users/8466720", "pm_score": 0, "selected": false, "text": "application.properties spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL8Dialect\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19419004/" ]
74,582,427
<p>I want to know how to rearrange values in JOLT. I want poDesciption field before poType.</p> <p>I tried the below but didn't worked.-</p> <pre class="lang-json prettyprint-override"><code>&quot;poDescription&quot;: &quot;&amp;5.&amp;4.&amp;3.&amp;2.&amp;1.&amp;&quot;, &quot;poType&quot;: &quot;&amp;5.&amp;4.&amp;3.&amp;2.&amp;1.&amp;&quot;, </code></pre> <p>Any idea on what changes I need to make to get poDesciption before poType and grossTotalAmount?</p> <p>Order that I want-</p> <p><a href="https://i.stack.imgur.com/FnsKy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FnsKy.png" alt="enter image description here" /></a></p> <p>Order that I am getting-</p> <p><a href="https://i.stack.imgur.com/6MbAq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6MbAq.png" alt="enter image description here" /></a></p> <p>Below is the Input data-</p> <pre class="lang-json prettyprint-override"><code>{ &quot;PURCHASE_ORDER_DISPATCH&quot;: { &quot;MsgData&quot;: { &quot;Transaction&quot;: { &quot;PO_POD_HDR_EVW1&quot;: { &quot;WG_ADDR_SEQ_NUM&quot;: 1, &quot;WG_PO_CNTCT_EMAIL&quot;: &quot;PeggyMeincke@westfieldgrp.com&quot;, &quot;WG_REQUESTOR_EMAIL&quot;: &quot;ZacharyEngels@westfieldgrp.com&quot;, &quot;WG_REQ_FIRST_NAME&quot;: &quot;Zachary&quot;, &quot;WG_REQ_LAST_NAME&quot;: &quot;Engels&quot;, &quot;WG_DELIVER_TO&quot;: &quot;ZacharyEngels@westfieldgrp.com&quot;, &quot;BUSINESS_UNIT&quot;: &quot;OFIC&quot;, &quot;PO_ID&quot;: 25052, &quot;VENDOR_SETID&quot;: &quot;WCOS&quot;, &quot;VENDOR_ID&quot;: 35958, &quot;VNDR_LOC&quot;: 1, &quot;PO_DT&quot;: &quot;2020-01-24&quot;, &quot;DB_NUMBER_BU&quot;: &quot;&quot;, &quot;DESCR_BU&quot;: &quot;OhioFarmersInsuranceCo&quot;, &quot;ADDRESS1_BU&quot;: &quot;WESTFIELDCOMPANIES&quot;, &quot;ADDRESS2_BU&quot;: &quot;HOMEOFFICE&quot;, &quot;ADDRESS3_BU&quot;: &quot;1PARKCIRCLE&quot;, &quot;ADDRESS4_BU&quot;: &quot;&quot;, &quot;CITY_BU&quot;: &quot;WESTFIELDCENTER&quot;, &quot;STATE_BU&quot;: &quot;OH&quot;, &quot;POSTAL_BU&quot;: &quot;44251-5001&quot;, &quot;COUNTRY_BU&quot;: &quot;USA&quot;, &quot;ADDRESS1_BILL&quot;: &quot;&quot;, &quot;ADDRESS2_BILL&quot;: &quot;&quot;, &quot;ADDRESS3_BILL&quot;: &quot;&quot;, &quot;ADDRESS4_BILL&quot;: &quot;&quot;, &quot;CITY_BILL&quot;: &quot;&quot;, &quot;STATE_BILL&quot;: &quot;&quot;, &quot;POSTAL_BILL&quot;: &quot;&quot;, &quot;COUNTRY_BILL&quot;: &quot;&quot;, &quot;CURRENCY_CD&quot;: &quot;USD&quot;, &quot;TAX_EXEMPT_ID&quot;: &quot;&quot;, &quot;STD_ID_NUM_VNDR&quot;: &quot;&quot;, &quot;NAME1_VNDR&quot;: &quot;AMAZONCAPITALSERVICESINC&quot;, &quot;ADDRESS1_VNDR&quot;: &quot;410TERRYAVEN&quot;, &quot;ADDRESS2_VNDR&quot;: &quot;&quot;, &quot;ADDRESS3_VNDR&quot;: &quot;&quot;, &quot;ADDRESS4_VNDR&quot;: &quot;&quot;, &quot;CITY_VNDR&quot;: &quot;SEATTLE&quot;, &quot;STATE_VNDR&quot;: &quot;WA&quot;, &quot;POSTAL_VNDR&quot;: 98109, &quot;COUNTRY_VNDR&quot;: &quot;USA&quot;, &quot;PYMNT_TERMS_CD&quot;: &quot;NET30&quot;, &quot;DESCR50_PAY&quot;: &quot;Net30&quot;, &quot;BUYER_ID&quot;: 1083, &quot;PO_AMT_TTL&quot;: 14.99, &quot;TEXT254_CC1&quot;: &quot;&quot;, &quot;TEXT254_CC2&quot;: &quot;&quot;, &quot;VNDR_UPN_FLG&quot;: &quot;N&quot;, &quot;STD_ID_NUM_VNDRGLN&quot;: &quot;&quot;, &quot;STD_ID_NUM_BILLTO&quot;: &quot;&quot;, &quot;ATTN_TO&quot;: &quot;ZacharyEngels&quot;, &quot;PO_POD_LN_EVW1&quot;: { &quot;WG_REQ_ID&quot;: 25694, &quot;WG_CATEGORY_CD&quot;: &quot;FSSUP&quot;, &quot;WG_ITEM_TYPE&quot;: 0, &quot;WG_ACCOUNT&quot;: 641100, &quot;WG_DEPT_ID&quot;: 30400, &quot;WG_PRODUCT&quot;: &quot;&quot;, &quot;BUSINESS_UNIT&quot;: &quot;OFIC&quot;, &quot;PO_ID&quot;: 25052, &quot;WG_ASSET_GROUP&quot;: &quot;&quot;, &quot;WG_CAPITALIZE&quot;: &quot;NO&quot;, &quot;WG_PROFILE_ID&quot;: &quot;&quot;, &quot;WG_SPLIT_TYPE&quot;: 1, &quot;WG_ASSET_LOC&quot;: &quot;HOME&quot;, &quot;WG_PROJECT&quot;: &quot;&quot;, &quot;VENDOR_SETID&quot;: &quot;WCOS&quot;, &quot;VENDOR_ID&quot;: 35958, &quot;VNDR_LOC&quot;: 1, &quot;LINE_NBR&quot;: 1, &quot;INV_ITEM_ID&quot;: &quot;&quot;, &quot;DESCR254_MIXED&quot;: &quot;147-1518156-3620845,1GreenMountainCoffeeRoastersCaramelVanillaCreamKeurigSingle-ServeK-CupPods,LightRoastCoffee,32Count&quot;, &quot;UNIT_OF_MEASURE&quot;: &quot;EA&quot;, &quot;ITM_ID_VNDR&quot;: &quot;B0798CX2Q9&quot;, &quot;INV_ITEM_WEIGHT&quot;: 0, &quot;INV_ITEM_HEIGHT&quot;: 0, &quot;INV_ITEM_VOLUME&quot;: 0, &quot;INV_ITEM_LENGTH&quot;: 0, &quot;INV_ITEM_WIDTH&quot;: 0, &quot;VNDR_CATALOG_ID&quot;: &quot;&quot;, &quot;MFG_ID&quot;: &quot;&quot;, &quot;MFG_ITM_ID&quot;: 5000196305, &quot;CNTRCT_ID&quot;: &quot;&quot;, &quot;VERSION_NBR&quot;: 0, &quot;CNTRCT_LINE_NBR&quot;: 0, &quot;CAT_LINE_NBR&quot;: 0, &quot;RELEASE_NBR&quot;: 0, &quot;CANCEL_STATUS&quot;: &quot;A&quot;, &quot;UPN_ID&quot;: &quot;&quot;, &quot;PO_POD_SHP_EVW1&quot;: { &quot;WG_SHIP_ADDR_TYPE&quot;: 0, &quot;WG_CUST_ADDR_CODE&quot;: &quot;OFIC&quot;, &quot;BUSINESS_UNIT&quot;: &quot;OFIC&quot;, &quot;PO_ID&quot;: 25052, &quot;VENDOR_SETID&quot;: &quot;WCOS&quot;, &quot;VENDOR_ID&quot;: 35958, &quot;VNDR_LOC&quot;: 1, &quot;LINE_NBR&quot;: 1, &quot;SCHED_NBR&quot;: 1, &quot;DUE_DT&quot;: &quot;2020-01-29&quot;, &quot;SHIPTO_ID&quot;: &quot;OFIC&quot;, &quot;DESCR_SHIPTO&quot;: &quot;OHIOFARMERSINSURANCECOMPANY&quot;, &quot;ADDRESS1_SHIPTO&quot;: &quot;OHIOFARMERSINSURANCECOMPANY&quot;, &quot;ADDRESS2_SHIPTO&quot;: &quot;1PARKCIRCLE&quot;, &quot;ADDRESS3_SHIPTO&quot;: &quot;POBOX5001&quot;, &quot;ADDRESS4_SHIPTO&quot;: &quot;&quot;, &quot;CITY_SHIPTO&quot;: &quot;WESTFIELDCENTER&quot;, &quot;STATE_SHIPTO&quot;: &quot;OH&quot;, &quot;POSTAL_SHIPTO&quot;: &quot;44251-5001&quot;, &quot;COUNTRY_SHIPTO&quot;: &quot;USA&quot;, &quot;PRICE_PO&quot;: 14.99, &quot;FREIGHT_TERMS&quot;: &quot;FOBDEST&quot;, &quot;QTY_PO&quot;: 1, &quot;SHIP_TYPE_ID&quot;: &quot;BEST_WAY&quot;, &quot;CANCEL_STATUS&quot;: &quot;A&quot;, &quot;ATTN_TO&quot;: &quot;&quot;, &quot;STD_ID_NUM_SHIPTO&quot;: &quot;&quot; }, &quot;PSCAMA&quot;: { &quot;AUDIT_ACTN&quot;: &quot;A&quot; } }, &quot;PSCAMA&quot;: { &quot;AUDIT_ACTN&quot;: &quot;A&quot; } }, &quot;PSCAMA&quot;: { &quot;LANGUAGE_CD&quot;: &quot;ENG&quot;, &quot;AUDIT_ACTN&quot;: &quot;A&quot;, &quot;BASE_LANGUAGE_CD&quot;: &quot;ENG&quot;, &quot;MSG_SEQ_FLG&quot;: &quot;&quot;, &quot;PROCESS_INSTANCE&quot;: 1199010, &quot;PUBLISH_RULE_ID&quot;: &quot;WG_MAIN_RULE&quot;, &quot;MSGNODENAME&quot;: &quot;&quot; } } } } } </code></pre> <p>Below is the JOLT Spec-</p> <pre class="lang-json prettyprint-override"><code>[ { &quot;operation&quot;: &quot;shift&quot;, &quot;spec&quot;: { &quot;#UPSERT&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityHeader.action&quot;, &quot;*&quot;: { &quot;*&quot;: { &quot;*&quot;: { &quot;*&quot;: { &quot;PO_ID&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.externalId&quot;, &quot;#APPROVED&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.status&quot;, &quot;PO_AMT_TTL&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.grossTotalAmount&quot;, &quot;FREIGHT_TERMS&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.deliveryTermCode&quot;, &quot;WG_REQUESTOR_EMAIL&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.requesterDetails.userEmailId&quot;, &quot;*&quot;: { &quot;WG_REQ_ID&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.poDescription&quot;, &quot;#STANDARD&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.poType&quot;, &quot;*&quot;: { &quot;FREIGHT_TERMS&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.deliveryTermCode&quot; } } } } } } } }, { &quot;operation&quot;: &quot;shift&quot;, &quot;spec&quot;: { &quot;*&quot;: { &quot;*&quot;: { &quot;*&quot;: { &quot;integrationEntityHeader&quot;: &quot;&amp;3.&amp;2.&amp;1.&amp;&quot;, &quot;integrationEntityDetails&quot;: { &quot;*&quot;: { &quot;externalId&quot;: &quot;&amp;5.&amp;4.&amp;3.&amp;2.&amp;1.&amp;&quot;, &quot;status&quot;: &quot;&amp;5.&amp;4.&amp;3.&amp;2.&amp;1.&amp;&quot;, &quot;poHeader&quot;: &quot;&amp;5.&amp;4.&amp;3.&amp;2.&amp;1.&amp;&quot;, &quot;poDescription&quot;: &quot;&amp;5.&amp;4.&amp;3.&amp;2.&amp;1.&amp;&quot;, &quot;poType&quot;: &quot;&amp;5.&amp;4.&amp;3.&amp;2.&amp;1.&amp;&quot;, &quot;items&quot;: &quot;&amp;5.&amp;4.&amp;3.&amp;2.&amp;1.&amp;&quot; } } } } } } }, { &quot;operation&quot;: &quot;cardinality&quot;, &quot;spec&quot;: { &quot;*&quot;: { &quot;*&quot;: { &quot;*&quot;: { &quot;*&quot;: { &quot;*&quot;: { &quot;status&quot;: &quot;ONE&quot;, &quot;poHeader&quot;: { &quot;*&quot;: &quot;ONE&quot; } } } } } } } } ] </code></pre>
[ { "answer_id": 74582515, "author": "Mark Rotteveel", "author_id": 466862, "author_profile": "https://Stackoverflow.com/users/466862", "pm_score": 2, "selected": true, "text": "org.hibernate.dialect.MySQLDialect InnoDB org.hibernate.dialect.MySQL8Dialect" }, { "answer_id": 74582523, "author": "Mohsen R. Agdam", "author_id": 8466720, "author_profile": "https://Stackoverflow.com/users/8466720", "pm_score": 0, "selected": false, "text": "application.properties spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL8Dialect\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20530341/" ]
74,582,432
<p>I come to this <a href="https://leetcode.com/problems/maximum-product-of-splitted-binary-tree/solutions/496549/java-c-python-easy-and-concise/https://leetcode.com/problems/maximum-product-of-splitted-binary-tree/solutions/496549/java-c-python-easy-and-concise/" rel="nofollow noreferrer">code</a> in a LeetCode problem</p> <pre><code>class Solution: def maxProduct(self, root): self.res = total = 0 def s(root): if not root: return 0 left, right = s(root.left), s(root.right) self.res = max(self.res, left * (total - left), right * (total - right)) return left + right + root.val total = s(root) s(root) return self.res % (10**9 + 7) </code></pre> <p>I change <code>self.res</code> to <code>res</code> like the following</p> <pre><code>class Solution: def maxProduct(self, root): res = total = 0 def s(root): if not root: return 0 left, right = s(root.left), s(root.right) res = max(res, left * (total - left), right * (total - right)) return left + right + root.val total = s(root) s(root) return res % (10**9 + 7) </code></pre> <p>and the code breaks with <code>UnboundLocalError: local variable 'res' referenced before assignment</code>. Why <code>res</code> has to be initialized as <code>self.res</code> while <code>total</code> does not?</p>
[ { "answer_id": 74582515, "author": "Mark Rotteveel", "author_id": 466862, "author_profile": "https://Stackoverflow.com/users/466862", "pm_score": 2, "selected": true, "text": "org.hibernate.dialect.MySQLDialect InnoDB org.hibernate.dialect.MySQL8Dialect" }, { "answer_id": 74582523, "author": "Mohsen R. Agdam", "author_id": 8466720, "author_profile": "https://Stackoverflow.com/users/8466720", "pm_score": 0, "selected": false, "text": "application.properties spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL8Dialect\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8926191/" ]
74,582,446
<p>I have such structure:</p> <pre><code>class Category(models.Model): name = models.CharField(max_length=255, validators=[MinLengthValidator(3)]) parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE ) slug = models.SlugField(max_length=255, null=False, unique=True) class Product(models.Model): name = models.CharField(max_length=255, validators=[MinLengthValidator(3)]) to_category = models.ForeignKey(Category, on_delete=models.SET_NULL, blank=True, null=True, ) slug = models.SlugField(max_length=255, null=False, unique=True) </code></pre> <p>I have created one category with slug &quot;test&quot;. When I try to create new category with slug &quot;test&quot; I got warning message and it is Ok. But If I try to create product with slug &quot;test&quot; I dont have warning and this is not good in my case. Is there a solution or method to validate slug field for uniqueness with Product and Category model?</p>
[ { "answer_id": 74582502, "author": "Alexander Schillemans", "author_id": 9625038, "author_profile": "https://Stackoverflow.com/users/9625038", "pm_score": 2, "selected": false, "text": "def is_slug_unique(slug):\n product_exists = Product.objects.filter(slug=slug).exists()\n category_exists = Category.objects.filter(slug=slug).exists()\n if product_exists or category_exists:\n return False\n else:\n return True\n\nclass Category(models.Model)\n ...\n\n def save(self, *args, **kwargs):\n slug_unique = is_slug_unique(self.slug)\n if not slug_unique:\n # do something when the slug is not unique\n else:\n # do something when the slug is unique\n super().save(*args, **kwargs)\n\nclass Product(models.Model)\n ...\n\n def save(self, *args, **kwargs):\n slug_unique = is_slug_unique(self.slug)\n if not slug_unique:\n # do something when the slug is not unique\n else:\n # do something when the slug is unique\n super().save(*args, **kwargs)\n\n\n" }, { "answer_id": 74584214, "author": "Willem Van Onsem", "author_id": 67579, "author_profile": "https://Stackoverflow.com/users/67579", "pm_score": 1, "selected": false, "text": "Slug class Slug(models.Model):\n slug = models.SlugField(max_length=255, primary_key=True)\n ForeignKey Slug from django.core.exceptions import ValidationError\n\n\nclass Product(models.Model):\n name = models.CharField(max_length=255, validators=[MinLengthValidator(3)])\n to_category = models.ForeignKey(\n Category, on_delete=models.SET_NULL, blank=True, null=True\n )\n slug = models.ForeignKey(Slug, on_delete=models.PROTECT)\n\n def validate_slug(self):\n if self.pk is not None and Slug.objects.filter(pk=self.slug_id).exclude(\n product__pk=self.pk\n ):\n raise ValidationError('The slug is already used.')\n\n def clean(self, *args, **kwargs):\n self.validate_slug()\n return super().clean(*args, **kwargs)\n\n def save(self, *args, **kwargs):\n self.validate_slug()\n return super().save(*args, **kwargs)" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20590534/" ]
74,582,472
<p>What does the <code>&lt;stdbool.h&gt;</code> do when using it in a C code?</p> <p>I searched for it on the Wikipedia and didn't get answers in my language, i would love that someone will explain to me what it means.</p>
[ { "answer_id": 74582925, "author": "chqrlie", "author_id": 4593267, "author_profile": "https://Stackoverflow.com/users/4593267", "pm_score": 2, "selected": true, "text": "bool true false _Bool <stdbool.h> <stdbool.h> <stdbool.h> bool\n _Bool #if true\n ((_Bool)+1u) false\n ((_Bool)+0u) __bool_true_false_are_defined\n 1 bool true false <stdbool.h> bool true false #if true ((_Bool)+1u) ((_Bool)1u) #if true #if ((_Bool)+1u) #if ((0)+1u) #if ((0)1u)" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20606902/" ]
74,582,505
<p>Hi to all kivy/python experts. I am looking for an advice/solution, after trying everything I found for the last week.</p> <h1>Here's my scenario:</h1> <ol> <li>I have a kivy app with 2 screens, therefore I am using a Screen manager, with each screen (1 and 2) defined in my .kv file</li> <li>after clicking log-in on my 1st screen, app jumps to 2nd one. In this second screen, I have a button and a label (keeping it simple for the example). Now the issue:</li> </ol> <ul> <li>when clicking on the button, I am calling a method <strong>foo1()</strong> which is in the same class: Screen2. <strong>foo1()</strong> is called on_press with a specific argument (from within .kv file, using <strong>on_press = root.foo1(arg)</strong>)</li> <li>based on the arg received, the function calculates something, then calls another function <strong>foo2()</strong>, passing the result. The <strong>foo2()</strong> is located in <strong>another python file(external.py), within another class</strong> (so we have different file, different class and in that class a method: foo2). All good so far</li> <li>after finalizing some calculations, <strong>foo2()</strong> should return the result. Where? Well, inside my kivy label, on Screen2.</li> </ul> <h1><strong>Problem encountered:</strong></h1> <p>When trying to write the result from <strong>foo2()</strong> into my text label <strong>(my_label)</strong> in <strong>screenTwo</strong>, **foo2() **fails to instantiate the ids of the screen 2 (throwing all sorts of errors, depending on the things I tried (see below).</p> <p>I can understand the reason: The moment I am calling <strong>foo2()</strong> from <strong>foo1()</strong> we are exiting the screenTwo as a parent for my_label, which changes the <strong>&quot;self&quot;</strong> context (of <strong>self.ids.my_label.text = result</strong> from <strong>foo2()</strong>). This now no longer refers to <strong>screenTwo</strong>, but probably to the in-memory address of the <strong>foo2()</strong> function which I think now acts as a parent (at least this is what I concluded, I am still a beginner in python).</p> <h1>Things I tried:</h1> <p>Basically everything I could find, to try and find the &quot;real&quot; parent that I need to enumerate, to find the children IDs where my_label actually is, but wasn't able to:</p> <ol> <li><p>tried declaring an ObjectProperty = None inside my Screen2 class, then give an id to my label and then a variable name which refers to that id inside my Screen2 class. This is recommended by many tutorials, but this is working when passing things between screens, not in my case.</p> </li> <li><p>tried changing (inside foo2()) the reference to the destination of the label, from self.ids to</p> </li> </ol> <ul> <li>root.self.ids.my_label.text</li> <li>root.manager.get_current('screenTwo').ids.my_label.text</li> <li>main.root.manager.get_current('screenTwo').ids.my_label.text</li> <li>app.main.root.manager.ids('screenTwo').ids.my_label.text</li> <li>and maaaany other... :(</li> </ul> <p>Depending on what I've tried (many tries) I received various errors. Here's some:</p> <p><em>- kivy AttributeError: 'super' object has no attribute '<strong>getattr</strong>'</em> <a href="https://stackoverflow.com/questions/39074550/python-kivy-attributeerror-super-object-has-no-attribute-getattr-whe">thread here also</a></p> <p><em>- NameError: name 'root' is not defined</em></p> <p><em>- AttributeError: 'str' object has no attribute 'text'</em></p> <p><em>- Kivy AttributeError: 'NoneType' object has no attribute 'ids'</em></p> <p>I do not seem to understand how this self/root/app context works, despite looking up at various resources (stackoverflow, pdf files, kivy official documentation) (if someone could recommend a good tutorial or explain for all newbies like me out there...wow how helpful it would be).</p> <p>Also, I couldn't find anything related to whether this is actually possible, considering that from within the class that holds the current screen you're actually calling an external function located in another py file: **does kivy even support passing down responses from external functions back to the main function? **(I assume it does, since this is pure python, not kivy. kivy just manages the writing, within the correct context....if I were just able to figure it out :( ).</p> <p>Anyway, here's my sample code (py + kv file). If any of you could give me a hint or a solution to how I could call a function which calls an external function which then writes the response back on the screen from which I started the events, in a label, I would be very thankful!</p> <h1>main.py</h1> <pre><code>from kivy.uix.screenmanager import ScreenManager, Screen from kivymd.app import MDApp from kivy.app import App from kivymd.uix.label import MDLabel from kivy.properties import ObjectProperty, StringProperty import external class Screen1Main(Screen): pass class Screen2(Screen): def foo1(): # 1. do something myArg = &quot;x&quot; # 2. then call foo2() external.myExternalClass.foo2(myArg) class WindowManager(ScreenManager): pass class MainApp(MDApp): def __init__(self, **kwargs): self.title = &quot;My Application&quot; super().__init__(**kwargs) if __name__ == &quot;__main__&quot;: MainApp().run() </code></pre> <p><strong>external.py</strong></p> <pre><code>from kivy.app import App import main class myExternalClass: def foo2(arg1): #1. does something blabla #2. gets the result myResult = &quot;anything&quot; #3. tries to write the result into my_label (located in Screen 2, which is a child # of my main app (in file: main.py), who manages the multi-screen via a screen manager within # WindowsManager class) Screen2.manager.get_screen(&quot;screenTwo&quot;).ids.my_label.text = myResult --- </code></pre> <h1>main.kv</h1> <pre><code>WindowManager: Screen1Main: id: id_screenOne Screen2: id: id_screenTwo &lt;Screen1Main&gt;: name: &quot;screenOne&quot; GridLayout: &lt;rest of layout here&gt; &lt;Screen2&gt;: name: &quot;screenTwo&quot; GridLayout: cols: 2 MDLabel: id: my_label text: &quot;-&quot; MDIconButton: id: my_button icon: &quot;message-arrow-left&quot; on_release: root.foo1(arg0) </code></pre> <pre><code> # Things I tried: Basically everything I could find, as described above. </code></pre>
[ { "answer_id": 74582925, "author": "chqrlie", "author_id": 4593267, "author_profile": "https://Stackoverflow.com/users/4593267", "pm_score": 2, "selected": true, "text": "bool true false _Bool <stdbool.h> <stdbool.h> <stdbool.h> bool\n _Bool #if true\n ((_Bool)+1u) false\n ((_Bool)+0u) __bool_true_false_are_defined\n 1 bool true false <stdbool.h> bool true false #if true ((_Bool)+1u) ((_Bool)1u) #if true #if ((_Bool)+1u) #if ((0)+1u) #if ((0)1u)" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20606508/" ]
74,582,510
<p>In a data set I have the following variables:</p> <p>• freehms: opinion if gays and lesbians free to live as they wish</p> <p>• prtvtcie: Party participant voted for</p> <p>• trstplt: Trust in politicians</p> <p>• agea: Calculated age of the participant</p> <p>• gndr_dummy: Dummy variable for gender</p> <p>I want to estimate the fit of two multinomial logistic regression models using a likelihood ratio test, one with interaction and one without an interaction term between level of trust (trstplt) and opinion on lesbian/gays (freehms).</p> <p>I have estimated the following model - without interaction:</p> <pre><code>model_without_interaction &lt;- multinom(prtvtcie ~ freehms + agea + gndr_dummy, data = ie) </code></pre> <p>For the model with interaction term, I have estimated the following term:</p> <pre><code>model_with_interaction &lt;- multinom(prtvtcie ~ freehms + trstplt + freehms*trstplt + agea + gndr_dummy, data = ie22) </code></pre> <p>I use the likelihood ratio test, to test whether the interaction term between level of trust (trstplt) and opinion on lesbian/gays (freehms) adds additional value to the model.</p> <p>For this I have used the following code:</p> <pre><code>lrtest(model_with_interaction,&quot;freehms * trstplt&quot;) </code></pre> <p>However, I receive the following error message: <kbd>Error in (function (classes, fdef, mtable) : cannot find inherited method for function 'lrtest' for signature '&quot;multinom&quot;'.</kbd></p> <p>So my question is: How can I estimate a likelihood ratio test?</p>
[ { "answer_id": 74582541, "author": "DaveArmstrong", "author_id": 8206434, "author_profile": "https://Stackoverflow.com/users/8206434", "pm_score": 1, "selected": false, "text": "model_without_interaction <- multinom(prtvtcie ~ freehms + \n agea + gndr_dummy, data = ie)\n\nmodel_with_interaction <- multinom(prtvtcie ~ freehms*trstplt + \n agea + gndr_dummy, data = ie22)\n\nlrtest(model_without_interaction, model_with_interaction)\n model_with_interaction model_without_interaction" }, { "answer_id": 74601370, "author": "Nick Glättli", "author_id": 17602505, "author_profile": "https://Stackoverflow.com/users/17602505", "pm_score": 0, "selected": false, "text": "VGAM lmtest::lrtest(model_without_interaction, model_with_interaction)\n nominal_model_interact <- multinom(party_vote ~ freehms*trust + age + sex,\n data = df_it,\n weights = dweight)\n\nnominal_model_nafree <- multinom(party_vote ~ freehms + age + sex,\n data = df_it %>% filter(!is.na(freehms)),\n weights = dweight)\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20373595/" ]
74,582,532
<p>I want to create an array which elements look like this &quot;1A 2A 3A... etc&quot;. My problem that every time, the program set all of the elements the value of the last added value. So my final output is &quot;25F 25F 25F...&quot;</p> <p>Here is my code:</p> <pre><code>void func() { char c[10]; char s[10]; char *arr[150]; int idx = 0; for (int i = 1; i &lt;= 25; ++i) { for (char j = 'A'; j &lt;= 'F'; ++j) { sprintf(c, &quot;%d%c&quot;, i,j); strcpy(s,c); arr[idx++] = s; printf(&quot;%s&quot;, s); } } for (int i = 0; i &lt; 150; ++i) { printf(&quot;%s\n&quot;, arr[i]); } } </code></pre>
[ { "answer_id": 74582562, "author": "john", "author_id": 882003, "author_profile": "https://Stackoverflow.com/users/882003", "pm_score": 0, "selected": false, "text": "arr s s arr" }, { "answer_id": 74613365, "author": "Luis Colorado", "author_id": 3899431, "author_profile": "https://Stackoverflow.com/users/3899431", "pm_score": 1, "selected": false, "text": " arr[idx++] = s;\n s arr[idx++] = strdup(s);\n s sprintf() free(arr[idx++]);" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17885051/" ]
74,582,551
<p>Here are some string items:</p> <pre><code>string[] r = {&quot;item1&quot;,&quot;item2&quot;, &quot;item3&quot;} </code></pre> <p>I want to loop through GridView and add each string items to the GridView rows</p> <pre><code>for (int i = 0; i &lt; GridView1.Rows.Count; i++) { GridView1.Rows[i].Cells[0].Text += r[i]; } </code></pre> <p>The GridView doesnt display any data... What method should use to solve this problem?</p>
[ { "answer_id": 74582562, "author": "john", "author_id": 882003, "author_profile": "https://Stackoverflow.com/users/882003", "pm_score": 0, "selected": false, "text": "arr s s arr" }, { "answer_id": 74613365, "author": "Luis Colorado", "author_id": 3899431, "author_profile": "https://Stackoverflow.com/users/3899431", "pm_score": 1, "selected": false, "text": " arr[idx++] = s;\n s arr[idx++] = strdup(s);\n s sprintf() free(arr[idx++]);" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20465780/" ]
74,582,552
<p>I am trying to solve this challenge, but my code doesn't seem to work, is there a fix? Here is the question:</p> <p>In this kata you are required to, given a string, replace every letter with its position in the alphabet.</p> <p>If anything in the text isn't a letter, ignore it and don't return it.</p> <p>&quot;a&quot; = 1, &quot;b&quot; = 2, etc.</p> <p>Example alphabet_position(&quot;The sunset sets at twelve o' clock.&quot;) Should return &quot;20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11&quot; ( as a string )</p> <p>Here is my code:</p> <p>`</p> <pre><code>def alphabet_position(text): new= '' a1 = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;,&quot;e&quot;,&quot;f&quot;,&quot;g&quot;,&quot;h&quot;,&quot;i&quot;,&quot;j&quot;,&quot;k&quot;,&quot;l&quot;,&quot;m&quot;,&quot;n&quot;,&quot;o&quot;,&quot;p&quot;,&quot;q&quot;,&quot;r&quot;,&quot;s&quot;,&quot;t&quot;,&quot;u&quot;,&quot;v&quot;,&quot;w&quot;,&quot;x&quot;,&quot;y&quot;,&quot;z&quot;] a2 = [&quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;D&quot;,&quot;E&quot;,&quot;F&quot;,&quot;G&quot;,&quot;H&quot;,&quot;I&quot;,&quot;J&quot;,&quot;K&quot;,&quot;L&quot;,&quot;M&quot;,&quot;N&quot;,&quot;O&quot;,&quot;P&quot;,&quot;Q&quot;,&quot;R&quot;,&quot;S&quot;,&quot;T&quot;,&quot;U&quot;,&quot;V&quot;,&quot;W&quot;,&quot;X&quot;,&quot;Y&quot;,&quot;Z&quot;] n= ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26'] for i in range(0, len(text)-1): if i in a1: index= a1.index(i) new+= n[index] elif i in a2: index=a2.index(i) new+= n[index] return new </code></pre> <p>`</p>
[ { "answer_id": 74582693, "author": "Daniel Hao", "author_id": 10760768, "author_profile": "https://Stackoverflow.com/users/10760768", "pm_score": 2, "selected": false, "text": "\ndef alphabet_position(s):\n return \" \".join(str(ord(c)-ord(\"a\")+1) for c in s.lower() if c.isalpha())\n\n# Or you still like your original mapping approach:\n\ndef alphabet_position(text):\n letters = \"abcdefghijklmnopqrstuvwxyz\"\n \n return \" \".join([str(letters.find(c) + 1)\n for c in text.lower() if c in letters])\n\n\nprint(alphabet_position(\"The sunset sets at twelve o' clock.\"))\n\n# 20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11\n" }, { "answer_id": 74582958, "author": "John Coleman", "author_id": 4996248, "author_profile": "https://Stackoverflow.com/users/4996248", "pm_score": 2, "selected": false, "text": "a1 a2 if text def alphabet_position(text):\n new= []\n a1 = [\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\",\"i\",\"j\",\"k\",\"l\",\"m\",\"n\",\"o\",\"p\",\"q\",\"r\",\"s\",\"t\",\"u\",\"v\",\"w\",\"x\",\"y\",\"z\"]\n a2 = [\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"I\",\"J\",\"K\",\"L\",\"M\",\"N\",\"O\",\"P\",\"Q\",\"R\",\"S\",\"T\",\"U\",\"V\",\"W\",\"X\",\"Y\",\"Z\"]\n n= ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26']\n for i in text:\n if i in a1:\n index= a1.index(i)\n new.append(n[index])\n elif i in a2:\n index=a2.index(i)\n new.append(n[index]) \n return ' '.join(new)\n alphabet_position(\"The sunset sets at twelve o' clock.\")\n'20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11'\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19905146/" ]
74,582,565
<pre class="lang-cpp prettyprint-override"><code>int dfs(int idx, int mv, char gest){ if (idx &gt; n || mv &gt; k){ return 0; } int tmp1 = 0; if(mv&lt;k){ if(fj[idx]=='H'){ if(gest!='P'){ tmp1=1+dfs(idx+1,mv+1, gest='P'); } else{ tmp1=1+dfs(idx+1, mv, gest='P'); } } else if(fj[idx]=='P'){ if(gest!='S'){ tmp1=1+dfs(idx+1,mv+1, 'S'); } else{ tmp1=1+dfs(idx+1, mv, 'S'); } } else if(fj[idx]=='S'){ if(gest!='H'){ tmp1=1+dfs(idx+1,mv+1,'H'); } else{ tmp1=1+dfs(idx+1, mv, 'H'); } } } int tmp2 = 0; if (check(fj[idx], gest)){ tmp2 = 1 + dfs(idx + 1, mv, gest); } else{ tmp2 = dfs(idx + 1, mv, gest); } return max(tmp1, tmp2); } </code></pre> <p>In order to complete an OI problem, I wrote the previous dfs function, but lines 9 and 12 led to incorrect results. If I delete the &quot;gest=&quot; in front of the parameter, the result is correct. Why? What problems will such function parameter transfer bring in C++?</p> <pre class="lang-cpp prettyprint-override"><code>if(mv&lt;k){ if(fj[idx]=='H'){ if(gest!='P'){ tmp1=1+dfs(idx+1,mv+1, 'P'); } else{ tmp1=1+dfs(idx+1, mv, 'P'); } } else if(fj[idx]=='P'){ if(gest!='S'){ tmp1=1+dfs(idx+1,mv+1, 'S'); } else{ tmp1=1+dfs(idx+1, mv, 'S'); } } else if(fj[idx]=='S'){ if(gest!='H'){ tmp1=1+dfs(idx+1,mv+1,'H'); } else{ tmp1=1+dfs(idx+1, mv, 'H'); } } } </code></pre> <p>this is right.</p>
[ { "answer_id": 74582687, "author": "skybaks", "author_id": 19788693, "author_profile": "https://Stackoverflow.com/users/19788693", "pm_score": 1, "selected": false, "text": "gest='P';\ntmp1=1+dfs(idx+1,mv+1, gest);\n" }, { "answer_id": 74582698, "author": "fabian", "author_id": 2991525, "author_profile": "https://Stackoverflow.com/users/2991525", "pm_score": -1, "selected": false, "text": "dfs(idx+1,mv+1, gest='P')\n gest 'P' gest tmp1=1+dfs(idx+1,mv+1, gest='P');\n gest = 'P';\ntmp1=1+dfs(idx+1,mv+1, gest);\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20606983/" ]
74,582,595
<p>For the following DOM, only child3 should be having a 100% width ignoring/overriding the padding of the parent container, and the rest child elements should have 100% width while also respecting the padding</p> <pre><code>&lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;child1&quot;&gt;&lt;/div&gt; &lt;div class=&quot;child2&quot;&gt;&lt;/div&gt; &lt;div class=&quot;child3&quot;&gt;&lt;/div&gt; &lt;div class=&quot;child4&quot;&gt;&lt;/div&gt; &lt;div class=&quot;child5&quot;&gt;&lt;/div&gt; &lt;div class=&quot;child6&quot;&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>constraints for container's CSS</p> <pre><code>.container { width: 300px; padding: 40px; } </code></pre> <p>what is the best way to implement the same? one way to achieve this is:</p> <pre><code>.child3 { width: 300px; margin-left: -40px; /*to offset parent container's padding*/ } </code></pre> <p>Here is what my code does:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.container { width: 300px; padding: 40px; } .child3 { width: 300px; margin-left: -40px; /*to offset parent container's padding*/ }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="container"&gt; &lt;div class="child1"&gt;&lt;/div&gt; &lt;div class="child2"&gt;&lt;/div&gt; &lt;div class="child3"&gt;&lt;/div&gt; &lt;div class="child4"&gt;&lt;/div&gt; &lt;div class="child5"&gt;&lt;/div&gt; &lt;div class="child6"&gt;&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Here is a rough diagram showing what I would like it to do<a href="https://i.stack.imgur.com/iF92z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iF92z.png" alt="." /></a></p>
[ { "answer_id": 74583088, "author": "Neptotech -vishnu", "author_id": 14862885, "author_profile": "https://Stackoverflow.com/users/14862885", "pm_score": 1, "selected": false, "text": "--padding :root total possible length when not parent padding is ignored + twice the padding(becuase padding acts on both side) - 1px(which is border) -padding :root {\n --padding: 40px;\n}\n.container {\n width: 300px;\n padding: var(--padding);\n height: 100px;\n border: 1px solid black;\n}\n.child3 {\n width: calc(100% + (2*var(--padding)) - 1px);\n margin-left: calc(0px - var(--padding)); /*to offset parent container's padding*/\n}\n.container *{\nborder: 1px solid red;\nheight:5px;\n} <div class=\"container\">\n <div class=\"child1\"></div>\n <div class=\"child2\"></div>\n <div class=\"child3\"></div>\n <div class=\"child4\"></div>\n <div class=\"child5\"></div>\n <div class=\"child6\"></div>\n</div>" }, { "answer_id": 74584231, "author": "tatactic", "author_id": 1247977, "author_profile": "https://Stackoverflow.com/users/1247977", "pm_score": 0, "selected": false, "text": " *{\n box-sizing: border-box;\n }\n .container {\n width: 300px;\n padding-top: 40px;\n padding-bottom: 40px;\n border:1px solid #000000;\n }\n .container div{\n margin-left: 40px;\n margin-right: 40px;\n margin-bottom: 10px;\n height:20px;\n border:1px solid #000000;\n }\n .container .child3 {\n width: 100%;\n margin-left:auto;\n margin-right:auto;\n border:1px solid #ff0000;\n }\n .container .child6 {\n margin-bottom: 0px;\n } <div class=\"container\">\n <div class=\"child1\">My content 1</div>\n <div class=\"child2\">My content 2</div>\n <div class=\"child3\">My content 3</div>\n <div class=\"child4\">My content 4</div>\n <div class=\"child5\">My content 5</div>\n <div class=\"child6\">My content 6 (last div)</div>\n</div>" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11837710/" ]
74,582,606
<pre><code>#include&lt;stdio.h&gt; int *arr; int main() { arr = calloc(1, sizeof(int)); free(arr); return 0; } </code></pre> <p>As far as I understand, this warning occurs because I did not declare the function in header (In this case I should've included <code>stdlib.h</code>). My questions are:</p> <ol> <li><p>Why doesn't the GCC give an error? Because as far as I understand, <code>calloc</code> is located at <code>stdlib.h</code>, but I didn't include it in my program. Why does my program still know what is <code>calloc</code>?</p> </li> <li><p>Should we close our eyes at the warning? Because my program works well even without include of <code>stdlib.h</code>.</p> </li> </ol>
[ { "answer_id": 74582726, "author": "Kompetenzbolzen", "author_id": 10986134, "author_profile": "https://Stackoverflow.com/users/10986134", "pm_score": 1, "selected": false, "text": "stdlib.h libc.so // a.c\nint asdf(int b){\n return b+1;\n}\n\n// main.c\nint main(void) {\n asdf();\n return 0;\n}\n gcc main.c a.c" }, { "answer_id": 74582884, "author": "chqrlie", "author_id": 4593267, "author_profile": "https://Stackoverflow.com/users/4593267", "pm_score": 3, "selected": true, "text": "<stdlib.h> <stdlib.h> calloc void *calloc(size_t, size_t); int calloc(int, size_t) calloc calloc int int * arr int * int arr free(arr) calloc gcc -Wall -Wextra -Werror <stdlib.h> gcc #include <stdio.h>\n#include <stdlib.h>\n\nint main() {\n int *arr = calloc(1, sizeof(*arr)); /* use object type for consistency */\n\n printf(\"pointer value is %p\\n\", (void *)arr);\n\n free(arr);\n return 0;\n}\n" }, { "answer_id": 74582912, "author": "chrslg", "author_id": 20037042, "author_profile": "https://Stackoverflow.com/users/20037042", "pm_score": 1, "selected": false, "text": "calloc stdlib.h stdlib.h .h stdlib.h calloc extern void *calloc(size_t nmemb, size_t size);\n calloc libc .c libc main calloc calloc calloc #include <stdio.h>\n\nvoid printInt(int a, int b){\n printf(\"ints %d %d\\n\", a, b);\n}\n\nvoid printFloat(float a, float b){\n printf(\"floats %f %f\\n\", a, b);\n}\n\nvoid printDouble(double a, double b){\n printf(\"doubles %f %f\\n\", a, b);\n}\n #include <stdio.h>\nint main(void) {\n printInt(1,2);\n printInt(1.0, 2.0);\n\n printFloat(1,2);\n printFloat(1.0,2.0);\n\n printDouble(1,2);\n printDouble(1.0,2.0);\n}\n gcc -std=gnu99 -o main one.c two.c # There is an implicit -lc here including libc, that contains printf\n ints 1 2\nints 1034078176 -2098396512\nfloats 0.000000 0.000000\nfloats 0.000000 0.000000\ndoubles 0.000000 0.000000\ndoubles 1.000000 2.000000\n printInt printDouble 1.0 printInt 1 printDouble printFloat two.c extern void printInt(int, int);\nextern void printFloat(float, float);\nextern void printDouble(double, double);\n one.h #include \"one.h\" two.c ints 1 2\nints 1 2\nfloats 1.000000 2.000000\nfloats 1.000000 2.000000\ndoubles 1.000000 2.000000\ndoubles 1.000000 2.000000\n #include .o -lsomelib #include" }, { "answer_id": 74612785, "author": "Luis Colorado", "author_id": 3899431, "author_profile": "https://Stackoverflow.com/users/3899431", "pm_score": 0, "selected": false, "text": "int int calloc void * main(argc, argv)\nchar **argv;\n{\n int i;\n char *sep = \"\";\n for (i = 0; i < argc; i++) {\n printf(\"%s[%s]\", sep, *argv++);\n sep = \", \";\n }\n puts(\"\");\n}\n argv stdout $ make pru$$\nMake: Don't know how to make pru31. Stop.\n[tty2]lcu@pdp-11 $ cc -o pru$$ pru$$.c\n[tty2]lcu@pdp-11 $ pru$$ a b c d e f\n[pru31], [a], [b], [c], [d], [e], [f]\n[tty2]lcu@pdp-11 $ \n\nThis is pdp11/45 UNIX(tm) V7\n(C) 1978 AT&T Bell Laboratories. All rights reserved.\n\nRestricted rights: Use, duplication, or disclosure\nis subject to restrictions stated in your contract with\nWestern Electric Company, Inc.\n\nlogin: \n #include <stdlib.h> #include <stdio.h> calloc() int int" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17481360/" ]
74,582,638
<p>I am using fetch() to call a url as follow:</p> <pre><code> const context = useContext(AuthContext); const navigate = useNavigate(); const handleSubmit = (event) =&gt; { event.preventDefault(); const data = new FormData(event.currentTarget); // console.log({ // email: data.get(&quot;email&quot;), // password: data.get(&quot;password&quot;), // }); if (data) { //TODO: Trigger a mutation or update fetch(&quot;http://localhost:4000/api/user/login&quot;, { method: &quot;POST&quot;, crossDomain: true, headers: { &quot;Content-Type&quot;: &quot;application/json&quot;, &quot;Accept&quot;: &quot;application/json&quot;, &quot;Access-Control-Allow-Origin&quot;: &quot;http://localhost:4000&quot;, }, body: JSON.stringify({ email: data.get(&quot;email&quot;), password: data.get(&quot;password&quot;), }), }) .then((res) =&gt; res.json()) .then((result) =&gt; { console.log(result); if (result.token) { context.login(result); navigate(&quot;/Home&quot;); } }) .catch((e) =&gt; console.log(e)); } else { console.log(&quot;Login failed.&quot;); } }; </code></pre> <p>{handleSubmit} is then triggered upon clicking on submit button on the page.</p> <p>The login controller:</p> <pre><code>const login = async (req, res, next) =&gt; { function generateToken(user) { return jwt.sign( { id: user.id, email: user.email, username: user.username, }, SECRET_KEY, { expiresIn: &quot;1h&quot; } ); } const user = await User.findOne({ email }); if (!user) { console.log(&quot;User not found.&quot;); } const match = bcrypt.compare(password, user.password); if (!match) { console.log(&quot;Wrong password.&quot;); } const token = generateToken(user); return { token }; }; </code></pre> <p>Right now the error thrown is &quot;User not found&quot;. I don't understand why is there no user found as the user with the entered email address exists in my mongodb atlas.</p> <p>Please provide some guidance. Cheers.</p>
[ { "answer_id": 74582726, "author": "Kompetenzbolzen", "author_id": 10986134, "author_profile": "https://Stackoverflow.com/users/10986134", "pm_score": 1, "selected": false, "text": "stdlib.h libc.so // a.c\nint asdf(int b){\n return b+1;\n}\n\n// main.c\nint main(void) {\n asdf();\n return 0;\n}\n gcc main.c a.c" }, { "answer_id": 74582884, "author": "chqrlie", "author_id": 4593267, "author_profile": "https://Stackoverflow.com/users/4593267", "pm_score": 3, "selected": true, "text": "<stdlib.h> <stdlib.h> calloc void *calloc(size_t, size_t); int calloc(int, size_t) calloc calloc int int * arr int * int arr free(arr) calloc gcc -Wall -Wextra -Werror <stdlib.h> gcc #include <stdio.h>\n#include <stdlib.h>\n\nint main() {\n int *arr = calloc(1, sizeof(*arr)); /* use object type for consistency */\n\n printf(\"pointer value is %p\\n\", (void *)arr);\n\n free(arr);\n return 0;\n}\n" }, { "answer_id": 74582912, "author": "chrslg", "author_id": 20037042, "author_profile": "https://Stackoverflow.com/users/20037042", "pm_score": 1, "selected": false, "text": "calloc stdlib.h stdlib.h .h stdlib.h calloc extern void *calloc(size_t nmemb, size_t size);\n calloc libc .c libc main calloc calloc calloc #include <stdio.h>\n\nvoid printInt(int a, int b){\n printf(\"ints %d %d\\n\", a, b);\n}\n\nvoid printFloat(float a, float b){\n printf(\"floats %f %f\\n\", a, b);\n}\n\nvoid printDouble(double a, double b){\n printf(\"doubles %f %f\\n\", a, b);\n}\n #include <stdio.h>\nint main(void) {\n printInt(1,2);\n printInt(1.0, 2.0);\n\n printFloat(1,2);\n printFloat(1.0,2.0);\n\n printDouble(1,2);\n printDouble(1.0,2.0);\n}\n gcc -std=gnu99 -o main one.c two.c # There is an implicit -lc here including libc, that contains printf\n ints 1 2\nints 1034078176 -2098396512\nfloats 0.000000 0.000000\nfloats 0.000000 0.000000\ndoubles 0.000000 0.000000\ndoubles 1.000000 2.000000\n printInt printDouble 1.0 printInt 1 printDouble printFloat two.c extern void printInt(int, int);\nextern void printFloat(float, float);\nextern void printDouble(double, double);\n one.h #include \"one.h\" two.c ints 1 2\nints 1 2\nfloats 1.000000 2.000000\nfloats 1.000000 2.000000\ndoubles 1.000000 2.000000\ndoubles 1.000000 2.000000\n #include .o -lsomelib #include" }, { "answer_id": 74612785, "author": "Luis Colorado", "author_id": 3899431, "author_profile": "https://Stackoverflow.com/users/3899431", "pm_score": 0, "selected": false, "text": "int int calloc void * main(argc, argv)\nchar **argv;\n{\n int i;\n char *sep = \"\";\n for (i = 0; i < argc; i++) {\n printf(\"%s[%s]\", sep, *argv++);\n sep = \", \";\n }\n puts(\"\");\n}\n argv stdout $ make pru$$\nMake: Don't know how to make pru31. Stop.\n[tty2]lcu@pdp-11 $ cc -o pru$$ pru$$.c\n[tty2]lcu@pdp-11 $ pru$$ a b c d e f\n[pru31], [a], [b], [c], [d], [e], [f]\n[tty2]lcu@pdp-11 $ \n\nThis is pdp11/45 UNIX(tm) V7\n(C) 1978 AT&T Bell Laboratories. All rights reserved.\n\nRestricted rights: Use, duplication, or disclosure\nis subject to restrictions stated in your contract with\nWestern Electric Company, Inc.\n\nlogin: \n #include <stdlib.h> #include <stdio.h> calloc() int int" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17559906/" ]
74,582,640
<p>I am using a script to go up and down a level (different tabs) based on the score of the tab you are on. So the script sets the active sheet to the correct sheet, then runs hideAllTabs script which sometimes works and other times will throw the error</p> <blockquote> <p>Exception: You can't hide all the sheets in a document'</p> </blockquote> <p>The script is run when the user clicks a 'Check Answer' button. If they get 4 or more answers correct, they move to the next level, if less than 4 they move back a level.</p> <p>This is what I have so far. And it works sometimes, but sometimes throw the error. Is it a question of clearing the cache? Maybe the order that I have?</p> <pre><code>const UI = SpreadsheetApp.getUi() const ss = SpreadsheetApp.getActiveSpreadsheet() function checkAnswers() { const sheet = ss.getActiveSheet() var score = sheet.getRange('G1').getValue() const nextTest = sheet.getRange('H1').getValue() var nextSheet = ss.getSheetByName(nextTest); //console.log(score) if (score &gt;= '4') { //Browser.msgBox('Go to the next level', Browser.Buttons.OK); ss.setActiveSheet(nextSheet) //Utilities.sleep(500) showAllSheets() hideAllSheets() } /* else if (score &lt;= 3) //Browser.msgBox('Go back a level', Browser.Buttons.OK); ss.setActiveSheet(nextSheet) //showAllSheets() hideAllSheets() */ } function hideAllSheets() { const ss = SpreadsheetApp.getActiveSpreadsheet(); const currentSheetId = ss.getActiveSheet().getSheetId(); const sheets = ss.getSheets(); sheets.filter(s =&gt; s.getSheetId() != currentSheetId) .forEach(s =&gt; s.hideSheet()); } function showAllSheets() { const ss = SpreadsheetApp.getActiveSpreadsheet(); const currentSheetId = ss.getActiveSheet().getSheetId(); const sheets = ss.getSheets(); sheets.filter(s =&gt; s.getSheetId() != currentSheetId) .forEach(s =&gt; s.showSheet()); } function startAssessments() { ss.setActiveSheet(ss.getSheetByName('level1'), true); Utilities.sleep(500) hideAllSheets() } </code></pre> <p>This is the new code that is now working as expected:</p> <pre><code>const UI = SpreadsheetApp.getUi(); const ss = SpreadsheetApp.getActiveSpreadsheet(); function onOpen(){ UI.createMenu(&quot;Utilities&quot;) .addItem(&quot;Show&quot;,&quot;showAllSheets&quot;) .addItem(&quot;Hide&quot;,&quot;hideAllSheets&quot;) .addItem(&quot;Start Over&quot;,&quot;startOver&quot;) .addToUi() } function startAssessments() { ss.setActiveSheet(ss.getSheetByName('level1'), true); } function startOver() { ss.setActiveSheet(ss.getSheetByName('Start'), true); SpreadsheetApp.flush(); hideAllSheets(); } function checkAnswers() { const sheet = ss.getActiveSheet(); var score = sheet.getRange('G1').getValue(); const nextTest = sheet.getRange('H1').getValue(); var nextSheet = ss.getSheetByName(nextTest); if (score &gt;= '4') { Browser.msgBox('Go to the next level', Browser.Buttons.OK); ss.setActiveSheet(nextSheet); SpreadsheetApp.flush(); hideAllSheets(); } else if (score == 3) { Browser.msgBox('Go back a level', Browser.Buttons.OK); ss.setActiveSheet(nextSheet); SpreadsheetApp.flush(); hideAllSheets(); } else { Browser.msgBox('thanks for trying', Browser.Buttons.OK); ss.setActiveSheet(nextSheet); SpreadsheetApp.flush(); hideAllSheets(); } } function hideAllSheets() { const ss = SpreadsheetApp.getActiveSpreadsheet(); const currentSheetName = ss.getActiveSheet().getSheetName(); const sheets = ss.getSheets(); sheets.forEach((sh) =&gt; { if(sh.getSheetName() != currentSheetName) { sh.hideSheet(); } }); } function showAllSheets() { const ss = SpreadsheetApp.getActiveSpreadsheet(); const currentSheetName = ss.getActiveSheet().getSheetName(); const sheets = ss.getSheets(); sheets.filter(s =&gt; s.getSheetName() != currentSheetName) .forEach(s =&gt; s.showSheet()); } </code></pre>
[ { "answer_id": 74582726, "author": "Kompetenzbolzen", "author_id": 10986134, "author_profile": "https://Stackoverflow.com/users/10986134", "pm_score": 1, "selected": false, "text": "stdlib.h libc.so // a.c\nint asdf(int b){\n return b+1;\n}\n\n// main.c\nint main(void) {\n asdf();\n return 0;\n}\n gcc main.c a.c" }, { "answer_id": 74582884, "author": "chqrlie", "author_id": 4593267, "author_profile": "https://Stackoverflow.com/users/4593267", "pm_score": 3, "selected": true, "text": "<stdlib.h> <stdlib.h> calloc void *calloc(size_t, size_t); int calloc(int, size_t) calloc calloc int int * arr int * int arr free(arr) calloc gcc -Wall -Wextra -Werror <stdlib.h> gcc #include <stdio.h>\n#include <stdlib.h>\n\nint main() {\n int *arr = calloc(1, sizeof(*arr)); /* use object type for consistency */\n\n printf(\"pointer value is %p\\n\", (void *)arr);\n\n free(arr);\n return 0;\n}\n" }, { "answer_id": 74582912, "author": "chrslg", "author_id": 20037042, "author_profile": "https://Stackoverflow.com/users/20037042", "pm_score": 1, "selected": false, "text": "calloc stdlib.h stdlib.h .h stdlib.h calloc extern void *calloc(size_t nmemb, size_t size);\n calloc libc .c libc main calloc calloc calloc #include <stdio.h>\n\nvoid printInt(int a, int b){\n printf(\"ints %d %d\\n\", a, b);\n}\n\nvoid printFloat(float a, float b){\n printf(\"floats %f %f\\n\", a, b);\n}\n\nvoid printDouble(double a, double b){\n printf(\"doubles %f %f\\n\", a, b);\n}\n #include <stdio.h>\nint main(void) {\n printInt(1,2);\n printInt(1.0, 2.0);\n\n printFloat(1,2);\n printFloat(1.0,2.0);\n\n printDouble(1,2);\n printDouble(1.0,2.0);\n}\n gcc -std=gnu99 -o main one.c two.c # There is an implicit -lc here including libc, that contains printf\n ints 1 2\nints 1034078176 -2098396512\nfloats 0.000000 0.000000\nfloats 0.000000 0.000000\ndoubles 0.000000 0.000000\ndoubles 1.000000 2.000000\n printInt printDouble 1.0 printInt 1 printDouble printFloat two.c extern void printInt(int, int);\nextern void printFloat(float, float);\nextern void printDouble(double, double);\n one.h #include \"one.h\" two.c ints 1 2\nints 1 2\nfloats 1.000000 2.000000\nfloats 1.000000 2.000000\ndoubles 1.000000 2.000000\ndoubles 1.000000 2.000000\n #include .o -lsomelib #include" }, { "answer_id": 74612785, "author": "Luis Colorado", "author_id": 3899431, "author_profile": "https://Stackoverflow.com/users/3899431", "pm_score": 0, "selected": false, "text": "int int calloc void * main(argc, argv)\nchar **argv;\n{\n int i;\n char *sep = \"\";\n for (i = 0; i < argc; i++) {\n printf(\"%s[%s]\", sep, *argv++);\n sep = \", \";\n }\n puts(\"\");\n}\n argv stdout $ make pru$$\nMake: Don't know how to make pru31. Stop.\n[tty2]lcu@pdp-11 $ cc -o pru$$ pru$$.c\n[tty2]lcu@pdp-11 $ pru$$ a b c d e f\n[pru31], [a], [b], [c], [d], [e], [f]\n[tty2]lcu@pdp-11 $ \n\nThis is pdp11/45 UNIX(tm) V7\n(C) 1978 AT&T Bell Laboratories. All rights reserved.\n\nRestricted rights: Use, duplication, or disclosure\nis subject to restrictions stated in your contract with\nWestern Electric Company, Inc.\n\nlogin: \n #include <stdlib.h> #include <stdio.h> calloc() int int" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16202242/" ]
74,582,658
<p>How to filter the row which contains all vowels in the column value. for example, the table letters contains list of column value.</p> <pre><code>str ---- apple orange education </code></pre> <p>I tried the sql with like command.</p> <pre><code>select str from letters where str like '%a%' and str like '%e%' and str like '%i%' and str like '%o%' and str like '%u%' </code></pre> <p>Would like to know is there any better way to handle this? Expected output is : education</p>
[ { "answer_id": 74582966, "author": "a_horse_with_no_name", "author_id": 330315, "author_profile": "https://Stackoverflow.com/users/330315", "pm_score": 2, "selected": false, "text": "ilike all() select str \nfrom letters \nwhere str ilike all (array['%a%', '%e%' , '%i%', '%o%', '%u%'])\n" }, { "answer_id": 74583016, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 2, "selected": true, "text": "@> ARRAY['a','e','i','o','u'] regexp_split_to_array(str, '\\s*') SELECT * FROm table1\n WHERE \n regexp_split_to_array(str, '\\s*') @> ARRAY['a','e','i','o','u'] \n\n SELECT 1\n SELECT * FROm table1\n WHERE\nstring_to_array(str, null) @> ARRAY['a','e','i','o','u'] \n SELECT 1\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8726488/" ]
74,582,679
<p>I am having difficulties reducing the size of my css button. The margins are long, I keep trying to reduce it but it is not working</p>
[ { "answer_id": 74582966, "author": "a_horse_with_no_name", "author_id": 330315, "author_profile": "https://Stackoverflow.com/users/330315", "pm_score": 2, "selected": false, "text": "ilike all() select str \nfrom letters \nwhere str ilike all (array['%a%', '%e%' , '%i%', '%o%', '%u%'])\n" }, { "answer_id": 74583016, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 2, "selected": true, "text": "@> ARRAY['a','e','i','o','u'] regexp_split_to_array(str, '\\s*') SELECT * FROm table1\n WHERE \n regexp_split_to_array(str, '\\s*') @> ARRAY['a','e','i','o','u'] \n\n SELECT 1\n SELECT * FROm table1\n WHERE\nstring_to_array(str, null) @> ARRAY['a','e','i','o','u'] \n SELECT 1\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20607085/" ]
74,582,699
<p>I'm adding rewrite rules to my PHP script which is included in a WordPress page with the permalink <strong>kb</strong></p> <p>So I can visit domain.com/kb and the page is displayed.</p> <pre><code>function wdm_add_rewrite_rules() { add_rewrite_rule( '^kb/([^/]+)/?$', 'kb?kb_cat=$matches[1]&amp;kb_seq=1', 'top'); } add_action('init', 'wdm_add_rewrite_rules'); </code></pre> <p>But when I visit the page with additional strings in the url, I get a 404.</p> <p>So when I visit domain.com/kb is shows the correct page, and then visiting domain.com/kb/84/92, it shows a 404</p> <p>I just need to be able to read the additional url params in my PHP script, such as <code>$_GET[&quot;kb_cat&quot;]</code></p>
[ { "answer_id": 74583329, "author": "Roby Raju Oommen", "author_id": 14399782, "author_profile": "https://Stackoverflow.com/users/14399782", "pm_score": 0, "selected": false, "text": "function wdm_add_rewrite_rules() {\n add_rewrite_rule( '^kb\\/([^\\/]+)\\/?([^\\/]+)$', 'kb?kb_cat=$matches[1]&kb_seq=1', 'top');\n}\nadd_action('init', 'wdm_add_rewrite_rules');\n" }, { "answer_id": 74630994, "author": "Moishy", "author_id": 1810810, "author_profile": "https://Stackoverflow.com/users/1810810", "pm_score": 1, "selected": false, "text": "function wdm_add_rewrite_rules() {\n add_rewrite_rule( '^kb$', 'index.php?kb_cat=$matches[1]&kb_seq=1', 'top');\n}\nadd_action('init', 'wdm_add_rewrite_rules');\n function add_query_vars_filter( $vars ){\n $vars[] = \"kb_cat\";\n $vars[] = \"kb_seq\";\n return $vars;\n}\nadd_filter( 'query_vars', 'add_query_vars_filter' );\n function include_custom_template($template){\n\n if(get_query_var('kb_cat') && get_query_var('kb_seq')){\n $template = get_template_directory() .\"/my-custom-template.php\";\n } \n \n return $template; \n}\n\nadd_filter('template_include', 'include_custom_template');\n functions.php" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4838253/" ]