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 = """2-4,6-8
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2-6,4-8"""
</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(",")[0], data.split(",")[1]
first_range_start, first_range_end = map(int, first_elf.split("-"))
second_range_start, second_range_end = map(int, second_elf.split("-"))
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>" word= {his or her} whatever "
</code></pre>
<p>I want to delete every whitespace except between {}, so that my modified string will be:</p>
<pre><code>"word={his or her}whatever"
</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 "", that is:</p>
<p>if I wanted to turn this string:</p>
<pre><code>" word= {his or her} and "his or her" whatever "
</code></pre>
<p>into this:</p>
<pre><code>"word={his or her}and"his or her"whatever"
</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 "Services"), 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><header>
<a href="/">
<p>Whatever logo</p>
</a>
<nav>
<ul>
<li>About us</li>
<li>Services</li>
<li>Pricing</li>
<li>Blog</li>
</ul>
</nav>
<a href="/">CONTACT</a>
</header></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: "color", value: "red"},
{filter: "color", value: "white"},
{filter: "size", value: "xl"},
{filter: "manufacturer", value: "adidas"},
{filter: "manufacturer", value: "nike"},
];
</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("Xx"); // true
isAllX("xAbX"); // false
</code></pre>
</blockquote>
<p>Below is my answer, but it is wrong. I want "false" for the complete string if any of the character is not "x" or "X":</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 < 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><div id="wrap">
<nav>
<div class="logo">
<img src="./photos-docs/ME-marine-logo.png" alt="logo" class="logo" />
</div>
<button type="button" class="btn-hamburger" data-action="nav-toggle">
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</button>
<ul class="nav-menu">
<li class="nav-item"><a href="index.html">עמוד ראשי</a></li>
<li class="nav-item dropdown">
<a href="#" data-action="dropdown-toggle">עיסויים </a>
<div class="dropdown-menu">
<a class="dropdown-item" href="#">רפואי</a>
<a class="dropdown-item" href="#">שוודי</a>
<a class="dropdown-item" href="#">רקמות עמוקות</a>
<a class="dropdown-item" href="#">ניקוז לימפטי</a>
<a class="dropdown-item" href="#">אבנים חמות</a>
</div>
</li>
<li class="nav-item dropdown">
<a href="#" data-action="dropdown-toggle">טיפולי פנים </a>
<div class="dropdown-menu">
<a class="dropdown-item" href="#">קלאסי</a>
<a class="dropdown-item" href="#">יופי</a>
<a class="dropdown-item" href="#">אקנה</a>
<a class="dropdown-item" href="#">פילינג</a>
<a class="dropdown-item" href="#">מיצוק</a>
<a class="dropdown-item" href="#">פיגמנטציה</a>
<a class="dropdown-item" href="#">אנטי אייג׳ינג</a>
</div>
</li>
<li class="nav-item"><a href="#">מזותרפיה</a></li>
<li class="nav-item"><a href="#">מיקרובליידינג</a></li>
<li class="nav-item"><a href="#">הזמינו תור</a></li>
<li class="nav-item"><a href="#">צרו קשר</a></li>
<li class="nav-item"><a href="tel:+972547809308">0547809308</a></li>
<li class="nav-item"><a href="https://api.whatsapp.com/send?phone=972547809308"><i class="fa-brands fa-whatsapp"></i></a>
</li>
</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("[data-action='dropdown-toggle']");
let navToggle = nav.querySelector("[data-action='nav-toggle']");
dropdownToggle.addEventListener('click', () => {
if (dropdown.classList.contains('show')) {
dropdown.classList.remove('show');
} else {
dropdown.classList.add('show');
}
})
navToggle.addEventListener('click', () => {
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 "2 * a + 3 * b".</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><div className="w-[var(--sidebar-width)]">
<MySidebar>
</div>
</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) <- for replicating results of betas in 1-2 1-3
sample_size <- 200
sample_meanvector <- c(3, 4)
sample_covariance_matrix <- matrix(c(2, 1, 1, 2),
ncol = 2)
# create bivariate normal distribution
sample_distribution <- mvrnorm(n = sample_size,
mu = sample_meanvector,
Sigma = sample_covariance_matrix)
#Convert the datatype
df_sample_distribution <- 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("correct-answers");
document.querySelector(".check").onclick = function () {
/* Hide unneeded sections and showing scores */
quiz.classList.add("hidden");
correctAnswer.classList.remove("hidden");
/*Showing all previous scores */
const lastScore = localStorage.getItem("latestScore") || [];
const scoreDetail = lastScore.split(',');
scoreDetail.push(score);
localStorage.setItem("latestScore", scoreDetail);
let userScoreTemplate = `<h2>This Round's Score: ${score}</h2>`;
scoreDetail.map((items, index) => {
userScoreTemplate += `<h3>Score ${index}: ${items}</h3>`
});
let userScoreBoard = document.getElementById("user-score");
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><form action="index.php" method="post">
<input type="text" name="name" placeholder="name" />
<input type="text" name="surname" placeholder="surname" />
<input type="text" name="emailbirthday" placeholder="emailbirthday" />
<input type="text" name="birthday" placeholder="birthday(dd/mm/aaa)" />
<button type="reset">Reset Form</button>
<button type="submit">Submit Form</button>
</form>
</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 "pack" 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["name"];
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,"select * offset "&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("connect-database.inc.php");
$question_query = "SELECT
questions.questionID,
answers.answer,
questions.question,
questions.feedback,
questions.mark,
questions.questionTypeID
FROM questions
JOIN answers ON questions.questionID=answers.questionID";
$questionList=array();
$answerList = array();
try {
$mysqliResult = $link->query($question_query);
while($var=$mysqliResult->fetch_assoc()){
$questionList[$var['questionID']]=new questions($var['question'],$var['feedback'], $var['mark'], $var['questionTypeID'], $var['answer']);
}
} catch (Exception $e) {
echo "MySQLi Error Code: " . $e->getCode() . "<br />";
echo "Exception Msg: " . $e->getMessage();
exit();
}
var_dump($questionList);
class questions {
public function __construct($question, $feedback, $mark, $questionTypeID, $answerList){
$this->question = $question;
$this->feedback = $feedback;
$this->mark = $mark;
$this->questionTypeID = $questionTypeID;
$this->answers($answerList);
}
public function answers($answers) {
$answers = array();
$this->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 <- memdb_frame(
grp = c(2, 2, 2, 1, 3, 1, 1),
win = c("B", "C", "A", "B", "C", "A", "C"),
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 %>%
collect() %>%
arrange(grp, win) %>%
group_by(grp) %>%
mutate(last_id = last(id)) %>%
ungroup()
#> # A tibble: 7 × 4
#> grp win id last_id
#> <dbl> <chr> <dbl> <dbl>
#> 1 1 A 4 6
#> 2 1 B 7 6
#> 3 1 C 6 6
#> 4 2 A 5 3
#> 5 2 B 1 3
#> 6 2 C 3 3
#> 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 %>%
arrange(grp, win) %>%
group_by(grp) %>%
mutate(last_id = last(id)) %>%
ungroup() %>%
print() %>%
show_query()
#> # Source: SQL [7 x 4]
#> # Database: sqlite 3.39.4 [:memory:]
#> # Ordered by: grp, win
#> grp win id last_id
#> <dbl> <chr> <dbl> <dbl>
#> 1 1 A 4 4
#> 2 1 B 7 7
#> 3 1 C 6 6
#> 4 2 A 5 5
#> 5 2 B 1 1
#> 6 2 C 3 3
#> 7 3 C 2 2
#> <SQL>
#> SELECT
#> *,
#> LAST_VALUE(`id`) OVER (PARTITION BY `grp` ORDER BY `grp`, `win`) AS `last_id`
#> FROM `dbplyr_001`
#> 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 %>%
arrange(grp, win) %>%
group_by(grp) %>%
window_order(win) %>%
mutate(last_id = last(id)) %>%
ungroup() %>%
print() %>%
show_query()
#> # Source: SQL [7 x 4]
#> # Database: sqlite 3.39.4 [:memory:]
#> # Ordered by: win
#> grp win id last_id
#> <dbl> <chr> <dbl> <dbl>
#> 1 1 A 4 4
#> 2 1 B 7 7
#> 3 1 C 6 6
#> 4 2 A 5 5
#> 5 2 B 1 1
#> 6 2 C 3 3
#> 7 3 C 2 2
#> <SQL>
#> SELECT *, LAST_VALUE(`id`) OVER (PARTITION BY `grp` ORDER BY `win`) AS `last_id`
#> FROM `dbplyr_001`
#> 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 %>%
arrange(grp, win) %>%
group_by(grp) %>%
window_order(grp) %>%
mutate(last_id = last(id)) %>%
ungroup() %>%
print() %>%
show_query()
#> # Source: SQL [7 x 4]
#> # Database: sqlite 3.39.4 [:memory:]
#> # Ordered by: grp
#> grp win id last_id
#> <dbl> <chr> <dbl> <dbl>
#> 1 1 A 4 6
#> 2 1 B 7 6
#> 3 1 C 6 6
#> 4 2 A 5 5
#> 5 2 B 1 5
#> 6 2 C 3 5
#> 7 3 C 2 2
#> <SQL>
#> SELECT *, LAST_VALUE(`id`) OVER (PARTITION BY `grp` ORDER BY `grp`) AS `last_id`
#> FROM `dbplyr_001`
#> 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 >= 90 or mem1sec.stdout|int >= 90 or mem2sec.stdout|int >= 90 or mem3sec.stdout|int >= 90
- name: 'Print message if MEMORY utilization is normal'
debug:
msg:
- -------------------------------------------------------
- Memory Utilization = ( ( Total - Free ) / Total * 100 ) = {{ memsec.stdout }}%
- -------------------------------------------------------
when: memsec.stdout|int < 90 and mem1sec.stdout|int < 90 and mem2sec.stdout|int < 90 and mem3sec.stdout|int < 90
- name: 'Print message if MEMORY utilization is abnormal'
debug:
msg:
- -------------------------------------------------------
- Memory Utilization = ( ( Total - Free ) / Total * 100 ) = {{ memhigusage.stdout }}%
- -------------------------------------------------------
when: memsec.stdout|int >= 90 or mem1sec.stdout|int >= 90 or mem2sec.stdout|int >= 90 or mem3sec.stdout|int >= 90
</code></pre>
<p>output:</p>
<pre><code>
TASK [Print message if MEMORY utilization is normal] *************************************************************************************************************************************************************
ok: [44.203.153.54] => {
"msg": [
"-------------------------------------------------------",
"Memory Utilization = ( ( Total - Free ) / Total * 100 ) = 13.87%",
"-------------------------------------------------------"
]
}
TASK [Print message if MEMORY utilization is abnormal] ***********************************************************************************************************************************************************
skipping: [44.203.153.54] => {}
</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()->groupBy(function($item){ return $item->created_at->format('d-M-y'); })->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("new_col"),
])
</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="dodge")+
geom_text(stat = "count", 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 = "\n".join("{} {}".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><body>
<div class="logocontainer">
<a href="index.html">
<img src="images/badasslogo.png" class="logo"></a>
</div>
<div id="buttoncontainer" class="buttoncontainer">
</div>
<script src="js/menu.js"></script>
</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 = `
<a href="index.html">
<img src="images/buttons/homebutton.png" class="button"></a>
<a href="blog/blogmain.html">
<img src="images/buttons/blogbutton.png" class="button"></a>
<a href="art/artmain.html">
<img src="images/buttons/artbutton.png" class="button"></a>
<a href="fanart/fanartmain.html">
<img src="images/buttons/fanartbutton.png" class="button"></a>
<a href="partners/partnersmain.html">
<img src="images/buttons/partnersbutton.png" class="button"></a>
<a href="guestbook/guestbook.html">
<img src="images/buttons/guestbookbutton.png" class="button"></a>
<a href="https://junessaidotnet.proboards.com/">
<img src="images/buttons/forumsbutton.png" class="button"></a>
<a href="downloads/downloadsmain.html">
<img src="images/buttons/downloadsbutton.png" class="button"></a>
<a href="extras/extrasmain.html">
<img src="images/buttons/extrasbutton.png" class="button"></a>
<a href="donate/donatemain.html">
<img src="images/buttons/donatebutton.png" class="button"></a>
<a href="about/about.html">
<img src="images/buttons/aboutbutton.png" class="button"></a>
`;
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="نام ",
validators=[
validators.MaxLengthValidator(100, "نام شما نمیتواند بیش از 100 کاراکتر باشد")])
last_name = forms.CharField(
widget=forms.TextInput(
attrs={'placeholder': 'نام خانوادگی خود را وارد کنید'}),
label="نام خانوادگی",
validators=[
validators.MaxLengthValidator(100, "نام خانوادگی شما نمیتواند بیش از 100 کاراکتر باشد")])
email = forms.EmailField(
widget=forms.EmailInput(
attrs={'placeholder': 'ایمیل خود را وارد کنید'}),
label="ایمیل",
validators=[
validators.MaxLengthValidator(200, "تعداد کاراکترهایایمیل شما نمیتواند بیش از ۲۰۰ کاراکتر باشد.")
])
title = forms.CharField(
widget=forms.TextInput(
attrs={'placeholder': 'عنوان پیام خود را وارد کنید'}),
label="عنوان",
validators=[
validators.MaxLengthValidator(250, "تعداد کاراکترهای شما نمیتواند بیش از 250 کاراکتر باشد.")
])
text = forms.CharField(
widget=forms.Textarea(
attrs={'placeholder': 'متن پیام خود را وارد کنید'}),
label="متن پیام",
)
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> <form action="{% url 'contact' %}" id="contactform" method="post">
{% csrf_token %}
<div class="col-md-6 col-lg-6">
<div class="form_block">
{{ form.first_name }}
{% for error in form.first_name.errors %}
<p class="text-danger">{{ error }}</p>
{% endfor %}
</div>
</div>
<div class="col-md-6 col-lg-6">
<div class="form_block">
{{ form.last_name }}
{% for error in form.last_name.errors %}
<p class="text-danger">{{ error }}</p>
{% endfor %}
</div>
</div>
<div class="col-md-6 col-lg-6">
<div class="form_block">
{{ form.email }}
{% for error in form.email.errors %}
<p class="text-danger">{{ error }}</p>
{% endfor %}
</div>
</div>
<div class="col-md-6 col-lg-6">
<div class="form_block">
{{ form.title }}
{% for error in form.title.errors %}
<p class="text-danger">{{ error }}</p>
{% endfor %}
</div>
</div>
<div class="col-md-12 col-lg-12">
<div class="form_block">
{{ form.text }}
{% for error in form.text.errors %}
<p class="text-danger">{{ error }}</p>
{% endfor %}
<div class="response"></div>
</div>
</div>
<div class="col-md-12 col-lg-12">
<div class="form_block">
<button type="submit" class="clv_btn submitForm"
data-type="contact">ارسال
</button>
</div>
</div>
</form>
</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 & Store Name</h1>
<h1></h1>
<p><strong>Formula Used :</strong> =FIND(LOOKUP(10^15,MID(A2,ROW(INDIRECT("1:"&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 < numbersOfCharacters)
{
cout << "Introduce character's number" << counter << ": ";
cin >> character;
counter = counter + 1;
phrase=character+character; //I'm not sure if I need an array here.
}
cout << "Concatenated characters: " << phrase << 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 "dymanicly":
# first group created and if the next row is not in that group -> create new one
def groupping(val_1, val_2):
# not using match case here, cause my Python < 3.10
if ((val_1 >= 0) and (val_1 <10)) and (val_2 == 1):
return 1
elif ((val_1 >= 0) and (val_1 <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 & 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<WiFi.h>
const char *ssid = "my_SSID";
const char *password = "my_Password";
void setup()
{
Serial.begin(115200);
delay(2000);
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
Serial.println("scan start");
// WiFi.scanNetworks will return the number of networks found
int n = WiFi.scanNetworks();
Serial.println("scan done");
if (n == 0) {
Serial.println("no networks found");
} else {
Serial.print(n);
Serial.println(" networks found");}
// Connect to my network.
WiFi.begin(ssid,password);
// Check Status of your WiFi Connection
int x = WiFi.status(); // If x=3 (Connected to Network) & If x=6 (Disconnected from Network)
Serial.print("WiFi Connection Status is ");
Serial.println(x);
while(WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("WiFi Connection Failed...");
WiFi.disconnect();
WiFi.reconnect(); }
//Print local IP address and start web server
Serial.println("\nConnecting");
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("ESP32 IP address: ");
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 "store_broken"."id",
"store_broken"."item_id",
"store_broken"."item_quantity_broken",
"store_broken"."item_broken_date",
"store_broken"."item_is_broken",
"store_broken"."date_repaired",
"store_items"."id",
"store_items"."item_name",
"store_items"."item_price",
"store_items"."item_quantity_received",
"store_items"."item_quantity_available",
"store_items"."item_purchased_date",
"store_items"."item_units"
FROM "store_broken"
INNER JOIN "store_items"
ON ("store_broken"."item_id" = "store_items"."id")
</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 %}
<tr>
<td>{{item.id}}</td>
<td>{{item.item_id}}</td>
<td>{{item.item_quantity_broken}}</td>
<td>{{item.item_broken_date}}</td>
<td>{{item.item_is_broken}}</td>
<td>{{item.date_repaired}}</td>
<td>{{item.item_name }}</td>
<td>{{item.item_item_quantity_received}}</td>
<td>{{item.item_quantity_available}}</td>
<td>{{item.item_purchased_date}}</td>
<td>{{item.items_item_units}}</td>
</tr>
{% 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<Node> queue = new LinkedList<>(); //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 >= 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 "Average Exam Grade",
AVG(CASE WHEN GRADE_TYPE <> 'e' THEN new_table.mark END) AS "Average Activity Grade",
(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"
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 <> 'e' THEN new_table.mark END))/3) >= 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 >= 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) => {
// 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("execution(* *(..)) && @within(org.springframework.data.jpa.repository.Query)")
private void createQuery(){}
@Around("createQuery()")
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))
<class 'botocore.client.S3'>
</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 => {
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><p class="a"><span class="b">1</span></p>
<p class="a"><span class="b">2</span></p>
<p class="a"><span class="b">3</span></p></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_][^-]*.*(?<!_)
</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_][^-]*.*(?<!_)</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 <iostream>
using namespace std;
int main ()
{
double s=0;
double i=1;
for (int m=1;m<5;m++)
{
i=m*i;
s=s+1/i;
}
cout<<s+1;
return 0;
}
</code></pre>
<p>But when I use <code>int i</code>, the output is 2:</p>
<pre><code>#include <iostream>
using namespace std;
int main ()
{
double s=0;
int i=1;
for (int m=1;m<5;m++)
{
i=m*i;
s=s+1/i;
}
cout<<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 "dropperso" and can open the Personal menu, I need the "openMenu" function to also react to the ID "dropsites" 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("dropperso").classList.toggle("dropopen");
}
</code></pre>
<p>HTML:</p>
<pre><code> <div class="dropdown">
<button onclick="openMenu()" class="drophover">Other Sites</button>
<div id="dropsites" class="dropdown-content">
A link
</div>
</div>
<div class="dropdown">
<button onclick="openMenu()" class="drophover">Personal</button>
<div id="dropperso" class="dropdown-content" style="right: 0;">
A link
A link
</div>
</div>
</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, "use JQuery" (I'm limited and can't use JQuery), or "use this other code (that doesn't work for mine)".</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] = {
"123foo", "bar456", "bla_blubb"
};
</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 <stdio.h>
#include <string.h>
#define NUM_PASSWDS 3
const char *passwd[NUM_PASSWDS] = {
"123foo", "bar456", "bla_blubb"
};
int pwdquery(char pass[]) {
for (int i = 0; i < 2; i++) {
if (passwd[i] == pass[i]) {
return printf("correct");
}
}
}
int main() {
char a[100];
for (int i = 0; i < 3; i++) {
printf("Please enter password");
scanf("%s", 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<CategoryProduct> CategoryProducts { get; set; }
}
public class CategoryProduct
{
public int CategoryProductId { get; set; }
public string Name { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
internal class EFDbContext : DbContext, IDBProductContext
{
public DbSet<Product> Products { get; set; }
public DbSet<CategoryProduct> CategoryProducts { get; set ; }
public EFDbContext()
{
Database.SetInitializer<EFDbContext>(new DropCreateDatabaseIfModelChanges<EFDbContext>());
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>().HasMany(p => p.CategoryProducts)
.WithMany(c => c.Products)
.Map(pc => {
pc.MapLeftKey("ProductRefId");
pc.MapRightKey("CategoryProductRefId");
pc.ToTable("CategoryProductTable");
});
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 "<em>if any of these rules</em>" hold valid and if not then throw exception!</p>
<pre><code>for {
i <- rules.map(_.validate()).sequence
_ <- if (i.contains(true)) IO.unit else IO.raiseError(new RuntimeException("Failed"))
} 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 "season_new", 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"C:\Users\awais\OneDrive\Documents\Greenwich Uni work\Face detec work\images folder",
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"outputs/{args['input'].split('/')[-1].split('.')[0]}_u{args['upsample']}.jpg"
# 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 "C:\Users\awais\OneDrive\Documents\Greenwich Uni work\Face detec work\face_det_image.py", line 20, in <module>
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><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
.class2,
.class2 tr,
.class2 td {
border: solid 2px;
border-collapse: collapse;
}
.class1{
color: red;
}
</style>
</head>
<body>
<table class="class2">
<tr class="class1">
<td>hello</td>
<td>world</td>
</tr>
<tr>
<td>hello</td>
<td>world</td>
</tr>
</table>
</body>
</html></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("Enter the number of customers: "));
int[] one = new int[number];
int[] two = new int[number];
for (int i = 0; i < number; i++) {
one[i] = Integer.parseInt(JOptionPane.showInputDialog("Customer number: "));
}
int y = 0;
for (int i = 0; i < one.length - 1; i++) {
for (int w = i + 1; w < one.length; w++) {
if (one[i] == one[w]) {
two[y] = one[w];
y = y + 1;
break;
}
}
for (int p = 0; p < y - 1; p++) {
if (one[p] == two[p - 1]) {
y = y - 1;
break;
}
}
}
if (y == 0) {
JOptionPane.showMessageDialog(null, "\nHONEST CUSTOMERS");
} else if (y != 0) {
JOptionPane.showMessageDialog(null, "Duplicates:");
for (int o = 0; o < y; o++) {
JOptionPane.showMessageDialog(null, "Customer #" + two[o]);
//jop.showMessageDialog(null, "Duplicates: Customer #" + 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 > 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 & y2), in which y1 = 1 when x <= 100 & y2 = 1 when x > 100 & 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 => s.GetTypes())
.Where(p => typeof(IQueue).IsAssignableFrom(p) && 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 ["java","-jar","app.jar"]
</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.<init>(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><div class="h-full bg-white" >
<div class="flex flex-col h-full">
<div id="Navbar" class="bg-blue-200">
Navbar
</div>
<div id="MainContent" class="flex flex-auto h-full overflow-y-hidden">
<div>
<div class="flex-grow-0 flex-shrink-0 flex flex-col h-full w-56 bg-green-100">
<div class="flex flex-grow overflow-y-auto overflow-x-hidden">
<div>
<p>lhs</p>
<p>lhs</p>
... lots more content here to ensure page overflow
</div>
</div>
<div>
Sidebar footer
</div>
</div>
</div>
<div class="bg-red-100 w-full">
Content
</div>
</div>
</div>
</div>
</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><p>las</p></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 => x.UserName == request.UserName
&& x.Date >= request.StartDate
&& x.Date <= request.EndDate)
.SumAsync(x => x.Amount),
TotalNumber = await dbContext.Transaction
.Where(x => x.UserName == request.UserName
&& x.Date = request.StartDate
&& x.Date <= 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 && item != null && !orderDetail.isUnitPriceModified()) {
ItemSizeColorStyle itemSizeColorStyle = itemSizeColorStyleRepository.findByRecordID(orderDetail.getItemSCSID());
if (origin != null && (origin.contains("b2baccess") || (origin.contains(".myappdev") && !origin.contains("apps.myappdev")))) {
RepGroupManufacturer repGroupManufacturer = repGroupManufacturerRepository.findByRepGroupIDAndManufacturerIDAndRecordDeleted(repGroupID, manufacturerID, NOT_DELETED);
if (repGroupManufacturer != null && repGroupManufacturer.getB2bItemPricingPolicy() != null && repGroupManufacturer.getB2bItemPricingPolicy().equalsIgnoreCase(ReptimeConstants.SHOWRETAILPRICE)) {
if (orderDetail.getItemSCSID() == null && item.getRetailPrice() != null) {
orderDetail.setUnitPrice(item.getRetailPrice());
} else {
// ItemSizeColorStyle itemSizeColorStyle = itemSizeColorStyleRepository.findByRecordID(orderDetail.getItemSCSID());
if (itemSizeColorStyle != null && itemSizeColorStyle.getRetailPrice() != null) {
orderDetail.setUnitPrice(itemSizeColorStyle.getRetailPrice());
} else if (itemSizeColorStyle != null && itemSizeColorStyle.getRetailPrice() == null && item.getRetailPrice() != null) {
orderDetail.setUnitPrice(item.getRetailPrice());
} else if (itemSizeColorStyle != null && itemSizeColorStyle.getRetailPrice() == null && item.getRetailPrice() == null) {
throw new NullPointerException("item price can not be null.");
}
}
}
}
</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 "cannot get/"</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, () => 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><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="codefreeze.js"></script>
<link rel="stylesheet" href="codefreeze.css">
<link href = "https://fonts.googleapis.com/css?family=Schoolbell&v1" rel="stylesheet">
<title>DIARY</title>
</head>
<body onload="Name()">
<h1>HELLO!</h1>
<p>Welcome <span id="name"></span></p>
<p id="date"></p>
<script>
document.getElementById("date").innerHTML = DATE();
</script>
<div id="user">
<label id="lbl1">Passage #1</label><br>
<textarea id="psg1" rows="10" cols="30"></textarea><br>
</div>
<button id="save" onclick="save()">SAVE</button>
<button id="add" onclick="add()">ADD</button>
<button id="delete" onclick="del()">DELETE</button>
</body>
</html>
</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><form class="" method="GET" action="manage_product.php">
<h6 class="dropdown-header px-0">Gender</h6>
<div class="form-check">
<input class="form-check-input" name="genderFil[]" type="checkbox" value="M" class="genderFil" id="genMale" <?= ($isMale == 1) ? "checked" : ""; ?>>
<label class="form-check-label" for="genMale">Male</label>
</div>
<div class="form-check">
<input class="form-check-input" name="genderFil[]" type="checkbox" value="F" class="genderFil" id="genFemale" <?= ($isFemale == 1) ? "checked" : ""; ?>>
<label class="form-check-label" for="genFemale">Female</label>
</div>
<div class="dropdown-divider"></div>
<h6 class="dropdown-header px-0">Category</h6>
<div class="form-check">
<input class="form-check-input" name="categoryFil[]" type="checkbox" value="1" class="categoryFil" id="catShoes" <?= ($isShoes == 1) ? "checked" : ""; ?>>
<label class="form-check-label" for="catShoes">Shoes</label>
</div>
<div class="form-check">
<input class="form-check-input" name="categoryFil[]" type="checkbox" value="2" class="categoryFil" id="catPants" <?= ($isPants == 1) ? "checked" : ""; ?>>
<label class="form-check-label" for="catPants">Pants</label>
</div>
<div class="form-check">
<input class="form-check-input" name="categoryFil[]" type="checkbox" value="3" class="categoryFil" id="catShirts" <?= ($isShirts == 1) ? "checked" : ""; ?>>
<label class="form-check-label" for="catShirts">Shirts</label>
</div>
<div class="dropdown-divider"></div>
<input type="submit" class="button_primary" name="applyFilter" value="Apply" onclick="checkFilter()">
</form>
</code></pre>
<p>Below is the javascript that I tried to code:</p>
<pre><code> function checkFilter()
{
var res = true;
var checkedGender = $('input[class="genderFil"]:checked').length;
if(checkedGender < 1)
{
alert("Please select at least one gender!");
res = false;
}
var checkedCategory = $('input[class="categoryFil"]:checked').length;
if(checkedCategory < 1)
{
alert("Please select at least one category!");
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: ["10:00","10:30","11:00","11:30","12:00"],
2: ["10:00","10:30","11:00","11:30","12:00"],
3: ["10:00","10:30","11:00","11:30","12:00"],
....
}
</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: "2022-12-01T11:30:00.000+02:00"
}
];
</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>["10:00","10:30","11:00","12:00"]</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) => {
let bookedDate = new Date(bookedDateObject.date);
// 1
let currentAvailableTimesOnDate = availableTimesPerDay[bookedDate.getDate()];
// ["10:00","10:30","11:00","11:30","12:00"]
let bookedTime = bookedDate.toLocaleTimeString('et');
// "13:30:00"
let time = bookedTime.substring(0,bookedTime.length - 3);
// "13:30"
let index = currentAvailableTimesOnDate.indexOf(time);
// 3
if (index > -1) {
currentAvailableTimesOnDate.splice(index, 1);
// ["10:00","10:30","11:00","12:00"]
}
})
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 {"1":["10:00","10:30","11:00","11:30","12:00"],"2":[],"3":[],"4":[],"5":[],"6":[],"7":[],"8":["10:00","10:30","11:00","11:30","12:00"],"9":[],"10":[],"11":[],"12":[],"13":[],"14":[],"15":["10:00","10:30","11:00","11:30","12:00"],"16":[],"17":[],"18":[],"19":[],"20":[],"21":[],"22":["10:00","10:30","11:00","11:30","12:00"],"23":[],"24":[],"25":[],"26":[],"27":[],"28":[],"29":["10:00","10:30","11:00","11:30","12:00"],"30":[],"31":[]}
booking-helper.js:105 {"1":["10:00","10:30","11:00","12:00"],"2":[],"3":[],"4":[],"5":[],"6":[],"7":[],"8":["10:00","10:30","11:00","12:00"],"9":[],"10":[],"11":[],"12":[],"13":[],"14":[],"15":["10:00","10:30","11:00","12:00"],"16":[],"17":[],"18":[],"19":[],"20":[],"21":[],"22":["10:00","10:30","11:00","12:00"],"23":[],"24":[],"25":[],"26":[],"27":[],"28":[],"29":["10:00","10:30","11:00","12:00"],"30":[],"31":[
</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<IFormProps> = ({formData, handleFormData, errors, handleValidate}) => {
const inputField = React.useRef() as React.MutableRefObject<HTMLInputElement>;
return (
<form className='user-form'>
<label>First Name</label>
<input
type="text"
ref = {inputField}
value={formData.firstName}
name="firstName" id="firstName"
onChange={(e) => handleFormData(e)} placeholder="Enter your first name"
onFocus={() => console.log('focus')}
onBlur={() => handleValidate(inputField)}
/>
<label>Last Name</label>
<input
type="text"
value={formData.lastName}
name="lastName" id="lastName"
onChange={(e) => handleFormData(e)}
placeholder="Enter the last name"
onBlur={() => handleValidate(inputField)}
ref = {inputField}
/>
</form>
)
}
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) => (inputField.current["firstName"] = el)}
</code></pre>
<pre><code>Element implicitly has an 'any' type because expression of type '"firstName"' 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 "@".
How can I escape the @? (need to escape the "fields.@version")</p>
<pre><code>let Source = datatable (fields: dynamic) [
dynamic({"seq":17300,"@version":"1"})
];
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 "I'm swimming!!!!" ;
}
}
</code></pre>
<p><strong>Program</strong></p>
<pre><code> Athete test = New Swimmer("John","Tigers");
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<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>}
"user-account-id": "John",
"user-account-number": "v1001",
"user-account-app": "v10.0.0",
"user-account-dbase": "v10.1.0",
}
</code></pre>
<p>I want the end result to be like this:</p>
<pre><code>}
"user-account-id": "John",
"user-account-number": "v1001",
"user-account-app": "v10.0.0",
"user-account-dbase": "v10.1.0"
}
</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 "2nd to the last line" in the file.</p>
<p>The output would just delete commas in every line, which doesn't make sense:</p>
<pre><code>}
"user-account-id": "John"
"user-account-number": "v1001"
"user-account-app": "v10.0.0"
"user-account-dbase": "v10.1.0"
}
</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(() => {
async function fetchData() {
const res = await checkLogin();
console.log(res);
}
fetchData();
}, []);
</code></pre>
<p>checkLogin returning "Hello world"</p>
<pre><code> async function checkLogin() {
try {
const resp = await linstance.get("/api/auth/user");
setUser(resp.data.user);
setEmail(resp.data.email);
setId(resp.data.id);
return "Hello world";
} 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 "Hello world" (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("####################################")
</code></pre>
<p>And here is the <code>JSON</code>:</p>
<pre class="lang-json prettyprint-override"><code>{"props": {
"XYZ": {
"ABC": [
{
"current": "sold",
"location": "FD",
"type": "d",
"uid": "01020633"
}
],
"searchTerm": "asd"
}
}}
</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)
<ipython-input-2-5efeb940cd16> in <module>
6 r_x = robjects.FloatVector(x)
7 r_y = robjects.FloatVector(y)
----> 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 """
--> 252 raise NotImplementedError(
253 "Conversion 'rpy2py' not defined for objects of type '%s'" %
254 str(type(obj))
NotImplementedError: Conversion 'rpy2py' not defined for objects of type '<class 'rpy2.rinterface.SexpClosure'>'
</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 "react";
import { useNavigate } from "react-router-dom";
export default function SearchReq(searchTerm: string) {
if (searchTerm === "") return;
const navigate = useNavigate();
console.log(searchTerm);
// window.location.href = "/search?searchTerm=" + searchTerm;
navigate("/search?searchTerm=" + 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) && clickEnable)
{
Debug.Log("Clicked"); // 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("Clicked2"); // THIS WORKS TOO
}
}
private void OnTriggerEnter(Collider collisionInfo)
{
if(gameData.isWatched) return;
if (collisionInfo.CompareTag("Player"))
{
interactButton.GetComponent<Button>().onClick.RemoveListener(tvDialog);
interactButton.GetComponent<Button>().onClick.AddListener(tvDialog);
}
}
private void OnTriggerExit(Collider collisionInfo)
{
Debug.Log("Hello");
if (gameData.isWatched) return;
if (collisionInfo.CompareTag("Player"))
{
interactButton.GetComponent<Button>().onClick.RemoveListener(tvDialog);
}
}
public void tvDialog()
{
dialogbox.SetActive(true);
interactButton.SetActive(false);
dialogCycle = 0;
followPlayer.player = tv;
objectJson = JsonUtility.FromJson<ObjectDialog>(objectData.text);
loadDialog();
}
public void loadDialog()
{
dialogbox.transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = objectJson.name;
dialogMessage = objectJson.object_dialog.Split('#');
dialogbox.transform.GetChild(1).GetComponent<TextMeshProUGUI>().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) && 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("Player"))
{
if(gameObject.CompareTag("Door"))
{
interactButton.SetActive(true);
interactButton.GetComponent<Image>().sprite = Resources.Load<Sprite>("InteractionAsset/OBJECT");
interactButton.transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = "Open";
interactButton.GetComponent<Button>().onClick.RemoveListener(enter);
interactButton.GetComponent<Button>().onClick.AddListener(enter);
}
else if(gameObject.CompareTag("Newspaper"))
{
if (!gameData.cryptoDone)
{
interactButton.SetActive(true);
interactButton.GetComponent<Image>().sprite = Resources.Load<Sprite>("InteractionAsset/OBJECT");
interactButton.transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = "View";
gameObject.GetComponent<Outline>().enabled = true;
// ADD ONCLICK FOR NEWSPAPER
interactButton.GetComponent<Button>().onClick.RemoveAllListeners();
interactButton.GetComponent<Button>().onClick.AddListener(showCryptogram);
}
}
else if(gameObject.CompareTag("ObjectDialog"))
{
interactButton.SetActive(true);
interactButton.GetComponent<Image>().sprite = Resources.Load<Sprite>("InteractionAsset/OBJECT");
interactButton.transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = "View";
gameObject.GetComponent<Outline>().enabled = true;
interactButton.GetComponent<Button>().onClick.RemoveAllListeners();
interactButton.GetComponent<Button>().onClick.AddListener(objectDialog);
}
// WHEN LEAVING ROOMS
if (gameObject.name == "apt_floor")
{
isInside = true;
aptArrow.SetActive(true);
}
else if (gameObject.name == "cafe_floor")
{
isInside = true;
cafeArrow.SetActive(true);
}
else if(gameObject.name == "konbini_floor")
{
isInside = true;
konbiniArrow.SetActive(true);
}
}
}
private void OnTriggerExit(Collider collisionInfo)
{
interactButton.SetActive(false);
interactButton.GetComponent<Button>().onClick.RemoveAllListeners();
if (collisionInfo.CompareTag("Player"))
{
// TURN OFF OUTLINE / HIGHLIGHT
if(gameObject.CompareTag("Newspaper"))
{
gameObject.GetComponent<Outline>().enabled = false;
}
else if (gameObject.CompareTag("ObjectDialog"))
{
gameObject.GetComponent<Outline>().enabled = false;
}
// WHEN LEAVING ROOMS
if (gameObject.name == "apt_floor" || (gameObject.name == "apt_wall" && !isInside && isOpen))
{
for (int i = 0; i < apartment.Length; i++)
{
transform.root.GetChild(apartment[i]).GetComponent<MeshRenderer>().enabled = true;
transform.root.GetChild(apartment[i]).gameObject.SetActive(true);
}
aptArrow.SetActive(false);
}
else if(gameObject.name == "cafe_floor" || (gameObject.name == "cafe_wall" && !isInside && isOpen))
{
for (int i = 0; i < cafe.Length; i++)
{
if (i != 13)
{
transform.root.GetChild(cafe[i]).gameObject.SetActive(true);
}
}
transform.root.GetChild(63).GetComponent<MeshRenderer>().enabled = true;
transform.root.GetChild(67).GetComponent<MeshRenderer>().enabled = true;
transform.root.GetChild(68).GetComponent<MeshRenderer>().enabled = true;
transform.root.GetChild(59).gameObject.SetActive(true);
cafeArrow.SetActive(false);
}
else if(gameObject.name == "konbini_floor" || (gameObject.name == "konbini_wall" && !isInside && isOpen))
{
for (int i = 0; i < konbini.Length; i++)
{
transform.root.GetChild(konbini[i]).GetComponent<MeshRenderer>().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<AudioManager>().Play("ButtonSound");
if (gameObject.name == "apt_door")
{
for(int i = 0; i < apartment.Length; i++)
{
transform.root.GetChild(apartment[i]).GetComponent<MeshRenderer>().enabled = false;
}
gameObject.SetActive(false);
}else if(gameObject.name == "cafe_door")
{
for (int i = 0; i < cafe.Length; i++)
{
if(i != 13)
{
transform.root.GetChild(cafe[i]).gameObject.SetActive(false);
}
}
transform.root.GetChild(63).GetComponent<MeshRenderer>().enabled = false;
transform.root.GetChild(67).GetComponent<MeshRenderer>().enabled = false;
transform.root.GetChild(68).GetComponent<MeshRenderer>().enabled = false;
gameObject.SetActive(false);
}else if(gameObject.name == "konbini_door1")
{
for (int i = 0; i < konbini.Length; i++)
{
transform.root.GetChild(konbini[i]).GetComponent<MeshRenderer>().enabled = false;
}
transform.root.GetChild(73).gameObject.SetActive(false);
transform.root.GetChild(74).gameObject.SetActive(false);
}
isOpen = true;
interactButton.SetActive(false);
interactButton.GetComponent<Button>().onClick.RemoveListener(enter);
}
// SHOW CRYPTOGRAM MINIGAME IN OBJECT
public void showCryptogram()
{
FindObjectOfType<AudioManager>().Play("ButtonSound");
cryptogram.SetActive(true);
}
public void objectDialog()
{
dialogbox.SetActive(true);
interactButton.SetActive(false);
dialogCycle = 0;
loadJson();
loadDialog();
}
public void loadJson()
{
if (gameObject.name == "Radio")
{
objectData = Resources.Load<TextAsset>("JSON/Objects/Radio");
}else if(gameObject.name == "Television")
{
objectData = Resources.Load<TextAsset>("JSON/Objects/TV");
}
objectJson = JsonUtility.FromJson<ObjectDialog>(objectData.text);
}
public void loadDialog()
{
dialogbox.transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = objectJson.name;
dialogMessage = objectJson.object_dialog.Split('#');
if (dialogMessage.Length == 1)
{
dialogbox.transform.GetChild(1).GetComponent<TextMeshProUGUI>().text = objectJson.object_dialog;
}
else if (dialogCycle < dialogMessage.Length)
{
dialogbox.transform.GetChild(1).GetComponent<TextMeshProUGUI>().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 <stdio.h>
int MyFun(void)
{
printf("Hello, World!");
return 0;
}
void *funarray[] = { NULL,NULL,&MyFun,NULL,NULL };
int main(void)
{
size_t CallMyFun = (size_t)&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>> A = np.array([[1, 2], [3, 4], [5,6]])
> output = np.zeros(shape=(A.shape[0], A.shape[1], A.shape[0]))
> for i in range(a.shape[0]):
output[:, :, i] = np.minimum(A, A[i])
> 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("mousemove", 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 + "px";
document.getElementById(obj.id).style.top = event.clientY + "px";
}
</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("test").innerText = e.clientX + ' ' + e.clientY;
document.getElementById("test").style.position = 'absolute';
document.getElementById("test").style.left = e.clientX + "px";
document.getElementById("test").style.top = e.clientY + "px";
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 > 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' => [
'required',
Rule::unique('users')->ignore($user->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' => 'required|string|exists:' . Product::class,
'product_name' => 'required|unique:' . Product::class,
'product_stock_amount' => 'required|integer|numeric|gte:0',
'product_price' => 'required|integer|numeric|gte:0',
'product_price_currency' => 'required|string|',
'product_description' => '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,"select AH, AW Where Schedule!A:A = '"&I2&"'")
</code></pre>
<p>Its shooting an error of "Unable to parse query string for Function QUERY parameter 2: PARSE_ERROR: Encountered " "Schedule "" at line 1, column 21. Was expecting one of: "(" ... "(" ...
"</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' => [
'required|email:rfc,dns|min:5|max:75',
Rule::unique("email")->where(function ($query) {
$query->where("product_uuid", $this->product_uuid)
->where("affiliate_uuid", $this->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 "react";
import axios from "axios";
const UserList = () => {
const [userData, setUserData] = useState("");
const fetchUserData = async () => {
const resp = await axios.get("/getTodo");
console.log(resp);
//if no user is there please dont set any value
if (resp.data.users.length > 0) {
setUserData(resp.data.users);
}
};
useEffect(() => {
fetchUserData();
}, [userData]);
///edit
const handleEdit = async (user) => {
var edittodo = `${user.todo}`;
var edittask = `${user.task}`;
const userTodo = prompt("Enter your Name", edittodo);
const userTask = prompt("Enter your Email", edittask);
if (!userTodo || !userTask) {
alert("please Enter Todo and Task Both");
} else {
const resp = await axios.put(`/editTodo/${user._id}`, {
todo: userTodo,
task: userTask,
});
console.log(resp);
}
};
//Delete
const handleDelete = async (userId) => {
const resp = await axios.delete(`/deleteTodo/${userId}`);
console.log(resp);
};
const searchHandle = async (event) => {
let key = event.target.value;
console.log(key)
await axios
.get(`http://localhost:5500/search/${key}`)
.then((response) => {
console.log(response.data);
})
.catch((err) => {
console.log(err);
});
};
return (
<div>
<form>
<input
type="text"
className="search-box"
placeholder="Search Todo"
onChange={(searchHandle)}
/>
</form>
<section className="text-gray-600 body-font">
<div className="container px-5 py-24 mx-auto">
<div className="flex flex-col text-center w-full mb-8">
<h1 className="sm:text-4xl text-3xl font-medium title-font mb-2 text-gray-900">
All Users
</h1>
</div>
<div className="lg:w-2/3 w-full mx-auto overflow-auto">
<table className="table-auto w-full text-left whitespace-no-wrap">
<thead>
<tr>
<th className="px-4 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100 rounded-tl rounded-bl">
Todo
</th>
<th className="px-4 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100">
Task
</th>
<th className="px-4 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100">
Edit
</th>
<th className="px-4 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100">
Delete
</th>
</tr>
</thead>
<tbody>
{userData &&
userData.map((user, index) => (
<tr key={index}>
<td className="px-4 py-3">{user.todo}</td>
<td className="px-4 py-3">{user.task}</td>
<td className="px-4 py-3">
<button
className="hover:text-green-500"
onClick={() => handleEdit(user)}
>
Edit
</button>
</td>
<td className="px-4 py-3 text-lg text-gray-900">
<button
className="hover:text-red-500"
onClick={() => handleDelete(user._id)}
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</section>
</div>
);
};
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><script>
import {leagueStandings} from "../../stores/league-standings-stores"
const tablePositions = $leagueStandings.flatMap(({ standings: { data } }) => data);
</script>
<div class="bg-[#1C1C25] p-8 rounded-lg box-border w-fit">
{#each tablePositions as tablePosition}
<div class="standings-table flex gap-9 mb-2 pb-4 pt-3 border-b border-[#303041]">
<div class="team-details flex gap-4 w-full" id="td">
<p class="w-[18px]">{tablePosition.position}</p>
<img src="{tablePosition.team.data.logo_path}" alt="" class="w-[1.5em] object-scale-down">
<p class="">{tablePosition.team_name}</p>
</div>
<div class="team-stats flex gap-5 text-left child:w-5 child:text-center w-full">
<p>{tablePosition.overall.games_played}</p>
<p>{tablePosition.overall.won}</p>
<p>{tablePosition.overall.draw}</p>
<p>{tablePosition.overall.lost}</p>
<p>{tablePosition.overall.goals_scored}</p>
<p>{tablePosition.overall.goals_against}</p>
<p>{tablePosition.total.goal_difference}</p>
<p>{tablePosition.overall.points}</p>
<p class="!w-[78px] !text-left">{tablePosition.recent_form}</p>
</div>
</div>
{/each}
</div>
</code></pre>
<p>Here is my svelte store</p>
<pre><code>import { writable } from "svelte/store";
export const leagueStandings = writable([]);
const fetchStandings = async () => {
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>...
<span class="uniqueParent">
<span class="notUniqueChildClassName">
I am the child
</span>
</span>
...
</code></pre>
<p>Output should be "I am the child".</p>
<p>I have tried:</p>
<pre><code>s = soup.select('span[class="uniqueParent"] > span[class="notUniqueChildClassName"]')
s.text
</code></pre>
<p>and</p>
<pre><code>s = soup.find('span[class="uniqueParent"] > span[class="notUniqueChildClassName"]')
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> <form action="/delete" method="post">
<button id="deleteForm" class="btn btn-danger" onclick="deleteConfirm(this.form)">Delete</button>
</form>
</code></pre>
<p>And in my script.js I wrote the function:</p>
<pre><code>function deleteConfirm() {
let text = "Are you sure?\nOk=Delete all data.";
if (confirm(text) == true) {
document.getElementById("deleteForm").submit();
} else {
alert("Cancelled.");
}
}
</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 = "";
while(key != "q"){
key += input.nextLine();
return key;
}
return "hello";
</code></pre>
<p>}
//if input is "1234" then it should return key = "1234",</p>
<p>if the input is "1234q" then it should return "hello"</p>
<p>The output im getting is >nothing< until I do it twice, and then it returns key = "1234q"</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/"
] |