qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
sequence
74,675,768
<p>Is it possible to target phones (iPhone 14 Pro and iPhone 14 Pro Max) with dynamic islands with React Native?</p>
[ { "answer_id": 74675974, "author": "Kevin Amiranoff", "author_id": 2829540, "author_profile": "https://Stackoverflow.com/users/2829540", "pm_score": 0, "selected": false, "text": " const iPhonesWithDynamicIsland = ['iPhone15,2', 'iPhone15,3']; // iPhone 14 Pro, iPhone 14 Pro Max\n const isIphoneWithDynamicIsland = iPhonesWithDynamicIsland.includes(DeviceInfo.getDeviceId());\n console.log(isIphoneWithDynamicIsland);\n DeviceInfo.hasDynamicIsland()\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2829540/" ]
74,675,785
<p>I have an <code>AoC</code> problem where I have been given the data below:</p> <pre><code>data = &quot;&quot;&quot;2-4,6-8 2-3,4-5 5-7,7-9 2-8,3-7 6-6,4-6 2-6,4-8&quot;&quot;&quot; </code></pre> <p>I need to find the number of pairs which fully contain another pair. For example, <code>2-8</code> fully contains <code>3-7</code>, and <code>6-6</code> is fully contained by <code>4-6</code>.</p> <p>I have solved it using the below code:</p> <pre><code> def aoc_part1(self, data): counter = 0 for lines_data in data.splitlines(): lines_data = lines_data.strip() first_range, second_range = self.__get_first_second_list_of_elements(lines_data) check_first_side_if_returns_true = all(item in first_range for item in second_range) check_second_side_if_returns_true = all(item in second_range for item in first_range) if check_first_side_if_returns_true or check_second_side_if_returns_true: counter += 1 return counter def __get_first_second_list_of_elements(self, data): first_elf, second_elf = data.split(&quot;,&quot;)[0], data.split(&quot;,&quot;)[1] first_range_start, first_range_end = map(int, first_elf.split(&quot;-&quot;)) second_range_start, second_range_end = map(int, second_elf.split(&quot;-&quot;)) first_range = list(range(first_range_start, first_range_end + 1)) second_range = list(range(second_range_start, second_range_end + 1)) return first_range, second_range </code></pre> <p>I was just wondering about the time complexity here. I think it should be a <code>brute force</code> here because for every iteration <code>all</code> will run another loop. How can I optimize this solution in order to get linear time complexity?</p> <p><code>first_range</code> and <code>second_range</code> are of <code>int</code> types. <code>check_first_side_if_returns_true</code> and <code>check_second_side_if_returns_true</code> are the <code>boolean</code> variables that check if the list is entirely contained or not. Based on that, it returns <code>True</code> or <code>False</code>.</p>
[ { "answer_id": 74679874, "author": "Daniel Hao", "author_id": 10760768, "author_profile": "https://Stackoverflow.com/users/10760768", "pm_score": 0, "selected": false, "text": " # some input reading, and split to a, b sets.\n # count = 0\n\n if set(range(a, b + 1)) & set(range(x, y + 1)):\n count += 1 # that's part1 answer.\n\n # part 2\nfor line in open('04.in'):\n a, b, x, y = map(int, line.replace(\",\", \"-\").split(\"-\"))\n if set(range(a, b + 1)) & set(range(x, y + 1)):\n ans += 1\n Filename: day04.py\n\nLine # Mem usage Increment Occurrences Line Contents\n=============================================================\n 27 43.758 MiB 43.758 MiB 1 @profile\n 28 def part2(file):\n 29 43.762 MiB 0.004 MiB 1 ans = 0\n 30\n 31 43.770 MiB 0.000 MiB 1001 for line in open(file):\n 32 43.770 MiB 0.004 MiB 1000 a, b, x, y = map(int, line.replace(\",\", \"-\").split(\"-\"))\n 33 43.770 MiB 0.000 MiB 1000 if set(range(a, b + 1)) & set(range(x, y + 1)):\n 34 43.770 MiB 0.004 MiB 847 ans += 1\n 35\n 36 43.770 MiB 0.000 MiB 1 return ans\n" }, { "answer_id": 74679938, "author": "Timus", "author_id": 14311263, "author_profile": "https://Stackoverflow.com/users/14311263", "pm_score": 1, "selected": false, "text": "data = \"\"\"2-4,6-8\n2-3,4-5\n5-7,7-9\n2-8,3-7\n6-6,4-6\n2-6,4-8\n\"\"\"\n\ndef included(line):\n (a1, b1), (a2, b2) = (map(int, pair.split(\"-\")) for pair in line.strip().split(\",\"))\n return (a1 <= a2 and b2 <= b1) or (a2 <= a1 and b1 <= b2)\n\nprint(sum(included(line) for line in data.splitlines()))\n from timeit import timeit\n\n# Extract the interval boundaries for the pairs\nboundaries = [\n [tuple(map(int, pair.split(\"-\"))) for pair in line.strip().split(\",\")]\n for line in data.splitlines()\n]\n\n# Version 1 with simple comparison of boundaries\ndef test1(boundaries):\n def included(pairs):\n (a1, b1), (a2, b2) = pairs\n return (a1 <= a2 and b2 <= b1) or (a2 <= a1 and b1 <= b2)\n \n return sum(included(pairs) for pairs in boundaries)\n\n# Version 2 with range-subset test\ndef test2(boundaries):\n def included(pairs):\n (a1, b1), (a2, b2) = pairs\n numbers1, numbers2 = set(range(a1, b1 + 1)), set(range(a2, b2 + 1))\n return numbers1 <= numbers2 or numbers2 <= numbers1\n \n return sum(included(pairs) for pairs in boundaries)\n\n# Test for identical result\nprint(test1(boundaries) == test2(boundaries))\n\n# Timing\nfor i in 1, 2:\n t = timeit(f\"test{i}(boundaries)\", globals=globals(), number=1_000)\n print(f\"Duration version {i}: {t:.1f} seconds\")\n Duration version 1: 0.4 seconds\nDuration version 2: 5.4 seconds\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9363181/" ]
74,675,792
<p>I have a string similar to (the below one is simplified):</p> <pre><code>&quot; word= {his or her} whatever &quot; </code></pre> <p>I want to delete every whitespace except between {}, so that my modified string will be:</p> <pre><code>&quot;word={his or her}whatever&quot; </code></pre> <p>lstrip or rstrip doesn't work of course. If I delete all whitespaces the whitespaces between {} are deleted as well. I tried to look up solutions for limiting the replace function to certain areas but even if I found out it I haven't been able to implement it. There are some stuff with regex (I am not sure if they are relevant here) but I haven't been able to understand them.</p> <p>EDIT: If I wanted to except the area between, say {} and &quot;&quot;, that is:</p> <p>if I wanted to turn this string:</p> <pre><code>&quot; word= {his or her} and &quot;his or her&quot; whatever &quot; </code></pre> <p>into this:</p> <pre><code>&quot;word={his or her}and&quot;his or her&quot;whatever&quot; </code></pre> <p>What would I change</p> <p><code>re.sub(r'\s+(?![^{]*})', '', list_name)</code> into?</p>
[ { "answer_id": 74675851, "author": "Mihir B", "author_id": 6462302, "author_profile": "https://Stackoverflow.com/users/6462302", "pm_score": -1, "selected": false, "text": "def remove(string):\n return string.replace(\" \", \"\")\n\nstring = 'hell o whatever'\nprint(remove(string)) // Output: hellowhatever\n" }, { "answer_id": 74675860, "author": "Jiao Dian", "author_id": 8883383, "author_profile": "https://Stackoverflow.com/users/8883383", "pm_score": 1, "selected": false, "text": "re.sub re.sub import re\n\n# Define the input string\ninput_str = \" word= {his or her} whatever \"\n\n# Use a regular expression to search for whitespace characters outside of the curly braces\noutput_str = re.sub(r'\\s+(?![^{]*})', '', input_str)\n\n# Print the result\nprint(output_str)\n word={his or her}whatever\n" }, { "answer_id": 74677409, "author": "Bhargav", "author_id": 15358800, "author_profile": "https://Stackoverflow.com/users/15358800", "pm_score": 1, "selected": false, "text": "re string.replace regex st =\" word= {his or her} whatever \"\nst2=\"\"\" word= {his or her} and \"his or her\" whatever \"\"\"\n\nnew = \" \".join(st2.split())\nnew = new.replace(\"= \", \"=\").replace(\"} \", \"}\").replace('\" ' , '\"').replace(' \"' , '\"')\nprint(new)\n word={his or her}whatever\n word={his or her}and\"his or her\"whatever\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17788139/" ]
74,675,862
<p>I have a navigation bar and I added a red line on the bottom when hovering any item of the list, but I want to move that red line under the header (something like &quot;Services&quot;), any idea how to achieve this?</p> <p>I added an small sample in codepen so you can easily check the HTML and CSS 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-css lang-css prettyprint-override"><code>header { background-color: lightblue; padding-top: 1rem; position: sticky; top: 0; display: flex; align-items: center; justify-content: space-around; } header nav { min-width: 50%; } header nav ul { margin: 0; height: 100%; list-style: none; padding-left: 0; display: flex; align-items: center; justify-content: space-between; } header li:hover { height: 100%; border-bottom: 2px solid red; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;header&gt; &lt;a href="/"&gt; &lt;p&gt;Whatever logo&lt;/p&gt; &lt;/a&gt; &lt;nav&gt; &lt;ul&gt; &lt;li&gt;About us&lt;/li&gt; &lt;li&gt;Services&lt;/li&gt; &lt;li&gt;Pricing&lt;/li&gt; &lt;li&gt;Blog&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;a href="/"&gt;CONTACT&lt;/a&gt; &lt;/header&gt;</code></pre> </div> </div> </p> <p><a href="https://codepen.io/Sergio18rg/pen/XWYyybY?editors=1100" rel="nofollow noreferrer">Link to check the code</a></p> <p><a href="https://i.stack.imgur.com/r1uQS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/r1uQS.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74677077, "author": "AMRITESH GUPTA", "author_id": 18188846, "author_profile": "https://Stackoverflow.com/users/18188846", "pm_score": 0, "selected": false, "text": "header {\n background-color: lightblue;\n padding-top: 1rem;\n height: 3rem;\n position: sticky;\n top: 0;\n display: flex;\n align-items: center;\n justify-content: space-around;\n}\n\nheader nav {\n min-width: 50%;\n height : 100%;\n}\n\nheader nav ul {\n margin: 0;\n height: 100%;\n list-style: none;\n padding-left: 0;\n display: flex;\n align-items: center;\n justify-content: space-between;\n}\n\nheader li{\n height: inherit;\n}\n\nheader li:hover {\n border-bottom: 2px solid red;\n} <body>\n <header>\n <a href=\"/\"\n ><p>Whatever logo</p></a>\n <nav>\n <ul>\n <li>About us</li>\n <li>Services</li>\n <li>Pricing</li>\n <li>Blog</li>\n </ul>\n </nav>\n <a href=\"/\">CONTACT</a>\n </header>\n </body>" }, { "answer_id": 74677148, "author": "Kalpit Agarwal", "author_id": 20619628, "author_profile": "https://Stackoverflow.com/users/20619628", "pm_score": 0, "selected": false, "text": "header {\n background-color: lightblue;\n padding-top: 1rem;\n height: 3rem;\n position: sticky;\n top: 0;\n display: flex;\n align-items: center;\n justify-content: space-around;\n}\n\nheader nav {\n min-width: 50%;\n height : 100%;\n}\n\nheader nav ul {\n margin: 0;\n height: 100%;\n list-style: none;\n padding-left: 0;\n display: flex;\n align-items: center;\n justify-content: space-between;\n}\n\nheader li{\n height: inherit;\n}\n\nheader li:hover {\n border-bottom: 2px solid red;\n}" }, { "answer_id": 74677242, "author": "Swaraj Gandhi", "author_id": 2125838, "author_profile": "https://Stackoverflow.com/users/2125838", "pm_score": 2, "selected": true, "text": "header {\n background-color: lightblue;\n position: sticky;\n display: flex;\n height: 60px;\n align-items: center;\n justify-content: space-around;\n}\n\nheader nav {\n min-width: 50%;\n}\n\nheader nav ul {\n margin: 0;\n height: 100%;\n list-style: none;\n padding-left: 0;\n display: flex;\n align-items: center;\n justify-content: space-between;\n height: 60px;\n}\n\nheader li {\n display: flex;\n align-items: center;\n border-bottom: 2px solid transparent;\n height: 60px;\n}\n\nheader li:hover {\n border-bottom: 2px solid red;\n}\n\n" }, { "answer_id": 74677865, "author": "David Thomas", "author_id": 82548, "author_profile": "https://Stackoverflow.com/users/82548", "pm_score": 0, "selected": false, "text": "/* removing default padding and margin from all\n elements, and forcing the browser to use the\n same sizing algorithm - border-box - to calculate\n element sizes, including the padding and border\n widths in the declared size: */\n*, ::before, ::after {\n box-sizing: border-box;\n padding: 0;\n margin: 0;\n}\n\n/* setting common properties for the two element\n groups: */\nheader,\nheader nav ul {\n /* using display: flex layout: */\n display: flex;\n /* forcing the flex-items within the flex parent\n to take the full height of that parent: */\n align-items: stretch;\n}\n\nheader {\n background-color: lightblue;\n block-size: 3em;\n position: sticky;\n justify-content: space-around;\n}\n\n/* using :is() to combine the two selectors\n header a,\n header li\n into one selector: */\nheader :is(a, li) {\n /* using grid layout: */\n display: grid;\n /* positioning the - including text - content\n at the center of the element: */\n place-items: center;\n}\n\nheader nav {\n min-width: 50%;\n}\n\nheader nav ul {\n /* the <ul> isn't a flex-item so we have to specify\n that we want it to take all available space on \n the block-axis (equivalent to 'height' in left-to-right\n languages such as English): */\n block-size: 100%;\n list-style: none;\n justify-content: space-between;\n}\n\nheader li {\n /* to prevent the jumping content: */\n border-bottom: 2px solid transparent;\n}\n\nheader li:hover {\n /* to style the color of the bottom border: */\n border-bottom-color: red;\n} <header>\n <a href=\"/\">\n <p>Whatever logo</p>\n </a>\n <nav>\n <ul>\n <li>About us</li>\n <li>Services</li>\n <li>Pricing</li>\n <li>Blog</li>\n </ul>\n </nav>\n <a href=\"/\">CONTACT</a>\n</header> align-items display justify-content place-items" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15416320/" ]
74,675,871
<p>I have object like this. I getting this object on backend with query and then transform with qs string library.</p> <pre><code>{ color: 'red,white', size: 'xl', manufacturer: 'adidas,nike' } </code></pre> <p>I would like have array of object, what i need for prisma map filtering</p> <pre><code> const filterList = [ {filter: &quot;color&quot;, value: &quot;red&quot;}, {filter: &quot;color&quot;, value: &quot;white&quot;}, {filter: &quot;size&quot;, value: &quot;xl&quot;}, {filter: &quot;manufacturer&quot;, value: &quot;adidas&quot;}, {filter: &quot;manufacturer&quot;, value: &quot;nike&quot;}, ]; </code></pre> <p>How can i this handle ? Thanks for a reply</p>
[ { "answer_id": 74675922, "author": "Felix G", "author_id": 7845355, "author_profile": "https://Stackoverflow.com/users/7845355", "pm_score": 2, "selected": true, "text": "Object.entries() Array.map() const obj = { \n color: 'red,white',\n size: 'xl', \n manufacturer: 'adidas,nike' \n};\n\nconst filterList = Object.entries(obj).map(([filter, value]) => {\n return value.split(\",\").map(v => ({ filter, value: v }));\n}).flat();\n\nconsole.log(filterList); [\n {filter: \"color\", value: \"red\"},\n {filter: \"color\", value: \"white\"}, \n {filter: \"size\", value: \"xl\"},\n {filter: \"manufacturer\", value: \"adidas\"},\n {filter: \"manufacturer\", value: \"nike\"},\n]\n" }, { "answer_id": 74675947, "author": "Cloudio", "author_id": 8198631, "author_profile": "https://Stackoverflow.com/users/8198631", "pm_score": -1, "selected": false, "text": "function transform(filters) {\n return Object.entries(filters).reduce((acc, [filter, commaSeparatedValues]) => {\n commaSeparatedValues.split(\",\").forEach(value => {\n acc.push({\n filter,\n value\n })\n });\n return acc;\n }, [])\n}\n\nconst sample = {\n color: \"red,white\",\n size: \"xl\",\n manufacturer: \"adidas,nike\",\n};\n\nconst transformed = transform(sample);\nconsole.log(transformed);" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18389635/" ]
74,675,876
<p>I am looking at this code challenge:</p> <blockquote> <p>Complete the function isAllX to determine if the entire string is made of lower-case x or upper-case X. Return true if they are, false if not.</p> <p>Examples:</p> <pre><code>isAllX(&quot;Xx&quot;); // true isAllX(&quot;xAbX&quot;); // false </code></pre> </blockquote> <p>Below is my answer, but it is wrong. I want &quot;false&quot; for the complete string if any of the character is not &quot;x&quot; or &quot;X&quot;:</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>function isAllX(string) { for (let i = 0; i &lt; string.length; i++) { if (string[i] === "x" || string[i] === "X") { console.log(true); } else if (string[i] !== "x" || string[i] !== "X") { console.log(false); } } } isAllX("xAbX");</code></pre> </div> </div> </p>
[ { "answer_id": 74675918, "author": "trincot", "author_id": 5459839, "author_profile": "https://Stackoverflow.com/users/5459839", "pm_score": 2, "selected": false, "text": "length function isAllX(string) {\n return string.toLowerCase().replaceAll(\"x\", \"\").length == 0;\n}\n\n\nconsole.log(isAllX(\"xxXXxxAxx\")); // false\nconsole.log(isAllX(\"xxXXxxXxx\")); // true test function isAllX(string) {\n return /^x*$/i.test(string);\n}\n\n\nconsole.log(isAllX(\"xxXXxxAxx\")); // false\nconsole.log(isAllX(\"xxXXxxXxx\")); // true" }, { "answer_id": 74675948, "author": "Rishabh Deep Singh", "author_id": 8077496, "author_profile": "https://Stackoverflow.com/users/8077496", "pm_score": 0, "selected": false, "text": "function allX(testString) {\n return /^x+$/i.test(testString);\n}\n\nconsole.log(allX(\"xxXX\"));\nconsole.log(allX(\"xxAAAXX\"));" }, { "answer_id": 74677325, "author": "Sanchit Bajaj", "author_id": 17444026, "author_profile": "https://Stackoverflow.com/users/17444026", "pm_score": 0, "selected": false, "text": "\nfunction isAllX(str) {\n let isX = true;\n let newString = str.toLowerCase();\n\n for (let i = 0; i < newString.length; i++) {\n if (newString[i] !== \"x\") {\n isX = false;\n }\n }\n return isX;\n}\nconsole.log(isAllX(\"xAbX\"));\nconsole.log(isAllX(\"XXXxxxXXXxxx\"));\n\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11571204/" ]
74,675,883
<p>im having trouble with the js in this code. I have 2 clickble dropdowns, but only one of them (the first dropdown) is working. I dont know how to fix it. here's the html part:</p> <pre><code>&lt;div id=&quot;wrap&quot;&gt; &lt;nav&gt; &lt;div class=&quot;logo&quot;&gt; &lt;img src=&quot;./photos-docs/ME-marine-logo.png&quot; alt=&quot;logo&quot; class=&quot;logo&quot; /&gt; &lt;/div&gt; &lt;button type=&quot;button&quot; class=&quot;btn-hamburger&quot; data-action=&quot;nav-toggle&quot;&gt; &lt;span&gt;&lt;/span&gt; &lt;span&gt;&lt;/span&gt; &lt;span&gt;&lt;/span&gt; &lt;span&gt;&lt;/span&gt; &lt;span&gt;&lt;/span&gt; &lt;/button&gt; &lt;ul class=&quot;nav-menu&quot;&gt; &lt;li class=&quot;nav-item&quot;&gt;&lt;a href=&quot;index.html&quot;&gt;עמוד ראשי&lt;/a&gt;&lt;/li&gt; &lt;li class=&quot;nav-item dropdown&quot;&gt; &lt;a href=&quot;#&quot; data-action=&quot;dropdown-toggle&quot;&gt;עיסויים &lt;/a&gt; &lt;div class=&quot;dropdown-menu&quot;&gt; &lt;a class=&quot;dropdown-item&quot; href=&quot;#&quot;&gt;רפואי&lt;/a&gt; &lt;a class=&quot;dropdown-item&quot; href=&quot;#&quot;&gt;שוודי&lt;/a&gt; &lt;a class=&quot;dropdown-item&quot; href=&quot;#&quot;&gt;רקמות עמוקות&lt;/a&gt; &lt;a class=&quot;dropdown-item&quot; href=&quot;#&quot;&gt;ניקוז לימפטי&lt;/a&gt; &lt;a class=&quot;dropdown-item&quot; href=&quot;#&quot;&gt;אבנים חמות&lt;/a&gt; &lt;/div&gt; &lt;/li&gt; &lt;li class=&quot;nav-item dropdown&quot;&gt; &lt;a href=&quot;#&quot; data-action=&quot;dropdown-toggle&quot;&gt;טיפולי פנים &lt;/a&gt; &lt;div class=&quot;dropdown-menu&quot;&gt; &lt;a class=&quot;dropdown-item&quot; href=&quot;#&quot;&gt;קלאסי&lt;/a&gt; &lt;a class=&quot;dropdown-item&quot; href=&quot;#&quot;&gt;יופי&lt;/a&gt; &lt;a class=&quot;dropdown-item&quot; href=&quot;#&quot;&gt;אקנה&lt;/a&gt; &lt;a class=&quot;dropdown-item&quot; href=&quot;#&quot;&gt;פילינג&lt;/a&gt; &lt;a class=&quot;dropdown-item&quot; href=&quot;#&quot;&gt;מיצוק&lt;/a&gt; &lt;a class=&quot;dropdown-item&quot; href=&quot;#&quot;&gt;פיגמנטציה&lt;/a&gt; &lt;a class=&quot;dropdown-item&quot; href=&quot;#&quot;&gt;אנטי אייג׳ינג&lt;/a&gt; &lt;/div&gt; &lt;/li&gt; &lt;li class=&quot;nav-item&quot;&gt;&lt;a href=&quot;#&quot;&gt;מזותרפיה&lt;/a&gt;&lt;/li&gt; &lt;li class=&quot;nav-item&quot;&gt;&lt;a href=&quot;#&quot;&gt;מיקרובליידינג&lt;/a&gt;&lt;/li&gt; &lt;li class=&quot;nav-item&quot;&gt;&lt;a href=&quot;#&quot;&gt;הזמינו תור&lt;/a&gt;&lt;/li&gt; &lt;li class=&quot;nav-item&quot;&gt;&lt;a href=&quot;#&quot;&gt;צרו קשר&lt;/a&gt;&lt;/li&gt; &lt;li class=&quot;nav-item&quot;&gt;&lt;a href=&quot;tel:+972547809308&quot;&gt;0547809308&lt;/a&gt;&lt;/li&gt; &lt;li class=&quot;nav-item&quot;&gt;&lt;a href=&quot;https://api.whatsapp.com/send?phone=972547809308&quot;&gt;&lt;i class=&quot;fa-brands fa-whatsapp&quot;&gt;&lt;/i&gt;&lt;/a&gt; &lt;/li&gt; </code></pre> <p>and here's the js part:</p> <pre><code>let nav = document.querySelector('nav'); let dropdown = nav.querySelector('.dropdown'); let dropdownToggle = nav.querySelector(&quot;[data-action='dropdown-toggle']&quot;); let navToggle = nav.querySelector(&quot;[data-action='nav-toggle']&quot;); dropdownToggle.addEventListener('click', () =&gt; { if (dropdown.classList.contains('show')) { dropdown.classList.remove('show'); } else { dropdown.classList.add('show'); } }) navToggle.addEventListener('click', () =&gt; { if (nav.classList.contains('opened')) { nav.classList.remove('opened'); } else { nav.classList.add('opened'); } }) </code></pre> <p>what should I do from here? I know the problem ia in the js but I dont know how to keep going from here, im stuck.</p>
[ { "answer_id": 74675918, "author": "trincot", "author_id": 5459839, "author_profile": "https://Stackoverflow.com/users/5459839", "pm_score": 2, "selected": false, "text": "length function isAllX(string) {\n return string.toLowerCase().replaceAll(\"x\", \"\").length == 0;\n}\n\n\nconsole.log(isAllX(\"xxXXxxAxx\")); // false\nconsole.log(isAllX(\"xxXXxxXxx\")); // true test function isAllX(string) {\n return /^x*$/i.test(string);\n}\n\n\nconsole.log(isAllX(\"xxXXxxAxx\")); // false\nconsole.log(isAllX(\"xxXXxxXxx\")); // true" }, { "answer_id": 74675948, "author": "Rishabh Deep Singh", "author_id": 8077496, "author_profile": "https://Stackoverflow.com/users/8077496", "pm_score": 0, "selected": false, "text": "function allX(testString) {\n return /^x+$/i.test(testString);\n}\n\nconsole.log(allX(\"xxXX\"));\nconsole.log(allX(\"xxAAAXX\"));" }, { "answer_id": 74677325, "author": "Sanchit Bajaj", "author_id": 17444026, "author_profile": "https://Stackoverflow.com/users/17444026", "pm_score": 0, "selected": false, "text": "\nfunction isAllX(str) {\n let isX = true;\n let newString = str.toLowerCase();\n\n for (let i = 0; i < newString.length; i++) {\n if (newString[i] !== \"x\") {\n isX = false;\n }\n }\n return isX;\n}\nconsole.log(isAllX(\"xAbX\"));\nconsole.log(isAllX(\"XXXxxxXXXxxx\"));\n\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20529874/" ]
74,675,902
<p>I'm working with a pandas Multiindex that is given by the three keys: <br /> [Verbundzuordnung, ProjektIndex, Datum],</p> <p>I would like to resample the dataframe on Datum hourly, which drops the right colum <code>TagDesAbdichtens</code>, I would like to keep it as it's static.</p> <pre><code> Verbundzuordnung ProjektIndex Datum TagDesAbdichtens 1 81679 2021-11-10 00:00:00+00:00 2021-12-08 2021-11-10 00:00:00+00:00 2021-12-08 2021-11-10 00:00:00+00:00 2021-12-08 2021-11-10 00:00:00+00:00 2021-12-08 2021-11-10 00:00:00+00:00 2021-12-08 ... ... ... ... 2 94574 2022-02-28 23:00:00+00:00 2022-01-31 2022-02-28 23:00:00+00:00 2022-01-31 2022-02-28 23:00:00+00:00 2022-01-31 2022-02-28 23:00:00+00:00 2022-01-31 2022-02-28 23:00:00+00:00 2022-01-31 285192 rows × 1 columns </code></pre> <p>There are aditional columns that I left out here for easier comprehension.</p> <p>I am currently applying this to resample the dataframe</p> <pre><code>all_merged = all_merged.groupby([ pd.Grouper(level='Verbundzuordnung'), pd.Grouper(level='ProjektIndex'), pd.Grouper(level='Datum', freq='H')] ) </code></pre> <p>all_merged.mean() gives me the wanted output with <code>TagDesAbdichtens</code> missing. This value ist for each Verbundzuordnung and ProjektIndex unique and static and I would like to have it back in the resampled version.</p> <p>Is there a way to do it with native pandas functions?</p>
[ { "answer_id": 74675918, "author": "trincot", "author_id": 5459839, "author_profile": "https://Stackoverflow.com/users/5459839", "pm_score": 2, "selected": false, "text": "length function isAllX(string) {\n return string.toLowerCase().replaceAll(\"x\", \"\").length == 0;\n}\n\n\nconsole.log(isAllX(\"xxXXxxAxx\")); // false\nconsole.log(isAllX(\"xxXXxxXxx\")); // true test function isAllX(string) {\n return /^x*$/i.test(string);\n}\n\n\nconsole.log(isAllX(\"xxXXxxAxx\")); // false\nconsole.log(isAllX(\"xxXXxxXxx\")); // true" }, { "answer_id": 74675948, "author": "Rishabh Deep Singh", "author_id": 8077496, "author_profile": "https://Stackoverflow.com/users/8077496", "pm_score": 0, "selected": false, "text": "function allX(testString) {\n return /^x+$/i.test(testString);\n}\n\nconsole.log(allX(\"xxXX\"));\nconsole.log(allX(\"xxAAAXX\"));" }, { "answer_id": 74677325, "author": "Sanchit Bajaj", "author_id": 17444026, "author_profile": "https://Stackoverflow.com/users/17444026", "pm_score": 0, "selected": false, "text": "\nfunction isAllX(str) {\n let isX = true;\n let newString = str.toLowerCase();\n\n for (let i = 0; i < newString.length; i++) {\n if (newString[i] !== \"x\") {\n isX = false;\n }\n }\n return isX;\n}\nconsole.log(isAllX(\"xAbX\"));\nconsole.log(isAllX(\"XXXxxxXXXxxx\"));\n\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17446553/" ]
74,675,913
<p>For example, I have a string like &quot;2 * a + 3 * b&quot;.</p> <p>I already have something that checks if a certain variable exists in the expression. So for example I input b, how could I make it return the 3?</p>
[ { "answer_id": 74675946, "author": "Haim Cohen", "author_id": 3752715, "author_profile": "https://Stackoverflow.com/users/3752715", "pm_score": -1, "selected": false, "text": "# Fit a linear model to the equation\nmodel <- lm(y ~ x)\n\n# Extract the coefficients\ncoef(model)\n" }, { "answer_id": 74675990, "author": "Chris Ruehlemann", "author_id": 8039978, "author_profile": "https://Stackoverflow.com/users/8039978", "pm_score": 1, "selected": false, "text": "d b str_extract library(stringr)\nstr_extract(x, \"\\\\d+(?=b)\")\n[1] \"3\"\n (?=b) b as.numeric(str_extract(x, \"\\\\d+(?=b)\"))\n x <- \"2a+3b\"\n" }, { "answer_id": 74679126, "author": "G. Grothendieck", "author_id": 516548, "author_profile": "https://Stackoverflow.com/users/516548", "pm_score": 1, "selected": false, "text": "# inputs\ns <- \"2 * a + 3 * b\"\nvar <- \"b\"\n\nD(parse(text = s), var)\n## [1] 3\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19312355/" ]
74,675,933
<p>I want to define a variable in a CSS file like this:</p> <pre><code>:root { --sidebar-width: 56; } </code></pre> <p>I'd like to now refer to that in a component to define that component's width:</p> <pre><code>&lt;div className=&quot;w-[var(--sidebar-width)]&quot;&gt; &lt;MySidebar&gt; &lt;/div&gt; </code></pre> <p>This doesn't work. What I'm trying to achieve is to add the <code>w-56</code> class to that component and to do so as a variable so that I can refer to that variable in several places. Is this possible and if so, how do I specify this?</p>
[ { "answer_id": 74675970, "author": "ATP", "author_id": 9977151, "author_profile": "https://Stackoverflow.com/users/9977151", "pm_score": 2, "selected": true, "text": ":root {\n --sidebar-width: 56;\n}\n\n<div className=\"w-[calc(4px*var(--sidebar-width)]\">\n <MySidebar>\n</div>\n 4px" }, { "answer_id": 74677030, "author": "Felix G", "author_id": 7845355, "author_profile": "https://Stackoverflow.com/users/7845355", "pm_score": 0, "selected": false, "text": ":root {\n --sidebar-width: 56px;\n} <script src=\"https://cdn.tailwindcss.com\"></script>\n<div class=\"w-[length:var(--sidebar-width)] bg-red-900\">Test</div>" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/272023/" ]
74,675,941
<p>I have a requirement to display different images based on certain user interactions. So, I'm storing the drawable resource ID in an integer variable. However, when I pass this variable into the Image's painterResource function the image is not rendered.</p> <p>Code looks like this:</p> <pre><code>val img = R.drawable.img1 val img2 = R.drawable.img2 // imageToDisplay is assigned based on certain conditions. var imageToDisplay = img Image(painter = painterResource(imageToDisplay), contentDescription = null) </code></pre>
[ { "answer_id": 74675970, "author": "ATP", "author_id": 9977151, "author_profile": "https://Stackoverflow.com/users/9977151", "pm_score": 2, "selected": true, "text": ":root {\n --sidebar-width: 56;\n}\n\n<div className=\"w-[calc(4px*var(--sidebar-width)]\">\n <MySidebar>\n</div>\n 4px" }, { "answer_id": 74677030, "author": "Felix G", "author_id": 7845355, "author_profile": "https://Stackoverflow.com/users/7845355", "pm_score": 0, "selected": false, "text": ":root {\n --sidebar-width: 56px;\n} <script src=\"https://cdn.tailwindcss.com\"></script>\n<div class=\"w-[length:var(--sidebar-width)] bg-red-900\">Test</div>" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11144845/" ]
74,675,944
<pre><code>library(MASS) # set seed and create data vectors #set.seed(98989) &lt;- for replicating results of betas in 1-2 1-3 sample_size &lt;- 200 sample_meanvector &lt;- c(3, 4) sample_covariance_matrix &lt;- matrix(c(2, 1, 1, 2), ncol = 2) # create bivariate normal distribution sample_distribution &lt;- mvrnorm(n = sample_size, mu = sample_meanvector, Sigma = sample_covariance_matrix) #Convert the datatype df_sample_distribution &lt;- as.data.frame(sample_distribution) </code></pre> <p>Is there a way to put this entire chunk of code in a loop and regenerate it for 500 times? Would be even better if i can store them somewhere.</p>
[ { "answer_id": 74675987, "author": "kppro", "author_id": 10955397, "author_profile": "https://Stackoverflow.com/users/10955397", "pm_score": 0, "selected": false, "text": "# set the number of iterations\nnum_iterations <- 500\n\n# create an empty list to store the generated data\ngenerated_data <- list()\n\n# loop through the number of iterations\nfor (i in 1:num_iterations) {\n # set the seed\n set.seed(i)\n \n # create the sample data using the mvrnorm function\n sample_distribution <- mvrnorm(n = sample_size,\n mu = sample_meanvector, \n Sigma = sample_covariance_matrix)\n \n # convert the data to a data frame\n df_sample_distribution <- as.data.frame(sample_distribution)\n \n # store the generated data in the list\n generated_data[[i]] <- df_sample_distribution\n}\n\n# you can access the generated data using the list index, for example:\ngenerated_data[[1]] # will return the first generated data\n # create an empty data frame to store the generated data\ngenerated_data_df <- data.frame()\n\n# loop through the generated data list\nfor (i in 1:num_iterations) {\n # bind the data frame at the current index to the generated data data frame\n generated_data_df <- rbind(generated_data_df, generated_data[[i]])\n}\n\n# generated_data_df will now contain all the generated data\n # create the data frame using the do.call and rbind functions\ngenerated_data_df <- do.call(rbind, generated_data)\n" }, { "answer_id": 74675997, "author": "Geilton Xavier Santos de Jesus", "author_id": 6253630, "author_profile": "https://Stackoverflow.com/users/6253630", "pm_score": 0, "selected": false, "text": "# set seed and create data vectors\nset.seed(98989)\nsample_size <- 200 \nsample_meanvector <- c(3, 4) \nsample_covariance_matrix <- matrix(c(2, 1, 1, 2),\n ncol = 2)\n\n# create a list to store the data frames\ndf_list <- list()\n\n# loop to generate the data\nfor (i in 1:500) {\n # create bivariate normal distribution\n sample_distribution <- mvrnorm(n = sample_size,\n mu = sample_meanvector, \n Sigma = sample_covariance_matrix)\n # Convert the data type\n df_sample_distribution <- as.data.frame(sample_distribution)\n # add the data frame to the list\n df_list[[i]] <- df_sample_distribution\n}\n" }, { "answer_id": 74676005, "author": "moodymudskipper", "author_id": 2270475, "author_profile": "https://Stackoverflow.com/users/2270475", "pm_score": 2, "selected": false, "text": "replicate() library(MASS)\nout <- replicate(3, simplify = FALSE, {sample_size <- 200 \n sample_meanvector <- c(3, 4) \n sample_covariance_matrix <- matrix(c(2, 1, 1, 2),\n ncol = 2)\n \n # create bivariate normal distribution\n sample_distribution <- mvrnorm(n = sample_size,\n mu = sample_meanvector, \n Sigma = sample_covariance_matrix)\n #Convert the datatype\n df_sample_distribution <- as.data.frame(sample_distribution)\n\n head(df_sample_distribution) # for shorter output\n })\n\nout\n#> [[1]]\n#> V1 V2\n#> 1 3.195478 4.393699\n#> 2 2.553590 5.065685\n#> 3 2.822811 2.389559\n#> 4 2.267116 4.076016\n#> 5 1.659459 3.830608\n#> 6 1.377554 4.009023\n#> \n#> [[2]]\n#> V1 V2\n#> 1 2.8850139 3.107203\n#> 2 3.0313680 5.163229\n#> 3 3.8649482 4.594017\n#> 4 3.2747060 4.085805\n#> 5 -0.1640264 3.628542\n#> 6 3.6504855 4.747372\n#> \n#> [[3]]\n#> V1 V2\n#> 1 1.3230817 4.075396\n#> 2 3.6049470 6.293968\n#> 3 6.1211276 7.673592\n#> 4 5.2955379 6.736665\n#> 5 0.9032304 2.606501\n#> 6 3.6034566 3.880563\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20680851/" ]
74,675,966
<p>I'm creating a quiz and console shows a problem with split, that it's not a function, but it worked before. I've tried using toString method but it doesn't help, console says instead that can't read properties of null. If someone could help me, it would be appreciated.</p> <pre><code>let correctAnswer = document.getElementById(&quot;correct-answers&quot;); document.querySelector(&quot;.check&quot;).onclick = function () { /* Hide unneeded sections and showing scores */ quiz.classList.add(&quot;hidden&quot;); correctAnswer.classList.remove(&quot;hidden&quot;); /*Showing all previous scores */ const lastScore = localStorage.getItem(&quot;latestScore&quot;) || []; const scoreDetail = lastScore.split(','); scoreDetail.push(score); localStorage.setItem(&quot;latestScore&quot;, scoreDetail); let userScoreTemplate = `&lt;h2&gt;This Round's Score: ${score}&lt;/h2&gt;`; scoreDetail.map((items, index) =&gt; { userScoreTemplate += `&lt;h3&gt;Score ${index}: ${items}&lt;/h3&gt;` }); let userScoreBoard = document.getElementById(&quot;user-score&quot;); userScoreBoard.innerHTML = userScoreTemplate; </code></pre>
[ { "answer_id": 74677020, "author": "Cloudio", "author_id": 8198631, "author_profile": "https://Stackoverflow.com/users/8198631", "pm_score": 1, "selected": false, "text": "localStorage.getItem() const lastScore = localStorage.getItem(\"latestScore\") || \"\";\n" }, { "answer_id": 74677026, "author": "Dirt DIRTSmurf Worth", "author_id": 10214999, "author_profile": "https://Stackoverflow.com/users/10214999", "pm_score": 0, "selected": false, "text": " const scoreDetail = JSON.parse(lastScore) || [];\n\nscoreDetail.push(score);\n localStorage.setItem(\"latestScore\", JSON.stringify(scoreDetail));\n" }, { "answer_id": 74677510, "author": "Suhail Qureshi", "author_id": 20308649, "author_profile": "https://Stackoverflow.com/users/20308649", "pm_score": 0, "selected": false, "text": "localStorage.getItem JSON.parse()" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20450499/" ]
74,675,978
<p>I'm developing an application inside Visual Studio using C#. This is a simple Console application.</p> <p>In some places, I wish to swallow exceptions. Thus I use an empty <code>catch</code> block. It' by design.</p> <p>When I hit F5, in codes of the <code>try</code> block of that <code>catch</code> block, when exceptions raise Visual Studio breaks on them.</p> <p>This behavior is very annoying and reduces our debugging speed. I want those exceptions to not break at all.</p> <p>How can I do that?</p> <p>I searched the Options menu and I found nothing.</p>
[ { "answer_id": 74676008, "author": "EEAH", "author_id": 13695921, "author_profile": "https://Stackoverflow.com/users/13695921", "pm_score": 2, "selected": false, "text": "Debug Windows Exception Settings Common Language Runtime Exceptions" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19864610/" ]
74,677,014
<p>When I tell awt/swing to draw a component at a given y that is smaller than the window height, that object renders on the bottom of the bottom border, but it should not, it is supposed to render at that given y.</p> <p>Here some code example:</p> <pre class="lang-java prettyprint-override"><code> public class Main { public static GameWindow window; public static void main(String[] args) { window = new GameWindow(); } } class GameWindow extends JFrame { private final GamePanel panel; public GameWindow() { super(); this.setSize(600, 400); //Observe that the height is 400 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); panel = new GamePanel(); this.add(panel); //Uncomment the following line and observe how the square now renders where it should //setUndecorated(true); this.setVisible(true); } //Uncomment the following method to see a black line just on top of the bottom border /*@Override public int getHeight() { return panel.getHeight(); }*/ } class GamePanel extends JPanel { public GamePanel() { super(); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); //Here it should render just above the bottom border, but it doesn't, it renders well below g.fill3DRect(0, Main.window.getHeight() - 22, 22, 22, false); } } </code></pre> <p>Case 1: If you live it decorated, you have to resize the window in order to see the square. Case 2: If you make the JFrame undecorated it renders as it should: just on top of the bottom border. Case 3: If you live it decorated, but override the getHeight method so that it returns the height of the panel, a black line is rendered in the bottom of the window.</p> <p>Images: Case 1: <a href="https://i.stack.imgur.com/v1XuI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/v1XuI.png" alt="Case 1" /></a></p> <p>Case 2: <a href="https://i.stack.imgur.com/R8zvM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/R8zvM.png" alt="Case 2" /></a></p> <p>Case 3: <a href="https://i.stack.imgur.com/molVr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/molVr.png" alt="Case 3" /></a></p>
[ { "answer_id": 74677447, "author": "Hovercraft Full Of Eels", "author_id": 522444, "author_profile": "https://Stackoverflow.com/users/522444", "pm_score": 0, "selected": false, "text": "@Override\npublic void paintComponent(Graphics g) {\n super.paintComponent(g);\n g.fill3DRect(0, Main.window.getHeight() - 22, 22, 22, false);\n}\n getHeight() int yPos = getHeight() - 22;\ng.fill3DRect(0, yPos, 22, 22, false);\n 22 getPreferredSize() public class GamePanel extends JPanel {\n public static final int PREF_W = 600;\n public static final int PREF_H = 400;\n public static final int SPRITE_WIDTH = 22;\n\n public GamePanel() {\n super();\n }\n\n @Override\n public void paintComponent(Graphics g) {\n super.paintComponent(g);\n int yPos = getHeight() - SPRITE_WIDTH;\n g.fill3DRect(0, yPos, SPRITE_WIDTH, SPRITE_WIDTH, false);\n }\n\n @Override\n public Dimension getPreferredSize() {\n Dimension superSize = super.getPreferredSize();\n int w = Math.max(PREF_W, superSize.width);\n int h = Math.max(PREF_H, superSize.height);\n return new Dimension(w, h);\n }\n\n public static void main(String[] args) {\n SwingUtilities.invokeLater(() -> {\n GamePanel mainPanel = new GamePanel();\n\n JFrame frame = new JFrame(\"GUI\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.add(mainPanel);\n frame.pack();\n frame.setLocationRelativeTo(null);\n frame.setVisible(true);\n });\n }\n\n}\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20682447/" ]
74,677,017
<p>I need to create a table of 17 rows where each row contains information such as row number, name, surname, email and birthday. The data is provided by this form:</p> <pre><code>&lt;form action=&quot;index.php&quot; method=&quot;post&quot;&gt; &lt;input type=&quot;text&quot; name=&quot;name&quot; placeholder=&quot;name&quot; /&gt; &lt;input type=&quot;text&quot; name=&quot;surname&quot; placeholder=&quot;surname&quot; /&gt; &lt;input type=&quot;text&quot; name=&quot;emailbirthday&quot; placeholder=&quot;emailbirthday&quot; /&gt; &lt;input type=&quot;text&quot; name=&quot;birthday&quot; placeholder=&quot;birthday(dd/mm/aaa)&quot; /&gt; &lt;button type=&quot;reset&quot;&gt;Reset Form&lt;/button&gt; &lt;button type=&quot;submit&quot;&gt;Submit Form&lt;/button&gt; &lt;/form&gt; </code></pre> <p>After clicking submit the data should be displayed in the nth row of the table(row number one if it is the first &quot;pack&quot; of data submitted, number two if its the second and so on). This problem could easely be solved using databases but i cannot use them(by professors order).</p> <p>I tried to create an array than push values into it like this:</p> <pre><code>$array_name = array(); $name = $_POST[&quot;name&quot;]; array_push($array_name, $name); </code></pre> <p>This approach doesn't work(the index of the array stays 0 alla of the time so it keeps replacing the first value again and again) and manually incrementing the index counter of the array doesn't work either.</p>
[ { "answer_id": 74677515, "author": "Ken Lee", "author_id": 11854986, "author_profile": "https://Stackoverflow.com/users/11854986", "pm_score": 1, "selected": false, "text": "session <?php\nsession_start();\n?>\n<form action=\"#\" method=\"post\">\n <input type=\"text\" name=\"name\" placeholder=\"name\" />\n <input type=\"text\" name=\"surname\" placeholder=\"surname\" />\n <input type=\"text\" name=\"email\" placeholder=\"email\" />\n <input type=\"text\" name=\"birthday\" placeholder=\"birthday(dd/mm/aaa)\" />\n <button type=\"reset\">Reset Form</button>\n <button type=\"submit\">Submit Form</button>\n</form>\n\n<?php\n\nif (!isset($_SESSION[\"arr\"])){\n $_SESSION[\"arr\"]=array();\n}\n\nif ($_POST) {\n $subarray=array(\n \"name\"=>$_POST[\"name\"], \n \"surname\"=>$_POST[\"surname\"],\n \"birthday\"=>$_POST[\"birthday\"], \n \"email\"=>$_POST[\"email\"]\n );\n $_SESSION[\"arr\"][]=$subarray;\n}\n\necho \"<table border=1><tr><td>Name<td>Surname<td>Email<td>Birthday\";\n\nforeach($_SESSION[\"arr\"] as $suba){\n echo \"<tr><td>\" . $suba[\"name\"] ;\n echo \"<td>\" . $suba[\"surname\"] ;\n echo \"<td>\" . $suba[\"email\"] ;\n echo \"<td>\" . $suba[\"birthday\"] ;\n}\necho \"</table>\";\n?>\n persistent file format cookies" }, { "answer_id": 74677601, "author": "rauwitt", "author_id": 5458987, "author_profile": "https://Stackoverflow.com/users/5458987", "pm_score": 0, "selected": false, "text": " <form action=\"\" method=\"post\">\n <input type=\"text\" name=\"name\" placeholder=\"name\" />\n <input type=\"text\" name=\"surname\" placeholder=\"surname\" />\n <input type=\"text\" name=\"emailbirthday\" placeholder=\"emailbirthday\" />\n <input type=\"text\" name=\"birthday\" placeholder=\"birthday(dd/mm/aaa)\" />\n <button type=\"reset\">Reset Form</button>\n <button type=\"submit\">Submit Form</button>\n \n<?php\nif($_POST[\"names\"] == \"\")\n{\n$value = $_POST[\"name\"];\n}\nelse\n{\n$value = $_POST[\"names\"].\"-\".$_POST[\"name\"];\n}\n?>\n<input type=\"text\" name=\"names\" style='display:none;' value=\"<?php echo $value ?>\">\n</form>\n" }, { "answer_id": 74678412, "author": "Александр Михайлов", "author_id": 7183451, "author_profile": "https://Stackoverflow.com/users/7183451", "pm_score": 1, "selected": false, "text": "<?php\n$file = 'path/to/file.txt';\n$data = json_decode(file_get_contents($file), true);\n\nif ($_POST) {\n $data[] = [\n \"name\" => $_POST['name'],\n \"surname\" => $_POST['surname'],\n \"emailbirthday\" => $_POST['emailbirthday'],\n \"birthday\" => $_POST['birthday']\n ];\n}\n\nfile_put_contents($file, json_encode($data));\n?>\n\n<form action=\"index.php\" method=\"post\">\n <input type=\"text\" name=\"name\" placeholder=\"name\" />\n <input type=\"text\" name=\"surname\" placeholder=\"surname\" />\n <input type=\"text\" name=\"emailbirthday\" placeholder=\"emailbirthday\" />\n <input type=\"text\" name=\"birthday\" placeholder=\"birthday(dd/mm/aaa)\" />\n <button type=\"reset\">Reset Form</button>\n <button type=\"submit\">Submit Form</button>\n</form>\n\n<table>\n <tr>\n <th>Name</th>\n <th>Surname</th>\n <th>Emailbirthday</th>\n <th>Birthday</th>\n </tr>\n<?php\n foreach ($data as $row) {\n print '<tr>\n <td>'.$row['name'].'</td>\n <td>'.$row['surname'].'</td>\n <td>'.$row['emailbirthday'].'</td>\n <td>'.$row['birthday'].'</td>\n </tr>';\n }\n?>\n</table>\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20682245/" ]
74,677,036
<p>I want to use Sparkline for a spreadsheet to show a trend of the last 5 soccer matches, where A and B are the goals, and C are the resulting points.</p> <p>In column C, the points are only generated if values are entered for the goals and goals conceded, i.e. the columns are not empty.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>A (Goals)</th> <th>B (Conceded)</th> <th>C (Points)</th> </tr> </thead> <tbody> <tr> <td>4</td> <td>4</td> <td>1</td> </tr> <tr> <td>4</td> <td>4</td> <td>1</td> </tr> <tr> <td>4</td> <td></td> <td></td> </tr> <tr> <td>4</td> <td>0</td> <td>3</td> </tr> <tr> <td>4</td> <td>4</td> <td>1</td> </tr> <tr> <td>0</td> <td>4</td> <td>0</td> </tr> </tbody> </table> </div> <p>As you see, in row 3, column c is empty.</p> <p>What I basically try to achieve, is to create a list where the last 5 entries which are not empty / null, are listed:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>C (Points)</th> </tr> </thead> <tbody> <tr> <td>1</td> </tr> <tr> <td>1</td> </tr> <tr> <td>3</td> </tr> <tr> <td>1</td> </tr> <tr> <td>0</td> </tr> </tbody> </table> </div> <p>Is used this formula, but it somehow does not work</p> <p><code>=query(J15:J114,&quot;select * offset &quot;&amp;count(J15:J114)-5)</code></p> <p>shorturl.at/gHPY9 (example result picture)</p> <p>Tried to find a solution myself, but am stuck.</p> <p>Best, Feal</p>
[ { "answer_id": 74677129, "author": "doubleunary", "author_id": 13045193, "author_profile": "https://Stackoverflow.com/users/13045193", "pm_score": 2, "selected": true, "text": "query() where =query( \n J15:J114, \n \"where J is not null \n offset \" & max(0, count(J15:J114) - 5), \n 0 \n)\n" }, { "answer_id": 74677153, "author": "Marcell Almeida", "author_id": 1690338, "author_profile": "https://Stackoverflow.com/users/1690338", "pm_score": 0, "selected": false, "text": "=QUERY(J15:J114, \"SELECT * WHERE J15:J114 IS NOT NULL ORDER BY ROW() DESC LIMIT 5\", 0)\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6439857/" ]
74,677,037
<p>I am trying to create a homepage where I will output question with its answers</p> <p>I have a question which has 3 answers, but when I create the object it only return 1 answer, whereas I need it to return the array of answers. Do I need to create additional class answers in order to do that?</p> <p>My code:</p> <pre><code> include(&quot;connect-database.inc.php&quot;); $question_query = &quot;SELECT questions.questionID, answers.answer, questions.question, questions.feedback, questions.mark, questions.questionTypeID FROM questions JOIN answers ON questions.questionID=answers.questionID&quot;; $questionList=array(); $answerList = array(); try { $mysqliResult = $link-&gt;query($question_query); while($var=$mysqliResult-&gt;fetch_assoc()){ $questionList[$var['questionID']]=new questions($var['question'],$var['feedback'], $var['mark'], $var['questionTypeID'], $var['answer']); } } catch (Exception $e) { echo &quot;MySQLi Error Code: &quot; . $e-&gt;getCode() . &quot;&lt;br /&gt;&quot;; echo &quot;Exception Msg: &quot; . $e-&gt;getMessage(); exit(); } var_dump($questionList); class questions { public function __construct($question, $feedback, $mark, $questionTypeID, $answerList){ $this-&gt;question = $question; $this-&gt;feedback = $feedback; $this-&gt;mark = $mark; $this-&gt;questionTypeID = $questionTypeID; $this-&gt;answers($answerList); } public function answers($answers) { $answers = array(); $this-&gt;answers = $answers; } } </code></pre> <p>I have tried to change to query and retrieve data by answerID, but then I get the same question 3 times. Can anybody help with the solution?</p>
[ { "answer_id": 74677129, "author": "doubleunary", "author_id": 13045193, "author_profile": "https://Stackoverflow.com/users/13045193", "pm_score": 2, "selected": true, "text": "query() where =query( \n J15:J114, \n \"where J is not null \n offset \" & max(0, count(J15:J114) - 5), \n 0 \n)\n" }, { "answer_id": 74677153, "author": "Marcell Almeida", "author_id": 1690338, "author_profile": "https://Stackoverflow.com/users/1690338", "pm_score": 0, "selected": false, "text": "=QUERY(J15:J114, \"SELECT * WHERE J15:J114 IS NOT NULL ORDER BY ROW() DESC LIMIT 5\", 0)\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20602209/" ]
74,677,042
<p>Consider the following remote table:</p> <pre class="lang-r prettyprint-override"><code>library(dbplyr) library(dplyr, w = F) remote_data &lt;- memdb_frame( grp = c(2, 2, 2, 1, 3, 1, 1), win = c(&quot;B&quot;, &quot;C&quot;, &quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;A&quot;, &quot;C&quot;), id = c(1,3,5,7,2,4,6), ) </code></pre> <p>I wish to group by <code>grp</code>, order by <code>win</code> and take the last id. This is fairly straightforward if I collect first</p> <pre><code># intended output when collecting first remote_data %&gt;% collect() %&gt;% arrange(grp, win) %&gt;% group_by(grp) %&gt;% mutate(last_id = last(id)) %&gt;% ungroup() #&gt; # A tibble: 7 × 4 #&gt; grp win id last_id #&gt; &lt;dbl&gt; &lt;chr&gt; &lt;dbl&gt; &lt;dbl&gt; #&gt; 1 1 A 4 6 #&gt; 2 1 B 7 6 #&gt; 3 1 C 6 6 #&gt; 4 2 A 5 3 #&gt; 5 2 B 1 3 #&gt; 6 2 C 3 3 #&gt; 7 3 C 2 2 </code></pre> <p>However I cannot directly convert this to {dbplyr} code by removing <code>collect()</code>, though the SQL code doesn't look bad, what's happening here ?</p> <pre><code>remote_data %&gt;% arrange(grp, win) %&gt;% group_by(grp) %&gt;% mutate(last_id = last(id)) %&gt;% ungroup() %&gt;% print() %&gt;% show_query() #&gt; # Source: SQL [7 x 4] #&gt; # Database: sqlite 3.39.4 [:memory:] #&gt; # Ordered by: grp, win #&gt; grp win id last_id #&gt; &lt;dbl&gt; &lt;chr&gt; &lt;dbl&gt; &lt;dbl&gt; #&gt; 1 1 A 4 4 #&gt; 2 1 B 7 7 #&gt; 3 1 C 6 6 #&gt; 4 2 A 5 5 #&gt; 5 2 B 1 1 #&gt; 6 2 C 3 3 #&gt; 7 3 C 2 2 #&gt; &lt;SQL&gt; #&gt; SELECT #&gt; *, #&gt; LAST_VALUE(`id`) OVER (PARTITION BY `grp` ORDER BY `grp`, `win`) AS `last_id` #&gt; FROM `dbplyr_001` #&gt; ORDER BY `grp`, `win` </code></pre> <p><code>dbplyr::window_order()</code> allows us to override th ORDER BY clause created by the group_by(), I tried <code>window_order(,win)</code>, but no cookie:</p> <pre><code>remote_data %&gt;% arrange(grp, win) %&gt;% group_by(grp) %&gt;% window_order(win) %&gt;% mutate(last_id = last(id)) %&gt;% ungroup() %&gt;% print() %&gt;% show_query() #&gt; # Source: SQL [7 x 4] #&gt; # Database: sqlite 3.39.4 [:memory:] #&gt; # Ordered by: win #&gt; grp win id last_id #&gt; &lt;dbl&gt; &lt;chr&gt; &lt;dbl&gt; &lt;dbl&gt; #&gt; 1 1 A 4 4 #&gt; 2 1 B 7 7 #&gt; 3 1 C 6 6 #&gt; 4 2 A 5 5 #&gt; 5 2 B 1 1 #&gt; 6 2 C 3 3 #&gt; 7 3 C 2 2 #&gt; &lt;SQL&gt; #&gt; SELECT *, LAST_VALUE(`id`) OVER (PARTITION BY `grp` ORDER BY `win`) AS `last_id` #&gt; FROM `dbplyr_001` #&gt; ORDER BY `grp`, `win` </code></pre> <p>For some reason <code>window_order(,grp)</code> does trigger a window calculation but not with the expected order:</p> <pre><code>remote_data %&gt;% arrange(grp, win) %&gt;% group_by(grp) %&gt;% window_order(grp) %&gt;% mutate(last_id = last(id)) %&gt;% ungroup() %&gt;% print() %&gt;% show_query() #&gt; # Source: SQL [7 x 4] #&gt; # Database: sqlite 3.39.4 [:memory:] #&gt; # Ordered by: grp #&gt; grp win id last_id #&gt; &lt;dbl&gt; &lt;chr&gt; &lt;dbl&gt; &lt;dbl&gt; #&gt; 1 1 A 4 6 #&gt; 2 1 B 7 6 #&gt; 3 1 C 6 6 #&gt; 4 2 A 5 5 #&gt; 5 2 B 1 5 #&gt; 6 2 C 3 5 #&gt; 7 3 C 2 2 #&gt; &lt;SQL&gt; #&gt; SELECT *, LAST_VALUE(`id`) OVER (PARTITION BY `grp` ORDER BY `grp`) AS `last_id` #&gt; FROM `dbplyr_001` #&gt; ORDER BY `grp`, `win` </code></pre> <p>What can I do to keep my initial output with only remote computations, preferably {dbplyr} code ?</p>
[ { "answer_id": 74677129, "author": "doubleunary", "author_id": 13045193, "author_profile": "https://Stackoverflow.com/users/13045193", "pm_score": 2, "selected": true, "text": "query() where =query( \n J15:J114, \n \"where J is not null \n offset \" & max(0, count(J15:J114) - 5), \n 0 \n)\n" }, { "answer_id": 74677153, "author": "Marcell Almeida", "author_id": 1690338, "author_profile": "https://Stackoverflow.com/users/1690338", "pm_score": 0, "selected": false, "text": "=QUERY(J15:J114, \"SELECT * WHERE J15:J114 IS NOT NULL ORDER BY ROW() DESC LIMIT 5\", 0)\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2270475/" ]
74,677,085
<p>I Have a Ansible playbook which prints the CPU utilisation of target machine.When the CPU utilization is less than 90% , I get a OK message and if more than 90% , I should get not okay message on screen and also generate a log file as monitor.log on the Ansible host machine when CPU utilization is not okay.</p> <p>I am able to generate the output on the console but I am not able to send this output to a log file.</p> <p>The Ansible playbook that I have created is.</p> <pre><code>#CPU callculation - name: Setup Nginx server on myserver list hosts: myservers become: True tasks: - name: 'copy Get-Memory-Utilization.sh script to {{ inventory_hostname }}' copy: src: /home/ec2-user/Memory-Utilization.sh dest: /tmp mode: '0775' - name: 'Preparing Memory utilization using script results' shell: | sh /tmp/Memory-Utilization.sh register: memsec - name: 'Preparing Memory utilization for 1st sec' shell: | sh /tmp/Memory-Utilization.sh register: mem1sec - name: 'Preparing Memory utilization for 2nd sec' shell: | sh /tmp/Memory-Utilization.sh register: mem2sec - name: 'Preparing Memory utilization for 3rd sec' shell: | sh /tmp/Memory-Utilization.sh register: mem3sec - name: 'Prepare Memory Used percentage if its abnormal' shell: | sh /tmp/Memory-Utilization.sh register: memhigusage when: memsec.stdout|int &gt;= 90 or mem1sec.stdout|int &gt;= 90 or mem2sec.stdout|int &gt;= 90 or mem3sec.stdout|int &gt;= 90 - name: 'Print message if MEMORY utilization is normal' debug: msg: - ------------------------------------------------------- - Memory Utilization = ( ( Total - Free ) / Total * 100 ) = {{ memsec.stdout }}% - ------------------------------------------------------- when: memsec.stdout|int &lt; 90 and mem1sec.stdout|int &lt; 90 and mem2sec.stdout|int &lt; 90 and mem3sec.stdout|int &lt; 90 - name: 'Print message if MEMORY utilization is abnormal' debug: msg: - ------------------------------------------------------- - Memory Utilization = ( ( Total - Free ) / Total * 100 ) = {{ memhigusage.stdout }}% - ------------------------------------------------------- when: memsec.stdout|int &gt;= 90 or mem1sec.stdout|int &gt;= 90 or mem2sec.stdout|int &gt;= 90 or mem3sec.stdout|int &gt;= 90 </code></pre> <p>output:</p> <pre><code> TASK [Print message if MEMORY utilization is normal] ************************************************************************************************************************************************************* ok: [44.203.153.54] =&gt; { &quot;msg&quot;: [ &quot;-------------------------------------------------------&quot;, &quot;Memory Utilization = ( ( Total - Free ) / Total * 100 ) = 13.87%&quot;, &quot;-------------------------------------------------------&quot; ] } TASK [Print message if MEMORY utilization is abnormal] *********************************************************************************************************************************************************** skipping: [44.203.153.54] =&gt; {} </code></pre> <p>Please help me to send this output to a file.</p>
[ { "answer_id": 74677102, "author": "Haim Cohen", "author_id": 3752715, "author_profile": "https://Stackoverflow.com/users/3752715", "pm_score": 1, "selected": false, "text": "ansible-playbook \"-l\" \"-v\" ansible-playbook -l /var/log/monitor.log -v my_playbook.yml\n name: 'Print message if MEMORY utilization is normal'\ndebug:\nmsg:\n- -------------------------------------------------------\n- Memory Utilization = ( ( Total - Free ) / Total * 100 ) = {{ memsec.stdout }}%\n- -------------------------------------------------------\nlog_path: /var/log/monitor.log\nwhen: memsec.stdout|int < 90 and mem1sec.stdout|int < 90 and mem2sec.stdout|int < 90 and mem3sec.stdout|int < 90\n" }, { "answer_id": 74680302, "author": "Motaz Hakim", "author_id": 17102062, "author_profile": "https://Stackoverflow.com/users/17102062", "pm_score": 0, "selected": false, "text": "ansible.builtin.log log - name: 'Write log message to file'\n log:\n msg: 'Memory utilization is not OK: {{ memhigusage.stdout }}%'\n path: /path/to/log/file/monitor.log\n Memory utilization is not OK: {{ memhigusage.stdout }}% monitor.log memsec.stdout mem1sec.stdout mem2sec.stdout mem3sec.stdout when - name: 'Write log message to file'\n log:\n msg: 'Memory utilization is not OK: {{ memhigusage.stdout }}%'\n path: /path/to/log/file/monitor.log\n when: memsec.stdout|int >= 90 or mem1sec.stdout|int >= 90 or mem2sec.stdout|int >= 90 or mem3sec.stdout|int >= 90\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11578464/" ]
74,677,103
<p>I would like to find out how many <code>Users</code> have <code>Swipes</code> per day without duplicates of <code>user_id</code> within group. So if a <code>User</code> has swiped multiple times on a day, I want the <code>User</code> only show once per group (per day). I am not really interested in the actual <code>Swipes</code> but rather in the <code>swipe count</code> per day.</p> <p>I tried:</p> <p><code>Swipe::all()-&gt;groupBy(function($item){ return $item-&gt;created_at-&gt;format('d-M-y'); })-&gt;unique('user_id') </code></p>
[ { "answer_id": 74677102, "author": "Haim Cohen", "author_id": 3752715, "author_profile": "https://Stackoverflow.com/users/3752715", "pm_score": 1, "selected": false, "text": "ansible-playbook \"-l\" \"-v\" ansible-playbook -l /var/log/monitor.log -v my_playbook.yml\n name: 'Print message if MEMORY utilization is normal'\ndebug:\nmsg:\n- -------------------------------------------------------\n- Memory Utilization = ( ( Total - Free ) / Total * 100 ) = {{ memsec.stdout }}%\n- -------------------------------------------------------\nlog_path: /var/log/monitor.log\nwhen: memsec.stdout|int < 90 and mem1sec.stdout|int < 90 and mem2sec.stdout|int < 90 and mem3sec.stdout|int < 90\n" }, { "answer_id": 74680302, "author": "Motaz Hakim", "author_id": 17102062, "author_profile": "https://Stackoverflow.com/users/17102062", "pm_score": 0, "selected": false, "text": "ansible.builtin.log log - name: 'Write log message to file'\n log:\n msg: 'Memory utilization is not OK: {{ memhigusage.stdout }}%'\n path: /path/to/log/file/monitor.log\n Memory utilization is not OK: {{ memhigusage.stdout }}% monitor.log memsec.stdout mem1sec.stdout mem2sec.stdout mem3sec.stdout when - name: 'Write log message to file'\n log:\n msg: 'Memory utilization is not OK: {{ memhigusage.stdout }}%'\n path: /path/to/log/file/monitor.log\n when: memsec.stdout|int >= 90 or mem1sec.stdout|int >= 90 or mem2sec.stdout|int >= 90 or mem3sec.stdout|int >= 90\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7337209/" ]
74,677,123
<p>I have a hard time with what should be a very common use case on polars dataframes. I simply want to create a new column on an existing dataframe based on some other column. Here is the code I try, but doesn't work:</p> <pre><code>import polars as pl df.with_columns([ (pl.col('old_col').apply(lambda x: func(x)).alias(&quot;new_col&quot;), ]) </code></pre>
[ { "answer_id": 74677102, "author": "Haim Cohen", "author_id": 3752715, "author_profile": "https://Stackoverflow.com/users/3752715", "pm_score": 1, "selected": false, "text": "ansible-playbook \"-l\" \"-v\" ansible-playbook -l /var/log/monitor.log -v my_playbook.yml\n name: 'Print message if MEMORY utilization is normal'\ndebug:\nmsg:\n- -------------------------------------------------------\n- Memory Utilization = ( ( Total - Free ) / Total * 100 ) = {{ memsec.stdout }}%\n- -------------------------------------------------------\nlog_path: /var/log/monitor.log\nwhen: memsec.stdout|int < 90 and mem1sec.stdout|int < 90 and mem2sec.stdout|int < 90 and mem3sec.stdout|int < 90\n" }, { "answer_id": 74680302, "author": "Motaz Hakim", "author_id": 17102062, "author_profile": "https://Stackoverflow.com/users/17102062", "pm_score": 0, "selected": false, "text": "ansible.builtin.log log - name: 'Write log message to file'\n log:\n msg: 'Memory utilization is not OK: {{ memhigusage.stdout }}%'\n path: /path/to/log/file/monitor.log\n Memory utilization is not OK: {{ memhigusage.stdout }}% monitor.log memsec.stdout mem1sec.stdout mem2sec.stdout mem3sec.stdout when - name: 'Write log message to file'\n log:\n msg: 'Memory utilization is not OK: {{ memhigusage.stdout }}%'\n path: /path/to/log/file/monitor.log\n when: memsec.stdout|int >= 90 or mem1sec.stdout|int >= 90 or mem2sec.stdout|int >= 90 or mem3sec.stdout|int >= 90\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15796158/" ]
74,677,136
<p>I am trying to plot Male and Female in different Age Groups. I am trying to show the individual Male and Female Count in their respective bars/colours but the graphs shows the total count value in the AgeGroup. <strong>How I am going to show/label the individual count of male and female in their respective bars/colours by AgeGroup.</strong> Example Data is presented. Thanks</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Age</th> <th style="text-align: center;">sex</th> <th style="text-align: right;">AgeGroup</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">22</td> <td style="text-align: center;">F</td> <td style="text-align: right;">18-25 Years</td> </tr> <tr> <td style="text-align: left;">36</td> <td style="text-align: center;">F</td> <td style="text-align: right;">36-45 Years</td> </tr> <tr> <td style="text-align: left;">20</td> <td style="text-align: center;">M</td> <td style="text-align: right;">18-25 Years</td> </tr> </tbody> </table> </div> <p>Code I used:</p> <pre><code>library(tidyverse) ggplot(demo_df, mapping = aes(x = AgeGroup)) + geom_bar(aes(fill = sex), position=&quot;dodge&quot;)+ geom_text(stat = &quot;count&quot;, aes(label = scales::comma(after_stat(count))), nudge_y = 10000, fontface = 2) + theme_minimal() + theme(axis.text.x = element_text(angle = 90, hjust = 0), axis.text.y.left = element_blank(), axis.title.y.left = element_blank()) </code></pre> <p><a href="https://i.stack.imgur.com/nVXVx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nVXVx.png" alt="" /></a></p>
[ { "answer_id": 74677102, "author": "Haim Cohen", "author_id": 3752715, "author_profile": "https://Stackoverflow.com/users/3752715", "pm_score": 1, "selected": false, "text": "ansible-playbook \"-l\" \"-v\" ansible-playbook -l /var/log/monitor.log -v my_playbook.yml\n name: 'Print message if MEMORY utilization is normal'\ndebug:\nmsg:\n- -------------------------------------------------------\n- Memory Utilization = ( ( Total - Free ) / Total * 100 ) = {{ memsec.stdout }}%\n- -------------------------------------------------------\nlog_path: /var/log/monitor.log\nwhen: memsec.stdout|int < 90 and mem1sec.stdout|int < 90 and mem2sec.stdout|int < 90 and mem3sec.stdout|int < 90\n" }, { "answer_id": 74680302, "author": "Motaz Hakim", "author_id": 17102062, "author_profile": "https://Stackoverflow.com/users/17102062", "pm_score": 0, "selected": false, "text": "ansible.builtin.log log - name: 'Write log message to file'\n log:\n msg: 'Memory utilization is not OK: {{ memhigusage.stdout }}%'\n path: /path/to/log/file/monitor.log\n Memory utilization is not OK: {{ memhigusage.stdout }}% monitor.log memsec.stdout mem1sec.stdout mem2sec.stdout mem3sec.stdout when - name: 'Write log message to file'\n log:\n msg: 'Memory utilization is not OK: {{ memhigusage.stdout }}%'\n path: /path/to/log/file/monitor.log\n when: memsec.stdout|int >= 90 or mem1sec.stdout|int >= 90 or mem2sec.stdout|int >= 90 or mem3sec.stdout|int >= 90\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1535580/" ]
74,677,158
<p>The <code>devcontainer.json</code> allows adding extensions to be installed in a container.</p> <p>I want to be able to set the list of mandatory extensions to be used by all team members, like <code>rust-lang.rust-analyzer</code> and <code>llvm-vs-code-extensions.vscode-clangd</code> and another file for personal extensions.</p> <p>Ideally, the personal one would be added to <code>.gitignore</code>.</p>
[ { "answer_id": 74677102, "author": "Haim Cohen", "author_id": 3752715, "author_profile": "https://Stackoverflow.com/users/3752715", "pm_score": 1, "selected": false, "text": "ansible-playbook \"-l\" \"-v\" ansible-playbook -l /var/log/monitor.log -v my_playbook.yml\n name: 'Print message if MEMORY utilization is normal'\ndebug:\nmsg:\n- -------------------------------------------------------\n- Memory Utilization = ( ( Total - Free ) / Total * 100 ) = {{ memsec.stdout }}%\n- -------------------------------------------------------\nlog_path: /var/log/monitor.log\nwhen: memsec.stdout|int < 90 and mem1sec.stdout|int < 90 and mem2sec.stdout|int < 90 and mem3sec.stdout|int < 90\n" }, { "answer_id": 74680302, "author": "Motaz Hakim", "author_id": 17102062, "author_profile": "https://Stackoverflow.com/users/17102062", "pm_score": 0, "selected": false, "text": "ansible.builtin.log log - name: 'Write log message to file'\n log:\n msg: 'Memory utilization is not OK: {{ memhigusage.stdout }}%'\n path: /path/to/log/file/monitor.log\n Memory utilization is not OK: {{ memhigusage.stdout }}% monitor.log memsec.stdout mem1sec.stdout mem2sec.stdout mem3sec.stdout when - name: 'Write log message to file'\n log:\n msg: 'Memory utilization is not OK: {{ memhigusage.stdout }}%'\n path: /path/to/log/file/monitor.log\n when: memsec.stdout|int >= 90 or mem1sec.stdout|int >= 90 or mem2sec.stdout|int >= 90 or mem3sec.stdout|int >= 90\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1333734/" ]
74,677,176
<p>I am currently struggling with a bracket position problem, I currently have a program that lists my employees and I need to add more data at the moment this is my output :</p> <pre><code>[ { gender: 'female', birthDate: '1999-01-09T01:03:14.158Z', name: 'Steven', surname: 'Johnson', workload: 30 }, { gender: 'male', birthDate: '1989-04-09T09:40:26.496Z', name: 'Jon', surname: 'Doe', workload: 20 } ] </code></pre> <p>and I want it like this:</p> <pre><code> { total: 50, workload10: 13, workload20: 12, workload30: 10, workload40: 15 averageAge: 33.6, minAge: 19, maxAge: 55, medianAge: 38, medianWorkload: 28, averageWomenWorkload: 26, sortedByWorkload:[ { gender: 'female', birthDate: '1999-01-09T01:03:14.158Z', name: 'Stephanie', surname: 'Johnson', workload: 30 }, { gender: 'male', birthDate: '1989-04-09T09:40:26.496Z', name: 'Jon', surname: 'Doe', workload: 20 } ] } </code></pre> <p>The problem is that I don't know how to define the brackets to get this shape, can someone please advise me ?</p>
[ { "answer_id": 74677102, "author": "Haim Cohen", "author_id": 3752715, "author_profile": "https://Stackoverflow.com/users/3752715", "pm_score": 1, "selected": false, "text": "ansible-playbook \"-l\" \"-v\" ansible-playbook -l /var/log/monitor.log -v my_playbook.yml\n name: 'Print message if MEMORY utilization is normal'\ndebug:\nmsg:\n- -------------------------------------------------------\n- Memory Utilization = ( ( Total - Free ) / Total * 100 ) = {{ memsec.stdout }}%\n- -------------------------------------------------------\nlog_path: /var/log/monitor.log\nwhen: memsec.stdout|int < 90 and mem1sec.stdout|int < 90 and mem2sec.stdout|int < 90 and mem3sec.stdout|int < 90\n" }, { "answer_id": 74680302, "author": "Motaz Hakim", "author_id": 17102062, "author_profile": "https://Stackoverflow.com/users/17102062", "pm_score": 0, "selected": false, "text": "ansible.builtin.log log - name: 'Write log message to file'\n log:\n msg: 'Memory utilization is not OK: {{ memhigusage.stdout }}%'\n path: /path/to/log/file/monitor.log\n Memory utilization is not OK: {{ memhigusage.stdout }}% monitor.log memsec.stdout mem1sec.stdout mem2sec.stdout mem3sec.stdout when - name: 'Write log message to file'\n log:\n msg: 'Memory utilization is not OK: {{ memhigusage.stdout }}%'\n path: /path/to/log/file/monitor.log\n when: memsec.stdout|int >= 90 or mem1sec.stdout|int >= 90 or mem2sec.stdout|int >= 90 or mem3sec.stdout|int >= 90\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20610394/" ]
74,677,196
<pre><code>a = ['a', 'b', 'c,'] b = [1, 2, 3] c = [1, 2, 3] #this is my effort on printing 3 lists side by side; however, I noticed it is completely wrong res = &quot;\n&quot;.join(&quot;{} {}&quot;.format(x, y, z) for x, y, z in zip(a, b, c)) print(res) </code></pre> <p>#how i want my results to look like a 1 1 b 2 2 c 3 3</p> <p>I was expecting to print 3 lists side by side</p>
[ { "answer_id": 74677102, "author": "Haim Cohen", "author_id": 3752715, "author_profile": "https://Stackoverflow.com/users/3752715", "pm_score": 1, "selected": false, "text": "ansible-playbook \"-l\" \"-v\" ansible-playbook -l /var/log/monitor.log -v my_playbook.yml\n name: 'Print message if MEMORY utilization is normal'\ndebug:\nmsg:\n- -------------------------------------------------------\n- Memory Utilization = ( ( Total - Free ) / Total * 100 ) = {{ memsec.stdout }}%\n- -------------------------------------------------------\nlog_path: /var/log/monitor.log\nwhen: memsec.stdout|int < 90 and mem1sec.stdout|int < 90 and mem2sec.stdout|int < 90 and mem3sec.stdout|int < 90\n" }, { "answer_id": 74680302, "author": "Motaz Hakim", "author_id": 17102062, "author_profile": "https://Stackoverflow.com/users/17102062", "pm_score": 0, "selected": false, "text": "ansible.builtin.log log - name: 'Write log message to file'\n log:\n msg: 'Memory utilization is not OK: {{ memhigusage.stdout }}%'\n path: /path/to/log/file/monitor.log\n Memory utilization is not OK: {{ memhigusage.stdout }}% monitor.log memsec.stdout mem1sec.stdout mem2sec.stdout mem3sec.stdout when - name: 'Write log message to file'\n log:\n msg: 'Memory utilization is not OK: {{ memhigusage.stdout }}%'\n path: /path/to/log/file/monitor.log\n when: memsec.stdout|int >= 90 or mem1sec.stdout|int >= 90 or mem2sec.stdout|int >= 90 or mem3sec.stdout|int >= 90\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20682643/" ]
74,677,200
<p>I've been trying to redesign my website recently, and I thought the idea to change the main header to change into different backgrounds depending on the button you hover would be cool</p> <p>However, I know nothing about javascript besides from the absolute basic, so some help would be nice</p> <p>Here's what I'm trying to to achieve</p> <p><a href="https://i.stack.imgur.com/BFfOJ.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BFfOJ.gif" alt="enter image description here" /></a></p> <p>Here's the current HTML for the header</p> <pre><code>&lt;body&gt; &lt;div class=&quot;logocontainer&quot;&gt; &lt;a href=&quot;index.html&quot;&gt; &lt;img src=&quot;images/badasslogo.png&quot; class=&quot;logo&quot;&gt;&lt;/a&gt; &lt;/div&gt; &lt;div id=&quot;buttoncontainer&quot; class=&quot;buttoncontainer&quot;&gt; &lt;/div&gt; &lt;script src=&quot;js/menu.js&quot;&gt;&lt;/script&gt; </code></pre> <p>Here's the CSS</p> <pre><code>.logocontainer { text-align: center; } .logo { display: inline-block; margin-bottom: 0.30%; align: center; } .buttoncontainer { text-align: center; } .button { display: inline-block; } .button:hover { box-shadow: 0 0 5px white; filter: brightness(125%); } .button:active { box-shadow: 0 0 10px white; filter: brightness(155%); } </code></pre> <p>And the .js file which I use for the buttons, since if I didn't use it, I would have to update every single page manually if I ever wanted to add more buttons to it</p> <pre><code>let headerContent = ` &lt;a href=&quot;index.html&quot;&gt; &lt;img src=&quot;images/buttons/homebutton.png&quot; class=&quot;button&quot;&gt;&lt;/a&gt; &lt;a href=&quot;blog/blogmain.html&quot;&gt; &lt;img src=&quot;images/buttons/blogbutton.png&quot; class=&quot;button&quot;&gt;&lt;/a&gt; &lt;a href=&quot;art/artmain.html&quot;&gt; &lt;img src=&quot;images/buttons/artbutton.png&quot; class=&quot;button&quot;&gt;&lt;/a&gt; &lt;a href=&quot;fanart/fanartmain.html&quot;&gt; &lt;img src=&quot;images/buttons/fanartbutton.png&quot; class=&quot;button&quot;&gt;&lt;/a&gt; &lt;a href=&quot;partners/partnersmain.html&quot;&gt; &lt;img src=&quot;images/buttons/partnersbutton.png&quot; class=&quot;button&quot;&gt;&lt;/a&gt; &lt;a href=&quot;guestbook/guestbook.html&quot;&gt; &lt;img src=&quot;images/buttons/guestbookbutton.png&quot; class=&quot;button&quot;&gt;&lt;/a&gt; &lt;a href=&quot;https://junessaidotnet.proboards.com/&quot;&gt; &lt;img src=&quot;images/buttons/forumsbutton.png&quot; class=&quot;button&quot;&gt;&lt;/a&gt; &lt;a href=&quot;downloads/downloadsmain.html&quot;&gt; &lt;img src=&quot;images/buttons/downloadsbutton.png&quot; class=&quot;button&quot;&gt;&lt;/a&gt; &lt;a href=&quot;extras/extrasmain.html&quot;&gt; &lt;img src=&quot;images/buttons/extrasbutton.png&quot; class=&quot;button&quot;&gt;&lt;/a&gt; &lt;a href=&quot;donate/donatemain.html&quot;&gt; &lt;img src=&quot;images/buttons/donatebutton.png&quot; class=&quot;button&quot;&gt;&lt;/a&gt; &lt;a href=&quot;about/about.html&quot;&gt; &lt;img src=&quot;images/buttons/aboutbutton.png&quot; class=&quot;button&quot;&gt;&lt;/a&gt; `; document.querySelector('#buttoncontainer').insertAdjacentHTML('beforeend', headerContent); </code></pre> <p>Also, if possible Is there any way to insert the logo into .js file aswell?</p>
[ { "answer_id": 74677102, "author": "Haim Cohen", "author_id": 3752715, "author_profile": "https://Stackoverflow.com/users/3752715", "pm_score": 1, "selected": false, "text": "ansible-playbook \"-l\" \"-v\" ansible-playbook -l /var/log/monitor.log -v my_playbook.yml\n name: 'Print message if MEMORY utilization is normal'\ndebug:\nmsg:\n- -------------------------------------------------------\n- Memory Utilization = ( ( Total - Free ) / Total * 100 ) = {{ memsec.stdout }}%\n- -------------------------------------------------------\nlog_path: /var/log/monitor.log\nwhen: memsec.stdout|int < 90 and mem1sec.stdout|int < 90 and mem2sec.stdout|int < 90 and mem3sec.stdout|int < 90\n" }, { "answer_id": 74680302, "author": "Motaz Hakim", "author_id": 17102062, "author_profile": "https://Stackoverflow.com/users/17102062", "pm_score": 0, "selected": false, "text": "ansible.builtin.log log - name: 'Write log message to file'\n log:\n msg: 'Memory utilization is not OK: {{ memhigusage.stdout }}%'\n path: /path/to/log/file/monitor.log\n Memory utilization is not OK: {{ memhigusage.stdout }}% monitor.log memsec.stdout mem1sec.stdout mem2sec.stdout mem3sec.stdout when - name: 'Write log message to file'\n log:\n msg: 'Memory utilization is not OK: {{ memhigusage.stdout }}%'\n path: /path/to/log/file/monitor.log\n when: memsec.stdout|int >= 90 or mem1sec.stdout|int >= 90 or mem2sec.stdout|int >= 90 or mem3sec.stdout|int >= 90\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19840551/" ]
74,677,222
<p>I tried to create a <code>contact us</code> form in django but i got always false when i want to use <code>.is_valid()</code> function.</p> <p><strong>this is my form:</strong></p> <pre><code>from django import forms from django.core import validators class ContactForm(forms.Form): first_name = forms.CharField( widget=forms.TextInput( attrs={'placeholder': 'نام خود را وارد کنید'}), label=&quot;نام &quot;, validators=[ validators.MaxLengthValidator(100, &quot;نام شما نمیتواند بیش از 100 کاراکتر باشد&quot;)]) last_name = forms.CharField( widget=forms.TextInput( attrs={'placeholder': 'نام خانوادگی خود را وارد کنید'}), label=&quot;نام خانوادگی&quot;, validators=[ validators.MaxLengthValidator(100, &quot;نام خانوادگی شما نمیتواند بیش از 100 کاراکتر باشد&quot;)]) email = forms.EmailField( widget=forms.EmailInput( attrs={'placeholder': 'ایمیل خود را وارد کنید'}), label=&quot;ایمیل&quot;, validators=[ validators.MaxLengthValidator(200, &quot;تعداد کاراکترهایایمیل شما نمیتواند بیش از ۲۰۰ کاراکتر باشد.&quot;) ]) title = forms.CharField( widget=forms.TextInput( attrs={'placeholder': 'عنوان پیام خود را وارد کنید'}), label=&quot;عنوان&quot;, validators=[ validators.MaxLengthValidator(250, &quot;تعداد کاراکترهای شما نمیتواند بیش از 250 کاراکتر باشد.&quot;) ]) text = forms.CharField( widget=forms.Textarea( attrs={'placeholder': 'متن پیام خود را وارد کنید'}), label=&quot;متن پیام&quot;, ) def __init__(self, *args, **kwargs): super(ContactForm, self).__init__() for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form_field require' </code></pre> <p><strong>this is my view:</strong></p> <pre><code>from django.shortcuts import render from .forms import ContactForm from .models import ContactUs def contact_us(request): contact_form = ContactForm(request.POST or None) if contact_form.is_valid(): first_name = contact_form.cleaned_data.get('first_name') last_name = contact_form.cleaned_data.get('last_name') email = contact_form.cleaned_data.get('email') title = contact_form.cleaned_data.get('title') text = contact_form.cleaned_data.get('text') ContactUs.objects.create(first_name=first_name, last_name=last_name, email=email, title=title, text=text) # todo: show user success message contact_form = ContactForm() context = { 'form': contact_form } return render(request, 'contact_us/contact_us.html', context) </code></pre> <p>** this is the codes in template**</p> <pre><code> &lt;form action=&quot;{% url 'contact' %}&quot; id=&quot;contactform&quot; method=&quot;post&quot;&gt; {% csrf_token %} &lt;div class=&quot;col-md-6 col-lg-6&quot;&gt; &lt;div class=&quot;form_block&quot;&gt; {{ form.first_name }} {% for error in form.first_name.errors %} &lt;p class=&quot;text-danger&quot;&gt;{{ error }}&lt;/p&gt; {% endfor %} &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col-md-6 col-lg-6&quot;&gt; &lt;div class=&quot;form_block&quot;&gt; {{ form.last_name }} {% for error in form.last_name.errors %} &lt;p class=&quot;text-danger&quot;&gt;{{ error }}&lt;/p&gt; {% endfor %} &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col-md-6 col-lg-6&quot;&gt; &lt;div class=&quot;form_block&quot;&gt; {{ form.email }} {% for error in form.email.errors %} &lt;p class=&quot;text-danger&quot;&gt;{{ error }}&lt;/p&gt; {% endfor %} &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col-md-6 col-lg-6&quot;&gt; &lt;div class=&quot;form_block&quot;&gt; {{ form.title }} {% for error in form.title.errors %} &lt;p class=&quot;text-danger&quot;&gt;{{ error }}&lt;/p&gt; {% endfor %} &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col-md-12 col-lg-12&quot;&gt; &lt;div class=&quot;form_block&quot;&gt; {{ form.text }} {% for error in form.text.errors %} &lt;p class=&quot;text-danger&quot;&gt;{{ error }}&lt;/p&gt; {% endfor %} &lt;div class=&quot;response&quot;&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col-md-12 col-lg-12&quot;&gt; &lt;div class=&quot;form_block&quot;&gt; &lt;button type=&quot;submit&quot; class=&quot;clv_btn submitForm&quot; data-type=&quot;contact&quot;&gt;ارسال &lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; </code></pre>
[ { "answer_id": 74677102, "author": "Haim Cohen", "author_id": 3752715, "author_profile": "https://Stackoverflow.com/users/3752715", "pm_score": 1, "selected": false, "text": "ansible-playbook \"-l\" \"-v\" ansible-playbook -l /var/log/monitor.log -v my_playbook.yml\n name: 'Print message if MEMORY utilization is normal'\ndebug:\nmsg:\n- -------------------------------------------------------\n- Memory Utilization = ( ( Total - Free ) / Total * 100 ) = {{ memsec.stdout }}%\n- -------------------------------------------------------\nlog_path: /var/log/monitor.log\nwhen: memsec.stdout|int < 90 and mem1sec.stdout|int < 90 and mem2sec.stdout|int < 90 and mem3sec.stdout|int < 90\n" }, { "answer_id": 74680302, "author": "Motaz Hakim", "author_id": 17102062, "author_profile": "https://Stackoverflow.com/users/17102062", "pm_score": 0, "selected": false, "text": "ansible.builtin.log log - name: 'Write log message to file'\n log:\n msg: 'Memory utilization is not OK: {{ memhigusage.stdout }}%'\n path: /path/to/log/file/monitor.log\n Memory utilization is not OK: {{ memhigusage.stdout }}% monitor.log memsec.stdout mem1sec.stdout mem2sec.stdout mem3sec.stdout when - name: 'Write log message to file'\n log:\n msg: 'Memory utilization is not OK: {{ memhigusage.stdout }}%'\n path: /path/to/log/file/monitor.log\n when: memsec.stdout|int >= 90 or mem1sec.stdout|int >= 90 or mem2sec.stdout|int >= 90 or mem3sec.stdout|int >= 90\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14559068/" ]
74,677,244
<p>So below are two different text strings. I am trying to get the position of four digit number which is a dynamic number in every text string (8555) to extract the store name (Amazing Stores 2584 or what ever is in that place again dynamic no fixed width so can't use =right).</p> <hr /> <p>04/12/2022 13:01:00 00 K 18.30 18.30 USD 926 4 DLKY 1 000 05 8555 0 AMAZING STORES 2584 02/12/2022 13:01:00 00 K 18.30 18.30 USD 926 4 DLKY 1 000 05 8555 0 AMAZING STORES</p> <hr /> <p>Now my formula works for the second text string but not for the first. even thought everything is similar with just a change in date (04 instead of 02) and a number after store i.e (Amazing Stores 2584)</p> <h1>Workflow to find the first character of the Four digit number &amp; Store Name</h1> <h1></h1> <p><strong>Formula Used :</strong> =FIND(LOOKUP(10^15,MID(A2,ROW(INDIRECT(&quot;1:&quot;&amp;LEN(A2))),5)+0),A2)+6 in cell b1 <strong>Formula Len :</strong> =len(a1) in cell c1 <strong>Final Result :</strong> = right(a1,c1-b1) to extract the store name.</p> <p>**Few things to note: **</p> <ol> <li>I can't convert text to columns so this option wont work</li> <li>There is no Fixed length its dynamic as data is dynamic</li> <li>The Start position cannot be fixed length so can't use mid function either as amount could differ</li> <li>Text Split not an option as i can only use excel 2016 for this project</li> </ol> <hr /> <p>I am fairly new to excel so Any help from you experts is greatly appreciated. Thanks.</p> <p>Tried using multiple formula's and spent close to hours on trying to figure this out on my own, Please help me.</p>
[ { "answer_id": 74677102, "author": "Haim Cohen", "author_id": 3752715, "author_profile": "https://Stackoverflow.com/users/3752715", "pm_score": 1, "selected": false, "text": "ansible-playbook \"-l\" \"-v\" ansible-playbook -l /var/log/monitor.log -v my_playbook.yml\n name: 'Print message if MEMORY utilization is normal'\ndebug:\nmsg:\n- -------------------------------------------------------\n- Memory Utilization = ( ( Total - Free ) / Total * 100 ) = {{ memsec.stdout }}%\n- -------------------------------------------------------\nlog_path: /var/log/monitor.log\nwhen: memsec.stdout|int < 90 and mem1sec.stdout|int < 90 and mem2sec.stdout|int < 90 and mem3sec.stdout|int < 90\n" }, { "answer_id": 74680302, "author": "Motaz Hakim", "author_id": 17102062, "author_profile": "https://Stackoverflow.com/users/17102062", "pm_score": 0, "selected": false, "text": "ansible.builtin.log log - name: 'Write log message to file'\n log:\n msg: 'Memory utilization is not OK: {{ memhigusage.stdout }}%'\n path: /path/to/log/file/monitor.log\n Memory utilization is not OK: {{ memhigusage.stdout }}% monitor.log memsec.stdout mem1sec.stdout mem2sec.stdout mem3sec.stdout when - name: 'Write log message to file'\n log:\n msg: 'Memory utilization is not OK: {{ memhigusage.stdout }}%'\n path: /path/to/log/file/monitor.log\n when: memsec.stdout|int >= 90 or mem1sec.stdout|int >= 90 or mem2sec.stdout|int >= 90 or mem3sec.stdout|int >= 90\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19833096/" ]
74,677,273
<p>I'm having problems with this simple example.</p> <p>The program inquires as to how many letters are required to form a complete word. Then it will ask for each letter individually, which is fine, but I can't make the code save the value from the current character and the next one from the next iteration until the number of letters finishes the word and print it to confirm the word.</p> <p>E.g. Let's say house, which has 5 letters.</p> <pre><code>int numbersOfCharacters=5; int counter=0; char character; string phrase; while (counter &lt; numbersOfCharacters) { cout &lt;&lt; &quot;Introduce character's number&quot; &lt;&lt; counter &lt;&lt; &quot;: &quot;; cin &gt;&gt; character; counter = counter + 1; phrase=character+character; //I'm not sure if I need an array here. } cout &lt;&lt; &quot;Concatenated characters: &quot; &lt;&lt; phrase &lt;&lt; endl; </code></pre> <p>The output is:</p> <pre class="lang-none prettyprint-override"><code>Introduce the character number 1: h Introduce the character number 2: o Introduce the character number 3: u Introduce the character number 4: s Introduce the character number 5: e Concatenated characters: ? </code></pre> <p><strong>And the expected output should be</strong>:</p> <pre class="lang-none prettyprint-override"><code>Concatenated characters: house </code></pre>
[ { "answer_id": 74677959, "author": "Utsav katharotiya", "author_id": 18757478, "author_profile": "https://Stackoverflow.com/users/18757478", "pm_score": -1, "selected": false, "text": "int numbersOfCharacters=5;\nint counter=0;\nchar character;\nchar phrase[numbersOfCharacters];\n\nwhile (counter < numbersOfCharacters)\n{\n cout << \"Introduce character's number\" << counter << \": \";\n cin >> character; \n phrase[counter]=character;\n counter++;\n\n}\ncout << \"Concatenated characters: \" << phrase << endl;\n" }, { "answer_id": 74678144, "author": "Remy Lebeau", "author_id": 65863, "author_profile": "https://Stackoverflow.com/users/65863", "pm_score": 0, "selected": false, "text": "phrase=character+character; char h o house phrase=phrase+character; char string operator+ string::operator+= phrase += character; string::push_back() phrase.push_back(character);" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2965052/" ]
74,677,294
<p>I have some data, that needs to be clusterised into groups. That should be done by a few predifined conditions.</p> <p>Suppose we have the following table:</p> <pre><code>d = {'ID': [100, 101, 102, 103, 104, 105], 'col_1': [12, 3, 7, 13, 19, 25], 'col_2': [3, 1, 3, 3, 2, 4] } df = pd.DataFrame(data=d) df.head() </code></pre> <p><a href="https://i.stack.imgur.com/3WrcL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3WrcL.png" alt="enter image description here" /></a></p> <p>Here, I want to group <code>ID</code> based on the following ranges, conditions, on <code>col_1</code> and <code>col_2</code>.</p> <p>For <code>col_1</code> I divide values into following groups: <code>[0, 10]</code>, <code>[11, 15]</code>, <code>[16, 20]</code>, <code>[20, +inf]</code></p> <p>For <code>col_2</code> just use the <code>df['col_2'].unique()</code> values: <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[4]</code>.</p> <p>The desired groupping is in <code>group_num</code> column:</p> <p><a href="https://i.stack.imgur.com/hftcw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hftcw.png" alt="enter image description here" /></a></p> <p><em>notice, that <code>0</code> and <code>3</code> rows have the same group number and the order, in which group number is assigned</em>.</p> <p>For now, I only came up with <code>if-elif</code> function to pre-define all the groups. It's not the solution for now cause in my real task there are far more ranges and confitions.</p> <p>My code snippet, if it's relevant:</p> <pre><code># This logic is not working cause here I have to predefine all the groups configurations, aka numbers, # but I want to make groups &quot;dymanicly&quot;: # first group created and if the next row is not in that group -&gt; create new one def groupping(val_1, val_2): # not using match case here, cause my Python &lt; 3.10 if ((val_1 &gt;= 0) and (val_1 &lt;10)) and (val_2 == 1): return 1 elif ((val_1 &gt;= 0) and (val_1 &lt;10)) and (val_2 == 2): return 2 elif ... ... df['group_num'] = df.apply(lambda x: groupping(x.col_1, x.col_2), axis=1) </code></pre>
[ { "answer_id": 74677959, "author": "Utsav katharotiya", "author_id": 18757478, "author_profile": "https://Stackoverflow.com/users/18757478", "pm_score": -1, "selected": false, "text": "int numbersOfCharacters=5;\nint counter=0;\nchar character;\nchar phrase[numbersOfCharacters];\n\nwhile (counter < numbersOfCharacters)\n{\n cout << \"Introduce character's number\" << counter << \": \";\n cin >> character; \n phrase[counter]=character;\n counter++;\n\n}\ncout << \"Concatenated characters: \" << phrase << endl;\n" }, { "answer_id": 74678144, "author": "Remy Lebeau", "author_id": 65863, "author_profile": "https://Stackoverflow.com/users/65863", "pm_score": 0, "selected": false, "text": "phrase=character+character; char h o house phrase=phrase+character; char string operator+ string::operator+= phrase += character; string::push_back() phrase.push_back(character);" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9137206/" ]
74,677,299
<p>(<a href="https://i.stack.imgur.com/IFtgk.png" rel="nofollow noreferrer">https://i.stack.imgur.com/IFtgk.png</a>) can someone help me plzzzzz</p>
[ { "answer_id": 74677959, "author": "Utsav katharotiya", "author_id": 18757478, "author_profile": "https://Stackoverflow.com/users/18757478", "pm_score": -1, "selected": false, "text": "int numbersOfCharacters=5;\nint counter=0;\nchar character;\nchar phrase[numbersOfCharacters];\n\nwhile (counter < numbersOfCharacters)\n{\n cout << \"Introduce character's number\" << counter << \": \";\n cin >> character; \n phrase[counter]=character;\n counter++;\n\n}\ncout << \"Concatenated characters: \" << phrase << endl;\n" }, { "answer_id": 74678144, "author": "Remy Lebeau", "author_id": 65863, "author_profile": "https://Stackoverflow.com/users/65863", "pm_score": 0, "selected": false, "text": "phrase=character+character; char h o house phrase=phrase+character; char string operator+ string::operator+= phrase += character; string::push_back() phrase.push_back(character);" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20682749/" ]
74,677,310
<p>I'm working on a drag and drop function for SVG path, which lets a user move the co-ordinates of the path.</p> <p>Please consider the string below:</p> <pre><code>M162.323 150.513L232.645 8L303.504 149.837L461.168 173.5L347.156 284.5L373.605 440.728L233.5 367.854L91.7415 442L118.424 284.883L5.151 173.549Z </code></pre> <p>Would it be possible to replace a specific(let's say the 4<sup>th</sup>) occurence of a matched regex group using the <code>.replace</code> method?</p> <p><a href="https://regex101.com/r/rWQXbr/1" rel="nofollow noreferrer">Regex</a>:</p> <pre class="lang-none prettyprint-override"><code>[A-Z](-?\d*\.?\d*\s-?\d*\.?\d*) </code></pre>
[ { "answer_id": 74677959, "author": "Utsav katharotiya", "author_id": 18757478, "author_profile": "https://Stackoverflow.com/users/18757478", "pm_score": -1, "selected": false, "text": "int numbersOfCharacters=5;\nint counter=0;\nchar character;\nchar phrase[numbersOfCharacters];\n\nwhile (counter < numbersOfCharacters)\n{\n cout << \"Introduce character's number\" << counter << \": \";\n cin >> character; \n phrase[counter]=character;\n counter++;\n\n}\ncout << \"Concatenated characters: \" << phrase << endl;\n" }, { "answer_id": 74678144, "author": "Remy Lebeau", "author_id": 65863, "author_profile": "https://Stackoverflow.com/users/65863", "pm_score": 0, "selected": false, "text": "phrase=character+character; char h o house phrase=phrase+character; char string operator+ string::operator+= phrase += character; string::push_back() phrase.push_back(character);" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10301756/" ]
74,677,311
<p>what is the best TUI module to use with python , I used prompt-toolkit and I can't use so many things in it like Layout and I can't use a view in textual there is so many errors .</p> <p>I want to build TUI for myself, and I want a well documented and working TUI or CUI python module</p>
[ { "answer_id": 74677959, "author": "Utsav katharotiya", "author_id": 18757478, "author_profile": "https://Stackoverflow.com/users/18757478", "pm_score": -1, "selected": false, "text": "int numbersOfCharacters=5;\nint counter=0;\nchar character;\nchar phrase[numbersOfCharacters];\n\nwhile (counter < numbersOfCharacters)\n{\n cout << \"Introduce character's number\" << counter << \": \";\n cin >> character; \n phrase[counter]=character;\n counter++;\n\n}\ncout << \"Concatenated characters: \" << phrase << endl;\n" }, { "answer_id": 74678144, "author": "Remy Lebeau", "author_id": 65863, "author_profile": "https://Stackoverflow.com/users/65863", "pm_score": 0, "selected": false, "text": "phrase=character+character; char h o house phrase=phrase+character; char string operator+ string::operator+= phrase += character; string::push_back() phrase.push_back(character);" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20579852/" ]
74,677,361
<p>I am trying to connect my ESP32 to my Wifi Router using Arduino IDE but it is not connecting &amp; giving a connection failed or disconnected status. I also confirmed it is scanning all the available Wifi Networks but not connecting to my router. I even tried with another ESP32 board but the problem is still there.</p> <pre><code> I tried this code below. This code would scan/give the available Wifi networks and it did. Also, I was expecting this code to run smoothly but my ESP32 won't connect to my Wifi router. </code></pre> <pre><code>#include&lt;WiFi.h&gt; const char *ssid = &quot;my_SSID&quot;; const char *password = &quot;my_Password&quot;; void setup() { Serial.begin(115200); delay(2000); WiFi.mode(WIFI_STA); WiFi.disconnect(); delay(100); Serial.println(&quot;scan start&quot;); // WiFi.scanNetworks will return the number of networks found int n = WiFi.scanNetworks(); Serial.println(&quot;scan done&quot;); if (n == 0) { Serial.println(&quot;no networks found&quot;); } else { Serial.print(n); Serial.println(&quot; networks found&quot;);} // Connect to my network. WiFi.begin(ssid,password); // Check Status of your WiFi Connection int x = WiFi.status(); // If x=3 (Connected to Network) &amp; If x=6 (Disconnected from Network) Serial.print(&quot;WiFi Connection Status is &quot;); Serial.println(x); while(WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println(&quot;WiFi Connection Failed...&quot;); WiFi.disconnect(); WiFi.reconnect(); } //Print local IP address and start web server Serial.println(&quot;\nConnecting&quot;); Serial.println(&quot;&quot;); Serial.println(&quot;WiFi connected.&quot;); Serial.println(&quot;ESP32 IP address: &quot;); Serial.println(WiFi.localIP()); } void loop() {} </code></pre> <p><a href="https://i.stack.imgur.com/SgjUN.jpg" rel="nofollow noreferrer">1st image shows the output of my serial monitor. 2nd inamge shows the return value for WiFi.status function</a></p> <pre><code></code></pre>
[ { "answer_id": 74677959, "author": "Utsav katharotiya", "author_id": 18757478, "author_profile": "https://Stackoverflow.com/users/18757478", "pm_score": -1, "selected": false, "text": "int numbersOfCharacters=5;\nint counter=0;\nchar character;\nchar phrase[numbersOfCharacters];\n\nwhile (counter < numbersOfCharacters)\n{\n cout << \"Introduce character's number\" << counter << \": \";\n cin >> character; \n phrase[counter]=character;\n counter++;\n\n}\ncout << \"Concatenated characters: \" << phrase << endl;\n" }, { "answer_id": 74678144, "author": "Remy Lebeau", "author_id": 65863, "author_profile": "https://Stackoverflow.com/users/65863", "pm_score": 0, "selected": false, "text": "phrase=character+character; char h o house phrase=phrase+character; char string operator+ string::operator+= phrase += character; string::push_back() phrase.push_back(character);" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13869281/" ]
74,677,397
<p>I have two models interrelated <strong><code>items</code></strong> and <strong><code>broken</code></strong> :</p> <pre><code>class Items(models.Model): id = models.AutoField(primary_key=True) item_name = models.CharField(max_length=50, blank=False) item_price = models.IntegerField(blank=True) item_quantity_received = models.IntegerField(blank=False) item_quantity_available = models.IntegerField(blank=True) item_purchased_date = models.DateField(auto_now_add=True, blank=False) item_units = models.CharField(max_length=50, blank=False) def __str__(self): return self.item_name class Broken(models.Model): item = models.ForeignKey(Items, default=1, on_delete=models.CASCADE) item_quantity_broken = models.IntegerField(blank=True) item_broken_date = models.DateField(auto_now_add=True, blank=False) item_is_broken = models.BooleanField(default=True) date_repaired = models.DateField(auto_now=True, blank=True) def __str__(self): return self.item.item_name </code></pre> <p>I wrote this <strong>view</strong> function to retrieve data to a table into a template:</p> <pre><code> def broken_items(request): br = Broken.objects.select_related('item').all() print(br.values_list()) context = { 'title': 'broken', 'items': br, } return render(request, 'store/broken.html', context) </code></pre> <p>this is the executing query:</p> <pre><code> SELECT &quot;store_broken&quot;.&quot;id&quot;, &quot;store_broken&quot;.&quot;item_id&quot;, &quot;store_broken&quot;.&quot;item_quantity_broken&quot;, &quot;store_broken&quot;.&quot;item_broken_date&quot;, &quot;store_broken&quot;.&quot;item_is_broken&quot;, &quot;store_broken&quot;.&quot;date_repaired&quot;, &quot;store_items&quot;.&quot;id&quot;, &quot;store_items&quot;.&quot;item_name&quot;, &quot;store_items&quot;.&quot;item_price&quot;, &quot;store_items&quot;.&quot;item_quantity_received&quot;, &quot;store_items&quot;.&quot;item_quantity_available&quot;, &quot;store_items&quot;.&quot;item_purchased_date&quot;, &quot;store_items&quot;.&quot;item_units&quot; FROM &quot;store_broken&quot; INNER JOIN &quot;store_items&quot; ON (&quot;store_broken&quot;.&quot;item_id&quot; = &quot;store_items&quot;.&quot;id&quot;) </code></pre> <p>looks like it gives me all the fields I want. In debugger it shows data from both tables, so I wrote <strong><code>for</code></strong> loop in template,</p> <pre><code> {% for item in items %} &lt;tr&gt; &lt;td&gt;{{item.id}}&lt;/td&gt; &lt;td&gt;{{item.item_id}}&lt;/td&gt; &lt;td&gt;{{item.item_quantity_broken}}&lt;/td&gt; &lt;td&gt;{{item.item_broken_date}}&lt;/td&gt; &lt;td&gt;{{item.item_is_broken}}&lt;/td&gt; &lt;td&gt;{{item.date_repaired}}&lt;/td&gt; &lt;td&gt;{{item.item_name }}&lt;/td&gt; &lt;td&gt;{{item.item_item_quantity_received}}&lt;/td&gt; &lt;td&gt;{{item.item_quantity_available}}&lt;/td&gt; &lt;td&gt;{{item.item_purchased_date}}&lt;/td&gt; &lt;td&gt;{{item.items_item_units}}&lt;/td&gt; &lt;/tr&gt; {% endfor %} </code></pre> <p>The thing is this loop only gives me data from broken table only. I can't see data from Items table.</p> <p><a href="https://i.stack.imgur.com/fXilo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fXilo.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/p07ou.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/p07ou.png" alt="enter image description here" /></a></p> <p><strong>can someone help me to find the reason why other details are not showing?</strong></p>
[ { "answer_id": 74677959, "author": "Utsav katharotiya", "author_id": 18757478, "author_profile": "https://Stackoverflow.com/users/18757478", "pm_score": -1, "selected": false, "text": "int numbersOfCharacters=5;\nint counter=0;\nchar character;\nchar phrase[numbersOfCharacters];\n\nwhile (counter < numbersOfCharacters)\n{\n cout << \"Introduce character's number\" << counter << \": \";\n cin >> character; \n phrase[counter]=character;\n counter++;\n\n}\ncout << \"Concatenated characters: \" << phrase << endl;\n" }, { "answer_id": 74678144, "author": "Remy Lebeau", "author_id": 65863, "author_profile": "https://Stackoverflow.com/users/65863", "pm_score": 0, "selected": false, "text": "phrase=character+character; char h o house phrase=phrase+character; char string operator+ string::operator+= phrase += character; string::push_back() phrase.push_back(character);" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20018036/" ]
74,677,432
<p>Just wondering if there is any difference between:</p> <pre class="lang-dart prettyprint-override"><code> // == Add all picked idoes to the mix table setState(() { Future.forEach(result, (asset) async { final video = await MixTableVideo.create(original: asset); videos.add(video); }); }); </code></pre> <p>and:</p> <pre class="lang-dart prettyprint-override"><code> // == Add all picked idoes to the mix table Future.forEach(result, (asset) async { final video = await MixTableVideo.create(original: asset); videos.add(video); }); setState(() {}); </code></pre>
[ { "answer_id": 74677443, "author": "Begging", "author_id": 16606223, "author_profile": "https://Stackoverflow.com/users/16606223", "pm_score": 1, "selected": false, "text": "setState Future.forEach MixTableVideo.create Future.forEach setState setState setState" }, { "answer_id": 74677666, "author": "Stéphane de Luca", "author_id": 2525948, "author_profile": "https://Stackoverflow.com/users/2525948", "pm_score": 0, "selected": false, "text": " // == Add all picked videos to the mix table\n Future.forEach(result, (asset) async {\n final video = await MixTableVideo.create(original: asset);\n setState(() {\n videos.add(video);\n });\n });\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2525948/" ]
74,677,457
<p>I have a problem about getting all siblings from the main node and implementing the process n Breadth First Search algorithm written by Java.</p> <p>How can I implement that?</p> <p>I shared my code snippets shown below.</p> <p>Here is my Node class shown below.</p> <pre><code>public class Node{ Node(int data){ this.data = data; this.left = null; this.right = null; this.visited = false; } int data; Node left; Node right; boolean visited; // getter and setter } </code></pre> <p>Here is the initilaization process shown below.</p> <pre><code>Node node1 = new Node(1); Node node7 = new Node(7); Node node9 = new Node(9); Node node8 = new Node(8); Node node2 = new Node(2); Node node3 = new Node(3); node1.left = node7; node1.right = node9; node7.right = node8; node9.right = node3; node9.left = node2; </code></pre> <p>Here is the method shown below.</p> <pre><code>public static void bfs(Node root){ if (root == null){ return; } Node temp; //a binary tree with a inner generic node class Queue&lt;Node&gt; queue = new LinkedList&lt;&gt;(); //can't instantiate a Queue since abstract, so use LLQueue queue.add(root); root.visited = true; while (!queue.isEmpty()) { temp = queue.poll(); //remove the node from the queue // How can I get all siblings of the node like // for (Node sibling : temp.getSiblingNodes()) // sibling.visited=true; // queue.add(sibling); } // get the result as a list } </code></pre>
[ { "answer_id": 74677955, "author": "trincot", "author_id": 5459839, "author_profile": "https://Stackoverflow.com/users/5459839", "pm_score": 0, "selected": false, "text": " public static List<Node> bfs(Node root){\n Queue<Node> queue = new LinkedList<>();\n List<Node> result = new ArrayList<>();\n if (root == null){\n return result;\n }\n queue.add(root); // Don't visit this root node yet...\n while (!queue.isEmpty())\n {\n Node node = queue.poll();\n result.add(node); // Here we visit the node\n // Add the children of the visited node to the queue\n if (node.left != null) queue.add(node.left);\n if (node.right != null) queue.add(node.right);\n }\n return result;\n }\n for (Node node : bfs(node1)) {\n System.out.println(node.data);\n }\n" }, { "answer_id": 74678578, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 3, "selected": true, "text": "Node isVisited root current left right null isVisited true public static List<Node> bfs(Node root) {\n if (root == null) return Collections.emptyList();\n \n List<Node> siblings = new ArrayList<>();\n Queue<Node> queue = new ArrayDeque<>(); // performs better than LinkedList\n \n queue.add(root);\n // siblings.add(root); // uncomment this line ONLY if you need the root-Node to be present in the result\n root.visited = true;\n \n while (!queue.isEmpty()) {\n Node current = queue.poll();\n\n tryAdd(siblings, queue, current.left);\n tryAdd(siblings, queue, current.right);\n }\n return siblings;\n}\n\npublic static void tryAdd(List<Node> siblings, Queue<Node> queue, Node next) {\n if (next != null && !next.isVisited()) {\n queue.add(next);\n siblings.add(next);\n next.setVisited(true);\n }\n}\n left right tryAdd() Predicate public static final Predicate<Node> IS_NULL_OR_VISITED =\n Predicate.<Node>isEqual(null).or(Node::isVisited);\n\npublic static void tryAdd(List<Node> siblings, Queue<Node> queue, Node next) {\n if (IS_NULL_OR_VISITED.test(next)) return;\n \n queue.add(next);\n siblings.add(next);\n next.setVisited(true);\n}\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5719229/" ]
74,677,459
<p>I have the following tables:</p> <p><code>Students (id, name, surname, study_year, department_id)</code></p> <p><code>Courses(id, name)</code></p> <p><code>Course_Signup(id, student_id, course_id, year)</code></p> <p><code>Grades(signup_id, grade_type, mark, date)</code>, where <code>grade_type</code> can be 'e' (exam), 'l' (lab) or 'p' (project)</p> <p>I want to display the students with their yearly grade (average of the final grade for all courses), but only for those students that have passed ALL the courses that they have signed up for. For example, if a student signs up for 3 courses but only gets a final grade &gt;= 5 to 2 of those courses, that student should not appear in the result. I wrote this so far:</p> <pre><code>SELECT new_table.id, new_table.name, AVG(CASE WHEN grade_type = 'e' THEN new_table.mark END) AS &quot;Average Exam Grade&quot;, AVG(CASE WHEN GRADE_TYPE &lt;&gt; 'e' THEN new_table.mark END) AS &quot;Average Activity Grade&quot;, (2*AVG(CASE WHEN grade_type = 'e' THEN new_table.mark END) + AVG(CASE WHEN GRADE_TYPE &lt;&gt; 'e' THEN new_table.mark END))/3 AS &quot;Course Final Grade&quot; FROM ( SELECT s.id, c.name, g.grade_type, g.mark FROM Students s JOIN Course_Signup csn ON s.id = csn.student_id JOIN Courses c ON c.id = csn.course_id JOIN Grades g ON g.signup_id = csn.id ) new_table GROUP BY new_table.id, new_table.name HAVING ((2*AVG(CASE WHEN grade_type = 'e' THEN new_table.mark END) + AVG(CASE WHEN GRADE_TYPE &lt;&gt; 'e' THEN new_table.mark END))/3) &gt;= 5.00 ORDER BY new_table.id ASC </code></pre> <p>This gives me the students with every course that they promoted. What would be the easiest way to check that a student has a course final grade &gt;= 5, for every course that they signed up for?</p>
[ { "answer_id": 74677593, "author": "Dimi", "author_id": 19173885, "author_profile": "https://Stackoverflow.com/users/19173885", "pm_score": 2, "selected": true, "text": "MIN Recap_ SELECT\n new_table.id,\n new_table.name,\n AVG(CASE WHEN grade_type = 'e' THEN new_table.mark END) AS \"Average Exam Grade\",\n AVG(CASE WHEN GRADE_TYPE <> 'e' THEN new_table.mark END) AS \"Average Activity Grade\",\n (2*AVG(CASE WHEN grade_type = 'e' THEN new_table.mark END) + AVG(CASE WHEN GRADE_TYPE <> 'e' THEN new_table.mark END))/3 AS \"Course Final Grade\"\nFROM\n(\n SELECT s.id, c.name, g.grade_type, g.mark\n FROM Students s\n JOIN Course_Signup csn\n ON s.id = csn.student_id\n JOIN Courses c\n ON c.id = csn.course_id\n JOIN Grades g\n ON g.signup_id = csn.id\n) new_table\nGROUP BY new_table.id, new_table.name\nHAVING MIN(new_table.mark) >= 5.00\nORDER BY new_table.id ASC\n" }, { "answer_id": 74679359, "author": "p3consulting", "author_id": 4956336, "author_profile": "https://Stackoverflow.com/users/4956336", "pm_score": 0, "selected": false, "text": "select s.id, s.name, cs.year, g.grade_type, g.mark \nfrom students s\n join Course_Signup cs on cs.student_id = s.id\n join Grades g ON cs.id = g.signup_id\nwhere not exists(\n select 1 from Course_Signup cs\n where s.id = cs.student_id\n and not exists(\n select 1 from grades g \n where g.signup_id = cs.id \n and g.mark >= 5\n )\n);\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15070339/" ]
74,677,473
<p>I have a spot in my Angular application where I do not want the Angular sanitizer to sanitize my content. My goal is to create a custom trusted type policy in my angular project. But I could not figure out what is the best practice to create one, store them and use them in code later.</p> <p>I know it works by using (window as any) And doing I was doing it in a separate trusted-types-service:</p> <pre><code>export class TrustedTypesService { readonly fooPolicy: any; constructor() { this.fooPolicy = (window as any).trustedTypes.createPolicy('foo', (bar) =&gt; { // ideally some sanitizing by e.g. DOM Purify return bar; }); } } </code></pre> <p>But is this the right and best way to do it?</p> <p>I'd appreciate any help. Thank you :)</p>
[ { "answer_id": 74677593, "author": "Dimi", "author_id": 19173885, "author_profile": "https://Stackoverflow.com/users/19173885", "pm_score": 2, "selected": true, "text": "MIN Recap_ SELECT\n new_table.id,\n new_table.name,\n AVG(CASE WHEN grade_type = 'e' THEN new_table.mark END) AS \"Average Exam Grade\",\n AVG(CASE WHEN GRADE_TYPE <> 'e' THEN new_table.mark END) AS \"Average Activity Grade\",\n (2*AVG(CASE WHEN grade_type = 'e' THEN new_table.mark END) + AVG(CASE WHEN GRADE_TYPE <> 'e' THEN new_table.mark END))/3 AS \"Course Final Grade\"\nFROM\n(\n SELECT s.id, c.name, g.grade_type, g.mark\n FROM Students s\n JOIN Course_Signup csn\n ON s.id = csn.student_id\n JOIN Courses c\n ON c.id = csn.course_id\n JOIN Grades g\n ON g.signup_id = csn.id\n) new_table\nGROUP BY new_table.id, new_table.name\nHAVING MIN(new_table.mark) >= 5.00\nORDER BY new_table.id ASC\n" }, { "answer_id": 74679359, "author": "p3consulting", "author_id": 4956336, "author_profile": "https://Stackoverflow.com/users/4956336", "pm_score": 0, "selected": false, "text": "select s.id, s.name, cs.year, g.grade_type, g.mark \nfrom students s\n join Course_Signup cs on cs.student_id = s.id\n join Grades g ON cs.id = g.signup_id\nwhere not exists(\n select 1 from Course_Signup cs\n where s.id = cs.student_id\n and not exists(\n select 1 from grades g \n where g.signup_id = cs.id \n and g.mark >= 5\n )\n);\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12932907/" ]
74,677,485
<p>I'm trying to add a custom annotation for JPA repository methods to have a advice on @Query value.</p> <p>Below is the piece of code I tried</p> <p>MyFilterAspect class</p> <pre><code>@Aspect @Component public class MyFilterAspect { @Pointcut(&quot;execution(* *(..)) &amp;&amp; @within(org.springframework.data.jpa.repository.Query)&quot;) private void createQuery(){} @Around(&quot;createQuery()&quot;) public void applyFilter(JointPoint jp) { } } </code></pre> <p>The Respository code</p> <pre><code>@MyFilter @Query(Select * ...) MyObject findByNameAndClass(...) </code></pre> <p>So I keep getting error</p> <pre><code>createQuery() is never called At MyFilterAspect </code></pre> <p>I'm trying to update the Query value using the advice.</p> <p>What am I doing wrong?</p>
[ { "answer_id": 74677497, "author": "DotNetRussell", "author_id": 2051392, "author_profile": "https://Stackoverflow.com/users/2051392", "pm_score": 0, "selected": false, "text": "@within @annotation @Pointcut(\"execution(* *(..)) && @annotation(org.springframework.data.jpa.repository.Query)\")\nprivate void createQuery(){}\n" }, { "answer_id": 74677591, "author": "René Winkler", "author_id": 4461537, "author_profile": "https://Stackoverflow.com/users/4461537", "pm_score": 0, "selected": false, "text": " @Aspect\n @Component\n public class MyFilterAspect {\n @Pointcut(\"execution(* *(..)) && @annotation(org.springframework.data.jpa.repository.Query)\")\n private void createQuery(){}\n\n @Around(\"createQuery()\")\n public void applyFilter(ProceedingJoinPoint jp) {\n }\n}\n" }, { "answer_id": 74677933, "author": "p3consulting", "author_id": 4956336, "author_profile": "https://Stackoverflow.com/users/4956336", "pm_score": 2, "selected": true, "text": " \"execution(@AnnotationToCapture * *(..)) && @annotation(annotationParam)\"\n (..., AnnotationToCapture annotationParam, ...)\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6070471/" ]
74,677,489
<p>I am trying to implement a incremental query in DBT using Jinja.</p> <p>Considering there are tables getting created every month in warehouse with year and month suffix and I need to write a logic to union the new table which gets created every month to execute the DBT model. Below is the code which I have started with</p> <pre><code>#initialize the months in a list {% set months= ['03','04','05','06','07','08','09','10','11','12','01','02'] %} #first select query for Feb month of 2022 SELECT *, '2022-02-01' AS ref_month FROM source_table_2022_02 #initilalize year variable to 2022 {% set year= namespace(items=2022) %} #loop through the months to generate dynamic query for upcoming months {% for month in months %} #if month is Jan increment the year {% if month == '01' %} {% set year.items = year.items + 1 %} {% endif %} UNION ALL SELECT *, '{{ year.items }}-{{ month }}-01' AS ref_month FROM source_table_{{ year.items }}_{{ month }} {% endfor %} </code></pre> <p>output of above logic is as below</p> <pre><code>SELECT *, '2022-02-01' AS ref_month FROM source_table_2022_02 UNION ALL SELECT *, '2022-03-01' AS ref_month FROM source_table_2022_03 UNION ALL SELECT *, '2022-04-01' AS ref_month FROM source_table_2022_04 . . . UNION ALL SELECT *, '2023-02-01' AS ref_month FROM source_table_2023_02 </code></pre> <p>I need help in stopping the for loop when we reach the current month i.e Dec(because there is no current_month method in Jinja and I need to implement this logic in DBT models.sql file and not a python file), instead of looping through the upcoming months.</p> <p>Note: as mentioned earlier the source table gets created every month with year and month suffix</p> <p>I also want to continue the loop after 2023 Feb in the upcoming months. Current logic stops immediately after the list iteration ends i.e 2023 Feb</p>
[ { "answer_id": 74677497, "author": "DotNetRussell", "author_id": 2051392, "author_profile": "https://Stackoverflow.com/users/2051392", "pm_score": 0, "selected": false, "text": "@within @annotation @Pointcut(\"execution(* *(..)) && @annotation(org.springframework.data.jpa.repository.Query)\")\nprivate void createQuery(){}\n" }, { "answer_id": 74677591, "author": "René Winkler", "author_id": 4461537, "author_profile": "https://Stackoverflow.com/users/4461537", "pm_score": 0, "selected": false, "text": " @Aspect\n @Component\n public class MyFilterAspect {\n @Pointcut(\"execution(* *(..)) && @annotation(org.springframework.data.jpa.repository.Query)\")\n private void createQuery(){}\n\n @Around(\"createQuery()\")\n public void applyFilter(ProceedingJoinPoint jp) {\n }\n}\n" }, { "answer_id": 74677933, "author": "p3consulting", "author_id": 4956336, "author_profile": "https://Stackoverflow.com/users/4956336", "pm_score": 2, "selected": true, "text": " \"execution(@AnnotationToCapture * *(..)) && @annotation(annotationParam)\"\n (..., AnnotationToCapture annotationParam, ...)\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13135040/" ]
74,677,506
<p><a href="https://i.stack.imgur.com/dehc7.png" rel="nofollow noreferrer">this is my component file and when I run this code displaying error products.map is not a function. </a></p>
[ { "answer_id": 74677543, "author": "Wael Ben Mustapha", "author_id": 15388696, "author_profile": "https://Stackoverflow.com/users/15388696", "pm_score": 1, "selected": false, "text": "products?.map\n" }, { "answer_id": 74677580, "author": "Naju Bhadarka", "author_id": 20497393, "author_profile": "https://Stackoverflow.com/users/20497393", "pm_score": 0, "selected": false, "text": ".map products (it is {} but you are expecting [])" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18009537/" ]
74,677,544
<p>With boto3 we can create a client for any service of our choice. For example,</p> <pre><code>client = boto3.client('s3') </code></pre> <p>Then if we check the type of the returned object,</p> <pre><code>print(type(client)) &lt;class 'botocore.client.S3'&gt; </code></pre> <p>But since there is no <code>botocore.client.S3</code> (since it is dynamically created), how do we strongly type the client?</p> <p>The closest I can think of is <code>botocore.client.BaseClient</code> as shown below, which is far from <code>S3</code> type.</p> <pre><code>from botocore.client import BaseClient client: BaseClient = boto3.client('s3') </code></pre> <p>Any idea?</p>
[ { "answer_id": 74677543, "author": "Wael Ben Mustapha", "author_id": 15388696, "author_profile": "https://Stackoverflow.com/users/15388696", "pm_score": 1, "selected": false, "text": "products?.map\n" }, { "answer_id": 74677580, "author": "Naju Bhadarka", "author_id": 20497393, "author_profile": "https://Stackoverflow.com/users/20497393", "pm_score": 0, "selected": false, "text": ".map products (it is {} but you are expecting [])" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219052/" ]
74,677,569
<p>I am trying to select elements in the loop and pass them to setTimeout.</p> <p>Why doesn't the following work as it is supposed to?</p> <p>Is it because el.querySelector('.b') is slower than setTimeout?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var ids = document.querySelectorAll('.a'), span ids.forEach(el =&gt; { span = el.querySelector('.b') setTimeout(function() { span.classList.add('visible'); }, 20, span); })</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.visible{ color:red; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;p class="a"&gt;&lt;span class="b"&gt;1&lt;/span&gt;&lt;/p&gt; &lt;p class="a"&gt;&lt;span class="b"&gt;2&lt;/span&gt;&lt;/p&gt; &lt;p class="a"&gt;&lt;span class="b"&gt;3&lt;/span&gt;&lt;/p&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74677543, "author": "Wael Ben Mustapha", "author_id": 15388696, "author_profile": "https://Stackoverflow.com/users/15388696", "pm_score": 1, "selected": false, "text": "products?.map\n" }, { "answer_id": 74677580, "author": "Naju Bhadarka", "author_id": 20497393, "author_profile": "https://Stackoverflow.com/users/20497393", "pm_score": 0, "selected": false, "text": ".map products (it is {} but you are expecting [])" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1009466/" ]
74,677,589
<p>I want to make a regex that recognize some patterns and some not.</p> <pre><code>_*[a-zA-Z][a-zA-Z0-9_][^-]*.*(?&lt;!_) </code></pre> <p>The sample of patterns that i want to recognize:</p> <pre><code>a100__version_2 _a100__version2 </code></pre> <p>And the sample of patterns that i dont want to recognize:</p> <pre><code>100__version_2 a100__version2_ _100__version_2 a100--version-2 </code></pre> <p>The regex works for all of them except this one:</p> <pre><code>a100--version-2 </code></pre> <p>So I don't want to match the dashes.</p> <p>I tried <code>_*[a-zA-Z][a-zA-Z0-9_][^-]*.*(?&lt;!_)</code> so the problem is at [^-]</p>
[ { "answer_id": 74677644, "author": "kppro", "author_id": 10955397, "author_profile": "https://Stackoverflow.com/users/10955397", "pm_score": 0, "selected": false, "text": "a100__version_2 // matches\n_a100__version2 // matches\n100__version_2 // does not match\na100__version2_ // does not match\n_100__version_2 // does not match\na100--version-2 // does not match\n" }, { "answer_id": 74677670, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 1, "selected": false, "text": "[^-]* ^_*[a-zA-Z][a-zA-Z0-9_][^-\\s]*$(?<!_)\n \\w* ^_*[a-zA-Z]\\w*$(?<!_)\n ^ _* [a-zA-Z] \\w* [a-zA-Z0-9_]* $ (?<!_) _" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20451221/" ]
74,677,598
<p>Why, when I use <code>double i</code> the output is (an approximation to) the value of <em>e</em>?</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main () { double s=0; double i=1; for (int m=1;m&lt;5;m++) { i=m*i; s=s+1/i; } cout&lt;&lt;s+1; return 0; } </code></pre> <p>But when I use <code>int i</code>, the output is 2:</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main () { double s=0; int i=1; for (int m=1;m&lt;5;m++) { i=m*i; s=s+1/i; } cout&lt;&lt;s+1; return 0; } </code></pre> <p>The variable that stores the value of <em>e</em> is <code>s</code>, which is <code>double</code>, so I was expecting that the datatype of <code>i</code> doesn't matter.</p>
[ { "answer_id": 74677644, "author": "kppro", "author_id": 10955397, "author_profile": "https://Stackoverflow.com/users/10955397", "pm_score": 0, "selected": false, "text": "a100__version_2 // matches\n_a100__version2 // matches\n100__version_2 // does not match\na100__version2_ // does not match\n_100__version_2 // does not match\na100--version-2 // does not match\n" }, { "answer_id": 74677670, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 1, "selected": false, "text": "[^-]* ^_*[a-zA-Z][a-zA-Z0-9_][^-\\s]*$(?<!_)\n \\w* ^_*[a-zA-Z]\\w*$(?<!_)\n ^ _* [a-zA-Z] \\w* [a-zA-Z0-9_]* $ (?<!_) _" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20682865/" ]
74,677,610
<p><a href="https://pub.dev/packages/sqflite" rel="nofollow noreferrer">sqflite</a> requires WidgetsFlutterBinding.ensureInitialized() but not <a href="https://pub.dev/packages/xmpp_plugin" rel="nofollow noreferrer">xmpp_plugin</a>, <a href="https://pub.dev/packages/shared_preferences/example" rel="nofollow noreferrer">shared_preferences</a> or <a href="https://pub.dev/packages/device_info_plus" rel="nofollow noreferrer">device_info_plus</a> ? As per my knowledge plugins require platform specific channels due to which WidgetsFlutterBinding.ensureInitialized() is placed in main() function of flutter app.</p>
[ { "answer_id": 74679130, "author": "jamesdlin", "author_id": 179715, "author_profile": "https://Stackoverflow.com/users/179715", "pm_score": 0, "selected": false, "text": "WidgetsFlutterBinding.ensureInitialized WidgetsFlutterBinding WidgetsFlutterBinding.ensureInitialized runApp" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10065622/" ]
74,677,621
<p>I've never tried Javascript before and looked around, but the tutorials I've found would take me weeks to figure out (attention/focus issues + I don't even know what words I want to search for) and none of the solutions I've searched for solved it, and I don't know enough to extrapolate it from other answers.</p> <p>Can someone give me an example of this code (from w3School) extended to also toggle more dropdown menus? It has to be usable with keyboard like this one is.</p> <p><strong>Currently it's only handling the menu with an ID of &quot;dropperso&quot; and can open the Personal menu, I need the &quot;openMenu&quot; function to also react to the ID &quot;dropsites&quot; and be able to open the Other Sites menu. A note that the button and affected ID-having div are siblings.</strong></p> <p>No JQuery please.</p> <p>JS:</p> <pre><code>function openMenu() { document.getElementById(&quot;dropperso&quot;).classList.toggle(&quot;dropopen&quot;); } </code></pre> <p>HTML:</p> <pre><code> &lt;div class=&quot;dropdown&quot;&gt; &lt;button onclick=&quot;openMenu()&quot; class=&quot;drophover&quot;&gt;Other Sites&lt;/button&gt; &lt;div id=&quot;dropsites&quot; class=&quot;dropdown-content&quot;&gt; A link &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;dropdown&quot;&gt; &lt;button onclick=&quot;openMenu()&quot; class=&quot;drophover&quot;&gt;Personal&lt;/button&gt; &lt;div id=&quot;dropperso&quot; class=&quot;dropdown-content&quot; style=&quot;right: 0;&quot;&gt; A link A link &lt;/div&gt; &lt;/div&gt; </code></pre> <p>All that the .dropopen css class does is change the display of .dropdown-content from none to block.</p> <p>I tried to search for my specific problem and all I found was either way beyond my ability to understand, &quot;use JQuery&quot; (I'm limited and can't use JQuery), or &quot;use this other code (that doesn't work for mine)&quot;.</p> <p>It works if I just copy the whole thing and make one function for each menu, but I get the feeling that's kinda bad spaghetti coding, and I can't compress this on my own without an example that works to learn from.</p> <p>I'd be VERY grateful if you could solve that for me so I can use that later, and even MORE grateful if you could either explain how you made it work or link to the specific parts of documentation that explain what you're using.</p>
[ { "answer_id": 74679130, "author": "jamesdlin", "author_id": 179715, "author_profile": "https://Stackoverflow.com/users/179715", "pm_score": 0, "selected": false, "text": "WidgetsFlutterBinding.ensureInitialized WidgetsFlutterBinding WidgetsFlutterBinding.ensureInitialized runApp" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20675906/" ]
74,677,640
<p>I would like to know if it was possible via the OS module to iterate on several lines with the command prompt Here is an example of what I would have liked to do but which does not work (non-persistent session):</p> <pre class="lang-py prettyprint-override"><code>from os import popen, system, getlogin system(f'cd C:/Users/{getlogin()}') print(popen('pip freeze')) </code></pre>
[ { "answer_id": 74678856, "author": "tttony", "author_id": 453348, "author_profile": "https://Stackoverflow.com/users/453348", "pm_score": 1, "selected": false, "text": "check_output subprocess cmd /C from os import getlogin\nfrom subprocess import check_output\n\ncmd_str = fr'cmd.exe /C \"cd C:\\Users\\{getlogin()} && pip freeze\"'\n\noutput = check_output(cmd_str, shell=True).decode()\nfor line in output.split('\\r\\n'):\n print(line)\n absl-py==1.3.0\naiohttp==3.7.3\naltgraph==0.17\nastroid==2.4.2\nastunparse==1.6.3\n.....\n" }, { "answer_id": 74678896, "author": "dsillman2000", "author_id": 3925758, "author_profile": "https://Stackoverflow.com/users/3925758", "pm_score": 0, "selected": false, "text": "popen system os subprocess stdin stdout import subprocess\nfrom os import getlogin\n\n# Spawn a new shell process\np = subprocess.Popen(['cmd'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n\n# Change the working directory to the user's home directory\np.stdin.write(f'cd C:/Users/{getlogin()}\\n')\n\n# Run the pip freeze command\np.stdin.write('pip freeze\\n')\n\n# Read the output of the command\noutput = p.stdout.read()\n\n# Print the output to the console\nprint(output)\n subprocess stdin stdout cd pip freeze stdout" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20683045/" ]
74,677,667
<p>I have got an assignment from uni which mentions that I have to compare a given set of passwords to the password given by the user. The set of passwords are predetermined in the question as follows</p> <pre class="lang-c prettyprint-override"><code>const char *passwd[NUM_PASSWDS] = { &quot;123foo&quot;, &quot;bar456&quot;, &quot;bla_blubb&quot; }; </code></pre> <p>and has to be compared with input from user...</p> <p>So I have written my code as follows;</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #define NUM_PASSWDS 3 const char *passwd[NUM_PASSWDS] = { &quot;123foo&quot;, &quot;bar456&quot;, &quot;bla_blubb&quot; }; int pwdquery(char pass[]) { for (int i = 0; i &lt; 2; i++) { if (passwd[i] == pass[i]) { return printf(&quot;correct&quot;); } } } int main() { char a[100]; for (int i = 0; i &lt; 3; i++) { printf(&quot;Please enter password&quot;); scanf(&quot;%s&quot;, a); } pwdquery(a); } </code></pre> <p>When I tried running my code, it shows an error...</p> <p>Thank you for your time</p>
[ { "answer_id": 74678856, "author": "tttony", "author_id": 453348, "author_profile": "https://Stackoverflow.com/users/453348", "pm_score": 1, "selected": false, "text": "check_output subprocess cmd /C from os import getlogin\nfrom subprocess import check_output\n\ncmd_str = fr'cmd.exe /C \"cd C:\\Users\\{getlogin()} && pip freeze\"'\n\noutput = check_output(cmd_str, shell=True).decode()\nfor line in output.split('\\r\\n'):\n print(line)\n absl-py==1.3.0\naiohttp==3.7.3\naltgraph==0.17\nastroid==2.4.2\nastunparse==1.6.3\n.....\n" }, { "answer_id": 74678896, "author": "dsillman2000", "author_id": 3925758, "author_profile": "https://Stackoverflow.com/users/3925758", "pm_score": 0, "selected": false, "text": "popen system os subprocess stdin stdout import subprocess\nfrom os import getlogin\n\n# Spawn a new shell process\np = subprocess.Popen(['cmd'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n\n# Change the working directory to the user's home directory\np.stdin.write(f'cd C:/Users/{getlogin()}\\n')\n\n# Run the pip freeze command\np.stdin.write('pip freeze\\n')\n\n# Read the output of the command\noutput = p.stdout.read()\n\n# Print the output to the console\nprint(output)\n subprocess stdin stdout cd pip freeze stdout" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20659169/" ]
74,677,671
<p>I want to combine two dataframes:</p> <pre><code>df1=pd.DataFrame({'A':['a','a',],'B':['b','b']}) df2=pd.DataFrame({'B':['b','b'],'A':['a','a']}) pd.concat([df1,df2],ignore_index=True) </code></pre> <p>result:</p> <p><a href="https://i.stack.imgur.com/iALM5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iALM5.png" alt="enter image description here" /></a></p> <p>But I want the output to be like this (I want the same code as SQL's union/union all):</p> <p><a href="https://i.stack.imgur.com/aakwd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aakwd.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74677820, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": 0, "selected": false, "text": "pandas.concat list_dfs = [df1, df2]\n\nout = (\n pd.concat([pd.DataFrame(sub_df.to_numpy()) for sub_df in list_dfs], \n ignore_index=True)\n .set_axis(df1.columns, axis=1)\n )\n print(out)\n\n A B\n0 a b\n1 a b\n2 b a\n3 b a\n" }, { "answer_id": 74680014, "author": "PaulS", "author_id": 11564487, "author_profile": "https://Stackoverflow.com/users/11564487", "pm_score": 1, "selected": false, "text": "numpy pd.DataFrame pd.DataFrame(np.vstack([df1.values,df2.values]), columns = df1.columns)\n A B\n0 a b\n1 a b\n2 b a\n3 b a\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18756733/" ]
74,677,696
<p>I want to get all product names with category if even product doesn't have a category</p> <p><a href="https://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx" rel="nofollow noreferrer">get informatoin for creation from here</a></p> <pre><code>public class Product { public int ProductId { get; set; } public string Name { get; set; } public virtual ICollection&lt;CategoryProduct&gt; CategoryProducts { get; set; } } public class CategoryProduct { public int CategoryProductId { get; set; } public string Name { get; set; } public virtual ICollection&lt;Product&gt; Products { get; set; } } internal class EFDbContext : DbContext, IDBProductContext { public DbSet&lt;Product&gt; Products { get; set; } public DbSet&lt;CategoryProduct&gt; CategoryProducts { get; set ; } public EFDbContext() { Database.SetInitializer&lt;EFDbContext&gt;(new DropCreateDatabaseIfModelChanges&lt;EFDbContext&gt;()); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity&lt;Product&gt;().HasMany(p =&gt; p.CategoryProducts) .WithMany(c =&gt; c.Products) .Map(pc =&gt; { pc.MapLeftKey(&quot;ProductRefId&quot;); pc.MapRightKey(&quot;CategoryProductRefId&quot;); pc.ToTable(&quot;CategoryProductTable&quot;); }); base.OnModelCreating(modelBuilder); } } </code></pre> <p>If I write a SQL query like this, I get all of them from joined EF table</p> <pre><code>SELECT p.Name, cp.Name FROM CategoryProductTable AS cpt, CategoryProducts AS cp, Products as p WHERE p.ProductId = cpt.ProductRefId AND cp.CategoryProductId = cpt.CategoryProductRefId </code></pre> <p>but I want to get all from product names with category if even product doesn't have a category</p> <p>UPDATED: thanks for SQL solution @Nick Scotney, but now I would want know how it do it in Linq</p>
[ { "answer_id": 74677805, "author": "Dimi", "author_id": 19173885, "author_profile": "https://Stackoverflow.com/users/19173885", "pm_score": 0, "selected": false, "text": "p.ProductId = cpt.ProductRefId SELECT p.Name, cp.Name \nFROM CategoryProductTable as cpt, CategoryProducts as cp, Products as p\nWHERE cp.CategoryProductId = cpt.CategoryProductRefId\n" }, { "answer_id": 74677817, "author": "Nick Scotney", "author_id": 4990925, "author_profile": "https://Stackoverflow.com/users/4990925", "pm_score": 3, "selected": true, "text": "SELECT\n p.Name,\n cp.Name\nFROM\n Products p\n LEFT OUTER JOIN CategoryProductTable cpt ON p.ProductId = cpt.ProductRefId\n LEFT OUTER JOIN CategoryProducts cp ON cpt.CategoryProductRefId = cp.CategoryProductId\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8528114/" ]
74,677,712
<p>Say I have a set of rules that have a validation function that returns <code>IO[Boolean]</code> at runtime.</p> <pre><code>case class Rule1() { def validate(): IO[Boolean] = IO.pure(false) } case class Rule2() { def validate(): IO[Boolean] = IO.pure(false) } case class Rule3() { def validate(): IO[Boolean] = IO.pure(true) } val rules = List(Rule1(), Rule2(), Rule3()) </code></pre> <p>Now I have to iterate through these rules and see &quot;<em>if any of these rules</em>&quot; hold valid and if not then throw exception!</p> <pre><code>for { i &lt;- rules.map(_.validate()).sequence _ &lt;- if (i.contains(true)) IO.unit else IO.raiseError(new RuntimeException(&quot;Failed&quot;)) } yield () </code></pre> <p>The problem with the code snippet above is that it is trying to evaluate all the rules! What I really want is to exit at the encounter of the first <code>true</code> validation.</p> <p>Not sure how to achieve this using cats effects in Scala.</p>
[ { "answer_id": 74677913, "author": "Dmytro Mitin", "author_id": 5249621, "author_profile": "https://Stackoverflow.com/users/5249621", "pm_score": 2, "selected": false, "text": "def firstTrue(rules: List[{def validate(): IO[Boolean]}]): IO[Unit] = rules match {\n case r :: rs => for {\n b <- r.validate()\n res <- if (b) IO.unit else firstTrue(rs)\n } yield res\n case _ => IO.raiseError(new RuntimeException(\"Failed\"))\n}\n" }, { "answer_id": 74677917, "author": "Mateusz Kubuszok", "author_id": 1305121, "author_profile": "https://Stackoverflow.com/users/1305121", "pm_score": 3, "selected": false, "text": "findM for {\n opt <- rules.findM(_.validate())\n _ <- opt match {\n case Some(_) => IO.unit\n case None => IO.raiseError(new RuntimeException(\"Failed\")\n }\n} yield ()\n foldLeft flatMap rules.foldLeft(IO.pure(false)) { (valueSoFar, nextValue) =>\n valueSoFar.flatMap {\n case true => IO.pure(true) // can skip evaluating nextValue \n case false => nextValue.validate() // need to find the first true IO yet\n }\n}.flatMap {\n case true => IO.unit\n case false => IO.raiseError(new RuntimeException(\"Failed\")\n}\n findM tailRecM" }, { "answer_id": 74678016, "author": "Luis Miguel Mejía Suárez", "author_id": 4111404, "author_profile": "https://Stackoverflow.com/users/4111404", "pm_score": 2, "selected": false, "text": "IO def validateRules(rules: List[Rule]): IO[Unit] =\n rules.traverse_ { rule =>\n rule.validate().flatMap { flag =>\n IO.raiseUnless(flag)(new RuntimeException(\"Failed\"))\n }\n }\n" }, { "answer_id": 74678080, "author": "Andrey Tyukin", "author_id": 2707792, "author_profile": "https://Stackoverflow.com/users/2707792", "pm_score": 4, "selected": true, "text": "existsM exists for {\n t <- rules.existsM(_.validate())\n _ <- IO.raiseUnless(t)(new RuntimeException(\"Failed\"))\n} yield ()\n true raiseUnless if-else" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1879109/" ]
74,677,738
<p>I would like to create a new column called &quot;season_new&quot;, where I want to maintain the non-null season and extract the season for null values from the programme name. My dataframe is something like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>programme</th> <th>season</th> </tr> </thead> <tbody> <tr> <td>grey's anatomy s1</td> <td>null</td> </tr> <tr> <td>friends season 1</td> <td>1</td> </tr> <tr> <td>grey's anatomy s2</td> <td>null</td> </tr> <tr> <td>big bang theory s2</td> <td>2</td> </tr> <tr> <td>big bang theory</td> <td>1</td> </tr> <tr> <td>peaky blinders</td> <td>1</td> </tr> </tbody> </table> </div> <p>I'd try using regex.</p> <p><code>dt['season_new'] = dt['programme'].str.extract(r'(season\s?\d+|s\s?\d+)')</code></p> <p>But it gave me this result:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>programme</th> <th>season</th> <th>season_new</th> </tr> </thead> <tbody> <tr> <td>grey's anatomy s1</td> <td>null</td> <td>1</td> </tr> <tr> <td>friends season 1</td> <td>1</td> <td>1</td> </tr> <tr> <td>grey's anatomy s2</td> <td>null</td> <td>2</td> </tr> <tr> <td>big bang theory s2</td> <td>2</td> <td>2</td> </tr> <tr> <td>big bang theory</td> <td>1</td> <td>null</td> </tr> <tr> <td>peaky blinders</td> <td>1</td> <td>null</td> </tr> </tbody> </table> </div> <p>The result that I expected is:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>programme</th> <th>season</th> <th>season_new</th> </tr> </thead> <tbody> <tr> <td>grey's anatomy s1</td> <td>null</td> <td>1</td> </tr> <tr> <td>friends season 1</td> <td>1</td> <td>1</td> </tr> <tr> <td>grey's anatomy s2</td> <td>null</td> <td>2</td> </tr> <tr> <td>big bang theory s2</td> <td>2</td> <td>2</td> </tr> <tr> <td>big bang theory</td> <td>1</td> <td>1</td> </tr> <tr> <td>peaky blinders</td> <td>1</td> <td>1</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74677997, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": -1, "selected": false, "text": "pandas.Series.fillna value dt['season_new'] = (\n dt['programme']\n .str.extract(r'[season\\s?|s](\\d+)', expand=False)\n .fillna(dt['season'])\n .astype(int)\n )\n pandas.Series.pop dt['season_new'] = (\n dt['programme']\n .str.extract(r'[season\\s?|s](\\d+)', expand=False)\n .fillna(dt.pop('season'))\n .astype(int)\n )\n print(dt)\n\n programme season_new\n0 grey's anatomy s1 1\n1 friends season 1 1\n2 grey's anatomy s2 2\n3 big bang theory s2 2\n4 big bang theory 1\n5 peaky blinders 1\n \n" }, { "answer_id": 74678310, "author": "Colin", "author_id": 16178733, "author_profile": "https://Stackoverflow.com/users/16178733", "pm_score": 0, "selected": false, "text": "0 grey's anatomy s1 NaN s1\n1 friends season 1 1.0 season 1\n2 grey's anatomy s2 NaN s2\n3 big bang theory s2 2.0 s2\n4 big bang theory 1.0 NaN\n5 peaky blinders 1.0 NaN\n df = pd.read_excel(source_file)\n\n# Empty list for data capture\nseason_data = []\n\n# Loop thought all rows\nfor idx in df.index:\n\n # Grab value to check\n check_val = df[\"season\"][idx]\n\n # If value is not null then keep it\n if pd.notnull(check_val):\n\n # Add value to list\n season_data.append(int(check_val))\n\n else:\n # Extract digits from programme description\n extract_result = \"\".join(i for i in df[\"programme\"][idx] if i.isdigit())\n\n # Add value to list\n season_data.append(extract_result)\n\n# Add full list to dataframe\ndf[\"season_new\"] = season_data\n\nprint(df)\n programme season season_new\n0 grey's anatomy s1 NaN 1\n1 friends season 1 1.0 1\n2 grey's anatomy s2 NaN 2\n3 big bang theory s2 2.0 2\n4 big bang theory 1.0 1\n5 peaky blinders 1.0 1\n" }, { "answer_id": 74678334, "author": "Panda Kim", "author_id": 20430449, "author_profile": "https://Stackoverflow.com/users/20430449", "pm_score": -1, "selected": false, "text": "pat = r'[season|s]\\s?(\\d+$)'\ndf.assign(season_new=df['season'].fillna(df['programme'].str.extract(pat)[0]))\n programme season season_new\ngrey's anatomy s1 NaN 1\nfriends season 1 1 1\ngrey's anatomy s2 NaN 2\nbig bang theory s2 2 2\nbig bang theory 1 1\npeaky blinders 1 1\n" }, { "answer_id": 74678773, "author": "Daila", "author_id": 20600582, "author_profile": "https://Stackoverflow.com/users/20600582", "pm_score": 0, "selected": false, "text": "apply() data['season_new'] = data.apply(lambda x: x.season if pd.notna(x.season) else re.search(r'(season\\s?\\d+|s\\s?\\d+)',x.programme).group(1), axis=1)\n programme season season_new\n0 grey's anatomy s1 NaN s1\n1 friends season 1 1.0 1.0\n2 grey's anatomy s2 NaN s2\n3 big bang theory s2 2.0 2.0\n4 big bang theory 1.0 1.0\n5 peaky blinders 1.0 1.0\n data['season_new'] = data.apply(lambda x: x.season if pd.notna(x.season) else (x.programme[-1] if x.programme[-1].isdigit() else np.nan), axis=1).astype('int')\n programme season season_new\n0 grey's anatomy s1 NaN 1\n1 friends season 1 1.0 1\n2 grey's anatomy s2 NaN 2\n3 big bang theory s2 2.0 2\n4 big bang theory 1.0 1\n5 peaky blinders 1.0 1\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18239197/" ]
74,677,763
<p>I am creating a face detection algorithm which should take in images from a folder as input but I get this error:</p> <pre><code>import dlib import argparse import cv2 import sys import time import process_dlib_boxes # construct the argument parser parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', default=r&quot;C:\Users\awais\OneDrive\Documents\Greenwich Uni work\Face detec work\images folder&quot;, help='path to the input image') parser.add_argument('-u', '--upsample', type=float, help='factor by which to upsample the image, default None, ' + 'pass 1, 2, 3, ...') args = vars(parser.parse_args()) # read the image and convert to RGB color format image = cv2.imread(args['input']) image_cvt = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # path for saving the result image save_name = f&quot;outputs/{args['input'].split('/')[-1].split('.')[0]}_u{args['upsample']}.jpg&quot; # initilaize the Dlib face detector according to the upsampling value detector = dlib.get_frontal_face_detector() </code></pre> <p>i get this error:</p> <pre><code>[ WARN:[email protected]] global D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp (239) cv::findDecoder imread_('C:\Users\awais\OneDrive\Documents\Greenwich Uni work\Face detec work\images folder'): can't open/read file: check file path/integrity Traceback (most recent call last): File &quot;C:\Users\awais\OneDrive\Documents\Greenwich Uni work\Face detec work\face_det_image.py&quot;, line 20, in &lt;module&gt; image_cvt = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) cv2.error: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor' </code></pre>
[ { "answer_id": 74677997, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": -1, "selected": false, "text": "pandas.Series.fillna value dt['season_new'] = (\n dt['programme']\n .str.extract(r'[season\\s?|s](\\d+)', expand=False)\n .fillna(dt['season'])\n .astype(int)\n )\n pandas.Series.pop dt['season_new'] = (\n dt['programme']\n .str.extract(r'[season\\s?|s](\\d+)', expand=False)\n .fillna(dt.pop('season'))\n .astype(int)\n )\n print(dt)\n\n programme season_new\n0 grey's anatomy s1 1\n1 friends season 1 1\n2 grey's anatomy s2 2\n3 big bang theory s2 2\n4 big bang theory 1\n5 peaky blinders 1\n \n" }, { "answer_id": 74678310, "author": "Colin", "author_id": 16178733, "author_profile": "https://Stackoverflow.com/users/16178733", "pm_score": 0, "selected": false, "text": "0 grey's anatomy s1 NaN s1\n1 friends season 1 1.0 season 1\n2 grey's anatomy s2 NaN s2\n3 big bang theory s2 2.0 s2\n4 big bang theory 1.0 NaN\n5 peaky blinders 1.0 NaN\n df = pd.read_excel(source_file)\n\n# Empty list for data capture\nseason_data = []\n\n# Loop thought all rows\nfor idx in df.index:\n\n # Grab value to check\n check_val = df[\"season\"][idx]\n\n # If value is not null then keep it\n if pd.notnull(check_val):\n\n # Add value to list\n season_data.append(int(check_val))\n\n else:\n # Extract digits from programme description\n extract_result = \"\".join(i for i in df[\"programme\"][idx] if i.isdigit())\n\n # Add value to list\n season_data.append(extract_result)\n\n# Add full list to dataframe\ndf[\"season_new\"] = season_data\n\nprint(df)\n programme season season_new\n0 grey's anatomy s1 NaN 1\n1 friends season 1 1.0 1\n2 grey's anatomy s2 NaN 2\n3 big bang theory s2 2.0 2\n4 big bang theory 1.0 1\n5 peaky blinders 1.0 1\n" }, { "answer_id": 74678334, "author": "Panda Kim", "author_id": 20430449, "author_profile": "https://Stackoverflow.com/users/20430449", "pm_score": -1, "selected": false, "text": "pat = r'[season|s]\\s?(\\d+$)'\ndf.assign(season_new=df['season'].fillna(df['programme'].str.extract(pat)[0]))\n programme season season_new\ngrey's anatomy s1 NaN 1\nfriends season 1 1 1\ngrey's anatomy s2 NaN 2\nbig bang theory s2 2 2\nbig bang theory 1 1\npeaky blinders 1 1\n" }, { "answer_id": 74678773, "author": "Daila", "author_id": 20600582, "author_profile": "https://Stackoverflow.com/users/20600582", "pm_score": 0, "selected": false, "text": "apply() data['season_new'] = data.apply(lambda x: x.season if pd.notna(x.season) else re.search(r'(season\\s?\\d+|s\\s?\\d+)',x.programme).group(1), axis=1)\n programme season season_new\n0 grey's anatomy s1 NaN s1\n1 friends season 1 1.0 1.0\n2 grey's anatomy s2 NaN s2\n3 big bang theory s2 2.0 2.0\n4 big bang theory 1.0 1.0\n5 peaky blinders 1.0 1.0\n data['season_new'] = data.apply(lambda x: x.season if pd.notna(x.season) else (x.programme[-1] if x.programme[-1].isdigit() else np.nan), axis=1).astype('int')\n programme season season_new\n0 grey's anatomy s1 NaN 1\n1 friends season 1 1.0 1\n2 grey's anatomy s2 NaN 2\n3 big bang theory s2 2.0 2\n4 big bang theory 1.0 1\n5 peaky blinders 1.0 1\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17810167/" ]
74,677,799
<p>I have tried the following, but it makes the border also red. I want to make only text red. Is that possible?</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;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;style&gt; .class2, .class2 tr, .class2 td { border: solid 2px; border-collapse: collapse; } .class1{ color: red; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;table class="class2"&gt; &lt;tr class="class1"&gt; &lt;td&gt;hello&lt;/td&gt; &lt;td&gt;world&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;hello&lt;/td&gt; &lt;td&gt;world&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74677923, "author": "Nick Scotney", "author_id": 4990925, "author_profile": "https://Stackoverflow.com/users/4990925", "pm_score": 1, "selected": false, "text": ".class1 td {\n color: red;\n border-color: #000;\n}\n .class2,\n.class2 tr,\n.class2 td {\n border: solid 2px #000;\n border-collapse: collapse;\n}\n" }, { "answer_id": 74677979, "author": "Davi Oliveira", "author_id": 19464177, "author_profile": "https://Stackoverflow.com/users/19464177", "pm_score": 1, "selected": false, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <meta charset=\"utf-8\">\n <style>\n .class2,\n .class2 tr,\n .class2 td {\n border: solid 2px;\n border-collapse: collapse;\n }\n \n .class1{\n color: red;\n }\n </style>\n</head>\n\n<body>\n <table class=\"class2\">\n <tr>\n <td><span class=\"class1\">hello</span></td>\n <td><span class=\"class1\">world</span></td>\n </tr>\n <tr>\n <td>hello</td>\n <td>world</td>\n </tr>\n </table>\n</body>\n\n</html>" }, { "answer_id": 74678044, "author": "Nick Scotney", "author_id": 4990925, "author_profile": "https://Stackoverflow.com/users/4990925", "pm_score": 0, "selected": false, "text": "<html>\n<head>\n <meta charset=\"utf-8\">\n <style>\n .class2,\n .class2 tr,\n .class2 td {\n border: solid 2px currentcolor;\n border-collapse: collapse;\n }\n \n .class1 td {\n color: red;\n \n }\n \n @media (prefers-color-scheme: dark) {\n .class1 td {\n border-color: #FF0;\n }\n }\n </style>\n</head>\n\n<body>\n <table class=\"class2\">\n <tr class=\"class1\">\n <td>hello</td>\n <td>world</td>\n </tr>\n <tr>\n <td>hello</td>\n <td>world</td>\n </tr>\n </table>\n</body>\n</html>\n" }, { "answer_id": 74678728, "author": "loshen", "author_id": 20683781, "author_profile": "https://Stackoverflow.com/users/20683781", "pm_score": 0, "selected": false, "text": " .class2,\n .class2 tr,\n .class2 td {\n border: solid 2px;\n border-collapse: collapse;\n\n border-color: #000;\n\n }\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/455796/" ]
74,677,828
<p>i would like to display 2 or more duplicated customers using joptionpane. It is working if there is only 1 duplicate customer but unfortunately the message dialogue wasnt showing if there is 2 or more duplicated customer. Here is my code.</p> <pre><code> public static void main(String[] args) { int number; number = Integer.parseInt(JOptionPane.showInputDialog(&quot;Enter the number of customers: &quot;)); int[] one = new int[number]; int[] two = new int[number]; for (int i = 0; i &lt; number; i++) { one[i] = Integer.parseInt(JOptionPane.showInputDialog(&quot;Customer number: &quot;)); } int y = 0; for (int i = 0; i &lt; one.length - 1; i++) { for (int w = i + 1; w &lt; one.length; w++) { if (one[i] == one[w]) { two[y] = one[w]; y = y + 1; break; } } for (int p = 0; p &lt; y - 1; p++) { if (one[p] == two[p - 1]) { y = y - 1; break; } } } if (y == 0) { JOptionPane.showMessageDialog(null, &quot;\nHONEST CUSTOMERS&quot;); } else if (y != 0) { JOptionPane.showMessageDialog(null, &quot;Duplicates:&quot;); for (int o = 0; o &lt; y; o++) { JOptionPane.showMessageDialog(null, &quot;Customer #&quot; + two[o]); //jop.showMessageDialog(null, &quot;Duplicates: Customer #&quot; + two[l]); //} } } } } </code></pre> <p>How can i show the message dialogue if i want to show 2 or more duplicated customers? thank you for the help.</p>
[ { "answer_id": 74677923, "author": "Nick Scotney", "author_id": 4990925, "author_profile": "https://Stackoverflow.com/users/4990925", "pm_score": 1, "selected": false, "text": ".class1 td {\n color: red;\n border-color: #000;\n}\n .class2,\n.class2 tr,\n.class2 td {\n border: solid 2px #000;\n border-collapse: collapse;\n}\n" }, { "answer_id": 74677979, "author": "Davi Oliveira", "author_id": 19464177, "author_profile": "https://Stackoverflow.com/users/19464177", "pm_score": 1, "selected": false, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <meta charset=\"utf-8\">\n <style>\n .class2,\n .class2 tr,\n .class2 td {\n border: solid 2px;\n border-collapse: collapse;\n }\n \n .class1{\n color: red;\n }\n </style>\n</head>\n\n<body>\n <table class=\"class2\">\n <tr>\n <td><span class=\"class1\">hello</span></td>\n <td><span class=\"class1\">world</span></td>\n </tr>\n <tr>\n <td>hello</td>\n <td>world</td>\n </tr>\n </table>\n</body>\n\n</html>" }, { "answer_id": 74678044, "author": "Nick Scotney", "author_id": 4990925, "author_profile": "https://Stackoverflow.com/users/4990925", "pm_score": 0, "selected": false, "text": "<html>\n<head>\n <meta charset=\"utf-8\">\n <style>\n .class2,\n .class2 tr,\n .class2 td {\n border: solid 2px currentcolor;\n border-collapse: collapse;\n }\n \n .class1 td {\n color: red;\n \n }\n \n @media (prefers-color-scheme: dark) {\n .class1 td {\n border-color: #FF0;\n }\n }\n </style>\n</head>\n\n<body>\n <table class=\"class2\">\n <tr class=\"class1\">\n <td>hello</td>\n <td>world</td>\n </tr>\n <tr>\n <td>hello</td>\n <td>world</td>\n </tr>\n </table>\n</body>\n</html>\n" }, { "answer_id": 74678728, "author": "loshen", "author_id": 20683781, "author_profile": "https://Stackoverflow.com/users/20683781", "pm_score": 0, "selected": false, "text": " .class2,\n .class2 tr,\n .class2 td {\n border: solid 2px;\n border-collapse: collapse;\n\n border-color: #000;\n\n }\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20683106/" ]
74,677,849
<p>I have a value x, which is a combination of decision variables.</p> <p>I need to calculate a cost, which only triggers if x &gt; 100. So cost = MAX(x - 100, 0) * 20.</p> <p>Is there any way to do this in linear programming?</p> <p>I've tried creating two binary variables (y1 &amp; y2), in which y1 = 1 when x &lt;= 100 &amp; y2 = 1 when x &gt; 100 &amp; y1 + y2 = 1, from this website - <a href="https://uk.mathworks.com/matlabcentral/answers/693740-linear-programming-with-conditional-constraints" rel="nofollow noreferrer">https://uk.mathworks.com/matlabcentral/answers/693740-linear-programming-with-conditional-constraints</a>. However, my excel solver is still giving non-linearity complaints...</p> <p>Any advice on how I can fix this?</p>
[ { "answer_id": 74677886, "author": "Mohsin Mehmood", "author_id": 12248102, "author_profile": "https://Stackoverflow.com/users/12248102", "pm_score": 2, "selected": true, "text": "minimize cost = 20 * x * y\n\nsubject to:\n\nx <= 100 * (1 - y) // x must be <= 100 if y is 0\nx >= 100 * y // x must be >= 100 if y is 1\ny in {0, 1} // y must be 0 or 1\n\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9957594/" ]
74,677,851
<p>I'm having the issue (which seems to be common) that I'm dockerizing applications that run on one machine, and these applications, now, need to run in different containers (because that's the docker paradigm and how things should be done). Currently I'm having issues with postfix and dovecot... people have found this too painful that there are tons of containers running both dovecot and postfix in one container, and I'm doing my best to do this right, but the lack of inet protocol examples (over tcp) is just too painful to continue with this. Leave alone bad logging and things that just don't work. I digress.</p> <p><strong>The question</strong></p> <p>Is it correct to have shared docker volumes that have socket files shared across different containers, and expect them to communicate correctly? Are there limitations that I have to be aware of?</p> <p>Bonus: Out of curiosity, can this be extended to virtual machines?</p>
[ { "answer_id": 74677886, "author": "Mohsin Mehmood", "author_id": 12248102, "author_profile": "https://Stackoverflow.com/users/12248102", "pm_score": 2, "selected": true, "text": "minimize cost = 20 * x * y\n\nsubject to:\n\nx <= 100 * (1 - y) // x must be <= 100 if y is 0\nx >= 100 * y // x must be >= 100 if y is 1\ny in {0, 1} // y must be 0 or 1\n\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1317944/" ]
74,677,861
<p>I have a interface. That interface name is IQueue. Also I have concrete classes. Their names are MyMessage1 and MyMessage2.</p> <pre><code>public interface IQueue { } public class MyMessage1 : IQueue { public string Message { get; set; } public DateTime PublishedDate { get; set; } } public class MyMessage2 : IQueue { public string Name { get; set; } } </code></pre> <p>I am getting all the concrete classes implemented from <code>IQueue</code> with reflection and create a instance.</p> <pre><code>var types = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(s =&gt; s.GetTypes()) .Where(p =&gt; typeof(IQueue).IsAssignableFrom(p) &amp;&amp; p.IsClass) .ToList); foreach(var type in types) { var instance = Activator.CreateInstance(type); } </code></pre> <p>Instance is an object. How I can cast to specific class without using below code? Is it possible.</p> <pre><code>(MyMessage1)Activator.CreateInstance(type) (MyMessage2)Activator.CreateInstance(type) </code></pre> <p>I want to create a specific class instance using type information</p>
[ { "answer_id": 74677886, "author": "Mohsin Mehmood", "author_id": 12248102, "author_profile": "https://Stackoverflow.com/users/12248102", "pm_score": 2, "selected": true, "text": "minimize cost = 20 * x * y\n\nsubject to:\n\nx <= 100 * (1 - y) // x must be <= 100 if y is 0\nx >= 100 * y // x must be >= 100 if y is 1\ny in {0, 1} // y must be 0 or 1\n\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17007595/" ]
74,677,873
<p>I want to know in the year in which more goals were scored (in total), how many goals were scored by and against team 1 when team 1 is either a or b.</p> <p>My table looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">year</th> <th style="text-align: center;">team1</th> <th style="text-align: center;">team2</th> <th style="text-align: center;">score_team1</th> <th style="text-align: right;">score_team2</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">1</td> <td style="text-align: center;">a</td> <td style="text-align: center;">x</td> <td style="text-align: center;">10</td> <td style="text-align: right;">5</td> </tr> <tr> <td style="text-align: left;">1</td> <td style="text-align: center;">b</td> <td style="text-align: center;">y</td> <td style="text-align: center;">4</td> <td style="text-align: right;">3</td> </tr> <tr> <td style="text-align: left;">2</td> <td style="text-align: center;">a</td> <td style="text-align: center;">z</td> <td style="text-align: center;">2</td> <td style="text-align: right;">7</td> </tr> <tr> <td style="text-align: left;">2</td> <td style="text-align: center;">a</td> <td style="text-align: center;">x</td> <td style="text-align: center;">9</td> <td style="text-align: right;">6</td> </tr> <tr> <td style="text-align: left;">2</td> <td style="text-align: center;">b</td> <td style="text-align: center;">z</td> <td style="text-align: center;">0</td> <td style="text-align: right;">7</td> </tr> </tbody> </table> </div> <p>This is the output that I need:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">year</th> <th style="text-align: center;">team</th> <th style="text-align: center;">max_score_team1</th> <th style="text-align: center;">max_score_team2</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">2</td> <td style="text-align: center;">a</td> <td style="text-align: center;">11</td> <td style="text-align: center;">13</td> </tr> <tr> <td style="text-align: left;">2</td> <td style="text-align: center;">b</td> <td style="text-align: center;">0</td> <td style="text-align: center;">7</td> </tr> </tbody> </table> </div> <p>I know that more goals were scored in year 2 by doing this query:</p> <pre><code>select year, sum(score_team1 + score_team2) as total from data group by year order by sum(score_team1 + score_team2) desc limit(1) </code></pre> <p>Now I want to know how many goals were scored by and against team1 when team1 is either a or b. I know how to write the queries separately but how can I nest them in one query so I can get the results in one table like the one above?</p>
[ { "answer_id": 74677886, "author": "Mohsin Mehmood", "author_id": 12248102, "author_profile": "https://Stackoverflow.com/users/12248102", "pm_score": 2, "selected": true, "text": "minimize cost = 20 * x * y\n\nsubject to:\n\nx <= 100 * (1 - y) // x must be <= 100 if y is 0\nx >= 100 * y // x must be >= 100 if y is 1\ny in {0, 1} // y must be 0 or 1\n\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20682844/" ]
74,677,911
<p>I am using Windows 11 x64, Java / JDK 19, Spring Boot 3, PostgreSQL 15.1 at my local PC. My <code>Dockerfile</code></p> <pre><code>FROM amazoncorretto:19-alpine3.16-jdk WORKDIR /app ARG JAR_FILE=target/spring_jwt-1.0.0-SNAPSHOT.jar COPY ${JAR_FILE} ./app.jar EXPOSE 8081 ENTRYPOINT [&quot;java&quot;,&quot;-jar&quot;,&quot;app.jar&quot;] </code></pre> <p>My console log:</p> <pre><code>org.postgresql.util.PSQLException: Connection to 127.0.0.1:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections. at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:319) ~[postgresql-42.5.1.jar!/:42.5.1] at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49) ~[postgresql-42.5.1.jar!/:42.5.1] at org.postgresql.jdbc.PgConnection.&lt;init&gt;(PgConnection.java:247) ~[postgresql-42.5.1.jar!/:42.5.1] at org.postgresql.Driver.makeConnection(Driver.java:434) ~[postgresql-42.5.1.jar!/:42.5.1] at org.postgresql.Driver.connect(Driver.java:291) ~[postgresql-42.5.1.jar!/:42.5.1] at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-5.0.1.jar!/:na] at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:359) ~[HikariCP-5.0.1.jar!/:na] at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:201) ~[HikariCP-5.0.1.jar!/:na] at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:470) ~[HikariCP-5.0.1.jar!/:na] at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:561) ~[HikariCP-5.0.1.jar!/:na] </code></pre> <p>full: <a href="https://gist.github.com/donhuvy/0821da63081f4fd447111b7d1c6f2310" rel="nofollow noreferrer">https://gist.github.com/donhuvy/0821da63081f4fd447111b7d1c6f2310</a></p> <p>Docker run</p> <pre><code>docker run -p 8081:8081 latest:latest </code></pre> <p>How to run image with database connect?</p>
[ { "answer_id": 74677886, "author": "Mohsin Mehmood", "author_id": 12248102, "author_profile": "https://Stackoverflow.com/users/12248102", "pm_score": 2, "selected": true, "text": "minimize cost = 20 * x * y\n\nsubject to:\n\nx <= 100 * (1 - y) // x must be <= 100 if y is 0\nx >= 100 * y // x must be >= 100 if y is 1\ny in {0, 1} // y must be 0 or 1\n\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3728901/" ]
74,677,961
<p>For a long time was using Terraform with Azure and it worked fine. Now for any reason the az cli command it doens't work. I'm getting follow error:</p> <pre><code>AADSTS500200: User account 'xxxx ' is a personal Microsoft account. Personal Microsoft accounts are not supported for this application unless explicitly invited to an organization. Try signing out and signing back in with an organizational account. </code></pre> <p>I've already upgrade az cli versin to 2.42 but problem perists. Even using incognito mode couldn't login to Azure. Instead of using az login, via browser I'm able to login to azure cloud without issues.</p>
[ { "answer_id": 74677886, "author": "Mohsin Mehmood", "author_id": 12248102, "author_profile": "https://Stackoverflow.com/users/12248102", "pm_score": 2, "selected": true, "text": "minimize cost = 20 * x * y\n\nsubject to:\n\nx <= 100 * (1 - y) // x must be <= 100 if y is 0\nx >= 100 * y // x must be >= 100 if y is 1\ny in {0, 1} // y must be 0 or 1\n\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20432287/" ]
74,677,986
<p>I am trying to understand how Stripe achieves its layout here: <a href="https://stripe.com/docs/payments" rel="nofollow noreferrer">https://stripe.com/docs/payments</a></p> <p>That page has a column flexbox div containing 2 child divs: one for the navbar and the second for the main content. The column direction means that the navbar will sit on top of the main content. The navbar does not use <code>sticky</code> and from what I can see it does not use <code>fixed</code> positioning either.</p> <p>The main content div is a Flexbox with <code>overflow-y: hidden</code> and has 2 child divs: the first for the LHS sidebar and the second for the main page content.</p> <p>Note that left sidebar and main page content scroll independently and the overall page itself does not scroll at all. Unless I misunderstand what is happening, Stripe appears to be using the overflow-hidden property in the primary div to ensure that the page contents div does not go outside the viewport and hence the overall page is not scrollable. The inner divs use <code>overflow-y-auto</code> to ensure that content inside them is scrollable.</p> <p>I'm trying to replicate this using the below using Tailwind and Nextjs:</p> <pre><code>&lt;div class=&quot;h-full bg-white&quot; &gt; &lt;div class=&quot;flex flex-col h-full&quot;&gt; &lt;div id=&quot;Navbar&quot; class=&quot;bg-blue-200&quot;&gt; Navbar &lt;/div&gt; &lt;div id=&quot;MainContent&quot; class=&quot;flex flex-auto h-full overflow-y-hidden&quot;&gt; &lt;div&gt; &lt;div class=&quot;flex-grow-0 flex-shrink-0 flex flex-col h-full w-56 bg-green-100&quot;&gt; &lt;div class=&quot;flex flex-grow overflow-y-auto overflow-x-hidden&quot;&gt; &lt;div&gt; &lt;p&gt;lhs&lt;/p&gt; &lt;p&gt;lhs&lt;/p&gt; ... lots more content here to ensure page overflow &lt;/div&gt; &lt;/div&gt; &lt;div&gt; Sidebar footer &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;bg-red-100 w-full&quot;&gt; Content &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>However, when I use the above I just get the whole page that scrolls, whereas I'm expecting to see the LHS sidebar containing the list of <code>&lt;p&gt;las&lt;/p&gt;</code> elements scroll and LHS sidebar footer and the page as a whole to stay static. There is no change when I add a load of content into the content div. Here's what it looks like: <a href="https://play.tailwindcss.com/J6unFAO47B" rel="nofollow noreferrer">https://play.tailwindcss.com/J6unFAO47B</a></p> <p>Whilst I know that I could use a <code>sticky</code> navbar, I'm trying to understand what Stripe is doing in their page and so I want to understand why is my sidebar not scrolling independently of the other areas of the page?</p>
[ { "answer_id": 74677886, "author": "Mohsin Mehmood", "author_id": 12248102, "author_profile": "https://Stackoverflow.com/users/12248102", "pm_score": 2, "selected": true, "text": "minimize cost = 20 * x * y\n\nsubject to:\n\nx <= 100 * (1 - y) // x must be <= 100 if y is 0\nx >= 100 * y // x must be >= 100 if y is 1\ny in {0, 1} // y must be 0 or 1\n\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74677986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/272023/" ]
74,678,001
<p>Using Entity Framework core, can I get the total sum of the column and row count in one call? I have the following code, but I think there is a better way to do this.</p> <pre class="lang-cs prettyprint-override"><code>TotalCostResponse result = new TotalCostResponse { TotalCost = await dbContext.Transaction .Where(x =&gt; x.UserName == request.UserName &amp;&amp; x.Date &gt;= request.StartDate &amp;&amp; x.Date &lt;= request.EndDate) .SumAsync(x =&gt; x.Amount), TotalNumber = await dbContext.Transaction .Where(x =&gt; x.UserName == request.UserName &amp;&amp; x.Date = request.StartDate &amp;&amp; x.Date &lt;= request.EndDate) .CountAsync() }; </code></pre> <p>So instead of calling dbContext two times, I need to make it in one call.</p>
[ { "answer_id": 74678118, "author": "dubdam", "author_id": 20683481, "author_profile": "https://Stackoverflow.com/users/20683481", "pm_score": 1, "selected": false, "text": "TotalCostResponse result = new TotalCostResponse\n{\n// Use the Sum and Count methods together in a LINQ query to get the total sum\n// and row count in a single call to the database.\nTotalCost = await dbContext.Transaction\n .Where(x => x.UserName == request.UserName\n && x.Date >= request.StartDate\n && x.Date <= request.EndDate)\n .Select(x => new\n {\n // Select the Amount column and use the Sum method to get the total sum.\n TotalCost = x.Amount.Sum(),\n // Use the Count method to get the row count.\n TotalNumber = x.Amount.Count()\n })\n // Use the SingleOrDefault method to get the first element of the query result.\n // If the query result is empty, this will return null.\n .SingleOrDefault(),\n\n// If the query result is not null, set the TotalCost and TotalNumber properties\n// of the TotalCostResponse object using the values from the query result.\n// If the query result is null, these properties will remain uninitialized.\nTotalCost = result?.TotalCost,\nTotalNumber = result?.TotalNumber\n};\n // Use the Sum method in a LINQ query to get the total sum.\ndecimal? totalCost = await dbContext.Transaction\n.Where(x => x.UserName == request.UserName\n && x.Date >= request.StartDate\n && x.Date <= request.EndDate)\n.SumAsync(x => x.Amount);\n\n// Use the Count method in a LINQ query to get the row count.\nint? totalNumber = await dbContext.Transaction\n.Where(x => x.UserName == request.UserName\n && x.Date = request.StartDate\n && x.Date <= request.EndDate)\n.CountAsync();\n\nTotalCostResponse result = new TotalCostResponse\n{\n// Set the TotalCost and TotalNumber properties of the TotalCostResponse\n// object using the values from the LINQ queries.\nTotalCost = totalCost,\nTotalNumber = totalNumber\n};\n" }, { "answer_id": 74678182, "author": "Darkk L", "author_id": 17627575, "author_profile": "https://Stackoverflow.com/users/17627575", "pm_score": 0, "selected": false, "text": "//In the select get only what you need, in your case only the Amount\nvar transactions = await this.dbContext.Transaction\n .Where(x => x.UserName == request.UserName\n && x.Date >= request.StartDate\n && x.Date <= request.EndDate)\n .Select(y => new\n {\n Amount = y.Amount,\n }).ToListAsync();\n\n//Calculating the data\nvar result = new TotalCostResponse\n{\n TotalCost = transactions.Sum(x => x),\n TotalNumber = transactions.Count(),\n}\n\n//Dto model for the result\npublic class TotalCostResponse\n{\n public decimal TotalCost { get; set; }\n public int TotalNumber { get; set; } \n}\n\n" }, { "answer_id": 74678630, "author": "Alexander Petrov", "author_id": 5045688, "author_profile": "https://Stackoverflow.com/users/5045688", "pm_score": 2, "selected": false, "text": "var result = await dbContext.Transaction\n .Where(x => x.UserName == request.UserName\n && x.Date >= request.StartDate\n && x.Date <= request.EndDate)\n .GroupBy(x => 1)\n .Select(group => new TotalCostResponse\n {\n TotalCost = group.Sum(x => x.Amount),\n TotalNumber = group.Count()\n })\n .FirstOrDefaultAsync();\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20683358/" ]
74,678,013
<p>WebStorm tries to push my project to an account that does not exist anymore. How do I change it? I have already added the new account to WebStorm and it still tries pushing to the old account.</p> <p><a href="https://i.stack.imgur.com/5aMJl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5aMJl.png" alt="the explaining" /></a></p>
[ { "answer_id": 74678118, "author": "dubdam", "author_id": 20683481, "author_profile": "https://Stackoverflow.com/users/20683481", "pm_score": 1, "selected": false, "text": "TotalCostResponse result = new TotalCostResponse\n{\n// Use the Sum and Count methods together in a LINQ query to get the total sum\n// and row count in a single call to the database.\nTotalCost = await dbContext.Transaction\n .Where(x => x.UserName == request.UserName\n && x.Date >= request.StartDate\n && x.Date <= request.EndDate)\n .Select(x => new\n {\n // Select the Amount column and use the Sum method to get the total sum.\n TotalCost = x.Amount.Sum(),\n // Use the Count method to get the row count.\n TotalNumber = x.Amount.Count()\n })\n // Use the SingleOrDefault method to get the first element of the query result.\n // If the query result is empty, this will return null.\n .SingleOrDefault(),\n\n// If the query result is not null, set the TotalCost and TotalNumber properties\n// of the TotalCostResponse object using the values from the query result.\n// If the query result is null, these properties will remain uninitialized.\nTotalCost = result?.TotalCost,\nTotalNumber = result?.TotalNumber\n};\n // Use the Sum method in a LINQ query to get the total sum.\ndecimal? totalCost = await dbContext.Transaction\n.Where(x => x.UserName == request.UserName\n && x.Date >= request.StartDate\n && x.Date <= request.EndDate)\n.SumAsync(x => x.Amount);\n\n// Use the Count method in a LINQ query to get the row count.\nint? totalNumber = await dbContext.Transaction\n.Where(x => x.UserName == request.UserName\n && x.Date = request.StartDate\n && x.Date <= request.EndDate)\n.CountAsync();\n\nTotalCostResponse result = new TotalCostResponse\n{\n// Set the TotalCost and TotalNumber properties of the TotalCostResponse\n// object using the values from the LINQ queries.\nTotalCost = totalCost,\nTotalNumber = totalNumber\n};\n" }, { "answer_id": 74678182, "author": "Darkk L", "author_id": 17627575, "author_profile": "https://Stackoverflow.com/users/17627575", "pm_score": 0, "selected": false, "text": "//In the select get only what you need, in your case only the Amount\nvar transactions = await this.dbContext.Transaction\n .Where(x => x.UserName == request.UserName\n && x.Date >= request.StartDate\n && x.Date <= request.EndDate)\n .Select(y => new\n {\n Amount = y.Amount,\n }).ToListAsync();\n\n//Calculating the data\nvar result = new TotalCostResponse\n{\n TotalCost = transactions.Sum(x => x),\n TotalNumber = transactions.Count(),\n}\n\n//Dto model for the result\npublic class TotalCostResponse\n{\n public decimal TotalCost { get; set; }\n public int TotalNumber { get; set; } \n}\n\n" }, { "answer_id": 74678630, "author": "Alexander Petrov", "author_id": 5045688, "author_profile": "https://Stackoverflow.com/users/5045688", "pm_score": 2, "selected": false, "text": "var result = await dbContext.Transaction\n .Where(x => x.UserName == request.UserName\n && x.Date >= request.StartDate\n && x.Date <= request.EndDate)\n .GroupBy(x => 1)\n .Select(group => new TotalCostResponse\n {\n TotalCost = group.Sum(x => x.Amount),\n TotalNumber = group.Count()\n })\n .FirstOrDefaultAsync();\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20683381/" ]
74,678,018
<p>I have a csv with one row of data. It represents legacy headers that I am trying to append as 1 new row (or consider it as many columns) in a second csv. I need to compare the legacy header with the second csv's current headers, so after i append the data from the first csv i want to move it so that it's the first row too.</p> <p>The issue right now is that when i append my data from the first csv it just all goes to the bottom of the first column.</p> <p>See below for my code. How can i make it so that it takes the 1 row of data in my first csv and appends it to my second csv as ONE NEW ROW. After how would i move it so that it becomes the first row in my data (not as a header)</p> <pre><code>with open('filewith1row.csv', 'r', encoding='utf8') as reader: with open('mainfile.csv', 'a', encoding='utf8') as writer: for line in reader: writer.write(line) </code></pre> <p>Please help!! Thank you in advanced</p>
[ { "answer_id": 74678503, "author": "ScottC", "author_id": 20174226, "author_profile": "https://Stackoverflow.com/users/20174226", "pm_score": 2, "selected": true, "text": "csv mainfile.csv Fruit,Animals,Numbers\nApple,Cat,5\nBanana,Dog,8\nCherry,Goat,2\nDurian,Horse,4\n Fruta,Animales,Números\n import pandas as pd\n\nmainfile = pd.read_csv('mainfile.csv', header=None)\none_liner = pd.read_csv('filewith1row.csv', header=None)\n\nmainfile.loc[0.5]=one_liner.loc[0]\nmainfile = mainfile.sort_index() \nmainfile.to_csv('mainfile.csv', index=False, header=False)\n Fruit,Animals,Numbers\nFruta,Animales,Números\nApple,Cat,5\nBanana,Dog,8\nCherry,Goat,2\nDurian,Horse,4\n" }, { "answer_id": 74679751, "author": "Adrian Klaver", "author_id": 7070613, "author_profile": "https://Stackoverflow.com/users/7070613", "pm_score": 0, "selected": false, "text": "cat hdr.csv \nfirst_col,second_col,third_col\n\ncat data.csv \n1,2,3\n4,5,6\n7,8,9\n\n\nwith open('new_file.csv', 'w') as new_file:\n with open('hdr.csv') as hdr_file:\n new_file.write(hdr_file.read())\n with open('data.csv') as data_file:\n new_file.write(data_file.read())\n\ncat new_file.csv \nfirst_col,second_col,third_col\n1,2,3\n4,5,6\n7,8,9\n\n\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16633745/" ]
74,678,058
<p>I am new to Java, I am bored with if else statement I want to refactor my code and relief from if-else statement, not I am not able to reduce my code, In my code nothing is static every thing comes from user side. I share my codes for your reference.</p> <pre class="lang-java prettyprint-override"><code>if (orderDetail != null &amp;&amp; item != null &amp;&amp; !orderDetail.isUnitPriceModified()) { ItemSizeColorStyle itemSizeColorStyle = itemSizeColorStyleRepository.findByRecordID(orderDetail.getItemSCSID()); if (origin != null &amp;&amp; (origin.contains(&quot;b2baccess&quot;) || (origin.contains(&quot;.myappdev&quot;) &amp;&amp; !origin.contains(&quot;apps.myappdev&quot;)))) { RepGroupManufacturer repGroupManufacturer = repGroupManufacturerRepository.findByRepGroupIDAndManufacturerIDAndRecordDeleted(repGroupID, manufacturerID, NOT_DELETED); if (repGroupManufacturer != null &amp;&amp; repGroupManufacturer.getB2bItemPricingPolicy() != null &amp;&amp; repGroupManufacturer.getB2bItemPricingPolicy().equalsIgnoreCase(ReptimeConstants.SHOWRETAILPRICE)) { if (orderDetail.getItemSCSID() == null &amp;&amp; item.getRetailPrice() != null) { orderDetail.setUnitPrice(item.getRetailPrice()); } else { // ItemSizeColorStyle itemSizeColorStyle = itemSizeColorStyleRepository.findByRecordID(orderDetail.getItemSCSID()); if (itemSizeColorStyle != null &amp;&amp; itemSizeColorStyle.getRetailPrice() != null) { orderDetail.setUnitPrice(itemSizeColorStyle.getRetailPrice()); } else if (itemSizeColorStyle != null &amp;&amp; itemSizeColorStyle.getRetailPrice() == null &amp;&amp; item.getRetailPrice() != null) { orderDetail.setUnitPrice(item.getRetailPrice()); } else if (itemSizeColorStyle != null &amp;&amp; itemSizeColorStyle.getRetailPrice() == null &amp;&amp; item.getRetailPrice() == null) { throw new NullPointerException(&quot;item price can not be null.&quot;); } } } } </code></pre> <p>How to convert this if else to map.</p>
[ { "answer_id": 74678503, "author": "ScottC", "author_id": 20174226, "author_profile": "https://Stackoverflow.com/users/20174226", "pm_score": 2, "selected": true, "text": "csv mainfile.csv Fruit,Animals,Numbers\nApple,Cat,5\nBanana,Dog,8\nCherry,Goat,2\nDurian,Horse,4\n Fruta,Animales,Números\n import pandas as pd\n\nmainfile = pd.read_csv('mainfile.csv', header=None)\none_liner = pd.read_csv('filewith1row.csv', header=None)\n\nmainfile.loc[0.5]=one_liner.loc[0]\nmainfile = mainfile.sort_index() \nmainfile.to_csv('mainfile.csv', index=False, header=False)\n Fruit,Animals,Numbers\nFruta,Animales,Números\nApple,Cat,5\nBanana,Dog,8\nCherry,Goat,2\nDurian,Horse,4\n" }, { "answer_id": 74679751, "author": "Adrian Klaver", "author_id": 7070613, "author_profile": "https://Stackoverflow.com/users/7070613", "pm_score": 0, "selected": false, "text": "cat hdr.csv \nfirst_col,second_col,third_col\n\ncat data.csv \n1,2,3\n4,5,6\n7,8,9\n\n\nwith open('new_file.csv', 'w') as new_file:\n with open('hdr.csv') as hdr_file:\n new_file.write(hdr_file.read())\n with open('data.csv') as data_file:\n new_file.write(data_file.read())\n\ncat new_file.csv \nfirst_col,second_col,third_col\n1,2,3\n4,5,6\n7,8,9\n\n\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13152124/" ]
74,678,092
<p>I have all my .js files and html linked to my server file. but when I lunch localhost3000, I get &quot;cannot get/&quot;</p> <p>I tried anything I though could be helpful but couldn't fix the problem. Anyone knows how to fix it?</p> <p>I have this for my server side</p> <pre><code>const express = require('express'); const app = express(); app.listen(3000, () =&gt; console.log('listening at port 3000!')); app.use(express.static('codefreeze.html')); </code></pre> <p>and I have this for client side</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;script type=&quot;text/javascript&quot; src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;codefreeze.js&quot;&gt;&lt;/script&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;codefreeze.css&quot;&gt; &lt;link href = &quot;https://fonts.googleapis.com/css?family=Schoolbell&amp;v1&quot; rel=&quot;stylesheet&quot;&gt; &lt;title&gt;DIARY&lt;/title&gt; &lt;/head&gt; &lt;body onload=&quot;Name()&quot;&gt; &lt;h1&gt;HELLO!&lt;/h1&gt; &lt;p&gt;Welcome &lt;span id=&quot;name&quot;&gt;&lt;/span&gt;&lt;/p&gt; &lt;p id=&quot;date&quot;&gt;&lt;/p&gt; &lt;script&gt; document.getElementById(&quot;date&quot;).innerHTML = DATE(); &lt;/script&gt; &lt;div id=&quot;user&quot;&gt; &lt;label id=&quot;lbl1&quot;&gt;Passage #1&lt;/label&gt;&lt;br&gt; &lt;textarea id=&quot;psg1&quot; rows=&quot;10&quot; cols=&quot;30&quot;&gt;&lt;/textarea&gt;&lt;br&gt; &lt;/div&gt; &lt;button id=&quot;save&quot; onclick=&quot;save()&quot;&gt;SAVE&lt;/button&gt; &lt;button id=&quot;add&quot; onclick=&quot;add()&quot;&gt;ADD&lt;/button&gt; &lt;button id=&quot;delete&quot; onclick=&quot;del()&quot;&gt;DELETE&lt;/button&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I know something I'm doing is wrong but I cannot seem to find what.</p>
[ { "answer_id": 74678503, "author": "ScottC", "author_id": 20174226, "author_profile": "https://Stackoverflow.com/users/20174226", "pm_score": 2, "selected": true, "text": "csv mainfile.csv Fruit,Animals,Numbers\nApple,Cat,5\nBanana,Dog,8\nCherry,Goat,2\nDurian,Horse,4\n Fruta,Animales,Números\n import pandas as pd\n\nmainfile = pd.read_csv('mainfile.csv', header=None)\none_liner = pd.read_csv('filewith1row.csv', header=None)\n\nmainfile.loc[0.5]=one_liner.loc[0]\nmainfile = mainfile.sort_index() \nmainfile.to_csv('mainfile.csv', index=False, header=False)\n Fruit,Animals,Numbers\nFruta,Animales,Números\nApple,Cat,5\nBanana,Dog,8\nCherry,Goat,2\nDurian,Horse,4\n" }, { "answer_id": 74679751, "author": "Adrian Klaver", "author_id": 7070613, "author_profile": "https://Stackoverflow.com/users/7070613", "pm_score": 0, "selected": false, "text": "cat hdr.csv \nfirst_col,second_col,third_col\n\ncat data.csv \n1,2,3\n4,5,6\n7,8,9\n\n\nwith open('new_file.csv', 'w') as new_file:\n with open('hdr.csv') as hdr_file:\n new_file.write(hdr_file.read())\n with open('data.csv') as data_file:\n new_file.write(data_file.read())\n\ncat new_file.csv \nfirst_col,second_col,third_col\n1,2,3\n4,5,6\n7,8,9\n\n\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20683442/" ]
74,678,108
<p>I want to add two numbers from two different objects.</p> <p>Here is a simplified version. I have two integers and I multiply those to get <code>multiplied</code> .</p> <p>models.py:</p> <pre><code>class ModelA(models.Model): number_a = models.IntegerField(default=1, null=True, blank=True) number_b = models.IntegerField(default=1, null=True, blank=True) def multiplied(self): return self.number_a * self.number_b </code></pre> <p>views.py:</p> <pre><code>@login_required def homeview(request): numbers = ModelA.objects.all() context = { 'numbers': numbers, } return TemplateResponse... </code></pre> <p>What I'm trying to do is basically <code>multiplied + multiplied</code> in the template but I simply can't figure out how to do it since I first have to loop through the objects.</p> <p>So if I had 2 instances of <code>ModelA</code> and <code>two 'multiplied' values of 100</code> I want to display <code>200</code> in the template. Is this possible?</p>
[ { "answer_id": 74678571, "author": "haduki", "author_id": 18229792, "author_profile": "https://Stackoverflow.com/users/18229792", "pm_score": 1, "selected": false, "text": "aggregate from django.db.models import Sum\n\nModelA.objects.aggregate(Sum('multiplied'))\n aggregate field" }, { "answer_id": 74678612, "author": "Swift", "author_id": 8874154, "author_profile": "https://Stackoverflow.com/users/8874154", "pm_score": 2, "selected": false, "text": "numbers {% for number in numbers %}\n {{ number.multiplied }}\n{% endfor %}\n multiplied numbers = ModelA.objects.aggregate(Sum('number_a', 'number_b'))\n SUM" }, { "answer_id": 74678665, "author": "Niko", "author_id": 7100120, "author_profile": "https://Stackoverflow.com/users/7100120", "pm_score": 2, "selected": true, "text": "def homeview(request):\n queryset = ModelA.objects.all()\n multipliers_addition = 0\n for obj in queryset:\n multipliers_addition += obj.multiplied()\n\n context = {\n 'addition': multipliers_addition,\n }\n\n return render(request, 'multiply.html', context)\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16280397/" ]
74,678,134
<p>I currently have a filter dropdown containing checkboxes. I have checkboxes for gender and category. I am now trying to make sure that the user will check at least one checkbox each part (gender and category). The problem is I don't know how to check whether the checkbox is empty or not.</p> <p>Below is the partial form for the filter dropdown:</p> <pre><code>&lt;form class=&quot;&quot; method=&quot;GET&quot; action=&quot;manage_product.php&quot;&gt; &lt;h6 class=&quot;dropdown-header px-0&quot;&gt;Gender&lt;/h6&gt; &lt;div class=&quot;form-check&quot;&gt; &lt;input class=&quot;form-check-input&quot; name=&quot;genderFil[]&quot; type=&quot;checkbox&quot; value=&quot;M&quot; class=&quot;genderFil&quot; id=&quot;genMale&quot; &lt;?= ($isMale == 1) ? &quot;checked&quot; : &quot;&quot;; ?&gt;&gt; &lt;label class=&quot;form-check-label&quot; for=&quot;genMale&quot;&gt;Male&lt;/label&gt; &lt;/div&gt; &lt;div class=&quot;form-check&quot;&gt; &lt;input class=&quot;form-check-input&quot; name=&quot;genderFil[]&quot; type=&quot;checkbox&quot; value=&quot;F&quot; class=&quot;genderFil&quot; id=&quot;genFemale&quot; &lt;?= ($isFemale == 1) ? &quot;checked&quot; : &quot;&quot;; ?&gt;&gt; &lt;label class=&quot;form-check-label&quot; for=&quot;genFemale&quot;&gt;Female&lt;/label&gt; &lt;/div&gt; &lt;div class=&quot;dropdown-divider&quot;&gt;&lt;/div&gt; &lt;h6 class=&quot;dropdown-header px-0&quot;&gt;Category&lt;/h6&gt; &lt;div class=&quot;form-check&quot;&gt; &lt;input class=&quot;form-check-input&quot; name=&quot;categoryFil[]&quot; type=&quot;checkbox&quot; value=&quot;1&quot; class=&quot;categoryFil&quot; id=&quot;catShoes&quot; &lt;?= ($isShoes == 1) ? &quot;checked&quot; : &quot;&quot;; ?&gt;&gt; &lt;label class=&quot;form-check-label&quot; for=&quot;catShoes&quot;&gt;Shoes&lt;/label&gt; &lt;/div&gt; &lt;div class=&quot;form-check&quot;&gt; &lt;input class=&quot;form-check-input&quot; name=&quot;categoryFil[]&quot; type=&quot;checkbox&quot; value=&quot;2&quot; class=&quot;categoryFil&quot; id=&quot;catPants&quot; &lt;?= ($isPants == 1) ? &quot;checked&quot; : &quot;&quot;; ?&gt;&gt; &lt;label class=&quot;form-check-label&quot; for=&quot;catPants&quot;&gt;Pants&lt;/label&gt; &lt;/div&gt; &lt;div class=&quot;form-check&quot;&gt; &lt;input class=&quot;form-check-input&quot; name=&quot;categoryFil[]&quot; type=&quot;checkbox&quot; value=&quot;3&quot; class=&quot;categoryFil&quot; id=&quot;catShirts&quot; &lt;?= ($isShirts == 1) ? &quot;checked&quot; : &quot;&quot;; ?&gt;&gt; &lt;label class=&quot;form-check-label&quot; for=&quot;catShirts&quot;&gt;Shirts&lt;/label&gt; &lt;/div&gt; &lt;div class=&quot;dropdown-divider&quot;&gt;&lt;/div&gt; &lt;input type=&quot;submit&quot; class=&quot;button_primary&quot; name=&quot;applyFilter&quot; value=&quot;Apply&quot; onclick=&quot;checkFilter()&quot;&gt; &lt;/form&gt; </code></pre> <p>Below is the javascript that I tried to code:</p> <pre><code> function checkFilter() { var res = true; var checkedGender = $('input[class=&quot;genderFil&quot;]:checked').length; if(checkedGender &lt; 1) { alert(&quot;Please select at least one gender!&quot;); res = false; } var checkedCategory = $('input[class=&quot;categoryFil&quot;]:checked').length; if(checkedCategory &lt; 1) { alert(&quot;Please select at least one category!&quot;); res = false; } return res; } </code></pre> <p>It is only can be submitted if there is at least one gender and at least one category checked.</p> <p>How can I check whether the checkbox is empty or not?</p>
[ { "answer_id": 74678571, "author": "haduki", "author_id": 18229792, "author_profile": "https://Stackoverflow.com/users/18229792", "pm_score": 1, "selected": false, "text": "aggregate from django.db.models import Sum\n\nModelA.objects.aggregate(Sum('multiplied'))\n aggregate field" }, { "answer_id": 74678612, "author": "Swift", "author_id": 8874154, "author_profile": "https://Stackoverflow.com/users/8874154", "pm_score": 2, "selected": false, "text": "numbers {% for number in numbers %}\n {{ number.multiplied }}\n{% endfor %}\n multiplied numbers = ModelA.objects.aggregate(Sum('number_a', 'number_b'))\n SUM" }, { "answer_id": 74678665, "author": "Niko", "author_id": 7100120, "author_profile": "https://Stackoverflow.com/users/7100120", "pm_score": 2, "selected": true, "text": "def homeview(request):\n queryset = ModelA.objects.all()\n multipliers_addition = 0\n for obj in queryset:\n multipliers_addition += obj.multiplied()\n\n context = {\n 'addition': multipliers_addition,\n }\n\n return render(request, 'multiply.html', context)\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19106554/" ]
74,678,167
<p>Sorry for the strange title, but I've come across an issue that is plain weird. To give some background, i'm working on a booking system that takes a time range as an input from admin, generates available times based on it, and then reduces the available times based on already made bookings (i.e admin specifies availability from 10:00 to 12:00, booking has been made to 11:30, available times will be <code>times = [10:00, 10:30, 11:00, 12:00]</code>).</p> <p>I have an object that contains per month for each day the available times.</p> <pre><code>availableTimesPerDay: { 1: [&quot;10:00&quot;,&quot;10:30&quot;,&quot;11:00&quot;,&quot;11:30&quot;,&quot;12:00&quot;], 2: [&quot;10:00&quot;,&quot;10:30&quot;,&quot;11:00&quot;,&quot;11:30&quot;,&quot;12:00&quot;], 3: [&quot;10:00&quot;,&quot;10:30&quot;,&quot;11:00&quot;,&quot;11:30&quot;,&quot;12:00&quot;], .... } </code></pre> <p>Where the number represents the date for the given month.</p> <p>Bookings are represented as an array of objects, format is:</p> <pre><code>bookedTimes = [ { date: &quot;2022-12-01T11:30:00.000+02:00&quot; } ]; </code></pre> <p>I planned to have a function which would iterate through each booking and remove the availability for that time on a given date (based on example above, 11:30 would need to be removed from <code>availableTimesPerDay[1]</code> leaving the value for it as <code>[&quot;10:00&quot;,&quot;10:30&quot;,&quot;11:00&quot;,&quot;12:00&quot;]</code></p> <p>The function itself is defined as such:</p> <pre><code>function reduceAvailableTimesBasedOnDateTime(availableTimesPerDay,bookedTimes){ console.log(JSON.stringify(availableTimesPerDay)); bookedTimes.forEach((bookedDateObject) =&gt; { let bookedDate = new Date(bookedDateObject.date); // 1 let currentAvailableTimesOnDate = availableTimesPerDay[bookedDate.getDate()]; // [&quot;10:00&quot;,&quot;10:30&quot;,&quot;11:00&quot;,&quot;11:30&quot;,&quot;12:00&quot;] let bookedTime = bookedDate.toLocaleTimeString('et'); // &quot;13:30:00&quot; let time = bookedTime.substring(0,bookedTime.length - 3); // &quot;13:30&quot; let index = currentAvailableTimesOnDate.indexOf(time); // 3 if (index &gt; -1) { currentAvailableTimesOnDate.splice(index, 1); // [&quot;10:00&quot;,&quot;10:30&quot;,&quot;11:00&quot;,&quot;12:00&quot;] } }) console.log(JSON.stringify(availableTimesPerDay)); return availableTimesPerDay; } </code></pre> <p>The way I understand this function is that i've extracted a specific array of available times into a new variable and removed a specific time from that array. I have done no modifications on an original data and I would expect at this stage the <code>availableTimesPerDay</code> to remain unmodified. However, when I run my code, the <code>availableTimesPerDay</code> is modified even though I do no operations with <code>availableTimesPerDay</code> object itself.</p> <p>What's even stranger is that the modification is not just strictly done on the 1st element, but on all specific dates that have the same day of the week. Here's output from the console for the <code>console.log(availableTimesPerDay)</code> defined in the function (note that <code>11:30</code> value is removed on dates 1st of December, 8th of December, 15th of December etc.</p> <pre><code>booking-helper.js:94 {&quot;1&quot;:[&quot;10:00&quot;,&quot;10:30&quot;,&quot;11:00&quot;,&quot;11:30&quot;,&quot;12:00&quot;],&quot;2&quot;:[],&quot;3&quot;:[],&quot;4&quot;:[],&quot;5&quot;:[],&quot;6&quot;:[],&quot;7&quot;:[],&quot;8&quot;:[&quot;10:00&quot;,&quot;10:30&quot;,&quot;11:00&quot;,&quot;11:30&quot;,&quot;12:00&quot;],&quot;9&quot;:[],&quot;10&quot;:[],&quot;11&quot;:[],&quot;12&quot;:[],&quot;13&quot;:[],&quot;14&quot;:[],&quot;15&quot;:[&quot;10:00&quot;,&quot;10:30&quot;,&quot;11:00&quot;,&quot;11:30&quot;,&quot;12:00&quot;],&quot;16&quot;:[],&quot;17&quot;:[],&quot;18&quot;:[],&quot;19&quot;:[],&quot;20&quot;:[],&quot;21&quot;:[],&quot;22&quot;:[&quot;10:00&quot;,&quot;10:30&quot;,&quot;11:00&quot;,&quot;11:30&quot;,&quot;12:00&quot;],&quot;23&quot;:[],&quot;24&quot;:[],&quot;25&quot;:[],&quot;26&quot;:[],&quot;27&quot;:[],&quot;28&quot;:[],&quot;29&quot;:[&quot;10:00&quot;,&quot;10:30&quot;,&quot;11:00&quot;,&quot;11:30&quot;,&quot;12:00&quot;],&quot;30&quot;:[],&quot;31&quot;:[]} booking-helper.js:105 {&quot;1&quot;:[&quot;10:00&quot;,&quot;10:30&quot;,&quot;11:00&quot;,&quot;12:00&quot;],&quot;2&quot;:[],&quot;3&quot;:[],&quot;4&quot;:[],&quot;5&quot;:[],&quot;6&quot;:[],&quot;7&quot;:[],&quot;8&quot;:[&quot;10:00&quot;,&quot;10:30&quot;,&quot;11:00&quot;,&quot;12:00&quot;],&quot;9&quot;:[],&quot;10&quot;:[],&quot;11&quot;:[],&quot;12&quot;:[],&quot;13&quot;:[],&quot;14&quot;:[],&quot;15&quot;:[&quot;10:00&quot;,&quot;10:30&quot;,&quot;11:00&quot;,&quot;12:00&quot;],&quot;16&quot;:[],&quot;17&quot;:[],&quot;18&quot;:[],&quot;19&quot;:[],&quot;20&quot;:[],&quot;21&quot;:[],&quot;22&quot;:[&quot;10:00&quot;,&quot;10:30&quot;,&quot;11:00&quot;,&quot;12:00&quot;],&quot;23&quot;:[],&quot;24&quot;:[],&quot;25&quot;:[],&quot;26&quot;:[],&quot;27&quot;:[],&quot;28&quot;:[],&quot;29&quot;:[&quot;10:00&quot;,&quot;10:30&quot;,&quot;11:00&quot;,&quot;12:00&quot;],&quot;30&quot;:[],&quot;31&quot;:[ </code></pre> <p>What's even more interesting is that if I copy the same function to codepen with same data or call it directly from the browsers console it works as expected - it removes the specific time from a specific date.</p>
[ { "answer_id": 74678208, "author": "Muhammad Salman", "author_id": 15715337, "author_profile": "https://Stackoverflow.com/users/15715337", "pm_score": -1, "selected": false, "text": "function reduceAvailableTimesBasedOnDateTime(availableTimesPerDay,bookedTimes){\n console.log(JSON.stringify(availableTimesPerDay));\n bookedTimes.forEach((bookedDateObject) => {\n // Parse the string using the `Date.parse()` method\n let bookedDateMilliseconds = Date.parse(bookedDateObject.date);\n // Create a new Date object using the parsed date and time\n let bookedDate = new Date(bookedDateMilliseconds);\n let currentAvailableTimesOnDate = availableTimesPerDay[bookedDate.getDate()];\n let bookedTime = bookedDate.toLocaleTimeString('et');\n let time = bookedTime.substring(0,bookedTime.length - 3);\n let index = currentAvailableTimesOnDate.indexOf(time);\n if (index > -1) { \n currentAvailableTimesOnDate.splice(index, 1);\n }\n })\n console.log(JSON.stringify(availableTimesPerDay));\n return availableTimesPerDay;\n}\n function reduceAvailableTimesBasedOnDateTime(availableTimesPerDay,bookedTimes){\n console.log(JSON.stringify(availableTimesPerDay));\n bookedTimes.forEach((bookedDateObject) => {\n // Parse the string using the `Date.parse()` method\n let bookedDateMilliseconds = Date.parse(bookedDateObject.date);\n // Create a new Date object using the parsed date and time\n let bookedDate = new Date(bookedDateMilliseconds);\n // Create a new Date object using the original object's `getTime()` method\n let newBookedDate = new Date(bookedDate.getTime());\n let currentAvailableTimesOnDate = availableTimesPerDay[newBookedDate.getDate()];\n let bookedTime = newBookedDate.toLocaleTimeString('et');\n let time = bookedTime.substring(0,bookedTime.length - 3);\n let index = currentAvailableTimesOnDate.indexOf(time);\n if (index > -1) { \n currentAvailableTimesOnDate.splice(index, 1);\n }\n })\n console.log(JSON.stringify(availableTimesPerDay));\n return availableTimesPerDay;\n}\n" }, { "answer_id": 74678259, "author": "trincot", "author_id": 5459839, "author_profile": "https://Stackoverflow.com/users/5459839", "pm_score": 3, "selected": true, "text": "availableTimesPerDay currentAvailableTimesOnDate availableTimesPerDay[bookedDate.getDate()] splice availableTimesPerDay[bookedDate.getDate()] let currentAvailableTimesOnDate = [...availableTimesPerDay[bookedDate.getDate()]];\n availableTimesPerDay let availableTimesPerDay = Array(7).fill( [\"10:00\",\"10:30\",\"11:00\",\"11:30\",\"12:00\"]);\n [\"10:00\",\"10:30\",\"11:00\",\"11:30\",\"12:00\"] let availableTimesPerDay = Array.from({length: 7}, () => \n [\"10:00\",\"10:30\",\"11:00\",\"11:30\",\"12:00\"]\n);\n" }, { "answer_id": 74678279, "author": "Aurast", "author_id": 3298338, "author_profile": "https://Stackoverflow.com/users/3298338", "pm_score": 0, "selected": false, "text": "let currentAvailableTimesOnDate = availableTimesPerDay[bookedDate.getDate()];\n const availableTimesPerDay = {\n 1: [\"10:00\",\"10:30\",\"11:00\",\"11:30\",\"12:00\"],\n 2: [\"10:00\",\"10:30\",\"11:00\",\"11:30\",\"12:00\"],\n 3: [\"10:00\",\"10:30\",\"11:00\",\"11:30\",\"12:00\"],\n};\n\nconst currentAvailableTimesOnDate = availableTimesPerDay[1];\ncurrentAvailableTimesOnDate.splice(0, 100);\n\nconsole.log(availableTimesPerDay[1]);\n const currentAvailableTimesOnDate = availableTimesPerDay[1].slice();\n// OR\nconst currentAvailableTimesOnDate = [...availableTimesPerDay[1]];\n// OR\nconst currentAvailableTimesOnDate = Array.from(availableTimesPerDay[1]);\n getDay() getDate() getDay()" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5353712/" ]
74,678,169
<p>I am trying to use the same ref for multiple input fields in for my form. But on logging it, the ref refers only to the first input field. Is there anyway I can use the same ref and use for different inputs?</p> <pre><code>import React, {FC, useEffect, useRef, useState} from 'react'; import { IFormProps } from '../../utils/Interfaces'; import 'react-phone-number-input/style.css' const Form:FC&lt;IFormProps&gt; = ({formData, handleFormData, errors, handleValidate}) =&gt; { const inputField = React.useRef() as React.MutableRefObject&lt;HTMLInputElement&gt;; return ( &lt;form className='user-form'&gt; &lt;label&gt;First Name&lt;/label&gt; &lt;input type=&quot;text&quot; ref = {inputField} value={formData.firstName} name=&quot;firstName&quot; id=&quot;firstName&quot; onChange={(e) =&gt; handleFormData(e)} placeholder=&quot;Enter your first name&quot; onFocus={() =&gt; console.log('focus')} onBlur={() =&gt; handleValidate(inputField)} /&gt; &lt;label&gt;Last Name&lt;/label&gt; &lt;input type=&quot;text&quot; value={formData.lastName} name=&quot;lastName&quot; id=&quot;lastName&quot; onChange={(e) =&gt; handleFormData(e)} placeholder=&quot;Enter the last name&quot; onBlur={() =&gt; handleValidate(inputField)} ref = {inputField} /&gt; &lt;/form&gt; ) } export default Form; </code></pre> <p>I am passing this information to the parent to handle validation. I am not sure how I can pass the same ref(inputField) as different input elements with its attributes.</p> <p>I have tried doing this <a href="https://stackoverflow.com/questions/72262303/use-a-single-ref-object-across-multiple-input-elements">Use a single ref object across multiple input elements</a>, but there is an error saying the following. I am aware its cause of typescript. But not sure how to handle it.</p> <pre><code>ref = {(el) =&gt; (inputField.current[&quot;firstName&quot;] = el)} </code></pre> <pre><code>Element implicitly has an 'any' type because expression of type '&quot;firstName&quot;' can't be used to index type 'HTMLInputElement'. Property 'firstName' does not exist on type 'HTMLInputElement'. </code></pre>
[ { "answer_id": 74678208, "author": "Muhammad Salman", "author_id": 15715337, "author_profile": "https://Stackoverflow.com/users/15715337", "pm_score": -1, "selected": false, "text": "function reduceAvailableTimesBasedOnDateTime(availableTimesPerDay,bookedTimes){\n console.log(JSON.stringify(availableTimesPerDay));\n bookedTimes.forEach((bookedDateObject) => {\n // Parse the string using the `Date.parse()` method\n let bookedDateMilliseconds = Date.parse(bookedDateObject.date);\n // Create a new Date object using the parsed date and time\n let bookedDate = new Date(bookedDateMilliseconds);\n let currentAvailableTimesOnDate = availableTimesPerDay[bookedDate.getDate()];\n let bookedTime = bookedDate.toLocaleTimeString('et');\n let time = bookedTime.substring(0,bookedTime.length - 3);\n let index = currentAvailableTimesOnDate.indexOf(time);\n if (index > -1) { \n currentAvailableTimesOnDate.splice(index, 1);\n }\n })\n console.log(JSON.stringify(availableTimesPerDay));\n return availableTimesPerDay;\n}\n function reduceAvailableTimesBasedOnDateTime(availableTimesPerDay,bookedTimes){\n console.log(JSON.stringify(availableTimesPerDay));\n bookedTimes.forEach((bookedDateObject) => {\n // Parse the string using the `Date.parse()` method\n let bookedDateMilliseconds = Date.parse(bookedDateObject.date);\n // Create a new Date object using the parsed date and time\n let bookedDate = new Date(bookedDateMilliseconds);\n // Create a new Date object using the original object's `getTime()` method\n let newBookedDate = new Date(bookedDate.getTime());\n let currentAvailableTimesOnDate = availableTimesPerDay[newBookedDate.getDate()];\n let bookedTime = newBookedDate.toLocaleTimeString('et');\n let time = bookedTime.substring(0,bookedTime.length - 3);\n let index = currentAvailableTimesOnDate.indexOf(time);\n if (index > -1) { \n currentAvailableTimesOnDate.splice(index, 1);\n }\n })\n console.log(JSON.stringify(availableTimesPerDay));\n return availableTimesPerDay;\n}\n" }, { "answer_id": 74678259, "author": "trincot", "author_id": 5459839, "author_profile": "https://Stackoverflow.com/users/5459839", "pm_score": 3, "selected": true, "text": "availableTimesPerDay currentAvailableTimesOnDate availableTimesPerDay[bookedDate.getDate()] splice availableTimesPerDay[bookedDate.getDate()] let currentAvailableTimesOnDate = [...availableTimesPerDay[bookedDate.getDate()]];\n availableTimesPerDay let availableTimesPerDay = Array(7).fill( [\"10:00\",\"10:30\",\"11:00\",\"11:30\",\"12:00\"]);\n [\"10:00\",\"10:30\",\"11:00\",\"11:30\",\"12:00\"] let availableTimesPerDay = Array.from({length: 7}, () => \n [\"10:00\",\"10:30\",\"11:00\",\"11:30\",\"12:00\"]\n);\n" }, { "answer_id": 74678279, "author": "Aurast", "author_id": 3298338, "author_profile": "https://Stackoverflow.com/users/3298338", "pm_score": 0, "selected": false, "text": "let currentAvailableTimesOnDate = availableTimesPerDay[bookedDate.getDate()];\n const availableTimesPerDay = {\n 1: [\"10:00\",\"10:30\",\"11:00\",\"11:30\",\"12:00\"],\n 2: [\"10:00\",\"10:30\",\"11:00\",\"11:30\",\"12:00\"],\n 3: [\"10:00\",\"10:30\",\"11:00\",\"11:30\",\"12:00\"],\n};\n\nconst currentAvailableTimesOnDate = availableTimesPerDay[1];\ncurrentAvailableTimesOnDate.splice(0, 100);\n\nconsole.log(availableTimesPerDay[1]);\n const currentAvailableTimesOnDate = availableTimesPerDay[1].slice();\n// OR\nconst currentAvailableTimesOnDate = [...availableTimesPerDay[1]];\n// OR\nconst currentAvailableTimesOnDate = Array.from(availableTimesPerDay[1]);\n getDay() getDate() getDay()" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8286824/" ]
74,678,197
<p>One of the inner values of my dynamic field contains &quot;@&quot;. How can I escape the @? (need to escape the &quot;fields.@version&quot;)</p> <pre><code>let Source = datatable (fields: dynamic) [ dynamic({&quot;seq&quot;:17300,&quot;@version&quot;:&quot;1&quot;}) ]; Source | project fields, fields.seq //, fields.@version </code></pre>
[ { "answer_id": 74678223, "author": "Guy Reginiano", "author_id": 14374898, "author_profile": "https://Stackoverflow.com/users/14374898", "pm_score": 0, "selected": false, "text": "let Source = datatable (fields: dynamic) [\n dynamic({\"seq\":17300,\"@version\":\"1\"})\n];\nSource | project fields, fields.seq , fields.['@version']\n" }, { "answer_id": 74678807, "author": "David דודו Markovitz", "author_id": 6336479, "author_profile": "https://Stackoverflow.com/users/6336479", "pm_score": 1, "selected": false, "text": "let Source = datatable (fields: dynamic) [\n dynamic({\"seq\":17300,\"@version\":\"1\"})\n];\nSource \n| project fields['@version'], fields[\"@version\"], fields[```@version```]\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14374898/" ]
74,678,226
<p>I'm the author of <a href="https://github.com/snoopyjc/pythonizer" rel="nofollow noreferrer">Pythonizer</a> and I'm trying to translate the code of CGI.pm from the standard perl library to Python. I came across this code in <a href="https://metacpan.org/dist/CGI/source/lib/CGI.pm#L1128" rel="nofollow noreferrer">read_from_client</a>:</p> <pre><code>read(\*STDIN, $$buff, $len, $offset) </code></pre> <p>Is <code>\*STDIN</code> the same thing as just <code>STDIN</code>? I'm not understanding why they are using it this way. Thanks for your help!</p> <p>The module also references <code>\*main::STDIN</code> - is this the same as <code>STDIN</code> too (I would translate plain <code>STDIN</code> to <code>sys.stdin</code> in python)? <a href="https://metacpan.org/dist/CGI/source/lib/CGI.pm#L213" rel="nofollow noreferrer">Code</a>:</p> <pre><code>foreach my $fh ( \*main::STDOUT, \*main::STDIN, \*main::STDERR, ) { ... } </code></pre>
[ { "answer_id": 74678223, "author": "Guy Reginiano", "author_id": 14374898, "author_profile": "https://Stackoverflow.com/users/14374898", "pm_score": 0, "selected": false, "text": "let Source = datatable (fields: dynamic) [\n dynamic({\"seq\":17300,\"@version\":\"1\"})\n];\nSource | project fields, fields.seq , fields.['@version']\n" }, { "answer_id": 74678807, "author": "David דודו Markovitz", "author_id": 6336479, "author_profile": "https://Stackoverflow.com/users/6336479", "pm_score": 1, "selected": false, "text": "let Source = datatable (fields: dynamic) [\n dynamic({\"seq\":17300,\"@version\":\"1\"})\n];\nSource \n| project fields['@version'], fields[\"@version\"], fields[```@version```]\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11397243/" ]
74,678,229
<p>I am trying to send a SOAP request and iteratively and the response captured for each iteration is as follows.</p> <pre><code>df = {'@diffgr:id': 'Table1', '@msdata:rowOrder': '0', 'NVIC_CUR': '0BQU22', 'NVIC_MODEL': '0BQU', 'ModelName': 'DIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC'} {'@diffgr:id': 'Table1', '@msdata:rowOrder': '0', 'NVIC_CUR': '0BQT22', 'NVIC_MODEL': '0BQT', 'ModelName': 'FDIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC'} [{'@diffgr:id': 'Table1', '@msdata:rowOrder': '0', 'NVIC_CUR': '09GE22', 'NVIC_MODEL': '09GE', 'ModelName': 'DIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC'}, {'@diffgr:id': 'Table2', '@msdata:rowOrder': '1', 'NVIC_CUR': '0BR222', 'NVIC_MODEL': '0BR2', 'ModelName': 'DIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC'}] [{'@diffgr:id': 'Table1', '@msdata:rowOrder': '0', 'NVIC_CUR': '09HR22', 'NVIC_MODEL': '09HR', 'ModelName': 'DIESEL TURBO 5 3198 cc DTFI 6 SP AUTOMATIC'}, {'@diffgr:id': 'Table2', '@msdata:rowOrder': '1', 'NVIC_CUR': '09HS22', 'NVIC_MODEL': '09HS', 'ModelName': 'DIESEL TURBO 5 3198 cc DTFI 6 SP MANUAL'}] </code></pre> <p>The SOAP API sometimes return dictionary data, and sometime list of dictionary.</p> <p>My idea was to create a Dataframe of selected columns (NVIC_CUR, NVIC_MODEL, ModelName)</p> <p><a href="https://i.stack.imgur.com/0ec0l.png" rel="nofollow noreferrer">output dataframe</a></p>
[ { "answer_id": 74678223, "author": "Guy Reginiano", "author_id": 14374898, "author_profile": "https://Stackoverflow.com/users/14374898", "pm_score": 0, "selected": false, "text": "let Source = datatable (fields: dynamic) [\n dynamic({\"seq\":17300,\"@version\":\"1\"})\n];\nSource | project fields, fields.seq , fields.['@version']\n" }, { "answer_id": 74678807, "author": "David דודו Markovitz", "author_id": 6336479, "author_profile": "https://Stackoverflow.com/users/6336479", "pm_score": 1, "selected": false, "text": "let Source = datatable (fields: dynamic) [\n dynamic({\"seq\":17300,\"@version\":\"1\"})\n];\nSource \n| project fields['@version'], fields[\"@version\"], fields[```@version```]\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20683444/" ]
74,678,233
<p>I have a base class and a child class, in the latter there is a method that is not present in the base class. Having several child classes with different methods, I need to declare an array of the type of the base class, but this way I cannot call the methods of the child classes. Here's my code:</p> <p><strong>Base class</strong></p> <pre><code>public class Athlete{ protected string name; public Athlete(string n) { this.name=n; } } </code></pre> <p><strong>Child Class</strong></p> <pre><code>public class Swimmer:Athlete{ string team; public Swimmer(string n, string t):Base(string n) { this.team=t; } public string Swim() { return &quot;I'm swimming!!!!&quot; ; } } </code></pre> <p><strong>Program</strong></p> <pre><code> Athete test = New Swimmer(&quot;John&quot;,&quot;Tigers&quot;); Console.WriteLine(test.Swim()); //Error!! </code></pre> <p>How can I solve this? Thanks in advance to anyone that will help me.</p>
[ { "answer_id": 74678300, "author": "Nick Scotney", "author_id": 4990925, "author_profile": "https://Stackoverflow.com/users/4990925", "pm_score": 0, "selected": false, "text": "public Swimmer(string n, string t) : base(n)\n{\n this.team = t;\n}\n internal class Program\n{\n static void Main(string[] arge)\n {\n Swimmer s = new Swimmer(\"Nick\", \"My Team\");\n Console.WriteLine(s.Swim());\n }\n} \n\npublic class Athlete\n{\n protected string name;\n\n public Athlete(string n)\n {\n this.name = n;\n }\n}\n\npublic class Swimmer : Athlete\n{\n string team;\n\n public Swimmer(string n, string t) : base(n)\n {\n this.team = t;\n }\n public string Swim()\n {\n return \"I'm swimming!!!!\";\n }\n}\n" }, { "answer_id": 74678344, "author": "Kanhaya Tyagi", "author_id": 14945515, "author_profile": "https://Stackoverflow.com/users/14945515", "pm_score": -1, "selected": false, "text": "//base class\npublic class Athlete\n{\n protected string name;\n\n public Athlete(string n)\n {\n name = n;\n }\n}\n// child class\npublic class Swimmer : Athlete\n{\n string team;\n\n public Swimmer(string n, string t) : base(n)\n {\n this.team = t;\n }\n\n public string Swim()\n {\n return \"I'm swimming!!!!\";\n }\n}\n\n//program main method\n Athlete test = new Swimmer(\"John\", \"Tigers\");\n if (test is Swimmer) {\n var swimmer = test as Swimmer;\n Console.WriteLine(swimmer.Swim());\n }\n" }, { "answer_id": 74678507, "author": "leocontext", "author_id": 12550194, "author_profile": "https://Stackoverflow.com/users/12550194", "pm_score": -1, "selected": false, "text": "//program\nConsole.WriteLine(((Swimmer)test).Swim());\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12550194/" ]
74,678,254
<p>Can someone help with setting up Heroicons in combination with Nuxt 3?</p> <p>I ran the following command:</p> <pre><code>yarn add @heroicons/vue </code></pre> <p>I also added @heroicons/vue as following to my <code>nuxt.config.js</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> build: { transpile: ["@headlessui/vue", "@heroicons/vue"], postcss: { plugins: { tailwindcss: {}, autoprefixer: {}, }, }, },</code></pre> </div> </div> </p> <p>But I can't seem to make it work at all.</p> <p>Could you tell me what I have to do?</p>
[ { "answer_id": 74678300, "author": "Nick Scotney", "author_id": 4990925, "author_profile": "https://Stackoverflow.com/users/4990925", "pm_score": 0, "selected": false, "text": "public Swimmer(string n, string t) : base(n)\n{\n this.team = t;\n}\n internal class Program\n{\n static void Main(string[] arge)\n {\n Swimmer s = new Swimmer(\"Nick\", \"My Team\");\n Console.WriteLine(s.Swim());\n }\n} \n\npublic class Athlete\n{\n protected string name;\n\n public Athlete(string n)\n {\n this.name = n;\n }\n}\n\npublic class Swimmer : Athlete\n{\n string team;\n\n public Swimmer(string n, string t) : base(n)\n {\n this.team = t;\n }\n public string Swim()\n {\n return \"I'm swimming!!!!\";\n }\n}\n" }, { "answer_id": 74678344, "author": "Kanhaya Tyagi", "author_id": 14945515, "author_profile": "https://Stackoverflow.com/users/14945515", "pm_score": -1, "selected": false, "text": "//base class\npublic class Athlete\n{\n protected string name;\n\n public Athlete(string n)\n {\n name = n;\n }\n}\n// child class\npublic class Swimmer : Athlete\n{\n string team;\n\n public Swimmer(string n, string t) : base(n)\n {\n this.team = t;\n }\n\n public string Swim()\n {\n return \"I'm swimming!!!!\";\n }\n}\n\n//program main method\n Athlete test = new Swimmer(\"John\", \"Tigers\");\n if (test is Swimmer) {\n var swimmer = test as Swimmer;\n Console.WriteLine(swimmer.Swim());\n }\n" }, { "answer_id": 74678507, "author": "leocontext", "author_id": 12550194, "author_profile": "https://Stackoverflow.com/users/12550194", "pm_score": -1, "selected": false, "text": "//program\nConsole.WriteLine(((Swimmer)test).Swim());\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13562685/" ]
74,678,276
<p>I have two tables in mysql database</p> <ol> <li><p>subjectids</p> <pre><code> id subject 11 Physics 12 Chemistry 13 Maths 14 Biology 15 History 16 Geography </code></pre> </li> <li><p>studentsScores</p> <pre><code> id student subjectid score 1 Ahaan 11 45 2 Ahaan 12 33 3 Ahaan 13 49 4 Ivaan 11 41 5 Ivaan 12 38 6 Ivaan 13 46 7 Ann 11 40 8 Ann 12 30 9 Ann 13 50 </code></pre> </li> </ol> <p>I am trying to find the average of each subject and give a tag of easy , medium, hard based on the average value, like hard if avg&lt;35, medium if avg between 35 and 45 and easy if avg greater than 45. My expected result is</p> <pre><code> subject subjectid avg_score level physics 11 42 medium chemistry 12 33 hard math 13 48 easy </code></pre> <p>I am new to sql, it would be great if you can help.</p>
[ { "answer_id": 74678300, "author": "Nick Scotney", "author_id": 4990925, "author_profile": "https://Stackoverflow.com/users/4990925", "pm_score": 0, "selected": false, "text": "public Swimmer(string n, string t) : base(n)\n{\n this.team = t;\n}\n internal class Program\n{\n static void Main(string[] arge)\n {\n Swimmer s = new Swimmer(\"Nick\", \"My Team\");\n Console.WriteLine(s.Swim());\n }\n} \n\npublic class Athlete\n{\n protected string name;\n\n public Athlete(string n)\n {\n this.name = n;\n }\n}\n\npublic class Swimmer : Athlete\n{\n string team;\n\n public Swimmer(string n, string t) : base(n)\n {\n this.team = t;\n }\n public string Swim()\n {\n return \"I'm swimming!!!!\";\n }\n}\n" }, { "answer_id": 74678344, "author": "Kanhaya Tyagi", "author_id": 14945515, "author_profile": "https://Stackoverflow.com/users/14945515", "pm_score": -1, "selected": false, "text": "//base class\npublic class Athlete\n{\n protected string name;\n\n public Athlete(string n)\n {\n name = n;\n }\n}\n// child class\npublic class Swimmer : Athlete\n{\n string team;\n\n public Swimmer(string n, string t) : base(n)\n {\n this.team = t;\n }\n\n public string Swim()\n {\n return \"I'm swimming!!!!\";\n }\n}\n\n//program main method\n Athlete test = new Swimmer(\"John\", \"Tigers\");\n if (test is Swimmer) {\n var swimmer = test as Swimmer;\n Console.WriteLine(swimmer.Swim());\n }\n" }, { "answer_id": 74678507, "author": "leocontext", "author_id": 12550194, "author_profile": "https://Stackoverflow.com/users/12550194", "pm_score": -1, "selected": false, "text": "//program\nConsole.WriteLine(((Swimmer)test).Swim());\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18937948/" ]
74,678,281
<p>I can't find how to plot these two series A and B with <code>time</code> on X.</p> <pre><code>from numpy import linspace import polars as pl import plotly.express as px import plotly.io as pio pio.renderers.default = 'browser' times = linspace(1, 6, 10) df = pl.DataFrame({ 'time': times, 'A': times**2, 'B': times**3, }) fig = px.line(df) fig.show() </code></pre> <p>Data keep showing as 10 series with 3 points, instead of 2 series with 10 points and the first column as X values.</p> <p><a href="https://i.stack.imgur.com/suYjO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/suYjO.png" alt="enter image description here" /></a></p> <hr /> <p>Edit:</p> <p>This line:</p> <pre><code>fig = px.line(df, x='time', y=['A', 'B']) </code></pre> <p>produces this error:</p> <blockquote> <p>ValueError: Value of 'x' is not the name of a column in 'data_frame'. Expected one of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] but received: time</p> </blockquote> <p>Using polars 0.15.0 and plotly 5.11.0</p>
[ { "answer_id": 74678326, "author": "Jiao Dian", "author_id": 8883383, "author_profile": "https://Stackoverflow.com/users/8883383", "pm_score": 0, "selected": false, "text": "# Import the necessary modules\nfrom numpy import linspace\nimport plotly.express as px\n\n# Create a DataFrame with time-series data for two series\ntimes = linspace(1, 6, 10)\ndf = pl.DataFrame({\n 'time': times,\n 'A': times**2,\n 'B': times**3,\n})\n\n# Use the line() function to plot the A and B columns from the DataFrame\nfig = px.line(df, x='time', y=['A', 'B'])\n\n# Show the plot\nfig.show()\n" }, { "answer_id": 74679469, "author": "Hamzah", "author_id": 16733101, "author_profile": "https://Stackoverflow.com/users/16733101", "pm_score": 2, "selected": true, "text": "Polars Dataframe Pandas dataframe to_pandas() fig = px.line(df.to_pandas(),x='time', y=['A', 'B'])\n fig = px.line(x=df['time'], y=[df[\"A\"],df[\"B\"]])\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/774575/" ]
74,678,314
<p>I'm trying to search and remove a comma <code>,</code> at the 2nd to the last line using sed.</p> <p>This is what I have now:</p> <pre><code>} &quot;user-account-id&quot;: &quot;John&quot;, &quot;user-account-number&quot;: &quot;v1001&quot;, &quot;user-account-app&quot;: &quot;v10.0.0&quot;, &quot;user-account-dbase&quot;: &quot;v10.1.0&quot;, } </code></pre> <p>I want the end result to be like this:</p> <pre><code>} &quot;user-account-id&quot;: &quot;John&quot;, &quot;user-account-number&quot;: &quot;v1001&quot;, &quot;user-account-app&quot;: &quot;v10.0.0&quot;, &quot;user-account-dbase&quot;: &quot;v10.1.0&quot; } </code></pre> <p>I thought I found the answer an hour after I posted this but I was wrong. It didn't work.</p> <p>Dry run with any of these combination doesn't work:</p> <pre><code>sed '2,$ s/,$//' filename sed '2,$ s/,//' filename sed '2,$ s/,//g' filename sed '2,$s/,$//' filename sed '2,$s/,//' filename sed '2,$s/,//g' filename </code></pre> <p>Actual removal with any of these combination doesn't work:</p> <pre><code>sed -i '2,$ s/,$//' filename sed -i '2,$ s/,//' filename sed -i '2,$ s/,//g' filename sed -i '2,$s/,$//' filename sed -i '2,$s/,//' filename sed -i '2,$s/,//g' filename </code></pre> <p>I thought running <code>sed</code> with <code>'2,$</code> would only modify &quot;2nd to the last line&quot; in the file.</p> <p>The output would just delete commas in every line, which doesn't make sense:</p> <pre><code>} &quot;user-account-id&quot;: &quot;John&quot; &quot;user-account-number&quot;: &quot;v1001&quot; &quot;user-account-app&quot;: &quot;v10.0.0&quot; &quot;user-account-dbase&quot;: &quot;v10.1.0&quot; } </code></pre>
[ { "answer_id": 74678410, "author": "Socowi", "author_id": 6770384, "author_profile": "https://Stackoverflow.com/users/6770384", "pm_score": 2, "selected": true, "text": "2,$ sed sed } sed -Ez 's/,([ \\t\\r\\n]*)\\}([ \\t\\r\\n]*)$/\\1}\\2/' file\n" }, { "answer_id": 74680164, "author": "glenn jackman", "author_id": 7552, "author_profile": "https://Stackoverflow.com/users/7552", "pm_score": 0, "selected": false, "text": "tac file | awk -v p=1 'p && /,$/ {sub(/,$/, \"\"); p=0} 1' | tac\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12693074/" ]
74,678,352
<p>I have an async function inside useEffect</p> <pre><code> useEffect(() =&gt; { async function fetchData() { const res = await checkLogin(); console.log(res); } fetchData(); }, []); </code></pre> <p>checkLogin returning &quot;Hello world&quot;</p> <pre><code> async function checkLogin() { try { const resp = await linstance.get(&quot;/api/auth/user&quot;); setUser(resp.data.user); setEmail(resp.data.email); setId(resp.data.id); return &quot;Hello world&quot;; } catch (error) { return error.response; } </code></pre> <p>}</p> <p>why in the console.log it's print undefined?</p> <p>I want checkLogin response to be &quot;Hello world&quot; (to make it clear)</p>
[ { "answer_id": 74678400, "author": "Hillel", "author_id": 7013797, "author_profile": "https://Stackoverflow.com/users/7013797", "pm_score": -1, "selected": false, "text": "fetchData useEffect useEffect fetchData useEffect fetchData useEffect useEffect(() => {\n async function fetchData() {\n const res = await checkLogin();\n console.log(res);\n }\n\n // Call the fetchData function directly\n fetchData();\n}, []);\n fetchData useEffect useEffect(() => {\nasync function fetchData() {\nconst res = await checkLogin();\nconsole.log(res);\n checkLogin" }, { "answer_id": 74678496, "author": "Yilmaz", "author_id": 10262805, "author_profile": "https://Stackoverflow.com/users/10262805", "pm_score": 3, "selected": true, "text": "checkLogin() try/catch catch error response catch catch (error) {\n // check what is logging here\n console.log(\"error in fetchLogin\", error)\n return error.response;\n}\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8776661/" ]
74,678,361
<p>I'm trying to get a key from a <code>JSON</code> from a website using the following code:</p> <pre class="lang-py prettyprint-override"><code>import json import requests from bs4 import BeautifulSoup url = input('Enter url:') html = requests.get(url) soup = BeautifulSoup(html.text,'html.parser') data = json.loads(soup.find('script', type='application/json').text) print(data) print(&quot;####################################&quot;) </code></pre> <p>And here is the <code>JSON</code>:</p> <pre class="lang-json prettyprint-override"><code>{&quot;props&quot;: { &quot;XYZ&quot;: { &quot;ABC&quot;: [ { &quot;current&quot;: &quot;sold&quot;, &quot;location&quot;: &quot;FD&quot;, &quot;type&quot;: &quot;d&quot;, &quot;uid&quot;: &quot;01020633&quot; } ], &quot;searchTerm&quot;: &quot;asd&quot; } }} </code></pre> <p>I'm able to load the page, find the <code>JSON</code>, and print all data. The question is, how can I print only the information from the <code>current</code> key? Will something like the following work?</p> <pre class="lang-py prettyprint-override"><code>print(data['props']['XYZ']['ABC']['current'] </code></pre>
[ { "answer_id": 74678549, "author": "newbie", "author_id": 10671274, "author_profile": "https://Stackoverflow.com/users/10671274", "pm_score": 1, "selected": false, "text": "data[\"props\"][\"XYZ\"][\"ABC\"][0][\"current\"]\n current ABC list" }, { "answer_id": 74678936, "author": "Siddharth Asodariya", "author_id": 19526287, "author_profile": "https://Stackoverflow.com/users/19526287", "pm_score": 0, "selected": false, "text": "data[\"props\"][\"XYZ\"][\"ABC\"][0][\"current\"]\n dict[key] or dict.get(key,default_value) list[0],list[1]" }, { "answer_id": 74680512, "author": "Driftr95", "author_id": 6146136, "author_profile": "https://Stackoverflow.com/users/6146136", "pm_score": 1, "selected": false, "text": "[0] ['ABC'] ['current'] \"ABC\" \"current\" data[\"props\"][\"XYZ\"][\"ABC\"][0][\"current\"]\n getNestedVal(data, 'current')\n sold getNestedVal(data, 'current', 'just_expr', 'data')\n data[\"props\"][\"XYZ\"][\"ABC\"][0][\"current\"]" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6484462/" ]
74,678,378
<p>If I run the following code once it works.</p> <pre><code>import numpy as np import rpy2.robjects as robjects x = np.linspace(0, 1, num = 11, endpoint=True) y = np.array([-1,1,1, -1,1,0, .5,.5,.4, .5, -1]) r_x = robjects.FloatVector(x) r_y = robjects.FloatVector(y) r_smooth_spline = robjects.r['smooth.spline'] #extract R function spline_xy = r_smooth_spline(x=r_x, y=r_y) print('x =', x) print('ysplined =',np.array(robjects.r['predict'](spline_xy,robjects.FloatVector(x)).rx2('y'))) </code></pre> <p>If I run this cell twice in a Jupyter notebook, I obtain the following error message:</p> <pre><code>--------------------------------------------------------------------------- NotImplementedError Traceback (most recent call last) &lt;ipython-input-2-5efeb940cd16&gt; in &lt;module&gt; 6 r_x = robjects.FloatVector(x) 7 r_y = robjects.FloatVector(y) ----&gt; 8 r_smooth_spline = robjects.r['smooth.spline'] #extract R function 9 spline_xy = r_smooth_spline(x=r_x, y=r_y) 10 print('x =', x) 2 frames /usr/local/lib/python3.8/dist-packages/rpy2/robjects/conversion.py in _rpy2py(obj) 250 non-rpy2) objects. 251 &quot;&quot;&quot; --&gt; 252 raise NotImplementedError( 253 &quot;Conversion 'rpy2py' not defined for objects of type '%s'&quot; % 254 str(type(obj)) NotImplementedError: Conversion 'rpy2py' not defined for objects of type '&lt;class 'rpy2.rinterface.SexpClosure'&gt;' </code></pre> <p>This code always used to run without problems multiple times. Probably a new version of python or rpy2 is the problem? How can I fix the problem such that I am able to run this code multiple times within one Jupyter notebook.</p>
[ { "answer_id": 74678549, "author": "newbie", "author_id": 10671274, "author_profile": "https://Stackoverflow.com/users/10671274", "pm_score": 1, "selected": false, "text": "data[\"props\"][\"XYZ\"][\"ABC\"][0][\"current\"]\n current ABC list" }, { "answer_id": 74678936, "author": "Siddharth Asodariya", "author_id": 19526287, "author_profile": "https://Stackoverflow.com/users/19526287", "pm_score": 0, "selected": false, "text": "data[\"props\"][\"XYZ\"][\"ABC\"][0][\"current\"]\n dict[key] or dict.get(key,default_value) list[0],list[1]" }, { "answer_id": 74680512, "author": "Driftr95", "author_id": 6146136, "author_profile": "https://Stackoverflow.com/users/6146136", "pm_score": 1, "selected": false, "text": "[0] ['ABC'] ['current'] \"ABC\" \"current\" data[\"props\"][\"XYZ\"][\"ABC\"][0][\"current\"]\n getNestedVal(data, 'current')\n sold getNestedVal(data, 'current', 'just_expr', 'data')\n data[\"props\"][\"XYZ\"][\"ABC\"][0][\"current\"]" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7735095/" ]
74,678,383
<p>I made a simple react hook.</p> <pre class="lang-js prettyprint-override"><code>import React from &quot;react&quot;; import { useNavigate } from &quot;react-router-dom&quot;; export default function SearchReq(searchTerm: string) { if (searchTerm === &quot;&quot;) return; const navigate = useNavigate(); console.log(searchTerm); // window.location.href = &quot;/search?searchTerm=&quot; + searchTerm; navigate(&quot;/search?searchTerm=&quot; + searchTerm, { replace: true }); } </code></pre> <p>But for some reason it is giving me an error I had figured out that the line that is causing an error is <code>const navigate = useNavigate()</code> but I don't understand why can any one explain it to me?</p> <p>Here is the error: <a href="https://i.stack.imgur.com/e49IR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e49IR.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74678398, "author": "Sachila Ranawaka", "author_id": 6428638, "author_profile": "https://Stackoverflow.com/users/6428638", "pm_score": 0, "selected": false, "text": "export default function SearchReq(searchTerm: string) {\n\n const navigate = useNavigate(); \n\n // window.location.href = \"/search?searchTerm=\" + searchTerm;\n\n useEffect(() => {\n if(searchTerm) navigate(\"/search?searchTerm=\" + searchTerm, { replace: true });\n\n }, [searchTerm])\n\n return null\n}\n" }, { "answer_id": 74678431, "author": "Necati Turan", "author_id": 4335325, "author_profile": "https://Stackoverflow.com/users/4335325", "pm_score": 2, "selected": true, "text": "import React from \"react\";\nimport { useNavigate } from \"react-router-dom\";\nimport { Router } from \"react-router\"; \n\nfunction MyComponent() {\n const navigate = useNavigate();\n\n const handleClick = () => {\n navigate(\"/some/other/route\");\n };\n\n return (\n <button onClick={handleClick}>\n Go to some other route\n </button>\n );\n}\n\nfunction App() {\n return (\n <Router>\n <MyComponent />\n </Router>\n );\n}\n import React from \"react\";\nimport { useNavigate } from \"react-router-dom\";\n\nfunction MyComponent() {\n const navigate = useNavigate();\n\n // Navigate to a different route when the button is clicked\n const handleClick = () => {\n navigate(\"/some/other/route\");\n };\n\n return (\n <button onClick={handleClick}>\n Go to some other route\n </button>\n );\n}\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17286169/" ]
74,678,396
<p>I have a problem where the line of codes in my Update function does not work. I added a debug.log both at the start and end of the update function but the whole if statement does not work. The <code>dialogCycle</code> variable does not even increment. Is there something wrong with the whole script?</p> <p>Here is the script:</p> <pre><code>using System; using System.Linq; using TMPro; using UnityEngine; using UnityEngine.UI; public class TelevisionEvent : MonoBehaviour { [SerializeField] private GameData gameData; // SCRIPTABLEOBJECT [SerializeField] private GameObject dialogbox, interactButton; [SerializeField] private FollowPlayer followPlayer; [SerializeField] private Transform tv, player; [SerializeField] private TextAsset objectData; private ObjectDialog objectJson; public string[] dialogMessage; public int dialogCycle; public bool clickEnable; private void Update() { //if (gameData.isWatched) return; if (Input.GetMouseButtonDown(0) &amp;&amp; clickEnable) { Debug.Log(&quot;Clicked&quot;); // THIS WORKS dialogCycle++; // I PUT THIS OUTSIDE TO CHECK IF IT WILL WORK OUTSIDE THE IF BUT IT STILL DOES NOT tvDialog(); // THE DEBUG.LOG IS THE ONE THAT ONLY WORKS if (dialogCycle != dialogMessage.Length - 1) // BUT THIS WHOLE IF STATEMENT DOES NOT GET CHECKED { dialogCycle++; tvDialog(); } else { dialogbox.SetActive(false); dialogCycle = 0; Array.Clear(dialogMessage, 0, dialogMessage.Length); clickEnable = false; gameData.isWatched = true; followPlayer.player = player; } Debug.Log(&quot;Clicked2&quot;); // THIS WORKS TOO } } private void OnTriggerEnter(Collider collisionInfo) { if(gameData.isWatched) return; if (collisionInfo.CompareTag(&quot;Player&quot;)) { interactButton.GetComponent&lt;Button&gt;().onClick.RemoveListener(tvDialog); interactButton.GetComponent&lt;Button&gt;().onClick.AddListener(tvDialog); } } private void OnTriggerExit(Collider collisionInfo) { Debug.Log(&quot;Hello&quot;); if (gameData.isWatched) return; if (collisionInfo.CompareTag(&quot;Player&quot;)) { interactButton.GetComponent&lt;Button&gt;().onClick.RemoveListener(tvDialog); } } public void tvDialog() { dialogbox.SetActive(true); interactButton.SetActive(false); dialogCycle = 0; followPlayer.player = tv; objectJson = JsonUtility.FromJson&lt;ObjectDialog&gt;(objectData.text); loadDialog(); } public void loadDialog() { dialogbox.transform.GetChild(0).GetComponent&lt;TextMeshProUGUI&gt;().text = objectJson.name; dialogMessage = objectJson.object_dialog.Split('#'); dialogbox.transform.GetChild(1).GetComponent&lt;TextMeshProUGUI&gt;().text = dialogMessage[dialogCycle]; clickEnable = true; } } </code></pre> <p>For more info, the game object that it is attached to have another script. Will it have an effect in this script? the other script is just like this but it is like an object interaction manager for the map (opening doors, etc.).</p> <p><a href="https://i.stack.imgur.com/lQVF9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lQVF9.png" alt="inspector" /></a></p> <p>By 'just like this' I mean there is also a line of codes similar to the prior script above. The script above is for an event when the player opens the door for the first time a television dialogue event will trigger. In the other script, I have the object interaction where I interact with object like a radio and the dialogue will show.</p> <p>I can just show you the script just for more info. the similarities will be in the update function and the last part of the script which is the <code>objectDialog</code> method</p> <pre><code>using System; using System.Linq; using TMPro; using UnityEngine; using UnityEngine.UI; public class ObjectInteraction : MonoBehaviour { [SerializeField] private GameData gameData; [SerializeField] private GameObject interactButton, cafeArrow, aptArrow, konbiniArrow; [SerializeField] private GameObject cryptogram; [SerializeField] private GameObject dialogbox; private static ObjectInteraction instance; private ObjectDialog objectJson; private TextAsset objectData; private string[] dialogMessage; private int dialogCycle; private bool clickEnable; private int[] apartment = { 3, 8, 15, 16 }; // APARTMENT private int[] cafe = Enumerable.Range(0, 17).ToArray(); // CAFE private int[] konbini = { 77, 78, 82, 83 }; // CONVENIENT STORE private static bool isInside, isOpen; private void Start() { isInside = false; isOpen = false; //Debug.Log(dialogCycle); } private void Update() { //if (instance != this) return; if (Input.GetMouseButtonDown(0) &amp;&amp; clickEnable) { if(dialogCycle != dialogMessage.Length-1) { dialogCycle++; loadDialog(); }else { dialogbox.SetActive(false); dialogCycle = 0; Array.Clear(dialogMessage, 0, dialogMessage.Length); clickEnable = false; } } } private void OnTriggerEnter(Collider collisionInfo) { if(collisionInfo.CompareTag(&quot;Player&quot;)) { if(gameObject.CompareTag(&quot;Door&quot;)) { interactButton.SetActive(true); interactButton.GetComponent&lt;Image&gt;().sprite = Resources.Load&lt;Sprite&gt;(&quot;InteractionAsset/OBJECT&quot;); interactButton.transform.GetChild(0).GetComponent&lt;TextMeshProUGUI&gt;().text = &quot;Open&quot;; interactButton.GetComponent&lt;Button&gt;().onClick.RemoveListener(enter); interactButton.GetComponent&lt;Button&gt;().onClick.AddListener(enter); } else if(gameObject.CompareTag(&quot;Newspaper&quot;)) { if (!gameData.cryptoDone) { interactButton.SetActive(true); interactButton.GetComponent&lt;Image&gt;().sprite = Resources.Load&lt;Sprite&gt;(&quot;InteractionAsset/OBJECT&quot;); interactButton.transform.GetChild(0).GetComponent&lt;TextMeshProUGUI&gt;().text = &quot;View&quot;; gameObject.GetComponent&lt;Outline&gt;().enabled = true; // ADD ONCLICK FOR NEWSPAPER interactButton.GetComponent&lt;Button&gt;().onClick.RemoveAllListeners(); interactButton.GetComponent&lt;Button&gt;().onClick.AddListener(showCryptogram); } } else if(gameObject.CompareTag(&quot;ObjectDialog&quot;)) { interactButton.SetActive(true); interactButton.GetComponent&lt;Image&gt;().sprite = Resources.Load&lt;Sprite&gt;(&quot;InteractionAsset/OBJECT&quot;); interactButton.transform.GetChild(0).GetComponent&lt;TextMeshProUGUI&gt;().text = &quot;View&quot;; gameObject.GetComponent&lt;Outline&gt;().enabled = true; interactButton.GetComponent&lt;Button&gt;().onClick.RemoveAllListeners(); interactButton.GetComponent&lt;Button&gt;().onClick.AddListener(objectDialog); } // WHEN LEAVING ROOMS if (gameObject.name == &quot;apt_floor&quot;) { isInside = true; aptArrow.SetActive(true); } else if (gameObject.name == &quot;cafe_floor&quot;) { isInside = true; cafeArrow.SetActive(true); } else if(gameObject.name == &quot;konbini_floor&quot;) { isInside = true; konbiniArrow.SetActive(true); } } } private void OnTriggerExit(Collider collisionInfo) { interactButton.SetActive(false); interactButton.GetComponent&lt;Button&gt;().onClick.RemoveAllListeners(); if (collisionInfo.CompareTag(&quot;Player&quot;)) { // TURN OFF OUTLINE / HIGHLIGHT if(gameObject.CompareTag(&quot;Newspaper&quot;)) { gameObject.GetComponent&lt;Outline&gt;().enabled = false; } else if (gameObject.CompareTag(&quot;ObjectDialog&quot;)) { gameObject.GetComponent&lt;Outline&gt;().enabled = false; } // WHEN LEAVING ROOMS if (gameObject.name == &quot;apt_floor&quot; || (gameObject.name == &quot;apt_wall&quot; &amp;&amp; !isInside &amp;&amp; isOpen)) { for (int i = 0; i &lt; apartment.Length; i++) { transform.root.GetChild(apartment[i]).GetComponent&lt;MeshRenderer&gt;().enabled = true; transform.root.GetChild(apartment[i]).gameObject.SetActive(true); } aptArrow.SetActive(false); } else if(gameObject.name == &quot;cafe_floor&quot; || (gameObject.name == &quot;cafe_wall&quot; &amp;&amp; !isInside &amp;&amp; isOpen)) { for (int i = 0; i &lt; cafe.Length; i++) { if (i != 13) { transform.root.GetChild(cafe[i]).gameObject.SetActive(true); } } transform.root.GetChild(63).GetComponent&lt;MeshRenderer&gt;().enabled = true; transform.root.GetChild(67).GetComponent&lt;MeshRenderer&gt;().enabled = true; transform.root.GetChild(68).GetComponent&lt;MeshRenderer&gt;().enabled = true; transform.root.GetChild(59).gameObject.SetActive(true); cafeArrow.SetActive(false); } else if(gameObject.name == &quot;konbini_floor&quot; || (gameObject.name == &quot;konbini_wall&quot; &amp;&amp; !isInside &amp;&amp; isOpen)) { for (int i = 0; i &lt; konbini.Length; i++) { transform.root.GetChild(konbini[i]).GetComponent&lt;MeshRenderer&gt;().enabled = true; } transform.root.GetChild(73).gameObject.SetActive(true); transform.root.GetChild(74).gameObject.SetActive(true); konbiniArrow.SetActive(false); } } } // ENTER ROOM public void enter() { FindObjectOfType&lt;AudioManager&gt;().Play(&quot;ButtonSound&quot;); if (gameObject.name == &quot;apt_door&quot;) { for(int i = 0; i &lt; apartment.Length; i++) { transform.root.GetChild(apartment[i]).GetComponent&lt;MeshRenderer&gt;().enabled = false; } gameObject.SetActive(false); }else if(gameObject.name == &quot;cafe_door&quot;) { for (int i = 0; i &lt; cafe.Length; i++) { if(i != 13) { transform.root.GetChild(cafe[i]).gameObject.SetActive(false); } } transform.root.GetChild(63).GetComponent&lt;MeshRenderer&gt;().enabled = false; transform.root.GetChild(67).GetComponent&lt;MeshRenderer&gt;().enabled = false; transform.root.GetChild(68).GetComponent&lt;MeshRenderer&gt;().enabled = false; gameObject.SetActive(false); }else if(gameObject.name == &quot;konbini_door1&quot;) { for (int i = 0; i &lt; konbini.Length; i++) { transform.root.GetChild(konbini[i]).GetComponent&lt;MeshRenderer&gt;().enabled = false; } transform.root.GetChild(73).gameObject.SetActive(false); transform.root.GetChild(74).gameObject.SetActive(false); } isOpen = true; interactButton.SetActive(false); interactButton.GetComponent&lt;Button&gt;().onClick.RemoveListener(enter); } // SHOW CRYPTOGRAM MINIGAME IN OBJECT public void showCryptogram() { FindObjectOfType&lt;AudioManager&gt;().Play(&quot;ButtonSound&quot;); cryptogram.SetActive(true); } public void objectDialog() { dialogbox.SetActive(true); interactButton.SetActive(false); dialogCycle = 0; loadJson(); loadDialog(); } public void loadJson() { if (gameObject.name == &quot;Radio&quot;) { objectData = Resources.Load&lt;TextAsset&gt;(&quot;JSON/Objects/Radio&quot;); }else if(gameObject.name == &quot;Television&quot;) { objectData = Resources.Load&lt;TextAsset&gt;(&quot;JSON/Objects/TV&quot;); } objectJson = JsonUtility.FromJson&lt;ObjectDialog&gt;(objectData.text); } public void loadDialog() { dialogbox.transform.GetChild(0).GetComponent&lt;TextMeshProUGUI&gt;().text = objectJson.name; dialogMessage = objectJson.object_dialog.Split('#'); if (dialogMessage.Length == 1) { dialogbox.transform.GetChild(1).GetComponent&lt;TextMeshProUGUI&gt;().text = objectJson.object_dialog; } else if (dialogCycle &lt; dialogMessage.Length) { dialogbox.transform.GetChild(1).GetComponent&lt;TextMeshProUGUI&gt;().text = dialogMessage[dialogCycle]; clickEnable = true; } } } </code></pre>
[ { "answer_id": 74678398, "author": "Sachila Ranawaka", "author_id": 6428638, "author_profile": "https://Stackoverflow.com/users/6428638", "pm_score": 0, "selected": false, "text": "export default function SearchReq(searchTerm: string) {\n\n const navigate = useNavigate(); \n\n // window.location.href = \"/search?searchTerm=\" + searchTerm;\n\n useEffect(() => {\n if(searchTerm) navigate(\"/search?searchTerm=\" + searchTerm, { replace: true });\n\n }, [searchTerm])\n\n return null\n}\n" }, { "answer_id": 74678431, "author": "Necati Turan", "author_id": 4335325, "author_profile": "https://Stackoverflow.com/users/4335325", "pm_score": 2, "selected": true, "text": "import React from \"react\";\nimport { useNavigate } from \"react-router-dom\";\nimport { Router } from \"react-router\"; \n\nfunction MyComponent() {\n const navigate = useNavigate();\n\n const handleClick = () => {\n navigate(\"/some/other/route\");\n };\n\n return (\n <button onClick={handleClick}>\n Go to some other route\n </button>\n );\n}\n\nfunction App() {\n return (\n <Router>\n <MyComponent />\n </Router>\n );\n}\n import React from \"react\";\nimport { useNavigate } from \"react-router-dom\";\n\nfunction MyComponent() {\n const navigate = useNavigate();\n\n // Navigate to a different route when the button is clicked\n const handleClick = () => {\n navigate(\"/some/other/route\");\n };\n\n return (\n <button onClick={handleClick}>\n Go to some other route\n </button>\n );\n}\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20502646/" ]
74,678,432
<p>I have the next implementation of Linked List:</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>class Node { constructor(data) { this.data = data; this.next = null; } } class LinkedLIst { constructor() { this.head = {}; } add(head) { if(!this.head.next) { this.head = new Node(head); } this.head.next = new Node(head); } } const list = new LinkedLIst(); list.add(1) list.add(2) list.add(3) console.log(list)</code></pre> </div> </div> </p> <p>I don't understand, why <code>2</code> is not added within the list? And how to fix that?</p>
[ { "answer_id": 74678398, "author": "Sachila Ranawaka", "author_id": 6428638, "author_profile": "https://Stackoverflow.com/users/6428638", "pm_score": 0, "selected": false, "text": "export default function SearchReq(searchTerm: string) {\n\n const navigate = useNavigate(); \n\n // window.location.href = \"/search?searchTerm=\" + searchTerm;\n\n useEffect(() => {\n if(searchTerm) navigate(\"/search?searchTerm=\" + searchTerm, { replace: true });\n\n }, [searchTerm])\n\n return null\n}\n" }, { "answer_id": 74678431, "author": "Necati Turan", "author_id": 4335325, "author_profile": "https://Stackoverflow.com/users/4335325", "pm_score": 2, "selected": true, "text": "import React from \"react\";\nimport { useNavigate } from \"react-router-dom\";\nimport { Router } from \"react-router\"; \n\nfunction MyComponent() {\n const navigate = useNavigate();\n\n const handleClick = () => {\n navigate(\"/some/other/route\");\n };\n\n return (\n <button onClick={handleClick}>\n Go to some other route\n </button>\n );\n}\n\nfunction App() {\n return (\n <Router>\n <MyComponent />\n </Router>\n );\n}\n import React from \"react\";\nimport { useNavigate } from \"react-router-dom\";\n\nfunction MyComponent() {\n const navigate = useNavigate();\n\n // Navigate to a different route when the button is clicked\n const handleClick = () => {\n navigate(\"/some/other/route\");\n };\n\n return (\n <button onClick={handleClick}>\n Go to some other route\n </button>\n );\n}\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12540500/" ]
74,678,473
<p>This example <a href="https://godbolt.org/z/EKvvEKa6T" rel="nofollow noreferrer">https://godbolt.org/z/EKvvEKa6T</a> calls MyFun() using this syntax</p> <pre><code>(*((int(**)(void))CallMyFun))(); </code></pre> <p>Is there a C breakdown of that obfuscated syntax to explain how it works?</p> <pre><code>#include &lt;stdio.h&gt; int MyFun(void) { printf(&quot;Hello, World!&quot;); return 0; } void *funarray[] = { NULL,NULL,&amp;MyFun,NULL,NULL }; int main(void) { size_t CallMyFun = (size_t)&amp;funarray + (2 * sizeof(funarray[0])); return (*((int(**)(void))CallMyFun))(); } </code></pre>
[ { "answer_id": 74678672, "author": "Eric Postpischil", "author_id": 298225, "author_profile": "https://Stackoverflow.com/users/298225", "pm_score": 3, "selected": true, "text": "void *funarray[] = { NULL,NULL,&MyFun,NULL,NULL }; MyFun void * size_t CallMyFun = (size_t)&funarray + (2 * sizeof(funarray[0])); CallMyFun funarray size_t (*((int(**)(void))CallMyFun))(); (int(**)(void)) CallMyFun CallMyFun int void * void void * MyFun () // Use array of pointers to functions (of a forced type).\nvoid (*funarray[])(void) = { NULL, NULL, (void (*)(void)) MyFun, NULL, NULL };\n\n…\n\n// Get array element using ordinary subscript notation.\nvoid (*CallMyFunc)(void) = funarray[2];\n\n// Convert pointer to function’s actual type, then call it.\nreturn ((int (*)(void)) CallMyFunc)();\n int (*funarray[])(void) = { NULL, NULL, MyFun, NULL, NULL };\n\n…\n\nreturn funarray[2]();\n" }, { "answer_id": 74678723, "author": "Unn", "author_id": 2774842, "author_profile": "https://Stackoverflow.com/users/2774842", "pm_score": 1, "selected": false, "text": "void *funarray[] = { NULL,NULL,&MyFun,NULL,NULL };\n NULL MyFunc &MyFunc int (*)(void) * void * void * size_t CallMyFun = (size_t)&funarray + (2 * sizeof(funarray[0]));\n size_t (size_t) &funarray[2] int (*[])(void) void*[] size_t return (*((int(**)(void))CallMyFun))();\n CallMyFunc MyFunc ((int(**)(void))CallMyFun) CallMyFunc size_t int (**)(void) int (*)(void) (*((int(**)(void))CallMyFun))" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2801187/" ]
74,678,481
<p>Given an NxM matrix A, I want to efficiently obtain the NxMxN tensor whose ith layer is the application of np.minimum between A and the ith row of A. Using a for loop:</p> <pre><code>&gt; A = np.array([[1, 2], [3, 4], [5,6]]) &gt; output = np.zeros(shape=(A.shape[0], A.shape[1], A.shape[0])) &gt; for i in range(a.shape[0]): output[:, :, i] = np.minimum(A, A[i]) &gt; output array([[[1., 1., 1.], [2., 2., 2.]], [[1., 3., 3.], [2., 4., 4.]], [[1., 3., 5.], [2., 4., 6.]]]) </code></pre> <p>This is very slow so I would like to get rid of the for loop and vectorize it. I feel like there should be a general method that works with any function of a matrix and a vector not just, minimum. Using np.minimum.outer does not work as it outputs an order 4 tensor.</p>
[ { "answer_id": 74678581, "author": "newbie", "author_id": 10671274, "author_profile": "https://Stackoverflow.com/users/10671274", "pm_score": 0, "selected": false, "text": "np.einsum import numpy as np\n\n\nA = np.array([[1, 2], [3, 4], [5,6]])\n\n\noutput = np.einsum('ij,ik->ijk', A, A)\n\n\nprint(output)\n np.einsum 'ij,ik->ijk' np.einsum 'ij' 'ik' 'ijk' np.einsum" }, { "answer_id": 74679017, "author": "hpaulj", "author_id": 901925, "author_profile": "https://Stackoverflow.com/users/901925", "pm_score": 1, "selected": false, "text": "broadcasting In [153]: np.minimum(A[:,None,:],A[None,:,:])\nOut[153]: \narray([[[1, 2],\n [1, 2],\n [1, 2]],\n\n [[1, 2],\n [3, 4],\n [3, 4]],\n\n [[1, 2],\n [3, 4],\n [5, 6]]])\n In [154]: np.minimum(A[:,None,:],A[None,:,:]).transpose(0,2,1)\nOut[154]: \narray([[[1, 1, 1],\n [2, 2, 2]],\n\n [[1, 3, 3],\n [2, 4, 4]],\n\n [[1, 3, 5],\n [2, 4, 6]]])\n In [155]: np.minimum(A[:,:,None],A.T[None,:,:]) # (3,2,1) (1,2,3)=>(3,2,3)\nOut[155]: \narray([[[1, 1, 1],\n [2, 2, 2]],\n\n [[1, 3, 3],\n [2, 4, 4]],\n\n [[1, 3, 5],\n [2, 4, 6]]])\n In [157]: np.minimum(A[:,:,None],A.T[None,:,:]).sum(axis=1)\nOut[157]: \narray([[ 3, 3, 3],\n [ 3, 7, 7],\n [ 3, 7, 11]])\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13716182/" ]
74,678,498
<p>I'm trying to create a function which can move a page element without having to reference it specifically.</p> <pre><code> function testmove(obj, event) { document.getElementById(obj.id).addEventListener(&quot;mousemove&quot;, move(obj,event)); } function move(obj, event) { document.getElementById(obj.id).innerText = event.clientX + ' ' + event.clientY; document.getElementById(obj.id).style.position = 'absolute'; document.getElementById(obj.id).style.left = event.clientX + &quot;px&quot;; document.getElementById(obj.id).style.top = event.clientY + &quot;px&quot;; } </code></pre> <p>This is the original code which worked fluidly:</p> <pre><code> function testmove(e) { document.addEventListener('mousemove', logmovement); } function logmovement(e) { document.getElementById(&quot;test&quot;).innerText = e.clientX + ' ' + e.clientY; document.getElementById(&quot;test&quot;).style.position = 'absolute'; document.getElementById(&quot;test&quot;).style.left = e.clientX + &quot;px&quot;; document.getElementById(&quot;test&quot;).style.top = e.clientY + &quot;px&quot;; mousemove = true; } </code></pre> <p>Any help is greatly appreciated!</p>
[ { "answer_id": 74678557, "author": "Necati Turan", "author_id": 4335325, "author_profile": "https://Stackoverflow.com/users/4335325", "pm_score": 0, "selected": false, "text": "function testmove(obj, event) {\n document.getElementById(obj.id).addEventListener(\"mousemove\", move);\n}\nfunction move(event) {\n document.getElementById(obj.id).innerText = event.clientX + ' ' + event.clientY;\n document.getElementById(obj.id).style.position = 'absolute';\n document.getElementById(obj.id).style.left = event.clientX + \"px\";\n document.getElementById(obj.id).style.top = event.clientY + \"px\";\n}\nfunction testmove(obj, event) {\n document.getElementById(obj.id).addEventListener(\"mousemove\", function() {\n testmove(obj, event);\n });\n}\n" }, { "answer_id": 74678715, "author": "Andy", "author_id": 1377002, "author_profile": "https://Stackoverflow.com/users/1377002", "pm_score": 1, "selected": false, "text": "move // Pass in the object\nfunction testmove(obj) {\n\n // Add the listener to the document element as in the\n // working example. Pass a function that calls `move` to the\n // listener.\n document.addEventListener(\"mousemove\", () => move(obj, event));\n}\n\nfunction move(obj, event) {\n document.getElementById(obj.id).innerText = event.clientX + ' ' + event.clientY;\n document.getElementById(obj.id).style.position = 'absolute';\n document.getElementById(obj.id).style.left = event.clientX + \"px\";\n document.getElementById(obj.id).style.top = event.clientY + \"px\";\n}\n\nconst obj = { id: 'move' };\n\ntestmove(obj); <div id=\"move\">Move</div>" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/784446/" ]
74,678,499
<p>I have the following question. I have generated the following RowNumber column by usage of the rownumber() function and the over(paritation by clause. The counting starts with '1' every time a new part_no is listed:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>SEQ_NO</th> <th>PART_NO</th> <th>RowNumber</th> <th>LEVEL</th> </tr> </thead> <tbody> <tr> <td>110</td> <td>PRD101</td> <td>1</td> <td>1</td> </tr> <tr> <td>120</td> <td>PRD101</td> <td>2</td> <td>2</td> </tr> <tr> <td>130</td> <td>PRD101</td> <td>3</td> <td>3</td> </tr> <tr> <td>140</td> <td>PRD101</td> <td>4</td> <td>4</td> </tr> <tr> <td>150</td> <td>PRD101</td> <td>5</td> <td>1</td> </tr> <tr> <td>160</td> <td>PRD101</td> <td>6</td> <td>2</td> </tr> <tr> <td>110</td> <td>PRD102</td> <td>1</td> <td>1</td> </tr> <tr> <td>120</td> <td>PRD102</td> <td>2</td> <td>2</td> </tr> <tr> <td>130</td> <td>PRD102</td> <td>3</td> <td>2</td> </tr> <tr> <td>140</td> <td>PRD102</td> <td>4</td> <td>1</td> </tr> <tr> <td>110</td> <td>PRD103</td> <td>1</td> <td>1</td> </tr> <tr> <td>120</td> <td>PRD103</td> <td>2</td> <td>1</td> </tr> </tbody> </table> </div> <p>The query is kind of like this:</p> <pre><code>select seq_no, part_no, row_number() over(partition by part_no order by seq_no) as RowNumber, level from table1 </code></pre> <p>The point is that I would like to create a second sequence which does not fill any value in for rows where levels &gt; 2<br /> The second sequence is also paritated by the part_no</p> <p>The table would result like:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>SEQ_NO</th> <th>PART_NO</th> <th>RowNumber</th> <th>SecondRowNumber</th> <th>LEVEL</th> </tr> </thead> <tbody> <tr> <td>110</td> <td>PRD101</td> <td>1</td> <td>1</td> <td>1</td> </tr> <tr> <td>120</td> <td>PRD101</td> <td>2</td> <td>2</td> <td>2</td> </tr> <tr> <td>130</td> <td>PRD101</td> <td>3</td> <td></td> <td>3</td> </tr> <tr> <td>140</td> <td>PRD101</td> <td>4</td> <td></td> <td>4</td> </tr> <tr> <td>150</td> <td>PRD101</td> <td>5</td> <td>3</td> <td>1</td> </tr> <tr> <td>160</td> <td>PRD101</td> <td>6</td> <td>4</td> <td>2</td> </tr> <tr> <td>110</td> <td>PRD102</td> <td>1</td> <td>1</td> <td>1</td> </tr> <tr> <td>120</td> <td>PRD102</td> <td>2</td> <td>2</td> <td>2</td> </tr> <tr> <td>130</td> <td>PRD102</td> <td>3</td> <td>3</td> <td>2</td> </tr> <tr> <td>140</td> <td>PRD102</td> <td>4</td> <td>4</td> <td>1</td> </tr> <tr> <td>110</td> <td>PRD103</td> <td>1</td> <td>1</td> <td>1</td> </tr> <tr> <td>120</td> <td>PRD103</td> <td>2</td> <td>2</td> <td>1</td> </tr> </tbody> </table> </div> <p>Does anyone have an idea how to solve this?</p>
[ { "answer_id": 74678557, "author": "Necati Turan", "author_id": 4335325, "author_profile": "https://Stackoverflow.com/users/4335325", "pm_score": 0, "selected": false, "text": "function testmove(obj, event) {\n document.getElementById(obj.id).addEventListener(\"mousemove\", move);\n}\nfunction move(event) {\n document.getElementById(obj.id).innerText = event.clientX + ' ' + event.clientY;\n document.getElementById(obj.id).style.position = 'absolute';\n document.getElementById(obj.id).style.left = event.clientX + \"px\";\n document.getElementById(obj.id).style.top = event.clientY + \"px\";\n}\nfunction testmove(obj, event) {\n document.getElementById(obj.id).addEventListener(\"mousemove\", function() {\n testmove(obj, event);\n });\n}\n" }, { "answer_id": 74678715, "author": "Andy", "author_id": 1377002, "author_profile": "https://Stackoverflow.com/users/1377002", "pm_score": 1, "selected": false, "text": "move // Pass in the object\nfunction testmove(obj) {\n\n // Add the listener to the document element as in the\n // working example. Pass a function that calls `move` to the\n // listener.\n document.addEventListener(\"mousemove\", () => move(obj, event));\n}\n\nfunction move(obj, event) {\n document.getElementById(obj.id).innerText = event.clientX + ' ' + event.clientY;\n document.getElementById(obj.id).style.position = 'absolute';\n document.getElementById(obj.id).style.left = event.clientX + \"px\";\n document.getElementById(obj.id).style.top = event.clientY + \"px\";\n}\n\nconst obj = { id: 'move' };\n\ntestmove(obj); <div id=\"move\">Move</div>" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18443141/" ]
74,678,537
<p>So I am trying to update a record with multiple fields in my database using laravel, however I am trying to validate the input first before proceeding with the actual updating of the record.</p> <p>So my problem is that one of my field has to be unique and should allow the other fields to be edited even if that field is not edited.</p> <p>I know that in the document it is that we can use this code to do that.</p> <pre><code>use Illuminate\Support\Facades\Validator; use Illuminate\Validation\Rule;   Validator::make($data, [ 'email' =&gt; [ 'required', Rule::unique('users')-&gt;ignore($user-&gt;id), ], ]); </code></pre> <p>However, the id that is supposed to be used in the ignore method is also validated.</p> <pre><code>'product_id' =&gt; 'required|string|exists:' . Product::class, 'product_name' =&gt; 'required|unique:' . Product::class, 'product_stock_amount' =&gt; 'required|integer|numeric|gte:0', 'product_price' =&gt; 'required|integer|numeric|gte:0', 'product_price_currency' =&gt; 'required|string|', 'product_description' =&gt; 'nullable|string' </code></pre> <p>I am confused on how should I apply the recommendation in the documentation to my validation rules.</p> <p>My idea is to check if the product exists with the <code>product_id</code> then proceedd with the rest of the validation but I don't know if that is correct and I am afraid that would make my code vulnerable to attacks.</p> <p>Any recommendations on how to solve this?</p>
[ { "answer_id": 74678557, "author": "Necati Turan", "author_id": 4335325, "author_profile": "https://Stackoverflow.com/users/4335325", "pm_score": 0, "selected": false, "text": "function testmove(obj, event) {\n document.getElementById(obj.id).addEventListener(\"mousemove\", move);\n}\nfunction move(event) {\n document.getElementById(obj.id).innerText = event.clientX + ' ' + event.clientY;\n document.getElementById(obj.id).style.position = 'absolute';\n document.getElementById(obj.id).style.left = event.clientX + \"px\";\n document.getElementById(obj.id).style.top = event.clientY + \"px\";\n}\nfunction testmove(obj, event) {\n document.getElementById(obj.id).addEventListener(\"mousemove\", function() {\n testmove(obj, event);\n });\n}\n" }, { "answer_id": 74678715, "author": "Andy", "author_id": 1377002, "author_profile": "https://Stackoverflow.com/users/1377002", "pm_score": 1, "selected": false, "text": "move // Pass in the object\nfunction testmove(obj) {\n\n // Add the listener to the document element as in the\n // working example. Pass a function that calls `move` to the\n // listener.\n document.addEventListener(\"mousemove\", () => move(obj, event));\n}\n\nfunction move(obj, event) {\n document.getElementById(obj.id).innerText = event.clientX + ' ' + event.clientY;\n document.getElementById(obj.id).style.position = 'absolute';\n document.getElementById(obj.id).style.left = event.clientX + \"px\";\n document.getElementById(obj.id).style.top = event.clientY + \"px\";\n}\n\nconst obj = { id: 'move' };\n\ntestmove(obj); <div id=\"move\">Move</div>" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6366565/" ]
74,678,551
<p>I am looking to pull certain cells from a row based upon the date(todays) which is in cell I1 on Dashboard. I would like to pull the row from Schedule but only return the team name which is in columns AH and AW.</p> <p>I tried this</p> <pre><code>=QUERY(Schedule!A:BU,&quot;select AH, AW Where Schedule!A:A = '&quot;&amp;I2&amp;&quot;'&quot;) </code></pre> <p>Its shooting an error of &quot;Unable to parse query string for Function QUERY parameter 2: PARSE_ERROR: Encountered &quot; &quot;Schedule &quot;&quot; at line 1, column 21. Was expecting one of: &quot;(&quot; ... &quot;(&quot; ... &quot;</p> <p><a href="https://docs.google.com/spreadsheets/d/1bWyFiPsOkmskPNNePvPrbaL2oHAht9QS-lFuwAlSS9o/edit" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/1bWyFiPsOkmskPNNePvPrbaL2oHAht9QS-lFuwAlSS9o/edit</a></p>
[ { "answer_id": 74678557, "author": "Necati Turan", "author_id": 4335325, "author_profile": "https://Stackoverflow.com/users/4335325", "pm_score": 0, "selected": false, "text": "function testmove(obj, event) {\n document.getElementById(obj.id).addEventListener(\"mousemove\", move);\n}\nfunction move(event) {\n document.getElementById(obj.id).innerText = event.clientX + ' ' + event.clientY;\n document.getElementById(obj.id).style.position = 'absolute';\n document.getElementById(obj.id).style.left = event.clientX + \"px\";\n document.getElementById(obj.id).style.top = event.clientY + \"px\";\n}\nfunction testmove(obj, event) {\n document.getElementById(obj.id).addEventListener(\"mousemove\", function() {\n testmove(obj, event);\n });\n}\n" }, { "answer_id": 74678715, "author": "Andy", "author_id": 1377002, "author_profile": "https://Stackoverflow.com/users/1377002", "pm_score": 1, "selected": false, "text": "move // Pass in the object\nfunction testmove(obj) {\n\n // Add the listener to the document element as in the\n // working example. Pass a function that calls `move` to the\n // listener.\n document.addEventListener(\"mousemove\", () => move(obj, event));\n}\n\nfunction move(obj, event) {\n document.getElementById(obj.id).innerText = event.clientX + ' ' + event.clientY;\n document.getElementById(obj.id).style.position = 'absolute';\n document.getElementById(obj.id).style.left = event.clientX + \"px\";\n document.getElementById(obj.id).style.top = event.clientY + \"px\";\n}\n\nconst obj = { id: 'move' };\n\ntestmove(obj); <div id=\"move\">Move</div>" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19823260/" ]
74,678,559
<p>Working in Laravel 9, and I am doing my validations in <code>FormRequests</code>.</p> <p>I have a <code>email_updates</code> table.</p> <p>I have 3 columns, <code>email</code>, <code>product_uuid</code>, <code>affiliate_uuid</code>, and I am looking to enforce <strong>row</strong> uniqueness. An email can signup for multiple products, or even the same product from a different affiliate.</p> <p>There is a shortened scenario of my data. The first 4 rows are valid.</p> <pre><code>+--------+--------------+----------------+------------+ | email | product_uuid | affiliate_uuid | created_at | +--------+--------------+----------------+------------+ | [email protected] | 3ed | 21c | 2022-01-01 | | [email protected] | 46a | 21c | 2022-01-01 | | [email protected] | 46a | 21c | 2022-01-01 | | [email protected] | 46a | 899 | 2022-01-01 | +--------+--------------+----------------+------------+ </code></pre> <p>But I need the validator to refuse this row, because trio of <code>[email protected]</code>, <code>3ed</code>, <code>21c</code> have already been used before</p> <pre><code>+--------+--------------+----------------+------------+ | [email protected] | 3ed | 21c | 2022-01-01 | +--------+--------------+----------------+------------+ </code></pre> <p>Here is the validator that I have written so far, but it does not catch my duplicate row</p> <pre><code>public function rules() { return [ 'email' =&gt; [ 'required|email:rfc,dns|min:5|max:75', Rule::unique(&quot;email&quot;)-&gt;where(function ($query) { $query-&gt;where(&quot;product_uuid&quot;, $this-&gt;product_uuid) -&gt;where(&quot;affiliate_uuid&quot;, $this-&gt;affiliate_uuid); }) ], ]; } </code></pre> <p>The Laravel docs do not seem to address my situation <a href="https://laravel.com/docs/9.x/validation#rule-unique" rel="nofollow noreferrer">https://laravel.com/docs/9.x/validation#rule-unique</a></p> <p>I am sure that it is something simple but what am I missing here?</p>
[ { "answer_id": 74678607, "author": "Osama Alma", "author_id": 20683749, "author_profile": "https://Stackoverflow.com/users/20683749", "pm_score": 2, "selected": false, "text": "public function rules()\n{\n return [\n 'email' => [\n 'required|email:rfc,dns|min:5|max:75',\n Rule::unique('email_updates', 'email', 'product_uuid', 'affiliate_uuid')\n ],\n ];\n}\n" }, { "answer_id": 74680209, "author": "wruckie", "author_id": 1272406, "author_profile": "https://Stackoverflow.com/users/1272406", "pm_score": 0, "selected": false, "text": "Method Illuminate\\Validation\\Validator::validateRequired|email does not exist. | rule public function rules()\n{\n return [\n 'email' => [\n 'required', 'email:rfc,dns', 'min:5', 'max:75',\n Rule::unique(\"email\")->where(function ($query) {\n $query->where(\"product_uuid\", $this->product_uuid)\n ->where(\"affiliate_uuid\", $this->affiliate_uuid);\n })\n ],\n ];\n}\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1272406/" ]
74,678,588
<p>I am able to use the search function through backend and its working in postman, also able to bring the search result on the frontend browser console. But i am not able to display the searched result in the page.</p> <p>Frontend code is attached below. searchHandler is bringing the searched result to console but i am not able to display that on page</p> <pre><code>import React, { useEffect, useState } from &quot;react&quot;; import axios from &quot;axios&quot;; const UserList = () =&gt; { const [userData, setUserData] = useState(&quot;&quot;); const fetchUserData = async () =&gt; { const resp = await axios.get(&quot;/getTodo&quot;); console.log(resp); //if no user is there please dont set any value if (resp.data.users.length &gt; 0) { setUserData(resp.data.users); } }; useEffect(() =&gt; { fetchUserData(); }, [userData]); ///edit const handleEdit = async (user) =&gt; { var edittodo = `${user.todo}`; var edittask = `${user.task}`; const userTodo = prompt(&quot;Enter your Name&quot;, edittodo); const userTask = prompt(&quot;Enter your Email&quot;, edittask); if (!userTodo || !userTask) { alert(&quot;please Enter Todo and Task Both&quot;); } else { const resp = await axios.put(`/editTodo/${user._id}`, { todo: userTodo, task: userTask, }); console.log(resp); } }; //Delete const handleDelete = async (userId) =&gt; { const resp = await axios.delete(`/deleteTodo/${userId}`); console.log(resp); }; const searchHandle = async (event) =&gt; { let key = event.target.value; console.log(key) await axios .get(`http://localhost:5500/search/${key}`) .then((response) =&gt; { console.log(response.data); }) .catch((err) =&gt; { console.log(err); }); }; return ( &lt;div&gt; &lt;form&gt; &lt;input type=&quot;text&quot; className=&quot;search-box&quot; placeholder=&quot;Search Todo&quot; onChange={(searchHandle)} /&gt; &lt;/form&gt; &lt;section className=&quot;text-gray-600 body-font&quot;&gt; &lt;div className=&quot;container px-5 py-24 mx-auto&quot;&gt; &lt;div className=&quot;flex flex-col text-center w-full mb-8&quot;&gt; &lt;h1 className=&quot;sm:text-4xl text-3xl font-medium title-font mb-2 text-gray-900&quot;&gt; All Users &lt;/h1&gt; &lt;/div&gt; &lt;div className=&quot;lg:w-2/3 w-full mx-auto overflow-auto&quot;&gt; &lt;table className=&quot;table-auto w-full text-left whitespace-no-wrap&quot;&gt; &lt;thead&gt; &lt;tr&gt; &lt;th className=&quot;px-4 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100 rounded-tl rounded-bl&quot;&gt; Todo &lt;/th&gt; &lt;th className=&quot;px-4 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100&quot;&gt; Task &lt;/th&gt; &lt;th className=&quot;px-4 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100&quot;&gt; Edit &lt;/th&gt; &lt;th className=&quot;px-4 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100&quot;&gt; Delete &lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; {userData &amp;&amp; userData.map((user, index) =&gt; ( &lt;tr key={index}&gt; &lt;td className=&quot;px-4 py-3&quot;&gt;{user.todo}&lt;/td&gt; &lt;td className=&quot;px-4 py-3&quot;&gt;{user.task}&lt;/td&gt; &lt;td className=&quot;px-4 py-3&quot;&gt; &lt;button className=&quot;hover:text-green-500&quot; onClick={() =&gt; handleEdit(user)} &gt; Edit &lt;/button&gt; &lt;/td&gt; &lt;td className=&quot;px-4 py-3 text-lg text-gray-900&quot;&gt; &lt;button className=&quot;hover:text-red-500&quot; onClick={() =&gt; handleDelete(user._id)} &gt; Delete &lt;/button&gt; &lt;/td&gt; &lt;/tr&gt; ))} &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; &lt;/div&gt; ); }; export default UserList; </code></pre>
[ { "answer_id": 74678607, "author": "Osama Alma", "author_id": 20683749, "author_profile": "https://Stackoverflow.com/users/20683749", "pm_score": 2, "selected": false, "text": "public function rules()\n{\n return [\n 'email' => [\n 'required|email:rfc,dns|min:5|max:75',\n Rule::unique('email_updates', 'email', 'product_uuid', 'affiliate_uuid')\n ],\n ];\n}\n" }, { "answer_id": 74680209, "author": "wruckie", "author_id": 1272406, "author_profile": "https://Stackoverflow.com/users/1272406", "pm_score": 0, "selected": false, "text": "Method Illuminate\\Validation\\Validator::validateRequired|email does not exist. | rule public function rules()\n{\n return [\n 'email' => [\n 'required', 'email:rfc,dns', 'min:5', 'max:75',\n Rule::unique(\"email\")->where(function ($query) {\n $query->where(\"product_uuid\", $this->product_uuid)\n ->where(\"affiliate_uuid\", $this->affiliate_uuid);\n })\n ],\n ];\n}\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20683823/" ]
74,678,598
<p>whenever I refresh my page the fetched content I've loaded decides to disappear, it will load the first time but every time after that it will go. I have another component that has almost the same code and that one works fine so I'm not entirely sure why it doesn't with this component.</p> <p>the feeling I have is in my standings.svelte component I have a flatMap function which is the main difference compared to my other components.</p> <p>here is a video showing what happens when I refresh the page. This won't happen to any other component but this one. (<a href="https://imgur.com/a/Ew4bwgB" rel="nofollow noreferrer">https://imgur.com/a/Ew4bwgB</a>)</p> <p>This is my standings.svelte component</p> <pre><code>&lt;script&gt; import {leagueStandings} from &quot;../../stores/league-standings-stores&quot; const tablePositions = $leagueStandings.flatMap(({ standings: { data } }) =&gt; data); &lt;/script&gt; &lt;div class=&quot;bg-[#1C1C25] p-8 rounded-lg box-border w-fit&quot;&gt; {#each tablePositions as tablePosition} &lt;div class=&quot;standings-table flex gap-9 mb-2 pb-4 pt-3 border-b border-[#303041]&quot;&gt; &lt;div class=&quot;team-details flex gap-4 w-full&quot; id=&quot;td&quot;&gt; &lt;p class=&quot;w-[18px]&quot;&gt;{tablePosition.position}&lt;/p&gt; &lt;img src=&quot;{tablePosition.team.data.logo_path}&quot; alt=&quot;&quot; class=&quot;w-[1.5em] object-scale-down&quot;&gt; &lt;p class=&quot;&quot;&gt;{tablePosition.team_name}&lt;/p&gt; &lt;/div&gt; &lt;div class=&quot;team-stats flex gap-5 text-left child:w-5 child:text-center w-full&quot;&gt; &lt;p&gt;{tablePosition.overall.games_played}&lt;/p&gt; &lt;p&gt;{tablePosition.overall.won}&lt;/p&gt; &lt;p&gt;{tablePosition.overall.draw}&lt;/p&gt; &lt;p&gt;{tablePosition.overall.lost}&lt;/p&gt; &lt;p&gt;{tablePosition.overall.goals_scored}&lt;/p&gt; &lt;p&gt;{tablePosition.overall.goals_against}&lt;/p&gt; &lt;p&gt;{tablePosition.total.goal_difference}&lt;/p&gt; &lt;p&gt;{tablePosition.overall.points}&lt;/p&gt; &lt;p class=&quot;!w-[78px] !text-left&quot;&gt;{tablePosition.recent_form}&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; {/each} &lt;/div&gt; </code></pre> <p>Here is my svelte store</p> <pre><code>import { writable } from &quot;svelte/store&quot;; export const leagueStandings = writable([]); const fetchStandings = async () =&gt; { const url = `https://soccer.sportmonks.com/api/v2.0/standings/season/19734?api_token=API_KEY`; const res = await fetch(url); const data = await res.json(); leagueStandings.set(data.data); } fetchStandings(); </code></pre> <p>id love some advice on what im doing wrong :)</p>
[ { "answer_id": 74678607, "author": "Osama Alma", "author_id": 20683749, "author_profile": "https://Stackoverflow.com/users/20683749", "pm_score": 2, "selected": false, "text": "public function rules()\n{\n return [\n 'email' => [\n 'required|email:rfc,dns|min:5|max:75',\n Rule::unique('email_updates', 'email', 'product_uuid', 'affiliate_uuid')\n ],\n ];\n}\n" }, { "answer_id": 74680209, "author": "wruckie", "author_id": 1272406, "author_profile": "https://Stackoverflow.com/users/1272406", "pm_score": 0, "selected": false, "text": "Method Illuminate\\Validation\\Validator::validateRequired|email does not exist. | rule public function rules()\n{\n return [\n 'email' => [\n 'required', 'email:rfc,dns', 'min:5', 'max:75',\n Rule::unique(\"email\")->where(function ($query) {\n $query->where(\"product_uuid\", $this->product_uuid)\n ->where(\"affiliate_uuid\", $this->affiliate_uuid);\n })\n ],\n ];\n}\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16044758/" ]
74,678,625
<p>Within a very large HTML page i want to get a <code>span</code> by <code>class</code> which is unique. The <strong>child</strong> <code>span</code> of this one, can be queried also by <code>class</code> but which is <strong>not unique</strong>.</p> <pre><code>... &lt;span class=&quot;uniqueParent&quot;&gt; &lt;span class=&quot;notUniqueChildClassName&quot;&gt; I am the child &lt;/span&gt; &lt;/span&gt; ... </code></pre> <p>Output should be &quot;I am the child&quot;.</p> <p>I have tried:</p> <pre><code>s = soup.select('span[class=&quot;uniqueParent&quot;] &gt; span[class=&quot;notUniqueChildClassName&quot;]') s.text </code></pre> <p>and</p> <pre><code>s = soup.find('span[class=&quot;uniqueParent&quot;] &gt; span[class=&quot;notUniqueChildClassName&quot;]') s.text </code></pre> <p>But both did not work.</p>
[ { "answer_id": 74678607, "author": "Osama Alma", "author_id": 20683749, "author_profile": "https://Stackoverflow.com/users/20683749", "pm_score": 2, "selected": false, "text": "public function rules()\n{\n return [\n 'email' => [\n 'required|email:rfc,dns|min:5|max:75',\n Rule::unique('email_updates', 'email', 'product_uuid', 'affiliate_uuid')\n ],\n ];\n}\n" }, { "answer_id": 74680209, "author": "wruckie", "author_id": 1272406, "author_profile": "https://Stackoverflow.com/users/1272406", "pm_score": 0, "selected": false, "text": "Method Illuminate\\Validation\\Validator::validateRequired|email does not exist. | rule public function rules()\n{\n return [\n 'email' => [\n 'required', 'email:rfc,dns', 'min:5', 'max:75',\n Rule::unique(\"email\")->where(function ($query) {\n $query->where(\"product_uuid\", $this->product_uuid)\n ->where(\"affiliate_uuid\", $this->affiliate_uuid);\n })\n ],\n ];\n}\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1595350/" ]
74,678,636
<p>I want to add a confirmation to a form action:</p> <pre><code> &lt;form action=&quot;/delete&quot; method=&quot;post&quot;&gt; &lt;button id=&quot;deleteForm&quot; class=&quot;btn btn-danger&quot; onclick=&quot;deleteConfirm(this.form)&quot;&gt;Delete&lt;/button&gt; &lt;/form&gt; </code></pre> <p>And in my script.js I wrote the function:</p> <pre><code>function deleteConfirm() { let text = &quot;Are you sure?\nOk=Delete all data.&quot;; if (confirm(text) == true) { document.getElementById(&quot;deleteForm&quot;).submit(); } else { alert(&quot;Cancelled.&quot;); } } </code></pre> <p>But with these codes when I click either ok or cancell, the form will submit. when I click cancel the alert show up but then the action /delete will execute.</p> <p>Is this an attribute of flask? Are there another ways to do this?</p>
[ { "answer_id": 74678607, "author": "Osama Alma", "author_id": 20683749, "author_profile": "https://Stackoverflow.com/users/20683749", "pm_score": 2, "selected": false, "text": "public function rules()\n{\n return [\n 'email' => [\n 'required|email:rfc,dns|min:5|max:75',\n Rule::unique('email_updates', 'email', 'product_uuid', 'affiliate_uuid')\n ],\n ];\n}\n" }, { "answer_id": 74680209, "author": "wruckie", "author_id": 1272406, "author_profile": "https://Stackoverflow.com/users/1272406", "pm_score": 0, "selected": false, "text": "Method Illuminate\\Validation\\Validator::validateRequired|email does not exist. | rule public function rules()\n{\n return [\n 'email' => [\n 'required', 'email:rfc,dns', 'min:5', 'max:75',\n Rule::unique(\"email\")->where(function ($query) {\n $query->where(\"product_uuid\", $this->product_uuid)\n ->where(\"affiliate_uuid\", $this->affiliate_uuid);\n })\n ],\n ];\n}\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5810563/" ]
74,678,662
<p>public static String input(){</p> <pre><code>Scanner input = new Scanner(System.in); String key = &quot;&quot;; while(key != &quot;q&quot;){ key += input.nextLine(); return key; } return &quot;hello&quot;; </code></pre> <p>} //if input is &quot;1234&quot; then it should return key = &quot;1234&quot;,</p> <p>if the input is &quot;1234q&quot; then it should return &quot;hello&quot;</p> <p>The output im getting is &gt;nothing&lt; until I do it twice, and then it returns key = &quot;1234q&quot;</p> <p>How can I fix this? Thanks</p>
[ { "answer_id": 74678607, "author": "Osama Alma", "author_id": 20683749, "author_profile": "https://Stackoverflow.com/users/20683749", "pm_score": 2, "selected": false, "text": "public function rules()\n{\n return [\n 'email' => [\n 'required|email:rfc,dns|min:5|max:75',\n Rule::unique('email_updates', 'email', 'product_uuid', 'affiliate_uuid')\n ],\n ];\n}\n" }, { "answer_id": 74680209, "author": "wruckie", "author_id": 1272406, "author_profile": "https://Stackoverflow.com/users/1272406", "pm_score": 0, "selected": false, "text": "Method Illuminate\\Validation\\Validator::validateRequired|email does not exist. | rule public function rules()\n{\n return [\n 'email' => [\n 'required', 'email:rfc,dns', 'min:5', 'max:75',\n Rule::unique(\"email\")->where(function ($query) {\n $query->where(\"product_uuid\", $this->product_uuid)\n ->where(\"affiliate_uuid\", $this->affiliate_uuid);\n })\n ],\n ];\n}\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74678662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20177615/" ]