qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,502,733
<p>I have my current sql query which I will later convert to a HIVE query.</p> <pre class="lang-sql prettyprint-override"><code>SELECT home_team, COUNT(home_team) from results WHERE results.home_score &lt; results.away_score GROUP BY home_team UNION SELECT away_team, COUNT(away_team) FROM results WHERE results.away_score &lt; results.home_score GROUP BY away_team </code></pre> <p>And it currently returns two occurrences of a country, once as a home_team and once as an away_team. <a href="https://i.stack.imgur.com/FQgV8.png" rel="nofollow noreferrer">Current results</a></p> <p>How can I modify this query so it adds the count(home_team) and makes the country only appear once? Ex. Argentina : 50</p> <p>I've tried to put both select queries in brackets and then count the sum being returned but I seem to always get an error when I do order by.</p>
[ { "answer_id": 74502812, "author": "Pepijn Kramer", "author_id": 16649550, "author_profile": "https://Stackoverflow.com/users/16649550", "pm_score": 3, "selected": true, "text": "#include <type_traits>\n#include <string>\n\n// declare your own concept\ntemplate<typename type_t>\nconcept my_concept = std::is_convertible_v<type_t, std::string>; // just a demo concept\n \nclass ColouredString\n{\npublic:\n // then you can limit your constructor to types satisfying that concept\n ColouredString(const my_concept auto& /*arg*/)\n {\n }\n\n ~ColouredString() = default;\n};\n\n\nint main()\n{\n // ColouredString str{ 1 };\n ColouredString str{ \"hello world!\" };\n\n return 0;\n}\n" }, { "answer_id": 74503750, "author": "apple apple", "author_id": 5980430, "author_profile": "https://Stackoverflow.com/users/5980430", "pm_score": 1, "selected": false, "text": "class ColouredString{\npublic:\n template<typename T>\n requires (std::is_convertible_v<T, std::string>)\n ColouredString(const T&){}\n};\n std::convertable_to class ColouredString{\npublic:\n ColouredString(const std::convertible_to<std::string> auto&){}\n};\n string ColouredString std::basic_string<ColouredChar> de(\"string\"_purple); // it already fail here\nColouredString d(de); \n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6286130/" ]
74,502,770
<p>I have a collection of docs like</p> <pre><code>{'id':1, 'score': 1, created_at: ISODate(...)} {'id':1, 'score': 2, created_at: ISODate(...)} {'id':2, 'score': 1, created_at: ISODate(...)} {'id':2, 'score': 20, created_at: ISODate(...)} </code></pre> <p>etc.</p> <p>Does anyone know how to find docs that were created within the past 24hrs where the difference of the <code>score</code> value between the two most recent docs of the same <code>id</code> is less than 5?</p> <p>So far I can only find all docs created within the past 24hrs:</p> <pre><code>[{ $project: { _id: 0, score: 1, created_at: 1 } }, { $match: { $expr: { $gte: [ '$created_at', { $subtract: [ '$$NOW', 86400000 ] } ] } } }] </code></pre> <p>Any advice appreciated.</p> <p>Edit: By the two most recent docs, the oldest of the two can be created more than 24hrs ago. So the most recent doc would be created within the past 24hrs, but the oldest doc could be created over 24hrs ago.</p>
[ { "answer_id": 74502812, "author": "Pepijn Kramer", "author_id": 16649550, "author_profile": "https://Stackoverflow.com/users/16649550", "pm_score": 3, "selected": true, "text": "#include <type_traits>\n#include <string>\n\n// declare your own concept\ntemplate<typename type_t>\nconcept my_concept = std::is_convertible_v<type_t, std::string>; // just a demo concept\n \nclass ColouredString\n{\npublic:\n // then you can limit your constructor to types satisfying that concept\n ColouredString(const my_concept auto& /*arg*/)\n {\n }\n\n ~ColouredString() = default;\n};\n\n\nint main()\n{\n // ColouredString str{ 1 };\n ColouredString str{ \"hello world!\" };\n\n return 0;\n}\n" }, { "answer_id": 74503750, "author": "apple apple", "author_id": 5980430, "author_profile": "https://Stackoverflow.com/users/5980430", "pm_score": 1, "selected": false, "text": "class ColouredString{\npublic:\n template<typename T>\n requires (std::is_convertible_v<T, std::string>)\n ColouredString(const T&){}\n};\n std::convertable_to class ColouredString{\npublic:\n ColouredString(const std::convertible_to<std::string> auto&){}\n};\n string ColouredString std::basic_string<ColouredChar> de(\"string\"_purple); // it already fail here\nColouredString d(de); \n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5349476/" ]
74,502,777
<p>Package <code>shinyscreenshot</code> is not able to print <code>plotly</code> colorbars (<a href="https://stackoverflow.com/questions/74473002/shiny-screenshot-appears-with-colorless-legend#comment131515103_74473168">shiny screenshot appears with colorless legend</a>), so I'm looking for a way to still use color gradient but display the legend as if it were factorised.</p> <hr /> <h1>Example</h1> <p><strong>Origin plot with colorbar</strong></p> <p><a href="https://i.stack.imgur.com/Y2OqIm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y2OqIm.png" alt="enter image description here" /></a></p> <p><strong>Goal</strong></p> <p><a href="https://i.stack.imgur.com/0Fpcwm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0Fpcwm.png" alt="enter image description here" /></a></p> <p>It doesn't mattert if there are 4, 5 or X datapoints in legend.</p> <hr /> <h1>MWE</h1> <pre><code>library(ggplot2) library(plotly) ggplotly( ggplot(data=mtcars, aes(x=mpg, y=cyl, color=qsec)) + geom_point() ) </code></pre>
[ { "answer_id": 74509733, "author": "jrcalabrese", "author_id": 14992857, "author_profile": "https://Stackoverflow.com/users/14992857", "pm_score": 1, "selected": false, "text": "scale_color_continuous guides(color = guide_legend()) ggplot ggplotly() ggplotly() library(tidyverse)\nlibrary(plotly)\ndata(mtcars)\n\np <- ggplot(mtcars, aes(x = mpg, y = cyl, color = qsec)) + \n geom_point() +\n scale_color_continuous(breaks = c(15, 17.5, 20, 22.5)) +\n guides(color = guide_legend(\n reverse = T, \n override.aes = list(shape = 19, size = 8))) +\n theme(legend.position = \"right\")\np\n\np2 <- ggplotly(p) %>% layout(showlegend = T)\np2\n" }, { "answer_id": 74510385, "author": "Kat", "author_id": 5329073, "author_profile": "https://Stackoverflow.com/users/5329073", "pm_score": 3, "selected": true, "text": "ggplot ggplotly plt <- ggplotly(\n ggplot(data=mtcars,\n aes(x=mpg, y=cyl, color=qsec)) +\n geom_point()\n)\n\ng <- ggplot(data=mtcars,\n aes(x=mpg, y=cyl, color=qsec)) +\n geom_point()\n ggplot mtcars qsec colByVal <- cbind(ggplot_build(g)$data[[1]], mtcars) %>% \n as.data.frame() %>% \n select(colour, qsec) %>% arrange(qsec) %>% \n group_by(colour) %>% \n summarise(qsec = median(qsec)) %>% as.data.frame()\n summary parts <- summary(colByVal$qsec)\n# drop the mean or median (the same color probably)\nparts <- parts[-4]\n DescTools::Closest qsec vals <- lapply(parts, function(k) {\n DescTools::Closest(colByVal$qsec, k)[1]\n}) %>% unlist(use.names = F)\n qsec cols <- colByVal %>% \n filter(qsec %in% vals) %>% select(colour) %>% \n unlist(use.names = F)\n ys <- seq(from = .7, by = .07, length.out = length(cols))\n lapply # create shapes\nshp <- function(y, cr) { # y0, and fillcolor\n list(type = \"circle\",\n xref = \"paper\", x0 = 1.1, x1 = 1.125,\n yref = \"paper\", y0 = y, y1 = y + .025,\n fillcolor = cr, yanchor = \"center\",\n line = list(color = cr))\n}\n# create labels\nano <- function(ya, lab) { # y and label\n list(x = 1.13, y = ya + .035, text = lab, \n xref = \"paper\", yref = \"paper\", \n xanchor = \"left\", yanchor = 'top', \n showarrow = F)\n}\n# the shapes list\nshps <- lapply(1:length(cols),\n function(j) {\n shp(ys[j], cols[j])\n })\n# the labels list\nlabs <- lapply(1:length(cols),\n function(i) {\n ano(ys[i], as.character(vals[i]))\n })\n ggplotly ggplotly shapes layout # ggplot > ggplotly adds an empty shape; this conflicts with calling it in\n# layout(); we'll replace 'shapes' first\nplt$x$layout$shapes <- shps\nplt %>% hide_colorbar() %>% \n layout(annotations = labs, showlegend = F, \n margin = list(t = 30, r = 100, l = 50, b = 30, pad = 3))\n library(tidyverse)\nlibrary(plotly)\n# original plot\nplt <- ggplotly(\n ggplot(data=mtcars,\n aes(x=mpg, y=cyl, color=qsec)) +\n geom_point()\n)\ng <- ggplot(data=mtcars,\n aes(x=mpg, y=cyl, color=qsec)) +\n geom_point()\n# color by qsec values frame\ncolByVal <- cbind(ggplot_build(g)$data[[1]], mtcars) %>% \n as.data.frame() %>% \n select(colour, qsec) %>% arrange(qsec) %>% \n group_by(colour) %>% \n summarise(qsec = median(qsec)) %>% as.data.frame()\n\nparts <- summary(colByVal$qsec)\n# drop the mean or median (the same color probably)\nparts <- parts[-4]\n\nvals <- lapply(parts, function(k) {\n DescTools::Closest(colByVal$qsec, k)[1]\n}) %>% unlist(use.names = F)\n\ncols <- colByVal %>% \n filter(qsec %in% vals) %>% select(colour) %>% \n unlist(use.names = F)\n\nys <- seq(from = .7, by = .07, length.out = length(cols))\n\n# create shapes\nshp <- function(y, cr) { # y0, and fillcolor\n list(type = \"circle\",\n xref = \"paper\", x0 = 1.1, x1 = 1.125,\n yref = \"paper\", y0 = y, y1 = y + .025,\n fillcolor = cr, yanchor = \"center\",\n line = list(color = cr))\n}\n# create labels\nano <- function(ya, lab) { # y and label\n list(x = 1.13, y = ya + .035, text = lab, \n xref = \"paper\", yref = \"paper\", \n xanchor = \"left\", yanchor = 'top', \n showarrow = F)\n}\n# the shapes list\nshps <- lapply(1:length(cols),\n function(j) {\n shp(ys[j], cols[j])\n })\n# the labels list\nlabs <- lapply(1:length(cols),\n function(i) {\n ano(ys[i], as.character(vals[i]))\n })\n# ggplot > ggplotly adds an empty shape; this conflicts with calling it in\n# layout(); we'll replace 'shapes' first\nplt$x$layout$shapes <- shps\nplt %>% hide_colorbar() %>% \n layout(annotations = labs, showlegend = F, \n margin = list(t = 30, r = 100, l = 50, b = 30, pad = 3))\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12242625/" ]
74,502,786
<p>I have this dataset:</p> <pre class="lang-js prettyprint-override"><code>const dataset = [ { date: &quot;2022-01-01&quot;, category: &quot;red&quot;, value: 10 }, { date: &quot;2022-01-01&quot;, category: &quot;blue&quot;, value: 20 }, { date: &quot;2022-01-01&quot;, category: &quot;gold&quot;, value: 30 }, { date: &quot;2022-01-01&quot;, category: &quot;green&quot;, value: 40 }, { date: &quot;2022-01-02&quot;, category: &quot;red&quot;, value: 5 }, { date: &quot;2022-01-02&quot;, category: &quot;blue&quot;, value: 15 }, { date: &quot;2022-01-02&quot;, category: &quot;gold&quot;, value: 25 }, { date: &quot;2022-01-02&quot;, category: &quot;green&quot;, value: 35 } ]; </code></pre> <p>And I need to flat the dataset to get this:</p> <pre class="lang-js prettyprint-override"><code>const flattenDataset = [ { &quot;date&quot;: &quot;2022-01-01&quot;, &quot;red&quot;: 10, &quot;blue&quot;: 20, &quot;gold&quot;: 30, &quot;green&quot;: 40 }, { &quot;date&quot;: &quot;2022-01-02&quot;, &quot;red&quot;: 5, &quot;blue&quot;: 15, &quot;gold&quot;: 25, &quot;green&quot;: 35 } ] </code></pre> <p>So group dataset by <code>date</code>s and for each <code>category</code> create a key with <code>value</code> as value. I created this function:</p> <pre class="lang-js prettyprint-override"><code>export function flatDataset( dataset: any, mainProperty: string, categoryProperty: string, valueProperty: string ) { if (dataset.length === 0 || !mainProperty) { return (dataset as unknown); } const columnToBeFlatValues = uniqBy(dataset, categoryProperty).map( (d) =&gt; d[categoryProperty] ); const datasetGroupedByMainProperty = groupBy(dataset, mainProperty); const datasetGroupedByMainCategoryFlat = Object.entries( datasetGroupedByMainProperty ).map(([date, datasetForDate]) =&gt; { const categoriesObject = columnToBeFlatValues.reduce((acc, value) =&gt; { const datum = datasetForDate.find( (d) =&gt; d[mainProperty] === date &amp;&amp; d[categoryProperty] === value ); acc[value] = datum?.[valueProperty]; return acc; }, {}); return { [mainProperty]: date, ...categoriesObject }; }); return datasetGroupedByMainCategoryFlat; } </code></pre> <p>It works but I would like to fix TypeScript. For example the dataset type should not be <code>any</code> but an array of objects with keys with name <code>mainProperty</code>, <code>categoryProperty</code>, <code>valueProperty</code>.</p> <p>For example, dataset could also be:</p> <pre class="lang-js prettyprint-override"><code>const dataset = [ { apple: ..., color: ..., something: ... }, ... ]; const flattenDataset = flatDataset(dataset, 'apple', 'color', 'something') </code></pre> <p>How can I do that?</p>
[ { "answer_id": 74509733, "author": "jrcalabrese", "author_id": 14992857, "author_profile": "https://Stackoverflow.com/users/14992857", "pm_score": 1, "selected": false, "text": "scale_color_continuous guides(color = guide_legend()) ggplot ggplotly() ggplotly() library(tidyverse)\nlibrary(plotly)\ndata(mtcars)\n\np <- ggplot(mtcars, aes(x = mpg, y = cyl, color = qsec)) + \n geom_point() +\n scale_color_continuous(breaks = c(15, 17.5, 20, 22.5)) +\n guides(color = guide_legend(\n reverse = T, \n override.aes = list(shape = 19, size = 8))) +\n theme(legend.position = \"right\")\np\n\np2 <- ggplotly(p) %>% layout(showlegend = T)\np2\n" }, { "answer_id": 74510385, "author": "Kat", "author_id": 5329073, "author_profile": "https://Stackoverflow.com/users/5329073", "pm_score": 3, "selected": true, "text": "ggplot ggplotly plt <- ggplotly(\n ggplot(data=mtcars,\n aes(x=mpg, y=cyl, color=qsec)) +\n geom_point()\n)\n\ng <- ggplot(data=mtcars,\n aes(x=mpg, y=cyl, color=qsec)) +\n geom_point()\n ggplot mtcars qsec colByVal <- cbind(ggplot_build(g)$data[[1]], mtcars) %>% \n as.data.frame() %>% \n select(colour, qsec) %>% arrange(qsec) %>% \n group_by(colour) %>% \n summarise(qsec = median(qsec)) %>% as.data.frame()\n summary parts <- summary(colByVal$qsec)\n# drop the mean or median (the same color probably)\nparts <- parts[-4]\n DescTools::Closest qsec vals <- lapply(parts, function(k) {\n DescTools::Closest(colByVal$qsec, k)[1]\n}) %>% unlist(use.names = F)\n qsec cols <- colByVal %>% \n filter(qsec %in% vals) %>% select(colour) %>% \n unlist(use.names = F)\n ys <- seq(from = .7, by = .07, length.out = length(cols))\n lapply # create shapes\nshp <- function(y, cr) { # y0, and fillcolor\n list(type = \"circle\",\n xref = \"paper\", x0 = 1.1, x1 = 1.125,\n yref = \"paper\", y0 = y, y1 = y + .025,\n fillcolor = cr, yanchor = \"center\",\n line = list(color = cr))\n}\n# create labels\nano <- function(ya, lab) { # y and label\n list(x = 1.13, y = ya + .035, text = lab, \n xref = \"paper\", yref = \"paper\", \n xanchor = \"left\", yanchor = 'top', \n showarrow = F)\n}\n# the shapes list\nshps <- lapply(1:length(cols),\n function(j) {\n shp(ys[j], cols[j])\n })\n# the labels list\nlabs <- lapply(1:length(cols),\n function(i) {\n ano(ys[i], as.character(vals[i]))\n })\n ggplotly ggplotly shapes layout # ggplot > ggplotly adds an empty shape; this conflicts with calling it in\n# layout(); we'll replace 'shapes' first\nplt$x$layout$shapes <- shps\nplt %>% hide_colorbar() %>% \n layout(annotations = labs, showlegend = F, \n margin = list(t = 30, r = 100, l = 50, b = 30, pad = 3))\n library(tidyverse)\nlibrary(plotly)\n# original plot\nplt <- ggplotly(\n ggplot(data=mtcars,\n aes(x=mpg, y=cyl, color=qsec)) +\n geom_point()\n)\ng <- ggplot(data=mtcars,\n aes(x=mpg, y=cyl, color=qsec)) +\n geom_point()\n# color by qsec values frame\ncolByVal <- cbind(ggplot_build(g)$data[[1]], mtcars) %>% \n as.data.frame() %>% \n select(colour, qsec) %>% arrange(qsec) %>% \n group_by(colour) %>% \n summarise(qsec = median(qsec)) %>% as.data.frame()\n\nparts <- summary(colByVal$qsec)\n# drop the mean or median (the same color probably)\nparts <- parts[-4]\n\nvals <- lapply(parts, function(k) {\n DescTools::Closest(colByVal$qsec, k)[1]\n}) %>% unlist(use.names = F)\n\ncols <- colByVal %>% \n filter(qsec %in% vals) %>% select(colour) %>% \n unlist(use.names = F)\n\nys <- seq(from = .7, by = .07, length.out = length(cols))\n\n# create shapes\nshp <- function(y, cr) { # y0, and fillcolor\n list(type = \"circle\",\n xref = \"paper\", x0 = 1.1, x1 = 1.125,\n yref = \"paper\", y0 = y, y1 = y + .025,\n fillcolor = cr, yanchor = \"center\",\n line = list(color = cr))\n}\n# create labels\nano <- function(ya, lab) { # y and label\n list(x = 1.13, y = ya + .035, text = lab, \n xref = \"paper\", yref = \"paper\", \n xanchor = \"left\", yanchor = 'top', \n showarrow = F)\n}\n# the shapes list\nshps <- lapply(1:length(cols),\n function(j) {\n shp(ys[j], cols[j])\n })\n# the labels list\nlabs <- lapply(1:length(cols),\n function(i) {\n ano(ys[i], as.character(vals[i]))\n })\n# ggplot > ggplotly adds an empty shape; this conflicts with calling it in\n# layout(); we'll replace 'shapes' first\nplt$x$layout$shapes <- shps\nplt %>% hide_colorbar() %>% \n layout(annotations = labs, showlegend = F, \n margin = list(t = 30, r = 100, l = 50, b = 30, pad = 3))\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13415477/" ]
74,502,795
<p>Im trying to configure my code to tell the user to re enter a number, taking them back to the scanner if it falls outside of my specified range of 25</p> <pre class="lang-java prettyprint-override"><code>long number;// declares variables for storing number long factorial = 1;// declare variable for storing factorial System.out.println(&quot;Enter a number between 1 and 25&quot;); // tells user to enter number number = scanner.nextLong(); if (number &lt;0) System.out.println(&quot;Positive numbers only&quot;);// if number entered is negative else if (number &gt; 25) System.out.println(&quot;Number to large to print&quot;); else if (number &lt;= 1)// if number entered is 0 or 1 System.out.printf(&quot;The factorial of &quot; + number+ &quot; is equal to &quot; + factorial); else { // if user enter 10, counter starts at 10 and runs to two for(long mynumber = number; mynumber &gt;= 1; mynumber--) { factorial = factorial*mynumber; // mynumber would contain different values and that is multiplied by value present in factorial value and storing again in factorial variable } System.out.println(&quot;The factorial of &quot; + number +&quot; is equal to &quot; + factorial); } </code></pre>
[ { "answer_id": 74503047, "author": "oleg.cherednik", "author_id": 3461397, "author_profile": "https://Stackoverflow.com/users/3461397", "pm_score": 1, "selected": false, "text": "public static void main(String... args) {\n Scanner scan = new Scanner(System.in);\n\n int num = getNumberWithin(scan, 1, 25);\n}\n\nprivate static int getNumberWithin(Scanner scan, int lo, int hi) {\n while (true) {\n System.out.format(\"Enter a number between %d and %d: \", lo, hi);\n int num = scan.nextInt();\n\n if (num >= lo && num <= hi)\n return num;\n\n System.err.format(\"The number should be between %d and %d\\n\", lo, hi);\n System.out.println();\n }\n}\n" }, { "answer_id": 74504142, "author": "Lau", "author_id": 20545889, "author_profile": "https://Stackoverflow.com/users/20545889", "pm_score": 1, "selected": true, "text": "boolean correctInputn = false;\n\nwhile(!correctInputn)\n{\n long number;// declares variables for storing number\n long factorial = 1;// declare variable for storing factorial\n \n\n System.out.println(\"Enter a number between 1 and 25\"); // tells user to enter number\n number = scanner.nextLong();\n \n if (number <0) {\n System.out.println(\"Positive numbers only\"); // if number entered is negative\n correctInputn = false;\n continue; // if user enters number less than 0 loops back to code start\n } else if (number > 25) {\n System.out.println(\"Number to large to print\");\n correctInputn = false;\n continue; // if user enters number over 25 loops back to code start\n } else {\n // if user enter 10, counter starts at 10 and runs to two\n for(long mynumber = number; mynumber >= 1; mynumber--) {\n factorial = factorial * mynumber; // mynumber would contain different values and that is multiplied by value present in factorial value and stored again in factorial variable\n }\n \n System.out.println(\"The factorial of \" + number +\" is equal to \" + factorial);\n break;\n }\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20545889/" ]
74,502,810
<p>The while loop and for loop works individually, but combining them does no generate the desired output. I want the user to enter a sentence, and then a character. The Character must be entered as a single 1 character, if not then the program should ask again.<br></p> <pre><code>sentence = input(&quot;Type sentence: &quot;) sentence = sentence.lower() singleCharacter = input(&quot;Type character: &quot;) char = 0 while len(singleCharacter) != 1: singleCharacter = input('Enter a single character: ') for i in sentence: if i == singleCharacter: char += 1 print(singleCharacter,&quot;appears&quot;,char,&quot;times in your sentence&quot;) </code></pre>
[ { "answer_id": 74502853, "author": "QWERTYL", "author_id": 11777402, "author_profile": "https://Stackoverflow.com/users/11777402", "pm_score": 1, "selected": false, "text": "sentence = input(\"Type sentence: \")\nsentence = sentence.lower()\nsingleCharacter = input(\"Type character: \")\n\nchar = 0\n\nwhile len(singleCharacter) != 1:\n singleCharacter = input('Enter a single character: ')\n\nprint(sum([1 for c in sentence if c == singleCharacter]))\n" }, { "answer_id": 74503030, "author": "Oghli", "author_id": 5169186, "author_profile": "https://Stackoverflow.com/users/5169186", "pm_score": 2, "selected": true, "text": "while len(singleCharacter) != 1:\n singleCharacter = input('Enter a single character: ')\n for i in sentence:\n if i == singleCharacter:\n char += 1\n len(singleCharacter) != 1 0 while len(singleCharacter) != 1:\n singleCharacter = input('Enter a single character: ')\nfor i in sentence:\n if i == singleCharacter:\n char += 1\n Type sentence: Hello World!\nType character: l\nl appears 3 times in your sentence\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4212022/" ]
74,502,816
<p>I am trying to use an <code>eventListener</code> to check input in an input box (<code>type=&quot;number&quot;</code>):</p> <pre><code>aE.addEventListener(&quot;input&quot;, (e) =&gt; { console.log(aE.value); } </code></pre> <p>But what I really need the <code>eventListener</code> to pick up is any change in <code>value</code> on the input box. This particular input box has a select where users can choose one of a few numerical options for constants. But the current method of eventListener does not pick up changes in value from that select.</p> <p>What is the correct syntax to get the value of the input box whenever it changes?</p>
[ { "answer_id": 74502853, "author": "QWERTYL", "author_id": 11777402, "author_profile": "https://Stackoverflow.com/users/11777402", "pm_score": 1, "selected": false, "text": "sentence = input(\"Type sentence: \")\nsentence = sentence.lower()\nsingleCharacter = input(\"Type character: \")\n\nchar = 0\n\nwhile len(singleCharacter) != 1:\n singleCharacter = input('Enter a single character: ')\n\nprint(sum([1 for c in sentence if c == singleCharacter]))\n" }, { "answer_id": 74503030, "author": "Oghli", "author_id": 5169186, "author_profile": "https://Stackoverflow.com/users/5169186", "pm_score": 2, "selected": true, "text": "while len(singleCharacter) != 1:\n singleCharacter = input('Enter a single character: ')\n for i in sentence:\n if i == singleCharacter:\n char += 1\n len(singleCharacter) != 1 0 while len(singleCharacter) != 1:\n singleCharacter = input('Enter a single character: ')\nfor i in sentence:\n if i == singleCharacter:\n char += 1\n Type sentence: Hello World!\nType character: l\nl appears 3 times in your sentence\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13062685/" ]
74,502,843
<p>I am building a simple Angular app.</p> <p>I have some static data in a JSON file which I want to load.</p> <p>I have put the file <code>data.json</code> under <code>src</code>.</p> <p>I am trying to load it as follows</p> <pre><code>export class AppComponent { private urlDataFile = './data.json'; constructor( private _http: HttpClient ) { this.loadData().subscribe((data) =&gt; { console.info(data); }); } private loadData() { return this._http.get(this.urlDataFile); } } </code></pre> <p>and am running my server with <code>ng serve</code>.</p> <p>At runtime (on page load), I see the <code>GET</code> request to <code>http://localhost:4200/data.json</code>, and it results in a <code>404 NOT FOUND</code></p> <p>I have tried putting this file elsewhere in the project - <code>/src</code>, <code>/src/app</code>, in the root of the project - with no success.</p> <p>Where should this file be located? Or am I fundamentally doing it wrong?</p>
[ { "answer_id": 74502853, "author": "QWERTYL", "author_id": 11777402, "author_profile": "https://Stackoverflow.com/users/11777402", "pm_score": 1, "selected": false, "text": "sentence = input(\"Type sentence: \")\nsentence = sentence.lower()\nsingleCharacter = input(\"Type character: \")\n\nchar = 0\n\nwhile len(singleCharacter) != 1:\n singleCharacter = input('Enter a single character: ')\n\nprint(sum([1 for c in sentence if c == singleCharacter]))\n" }, { "answer_id": 74503030, "author": "Oghli", "author_id": 5169186, "author_profile": "https://Stackoverflow.com/users/5169186", "pm_score": 2, "selected": true, "text": "while len(singleCharacter) != 1:\n singleCharacter = input('Enter a single character: ')\n for i in sentence:\n if i == singleCharacter:\n char += 1\n len(singleCharacter) != 1 0 while len(singleCharacter) != 1:\n singleCharacter = input('Enter a single character: ')\nfor i in sentence:\n if i == singleCharacter:\n char += 1\n Type sentence: Hello World!\nType character: l\nl appears 3 times in your sentence\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15452/" ]
74,502,858
<p>i am trying to dynamically alloc multiple matrixes instide of a struct, i've found a way to do it but it makes all of them the same size and i need them to be of different sizes</p> <pre><code>#include &lt;stdio.h&gt; #include&lt;stdlib.h&gt; #include &lt;stdbool.h&gt; struct matrice_dinamica{ int linii, coloane; int **matrice; } v[100], aux; void comanda_L_citire_matrice(int i) { scanf(&quot;%d %d&quot;, v[i].linii, v[i].coloane); v[0].**matrice = (int **) malloc(v[i].linii * sizeof(int *)); for(int i = 0; i &lt; v[i].linii; i++){ *(v[0].**matrice + i) = (int *)malloc(v[i].coloane * sizeof(int)); } } </code></pre> <p>i tried to do this but it gives an error that i can't get rid of: &quot;expected identifier before '*' token&quot;</p>
[ { "answer_id": 74503045, "author": "Weather Vane", "author_id": 4142924, "author_profile": "https://Stackoverflow.com/users/4142924", "pm_score": 1, "selected": true, "text": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct matrice_dinamica{\n int linii, coloane;\n int **matrice;\n} v[100];\n\nvoid comanda_L_citire_matrice(int i)\n{\n if(i < 0 || i >= 100 || scanf(\"%d %d\", &v[i].linii, &v[i].coloane) != 2) {\n /* handle error */\n }\n\n v[i].matrice = malloc(v[i].linii * sizeof(int *)); // don't cast malloc\n for(int j = 0; j < v[i].linii; j++){ // distinct variable j\n v[i].matrice[j] = malloc(v[i].coloane * sizeof(int)); // corrected [0] index\n }\n}\n & scanf scanf i i [0] [i] malloc malloc NULL" }, { "answer_id": 74503333, "author": "0___________", "author_id": 6110094, "author_profile": "https://Stackoverflow.com/users/6110094", "pm_score": 1, "selected": false, "text": "#define GET(str, row, col) ((int (*)[col])(str).matrice)[row][col]\n#define PUT(str, row, col, val) ((int (*)[col])(str).matrice)[row][col] = (val)\n\nstruct matrice_dinamica{\n size_t linii, coloane;\n void *matrice;\n} v[100];\n\nstruct matrice_dinamica *comanda_L_citire_matrice(size_t i)\n{\n struct matrice_dinamica *result = NULL;\n\n if((i < sizeof(v) / sizeof(v[0])))\n if(scanf(\"%zu %zu\", &v[i].linii, &v[i].coloane) == 2) \n {\n int (*ptr)[v[i].coloane] = malloc(v[i].linii *sizeof(*ptr));\n v[i].matrice = ptr;\n result = &v[i];\n }\n return result;\n}\n\n/* example usage */\nint foo(size_t r, size_t c, size_t x, int y)\n{\n printf(\"%d\", GET(v[5], 5, 6));\n PUT(v[x], r, c, y);\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17064433/" ]
74,502,864
<p>I have a class like:</p> <pre><code>#[derive(Clone,PartialEq,Debug)] pub enum List&lt;T&gt; { Nil, Cons(T,Box&lt;List&lt;T&gt;&gt;) } </code></pre> <p>Now suppose the Lists are created like the following:</p> <pre><code>let x = List::Cons(0, Box::new(List::Cons(1, Box::new(List::Cons(2, Box::new(List::Cons(3, Box::new(List::Nil)))))))); </code></pre> <p>Now I want to create a map function that applies f to each element in the List type but I have a problem because I do not know how to traverse through this data type.</p> <pre><code>pub fn map&lt;T,U,F:Fn(&amp;T)-&gt;U&gt;(f:F,l:&amp; List&lt;T&gt;) -&gt; List&lt;U&gt; { let mut myList = List::Nil; if let List::Nil = l { return List::Nil; } //Want to apply F to each element of l and than // append it to myList but do not know how. return myList; } </code></pre> <p>So something like:</p> <pre><code>let x = List::Cons(0, Box::new(List::Cons(1, Box::new(List::Cons(2, Box::new(List::Cons(3, Box::new(List::Nil)))))))); map(|val| val+1,&amp;x) </code></pre> <p>Should result in</p> <pre><code>List::Cons(1, Box::new(List::Cons(2, Box::new(List::Cons(3, Box::new(List::Cons(4, Box::new(List::Nil)))))))); </code></pre> <p>Can someone help me solve this?</p>
[ { "answer_id": 74503369, "author": "rodrigo", "author_id": 865874, "author_profile": "https://Stackoverflow.com/users/865874", "pm_score": 3, "selected": true, "text": "pub fn map<T, U, F: Fn(&T) -> U>(f: F, l: &List<T>) -> List<U> {\n match l {\n List::Nil => List::Nil,\n List::Cons(h, s) => List::Cons(f(h), Box::new(map(f, s)))\n }\n}\n" }, { "answer_id": 74503682, "author": "cafce25", "author_id": 442760, "author_profile": "https://Stackoverflow.com/users/442760", "pm_score": 1, "selected": false, "text": "#[derive(Clone,PartialEq,Debug)]\npub enum List<T: Clone + PartialEq + std::fmt::Debug> {\n Nil,\n Cons(T,Box<List<T>>)\n}\n\npub fn map<T,U,F:Fn(&T)->U>(f:F,mut l:&List<T>) -> List<U>\nwhere\n T: Clone + PartialEq + std::fmt::Debug,\n U: Clone + PartialEq + std::fmt::Debug,\n{\n let mut my_list = List::Nil;\n let mut current = &mut my_list;\n while let List::Cons(ref v, ref next) = l {\n *current = List::Cons(f(v), Box::new(List::Nil));\n current = match current {\n List::Cons(_, ref mut next) => next,\n _ => unreachable!(),\n };\n l = next;\n }\n my_list\n}\n Iterator FromIterator pub struct Iter<'a, T>\nwhere\n T: Clone + PartialEq + std::fmt::Debug + 'a,\n{\n list: &'a List<T>,\n}\n\nimpl<'a, T> Iterator for Iter<'a, T>\nwhere\n T: Clone + PartialEq + std::fmt::Debug + 'a,\n{\n type Item = &'a T;\n fn next(&mut self) -> Option<&'a T> {\n match self.list {\n List::Nil => None,\n List::Cons(ref v, ref rest) => {\n self.list = rest;\n Some(v)\n }\n }\n }\n}\n\nimpl<T> List<T>\nwhere\n T: Clone + PartialEq + std::fmt::Debug,\n{\n pub fn iter(&self) -> Iter<'_, T> {\n Iter{ list: self }\n }\n}\n\nimpl<A> FromIterator<A> for List<A>\nwhere\n A: Clone + PartialEq + std::fmt::Debug,\n{\n fn from_iter<T>(vals: T) -> List<A>\n where\n T: IntoIterator<Item = A>,\n {\n let mut head = List::Nil;\n let mut current = &mut head;\n for v in vals {\n *current = List::Cons(v, Box::new(List::Nil));\n current = match current {\n List::Cons(_, ref mut next) => next,\n _ => unreachable!(),\n };\n }\n head\n }\n}\n\npub fn map<T,U,F:Fn(&T)->U>(f:F,mut l:&List<T>) -> List<U>\nwhere\n T: Clone + PartialEq + std::fmt::Debug,\n U: Clone + PartialEq + std::fmt::Debug,\n{\n l.iter().map(f).collect()\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20064859/" ]
74,502,866
<p>I am trying to create association between active record objects with custom name.</p> <p>For example, I have a <code>User</code> table and <code>Post</code> class, and <code>Post</code> class has <code>writer_id</code> and <code>reader_id</code>. I want to create association for both <code>writer_id</code> and <code>reader_id</code> so that I can just call <code>post.writer</code> to get the <code>User</code> object. I have tried multiple options (one of them: <a href="https://stackoverflow.com/questions/25047920/rails-belongs-to-with-custom-column-name">Rails belongs_to with custom column name</a>), but it did not solve the problem. Anyone knows how to unblock this issue?</p>
[ { "answer_id": 74503369, "author": "rodrigo", "author_id": 865874, "author_profile": "https://Stackoverflow.com/users/865874", "pm_score": 3, "selected": true, "text": "pub fn map<T, U, F: Fn(&T) -> U>(f: F, l: &List<T>) -> List<U> {\n match l {\n List::Nil => List::Nil,\n List::Cons(h, s) => List::Cons(f(h), Box::new(map(f, s)))\n }\n}\n" }, { "answer_id": 74503682, "author": "cafce25", "author_id": 442760, "author_profile": "https://Stackoverflow.com/users/442760", "pm_score": 1, "selected": false, "text": "#[derive(Clone,PartialEq,Debug)]\npub enum List<T: Clone + PartialEq + std::fmt::Debug> {\n Nil,\n Cons(T,Box<List<T>>)\n}\n\npub fn map<T,U,F:Fn(&T)->U>(f:F,mut l:&List<T>) -> List<U>\nwhere\n T: Clone + PartialEq + std::fmt::Debug,\n U: Clone + PartialEq + std::fmt::Debug,\n{\n let mut my_list = List::Nil;\n let mut current = &mut my_list;\n while let List::Cons(ref v, ref next) = l {\n *current = List::Cons(f(v), Box::new(List::Nil));\n current = match current {\n List::Cons(_, ref mut next) => next,\n _ => unreachable!(),\n };\n l = next;\n }\n my_list\n}\n Iterator FromIterator pub struct Iter<'a, T>\nwhere\n T: Clone + PartialEq + std::fmt::Debug + 'a,\n{\n list: &'a List<T>,\n}\n\nimpl<'a, T> Iterator for Iter<'a, T>\nwhere\n T: Clone + PartialEq + std::fmt::Debug + 'a,\n{\n type Item = &'a T;\n fn next(&mut self) -> Option<&'a T> {\n match self.list {\n List::Nil => None,\n List::Cons(ref v, ref rest) => {\n self.list = rest;\n Some(v)\n }\n }\n }\n}\n\nimpl<T> List<T>\nwhere\n T: Clone + PartialEq + std::fmt::Debug,\n{\n pub fn iter(&self) -> Iter<'_, T> {\n Iter{ list: self }\n }\n}\n\nimpl<A> FromIterator<A> for List<A>\nwhere\n A: Clone + PartialEq + std::fmt::Debug,\n{\n fn from_iter<T>(vals: T) -> List<A>\n where\n T: IntoIterator<Item = A>,\n {\n let mut head = List::Nil;\n let mut current = &mut head;\n for v in vals {\n *current = List::Cons(v, Box::new(List::Nil));\n current = match current {\n List::Cons(_, ref mut next) => next,\n _ => unreachable!(),\n };\n }\n head\n }\n}\n\npub fn map<T,U,F:Fn(&T)->U>(f:F,mut l:&List<T>) -> List<U>\nwhere\n T: Clone + PartialEq + std::fmt::Debug,\n U: Clone + PartialEq + std::fmt::Debug,\n{\n l.iter().map(f).collect()\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14428378/" ]
74,502,901
<p>I am fetching all the info from backend and maping it as object, I want to show this like grouping as exact like 2nd image while fetching data I am getting objects with there permissions and there displayName (Read all,Read,Creat,Update) and group(Admin Agent etc) I want to show admin agent name only once which is showing multiple times.</p> <p>here is backend data which are fetching from backend:</p> <pre class="lang-js prettyprint-override"><code>[ { id: 54, name: &quot;agent_read_all&quot;, description: null, displayName: &quot;Read all&quot;, group: &quot;Admin - Agent&quot;, }, { id: 55, name: &quot;agent_read&quot;, description: &quot;Fetch single record&quot;, displayName: &quot;Read&quot;, }, { id: 56, name: &quot;agent_create&quot;, description: null, displayName: &quot;Create&quot;, group: &quot;Admin - Agent&quot;, }, { id: 57, name: &quot;agent_update&quot;, description: null, displayName: &quot;Update&quot;, group: &quot;Admin - Agent&quot;, }, { id: 62, name: &quot;candidate_upload_batch_read_all&quot;, description: null, displayName: &quot;Read all&quot;, }, ]; </code></pre> <p><a href="https://i.stack.imgur.com/dz0aX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dz0aX.png" alt="enter image description here" /></a></p> <p>2nd image <a href="https://i.stack.imgur.com/CesWg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CesWg.png" alt="enter image description here" /></a></p> <p>here is the code :</p> <pre class="lang-js prettyprint-override"><code>&lt;b&gt;Permissions Section&lt;/b&gt;; { Object.keys(permissions).map((item, index) =&gt; ( &lt;&gt; &lt;List style={{ display: &quot;flex&quot; }}&gt; &lt;p&gt;{permissions[item].group}&lt;/p&gt; &lt;FormGroup&gt; &lt;FormControlLabel control={ &lt;Checkbox checked={uroleData.permissions[index] ? true : false} value={roleData.permissionId} onChange={(e) =&gt; { if (e.target.checked) { checkedp.push(permissions[item].id); setRoleData({ ...roleData, permissionId: checkedp }); } else { roleData.permissionId.splice( checkedp.indexOf(e.target.value), 1 ); } // console.log(roleData); }} /&gt; } label={permissions[item].displayName} /&gt; &lt;/FormGroup&gt; &lt;/List&gt; &lt;/&gt; )); } </code></pre>
[ { "answer_id": 74503369, "author": "rodrigo", "author_id": 865874, "author_profile": "https://Stackoverflow.com/users/865874", "pm_score": 3, "selected": true, "text": "pub fn map<T, U, F: Fn(&T) -> U>(f: F, l: &List<T>) -> List<U> {\n match l {\n List::Nil => List::Nil,\n List::Cons(h, s) => List::Cons(f(h), Box::new(map(f, s)))\n }\n}\n" }, { "answer_id": 74503682, "author": "cafce25", "author_id": 442760, "author_profile": "https://Stackoverflow.com/users/442760", "pm_score": 1, "selected": false, "text": "#[derive(Clone,PartialEq,Debug)]\npub enum List<T: Clone + PartialEq + std::fmt::Debug> {\n Nil,\n Cons(T,Box<List<T>>)\n}\n\npub fn map<T,U,F:Fn(&T)->U>(f:F,mut l:&List<T>) -> List<U>\nwhere\n T: Clone + PartialEq + std::fmt::Debug,\n U: Clone + PartialEq + std::fmt::Debug,\n{\n let mut my_list = List::Nil;\n let mut current = &mut my_list;\n while let List::Cons(ref v, ref next) = l {\n *current = List::Cons(f(v), Box::new(List::Nil));\n current = match current {\n List::Cons(_, ref mut next) => next,\n _ => unreachable!(),\n };\n l = next;\n }\n my_list\n}\n Iterator FromIterator pub struct Iter<'a, T>\nwhere\n T: Clone + PartialEq + std::fmt::Debug + 'a,\n{\n list: &'a List<T>,\n}\n\nimpl<'a, T> Iterator for Iter<'a, T>\nwhere\n T: Clone + PartialEq + std::fmt::Debug + 'a,\n{\n type Item = &'a T;\n fn next(&mut self) -> Option<&'a T> {\n match self.list {\n List::Nil => None,\n List::Cons(ref v, ref rest) => {\n self.list = rest;\n Some(v)\n }\n }\n }\n}\n\nimpl<T> List<T>\nwhere\n T: Clone + PartialEq + std::fmt::Debug,\n{\n pub fn iter(&self) -> Iter<'_, T> {\n Iter{ list: self }\n }\n}\n\nimpl<A> FromIterator<A> for List<A>\nwhere\n A: Clone + PartialEq + std::fmt::Debug,\n{\n fn from_iter<T>(vals: T) -> List<A>\n where\n T: IntoIterator<Item = A>,\n {\n let mut head = List::Nil;\n let mut current = &mut head;\n for v in vals {\n *current = List::Cons(v, Box::new(List::Nil));\n current = match current {\n List::Cons(_, ref mut next) => next,\n _ => unreachable!(),\n };\n }\n head\n }\n}\n\npub fn map<T,U,F:Fn(&T)->U>(f:F,mut l:&List<T>) -> List<U>\nwhere\n T: Clone + PartialEq + std::fmt::Debug,\n U: Clone + PartialEq + std::fmt::Debug,\n{\n l.iter().map(f).collect()\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19982657/" ]
74,502,929
<p>I have a dataset looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Car</th> <th>Make</th> <th>Model</th> <th>Engine</th> </tr> </thead> <tbody> <tr> <td>Toyota Rav 4 8cyl6L</td> <td>Toyota</td> <td></td> <td>8cyl6L</td> </tr> <tr> <td>Mitsubishi Eclipse 2.1T</td> <td>Mitsubishi</td> <td></td> <td>2.1T</td> </tr> <tr> <td>Monster Gravedigger 25Lsc</td> <td>Monster</td> <td></td> <td>25Lsc</td> </tr> </tbody> </table> </div> <p>The data was clearly concatenated from Make + Model + Engine at some point but the car Model was not provided to me.</p> <p>I've been trying to use Pandas to say that if we take Car, replace instances of Make with a nothing, replace instances of Engine with nothing, then trim the spaces around the result, we will have Model.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Car</th> <th>Make</th> <th>Model</th> <th>Engine</th> </tr> </thead> <tbody> <tr> <td>Toyota Rav 4 8cyl6L</td> <td>Toyota</td> <td>Rav 4</td> <td>8cyl6L</td> </tr> <tr> <td>Mitsubishi Eclipse 2.1T</td> <td>Mitsubishi</td> <td>Eclipse</td> <td>2.1T</td> </tr> <tr> <td>Monster Gravedigger 25Lsc</td> <td>Monster</td> <td>Gravedigger</td> <td>25Lsc</td> </tr> </tbody> </table> </div> <p>There's something I'm doing wrong when I'm trying to reference another column in this manner.</p> <pre><code>df['Model'] = df['Car'].str.replace(df['Make'],'') </code></pre> <p>gives me an error of &quot;unhashable type: 'Series'&quot;. I'm guessing I'm accidentally inputting the entire 'Make' column.</p> <p>At every row I want to make a different substitution using data from other columns in that row. How would I accomplish this?</p>
[ { "answer_id": 74502960, "author": "Bushmaster", "author_id": 15415267, "author_profile": "https://Stackoverflow.com/users/15415267", "pm_score": 3, "selected": true, "text": "df['Model']=df.apply(lambda x: x['Car'].replace(x['Make'],\"\").replace(x['Engine'],\"\"),axis=1)\nprint(df)\n'''\n Car Make Model Engine\n0 Toyota Rav 4 8cyl6L Toyota Rav 4 8cyl6L\n1 Mitsubishi Eclipse 2.1T Mitsubishi Eclipse 2.1T\n2 Monster Gravedigger 25Lsc Monster Gravedigger 25Lsc\n'''\n" }, { "answer_id": 74503111, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": 1, "selected": false, "text": "regex re.sub import re\n\ndf['Model'] = [re.sub(f'{b}|{c}', '', a) for a,b,c in zip(df['Car'], df['Make'], df[\"Engine\"])]\n print(df)\n\n Car Make Model Engine\n0 Toyota Rav 4 8cyl6L Toyota Rav 4 8cyl6L\n1 Mitsubishi Eclipse 2.1T Mitsubishi Eclipse 2.1T\n2 Monster Gravedigger 25Lsc Monster Gravedigger 25Lsc\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4796998/" ]
74,502,933
<p>I have a problem about writing a java stream by filtering multiple condition, grouping by month of the date and calculating the sum of person.</p> <p>I store the values as <code>Map&lt;String(pId),List&lt;Person&gt;&gt;</code></p> <p>Here is my Person class shown below</p> <pre><code>public class Person{ private String id; private String name; private String surname; private Statement event; // JOIN , EXIT private Object value; private LocalDate eventDate; } </code></pre> <p>Here is the list</p> <pre><code>ID,Info,Date (All values are stored in Person object defined in the List) per1, JOIN, 10-01-2022 per2, JOIN, 10-01-2022 per3, EXIT, 10-01-2022 per3 EXIT, 10-02-2022 per4, JOIN, 10-03-2022 </code></pre> <p>What I want to do is to get this result.</p> <pre><code>Month Info Total Number 1 JOIN 2 1 EXIT 1 2 EXIT 1 3 JOIN 1 </code></pre> <p>Here is my dto shown below.</p> <pre><code>public class DTO { private int month; private State info; // State -&gt; enum private int totalEmployees; } </code></pre> <p>Here is my GroupDto shown below.</p> <pre><code>public class GroupDto { private int month; private State info; } </code></pre> <p>Here is the code snippet but I cannot complete it.</p> <pre><code>List&lt;DTO &gt; result = persons .values().stream() .flatMap(List::stream) .filter(person -&gt; person .getInfo() == Value.ONBOARD || person .getInfo() == Value.EXIT) .collect(Collectors.groupingBy( p -&gt; new GroupDto(p.getEventDate().getMonthValue(), p.getEvent()), Collectors.counting() )) .entrySet().stream() .map(e -&gt; new DTO(p.getKey().get, p.getKey(), (int) (long) e.getValue())) // -&gt; ERROR Line .sorted(Comparator.comparing(MonthWiseDto::getMonth)) .toList(); </code></pre> <p>How can I do that?</p>
[ { "answer_id": 74503300, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 3, "selected": true, "text": "record class public record MonthState(int mont, State info) {}\n groupingBy() counting() Person Map<String, List<Person>> personListById = // initializing the map\n\nList<DTO> result = personListById.values().stream()\n .flatMap(List::stream)\n .filter(per -> per.getInfo() == State.EXIT || per.getInfo() == State.JOIN)\n .collect(Collectors.groupingBy(\n p -> new MonthState(p.getEventDate().getMonthValue(), p.getInfo()),\n Collectors.counting()\n ))\n .entrySet().stream()\n .map(e -> new DTO(e.getKey().mont(), e.getKey().info(), (int) (long) e.getValue()))\n .sorted(Comparator.comparing(DTO::getMonth))\n .toList();\n" }, { "answer_id": 74503391, "author": "oleg.cherednik", "author_id": 3461397, "author_profile": "https://Stackoverflow.com/users/3461397", "pm_score": -1, "selected": false, "text": "public class Main {\n\n public static void main(String... args) {\n List<Person> persons = List.of(\n new Person(\"per1\", Statement.JOIN, LocalDate.of(2022, 1, 10)),\n new Person(\"per2\", Statement.JOIN, LocalDate.of(2022, 1, 10)),\n new Person(\"per3\", Statement.EXIT, LocalDate.of(2022, 1, 10)),\n new Person(\"per3\", Statement.EXIT, LocalDate.of(2022, 2, 10)),\n new Person(\"per4\", Statement.JOIN, LocalDate.of(2022, 3, 10)));\n\n List<Dto> groupResults = calculateGroupResults(persons);\n groupResults.forEach(System.out::println);\n }\n\n public static List<Dto> calculateGroupResults(List<Person> persons) {\n Map<GroupKey, Long> map = persons.stream()\n .filter(person -> person.getEvent() == Statement.EXIT || person.getEvent() == Statement.JOIN)\n .collect(Collectors.groupingBy(\n person -> new GroupKey(person.getEventDate().getMonthValue(), person.getEvent()),\n Collectors.counting()));\n\n return map.entrySet().stream()\n .map(entry -> new Dto(entry.getKey().getMonth(), entry.getKey().getInfo(), entry.getValue()))\n .sorted(Dto.SORT_BY_MONTH_INFO)\n .collect(Collectors.toList());\n }\n\n enum Statement {\n JOIN,\n EXIT\n }\n\n @Getter\n @RequiredArgsConstructor\n public static final class Person {\n\n private final String id;\n private final Statement event;\n private final LocalDate eventDate;\n\n }\n\n @Getter\n @EqualsAndHashCode\n @RequiredArgsConstructor\n public static final class GroupKey {\n\n private final int month;\n private final Statement info;\n\n }\n\n @Getter\n @RequiredArgsConstructor\n public static final class Dto {\n\n public static final Comparator<Dto> SORT_BY_MONTH_INFO =\n Comparator.comparing(Dto::getMonth)\n .thenComparingInt(one -> one.getInfo().ordinal());\n\n private final int month;\n private final Statement info;\n private final long totalEmployees;\n\n @Override\n public String toString() {\n return month + \"-\" + info + '-' + totalEmployees;\n }\n }\n\n}\n 1-JOIN-2\n1-EXIT-1\n2-EXIT-1\n3-JOIN-1\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5719229/" ]
74,502,951
<p>I have a form in my django website where the user requests coins and the information is sent to the admin for me to process. I want to automatically get the user who filled the form without them doing it themselves.</p> <p>Here's the model.py file:</p> <pre><code>class Requestpayment (models.Model): username= models.ForeignKey(User, on_delete= models.CASCADE, null=True) useremail= models.CharField(max_length=100) accountmail= models.CharField(max_length=100) accountphonenumber=models.CharField(max_length=15) coinsrequested=models.ForeignKey(Requestamount, on_delete= models.SET_NULL, null=True) created= models.DateTimeField(auto_now_add=True) def __str__(self): return self.accountmail </code></pre> <p>the forms.py:</p> <pre><code>class Requestpaymentform (ModelForm): class Meta: model = Requestpayment fields = '__all__' </code></pre> <p>and the views.py:</p> <pre><code>@login_required(login_url='login') def redeemcoins (request): form = Requestpaymentform if request.method =='POST': form = Requestpaymentform(request.POST) if form.is_valid(): form = form.save(commit=False) username = request.user form.save() return redirect ('home') </code></pre> <p>I am pretty sure something is wrong but i don't know what it is (I'm very new at django) anyway the form always shows all the users in the website for the current user to pick who they are.</p> <p><a href="https://i.stack.imgur.com/NfXQM.png" rel="nofollow noreferrer">redeem coins page</a></p> <p>I also tried excluding that part of the form but it didn't work it just shows up empty in the admin.</p> <p>thank you.</p>
[ { "answer_id": 74503300, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 3, "selected": true, "text": "record class public record MonthState(int mont, State info) {}\n groupingBy() counting() Person Map<String, List<Person>> personListById = // initializing the map\n\nList<DTO> result = personListById.values().stream()\n .flatMap(List::stream)\n .filter(per -> per.getInfo() == State.EXIT || per.getInfo() == State.JOIN)\n .collect(Collectors.groupingBy(\n p -> new MonthState(p.getEventDate().getMonthValue(), p.getInfo()),\n Collectors.counting()\n ))\n .entrySet().stream()\n .map(e -> new DTO(e.getKey().mont(), e.getKey().info(), (int) (long) e.getValue()))\n .sorted(Comparator.comparing(DTO::getMonth))\n .toList();\n" }, { "answer_id": 74503391, "author": "oleg.cherednik", "author_id": 3461397, "author_profile": "https://Stackoverflow.com/users/3461397", "pm_score": -1, "selected": false, "text": "public class Main {\n\n public static void main(String... args) {\n List<Person> persons = List.of(\n new Person(\"per1\", Statement.JOIN, LocalDate.of(2022, 1, 10)),\n new Person(\"per2\", Statement.JOIN, LocalDate.of(2022, 1, 10)),\n new Person(\"per3\", Statement.EXIT, LocalDate.of(2022, 1, 10)),\n new Person(\"per3\", Statement.EXIT, LocalDate.of(2022, 2, 10)),\n new Person(\"per4\", Statement.JOIN, LocalDate.of(2022, 3, 10)));\n\n List<Dto> groupResults = calculateGroupResults(persons);\n groupResults.forEach(System.out::println);\n }\n\n public static List<Dto> calculateGroupResults(List<Person> persons) {\n Map<GroupKey, Long> map = persons.stream()\n .filter(person -> person.getEvent() == Statement.EXIT || person.getEvent() == Statement.JOIN)\n .collect(Collectors.groupingBy(\n person -> new GroupKey(person.getEventDate().getMonthValue(), person.getEvent()),\n Collectors.counting()));\n\n return map.entrySet().stream()\n .map(entry -> new Dto(entry.getKey().getMonth(), entry.getKey().getInfo(), entry.getValue()))\n .sorted(Dto.SORT_BY_MONTH_INFO)\n .collect(Collectors.toList());\n }\n\n enum Statement {\n JOIN,\n EXIT\n }\n\n @Getter\n @RequiredArgsConstructor\n public static final class Person {\n\n private final String id;\n private final Statement event;\n private final LocalDate eventDate;\n\n }\n\n @Getter\n @EqualsAndHashCode\n @RequiredArgsConstructor\n public static final class GroupKey {\n\n private final int month;\n private final Statement info;\n\n }\n\n @Getter\n @RequiredArgsConstructor\n public static final class Dto {\n\n public static final Comparator<Dto> SORT_BY_MONTH_INFO =\n Comparator.comparing(Dto::getMonth)\n .thenComparingInt(one -> one.getInfo().ordinal());\n\n private final int month;\n private final Statement info;\n private final long totalEmployees;\n\n @Override\n public String toString() {\n return month + \"-\" + info + '-' + totalEmployees;\n }\n }\n\n}\n 1-JOIN-2\n1-EXIT-1\n2-EXIT-1\n3-JOIN-1\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20317259/" ]
74,502,959
<p>What is the difference between:</p> <pre><code>guard let json_data = Data(contentsOf: path) else {return nil} </code></pre> <p>and</p> <pre><code>let json_data = try? Data(contentsOf: path) </code></pre> <p>I dont want to use optional while loading the data into the variable. I want other ways to try it. Thanks in advance.</p>
[ { "answer_id": 74503819, "author": "Rob", "author_id": 1271826, "author_profile": "https://Stackoverflow.com/users/1271826", "pm_score": 3, "selected": false, "text": "guard try? func foo() -> Bar? {\n guard let jsonData = try? Data(contentsOf: path) else { return nil }\n\n // if you get here, `jsonData` is not `Optional`\n\n …\n}\n nil if func foo() -> Bar? {\n let jsonData = try? Data(contentsOf: path)\n\n // jsonData is `Optional` in this example\n\n if let jsonData {\n …\n } else {\n return nil\n }\n}\n guard try try? func foo() throws -> Bar {\n let jsonData = try Data(contentsOf: path)\n\n // `jsonData` is not `Optional`\n\n …\n}\n do catch try! func foo() -> Bar {\n let jsonData = try! Data(contentsOf: path)\n\n // `jsonData` is not `Optional`\n\n …\n}\n Data(contentsOf:) Data(contentsOf:) catch try?" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20550011/" ]
74,503,028
<p>I'm looking for a way to compile print strings out of my binary if a specific macro-based condition is met.</p> <p>here, <code>_dLvl</code> can be conditionally set equal or lower than the maximum allowed level.</p> <pre class="lang-cpp prettyprint-override"><code> enum DEBUG_LEVELS : int { DEBUG_NONE, DEBUG_ERRORS, DEBUG_WARN, DEBUG_INFO, DEBUG_VERBOSE }; #define MAX_LEVEL DEBUG_WARN int _dLvl = DEBUG_ERRORS; template &lt;typename... Args&gt; void E(const char * _f, Args... args){ if (_dLvl &gt;= DEBUG_ERRORS){ printf(_f, args...); } } template &lt;typename... Args&gt; void W(const char * _f, Args... args){ if (_dLvl &gt;= DEBUG_WARN){ printf(_f, args...); } } template &lt;typename... Args&gt; void I(const char * _f, Args... args){ if (_dLvl &gt;= DEBUG_INFO){ printf(_f, args...); } } template &lt;typename... Args&gt; void V(const char * _f, Args... args){ if (_dLvl &gt;= DEBUG_VERBOSE){ printf(_f, args...); } } int main(){ E(&quot;This will print\n&quot;); W(&quot;This might be printed based on _dLvl, existence of this string is ok.\n&quot;); I(&quot;This wont print ever, the existence of this string is memory waste\n&quot;); V(&quot;Same as I\n&quot;); } </code></pre> <p>What adds to the challenge that I've multiple instances of a logger class, where each instance would have a different MAX level, see <a href="https://stackoverflow.com/questions/73600818/indentation-level-management-in-c-logger-class">this question</a> for a more clear example of multi-instances.</p> <p>Here's a solution for my situation (but an ugly and unmanageable onewherein it requires a special macro per instance to be used differently within the source code):</p> <pre class="lang-cpp prettyprint-override"><code>#if (WIFI_LOG_MAX_LEVEL &gt;= 1) #define w_log_E(f_, ...) logger.E((f_), ##__VA_ARGS__) #else #define w_log_E(f_, ...) #endif #if (WIFI_LOG_MAX_LEVEL &gt;= 2) #define w_log_W(f_, ...) logger.W((f_), ##__VA_ARGS__) #else #define w_log_W(f_, ...) #endif #if (WIFI_LOG_MAX_LEVEL &gt;= 3) #define w_log_I(f_, ...) logger.I((f_), ##__VA_ARGS__) #else #define w_log_I(f_, ...) #endif #if (WIFI_LOG_MAX_LEVEL &gt;= 4) #define w_log_V(f_, ...) logger.V((f_), ##__VA_ARGS__) #else #define w_log_V(f_, ...) #endif </code></pre> <p>Is there any trick to solve it?</p>
[ { "answer_id": 74504307, "author": "Nikos Athanasiou", "author_id": 2567683, "author_profile": "https://Stackoverflow.com/users/2567683", "pm_score": 1, "selected": false, "text": "constexpr if // Sorry just a habit to order severity the other way around\nenum DEBUG_LEVELS : int\n{\n DEBUG_VERBOSE = 0,\n DEBUG_INFO = 1,\n DEBUG_WARN = 2,\n DEBUG_ERRORS = 3,\n DEBUG_NONE = 4\n};\n\nconstexpr DEBUG_LEVELS kLevel = DEBUG_LEVELS::DEBUG_WARN;\n// ^^^^^^^^^^^^^^^^^^^^^^^^^^ Log level\n\ntemplate <class... Args>\nvoid warning([[maybe_unused]] const char *msg, Args&&... args)\n{\n if constexpr (kLevel <= DEBUG_WARN) {\n printf(msg, std::forward<Args>(args)...);\n }\n}\n\ntemplate <class... Args>\nvoid info([[maybe_unused]] const char *msg, Args&&... args)\n{\n if constexpr (kLevel <= DEBUG_INFO) {\n printf(msg, std::forward<Args>(args)...);\n }\n}\n\nint main()\n{\n warning(\"Ruuuun %i\", 2);\n info(\"Fuuuun %i\", 2);\n}\n \"Fuuuuuun\" unsigned __int64 `__local_stdio_printf_options'::`2'::_OptionsStorage DQ 01H DUP (?) ; `__local_stdio_printf_options'::`2'::_OptionsStorage\n`string' DB 'Ruuuun %i', 00H ; `string'\n\nmsg$ = 8\n<args_0>$ = 16\nvoid warning<int>(char const *,int &&) PROC ; warning<int>, COMDAT\n mov edx, DWORD PTR [rdx]\n jmp printf\nvoid warning<int>(char const *,int &&) ENDP ; warning<int>\n\nmsg$ = 8\n<args_0>$ = 16\nvoid info<int>(char const *,int &&) PROC ; info<int>, COMDAT\n ret 0\nvoid info<int>(char const *,int &&) ENDP ; info<int>\n\nmain PROC ; COMDAT\n$LN6:\n sub rsp, 40 ; 00000028H\n mov edx, 2\n lea rcx, OFFSET FLAT:`string'\n call printf\n xor eax, eax\n add rsp, 40 ; 00000028H\n ret 0\nmain ENDP\n" }, { "answer_id": 74640899, "author": "Hamza Hajeir", "author_id": 9168874, "author_profile": "https://Stackoverflow.com/users/9168874", "pm_score": 1, "selected": true, "text": "DEBUG_LEVELS MAX_LEVEL constexpr if #include <utility>\n#include <cstdio>\n\nenum DEBUG_LEVELS : int\n{\n DEBUG_NONE,\n DEBUG_ERRORS,\n DEBUG_WARN,\n DEBUG_INFO,\n DEBUG_VERBOSE\n};\n\ntemplate <int MAX_LEVEL>\nclass Logger {\n DEBUG_LEVELS dLvl;\npublic:\n void set_level(DEBUG_LEVELS level) {\n if (level > MAX_LEVEL)\n dLvl = static_cast<DEBUG_LEVELS>(MAX_LEVEL);\n else\n dLvl = level;\n }\n Logger(DEBUG_LEVELS defaultLvl) {\n if (defaultLvl > MAX_LEVEL)\n dLvl = static_cast<DEBUG_LEVELS>(MAX_LEVEL);\n else\n dLvl = defaultLvl;\n }\n template <class... Args>\n void warning([[maybe_unused]] const char *msg, Args&&... args)\n {\n if constexpr (MAX_LEVEL >= DEBUG_WARN) {\n if (dLvl >= DEBUG_WARN)\n printf(msg, std::forward<Args>(args)...);\n }\n }\n\n template <class... Args>\n void info([[maybe_unused]] const char *msg, Args&&... args)\n {\n if constexpr (MAX_LEVEL >= DEBUG_INFO) {\n if (dLvl >= DEBUG_INFO)\n printf(msg, std::forward<Args>(args)...);\n }\n }\n};\n\nLogger<DEBUG_WARN> logger(DEBUG_WARN);\nLogger<DEBUG_INFO> logger_2(DEBUG_INFO);\nint main()\n{\n logger.warning(\"Ruuuun %i\\n\", 2);\n logger.info(\"Fuuuun %i\\n\", 2);\n logger_2.info(\"Hello\\n\");\n logger_2.set_level(DEBUG_NONE);\n logger_2.info(\"Doesn't print\\n\"); // Dynamically set (But the whole call and related string are optimised by the compiler..)\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9168874/" ]
74,503,039
<p>For example, I have the array</p> <pre><code>int [] array = new int[2]; </code></pre> <p>using code</p> <pre><code>for (int i: array){ System.out.println(i); }; </code></pre> <p>I see the output 0 and 0, it's expected</p> <p>but what if I want to output the multi-array:</p> <pre><code>int [][] array2 = new int[2]\[2]; </code></pre> <pre><code>for (int[] i : array2) { for(int[] j : array2 ){ System.out.println(Arrays.toString(array2)); } System.out.println(Arrays.toString(array2)); }; </code></pre> <p>I have strange output</p> <pre><code>[[I@7d4991ad, [I@28d93b30] [[I@7d4991ad, [I@28d93b30] [[I@7d4991ad, [I@28d93b30] [[I@7d4991ad, [I@28d93b30] [[I@7d4991ad, [I@28d93b30] [[I@7d4991ad, [I@28d93b30] </code></pre> <p>but expected result for me is</p> <pre><code>0 0 0 0 </code></pre>
[ { "answer_id": 74503079, "author": "Timo", "author_id": 12828626, "author_profile": "https://Stackoverflow.com/users/12828626", "pm_score": 2, "selected": false, "text": "array2 for (int i = 0; i < array.length; i++) {\n for(int j = 0; i < array.length; j++){\n System.out.println(array[i][j]);\n }\n};\n" }, { "answer_id": 74503080, "author": "Mahesh Biradar", "author_id": 4991722, "author_profile": "https://Stackoverflow.com/users/4991722", "pm_score": 2, "selected": false, "text": "for (int[] row : array2) {\n System.out.println(Arrays.toString(row));\n }\n [0, 0]\n[0, 0]\n" }, { "answer_id": 74524070, "author": "Ole V.V.", "author_id": 5772882, "author_profile": "https://Stackoverflow.com/users/5772882", "pm_score": 2, "selected": false, "text": "int[][] array2 = new int[2][2];\nfor (int[] i : array2) {\n for (int j : i) {\n System.out.printf(\"%-2d\", j);\n }\n System.out.println();\n}\n 0 0 \n0 0 \n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14221265/" ]
74,503,041
<p>I have a task that need to be scheduled on aws lambda function. I wrote a SAM template as below and I see it works when deploying on aws environment (my function get triggered intervally).</p> <p>But we want to do testing on dev environment first before deploying. I use <code>sam local start-api [OPTIONS]</code> to deploy our functions to dev environment. But the problem is that, every functions configured as rest API work, but the schedule task not. I'm not sure is it possible on local/dev environment or not. If not, please suggest a solution (is <a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-local-generate-event.html" rel="nofollow noreferrer">it</a> possible?). Thank you</p> <p>This is template:</p> <pre class="lang-yaml prettyprint-override"><code>aRestApi: ... ... sendMonthlyReport: Type: AWS::Serverless::Function Properties: Handler: src.monthlyReport Runtime: nodejs16.x Events: ScheduledEvent: Type: Schedule Properties: Schedule: &quot;cron(* * * * *)&quot; </code></pre>
[ { "answer_id": 74503100, "author": "Carlos Jafet Neto", "author_id": 6111165, "author_profile": "https://Stackoverflow.com/users/6111165", "pm_score": -1, "selected": false, "text": "var cron = require('node-cron');\n\ncron.schedule('* * * * *', () => {\n console.log('running a task every minute');\n});\n" }, { "answer_id": 74503216, "author": "Adhin Neupane", "author_id": 18153348, "author_profile": "https://Stackoverflow.com/users/18153348", "pm_score": 0, "selected": false, "text": "FROM public.ecr.aws/lambda/python:3.8\n\nRUN yum -y install tar gzip zlib freetype-devel \\\n gcc \\\n ghostscript \\\n lcms2-devel \\\n libffi-devel \\\n libimagequant-devel \\\n .\n enter code here\n enter code here\n and some more dependencies .... \n && yum clean all\n\n\nCOPY requirements.txt ./\n\n\nRUN python3.8 -m pip install -r requirements.txt\n# Replace Pillow with Pillow-SIMD to take advantage of AVX2\nRUN pip uninstall -y pillow && CC=\"cc -mavx2\" pip install -U --force-reinstall pillow-simd\n\nCOPY <handler>.py ./<handler>.py\n\n# Set the CMD to your handler\nENTRYPOINT [ \"python3.8\",\"app5.py\" ]\n # !/bin/bash\nexport AWS_PROFILE=<your aws profile>\nexport AWS_REGION=<aws region>\n\naws lambda invoke --function-name <function name> \\\n--cli-binary-format raw-in-base64-out \\\n--log-type Tail \\\n--payload <your json payload > \\\n<output filename>\n" }, { "answer_id": 74515246, "author": "Đặng Hữu Lộc", "author_id": 14512647, "author_profile": "https://Stackoverflow.com/users/14512647", "pm_score": 0, "selected": false, "text": "localstack" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14512647/" ]
74,503,060
<p>The dataset i have taken is having columns country,coal_<em>production</em>_change<em>pct,gasprodchangepct,year.There are null values in coal</em> prod change pct and gas prod change pct and i want to replace the null values with average of coal prod change pct non null values and gas prod change pct non null values.the dataframe is as looks like below img.</p> <pre><code>[{&quot;metadata&quot;:{&quot;trusted&quot;:true},&quot;cell_type&quot;:&quot;code&quot;,&quot;source&quot;:&quot;sample_df.loc[490:500,['country','coal_prod_change_pct','year','gas_prod_change_pct']]&quot;,&quot;execution_count&quot;:79,&quot;outputs&quot;:[{&quot;output_type&quot;:&quot;execute_result&quot;,&quot;execution_count&quot;:79,&quot;data&quot;:{&quot;text/plain&quot;:&quot; country coal_prod_change_pct year gas_prod_change_pct\n490 Ukraine 2.737000 2018 1.463000\n491 Ukraine -2.299000 2019 -0.481000\n492 Ukraine -4.111211 2020 1.197368\n493 United Arab Emirates NaN 2001 2.553000\n494 United Arab Emirates NaN 2002 10.239000\n495 United Arab Emirates NaN 2003 3.227000\n496 United Arab Emirates NaN 2004 3.349000\n497 United Arab Emirates NaN 2005 3.240000\n498 United Arab Emirates NaN 2006 2.092000\n499 United Arab Emirates NaN 2007 3.074000\n500 United Arab Emirates NaN 2008 -0.099000&quot;,&quot;text/html&quot;:&quot;\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \ncountrycoal_prod_change_pctyeargas_prod_change_pct490Ukraine2.73700020181.463000491Ukraine-2.2990002019-0.481000492Ukraine-4.11121120201.197368493United Arab EmiratesNaN20012.553000494United Arab EmiratesNaN200210.239000495United Arab EmiratesNaN20033.227000496United Arab EmiratesNaN20043.349000497United Arab EmiratesNaN20053.240000498United Arab EmiratesNaN20062.092000499United Arab EmiratesNaN20073.074000500United Arab EmiratesNaN2008-0.099000\n&quot;},&quot;metadata&quot;:{}}]}] country_grp = sample_df.groupby('country') country_grp\['coal_prod_change_pct'\].fillna(country_grp\['coal_prod_change_pct'\].mean()) country_grp\['coal_prod_change_pct'\].apply(lambda x: x.fillna(x.mean())) </code></pre> <p>but in the second method there is no inplace = true as we apply method</p>
[ { "answer_id": 74503082, "author": "BENY", "author_id": 7964527, "author_profile": "https://Stackoverflow.com/users/7964527", "pm_score": 1, "selected": false, "text": "transform filler = country_grp['coal_prod_change_pct'].transform('mean')\nsample_df['coal_prod_change_pct'].fillna(filler, inplace=True)\n" }, { "answer_id": 74503362, "author": "ANISH SAJI KUMAR", "author_id": 12309235, "author_profile": "https://Stackoverflow.com/users/12309235", "pm_score": 0, "selected": false, "text": "import pandas as pd df = pd.DataFrame({'A':[1,2,3,4,5], 'B':[1,2,3,4,5]}) df['B'].fillna(df['B'].mean(), inplace=True)\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20549925/" ]
74,503,136
<p>I need to create a function called as convert_to_qtr() that converts monthly values in the month value of data frame into quarters. Given below is the month data frame below:-</p> <p><a href="https://i.stack.imgur.com/qiISQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qiISQ.png" alt="month dataframe" /></a></p> <p>In the convert_to_qtr() function, we should use the following if conditions:- • If the month input is Jan-Mar, then the function returns “Q1” • If the month input is Apr-Jun, then the function returns “Q2” • If the month input is Jul-Sep, then the function returns “Q3” • If the month input is Oct-Dec, then the function returns “Q4”</p> <p>Then this function should be applied to Month Dataframe provided above and a new column called as Quarter should be created that contains the quarter of each observations of months(January, Feb) etc it is aligned to .</p> <pre><code>quarter = 0 excl_merged['quarter'] = excl_merged[quarter] excl_merged def convert_to_quarterly(excl_merged): if excl_merged['Month'] == 'January' &amp; excl_merged['Month'] == 'February' &amp; excl_merged['Month'] == 'March': print(excl_merged[quarter] == 'Q1') elif excl_merged['Month'] == 'April' &amp; excl_merged['Month'] == 'May' &amp; excl_merged['Month'] == 'June': print(excl_merged[quarter] == 'Q2') elif excl_merged['Month'] == 'July' &amp; excl_merged['Month'] == 'August' &amp; excl_merged['Month'] == 'September': print(excl_merged[quarter] == 'Q3') else: print(excl_merged[quarter] == 'Q4') convert_to_quarterly(excl_merged) </code></pre> <p>I was not able to run the function properly and hence was getting errors</p>
[ { "answer_id": 74503276, "author": "NameVergessen", "author_id": 11003343, "author_profile": "https://Stackoverflow.com/users/11003343", "pm_score": 0, "selected": false, "text": "def convert_to_quarterly(excl_merged):\n if excl_merged['Month'] in ['January', 'February', \"March\"]:\n excl_merged[quarter] == 'Q1'\n elif excl_merged['Month'] in [\"April\", \"May\", \"June\"]:\n excl_merged[quarter] == 'Q2'\n elif excl_merged['Month'] in ['July', 'August', 'September']:\n excl_merged[quarter] == 'Q3'\n elif excl_merged[\"Month\"] in [\"November\", \"December\", \"December\"]:\n excl_merged[quarter] == 'Q4'\n else:\n print(\"Unkown month name!\")\n\n" }, { "answer_id": 74503323, "author": "Marco_CH", "author_id": 12242625, "author_profile": "https://Stackoverflow.com/users/12242625", "pm_score": 0, "selected": false, "text": "df.Transaction_Timestamp.apply(lambda x: \"Q\" + str(x.quarter))\n import pandas as pd\nimport numpy as np\n\nrng = np.random.default_rng()\ndf = pd.DataFrame({\n \"Transaction_Timestamp\":pd.date_range(\"2022-01-01\", periods=365),\n \"Value\":rng.integers(0, 100, size=365)\n})\n\ndf[\"Qrt\"] = df.Transaction_Timestamp.apply(lambda x: \"Q\" + str(x.quarter))\n\ndf.head()\n\n Transaction_Timestamp Value Qrt\n0 2022-01-01 84 Q1\n1 2022-01-02 43 Q1\n2 2022-01-03 91 Q1\n3 2022-01-04 29 Q1\n4 2022-01-05 88 Q1\n" }, { "answer_id": 74504167, "author": "eracer9", "author_id": 13400112, "author_profile": "https://Stackoverflow.com/users/13400112", "pm_score": 0, "selected": false, "text": "df['Quarter'] = df.Month.apply(lambda month: convert_to_qtr(month))" }, { "answer_id": 74504179, "author": "user3435121", "author_id": 3435121, "author_profile": "https://Stackoverflow.com/users/3435121", "pm_score": 1, "selected": false, "text": "def convert_to_quarter( month):\n months = [ 'January', 'February', 'March', 'April ', 'May', 'June', \\\n 'July', 'August', 'September', 'October', 'November', 'December']\n return months.index[ 'month'] // 3\n" }, { "answer_id": 74505458, "author": "Hugo Contreras", "author_id": 20551724, "author_profile": "https://Stackoverflow.com/users/20551724", "pm_score": 0, "selected": false, "text": "import pandas as pd\n\n# an sorted list of months\nlist_of_months =['Jan','Feb','Mar','Apr','Jun','Jul','Aug','Sep','Oct','Nov','Dec']\n\n# creating a dictionary with the months and quarters\nd = {}\nfor i, month in enumerate(list_of_months):\n d[month] = 'Q' + str(i//3+1)\n\n# example dataframe\ndf = pd.DataFrame(['Jan','Dec','Mar'],columns=['Month'])\n\n# applying map to series\ndf['Month'].map(d)\n Month Quarter\n0 Jan Q1\n1 Dec Q4\n2 Mar Q1\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19831324/" ]
74,503,137
<p>Why does the page reload after sending a POST request to the json-server-auth (local database)? How to solve this problem? Due to the reboot, I don't have time to get the data and record it.</p> <pre><code>&lt;form class=&quot;form&quot;&gt; &lt;input type=&quot;email&quot;&gt; &lt;input type=&quot;password&quot;&gt; &lt;button&gt;Регистрация&lt;/button&gt; &lt;/form&gt; </code></pre> <pre><code>&lt;code lang=&quot;javascript&quot;&gt; const form = document.querySelector('.form') form.addEventListener('submit', async (e) =&gt; { e.preventDefault() let data = { email: e.target[0].value, password: e.target[1].value } let res = await fetch('http://localhost:8080/signup', { method: &quot;POST&quot;, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) let json = await res.json() console.log(json) return false }) </code></pre> <pre><code> I tried the same code in codepen and there is no reboot, but when sending from the browser via Live Server in VS Code, the page is reloaded. </code></pre>
[ { "answer_id": 74503276, "author": "NameVergessen", "author_id": 11003343, "author_profile": "https://Stackoverflow.com/users/11003343", "pm_score": 0, "selected": false, "text": "def convert_to_quarterly(excl_merged):\n if excl_merged['Month'] in ['January', 'February', \"March\"]:\n excl_merged[quarter] == 'Q1'\n elif excl_merged['Month'] in [\"April\", \"May\", \"June\"]:\n excl_merged[quarter] == 'Q2'\n elif excl_merged['Month'] in ['July', 'August', 'September']:\n excl_merged[quarter] == 'Q3'\n elif excl_merged[\"Month\"] in [\"November\", \"December\", \"December\"]:\n excl_merged[quarter] == 'Q4'\n else:\n print(\"Unkown month name!\")\n\n" }, { "answer_id": 74503323, "author": "Marco_CH", "author_id": 12242625, "author_profile": "https://Stackoverflow.com/users/12242625", "pm_score": 0, "selected": false, "text": "df.Transaction_Timestamp.apply(lambda x: \"Q\" + str(x.quarter))\n import pandas as pd\nimport numpy as np\n\nrng = np.random.default_rng()\ndf = pd.DataFrame({\n \"Transaction_Timestamp\":pd.date_range(\"2022-01-01\", periods=365),\n \"Value\":rng.integers(0, 100, size=365)\n})\n\ndf[\"Qrt\"] = df.Transaction_Timestamp.apply(lambda x: \"Q\" + str(x.quarter))\n\ndf.head()\n\n Transaction_Timestamp Value Qrt\n0 2022-01-01 84 Q1\n1 2022-01-02 43 Q1\n2 2022-01-03 91 Q1\n3 2022-01-04 29 Q1\n4 2022-01-05 88 Q1\n" }, { "answer_id": 74504167, "author": "eracer9", "author_id": 13400112, "author_profile": "https://Stackoverflow.com/users/13400112", "pm_score": 0, "selected": false, "text": "df['Quarter'] = df.Month.apply(lambda month: convert_to_qtr(month))" }, { "answer_id": 74504179, "author": "user3435121", "author_id": 3435121, "author_profile": "https://Stackoverflow.com/users/3435121", "pm_score": 1, "selected": false, "text": "def convert_to_quarter( month):\n months = [ 'January', 'February', 'March', 'April ', 'May', 'June', \\\n 'July', 'August', 'September', 'October', 'November', 'December']\n return months.index[ 'month'] // 3\n" }, { "answer_id": 74505458, "author": "Hugo Contreras", "author_id": 20551724, "author_profile": "https://Stackoverflow.com/users/20551724", "pm_score": 0, "selected": false, "text": "import pandas as pd\n\n# an sorted list of months\nlist_of_months =['Jan','Feb','Mar','Apr','Jun','Jul','Aug','Sep','Oct','Nov','Dec']\n\n# creating a dictionary with the months and quarters\nd = {}\nfor i, month in enumerate(list_of_months):\n d[month] = 'Q' + str(i//3+1)\n\n# example dataframe\ndf = pd.DataFrame(['Jan','Dec','Mar'],columns=['Month'])\n\n# applying map to series\ndf['Month'].map(d)\n Month Quarter\n0 Jan Q1\n1 Dec Q4\n2 Mar Q1\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20550130/" ]
74,503,146
<p>Trying to pass an EventHandler to a Blazor component. Error I'm getting: The event AppState.IntegerChanged can only appear on the left hand side of +=</p> <p>Seems like this should work, is it a blazor limitation or am I doing something wrong?</p> <p>Getting compiler error in MixedNumber.razor trying to assign event to ValueChanged.</p> <p>Thanks</p> <p>MixedNumber.razor</p> <pre><code>@inject AppState AppState &lt;CustomInput ValueChanged=@AppState.IntegerChanged&gt; &lt;/CustomInput&gt; &lt;CustomInput ValueChanged=@AppState.NumeratorChanged&gt; &lt;/CustomInput&gt; &lt;CustomInput ValueChanged=@AppState.DenominatorChanged&gt; &lt;/CustomInput&gt; @code { [Parameter] public EventHandler&lt;CustomValidationResult&gt; ValueChanged { get; set; } public void MixedValueChanged() { CustomValidationResult result = new() { Integer = 1, Numerator = 10, Denominator = 100 }; AppState.OnMixedChanged(result); } public class CustomValidationResult { public double Integer { get; set; } public double Numerator { get; set; } public double Denominator { get; set; } } } </code></pre> <p>CustomInput.razor</p> <pre><code>@code { [Parameter] public EventHandler&lt;double&gt;? ValueChanged { get; set; } protected override void OnInitialized() { base.OnInitialized(); ValueChanged += valueChanged; } public void valueChanged(object sender, double newValue) { //do something } } </code></pre> <p>AppState.cs</p> <pre><code>public class AppState { public static event EventHandler&lt;double&gt;? IntegerChanged; public static event EventHandler&lt;double&gt;? NumeratorChanged; public static event EventHandler&lt;double&gt;? DenominatorChanged; public static void OnMixedChanged(MixedNumber.CustomValidationResult result) { IntegerChanged?.Invoke(new object(), result.Integer); NumeratorChanged?.Invoke(new object(), result.Numerator); DenominatorChanged?.Invoke(new object(), result.Denominator); } } </code></pre>
[ { "answer_id": 74512962, "author": "MrC aka Shaun Curtis", "author_id": 13065781, "author_profile": "https://Stackoverflow.com/users/13065781", "pm_score": -1, "selected": false, "text": "[Parameter] public EventHandler<double>? ValueChanged { get; set; }\n Task MethodName(double value)" }, { "answer_id": 74522366, "author": "Henk", "author_id": 60761, "author_profile": "https://Stackoverflow.com/users/60761", "pm_score": 2, "selected": true, "text": "public static event EventHandler<double>? IntegerChanged; event += -= event event [Parameter] event @code {\n [Parameter] \n public double Value { get; set; } // don't use the set in this file\n\n [Parameter] \n public EventCallback<double> ValueChanged { get; set; } // same\n\n ... ValueChanged.InvokeAsync(localValue);\n}\n @inject AppState AppState \n \n<CustomInput @bind-Value=@AppState.Integer> </CustomInput>\n\n// or:\n\n<CustomInput Value=@AppState.Numerator ValueChanged=AppState.NumeratorChanged > </CustomInput>\n\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1068557/" ]
74,503,151
<p>making a function that recieves numbers separated by spaces and adds the first element to the rest, the ouput should be a list of numbers if the first element is a number i'm trying to remove all non numeric elements of list b</p> <p>examples- input: 1 2 3 4 output: [3, 4, 5] (2+1, 3+1, 4+1)</p> <p>input: 1 2 b 4 output: [3, 5] (2+1,b is purged, 4+1)</p> <p>input: a 1 2 3 output: Sucessor invalido</p> <pre><code>linha = input() a = linha.split() b = [x for x in (a[1:]) if type(x)==int] b = [eval(x) for x in b] c = eval(a[0]) d = [] d.append(c) f = d*len(b) def soma(): if type(c)!= int: return print(&quot;Sucessor invalido&quot;) else: return list(map(lambda x, y: x + y, b, f)) g = soma() g </code></pre> <blockquote> <p>&gt; this condition always returns an empty list</p> <pre><code>if type(x)==int </code></pre> </blockquote> <p>sorry if im not clear, i started learning recently</p>
[ { "answer_id": 74503186, "author": "rikyeah", "author_id": 17902018, "author_profile": "https://Stackoverflow.com/users/17902018", "pm_score": 0, "selected": false, "text": "b = [int(x) for x in (a[1:]) if x.isnumeric()] \n split()" }, { "answer_id": 74503218, "author": "scotscotmcc", "author_id": 15804190, "author_profile": "https://Stackoverflow.com/users/15804190", "pm_score": 2, "selected": false, "text": "input '7' isinstance(x,int) type(x)==int try:...except:... linha = input()\na = linha.split()\nb = [] #empty list\nfor x in a[1:]: # confusing thing you are doing here, also... you want to skip the first element?\n try:\n x_int = int(x)\n b.append(x_int)\n except ValueError:\n pass\n...\n" }, { "answer_id": 74503681, "author": "Arifa Chan", "author_id": 19574157, "author_profile": "https://Stackoverflow.com/users/19574157", "pm_score": 0, "selected": false, "text": "string int str.islpha() def soma(linha):\n if linha[0].isalpha():\n return f\"Sucessor invalido\"\n result = []\n for i in range(len(linha) - 1):\n try:\n result.append(int(linha[0]) + int(linha[i+1]))\n except ValueError:\n continue\n return result\n\n\nlinha = input().split()\n\nprint(soma(linha))\n 1 2 3 4\n[3, 4, 5]\n\n1 2 b 4\n[3, 5]\n\na 1 2 3\nSucessor invalido\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20550063/" ]
74,503,152
<pre><code> The goal is: The db will have a handful of &quot;plans&quot; that can be used across multiple customers. Each customer can have only a single plan associated with them at a time. Think of this as your &quot;scription plan&quot;. The vanilla SQL below works to create this enforces that we cannot delete a plan that is associated with at least 1 customer. I have not been able to recreate this simple fKey setup in Sequelize. For berevity just plat of the DDL: CREATE TABLE customers ( id int NOT NULL AUTO_INCREMENT, planId int, PRIMARY KEY (id) ) CREATE TABLE plans ( planId int NOT NULL AUTO_INCREMENT, PRIMARY KEY (planId) ) ADD CONSTRAINT FK_customers_planId FOREIGN KEY (planId) REFERENCES plans (planId); </code></pre> <p>I've read the creating associations and advanced associates sections fo the version 6 reference.<br /> I tried hasOne, belongsTo, belongsToMany, and using the through option etc. I know the through option is for creating a linking table but was just testing to understand how this method works. db is the exported database object. None of these do what the above SQL does.</p> <pre><code> db.Plans.User = db.Plans.belongsTo(db.Customer); db.Customer.Plans = db.Customer.hasOne(db.Plans, { foreignKey: db.Plans.planId }); db.Plans.belongsToMany(db.Customer, { through: 'customerplans' }); db.Customer.hasOne(db.Plans, { through: 'customerplans' }); </code></pre>
[ { "answer_id": 74503186, "author": "rikyeah", "author_id": 17902018, "author_profile": "https://Stackoverflow.com/users/17902018", "pm_score": 0, "selected": false, "text": "b = [int(x) for x in (a[1:]) if x.isnumeric()] \n split()" }, { "answer_id": 74503218, "author": "scotscotmcc", "author_id": 15804190, "author_profile": "https://Stackoverflow.com/users/15804190", "pm_score": 2, "selected": false, "text": "input '7' isinstance(x,int) type(x)==int try:...except:... linha = input()\na = linha.split()\nb = [] #empty list\nfor x in a[1:]: # confusing thing you are doing here, also... you want to skip the first element?\n try:\n x_int = int(x)\n b.append(x_int)\n except ValueError:\n pass\n...\n" }, { "answer_id": 74503681, "author": "Arifa Chan", "author_id": 19574157, "author_profile": "https://Stackoverflow.com/users/19574157", "pm_score": 0, "selected": false, "text": "string int str.islpha() def soma(linha):\n if linha[0].isalpha():\n return f\"Sucessor invalido\"\n result = []\n for i in range(len(linha) - 1):\n try:\n result.append(int(linha[0]) + int(linha[i+1]))\n except ValueError:\n continue\n return result\n\n\nlinha = input().split()\n\nprint(soma(linha))\n 1 2 3 4\n[3, 4, 5]\n\n1 2 b 4\n[3, 5]\n\na 1 2 3\nSucessor invalido\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20550151/" ]
74,503,167
<p>Im working on a game in unity and I followed a dapper dino tutorial for character movement and character camera control. Everything was working with a few minor issues, most of which I solved, but the one issue I couldnt solve, was when I move the camera to face more the 90 degrees left or right, the character just spins out of control, and I spent a long time scrolling through comments and watching the other videos and stuff, but nothing seemed to work. Here is my code:</p> <pre><code>`using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovementController : MonoBehaviour { [SerializeField] private float speed; [SerializeField] private float jumpForce; [SerializeField] private float JumpraycastDistance; private Rigidbody rb; private void Start() { rb = GetComponent&lt;Rigidbody&gt;(); } private void Update() { Jump(); } private void FixedUpdate() { Move(); } private void Move() { float hAxis = Input.GetAxisRaw(&quot;Horizontal&quot;); float vAxis = Input.GetAxisRaw(&quot;Vertical&quot;); Vector3 movement = new Vector3(hAxis, 0, vAxis) * speed * Time.fixedDeltaTime; Vector3 newPosition = rb.position + rb.transform.TransformDirection(movement); rb.MovePosition(newPosition); } private void Jump() { if(Input.GetKeyDown(KeyCode.Space)) { if (IsGrounded()) { rb.AddForce(0, jumpForce, 0, ForceMode.Impulse); } } } private bool IsGrounded() { return Physics.Raycast(transform.position, Vector3.down, JumpraycastDistance); } } </code></pre> <p><a href="https://youtu.be/1rdURdzCaIc" rel="nofollow noreferrer">Video of broken character</a></p> <p>ANY AND ALL HELP GREATLY APPRECIATED</p> <p>I tried a bunch of stuff from the youtube comments of the video I was watching and it didnt solve anything</p> <p>Camera code:</p> <pre><code> [SerializeField] private float lookSensitivity; [SerializeField] private float smoothing; private GameObject player; private Vector2 smoothedVelocity; private Vector2 currentLookingPos; private void Start() { player = transform.parent.gameObject; Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; } private void Update() { RotateCamera(); CheckForShooting(); } private void RotateCamera() { Vector2 inputeValues = new Vector2(Input.GetAxisRaw(&quot;Mouse X&quot;), Input.GetAxisRaw(&quot;Mouse Y&quot;)); inputeValues = Vector2.Scale(inputeValues, new Vector2(lookSensitivity * smoothing, lookSensitivity * smoothing)); smoothedVelocity.x = Mathf.Lerp(smoothedVelocity.x, inputeValues.x, 1f / smoothing); smoothedVelocity.y = Mathf.Lerp(smoothedVelocity.y, inputeValues.y, 1f / smoothing); currentLookingPos += smoothedVelocity; currentLookingPos.y = Mathf.Clamp(currentLookingPos.y, -80f, 80f); transform.localRotation = Quaternion.AngleAxis(-currentLookingPos.y, Vector3.right); player.transform.localRotation = Quaternion.AngleAxis(currentLookingPos.x, player.transform.up); } </code></pre>
[ { "answer_id": 74520682, "author": "user15500238", "author_id": 15500238, "author_profile": "https://Stackoverflow.com/users/15500238", "pm_score": 2, "selected": true, "text": "transform.localRotation = Quaternion.AngleAxis(-currentLookingPos.y, Vector3.right);\nplayer.transform.localRotation = Quaternion.AngleAxis(currentLookingPos.x, player.transform.up);\n player.transform.localRotation = Quaternion.AngleAxis(currentLookingPos.x, Vector3.up);\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15500238/" ]
74,503,195
<p>I want to plot multiple subplots of scatter plots inside a function, after calling the <code>*args</code> parameter to unpack <code>(x,y)</code> input values. However, I keep getting a simple error:</p> <blockquote> <p>ValueError: s must be a scalar, or float array-like with the same size as x and y</p> </blockquote> <p>I cannot seem to solve it even after changing the function into alternative orders of <code>args</code>. Here is my sample code:</p> <pre><code>import pandas as pd import numpy as np from matplotlib.pyplot import plt x = np.array([[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4], [0.3, 0.5, 0.6, 0.2, 0.4, 0.5, 0.6, 0.5, 0.8, 0.9, 0.9, 0.8, 0.2, 0.1, 0.5, 0.6], ['r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b']]) values = pd.DataFrame(x.T, columns=['a', 'b', 'c']) X = values[values['c'] == 'r'].iloc[ : , 0:2 ].values Y = values[values['c'] == 'b'].iloc[ : , 0:2 ].values def test(*args): figs, axs = plt.subplots( 1 , 2 , figsize = ( 8 , 8 ) ) for xy , ax in zip( args , axs.flat ) : print(xy) ax.scatter(*xy) test(X, Y) plt.show() </code></pre>
[ { "answer_id": 74520682, "author": "user15500238", "author_id": 15500238, "author_profile": "https://Stackoverflow.com/users/15500238", "pm_score": 2, "selected": true, "text": "transform.localRotation = Quaternion.AngleAxis(-currentLookingPos.y, Vector3.right);\nplayer.transform.localRotation = Quaternion.AngleAxis(currentLookingPos.x, player.transform.up);\n player.transform.localRotation = Quaternion.AngleAxis(currentLookingPos.x, Vector3.up);\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17124619/" ]
74,503,223
<p>I'm trying to do something very simple but can't figure out how.</p> <p>Say I have this table called &quot;Tasks&quot; where each task has a chosen set of users that should carry it out. The numbers in the Users column refer to the ID column of the &quot;Users&quot; table.</p> <p><strong>Tasks table:</strong></p> <pre><code>+--------------+-------------+--------------+ | Task | Created_On | Users | +--------------+-------------+--------------+ | Task A | 19/11/22 | 1,3,4 | | Task B | 19/11/22 | 1,4,5,6 | | Task C | 19/11/22 | 2,3,6 | +--------------+-------------+--------------+ </code></pre> <p><strong>Users table:</strong></p> <pre><code>+--------------+-------------+ | ID | User | +--------------+-------------+ | 1 | George | | 2 | John | | 3 | Jim | | 4 | James | | 5 | Jill | | 6 | Joe | +--------------+-------------+ </code></pre> <p>How do you create the &quot;Users&quot; column of the Tasks table? There's no &quot;Array&quot; column type in Oracle.</p>
[ { "answer_id": 74503504, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 3, "selected": true, "text": "CREATE TABLE task_users (\n Task CONSTRAINT task_users__task__fk REFERENCES tasks (task),\n User_id CONSTRAINT task_users__user_id__fk REFERENCES users (id),\n CONSTRAINT task_users__task__user_id__pk PRIMARY KEY(task, user_id)\n);\n INSERT INTO task_users (task, user_id)\nSELECT 'Task A', 1 FROM DUAL UNION ALL\nSELECT 'Task A', 3 FROM DUAL UNION ALL\nSELECT 'Task A', 4 FROM DUAL UNION ALL\nSELECT 'Task B', 1 FROM DUAL UNION ALL\nSELECT 'Task B', 4 FROM DUAL UNION ALL\nSELECT 'Task B', 5 FROM DUAL UNION ALL\nSELECT 'Task B', 6 FROM DUAL UNION ALL\nSELECT 'Task C', 2 FROM DUAL UNION ALL\nSELECT 'Task C', 3 FROM DUAL UNION ALL\nSELECT 'Task C', 6 FROM DUAL;\n" }, { "answer_id": 74503514, "author": "Littlefoot", "author_id": 9097906, "author_profile": "https://Stackoverflow.com/users/9097906", "pm_score": 1, "selected": false, "text": "sys.odcinumberlist SQL> create table task (task varchar2(10), created_on date, users sys.odcinumberlist);\n\nTable created.\n\nSQL> insert into task (task, created_on, users)\n 2 values ('Task A', date '2022-11-19', sys.odcinumberlist(1,3,4));\n\n1 row created.\n\nSQL> select * from task;\n\nTASK CREATED_ON USERS\n---------- ---------- ----------------------------------------\nTask A 19.11.2022 ODCINUMBERLIST(1, 3, 4)\n\nSQL>\n SQL> select * from users;\n\n ID USERNAME\n---------- ----------\n 1 George --> this\n 2 John\n 3 Jim --> this\n 4 James --> this\n 5 Jill\n 6 Joe\n\n6 rows selected.\n\nSQL> select t.task, u.username\n 2 from task t join users u on u.id in (select * From table(t.users));\n\nTASK USERNAME\n---------- ----------\nTask A George\nTask A Jim\nTask A James\n\nSQL>\n" }, { "answer_id": 74507388, "author": "d r", "author_id": 19023353, "author_profile": "https://Stackoverflow.com/users/19023353", "pm_score": 0, "selected": false, "text": "SELECT t.TASK, t.CREATED_ON, t.USERS, t.IDS_COUNT, t.IDX \"ID_NO\", t.ID, u.USER_NAME\nFROM ( Select *\n From ( Select TASK, CAST(0 As VarChar2(32)) \"ID\", USERS, CREATED_ON,\n Coalesce(Length(USERS) - Length(Replace(USERS,',',null)), Length(USERS), 0) + 1 \"IDS_COUNT\"\n From tasks\n )\n MODEL\n PARTITION BY (TASK)\n DIMENSION BY (0 \"IDX\")\n MEASURES (USERS, CREATED_ON, IDS_COUNT, ID)\n RULES ITERATE(6) -- declare bigger number than expected number of elements in list\n (\n USERS[ITERATION_NUMBER] = USERS[0], CREATED_ON[ANY] = CREATED_ON[0], IDS_COUNT[ANY] = IDS_COUNT[0],\n ID[ITERATION_NUMBER] = CASE \n WHEN ITERATION_NUMBER BETWEEN 1 And IDS_COUNT[0] \n THEN SubStr(SubStr(',' || USERS[0] || ',', InStr(',' || USERS[0] || ',', ',', 1, ITERATION_NUMBER)+1), 1, InStr(',' || USERS[0] || ',', ',', 1, ITERATION_NUMBER+1) - InStr(',' || USERS[0] || ',', ',', 1, ITERATION_NUMBER) - 1) \n END \n )\n ) t\nINNER JOIN users u ON(u.ID = t.ID) --LEFT JOIN if you want to see possible unmatched IDs - USER_NAME would be Null\nWhere IDX Between 1 And IDS_COUNT\nOrder By TASK, IDX\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13709246/" ]
74,503,250
<p>First time I am working with threads in spring boot webapp and when I do debugging then I see thread names are increasing like Thread-1, Thread-2... for every call method so I thought that the program is not killing the thread but creating new thread for every call.</p> <p>Here is my code:</p> <pre><code>public Advert saveAdvert(Advert advert) { Advert advertToSave = advertRepository.save(advert); new Thread(() -&gt; { try { populateAdvertSearch(advertToSave); } catch (ParseException e) { e.printStackTrace(); } catch (OfficeNotFoundException e) { e.printStackTrace(); } catch (OfficePropertyNotFoundException e) { e.printStackTrace(); } }).start(); return advertToSave; } </code></pre> <p>Here <code>populateAdvertSearch()</code> is a void method. I just want to do that task independently from the main thread because it is very long and I do not want client to wait whole method so another independent thread will do this void method. But as I said I though that the program is not killing threads. How can I kill the thread or Should I kill explicitly (I am not sure maybe it is already killed after execution is done but then why Intellij IDEA debug showing thread names as increasing)</p>
[ { "answer_id": 74503289, "author": "KunalVarpe", "author_id": 3649352, "author_profile": "https://Stackoverflow.com/users/3649352", "pm_score": 3, "selected": true, "text": "run() Thread" }, { "answer_id": 74503904, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 2, "selected": false, "text": "@Async @EnableAsync ThreadPoolTaskExecutor application.properties @Async @Component @Controller @Async\npublic Advert saveAdvert(Advert advert) {\n Advert advertToSave = advertRepository.save(advert);\n\n try {\n populateAdvertSearch(advertToSave);\n } catch (ParseException e) {\n e.printStackTrace();\n } catch (OfficeNotFoundException e) {\n e.printStackTrace();\n } catch (OfficePropertyNotFoundException e) {\n e.printStackTrace();\n }\n \n return advertToSave;\n}\n" }, { "answer_id": 74504113, "author": "muhammed ozbilici", "author_id": 2165146, "author_profile": "https://Stackoverflow.com/users/2165146", "pm_score": 0, "selected": false, "text": "ExecutorService if (executor.awaitTermination(5, TimeUnit.SECONDS)) {\n // continue\n} else {\n // force shutdown\n executor.shutdownNow();\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1261764/" ]
74,503,255
<p>Lets say I have very simple <code>xaml</code></p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt; &lt;ContentPage xmlns=&quot;http://schemas.microsoft.com/dotnet/2021/maui&quot; xmlns:x=&quot;http://schemas.microsoft.com/winfx/2009/xaml&quot; xmlns:drawable=&quot;clr-namespace:eden.Pages&quot; x:Class=&quot;eden.Pages.Modeler&quot;&gt; &lt;ContentPage.Resources&gt; &lt;drawable:GraphicsDrawable x:Key=&quot;drawable&quot; /&gt; &lt;/ContentPage.Resources&gt; &lt;VerticalStackLayout&gt; &lt;GraphicsView x:Name=&quot;modelerArea&quot; Drawable=&quot;{StaticResource drawable}&quot;&gt; &lt;FlyoutBase.ContextFlyout&gt; &lt;MenuFlyout&gt; &lt;MenuFlyoutItem Text=&quot;Add rectangle&quot; Clicked=&quot;AddRectangle&quot;&gt; &lt;!-- HERE I WANT TO ADD RECTANGLE ON CLICK --&gt; &lt;/MenuFlyoutItem&gt; &lt;/MenuFlyout&gt; &lt;/FlyoutBase.ContextFlyout&gt; &lt;/GraphicsView&gt; &lt;/VerticalStackLayout&gt; &lt;/ContentPage&gt; </code></pre> <p>And then very simple <code>xaml.cs</code></p> <pre><code>public partial class Modeler : ContentPage { public Modeler() { InitializeComponent(); } private void AddRectangle(object sender, EventArgs e) { // for example // var mySpecialRectangle = new specialRectangle(); // canvas.Add(mySpecialRectangle); } } public class GraphicsDrawable : IDrawable { public void Draw(ICanvas canvas, RectF dirtyRect) { canvas.StrokeColor = Colors.Red; canvas.StrokeSize = 6; canvas.DrawLine(10, 10, 90, 100); } } } </code></pre> <p>How can I add that object to canvas/graphicsview?</p>
[ { "answer_id": 74503289, "author": "KunalVarpe", "author_id": 3649352, "author_profile": "https://Stackoverflow.com/users/3649352", "pm_score": 3, "selected": true, "text": "run() Thread" }, { "answer_id": 74503904, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 2, "selected": false, "text": "@Async @EnableAsync ThreadPoolTaskExecutor application.properties @Async @Component @Controller @Async\npublic Advert saveAdvert(Advert advert) {\n Advert advertToSave = advertRepository.save(advert);\n\n try {\n populateAdvertSearch(advertToSave);\n } catch (ParseException e) {\n e.printStackTrace();\n } catch (OfficeNotFoundException e) {\n e.printStackTrace();\n } catch (OfficePropertyNotFoundException e) {\n e.printStackTrace();\n }\n \n return advertToSave;\n}\n" }, { "answer_id": 74504113, "author": "muhammed ozbilici", "author_id": 2165146, "author_profile": "https://Stackoverflow.com/users/2165146", "pm_score": 0, "selected": false, "text": "ExecutorService if (executor.awaitTermination(5, TimeUnit.SECONDS)) {\n // continue\n} else {\n // force shutdown\n executor.shutdownNow();\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16344063/" ]
74,503,260
<p>I have the following data structure:</p> <pre><code>{ &quot;nodes&quot;: [ { &quot;frontmatter&quot;: { &quot;excerpt&quot;: null, &quot;featured&quot;: true, &quot;title&quot;: &quot;A Post with Content&quot; }, &quot;fields&quot;: { &quot;slug&quot;: &quot;posts/a-post-of-type-page&quot;, } }, { &quot;frontmatter&quot;: { &quot;excerpt&quot;: null, &quot;featured&quot;: null, &quot;title&quot;: &quot;A post of type post&quot; }, &quot;fields&quot;: { &quot;slug&quot;: &quot;posts/a-post-of-type-post&quot;, } }, { &quot;frontmatter&quot;: { &quot;excerpt&quot;: null, &quot;featured&quot;: null, &quot;title&quot;: &quot;Another Post (or type post)&quot; }, &quot;fields&quot;: { &quot;slug&quot;: &quot;posts/another-post-or-type-post&quot;, } }, { &quot;frontmatter&quot;: { &quot;excerpt&quot;: &quot;This is the excerpt of a post&quot;, &quot;featured&quot;: null, &quot;title&quot;: &quot;With Content&quot; }, &quot;fields&quot;: { &quot;slug&quot;: &quot;posts/with-content&quot;, } }, ] } </code></pre> <p>I know that I can use <code>myObject.nodes.map(x =&gt; x.frontmatter)</code> to bring the <code>frontmatter</code> up a level and removing the nesting. But, I now need to change each node into the following structure within the resulting array:</p> <pre><code>{ &quot;nodes&quot;: [ { &quot;excerpt&quot;: null, &quot;featured&quot;: true, &quot;title&quot;: &quot;A Post with Content&quot; &quot;slug&quot;: &quot;posts/a-post-of-type-page&quot;, }, ... ] } </code></pre> <p>So, I need to remove the nesting for both the <code>frontmatter</code> and <code>fields</code>.</p> <p>Thanks</p>
[ { "answer_id": 74503289, "author": "KunalVarpe", "author_id": 3649352, "author_profile": "https://Stackoverflow.com/users/3649352", "pm_score": 3, "selected": true, "text": "run() Thread" }, { "answer_id": 74503904, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 2, "selected": false, "text": "@Async @EnableAsync ThreadPoolTaskExecutor application.properties @Async @Component @Controller @Async\npublic Advert saveAdvert(Advert advert) {\n Advert advertToSave = advertRepository.save(advert);\n\n try {\n populateAdvertSearch(advertToSave);\n } catch (ParseException e) {\n e.printStackTrace();\n } catch (OfficeNotFoundException e) {\n e.printStackTrace();\n } catch (OfficePropertyNotFoundException e) {\n e.printStackTrace();\n }\n \n return advertToSave;\n}\n" }, { "answer_id": 74504113, "author": "muhammed ozbilici", "author_id": 2165146, "author_profile": "https://Stackoverflow.com/users/2165146", "pm_score": 0, "selected": false, "text": "ExecutorService if (executor.awaitTermination(5, TimeUnit.SECONDS)) {\n // continue\n} else {\n // force shutdown\n executor.shutdownNow();\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1972982/" ]
74,503,272
<p>I'm new in programming, actually I use it for Machine Learning. I have installed python and anaconda (I don't know if that is right, or I have to install only anaconda?). And I can see in start menu: (Anaconda powershell, Jupyter, Spyder, Anaconda navigator, Anaconda prompt). So my question is: Do I still have to use vscode as IDE, or one of the listed programs that come with anaconda? If the answer is the second choice, I will ask, which one of them?</p> <p>Thanks.</p> <p>I'm using python just because I have a project in ML, So I must to set the necessary things for ML, like libraries, dataset, and algorithms. Then I have to learn how to use them. Any help will be very apprecheated.</p>
[ { "answer_id": 74503289, "author": "KunalVarpe", "author_id": 3649352, "author_profile": "https://Stackoverflow.com/users/3649352", "pm_score": 3, "selected": true, "text": "run() Thread" }, { "answer_id": 74503904, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 2, "selected": false, "text": "@Async @EnableAsync ThreadPoolTaskExecutor application.properties @Async @Component @Controller @Async\npublic Advert saveAdvert(Advert advert) {\n Advert advertToSave = advertRepository.save(advert);\n\n try {\n populateAdvertSearch(advertToSave);\n } catch (ParseException e) {\n e.printStackTrace();\n } catch (OfficeNotFoundException e) {\n e.printStackTrace();\n } catch (OfficePropertyNotFoundException e) {\n e.printStackTrace();\n }\n \n return advertToSave;\n}\n" }, { "answer_id": 74504113, "author": "muhammed ozbilici", "author_id": 2165146, "author_profile": "https://Stackoverflow.com/users/2165146", "pm_score": 0, "selected": false, "text": "ExecutorService if (executor.awaitTermination(5, TimeUnit.SECONDS)) {\n // continue\n} else {\n // force shutdown\n executor.shutdownNow();\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11541847/" ]
74,503,273
<p>I'm new in bash scripting and I'm trying to create a bash script which can create multiple file with content (around 10000 lines [no matters what text]) but with user input. I made a script which create files (see below) but how can I fill each file with 10000 lines? Thank you in advance!</p> <pre><code>#!/bin/bash echo How many files do you want to create? read numberOfFiles echo echo Please enter the files name with should start: read nameForFiles echo for i in $(seq 1 $numberOfFiles) do touch $nameForFiles-$i.txt done </code></pre>
[ { "answer_id": 74503289, "author": "KunalVarpe", "author_id": 3649352, "author_profile": "https://Stackoverflow.com/users/3649352", "pm_score": 3, "selected": true, "text": "run() Thread" }, { "answer_id": 74503904, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 2, "selected": false, "text": "@Async @EnableAsync ThreadPoolTaskExecutor application.properties @Async @Component @Controller @Async\npublic Advert saveAdvert(Advert advert) {\n Advert advertToSave = advertRepository.save(advert);\n\n try {\n populateAdvertSearch(advertToSave);\n } catch (ParseException e) {\n e.printStackTrace();\n } catch (OfficeNotFoundException e) {\n e.printStackTrace();\n } catch (OfficePropertyNotFoundException e) {\n e.printStackTrace();\n }\n \n return advertToSave;\n}\n" }, { "answer_id": 74504113, "author": "muhammed ozbilici", "author_id": 2165146, "author_profile": "https://Stackoverflow.com/users/2165146", "pm_score": 0, "selected": false, "text": "ExecutorService if (executor.awaitTermination(5, TimeUnit.SECONDS)) {\n // continue\n} else {\n // force shutdown\n executor.shutdownNow();\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20550025/" ]
74,503,284
<p><a href="https://i.stack.imgur.com/xhVia.png" rel="nofollow noreferrer">MY DATA IN EXCEL</a></p> <p><a href="https://i.stack.imgur.com/ZysU1.png" rel="nofollow noreferrer">MY CODE</a></p> <p>Hello Everyone!</p> <p>I am brand new to python and have some simple data I want to separate and graph in a bar chart.</p> <p>I have a data set on the cars currently being driven in California. They are separated by Year, Fuel type, Zip Code, Make, and 'Light/Heavy'.</p> <p>I want to tell python to count the number of Gasoline cars, the number of diesel cars, the number of battery electric cars, etc.</p> <p>How could i separate this data, and then graph it on a bar chart? I am assuming it is quite easy, but I have been learning python myself for maybe a week.</p> <p>I attached the data set, as well as some code that I have so far. It is returning 'TRUE' when I tried to make subseries of the data as 'gas', 'diesel', etc. I am assuming python is just telling me &quot;yes, it says gasoline there&quot;. I now just hope to gather all the &quot;Gasoline&quot;s in the 'Fuel' column, and add them all up by the number in the 'Vehicle' column.</p> <p>Any help would be very much appreciated!!!</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('~/Desktop/PYTHON/californiavehicles.csv') print(df.head()) print(df.describe()) X = df['Fuel'] y = df['Vehicles'] gas = df[(df['Fuel']=='Gasoline','Flex-Fuel')] diesel = df[(df['Fuel']=='Diesel and Diesel Hybrid')] hybrid = df[(df['Fuel']=='Hybrid Gasoline', 'Plug-in Hybrid')] electric = df[(df['Fuel']=='Battery Electric')] </code></pre> <p>I tried to create a subseries of the data. I haven't tried to include the numbers in 'vehicles' yet because I don't know how.</p>
[ { "answer_id": 74503289, "author": "KunalVarpe", "author_id": 3649352, "author_profile": "https://Stackoverflow.com/users/3649352", "pm_score": 3, "selected": true, "text": "run() Thread" }, { "answer_id": 74503904, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 2, "selected": false, "text": "@Async @EnableAsync ThreadPoolTaskExecutor application.properties @Async @Component @Controller @Async\npublic Advert saveAdvert(Advert advert) {\n Advert advertToSave = advertRepository.save(advert);\n\n try {\n populateAdvertSearch(advertToSave);\n } catch (ParseException e) {\n e.printStackTrace();\n } catch (OfficeNotFoundException e) {\n e.printStackTrace();\n } catch (OfficePropertyNotFoundException e) {\n e.printStackTrace();\n }\n \n return advertToSave;\n}\n" }, { "answer_id": 74504113, "author": "muhammed ozbilici", "author_id": 2165146, "author_profile": "https://Stackoverflow.com/users/2165146", "pm_score": 0, "selected": false, "text": "ExecutorService if (executor.awaitTermination(5, TimeUnit.SECONDS)) {\n // continue\n} else {\n // force shutdown\n executor.shutdownNow();\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20534582/" ]
74,503,297
<p>We have many AWS Glue jobs and we are only updating the job code, which are scripts stored in S3. The problem is CloudFormation couldn't tell when and when not to update our Glue jobs because all CloudFormation template parameters remain the same after script changes, even the script location is pointing to the same S3 object.</p>
[ { "answer_id": 74505877, "author": "omuthu", "author_id": 4840338, "author_profile": "https://Stackoverflow.com/users/4840338", "pm_score": 0, "selected": false, "text": "{\n \"Name\" : String,\n \"PythonVersion\" : String,\n \"ScriptLocation\" : String\n}\n" }, { "answer_id": 74510226, "author": "Robert Kossendey", "author_id": 12638118, "author_profile": "https://Stackoverflow.com/users/12638118", "pm_score": 2, "selected": true, "text": "package" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3307887/" ]
74,503,306
<p>I am making a discord bot in Discord4J, with a command handler that returns the valid command:</p> <pre class="lang-java prettyprint-override"><code>return Mono.just(event.getCommandName()) .filter(commandRegistry::has) .map(commandRegistry::get) .flatMap(discordCommand -&gt; { try { return discordCommand.executeCommand(event); } catch (Exception e) { logger.error(e.getMessage()); return event.reply(&quot;Error occurred!&quot;).then(); } }) .then(); </code></pre> <p>(discordCommand.executeCommand returns Mono)</p> <p>If I try to handle the error with <code>doOnError</code> the error propagates and crashes the program. My question is, how do I make this reactive without the error propagating. Surrounding the entire block with try/catch doesn't work either.</p>
[ { "answer_id": 74503572, "author": "Azn9", "author_id": 10836980, "author_profile": "https://Stackoverflow.com/users/10836980", "pm_score": 1, "selected": false, "text": ".onErrorResume(throwable -> {\n //Do whatever you want with the error\n return Mono.empty();\n})\n" }, { "answer_id": 74503635, "author": "NovaFox161", "author_id": 9570150, "author_profile": "https://Stackoverflow.com/users/9570150", "pm_score": 3, "selected": true, "text": ".doOnX return Mono.just(event.getCommandName())\n .filter(commandRegistry::has)\n .map(commandRegistry::get)\n .flatMap(discordCommand ->> discordCommand.executeCommand(event);})\n .doOnError(e -> logger.error(\"an error happened\", e))\n .onErrorResume(e -> event.reply(\"Sorry, an error occurred\"));\n .doOnError onErrorResume" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15935845/" ]
74,503,314
<p>I can't figure out how to keep the keys and values on a dictionary when I try to merge two dictionaries. I keep getting <code>ArgumentException</code> due to duplicate of key. When the key match I would just like to add the value by <code>=+ kvp.value;</code></p> <p>I have a list of Dictionaries where the</p> <p>1st Dictionary = <code>kvp = &quot;jump&quot;, 2;</code></p> <p>2ndDictionary = <code>kvp = &quot;jump&quot;, 4;</code></p> <p>I like to merge them and get something like: Dictionary = <code>kvp = &quot;jump&quot;, 6;</code></p> <p>That I can later add to my list of Dictionaries</p> <p>I've tried to run something I found in StackOverflow thread.</p> <pre><code>foreach (var dict in listOfDict) { dict.SelectMany(d =&gt; d) .ToLookup(pair =&gt; pair.Key, pair =&gt; pair.Value) .ToDictionary(group =&gt; group.Key, group =&gt; group.First()); } </code></pre> <p>But I keep getting.</p> <blockquote> <p>cannot be inferred from the usage. Try specifying the type arguments explicitly.</p> </blockquote> <p>I want to avoid getting all keys and all values on separate lists that I later loop through to add key and value on a new dictionary.</p>
[ { "answer_id": 74504127, "author": "Avrohom Yisroel", "author_id": 706346, "author_profile": "https://Stackoverflow.com/users/706346", "pm_score": 0, "selected": false, "text": "=+ kvp.value" }, { "answer_id": 74504220, "author": "Gabriel Stancu", "author_id": 8187400, "author_profile": "https://Stackoverflow.com/users/8187400", "pm_score": 2, "selected": false, "text": " var dictionaries = new List<Dictionary<string, int>>(); // this is the list of dictionaries you want to merge\n var unifiedDictionary = new Dictionary<string, int>(); // this is the dictionary where you merge and add the values\n\n foreach (var kvp in dictionaries.SelectMany(dictionary => dictionary))\n {\n if (unifiedDictionary.ContainsKey(kvp.Key))\n {\n unifiedDictionary[kvp.Key] += kvp.Value;\n }\n else\n {\n unifiedDictionary.Add(kvp.Key, kvp.Value);\n }\n }\n for-loop var dictionaries = new List<Dictionary<string, int>>(); // this is the list of dictionaries you want to merge\n var unifiedDictionary = new Dictionary<string, int>(); // this is the dictionary where you merge and add the values\n\n foreach (var dictionary in dictionaries)\n {\n foreach (var kvp in dictionary)\n {\n if (unifiedDictionary.ContainsKey(kvp.Key))\n {\n unifiedDictionary[kvp.Key] += kvp.Value;\n }\n else\n {\n unifiedDictionary.Add(kvp.Key, kvp.Value);\n }\n }\n }\n" }, { "answer_id": 74504664, "author": "Adam Silenko", "author_id": 6089766, "author_profile": "https://Stackoverflow.com/users/6089766", "pm_score": 3, "selected": true, "text": "public static class ExtListOfDict {\n public static Dictionary<TKey, double> SumValue1<TKey>(this List<Dictionary<TKey, double>> list) \n => list?.SelectMany(i => i).ToLookup(i => i.Key, i => i.Value).ToDictionary(i => i.Key, i => i.Sum());\n\n}\n public static Dictionary<TKey, double> SumValue2<TKey>(this List<Dictionary<TKey, double>> list) {\n if(list?.Count > 0) {\n var dir = new Dictionary<TKey, double>(list[0]);\n for(var i = 1; i < list.Count; i++) \n foreach (var kv in list[i])\n if (dir.TryGetValue(kv.Key, out double sum))\n dir[kv.Key] = sum + kv.Value; \n else \n dir.Add(kv.Key, kv.Value); \n return dir;\n } else\n return null;\n}\n" }, { "answer_id": 74506562, "author": "Theodor Zoulias", "author_id": 11178549, "author_profile": "https://Stackoverflow.com/users/11178549", "pm_score": 2, "selected": false, "text": "CollectionsMarshal.GetValueRefOrAddDefault INumber<TSelf> public static Dictionary<TKey, TValue> ToSumDictionary<TKey, TValue>(\n this IEnumerable<Dictionary<TKey, TValue>> dictionaries)\n where TValue : struct, INumber<TValue>\n{\n ArgumentNullException.ThrowIfNull(dictionaries);\n Dictionary<TKey, TValue> result = null;\n foreach (var dictionary in dictionaries)\n {\n if (result is null)\n {\n result = new(dictionary, dictionary.Comparer);\n continue;\n }\n if (!ReferenceEquals(dictionary.Comparer, result.Comparer))\n throw new InvalidOperationException(\"Incompatible comparers.\");\n foreach (var (key, value) in dictionary)\n {\n ref TValue refValue = ref CollectionsMarshal\n .GetValueRefOrAddDefault(result, key, out bool exists);\n refValue = exists ? refValue + value : value;\n }\n }\n result ??= new();\n return result;\n}\n KeyValuePair<TKey, TValue>" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20529565/" ]
74,503,315
<p>I'm having a problem in where i want to count how many medals in total a country has won from both the individual and team competitions does not give me the disered outcome. i have managed so far tocome up with this.</p> <pre><code>select distinct C.Cname as Country, count(i.medal) as Medals_Won from individual_results as i, Country as C, participant as p where (i.Olympian = p.OlympicID and C.Cname = p.country) union select distinct C.Cname, count(r.medal) as medals_Won from team_results as r, Country as C, participant as p, team as t where (r.team = t.TeamID and t.Member1 = p.OlympicID and C.Cname = p.Country) group by C.Cname order by medals_won desc </code></pre> <p><a href="https://i.stack.imgur.com/mN2R6.png" rel="nofollow noreferrer">enter image description here</a></p> <p>but i get this result.</p> <p>even tho if i run the two separate pieces of code i ge the wanted restuls that is <a href="https://i.stack.imgur.com/Tv5Wp.png" rel="nofollow noreferrer">enter image description here</a></p>
[ { "answer_id": 74504127, "author": "Avrohom Yisroel", "author_id": 706346, "author_profile": "https://Stackoverflow.com/users/706346", "pm_score": 0, "selected": false, "text": "=+ kvp.value" }, { "answer_id": 74504220, "author": "Gabriel Stancu", "author_id": 8187400, "author_profile": "https://Stackoverflow.com/users/8187400", "pm_score": 2, "selected": false, "text": " var dictionaries = new List<Dictionary<string, int>>(); // this is the list of dictionaries you want to merge\n var unifiedDictionary = new Dictionary<string, int>(); // this is the dictionary where you merge and add the values\n\n foreach (var kvp in dictionaries.SelectMany(dictionary => dictionary))\n {\n if (unifiedDictionary.ContainsKey(kvp.Key))\n {\n unifiedDictionary[kvp.Key] += kvp.Value;\n }\n else\n {\n unifiedDictionary.Add(kvp.Key, kvp.Value);\n }\n }\n for-loop var dictionaries = new List<Dictionary<string, int>>(); // this is the list of dictionaries you want to merge\n var unifiedDictionary = new Dictionary<string, int>(); // this is the dictionary where you merge and add the values\n\n foreach (var dictionary in dictionaries)\n {\n foreach (var kvp in dictionary)\n {\n if (unifiedDictionary.ContainsKey(kvp.Key))\n {\n unifiedDictionary[kvp.Key] += kvp.Value;\n }\n else\n {\n unifiedDictionary.Add(kvp.Key, kvp.Value);\n }\n }\n }\n" }, { "answer_id": 74504664, "author": "Adam Silenko", "author_id": 6089766, "author_profile": "https://Stackoverflow.com/users/6089766", "pm_score": 3, "selected": true, "text": "public static class ExtListOfDict {\n public static Dictionary<TKey, double> SumValue1<TKey>(this List<Dictionary<TKey, double>> list) \n => list?.SelectMany(i => i).ToLookup(i => i.Key, i => i.Value).ToDictionary(i => i.Key, i => i.Sum());\n\n}\n public static Dictionary<TKey, double> SumValue2<TKey>(this List<Dictionary<TKey, double>> list) {\n if(list?.Count > 0) {\n var dir = new Dictionary<TKey, double>(list[0]);\n for(var i = 1; i < list.Count; i++) \n foreach (var kv in list[i])\n if (dir.TryGetValue(kv.Key, out double sum))\n dir[kv.Key] = sum + kv.Value; \n else \n dir.Add(kv.Key, kv.Value); \n return dir;\n } else\n return null;\n}\n" }, { "answer_id": 74506562, "author": "Theodor Zoulias", "author_id": 11178549, "author_profile": "https://Stackoverflow.com/users/11178549", "pm_score": 2, "selected": false, "text": "CollectionsMarshal.GetValueRefOrAddDefault INumber<TSelf> public static Dictionary<TKey, TValue> ToSumDictionary<TKey, TValue>(\n this IEnumerable<Dictionary<TKey, TValue>> dictionaries)\n where TValue : struct, INumber<TValue>\n{\n ArgumentNullException.ThrowIfNull(dictionaries);\n Dictionary<TKey, TValue> result = null;\n foreach (var dictionary in dictionaries)\n {\n if (result is null)\n {\n result = new(dictionary, dictionary.Comparer);\n continue;\n }\n if (!ReferenceEquals(dictionary.Comparer, result.Comparer))\n throw new InvalidOperationException(\"Incompatible comparers.\");\n foreach (var (key, value) in dictionary)\n {\n ref TValue refValue = ref CollectionsMarshal\n .GetValueRefOrAddDefault(result, key, out bool exists);\n refValue = exists ? refValue + value : value;\n }\n }\n result ??= new();\n return result;\n}\n KeyValuePair<TKey, TValue>" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20550247/" ]
74,503,325
<p>Currently i have below Array of Objects</p> <pre><code>const dataClass = [ { &quot;id&quot;: 101, &quot;class&quot;: [ { &quot;type&quot;: &quot;A&quot;, &quot;value&quot;: &quot;A-class&quot; }, { &quot;type&quot;: &quot;B&quot;, &quot;value&quot;: &quot;B-class&quot; }, { &quot;type&quot;: &quot;C&quot;, &quot;value&quot;: &quot;C-class&quot; } ], &quot;rank&quot;: 1 }, { &quot;id&quot;: 102, &quot;class&quot;: [ { &quot;type&quot;: &quot;D&quot;, &quot;value&quot;: &quot;D-class&quot; }, { &quot;type&quot;: &quot;E&quot;, &quot;value&quot;: &quot;E-class&quot; }, { &quot;type&quot;: &quot;F&quot;, &quot;value&quot;: &quot;F-class&quot; } ], &quot;rank&quot;: 2 }, { &quot;id&quot;: 103, &quot;class&quot;: [ { &quot;type&quot;: &quot;G&quot;, &quot;value&quot;: &quot;G-class&quot; }, { &quot;type&quot;: &quot;H&quot;, &quot;value&quot;: &quot;H-class&quot; }, { &quot;type&quot;: &quot;I&quot;, &quot;value&quot;: &quot;I-class&quot; } ], &quot;rank&quot;: 3 } ]; </code></pre> <p>i need to get dataClass object using all value inside the class object, let say i want to get the second object, so i have to search/input &quot;type&quot;: &quot;D&quot;, &quot;type&quot;: &quot;E&quot;, and &quot;type&quot;: &quot;F&quot;.</p> <p>return array object/object i expect:</p> <pre><code> [{ &quot;id&quot;: 102, &quot;class&quot;: [ { &quot;type&quot;: &quot;D&quot;, &quot;value&quot;: &quot;D-class&quot; }, { &quot;type&quot;: &quot;E&quot;, &quot;value&quot;: &quot;E-class&quot; }, { &quot;type&quot;: &quot;F&quot;, &quot;value&quot;: &quot;F-class&quot; } ], &quot;rank&quot;: 2 }] </code></pre> <p>I don't find any solution so far, Thanks for any help.</p>
[ { "answer_id": 74504127, "author": "Avrohom Yisroel", "author_id": 706346, "author_profile": "https://Stackoverflow.com/users/706346", "pm_score": 0, "selected": false, "text": "=+ kvp.value" }, { "answer_id": 74504220, "author": "Gabriel Stancu", "author_id": 8187400, "author_profile": "https://Stackoverflow.com/users/8187400", "pm_score": 2, "selected": false, "text": " var dictionaries = new List<Dictionary<string, int>>(); // this is the list of dictionaries you want to merge\n var unifiedDictionary = new Dictionary<string, int>(); // this is the dictionary where you merge and add the values\n\n foreach (var kvp in dictionaries.SelectMany(dictionary => dictionary))\n {\n if (unifiedDictionary.ContainsKey(kvp.Key))\n {\n unifiedDictionary[kvp.Key] += kvp.Value;\n }\n else\n {\n unifiedDictionary.Add(kvp.Key, kvp.Value);\n }\n }\n for-loop var dictionaries = new List<Dictionary<string, int>>(); // this is the list of dictionaries you want to merge\n var unifiedDictionary = new Dictionary<string, int>(); // this is the dictionary where you merge and add the values\n\n foreach (var dictionary in dictionaries)\n {\n foreach (var kvp in dictionary)\n {\n if (unifiedDictionary.ContainsKey(kvp.Key))\n {\n unifiedDictionary[kvp.Key] += kvp.Value;\n }\n else\n {\n unifiedDictionary.Add(kvp.Key, kvp.Value);\n }\n }\n }\n" }, { "answer_id": 74504664, "author": "Adam Silenko", "author_id": 6089766, "author_profile": "https://Stackoverflow.com/users/6089766", "pm_score": 3, "selected": true, "text": "public static class ExtListOfDict {\n public static Dictionary<TKey, double> SumValue1<TKey>(this List<Dictionary<TKey, double>> list) \n => list?.SelectMany(i => i).ToLookup(i => i.Key, i => i.Value).ToDictionary(i => i.Key, i => i.Sum());\n\n}\n public static Dictionary<TKey, double> SumValue2<TKey>(this List<Dictionary<TKey, double>> list) {\n if(list?.Count > 0) {\n var dir = new Dictionary<TKey, double>(list[0]);\n for(var i = 1; i < list.Count; i++) \n foreach (var kv in list[i])\n if (dir.TryGetValue(kv.Key, out double sum))\n dir[kv.Key] = sum + kv.Value; \n else \n dir.Add(kv.Key, kv.Value); \n return dir;\n } else\n return null;\n}\n" }, { "answer_id": 74506562, "author": "Theodor Zoulias", "author_id": 11178549, "author_profile": "https://Stackoverflow.com/users/11178549", "pm_score": 2, "selected": false, "text": "CollectionsMarshal.GetValueRefOrAddDefault INumber<TSelf> public static Dictionary<TKey, TValue> ToSumDictionary<TKey, TValue>(\n this IEnumerable<Dictionary<TKey, TValue>> dictionaries)\n where TValue : struct, INumber<TValue>\n{\n ArgumentNullException.ThrowIfNull(dictionaries);\n Dictionary<TKey, TValue> result = null;\n foreach (var dictionary in dictionaries)\n {\n if (result is null)\n {\n result = new(dictionary, dictionary.Comparer);\n continue;\n }\n if (!ReferenceEquals(dictionary.Comparer, result.Comparer))\n throw new InvalidOperationException(\"Incompatible comparers.\");\n foreach (var (key, value) in dictionary)\n {\n ref TValue refValue = ref CollectionsMarshal\n .GetValueRefOrAddDefault(result, key, out bool exists);\n refValue = exists ? refValue + value : value;\n }\n }\n result ??= new();\n return result;\n}\n KeyValuePair<TKey, TValue>" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12028187/" ]
74,503,366
<p>I have a variant of exact match that I'm struggling to execute using regex. I would like to match several words (e.g. Apple, Bat, Car) to a string while ignoring order and also being exclusive (i.e. ignoring cases with extra words, or too few words). For example (using the list above), I'd like the following outcomes (<strong>true</strong>/false):</p> <ul> <li><strong>Bat, Car, Apple (True)</strong></li> <li><strong>Car, Bat, Apple (True)</strong></li> <li><strong>Apple, Car, Bat (True)</strong></li> <li>Apple, Car, Bat, Stick (False)</li> <li>Bat, Car (False)</li> <li>Apple (False)</li> </ul> <p>I have tried two things;</p> <p>(1) lookahead assertions</p> <pre><code>^(?=.*Apple)(?=.*Bat)(?=.*Car).* </code></pre> <ul> <li><strong>Bat, Car, Apple (True)</strong></li> <li><strong>Car, Bat, Apple (True)</strong></li> <li><strong>Apple, Car, Bat (True)</strong></li> <li><strong>Apple, Car, Bat, Stick (True)</strong></li> <li>Bat, Car (False)</li> <li>Apple (False)</li> </ul> <p>This almost works, but allows strings with additional words (e.g. the case with &quot;Stick&quot;). What can I add to exclude these cases, assuming &quot;Stick&quot; can be any other word, and there could be multiple additional words.</p> <p>(2) Following <a href="https://stackoverflow.com/questions/43346897/regex-to-match-multiple-words-in-any-order">related Q/A examples on stack overflow</a></p> <pre><code>^(Apple|Bat|Car|[,\s])+$ </code></pre> <ul> <li><strong>Bat, Car, Apple (True)</strong></li> <li><strong>Car, Bat, Apple (True)</strong></li> <li><strong>Apple, Car, Bat (True)</strong></li> <li>Apple, Car, Bat, Stick (False)</li> <li><strong>Bat, Car (True)</strong></li> <li><strong>Apple (True)</strong></li> </ul> <p>Which again almost works, but it incorrectly includes the smaller subsets.</p> <p><strong>Edit:</strong> Note, my list of words to match is just an example, it will be variable <strong>and can be any number of words.</strong></p>
[ { "answer_id": 74503641, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 1, "selected": true, "text": "(?=.*Apple)(?=.*Car)(?=.*Bat)(?!.*(?:,|^)(?:(?!Apple|Bat|Car).)+(?:,|$))^.*$\n (?=.*Apple)(?=.*Car)(?=.*Bat) (?!.*(?:,|^)(?:(?!Apple|Bat|Car).)+(?:,|$)) , ^.*$ \\b Cartography (?=.*\\bApple\\b)(?=.*\\bCar\\b)(?=.*\\bBat\\b)(?!.*(?:,|^)(?:(?!\\b(?:Apple|Bat|Car)\\b).)+(?:,|$))^.*$\n" }, { "answer_id": 74503704, "author": "akash", "author_id": 9839769, "author_profile": "https://Stackoverflow.com/users/9839769", "pm_score": 2, "selected": false, "text": "^(apple|bat|car), (?!\\1)(apple|bat|car), (?!\\1|\\2)(apple|bat|car)$" }, { "answer_id": 74503842, "author": "bobble bubble", "author_id": 5527985, "author_profile": "https://Stackoverflow.com/users/5527985", "pm_score": 2, "selected": false, "text": "^(?=.*?\\bApple\\b)(?=.*?\\bBat\\b)(?=.*?\\bCar\\b)\\w+(?:, ?\\w+){2}$\n \\b \\w , ? ^(?:\\b(?:, ?)?(Apple|Bat|Car)\\b(?!.*?\\b\\1\\b)){3}$\n \\b" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20548760/" ]
74,503,397
<p>I'm working on a card game and for the most part its working out. It shuffles, and divides the deck into two (1st 26cards to player 1, the other half to player 2). My problem is when a player wins they are supposed to gain a card from the other player's hand. (player1Cards.push(player2Cards[card])) - This works, but because of the setup of the game every time you click play the entire game resets.</p> <p>Is there a way I can make it so once the card gets pushed it stays within the winners array without refreshing every time?</p> <p>I tried putting my shuffle for loop in a function, but then it wont read any of my variables.</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 start() { //Deck with ranks: let starterDeck = [ {"img": '2_of_clubs.png',"rank": 1},{"img": '3_of_clubs.png',"rank": 2},{"img": '4_of_clubs.png',"rank": 3},{"img": '5_of_clubs.png',"rank": 4},{"img": '6_of_clubs.png',"rank": 5},{"img": '7_of_clubs.png',"rank": 6},{"img": '8_of_clubs.png',"rank": 7},{"img": '9_of_clubs.png',"rank": 8},{"img": '10_of_clubs.png',"rank": 9},{"img": 'jack_of_clubs.png',"rank": 10},{"img": 'queen_of_clubs.png',"rank": 11},{"img": 'king_of_clubs.png',"rank": 12},{"img": 'ace_of_clubs.png',"rank": 13}, {"img": '2_of_diamonds.png',"rank": 1},{"img": '3_of_diamonds.png',"rank": 2},{"img": '4_of_diamonds.png',"rank": 3},{"img": '5_of_diamonds.png',"rank": 4},{"img": '6_of_diamonds.png',"rank": 5},{"img": '7_of_diamonds.png',"rank": 6},{"img": '8_of_diamonds.png',"rank": 7},{"img": '9_of_diamonds.png',"rank": 8},{"img": '10_of_diamonds.png',"rank": 9},{"img": 'jack_of_diamonds.png',"rank": 10},{"img": 'queen_of_diamonds.png',"rank": 11},{"img": 'king_of_diamonds.png',"rank": 12},{"img": 'ace_of_diamonds.png',"rank": 13}, {"img": '2_of_hearts.png',"rank": 1},{"img": '3_of_hearts.png',"rank": 2},{"img": '4_of_hearts.png',"rank": 3},{"img": '5_of_hearts.png',"rank": 4},{"img": '6_of_hearts.png',"rank": 5},{"img": '7_of_hearts.png',"rank": 6},{"img": '8_of_hearts.png',"rank": 7},{"img": '9_of_hearts.png',"rank": 8},{"img": '10_of_hearts.png',"rank": 9},{"img": 'jack_of_hearts.png',"rank": 10},{"img": 'queen_of_hearts.png',"rank": 11},{"img": 'king_of_hearts.png',"rank": 12},{"img": 'ace_of_hearts.png',"rank": 13}, {"img": '2_of_spades.png',"rank": 1},{"img": '3_of_spades.png',"rank": 2},{"img": '4_of_spades.png',"rank": 3},{"img": '5_of_spades.png',"rank": 4},{"img": '6_of_spades.png',"rank": 5},{"img": '7_of_spades.png',"rank": 6},{"img": '8_of_spades.png',"rank": 7},{"img": '9_of_spades.png',"rank": 8},{"img": '10_of_spades.png',"rank": 9},{"img": 'jack_of_spades.png',"rank": 10},{"img": 'queen_of_spades.png',"rank": 11},{"img": 'king_of_spades.png',"rank": 12},{"img": 'ace_of_spades.png',"rank": 13}, ] //Shuffled Our Deck: for(let i=0;i&lt;52; i++) { // We are taking our tempCard and placing it in the random position (randomIndex) let shuffledCards = starterDeck[i]; let randomIndex = Math.floor(Math.random() * 52); starterDeck[i] = starterDeck[randomIndex] starterDeck[randomIndex] = shuffledCards; } //console.log(starterDeck) //Make it random out of the 26 cards received by players: let card = Math.floor(Math.random() * 26) //Player 1 gets the first 26 cards from the random shuffled deck. let player1Cards = starterDeck.splice(26) //Place the image let selectedCardImg = [player1Cards[card].img] document.getElementById('p1Card').src = "./images/cards/" + selectedCardImg //Player 2 gets the last 26 cards from the random shuffled deck. let player2Cards = starterDeck.splice(-26) //console.log(player2Cards) console.log('PLAYER 1 CARD') console.log(player1Cards[card]) console.log('PLAYER 2 CARD') console.log(player2Cards[card]) //Place the image let selectedCardImg2 = [player2Cards[card].img] document.getElementById('p2Card').src = "./images/cards/" + selectedCardImg2 if (player1Cards[card].rank &lt; player2Cards[card].rank){ //alert("Player 2 Wins") player2Cards.push(player1Cards[card]) console.log(player2Cards) } else if (player1Cards[card].rank &gt; player2Cards[card].rank){ // alert("Player 1 wins") player1Cards.push(player2Cards[card]) console.log(player1Cards) } else { // alert("TIE!") console.log('Tie!'); } } </code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;title&gt;War&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div&gt; Game&lt;/div&gt; &lt;img src="./images/cards/black_joker.png" height="300px" id="p1Card"&gt; &lt;img src="./images/cards/red_joker.png" height="300px" id="p2Card"&gt; &lt;input type="text" readonly id="player1Score"/&gt; &lt;input type="text" readonly id="player2Score"/&gt; &lt;button onclick = "start()"&gt;play me&lt;/button&gt; &lt;script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script src="./js/index.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74503641, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 1, "selected": true, "text": "(?=.*Apple)(?=.*Car)(?=.*Bat)(?!.*(?:,|^)(?:(?!Apple|Bat|Car).)+(?:,|$))^.*$\n (?=.*Apple)(?=.*Car)(?=.*Bat) (?!.*(?:,|^)(?:(?!Apple|Bat|Car).)+(?:,|$)) , ^.*$ \\b Cartography (?=.*\\bApple\\b)(?=.*\\bCar\\b)(?=.*\\bBat\\b)(?!.*(?:,|^)(?:(?!\\b(?:Apple|Bat|Car)\\b).)+(?:,|$))^.*$\n" }, { "answer_id": 74503704, "author": "akash", "author_id": 9839769, "author_profile": "https://Stackoverflow.com/users/9839769", "pm_score": 2, "selected": false, "text": "^(apple|bat|car), (?!\\1)(apple|bat|car), (?!\\1|\\2)(apple|bat|car)$" }, { "answer_id": 74503842, "author": "bobble bubble", "author_id": 5527985, "author_profile": "https://Stackoverflow.com/users/5527985", "pm_score": 2, "selected": false, "text": "^(?=.*?\\bApple\\b)(?=.*?\\bBat\\b)(?=.*?\\bCar\\b)\\w+(?:, ?\\w+){2}$\n \\b \\w , ? ^(?:\\b(?:, ?)?(Apple|Bat|Car)\\b(?!.*?\\b\\1\\b)){3}$\n \\b" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11996252/" ]
74,503,413
<p>Table 1</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Loc_Id</th> <th>Label_Id</th> <th>Active_Date</th> <th>Inactive_Date</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>1001</td> <td>2022/05/13</td> <td>9999/12/31</td> </tr> <tr> <td>2</td> <td>1001</td> <td>2018/05/20</td> <td>2022/05/12</td> </tr> <tr> <td>3</td> <td>1001</td> <td>2012/06/14</td> <td>2018/05/12</td> </tr> </tbody> </table> </div> <p>Table 2</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Label_Id</th> <th>Tab2_Active_Date</th> <th>Tab2_Inactive_Date</th> </tr> </thead> <tbody> <tr> <td>1001</td> <td>2022/05/13</td> <td>9999/12/31</td> </tr> <tr> <td>1001</td> <td>2018/05/22</td> <td>2022/05/12</td> </tr> <tr> <td>1001</td> <td>2012/06/14</td> <td>2018/05/12</td> </tr> </tbody> </table> </div> <p>I want to know which records in Table2 have Tab2_Active Date &gt; Active Date in Table 1 and Tab2_Inactive Date &lt; Inactive Date in Table 1. For example in this the scenario the date Tab2_Active Date 2018/05/22 mentioned in Table 2 is greater than 2018/05/20 mentioned in table 1.</p> <p>So the o/p will be</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Loc_Id</th> <th>Tab2_Active_Date</th> <th>Tab2_Inactive_Date</th> </tr> </thead> <tbody> <tr> <td>2</td> <td>2018/05/22</td> <td>2022/05/12</td> </tr> </tbody> </table> </div> <p>Since I only have only Ids to join as the keys for 2 tables and I need to compare the dates, I cannot take dates to join the tables which results in inaccurate data.</p>
[ { "answer_id": 74503641, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 1, "selected": true, "text": "(?=.*Apple)(?=.*Car)(?=.*Bat)(?!.*(?:,|^)(?:(?!Apple|Bat|Car).)+(?:,|$))^.*$\n (?=.*Apple)(?=.*Car)(?=.*Bat) (?!.*(?:,|^)(?:(?!Apple|Bat|Car).)+(?:,|$)) , ^.*$ \\b Cartography (?=.*\\bApple\\b)(?=.*\\bCar\\b)(?=.*\\bBat\\b)(?!.*(?:,|^)(?:(?!\\b(?:Apple|Bat|Car)\\b).)+(?:,|$))^.*$\n" }, { "answer_id": 74503704, "author": "akash", "author_id": 9839769, "author_profile": "https://Stackoverflow.com/users/9839769", "pm_score": 2, "selected": false, "text": "^(apple|bat|car), (?!\\1)(apple|bat|car), (?!\\1|\\2)(apple|bat|car)$" }, { "answer_id": 74503842, "author": "bobble bubble", "author_id": 5527985, "author_profile": "https://Stackoverflow.com/users/5527985", "pm_score": 2, "selected": false, "text": "^(?=.*?\\bApple\\b)(?=.*?\\bBat\\b)(?=.*?\\bCar\\b)\\w+(?:, ?\\w+){2}$\n \\b \\w , ? ^(?:\\b(?:, ?)?(Apple|Bat|Car)\\b(?!.*?\\b\\1\\b)){3}$\n \\b" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11601256/" ]
74,503,440
<p>I would like to retain the syntax highlighting for code written in code blocks in the Quarto document (.qmd) after rendering a PDF. Please let me know if this is possible.</p> <p><a href="https://i.stack.imgur.com/WnLqQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WnLqQ.png" alt="Code in .qmd file" /></a>\</p> <p><a href="https://i.stack.imgur.com/6Kgx2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6Kgx2.png" alt="Code After Rendering" /></a></p> <p>Colors not retained after rendering</p>
[ { "answer_id": 74503641, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 1, "selected": true, "text": "(?=.*Apple)(?=.*Car)(?=.*Bat)(?!.*(?:,|^)(?:(?!Apple|Bat|Car).)+(?:,|$))^.*$\n (?=.*Apple)(?=.*Car)(?=.*Bat) (?!.*(?:,|^)(?:(?!Apple|Bat|Car).)+(?:,|$)) , ^.*$ \\b Cartography (?=.*\\bApple\\b)(?=.*\\bCar\\b)(?=.*\\bBat\\b)(?!.*(?:,|^)(?:(?!\\b(?:Apple|Bat|Car)\\b).)+(?:,|$))^.*$\n" }, { "answer_id": 74503704, "author": "akash", "author_id": 9839769, "author_profile": "https://Stackoverflow.com/users/9839769", "pm_score": 2, "selected": false, "text": "^(apple|bat|car), (?!\\1)(apple|bat|car), (?!\\1|\\2)(apple|bat|car)$" }, { "answer_id": 74503842, "author": "bobble bubble", "author_id": 5527985, "author_profile": "https://Stackoverflow.com/users/5527985", "pm_score": 2, "selected": false, "text": "^(?=.*?\\bApple\\b)(?=.*?\\bBat\\b)(?=.*?\\bCar\\b)\\w+(?:, ?\\w+){2}$\n \\b \\w , ? ^(?:\\b(?:, ?)?(Apple|Bat|Car)\\b(?!.*?\\b\\1\\b)){3}$\n \\b" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19653760/" ]
74,503,454
<pre><code>#include &lt;stdio.h&gt; #include &lt;time.h&gt; int main(){ printf(&quot;%d\n&quot;, time(NULL)); printf(&quot;Second: %ld\n&quot;, time(NULL)/60); printf(&quot;Minute: %ld\n&quot;, time(NULL)/(60*60)); printf(&quot;Hour: %ld\n&quot;, time(NULL)/(60*60*60)); printf(&quot;Day %ld\n&quot;, time(NULL)/(60*60*60*24)); return 0; } </code></pre> <p>Today is November 19. And it is 323. day of the year. When I run the program it print 321. What is the reason?</p>
[ { "answer_id": 74503600, "author": "Lindydancer", "author_id": 623133, "author_profile": "https://Stackoverflow.com/users/623133", "pm_score": 1, "selected": false, "text": "time(NULL)" }, { "answer_id": 74503693, "author": "Ahmed Masud", "author_id": 894328, "author_profile": "https://Stackoverflow.com/users/894328", "pm_score": 1, "selected": true, "text": "#include <stdio.h>\n#include <time.h>\n\n/* constants for time conversion\n * source: https://www.epochconverter.com/\nHuman-readable time(Seconds)\n1 Minute 60\n1 hour 3,600\n1 day 86,400\n1 week 604,800\n1 month (30.44 days)  2,629,743\n1 year (365.24 days) 31,556,926\n*/\nint main(){\n // number of years since epoch\n // 00:00 January 1, 1970\n time_t t = time(NULL) % 31556926; /* number of seconds elapsed in this year */\n\n printf(\"Seconds: %ld\\n\", t);\n printf(\"Minute: %ld\\n\", t/60);\n printf(\"Hour: %ld\\n\", t/3600);\n printf(\"Day %ld\\n\",t/86400);\n return 0;\n}\n\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20408952/" ]
74,503,488
<p>As the title says. I have a Django 4.1 app, which uses Werkzeug to enable https. I have the following launch.json set up:</p> <pre><code>{ &quot;version&quot;: &quot;0.2.0&quot;, &quot;configurations&quot;: [ { &quot;name&quot;: &quot;Python: Django&quot;, &quot;type&quot;: &quot;python&quot;, &quot;request&quot;: &quot;launch&quot;, &quot;python&quot;: &quot;${workspaceFolder}/venv/Scripts/python.exe&quot;, &quot;program&quot;: &quot;${workspaceFolder}\\appname\\manage.py&quot;, &quot;args&quot;: [ &quot;runserver_plus&quot;, &quot;--cert-file&quot;, &quot;${workspaceFolder}/certs/cert.pem&quot;, &quot;--key-file&quot;, &quot;${workspaceFolder}/certs/key.pem&quot; ], &quot;justMyCode&quot;: false, &quot;django&quot;: true } ] } </code></pre> <p>When I run this through the VSCode debugger it immediately quits in the <code>get_wsgi_application()</code> function with &quot;No module named manage&quot;. I tried googling around, but no answer proved to be useful. Any ideas what I am doing wrong?</p>
[ { "answer_id": 74559174, "author": "Ajay K", "author_id": 10782096, "author_profile": "https://Stackoverflow.com/users/10782096", "pm_score": -1, "selected": false, "text": "{\n \"version\": \"0.2.0\",\n \"configurations\": [\n {\n \"name\": \"Python: Django\",\n \"type\": \"python\",\n \"request\": \"launch\",\n \"python\": \"${workspaceFolder}/venv/Scripts/python.exe\",\n \"program\": \"${workspaceFolder}/manage.py\",\n \"args\": [\n \"runserver\",\n ],\n \"justMyCode\": false,\n \"django\": true\n }\n ]\n}\n" }, { "answer_id": 74563160, "author": "Ahmed Abo 6", "author_id": 11934499, "author_profile": "https://Stackoverflow.com/users/11934499", "pm_score": -1, "selected": false, "text": " \"program\": \"${workspaceFolder}\\\\manage.py\",\n" }, { "answer_id": 74601273, "author": "ruddra", "author_id": 2696165, "author_profile": "https://Stackoverflow.com/users/2696165", "pm_score": 3, "selected": true, "text": "PYTHONPATH env launch.json PYTHONPATH \"configurations\": [\n {\"env\": {\n \"PYTHONPATH\": \"${workspaceRoot}\\\\appname\"\n },\n \"name\": \"Python: Django\",\n \"type\": \"python\",\n \"request\": \"launch\",\n \"program\": \"${workspaceFolder}\\\\appname\\\\manage.py\",\n \"args\": [\n \"runserver_plus\"\n ],\n \"django\": true,\n \"justMyCode\": false\n }\n ]\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6874134/" ]
74,503,499
<p>i want a sticky side nav. I have three sections and place the nev in my first section but it just sticks till the end of the first section.</p> <p>HTML:</p> <pre><code>&lt;body&gt; &lt;div id=&quot;sections&quot;&gt; &lt;div class=&quot;section&quot; id=&quot;section1&quot;&gt; &lt;nav id=&quot;my-navigation&quot;&gt; &lt;div id=&quot;container&quot;&gt; &lt;li&gt;&lt;a href=&quot;&quot;&gt;Start.&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;&quot;&gt;My work.&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;&quot;&gt;Skills.&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;&quot;&gt;Education.&lt;/a&gt;&lt;/li&gt; &lt;/div&gt; &lt;/nav&gt; &lt;/div&gt; &lt;div class=&quot;section&quot; id=&quot;section2&quot;&gt;&lt;/div&gt; &lt;div class=&quot;section&quot; id=&quot;section3&quot;&gt;&lt;/div&gt; &lt;/div&gt; &lt;/body&gt; </code></pre> <p>CSS:</p> <pre><code>* { font-size: 16px; margin: 0; } .section{ width: 100%; height: 100vh; } #section1 { background-color: grey; } #section2 { background-color: aquamarine; } #section3 { background-color: brown; } #my-navigation { display: inline-block; position: sticky; height: 75vh; top: calc(25vh/2); left: 30px; border-left: 2px solid #000; } #container { display: flex; height: inherit; flex-direction: column; justify-content: space-around; } #container &gt; li { list-style: none; margin-left: 1rem; } </code></pre> <p>I already tried to place the nav before the first section like this:</p> <pre><code>&lt;body&gt; &lt;div id=&quot;sections&quot;&gt; &lt;nav id=&quot;my-navigation&quot;&gt; &lt;div id=&quot;container&quot;&gt; &lt;li&gt;&lt;a href=&quot;&quot;&gt;Start.&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;&quot;&gt;My work.&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;&quot;&gt;Skills.&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;&quot;&gt;Education.&lt;/a&gt;&lt;/li&gt; &lt;/div&gt; &lt;/nav&gt; &lt;div class=&quot;section&quot; id=&quot;section1&quot;&gt;&lt;/div&gt; &lt;div class=&quot;section&quot; id=&quot;section2&quot;&gt;&lt;/div&gt; &lt;div class=&quot;section&quot; id=&quot;section3&quot;&gt;&lt;/div&gt; &lt;/div&gt; &lt;/body&gt; </code></pre> <p>But the result was not what i expected.</p> <p><a href="https://i.stack.imgur.com/Egv23.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Egv23.png" alt="There is now a white space before my first section" /></a></p> <p>Is there a possibility to place the nav somehow independent? It just should be sticky for the whole website.</p>
[ { "answer_id": 74559174, "author": "Ajay K", "author_id": 10782096, "author_profile": "https://Stackoverflow.com/users/10782096", "pm_score": -1, "selected": false, "text": "{\n \"version\": \"0.2.0\",\n \"configurations\": [\n {\n \"name\": \"Python: Django\",\n \"type\": \"python\",\n \"request\": \"launch\",\n \"python\": \"${workspaceFolder}/venv/Scripts/python.exe\",\n \"program\": \"${workspaceFolder}/manage.py\",\n \"args\": [\n \"runserver\",\n ],\n \"justMyCode\": false,\n \"django\": true\n }\n ]\n}\n" }, { "answer_id": 74563160, "author": "Ahmed Abo 6", "author_id": 11934499, "author_profile": "https://Stackoverflow.com/users/11934499", "pm_score": -1, "selected": false, "text": " \"program\": \"${workspaceFolder}\\\\manage.py\",\n" }, { "answer_id": 74601273, "author": "ruddra", "author_id": 2696165, "author_profile": "https://Stackoverflow.com/users/2696165", "pm_score": 3, "selected": true, "text": "PYTHONPATH env launch.json PYTHONPATH \"configurations\": [\n {\"env\": {\n \"PYTHONPATH\": \"${workspaceRoot}\\\\appname\"\n },\n \"name\": \"Python: Django\",\n \"type\": \"python\",\n \"request\": \"launch\",\n \"program\": \"${workspaceFolder}\\\\appname\\\\manage.py\",\n \"args\": [\n \"runserver_plus\"\n ],\n \"django\": true,\n \"justMyCode\": false\n }\n ]\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16116548/" ]
74,503,501
<p>I have below pandas dataframe which has employees sales data for october month.</p> <pre><code> Employee Timerange Dials Conn Conv Mtg Bkd Talk Dial 0 Ricky Ponting 10/3 - 10/7 1,869 102 60.0 2.0 3h:08m 5h:23m 1 Adam Gilchrist 10/3 - 10/7 1,336 53 30.0 1.0 1h:10m 3h:58m 2 Michael Clarke 10/3 - 10/7 1,960 74 42.0 1.0 2h:02m 5h:28m 3 Shane Warne 10/3 - 10/7 1,478 62 45.0 1.0 1h:55m 4h:07m </code></pre> <p>Schema -</p> <pre><code># Column Non-Null Count Dtype --- ------ -------------- ----- 1 Timerange 40 non-null object 2 Dials 40 non-null object 3 Conn 40 non-null int64 4 Conv 39 non-null float64 5 Mtg Bkd 39 non-null float64 6 Talk 40 non-null object 7 Dial︎ 40 non-null object </code></pre> <p>I basically want to check the dials-to-connection and the dials-to-conversation average rates of the whole team for the month. Example output like below -</p> <pre><code> Month Dials Conn Dials -&gt; Conn Dials -&gt; Conv October 60517 2702 0.045 0.026 </code></pre> <p>I tried using pd.DatetimeIndex(df['Timerange']).Month and separate the column but it is giving me error dateutil.parser._parser.ParserError: Unknown string format: 10/3 - 10/7. Please help me guys</p>
[ { "answer_id": 74559174, "author": "Ajay K", "author_id": 10782096, "author_profile": "https://Stackoverflow.com/users/10782096", "pm_score": -1, "selected": false, "text": "{\n \"version\": \"0.2.0\",\n \"configurations\": [\n {\n \"name\": \"Python: Django\",\n \"type\": \"python\",\n \"request\": \"launch\",\n \"python\": \"${workspaceFolder}/venv/Scripts/python.exe\",\n \"program\": \"${workspaceFolder}/manage.py\",\n \"args\": [\n \"runserver\",\n ],\n \"justMyCode\": false,\n \"django\": true\n }\n ]\n}\n" }, { "answer_id": 74563160, "author": "Ahmed Abo 6", "author_id": 11934499, "author_profile": "https://Stackoverflow.com/users/11934499", "pm_score": -1, "selected": false, "text": " \"program\": \"${workspaceFolder}\\\\manage.py\",\n" }, { "answer_id": 74601273, "author": "ruddra", "author_id": 2696165, "author_profile": "https://Stackoverflow.com/users/2696165", "pm_score": 3, "selected": true, "text": "PYTHONPATH env launch.json PYTHONPATH \"configurations\": [\n {\"env\": {\n \"PYTHONPATH\": \"${workspaceRoot}\\\\appname\"\n },\n \"name\": \"Python: Django\",\n \"type\": \"python\",\n \"request\": \"launch\",\n \"program\": \"${workspaceFolder}\\\\appname\\\\manage.py\",\n \"args\": [\n \"runserver_plus\"\n ],\n \"django\": true,\n \"justMyCode\": false\n }\n ]\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15215859/" ]
74,503,516
<p>I'm creating a search field to allow users to search for tags associated with a photo, and then only show photos containing that tag in my List. I'm using a computed property to check if my array of <code>Photo</code> contains the tag but the tags are in a nested array several properties deep in my <code>Photo</code> object. I need some help filtering the photos array from the computed property so my List uses the correct photos.</p> <p>I'm trying to use this computed property to filter my photos:</p> <pre><code>struct PhotoListView: View { let photos: [Photo] @State private var searchText: String = &quot;&quot; var filteredPhotos: [Photo] { if searchText.count == 0 { return photos } else { return photos.filter { photo in return photo.info?.tags.tagContent.filter { $0._content.contains(searchText) } } } } var body: some View { NavigationStack { List { ForEach(filteredPhotos) { photo in NavigationLink { PhotoDetailView(photo: photo) } label: { PhotoRow(photo: photo) } } } .navigationTitle(&quot;Recent Photos&quot;) .searchable(text: $searchText) } } } </code></pre> <p>The attempt above results in an error - <code>Cannot convert value of type '[TagContent]?' to closure result type 'Bool'</code></p> <pre><code>class Photo: Decodable, Identifiable { let id: String let owner: String let secret: String let title: String let server: String let farm: Int var imageURL: URL? var info: PhotoInfo? } struct PhotoInfo: Decodable { let id: String let dateuploaded: String let tags: PhotoTags } struct PhotoTags: Decodable { let tagContent: [TagContent] enum CodingKeys: String, CodingKey { case tagContent = &quot;tag&quot; } } struct TagContent: Decodable, Hashable { let id: String let _content: String } </code></pre> <p>Using the above model structure can anyone help me filter the tags by <code>_content</code> from my computed property?</p>
[ { "answer_id": 74559174, "author": "Ajay K", "author_id": 10782096, "author_profile": "https://Stackoverflow.com/users/10782096", "pm_score": -1, "selected": false, "text": "{\n \"version\": \"0.2.0\",\n \"configurations\": [\n {\n \"name\": \"Python: Django\",\n \"type\": \"python\",\n \"request\": \"launch\",\n \"python\": \"${workspaceFolder}/venv/Scripts/python.exe\",\n \"program\": \"${workspaceFolder}/manage.py\",\n \"args\": [\n \"runserver\",\n ],\n \"justMyCode\": false,\n \"django\": true\n }\n ]\n}\n" }, { "answer_id": 74563160, "author": "Ahmed Abo 6", "author_id": 11934499, "author_profile": "https://Stackoverflow.com/users/11934499", "pm_score": -1, "selected": false, "text": " \"program\": \"${workspaceFolder}\\\\manage.py\",\n" }, { "answer_id": 74601273, "author": "ruddra", "author_id": 2696165, "author_profile": "https://Stackoverflow.com/users/2696165", "pm_score": 3, "selected": true, "text": "PYTHONPATH env launch.json PYTHONPATH \"configurations\": [\n {\"env\": {\n \"PYTHONPATH\": \"${workspaceRoot}\\\\appname\"\n },\n \"name\": \"Python: Django\",\n \"type\": \"python\",\n \"request\": \"launch\",\n \"program\": \"${workspaceFolder}\\\\appname\\\\manage.py\",\n \"args\": [\n \"runserver_plus\"\n ],\n \"django\": true,\n \"justMyCode\": false\n }\n ]\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13816223/" ]
74,503,551
<p>So as the title says I'm supposed to make a function that takes a list and returns the list without the duplicates, but I can't use list comprehensions, only high-order functions and lambdas.</p> <p>I've found this code from another users question.</p> <pre><code>has :: (Eq a) =&gt; [a] -&gt; a -&gt; Bool has [] _ = False has (x:xs) a | x == a = True | otherwise = has xs a unique :: (Eq a) =&gt; [a] -&gt; [a] unique [] = [] unique (x:xs) | has xs x = unique xs | otherwise = x : unique xs </code></pre> <p>I understand how it works, but I don't understand how I could do the same thing with high-order fuctions. I'm new to Haskell so any tips would be appreciated.</p>
[ { "answer_id": 74559174, "author": "Ajay K", "author_id": 10782096, "author_profile": "https://Stackoverflow.com/users/10782096", "pm_score": -1, "selected": false, "text": "{\n \"version\": \"0.2.0\",\n \"configurations\": [\n {\n \"name\": \"Python: Django\",\n \"type\": \"python\",\n \"request\": \"launch\",\n \"python\": \"${workspaceFolder}/venv/Scripts/python.exe\",\n \"program\": \"${workspaceFolder}/manage.py\",\n \"args\": [\n \"runserver\",\n ],\n \"justMyCode\": false,\n \"django\": true\n }\n ]\n}\n" }, { "answer_id": 74563160, "author": "Ahmed Abo 6", "author_id": 11934499, "author_profile": "https://Stackoverflow.com/users/11934499", "pm_score": -1, "selected": false, "text": " \"program\": \"${workspaceFolder}\\\\manage.py\",\n" }, { "answer_id": 74601273, "author": "ruddra", "author_id": 2696165, "author_profile": "https://Stackoverflow.com/users/2696165", "pm_score": 3, "selected": true, "text": "PYTHONPATH env launch.json PYTHONPATH \"configurations\": [\n {\"env\": {\n \"PYTHONPATH\": \"${workspaceRoot}\\\\appname\"\n },\n \"name\": \"Python: Django\",\n \"type\": \"python\",\n \"request\": \"launch\",\n \"program\": \"${workspaceFolder}\\\\appname\\\\manage.py\",\n \"args\": [\n \"runserver_plus\"\n ],\n \"django\": true,\n \"justMyCode\": false\n }\n ]\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20477097/" ]
74,503,579
<p>I have a huge text file (~1.5GB) with numerous lines ending with &quot;.Ends&quot;.<br /> I need a linux oneliner (perl\ awk\ sed) to find the <strong>last</strong> place '.Ends' appear in the file and add a couple of lines <strong>before</strong> it.</p> <p>I tried using <code>tac</code> twice, and stumbled with my perl:</p> <p>When I use:<br /> <code>tac ../../test | perl -pi -e 'BEGIN {$flag = 1} if ($flag==1 &amp;&amp; /.Ends/) {$flag = 0 ; print &quot;someline\n&quot;}' | tac</code><br /> It first prints the &quot;someline\n&quot; and only than prints the .Ends The result is:<br /> …<br /> .Ends<br /> someline</p> <p>When I use:<br /> <code>tac ../../test | perl -e 'BEGIN {$flag = 1} print ; if ($flag==1 &amp;&amp; /.Ends/) {$flag = 0 ; print &quot;someline\n&quot;}' | tac</code><br /> It doesn’t print anything.</p> <p>And when I use:<br /> <code>tac ../../test | perl -p -e 'BEGIN {$flag = 1} print $_ ; if ($flag==1 &amp;&amp; /.Ends/) {$flag = 0 ; print &quot;someline\n&quot;}' | tac</code><br /> It prints everything twice:<br /> …<br /> .Ends<br /> someline<br /> .Ends</p> <p>Is there a smooth way to perform this edit?<br /> Don't have to be with my solution direction, I'm not picky...<br /> Bonus - if the lines can come from a different file, it would be great (but really not a must)</p> <p><em>Edit</em><br /> test input file:</p> <pre><code>gla2 fla3 dla4 rfa5 .Ends shu sha she .Ends res pes ges .Ends ---&gt; ... pes ges someline .Ends # * some irrelevant junk * # </code></pre>
[ { "answer_id": 74503810, "author": "markp-fuso", "author_id": 7366100, "author_profile": "https://Stackoverflow.com/users/7366100", "pm_score": 3, "selected": true, "text": "$ cat test.dat\ndla4\n.Ends\nshe\n.Ends\nres\n.Ends\nabc\n\n$ cat new.dat\nnewline 111\nnewline 222\n awk tac | <process> | tac $ tac test.dat | awk -v new_dat=\"new.dat\" '1;/\\.Ends/ && !(seen++) {system(\"tac \" new_dat)}' | tac\ndla4\n.Ends\nshe\n.Ends\nres\nnewline 111\nnewline 222\n.Ends\nabc\n awk tac $ awk -v new_dat=\"new.dat\" 'FNR==NR { if ($0 ~ /\\.Ends/) lastline=FNR; next} FNR==lastline { system(\"cat \"new_dat) }; 1' test.dat test.dat\ndla4\n.Ends\nshe\n.Ends\nres\nnewline 111\nnewline 222\n.Ends\nabc\n test.dat" }, { "answer_id": 74503951, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 0, "selected": false, "text": "grep awk $ cat insert\nnew content\nnew content\n\n$ line=$(cat insert)\n\n$ awk -v var=\"${line}\" '\n NR==1{last=$1; next} \n FNR==last{print var}1' <(grep -n \"^\\.Ends$\" file | cut -f 1 -d : | tail -1) file\nrfa5 \n.Ends\nshe\n.Ends\nges\n.Ends \nges\nnew content\nnew content\n.Ends\nges\nges\n $ cat file\nrfa5 \n.Ends\nshe\n.Ends\nges\n.Ends \nges\n.Ends\nges\nges\n" }, { "answer_id": 74504009, "author": "HatLess", "author_id": 16372109, "author_profile": "https://Stackoverflow.com/users/16372109", "pm_score": 2, "selected": false, "text": "sed -i.bak .bak $ sed -Ezi.bak 's/(.*)(\\.Ends)/\\1newline\\nnewline\\n\\2/' input_file\n$ cat input_file\ngla2\nfla3\ndla4\nrfa5\n.Ends\nshu\nsha\nshe\n.Ends\nres\npes\nges\n.Ends\n--->\n...\npes\nges\nsomeline\nnewline\nnewline\n.Ends\n" }, { "answer_id": 74504194, "author": "markp-fuso", "author_id": 7366100, "author_profile": "https://Stackoverflow.com/users/7366100", "pm_score": 1, "selected": false, "text": "$ cat test.dat\ndla4\n.Ends\nshe\n.Ends\nres\n.Ends\nabc\n\n$ cat new.dat\nnewline 111\nnewline 222\n ed $ ed test.dat >/dev/null 2>&1 <<EOF\n1\n?.Ends\n-1r new.dat\nwq\nEOF\n $ ed test.dat < <(printf '%s\\n' 1 ?.Ends '-1r new.dat' wq) >/dev/null 2>&1\n >/dev/null 2>&1 1 ?.Ends .Ends .Ends -1r new.dat -1 r new.dat wq w q $ cat test.dat\ndla4\n.Ends\nshe\n.Ends\nres\nnewline 111\nnewline 222\n.Ends\nabc\n test.dat" }, { "answer_id": 74504336, "author": "zdim", "author_id": 4653379, "author_profile": "https://Stackoverflow.com/users/4653379", "pm_score": 3, "selected": false, "text": "use warnings;\nuse strict;\nuse feature 'say';\nuse Path::Tiny;\nuse File::ReadBackwards;\n \nmy $file = shift // die \"Usage: $0 file\\n\"; \n\nmy $bw = File::ReadBackwards->new($file);\n\nmy @rest_after_marker; \n\nwhile ( my $line = $bw->readline ) { \n unshift @rest_after_marker, $line;\n last if $line =~ /\\.Ends/;\n}\n# Position after which to add text and copy back the rest\nmy $pos = $bw->tell; \n$bw->close;\n\nopen my $fh, '+<', $file or die $!; \nseek $fh, $pos, 0;\ntruncate $fh, $pos; \nprint $fh $_ for path(\"add.txt\")->slurp, @rest_after_marker;\n .Ends add.txt .Ends" }, { "answer_id": 74504690, "author": "Ed Morton", "author_id": 1745001, "author_profile": "https://Stackoverflow.com/users/1745001", "pm_score": 1, "selected": false, "text": "$ cat new\nfoo\nbar\netc\n $ tac file | awk 'NR==FNR{str=$0 ORS str; next} {print} $0==\".Ends\"{printf \"%s\", str; str=\"\"}' new - | tac\ngla2\nfla3\ndla4\nrfa5\n.Ends\nshu\nsha\nshe\n.Ends\nres\npes\nges\n.Ends\n--->\n...\npes\nges\nsomeline\nfoo\nbar\netc\n.Ends\n# * some irrelevant junk * #\n .Ends $0==\".Ends\" /^\\.Ends[[:space:]]*$/ /^[[:space:]]*\\.Ends[[:space:]]*$/ /\\.Ends/ .Ends" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2141046/" ]
74,503,615
<p>my first time, be patient pls.</p> <p>I want to highlight the selected nav-link, it works well but the first one (small), doesn't highlight.</p> <p>Even when i select the other ones, (medium or large, that do change the color), and select the first one (small) again, small won't change its color.</p> <p>and its also just black at the beginning.</p> <p>here my code , I am using vue and bootstrap is installed</p> <pre><code>&lt;template&gt; &lt;div &gt; &lt;nav&gt; &lt;div class=&quot;nav nav-tabs&quot; id=&quot;nav-tab&quot; role=&quot;tablist&quot;&gt; &lt;button class=&quot;nav-link car-head active&quot; id=&quot;nav-ssprinter-tab&quot; data-bs-toggle=&quot;tab&quot; data-bs-target=&quot;#nav-ssprinter&quot; type=&quot;button&quot; role=&quot;tab&quot; aria-controls=&quot;nav-ssprinter&quot; aria-selected=&quot;true&quot; &gt;Small &lt;/button&gt; &lt;button class=&quot;nav-link car-head&quot; id=&quot;nav-msprinter-tab&quot; data-bs-toggle=&quot;tab&quot; data-bs-target=&quot;#nav-msprinter&quot; type=&quot;button&quot; role=&quot;tab&quot; aria-controls=&quot;nav-msprinter&quot; aria-selected=&quot;false&quot; &gt; Middle &lt;/button&gt; &lt;button class=&quot;nav-link car-head&quot; id=&quot;nav-xlsprinter-tab&quot; data-bs-toggle=&quot;tab&quot; data-bs-target=&quot;#nav-xlsprinter&quot; type=&quot;button&quot; role=&quot;tab&quot; aria-controls=&quot;nav-xlsprinter&quot; aria-selected=&quot;false&quot; &gt; big &lt;/button&gt; &lt;/div&gt; &lt;/nav&gt; &lt;div class=&quot;tab-content&quot; id=&quot;nav-tabContent&quot;&gt; &lt;div class=&quot;tab-pane fade show active&quot; id=&quot;nav-ssprinter&quot; role=&quot;tabpanel&quot; aria-labelledby=&quot;nav-ssprinter-tab&quot; tabindex=&quot;0&quot; &gt; Small text &lt;/div&gt; &lt;div class=&quot;tab-pane fade&quot; id=&quot;nav-msprinter&quot; role=&quot;tabpanel&quot; aria-labelledby=&quot;nav-msprinter-tab&quot; tabindex=&quot;0&quot; &gt; medium text &lt;/div&gt; &lt;div class=&quot;tab-pane fade&quot; id=&quot;nav-xlsprinter&quot; role=&quot;tabpanel&quot; aria-labelledby=&quot;nav-xlsprinter-tab&quot; tabindex=&quot;0&quot; &gt; big text &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; export default { components: {}, methods: {}, }; &lt;/script&gt; &lt;style&gt; .car-head{ color: black !important; font-weight: bold !important; } .car-head + .active { color: rgb(243, 158, 0) !important; background: rgb(220, 220, 220) !important; } &lt;/style&gt; </code></pre> <p>i have checked the id's and classes and changed the order in the css part at the bottom, it helped at a different problem don't didn't solved this one.</p> <p>i hoped to find a mistyping in class names for the small nav-link, because, I see no other reason that it's color is always black, at the beginning (default selected) and when I select It after selecting something else.</p>
[ { "answer_id": 74503810, "author": "markp-fuso", "author_id": 7366100, "author_profile": "https://Stackoverflow.com/users/7366100", "pm_score": 3, "selected": true, "text": "$ cat test.dat\ndla4\n.Ends\nshe\n.Ends\nres\n.Ends\nabc\n\n$ cat new.dat\nnewline 111\nnewline 222\n awk tac | <process> | tac $ tac test.dat | awk -v new_dat=\"new.dat\" '1;/\\.Ends/ && !(seen++) {system(\"tac \" new_dat)}' | tac\ndla4\n.Ends\nshe\n.Ends\nres\nnewline 111\nnewline 222\n.Ends\nabc\n awk tac $ awk -v new_dat=\"new.dat\" 'FNR==NR { if ($0 ~ /\\.Ends/) lastline=FNR; next} FNR==lastline { system(\"cat \"new_dat) }; 1' test.dat test.dat\ndla4\n.Ends\nshe\n.Ends\nres\nnewline 111\nnewline 222\n.Ends\nabc\n test.dat" }, { "answer_id": 74503951, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 0, "selected": false, "text": "grep awk $ cat insert\nnew content\nnew content\n\n$ line=$(cat insert)\n\n$ awk -v var=\"${line}\" '\n NR==1{last=$1; next} \n FNR==last{print var}1' <(grep -n \"^\\.Ends$\" file | cut -f 1 -d : | tail -1) file\nrfa5 \n.Ends\nshe\n.Ends\nges\n.Ends \nges\nnew content\nnew content\n.Ends\nges\nges\n $ cat file\nrfa5 \n.Ends\nshe\n.Ends\nges\n.Ends \nges\n.Ends\nges\nges\n" }, { "answer_id": 74504009, "author": "HatLess", "author_id": 16372109, "author_profile": "https://Stackoverflow.com/users/16372109", "pm_score": 2, "selected": false, "text": "sed -i.bak .bak $ sed -Ezi.bak 's/(.*)(\\.Ends)/\\1newline\\nnewline\\n\\2/' input_file\n$ cat input_file\ngla2\nfla3\ndla4\nrfa5\n.Ends\nshu\nsha\nshe\n.Ends\nres\npes\nges\n.Ends\n--->\n...\npes\nges\nsomeline\nnewline\nnewline\n.Ends\n" }, { "answer_id": 74504194, "author": "markp-fuso", "author_id": 7366100, "author_profile": "https://Stackoverflow.com/users/7366100", "pm_score": 1, "selected": false, "text": "$ cat test.dat\ndla4\n.Ends\nshe\n.Ends\nres\n.Ends\nabc\n\n$ cat new.dat\nnewline 111\nnewline 222\n ed $ ed test.dat >/dev/null 2>&1 <<EOF\n1\n?.Ends\n-1r new.dat\nwq\nEOF\n $ ed test.dat < <(printf '%s\\n' 1 ?.Ends '-1r new.dat' wq) >/dev/null 2>&1\n >/dev/null 2>&1 1 ?.Ends .Ends .Ends -1r new.dat -1 r new.dat wq w q $ cat test.dat\ndla4\n.Ends\nshe\n.Ends\nres\nnewline 111\nnewline 222\n.Ends\nabc\n test.dat" }, { "answer_id": 74504336, "author": "zdim", "author_id": 4653379, "author_profile": "https://Stackoverflow.com/users/4653379", "pm_score": 3, "selected": false, "text": "use warnings;\nuse strict;\nuse feature 'say';\nuse Path::Tiny;\nuse File::ReadBackwards;\n \nmy $file = shift // die \"Usage: $0 file\\n\"; \n\nmy $bw = File::ReadBackwards->new($file);\n\nmy @rest_after_marker; \n\nwhile ( my $line = $bw->readline ) { \n unshift @rest_after_marker, $line;\n last if $line =~ /\\.Ends/;\n}\n# Position after which to add text and copy back the rest\nmy $pos = $bw->tell; \n$bw->close;\n\nopen my $fh, '+<', $file or die $!; \nseek $fh, $pos, 0;\ntruncate $fh, $pos; \nprint $fh $_ for path(\"add.txt\")->slurp, @rest_after_marker;\n .Ends add.txt .Ends" }, { "answer_id": 74504690, "author": "Ed Morton", "author_id": 1745001, "author_profile": "https://Stackoverflow.com/users/1745001", "pm_score": 1, "selected": false, "text": "$ cat new\nfoo\nbar\netc\n $ tac file | awk 'NR==FNR{str=$0 ORS str; next} {print} $0==\".Ends\"{printf \"%s\", str; str=\"\"}' new - | tac\ngla2\nfla3\ndla4\nrfa5\n.Ends\nshu\nsha\nshe\n.Ends\nres\npes\nges\n.Ends\n--->\n...\npes\nges\nsomeline\nfoo\nbar\netc\n.Ends\n# * some irrelevant junk * #\n .Ends $0==\".Ends\" /^\\.Ends[[:space:]]*$/ /^[[:space:]]*\\.Ends[[:space:]]*$/ /\\.Ends/ .Ends" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16222863/" ]
74,503,622
<p>How Do I sum up all the values in 'exports' and 'imports' of all countries by year?</p> <p>data frame :</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Country</th> <th>Year</th> <th>exports</th> <th>imports</th> </tr> </thead> <tbody> <tr> <td>Denmark</td> <td>2004</td> <td>10000000</td> <td>10000000</td> </tr> <tr> <td>Denmark</td> <td>2008</td> <td>20000000</td> <td>20000000</td> </tr> <tr> <td>Denmark</td> <td>2009</td> <td>30000000</td> <td>30000000</td> </tr> <tr> <td>Norway</td> <td>2004</td> <td>10000000</td> <td>10000000</td> </tr> <tr> <td>Norway</td> <td>2008</td> <td>20000000</td> <td>20000000</td> </tr> <tr> <td>Norway</td> <td>2009</td> <td>10000000</td> <td>30000000</td> </tr> </tbody> </table> </div> <p>I tried:</p> <pre><code>df_frame %&gt;% group_by(Year) %&gt;% summarize( total_exports = sum(exports), total_imports = sum(imports) ) </code></pre> <p>But I got:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Year</th> <th>exports</th> <th>imports</th> </tr> </thead> <tbody> <tr> <td>2004</td> <td>NA</td> <td>NA</td> </tr> <tr> <td>2008</td> <td>NA</td> <td>NA</td> </tr> <tr> <td>2009</td> <td>NA</td> <td>NA</td> </tr> </tbody> </table> </div> <p>I want:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Year</th> <th>exports</th> <th>imports</th> </tr> </thead> <tbody> <tr> <td>2004</td> <td>40000000</td> <td>20000000</td> </tr> <tr> <td>2008</td> <td>40000000</td> <td>40000000</td> </tr> <tr> <td>2009</td> <td>20000000</td> <td>60000000</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74503810, "author": "markp-fuso", "author_id": 7366100, "author_profile": "https://Stackoverflow.com/users/7366100", "pm_score": 3, "selected": true, "text": "$ cat test.dat\ndla4\n.Ends\nshe\n.Ends\nres\n.Ends\nabc\n\n$ cat new.dat\nnewline 111\nnewline 222\n awk tac | <process> | tac $ tac test.dat | awk -v new_dat=\"new.dat\" '1;/\\.Ends/ && !(seen++) {system(\"tac \" new_dat)}' | tac\ndla4\n.Ends\nshe\n.Ends\nres\nnewline 111\nnewline 222\n.Ends\nabc\n awk tac $ awk -v new_dat=\"new.dat\" 'FNR==NR { if ($0 ~ /\\.Ends/) lastline=FNR; next} FNR==lastline { system(\"cat \"new_dat) }; 1' test.dat test.dat\ndla4\n.Ends\nshe\n.Ends\nres\nnewline 111\nnewline 222\n.Ends\nabc\n test.dat" }, { "answer_id": 74503951, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 0, "selected": false, "text": "grep awk $ cat insert\nnew content\nnew content\n\n$ line=$(cat insert)\n\n$ awk -v var=\"${line}\" '\n NR==1{last=$1; next} \n FNR==last{print var}1' <(grep -n \"^\\.Ends$\" file | cut -f 1 -d : | tail -1) file\nrfa5 \n.Ends\nshe\n.Ends\nges\n.Ends \nges\nnew content\nnew content\n.Ends\nges\nges\n $ cat file\nrfa5 \n.Ends\nshe\n.Ends\nges\n.Ends \nges\n.Ends\nges\nges\n" }, { "answer_id": 74504009, "author": "HatLess", "author_id": 16372109, "author_profile": "https://Stackoverflow.com/users/16372109", "pm_score": 2, "selected": false, "text": "sed -i.bak .bak $ sed -Ezi.bak 's/(.*)(\\.Ends)/\\1newline\\nnewline\\n\\2/' input_file\n$ cat input_file\ngla2\nfla3\ndla4\nrfa5\n.Ends\nshu\nsha\nshe\n.Ends\nres\npes\nges\n.Ends\n--->\n...\npes\nges\nsomeline\nnewline\nnewline\n.Ends\n" }, { "answer_id": 74504194, "author": "markp-fuso", "author_id": 7366100, "author_profile": "https://Stackoverflow.com/users/7366100", "pm_score": 1, "selected": false, "text": "$ cat test.dat\ndla4\n.Ends\nshe\n.Ends\nres\n.Ends\nabc\n\n$ cat new.dat\nnewline 111\nnewline 222\n ed $ ed test.dat >/dev/null 2>&1 <<EOF\n1\n?.Ends\n-1r new.dat\nwq\nEOF\n $ ed test.dat < <(printf '%s\\n' 1 ?.Ends '-1r new.dat' wq) >/dev/null 2>&1\n >/dev/null 2>&1 1 ?.Ends .Ends .Ends -1r new.dat -1 r new.dat wq w q $ cat test.dat\ndla4\n.Ends\nshe\n.Ends\nres\nnewline 111\nnewline 222\n.Ends\nabc\n test.dat" }, { "answer_id": 74504336, "author": "zdim", "author_id": 4653379, "author_profile": "https://Stackoverflow.com/users/4653379", "pm_score": 3, "selected": false, "text": "use warnings;\nuse strict;\nuse feature 'say';\nuse Path::Tiny;\nuse File::ReadBackwards;\n \nmy $file = shift // die \"Usage: $0 file\\n\"; \n\nmy $bw = File::ReadBackwards->new($file);\n\nmy @rest_after_marker; \n\nwhile ( my $line = $bw->readline ) { \n unshift @rest_after_marker, $line;\n last if $line =~ /\\.Ends/;\n}\n# Position after which to add text and copy back the rest\nmy $pos = $bw->tell; \n$bw->close;\n\nopen my $fh, '+<', $file or die $!; \nseek $fh, $pos, 0;\ntruncate $fh, $pos; \nprint $fh $_ for path(\"add.txt\")->slurp, @rest_after_marker;\n .Ends add.txt .Ends" }, { "answer_id": 74504690, "author": "Ed Morton", "author_id": 1745001, "author_profile": "https://Stackoverflow.com/users/1745001", "pm_score": 1, "selected": false, "text": "$ cat new\nfoo\nbar\netc\n $ tac file | awk 'NR==FNR{str=$0 ORS str; next} {print} $0==\".Ends\"{printf \"%s\", str; str=\"\"}' new - | tac\ngla2\nfla3\ndla4\nrfa5\n.Ends\nshu\nsha\nshe\n.Ends\nres\npes\nges\n.Ends\n--->\n...\npes\nges\nsomeline\nfoo\nbar\netc\n.Ends\n# * some irrelevant junk * #\n .Ends $0==\".Ends\" /^\\.Ends[[:space:]]*$/ /^[[:space:]]*\\.Ends[[:space:]]*$/ /\\.Ends/ .Ends" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20550379/" ]
74,503,655
<p>I was going through the documentation for &quot;Floating-point numeric types (C# reference)&quot; at MSDN, <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types</a>.</p> <p>It has a table, &quot;Characteristics of the floating-point types,&quot; describing the approximate ranges for the different floating datatypes that C# deals with. What I do not understand is why both the MIN and MAX in &quot;Approximate range&quot; column are both positive and negative. Skipping a link click, here is the table,</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>C# type/keyword</th> <th>Approximate range</th> <th>Precision</th> <th>Size</th> <th>.NET type</th> </tr> </thead> <tbody> <tr> <td>float</td> <td>±1.5 x 10<sup>−45</sup> to ±3.4 x 10<sup>38</sup></td> <td>~6-9 digits</td> <td>4 bytes</td> <td>System.Single</td> </tr> <tr> <td>double</td> <td>±5.0 × 10<sup>−324</sup> to ±1.7 × 10<sup>308</sup></td> <td>~15-17 digits</td> <td>8 bytes</td> <td>System.Double</td> </tr> <tr> <td>decimal</td> <td>±1.0 x 10<sup>-28</sup> to ±7.9228 x 10<sup>28</sup></td> <td>28-29 digits</td> <td>16 bytes</td> <td>System.Decimal</td> </tr> </tbody> </table> </div> <p>Why does the approximate range on both the MIN and MAX have a ±? Should it not be a <code>-</code> for the MIN, and <code>+</code> for the MAX, as it does for the Integer type here <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types</a>? Maybe I misunderstood something about floating points.</p> <p>Thank you.</p>
[ { "answer_id": 74504106, "author": "Andrew McClement", "author_id": 13893216, "author_profile": "https://Stackoverflow.com/users/13893216", "pm_score": 1, "selected": false, "text": "double double.Epsilon" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10576072/" ]
74,503,659
<p>Let's say I have a weighted, undirected, acyclic graph with no negative value weights, comprised of n vertices and n-1 edges. If I want to calculate the total distance between every single one of them (using edge weight) and then add it up, which algorithm should I use? If for example a graph has 4 vertices, connected like a-b, a-c, c-d then the program should output the total distance needed to go from a-d, a-c, a-b, b-c, b-d and so on. You could call it every possible path between the given vertices. The language I am using is C++.</p> <p>I have tried using Dijikstra's and Prim's algorithm, but none have worked for me. I have thought about using normal or multisource DFS, but I have been struggling with it for some time now. Is there really a fast way to calculate it, or have I misunderstood the problem entirely?</p>
[ { "answer_id": 74504106, "author": "Andrew McClement", "author_id": 13893216, "author_profile": "https://Stackoverflow.com/users/13893216", "pm_score": 1, "selected": false, "text": "double double.Epsilon" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20549157/" ]
74,503,660
<p>I used DatePickerDialog in a fragment. I have a Button and an unclickable EditText. Whenever the user presses the button, it shows the DatePickerDialog, but the problem is when it chooses January, the value of the month is 0.</p> <p>This is my code</p> <pre><code>DatePickerDialog datePickerDialog = new DatePickerDialog(this.Activity, this, year, month, day); datePickerDialog.Show(); this.year = year; this.month = month + 1; this.day = dayOfMonth; eventdatesetText.EditText.Text = month + &quot;/&quot; + dayOfMonth + &quot;/&quot; + year; </code></pre> <p>Is my code right? Do I need to add something more on this code?</p> <pre><code>this.month = month + 1; </code></pre> <p>I have added + 1 but for some reason it is not working. Any solution? Thank you for future answers! I appreciate it a lot! :)</p>
[ { "answer_id": 74513289, "author": "Liyun Zhang - MSFT", "author_id": 17455524, "author_profile": "https://Stackoverflow.com/users/17455524", "pm_score": 1, "selected": true, "text": "this.month = month + 1; eventdatesetText.EditText.Text = this.month + \"/\" + dayOfMonth + \"/\" + year; eventdatesetText.EditText.Text = (month+1) + \"/\" + dayOfMonth + \"/\" + year;" }, { "answer_id": 74513661, "author": "Flater", "author_id": 952296, "author_profile": "https://Stackoverflow.com/users/952296", "pm_score": 0, "selected": false, "text": "eventdatesetText.EditText.Text = this.month month month this.month +1 this.month DatePickerDialog datePickerDialog = new DatePickerDialog(this.Activity, this, year, month, day);\n datePickerDialog.Show();\n\n\nthis.year = year;\nthis.month = month + 1;\nthis.day = dayOfMonth;\neventdatesetText.EditText.Text = this.month + \"/\" + this.day + \"/\" + this.year;\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20498910/" ]
74,503,668
<p>I'm a student and I have this exercise: we have to write a function with 2 parameters, account number and withdrawal, and return the new balance of a bank account only if the account balance - withdrawal &gt; Flow threshold</p> <p>This is my code:</p> <pre><code>set serveroutput on CREATE OR REPLACE FONCTION Retrait (f_numcomp in varchar2,f_montant NUMBER(38,3)) RETURN NUMBER(38,3) AS v_compte compte%rowtype; v_solde compte.Solde%type; BEGIN SELECT * into v_compte from compte where f_numcomp = compte.NUMEROCOMPTE; if (v_compte.Solde - f_montant) &gt; v_compte.SeuilDebit /*and compte.Etat != 'desactiver'*/ THEN v_solde := v_compte.Solde - f_montant; UPDATE compte SET Solde = Solde - f_montant where f_numcomp = compte.NumeroCompte; else dbms_output.put_line('solde insufusant!'); end if; return(v_solde); END Retrait; / </code></pre> <p>This is what I get:</p> <blockquote> <p>Rapport d'erreur -</p> <p>ORA-06550: Ligne 9, colonne 16 :<br /> PLS-00103: Symbole &quot;(&quot; rencontré à la place d'un des symboles suivants :</p> <p>. ;<br /> 06550. 00000 - &quot;line %s, column %s:\n%s&quot;<br /> *Cause: Usually a PL/SQL compilation error.<br /> *Action:</p> </blockquote> <p>I'm new here; I read some articles here but still didn't find the error</p>
[ { "answer_id": 74513289, "author": "Liyun Zhang - MSFT", "author_id": 17455524, "author_profile": "https://Stackoverflow.com/users/17455524", "pm_score": 1, "selected": true, "text": "this.month = month + 1; eventdatesetText.EditText.Text = this.month + \"/\" + dayOfMonth + \"/\" + year; eventdatesetText.EditText.Text = (month+1) + \"/\" + dayOfMonth + \"/\" + year;" }, { "answer_id": 74513661, "author": "Flater", "author_id": 952296, "author_profile": "https://Stackoverflow.com/users/952296", "pm_score": 0, "selected": false, "text": "eventdatesetText.EditText.Text = this.month month month this.month +1 this.month DatePickerDialog datePickerDialog = new DatePickerDialog(this.Activity, this, year, month, day);\n datePickerDialog.Show();\n\n\nthis.year = year;\nthis.month = month + 1;\nthis.day = dayOfMonth;\neventdatesetText.EditText.Text = this.month + \"/\" + this.day + \"/\" + this.year;\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15259670/" ]
74,503,680
<p>I extracted data from an API using Airflow. The data is extracted from the API and saved on cloud storage in JSON format.</p> <p>The next step is to insert the data into an SQL DB. I have a few questions:</p> <ul> <li>Should I do it on Airflow or using another ETL like AWS Glue/Azure Data factory?</li> <li>How to insert the data into the SQL DB? I google &quot;how to insert data into SQL DB using python&quot;?. I found a solution that loops all over JSON records and inserts the data 1 record at a time. It is not very efficient. Any other way I can do it?</li> <li>Any other recommendations and best practices on how to insert the JSON data into the SQL server?</li> </ul> <p>I haven't decided on a specific DB so far, so feel free to pick the one you think fits best.</p> <p>thank you!</p>
[ { "answer_id": 74513289, "author": "Liyun Zhang - MSFT", "author_id": 17455524, "author_profile": "https://Stackoverflow.com/users/17455524", "pm_score": 1, "selected": true, "text": "this.month = month + 1; eventdatesetText.EditText.Text = this.month + \"/\" + dayOfMonth + \"/\" + year; eventdatesetText.EditText.Text = (month+1) + \"/\" + dayOfMonth + \"/\" + year;" }, { "answer_id": 74513661, "author": "Flater", "author_id": 952296, "author_profile": "https://Stackoverflow.com/users/952296", "pm_score": 0, "selected": false, "text": "eventdatesetText.EditText.Text = this.month month month this.month +1 this.month DatePickerDialog datePickerDialog = new DatePickerDialog(this.Activity, this, year, month, day);\n datePickerDialog.Show();\n\n\nthis.year = year;\nthis.month = month + 1;\nthis.day = dayOfMonth;\neventdatesetText.EditText.Text = this.month + \"/\" + this.day + \"/\" + this.year;\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11254743/" ]
74,503,686
<p>I am experimenting with colorized text output to the console in c. I know that you are able to change the color of entire printf statements, but I was wondering if I am able to change the text color of individual characters within a printf statement. In summary, I would like to be able to print out &quot;asdf&quot; with the a being red, the s being green, the d being blue, and the f being orange. Thank you in advance.</p>
[ { "answer_id": 74503897, "author": "RMEM", "author_id": 18945783, "author_profile": "https://Stackoverflow.com/users/18945783", "pm_score": 0, "selected": false, "text": "printf" }, { "answer_id": 74504132, "author": "chrslg", "author_id": 20037042, "author_profile": "https://Stackoverflow.com/users/20037042", "pm_score": 1, "selected": false, "text": "printf(\"\\033[31m\");\n printf(\"\\033[m\");\n printf(\"\\033[31ma\\033[32ms\\033[34md\\033[33mf\\033[m\\n\");\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18945783/" ]
74,503,697
<p>Out of all the months in the year, I need to code the month with largest total balance (it's June as all together June has the biggest &quot;amount&quot; value)</p> <pre class="lang-py prettyprint-override"><code>lst = [ {'account': 'x\\*', 'amount': 300, 'day': 3, 'month': 'June'}, {'account': 'y\\*', 'amount': 550, 'day': 9, 'month': 'May'}, {'account': 'z\\*', 'amount': -200, 'day': 21, 'month': 'June'}, {'account': 'g', 'amount': 80, 'day': 10, 'month': 'May'}, {'account': 'x\\*', 'amount': 30, 'day': 16, 'month': 'August'}, {'account': 'x\\*', 'amount': 100, 'day': 5, 'month': 'June'}, ] </code></pre> <p>The problem is that both &quot;amount&quot; and the name of the months are values.</p> <p>I tried to find the total for each month, but I need to use for loop to code the highest month &quot;amount&quot;.</p> <p>My attempt:</p> <pre class="lang-py prettyprint-override"><code>get_sum = lambda my_dict, month: sum(d['amount'] for d in my_list if d['month'] == month) total_June = get_sum(my_list,'June') total_August = get_sum(my_list),'August') </code></pre>
[ { "answer_id": 74503987, "author": "Pierre D", "author_id": 758174, "author_profile": "https://Stackoverflow.com/users/758174", "pm_score": 0, "selected": false, "text": "from itertools import groupby\nfrom operator import itemgetter\n\nmo_total = {\n k: sum([d.get('amount', 0) for d in v])\n for k, v in groupby(sorted(lst, key=itemgetter('month')), key=itemgetter('month'))\n}\n>>> mo_total\n{'August': 30, 'June': 200, 'May': 630}\n\n>>> max(mo_total.items(), key=lambda kv: kv[1])\n('May', 630)\n itemgetter bymonth = lambda d: d.get('month')\nmo_total = {\n k: sum([d.get('amount', 0) for d in v])\n for k, v in groupby(sorted(lst, key=bymonth), key=bymonth)\n}\n defaultdict from collections import defaultdict\n\ntot = defaultdict(int)\n\nfor d in lst:\n tot[d['month']] += d.get('amount', 0)\n>>> tot\ndefaultdict(int, {'June': 200, 'May': 630, 'August': 30})\n\n>>> max(tot, key=lambda k: tot[k])\n'May'\n" }, { "answer_id": 74504172, "author": "ferreiradev", "author_id": 5721867, "author_profile": "https://Stackoverflow.com/users/5721867", "pm_score": 1, "selected": false, "text": "import pandas as pd\n\nlst = [\n {'account': 'x\\\\*', 'amount': 300, 'day': 3, 'month': 'June'},\n {'account': 'y\\\\*', 'amount': 550, 'day': 9, 'month': 'May'},\n {'account': 'z\\\\*', 'amount': -200, 'day': 21, 'month': 'June'},\n {'account': 'g', 'amount': 80, 'day': 10, 'month': 'May'},\n {'account': 'x\\\\*', 'amount': 30, 'day': 16, 'month': 'August'},\n {'account': 'x\\\\*', 'amount': 100, 'day': 5, 'month': 'June'},\n]\n\n# convert list of dictionaries to dataframe\ndf = pd.DataFrame(lst)\n\n# Get the row / series that has max amount. \n# idxmax returns an index for loc.\nmax_series_by_amount = df.loc[df['amount'].idxmax(axis=\"index\")]\n\n# Get only month and amount in a plain list\nprint(max_series_by_amount[[\"month\", \"amount\"]].tolist())\n['May', 550]\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20544158/" ]
74,503,739
<p>I am trying to create a contact info txt file with python</p> <pre><code>what_you_want = input(&quot;Do you want to add or remove (if add write add), (if remove write remove): &quot;) if what_you_want == &quot;remove&quot;: what_you_want_remove = input(&quot;What contact number you want to remove: &quot;) with open(&quot;All Contact.txt&quot;, &quot;r&quot;) as f: contact_info = f.readlines() if what_you_want_remove in contact_info: with open(&quot;All Contact.txt&quot;, &quot;a&quot;) as f: if what_you_want_remove in contact_info: new_contact_info = contact_info.replace(what_you_want_remove, &quot;&quot;) f.write(new_contact_info) </code></pre> <p>I couldn't find a way to directly remove something from a txt file so I want to put it into a list and then write it back to txt file but when I try to use remove command it doesn't work.</p> <p>I want to ask if there is a way to remove something from a text file directly.</p>
[ { "answer_id": 74503987, "author": "Pierre D", "author_id": 758174, "author_profile": "https://Stackoverflow.com/users/758174", "pm_score": 0, "selected": false, "text": "from itertools import groupby\nfrom operator import itemgetter\n\nmo_total = {\n k: sum([d.get('amount', 0) for d in v])\n for k, v in groupby(sorted(lst, key=itemgetter('month')), key=itemgetter('month'))\n}\n>>> mo_total\n{'August': 30, 'June': 200, 'May': 630}\n\n>>> max(mo_total.items(), key=lambda kv: kv[1])\n('May', 630)\n itemgetter bymonth = lambda d: d.get('month')\nmo_total = {\n k: sum([d.get('amount', 0) for d in v])\n for k, v in groupby(sorted(lst, key=bymonth), key=bymonth)\n}\n defaultdict from collections import defaultdict\n\ntot = defaultdict(int)\n\nfor d in lst:\n tot[d['month']] += d.get('amount', 0)\n>>> tot\ndefaultdict(int, {'June': 200, 'May': 630, 'August': 30})\n\n>>> max(tot, key=lambda k: tot[k])\n'May'\n" }, { "answer_id": 74504172, "author": "ferreiradev", "author_id": 5721867, "author_profile": "https://Stackoverflow.com/users/5721867", "pm_score": 1, "selected": false, "text": "import pandas as pd\n\nlst = [\n {'account': 'x\\\\*', 'amount': 300, 'day': 3, 'month': 'June'},\n {'account': 'y\\\\*', 'amount': 550, 'day': 9, 'month': 'May'},\n {'account': 'z\\\\*', 'amount': -200, 'day': 21, 'month': 'June'},\n {'account': 'g', 'amount': 80, 'day': 10, 'month': 'May'},\n {'account': 'x\\\\*', 'amount': 30, 'day': 16, 'month': 'August'},\n {'account': 'x\\\\*', 'amount': 100, 'day': 5, 'month': 'June'},\n]\n\n# convert list of dictionaries to dataframe\ndf = pd.DataFrame(lst)\n\n# Get the row / series that has max amount. \n# idxmax returns an index for loc.\nmax_series_by_amount = df.loc[df['amount'].idxmax(axis=\"index\")]\n\n# Get only month and amount in a plain list\nprint(max_series_by_amount[[\"month\", \"amount\"]].tolist())\n['May', 550]\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20550454/" ]
74,503,746
<p>How to convert e.g. <code>&amp;[u64]</code> to <code>&amp;[u8]</code>? I contend that it's safe to do with this method (edited to make harder to misuse):</p> <pre><code>use num_traits::PrimInt; /// Reinterpret a slice of T as a slice of bytes without copying. /// Only use with simple copy types like integers, floats, bools, etc. Don't use with structs or enums. pub fn get_bytes&lt;T: PrimInt&gt;(array: &amp;[T]) -&gt; &amp;[u8] { // Add some checks to try and catch unsound use debug_assert!(size_of::&lt;T&gt;() &lt;= 16); debug_assert!(size_of::&lt;T&gt;().is_power_of_two()); debug_assert_eq!(size_of::&lt;T&gt;(), align_of::&lt;T&gt;()); // Safety: &amp;[u64] can be safely converted to &amp;[u8] // (so why doesn't rust have a safe method for this?) unsafe { std::slice::from_raw_parts(array.as_ptr() as *const u8, array.len() * std::mem::size_of::&lt;T&gt;()) } } </code></pre> <p><a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2021&amp;gist=8f30b03d44aadd6c720057337ac41236" rel="nofollow noreferrer">https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2021&amp;gist=8f30b03d44aadd6c720057337ac41236</a></p> <p>That's how it would be written in C or C++. It's not safe to do the inverse conversion, because the alignment of the types differs. But casting down into a slice of bytes works, and it's why you can cast everything to <code>char*</code> in C.</p> <p>Does Rust expose a safe method to do this? I'm currently just using the code above, but it'd be nice to get rid of one more unsafe block if I can. If not, why not? Is it unsafe for some reason I haven't considered?</p>
[ { "answer_id": 74503976, "author": "cafce25", "author_id": 442760, "author_profile": "https://Stackoverflow.com/users/442760", "pm_score": 0, "selected": false, "text": "#[derive(Debug, Clone, Copy)]\nstruct Thingy {\n a: u32,\n b: u16,\n}\n/// Reinterpret a slice of T as a slice of bytes without copying.\n/// Only use with simple copy types like integers, floats, bools, etc. Don't use with structs or enums.\npub fn get_bytes<T: Copy>(array: &[T]) -> &[u8] {\n // Safety: &[u64] can be safely converted to &[u8]\n // (so why doesn't rust have a safe method for this?)\n unsafe { std::slice::from_raw_parts(array.as_ptr() as *const u8, array.len() * std::mem::size_of::<T>()) }\n}\n\nfn main() {\n let a = [Thingy {\n a: 0xca_fc_e2_50,\n b: 0x12_34,\n }, Thingy {\n a: 0x98_76_54_32,\n b: 0xca_fc,\n }];\n let b: &[u8] = get_bytes(&a);\n println!(\"{:?}\", b);\n // [80, 226, 252, 202, 52, 18, 0, 0, 50, 84, 118, 152, 252, 202, 0, 0]\n}\n Thingy unsafe" }, { "answer_id": 74504906, "author": "Chayim Friedman", "author_id": 7884305, "author_profile": "https://Stackoverflow.com/users/7884305", "pm_score": 3, "selected": true, "text": "bytemuck cast_slice() pub fn get_bytes<T: bytemuck::NoUninit>(array: &[T]) -> &[u8] {\n bytemuck::cast_slice(array)\n}\n uninit u8 bytemuck::cast_slice() NoUninit #[derive(NoUninit)]" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/152580/" ]
74,503,788
<p>I try to adapt the this <a href="https://github.com/tensorflow/agents/blob/635af30a6365ec963823d4623f14df25fcefaadd/tf_agents/experimental/examples/dqn/mnih15/dqn_train_eval_atari.py" rel="nofollow noreferrer">tf-agents actor&lt;-&gt;learner</a> DQN Atari Pong example to my windows machine using a <a href="https://www.tensorflow.org/agents/api_docs/python/tf_agents/replay_buffers/TFUniformReplayBuffer" rel="nofollow noreferrer">TFUniformReplayBuffer</a> instead of the <a href="https://www.tensorflow.org/agents/api_docs/python/tf_agents/replay_buffers/ReverbReplayBuffer" rel="nofollow noreferrer">ReverbReplayBuffer</a> which only works on linux machine but I face a dimensional issue.</p> <pre><code> [...] ---&gt; 67 init_buffer_actor.run() [...] InvalidArgumentError: {{function_node __wrapped__ResourceScatterUpdate_device_/job:localhost/replica:0/task:0/device:CPU:0}} Must have updates.shape = indices.shape + params.shape[1:] or updates.shape = [], got updates.shape [84,84,4], indices.shape [1], params.shape [1000,84,84,4] [Op:ResourceScatterUpdate] </code></pre> <p>The problem is as follows: The tf actor tries to access the replay buffer and initialize the it with a certain number random samples of shape (84,84,4) according to this <a href="https://web.stanford.edu/class/psych209/Readings/MnihEtAlHassibis15NatureControlDeepRL.pdf" rel="nofollow noreferrer">deepmind paper</a> but the replay buffer requires samples of shape (1,84,84,4).</p> <p>My code is as follows:</p> <pre><code> def train_pong( env_name='ALE/Pong-v5', initial_collect_steps=50000, max_episode_frames_collect=50000, batch_size=32, learning_rate=0.00025, replay_capacity=1000): # load atari environment collect_env = suite_atari.load( env_name, max_episode_steps=max_episode_frames_collect, gym_env_wrappers=suite_atari.DEFAULT_ATARI_GYM_WRAPPERS_WITH_STACKING) # create tensor specs observation_tensor_spec, action_tensor_spec, time_step_tensor_spec = ( spec_utils.get_tensor_specs(collect_env)) # create training util train_step = train_utils.create_train_step() # calculate no. of actions num_actions = action_tensor_spec.maximum - action_tensor_spec.minimum + 1 # create agent agent = dqn_agent.DqnAgent( time_step_tensor_spec, action_tensor_spec, q_network=create_DL_q_network(num_actions), optimizer=tf.compat.v1.train.RMSPropOptimizer(learning_rate=learning_rate)) # create uniform replay buffer replay_buffer = tf_uniform_replay_buffer.TFUniformReplayBuffer( data_spec=agent.collect_data_spec, batch_size=1, max_length=replay_capacity) # observer of replay buffer rb_observer = replay_buffer.add_batch # create batch dataset dataset = replay_buffer.as_dataset( sample_batch_size=batch_size, num_steps = 2, single_deterministic_pass=False).prefetch(3) # create callable function for actor experience_dataset_fn = lambda: dataset # create random policy for buffer init random_policy = random_py_policy.RandomPyPolicy(collect_env.time_step_spec(), collect_env.action_spec()) # create initalizer init_buffer_actor = actor.Actor( collect_env, random_policy, train_step, steps_per_run=initial_collect_steps, observers=[replay_buffer.add_batch]) # initialize buffer with random samples init_buffer_actor.run() </code></pre> <p>(The approach is using the OpenAI Gym Env as well as the corresponding wrapper functions)</p> <p>I worked with <em>keras-rl2</em> and <em>tf-agents without actor&lt;-&gt;learner</em> for other atari games to create the DQN and both worked quite well afer a some adaptions. I guess my current code will also work after a few adaptions in the tf-agent libary functions, but that would obviate the purpose of the libary.</p> <p>My current assumption: <strong>The actor&lt;-&gt;learner methods are not able to work with the TFUniformReplayBuffer (as I expect them to), due to the missing support of the TFPyEnvironment</strong> - or I still have some knowledge shortcomings regarding this tf-agents approach</p> <p>Previous (successful) attempt:</p> <pre><code> from tf_agents.environments.tf_py_environment import TFPyEnvironment tf_collect_env = TFPyEnvironment(collect_env) init_driver = DynamicStepDriver( tf_collect_env, random_policy, observers=[replay_buffer.add_batch], num_steps=200) init_driver.run() </code></pre> <p>I would be very grateful if someone could explain me what I'm overseeing here.</p>
[ { "answer_id": 74503976, "author": "cafce25", "author_id": 442760, "author_profile": "https://Stackoverflow.com/users/442760", "pm_score": 0, "selected": false, "text": "#[derive(Debug, Clone, Copy)]\nstruct Thingy {\n a: u32,\n b: u16,\n}\n/// Reinterpret a slice of T as a slice of bytes without copying.\n/// Only use with simple copy types like integers, floats, bools, etc. Don't use with structs or enums.\npub fn get_bytes<T: Copy>(array: &[T]) -> &[u8] {\n // Safety: &[u64] can be safely converted to &[u8]\n // (so why doesn't rust have a safe method for this?)\n unsafe { std::slice::from_raw_parts(array.as_ptr() as *const u8, array.len() * std::mem::size_of::<T>()) }\n}\n\nfn main() {\n let a = [Thingy {\n a: 0xca_fc_e2_50,\n b: 0x12_34,\n }, Thingy {\n a: 0x98_76_54_32,\n b: 0xca_fc,\n }];\n let b: &[u8] = get_bytes(&a);\n println!(\"{:?}\", b);\n // [80, 226, 252, 202, 52, 18, 0, 0, 50, 84, 118, 152, 252, 202, 0, 0]\n}\n Thingy unsafe" }, { "answer_id": 74504906, "author": "Chayim Friedman", "author_id": 7884305, "author_profile": "https://Stackoverflow.com/users/7884305", "pm_score": 3, "selected": true, "text": "bytemuck cast_slice() pub fn get_bytes<T: bytemuck::NoUninit>(array: &[T]) -> &[u8] {\n bytemuck::cast_slice(array)\n}\n uninit u8 bytemuck::cast_slice() NoUninit #[derive(NoUninit)]" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20549040/" ]
74,503,814
<p>I need to create a new file name test.sh. I need to write those lines with echo or somethings else but cant open new file manually and write it. That is, I have to write down some things in the bash such a way that the following file is created:</p> <pre><code>TEST_VALUE=$1 if [[cat data | grep $TEST_VALUE]]; then exit 1 fi exit 0 </code></pre> <p>But, when I do that by echo the result is:</p> <pre><code>TEST_VALUE= if [[]]; then exit 1 fi exit 0 </code></pre> <p>I need the file as I write it with $1 and not the argument and with the grep. I tried to grep each row but it is doing the command and not copied it as I want. How do I do it? Thank You</p>
[ { "answer_id": 74503967, "author": "mbofos01", "author_id": 17790231, "author_profile": "https://Stackoverflow.com/users/17790231", "pm_score": 0, "selected": false, "text": "echo 'TEST_VALUE=$1 \nif [[cat data | grep $TEST_VALUE]]; then\nexit 1\nfi\nexit 0' > test.sh\n" }, { "answer_id": 74503979, "author": "Charles Duffy", "author_id": 14122, "author_profile": "https://Stackoverflow.com/users/14122", "pm_score": 2, "selected": true, "text": "cat >file <<'EOF'\nTEST_VALUE=$1\nif [[cat data | grep $TEST_VALUE]]; then\nexit 1\nfi\nexit 0\nEOF\n cat >file <<'EOF'\n#!/bin/sh\ntest_value=$1\n! grep -q -e \"$test_value\" <data\nEOF\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17696754/" ]
74,503,898
<p>I need to replace two strings using regular expression value replacement so the resulting string is <code>$?tlang=es&amp;text=Hello world</code>, so I didn't know to use here <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace" rel="nofollow noreferrer">String.prototype.replace()</a>.</p> <pre><code>const value = &quot;Hello world&quot; const queryString = &quot;?tlang=es&amp;text=$1&quot; </code></pre> <p>In this scenary, <code>value</code> and <code>queryString</code> are hard-coded, but in &quot;real life&quot; it should be the result of a regular expression group capturing like <code>line.match(/msgid \&quot;(.*)\&quot;/)</code> where <code>line</code> is an iterated text line and <code>queryString</code> is what the user submitted.</p> <p>I thought I just could do this, but maybe it's too much effort where there is a better solution (that I couldn't find):</p> <pre><code>const line = &quot;Full name: John Doe&quot; // text input const sourcePattern = /Full name: (.*) (.*)/ // user input let queryString = 'name=$1&amp;lname=$2' // user input const matches = line.match(sourcePattern) matches.splice(0, 1) for (let i = 0; i &lt; matches.length; i++) { queryString = queryString.replace(`\$${i+1}`, matches[i]) } </code></pre> <p>Any ideas?</p>
[ { "answer_id": 74503977, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 2, "selected": false, "text": "const line = \"Full name: John Doe\" // text input\nconst sourcePattern = /Full name: (.*) (.*)/ // user input\nlet queryString = 'name=$1&lname=$2' // user input\nconst [_, ...matches] = line.match(sourcePattern)\n\nconsole.log(queryString.split(/\\$\\d+/)\n .map((p,i)=>`${p}${matches[i]??''}`).join(''))" }, { "answer_id": 74503986, "author": "Jared Smith", "author_id": 3757232, "author_profile": "https://Stackoverflow.com/users/3757232", "pm_score": 3, "selected": true, "text": "const entries = [...new URLSearchParams(queryString).entries()]\n\nif (matches.length !== entries.length) {\n // handle error\n}\n\nconst replaced = entries.reduce((params, [key], index) => {\n params.append(key, matches[index]);\n return params;\n}, new URLSearchParams());\n toString()" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6421288/" ]
74,503,923
<p>I am looking to redirect my user to <code>login</code> page, if they have not logged in.</p> <p>I initally looked at the decorator <code>@login_required(login_url='/accounts/login/')</code>.</p> <p>But this is not ideal, for 2 reasons: first I want this to apply to all views. Also the decorator returns an error message when I try to login with allauth.</p> <p>I am sure this is solvable, but I am looking for a solution that could apply to all views.</p> <p>I found something using <code>authmiddleware</code>(doc: <a href="https://pypi.org/project/django-authmiddleware/" rel="nofollow noreferrer">https://pypi.org/project/django-authmiddleware/</a>). However the code doesn't not seem to be responsive, in the sense nothing is happening and the logs on the console don't seem to pick up anything.</p> <p>Can someone see what I am doing wrong?</p> <p><strong>base.py</strong></p> <pre><code>MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'AuthMiddleware.middleware.AuthRequiredMiddleware', ] AUTH_SETTINGS = { &quot;LOGIN_URL&quot; : &quot;login_user&quot;, &quot;DEFAULT_REDIRECT_URL&quot; : None, &quot;REDIRECT_AFTER_LOGIN&quot; : False, } </code></pre> <p><strong>views.py</strong></p> <pre><code>from django.shortcuts import render, redirect, reverse from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth import authenticate, login, logout, get_user_model from django.urls import reverse def list_event(request): #ADDED FOLLOWING REQUEST IN COMMENTS event_list = Event.objects.all return render(request, 'main/list_event.html',{'event_list':event_list}) class AuthRequiredMiddleware(object): def process_request(self, request): if not request.user.is_authenticated(): return HttpResponseRedirect(reverse('login_user')) return None </code></pre>
[ { "answer_id": 74504199, "author": "Dino Corry", "author_id": 20535274, "author_profile": "https://Stackoverflow.com/users/20535274", "pm_score": 0, "selected": false, "text": "return redirect('%s?next=%s' % (settings.login_user, request.path))' \n HttpResponse" }, { "answer_id": 74512029, "author": "PhilM", "author_id": 19003861, "author_profile": "https://Stackoverflow.com/users/19003861", "pm_score": 2, "selected": true, "text": "MIDDLEWARE = [\n\n '[yourappname].middleware.LoginRequiredMiddleware', \n]\n\nLOGIN_EXEMPT_URLS =( #<-- I am using allauth, so left some examples here)\n r'logout',\n r'register_user',\n r'accounts/google/login/',\n r'accounts/social/signup/',\n r'accounts/facebook/login/',\n \n)\n import re\nfrom django.conf import settings\nfrom django.shortcuts import redirect\n\nEXEMPT_URLS = [re.compile(settings.LOGIN_URL.lstrip('/'))]\nif hasattr(settings, 'LOGIN_EXEMPT_URLS'):\n EXEMPT_URLS += [re.compile(url) for url in settings.LOGIN_EXEMPT_URLS]\n\nclass LoginRequiredMiddleware:\n pass\n def __init__(self, get_response):\n self.get_response = get_response\n \n def __call__ (self, request):\n response = self.get_response(request)\n return response\n \n def process_view(self, request, view_func, view_args, view_kwargs):\n assert hasattr(request,'user')\n path = request.path_info.lstrip('/')\n print(path)\n \n if not request.user.is_authenticated:\n if not any(url.match(path) for url in EXEMPT_URLS):\n return redirect(settings.LOGIN_URL)\n \n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19003861/" ]
74,503,935
<p>Firstly apologies as I am fairly new to fetching from an API and I am trying to learn.</p> <p>I need to fetch &quot;name&quot; , &quot;age&quot; and &quot;phone&quot; from &quot;id&quot; 1 from &quot;is&quot; and display it when click on button. This is my javascript-fetch-api.js file:</p> <p>I'm not sure how to fetch only from id 1 &quot;is&quot;</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const events = [{ "id": 1, "language": { "is": { "name": "Ali Sakaroğlu", "age": 27, "phone": "05368218685", "tags": [ "Gallery", "STAK", "Gallery Julius", "mom", "young", "lorem", "ipsum", "show", "born", "worm", "dorm", "norm", "dlla" ] }, "en": { "name": "Ali Sakaroğlus", "age": 27, "phone": "05368218685", "tags": [ "Gallery", "STAK", "Gallery Julius", "mom", "young", "lorem", "ipsum", "show", "born", "worm", "dorm", "norm", "dlla" ] } } }] let output = '&lt;ul&gt;'; events.forEach((event) =&gt; { output += `&lt;li&gt;${event.id}) Name: ${event.name} - Age: ${event.age} - Phone: ${event.phone} &lt;/li&gt; `; }); output += '&lt;/ul&gt; &lt;hr&gt;'; document.getElementById('output').innerHTML += output;</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="output"&gt;&lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74503978, "author": "Georgemff", "author_id": 9716786, "author_profile": "https://Stackoverflow.com/users/9716786", "pm_score": 3, "selected": true, "text": " event.language.is.age\n event.language.is.name\n event.language.is.phone\n" }, { "answer_id": 74503985, "author": "Peter Thoeny", "author_id": 7475450, "author_profile": "https://Stackoverflow.com/users/7475450", "pm_score": 0, "selected": false, "text": "name is output += `<li>${event.id}) Name: ${event.is.name} - Age: ${event.is.age} - Phone: ${event.is.phone} </li> `;\n" }, { "answer_id": 74504188, "author": "BizOAlly", "author_id": 19128679, "author_profile": "https://Stackoverflow.com/users/19128679", "pm_score": 0, "selected": false, "text": "live code: https://jsfiddle.net/cu2q9dzm/\n function getJson() {\n fetch('https://raw.githubusercontent.com/FEND16/movie-json-data/master/json/movies-in-theaters.json').then((response) => response.json())\n .then((data) => data.forEach(data => {\n console.log(\"id: \", data.id, \"year: \", data.year, \"title: \", data.title);\n }));\n}\ngetJson();" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20550608/" ]
74,503,971
<p>I have a struct and a struct array similar to this:</p> <pre><code>struct point{ double x; double y; char name[10]; }; struct point points[1000]; </code></pre> <p>I created an algorithm that calculates the distances between all the points and prints the pair with the smallest distance, like this:</p> <pre><code> int count = 0; for (int i = 0; i &lt; 1000; i++){ for(int j = 0; j &lt; 1000; j++){ if(i != j){ double distance = sqrt(pow(points[i].x - points[j].x, 2) + pow(points[i].y - points[j].y, 2)); if(distance == min){ printf(&quot;%s - %s\n&quot;, points[i].name, points[j].name); count++; } } } } </code></pre> <p>If there are multiple pairs with the same distance, it prints all of them, <strong>but it prints them TWICE</strong> (the second time in a different order), what would be an ideal logical gate in the printing loop to prevent the structures with the same distance being printed twice?</p>
[ { "answer_id": 74504007, "author": "White Wizard", "author_id": 9366059, "author_profile": "https://Stackoverflow.com/users/9366059", "pm_score": 1, "selected": false, "text": "for(int i = 0; i < 1000; i++){\n struct point a = points[i]\n for(int j = 0; j < 1000; j++){\n struct point b = points[j]\n }\n}\n for(int i = 0; i < 999; i++){\n struct point a = points[i]\n for(int j = i; j < 1000; j++){\n struct point b = points[j]\n }\n}\n" }, { "answer_id": 74504068, "author": "klutt", "author_id": 6699433, "author_profile": "https://Stackoverflow.com/users/6699433", "pm_score": 3, "selected": true, "text": "for (int i = 0; i < 999; i++){\n for(int j = i+1; j < 1000; j++){\n double distance = sqrt(pow(points[i].x - points[j].x, 2) + pow(points[i].y - points[j].y, 2));\n if(distance == min){\n printf(\"%s - %s\\n\", points[i].name, points[j].name);\n count++;\n }\n }\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74503971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18361723/" ]
74,504,021
<p>Recently I have had some problems regarding basic npm commands.</p> <p>I have the following package.json:</p> <pre><code>{ &quot;name&quot;: &quot;bundle&quot;, &quot;version&quot;: &quot;1.0.0&quot;, &quot;description&quot;: &quot;&quot;, &quot;main&quot;: &quot;webpack.config.js&quot;, &quot;author&quot;: &quot;&quot;, &quot;license&quot;: &quot;ISC&quot;, &quot;scripts&quot;: { &quot;install&quot;: &quot;npm i&quot;, &quot;bundle&quot;: &quot;webpack&quot;, &quot;watch&quot;: &quot;webpack --mode=development --watch&quot; }, &quot;devDependencies&quot;: { &quot;@babel/plugin-transform-runtime&quot;: &quot;^7.19.6&quot;, &quot;@babel/preset-env&quot;: &quot;^7.20.2&quot;, &quot;@babel/preset-react&quot;: &quot;^7.18.6&quot;, &quot;@babel/preset-typescript&quot;: &quot;^7.18.6&quot;, &quot;@types/react&quot;: &quot;^18.0.25&quot;, &quot;@types/react-dom&quot;: &quot;^18.0.8&quot;, &quot;babel-loader&quot;: &quot;^9.1.0&quot;, &quot;css-loader&quot;: &quot;^6.7.1&quot;, &quot;html-webpack-plugin&quot;: &quot;^5.5.0&quot;, &quot;sass&quot;: &quot;^1.56.0&quot;, &quot;sass-loader&quot;: &quot;^13.1.0&quot;, &quot;source-map-loader&quot;: &quot;^4.0.1&quot;, &quot;style-loader&quot;: &quot;^3.3.1&quot;, &quot;ts-loader&quot;: &quot;^9.4.1&quot;, &quot;typescript&quot;: &quot;^4.8.4&quot;, &quot;webpack&quot;: &quot;^5.74.0&quot;, &quot;webpack-cli&quot;: &quot;^4.10.0&quot; }, &quot;dependencies&quot;: { &quot;react&quot;: &quot;^18.2.0&quot;, &quot;react-dom&quot;: &quot;^18.2.0&quot; } } </code></pre> <p>I get the following when i try to install:</p> <pre><code> &gt; bundle@1.0.0 install &gt; npm i &gt; bundle@1.0.0 install &gt; npm i &gt; bundle@1.0.0 install &gt; npm i &gt; bundle@1.0.0 install &gt; npm i &gt; bundle@1.0.0 install &gt; npm i &gt; bundle@1.0.0 install &gt; npm i &gt; bundle@1.0.0 install &gt; npm i &gt; bundle@1.0.0 install &gt; npm i 'npm' is not recognized as an internal or external command, operable program or batch file. npm ERR! code 1 npm ERR! path C:\Users\Niklas\Desktop\Project\Learn4Fun\Web\wwwroot npm ERR! command failed npm ERR! command C:\Windows\system32\cmd.exe /d /s /c npm i npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\Niklas\AppData\Local\npm-cache\_logs\2022-11-19T21_35_56_965Z-debug.log npm ERR! code 1 npm ERR! path C:\Users\Niklas\Desktop\Project\Learn4Fun\Web\wwwroot npm ERR! command failed npm ERR! command C:\Windows\system32\cmd.exe /d /s /c npm i npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\Niklas\AppData\Local\npm-cache\_logs\2022-11-19T21_35_56_990Z-debug.log npm ERR! code 1 npm ERR! path C:\Users\Niklas\Desktop\Project\Learn4Fun\Web\wwwroot npm ERR! command failed npm ERR! command C:\Windows\system32\cmd.exe /d /s /c npm i npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\Niklas\AppData\Local\npm-cache\_logs\2022-11-19T21_35_57_010Z-debug.log npm ERR! code 1 npm ERR! path C:\Users\Niklas\Desktop\Project\Learn4Fun\Web\wwwroot npm ERR! command failed npm ERR! command C:\Windows\system32\cmd.exe /d /s /c npm i npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\Niklas\AppData\Local\npm-cache\_logs\2022-11-19T21_35_57_032Z-debug.log npm ERR! code 1 npm ERR! path C:\Users\Niklas\Desktop\Project\Learn4Fun\Web\wwwroot npm ERR! command failed npm ERR! command C:\Windows\system32\cmd.exe /d /s /c npm i </code></pre> <p>One of the log files. (this is when it runs from VS 2022</p> <pre><code>0 verbose cli [ 0 verbose cli 'C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\MSBuild\\Microsoft\\VisualStudio\\NodeJs\\node.exe', 0 verbose cli 'C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\MSBuild\\Microsoft\\VisualStudio\\NodeJs\\node_modules\\npm\\bin\\npm-cli.js', 0 verbose cli 'prefix', 0 verbose cli '-g' 0 verbose cli ] 1 info using npm@8.3.1 2 info using node@v16.14.0 3 timing npm:load:whichnode Completed in 0ms 4 timing config:load:defaults Completed in 1ms 5 timing config:load:file:C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Microsoft\VisualStudio\NodeJs\node_modules\npm\npmrc Completed in 1ms 6 timing config:load:builtin Completed in 1ms 7 timing config:load:cli Completed in 1ms 8 timing config:load:env Completed in 1ms 9 timing config:load:project Completed in 0ms 10 timing config:load:file:C:\Users\Niklas\.npmrc Completed in 0ms 11 timing config:load:user Completed in 0ms 12 timing config:load:file:C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Microsoft\VisualStudio\NodeJs\etc\npmrc Completed in 0ms 13 timing config:load:global Completed in 1ms 14 timing config:load:validate Completed in 0ms 15 timing config:load:credentials Completed in 0ms 16 timing config:load:setEnvs Completed in 1ms 17 timing config:load Completed in 6ms 18 timing npm:load:configload Completed in 6ms 19 timing npm:load:setTitle Completed in 0ms 20 timing config:load:flatten Completed in 2ms 21 timing npm:load:display Completed in 2ms 22 verbose logfile C:\Users\Niklas\AppData\Local\npm-cache\_logs\2022-11-19T21_17_05_361Z-debug-0.log 23 timing npm:load:logFile Completed in 4ms 24 timing npm:load:timers Completed in 0ms 25 timing npm:load:configScope Completed in 0ms 26 timing npm:load Completed in 13ms 27 timing command:prefix Completed in 1ms 28 verbose exit 0 29 timing npm Completed in 171ms 30 info ok </code></pre> <p>I have tried uninstall / re install node/npm (different versions). Removed npm cache. Removed all npm folders on pc. Restarted pc.</p>
[ { "answer_id": 74504007, "author": "White Wizard", "author_id": 9366059, "author_profile": "https://Stackoverflow.com/users/9366059", "pm_score": 1, "selected": false, "text": "for(int i = 0; i < 1000; i++){\n struct point a = points[i]\n for(int j = 0; j < 1000; j++){\n struct point b = points[j]\n }\n}\n for(int i = 0; i < 999; i++){\n struct point a = points[i]\n for(int j = i; j < 1000; j++){\n struct point b = points[j]\n }\n}\n" }, { "answer_id": 74504068, "author": "klutt", "author_id": 6699433, "author_profile": "https://Stackoverflow.com/users/6699433", "pm_score": 3, "selected": true, "text": "for (int i = 0; i < 999; i++){\n for(int j = i+1; j < 1000; j++){\n double distance = sqrt(pow(points[i].x - points[j].x, 2) + pow(points[i].y - points[j].y, 2));\n if(distance == min){\n printf(\"%s - %s\\n\", points[i].name, points[j].name);\n count++;\n }\n }\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14540793/" ]
74,504,032
<p>I have 25-km raster grid and a point. If I plot the point on the raster, it falls ~on the borderof two adjacent raster cells. I don't how to generate a sample data for this specific case but here's a visualisation of what I am taking about.</p> <p><a href="https://i.stack.imgur.com/1uZ9v.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1uZ9v.png" alt="enter image description here" /></a></p> <p>Is there any way I can detect for a group of points how many points are cases like this which could like very close to the border of two adjacent raster cells?</p>
[ { "answer_id": 74504500, "author": "Grzegorz Sapijaszko", "author_id": 17486894, "author_profile": "https://Stackoverflow.com/users/17486894", "pm_score": 0, "selected": false, "text": "library(terra)\n#> terra 1.6.17\nr <- rast(nrows=20, ncols=10, xmin=0, xmax=10, ymin = 0, ymax = 10)\nfor (i in seq_len(nrow(r))) {\n for (j in seq_len(ncol(r))) {\n if(i %% 2 != 0 & j %% 2 != 0) {\n print(paste(i, j))\n r[i,j] <- 1\n }\n }\n}\nfor (i in seq_len(nrow(r))) {\n for (j in seq_len(ncol(r))) {\n if(i %% 2 == 0 & j %% 2 == 0) {\n print(paste(i, j))\n r[i,j] <- 1\n }\n }\n}\n\nterra::plot(r, axes = TRUE)\n\n# a few points\np <- rbind(c(1,1), c(2.3,3), c(3, 4), c(5.5,5.5)) |>\n terra::vect(\"points\")\nterra::plot(p, add = TRUE, pch = 12)\n dim(r)\n#> [1] 20 10 1\nres(r)\n#> [1] 1.0 0.5\n xcoords <- vector(mode=\"list\", length=dim(r)[1]-1)\nfor (i in seq_along(xcoords)) {\n xcoords[[i]] <- as.numeric(ext(r)[1])+i*res(r)[1]\n}\n xx <- geom(p)[,\"x\"]\n\nwhich(xx %in% xcoords)\n#> [1] 1 3\n sf::st_make_grid()" }, { "answer_id": 74505277, "author": "Robert Hijmans", "author_id": 635245, "author_profile": "https://Stackoverflow.com/users/635245", "pm_score": 1, "selected": false, "text": "on_border r x y tolerance on_border <- function(r, x, y, tolerance = sqrt(.Machine$double.eps)) {\n v <- h <- (x >= xmin(r)) & (x <= xmax(r)) & (y >= ymin(r)) & (y <= ymax(r))\n v[v] <- ((x[v] - xmin(r)) %% res(r)[1]) < tolerance\n h[h] <- ((y[h] - ymin(r)) %% res(r)[2]) < tolerance\n h | v\n}\n library(terra)\nr <- rast(nrow=5, ncol=5, xmin=0, xmax=5, ymin=0, ymax=5, vals=1:25)\nx <- c(1, 1.5, 2, 3.5, 4.5)\ny <- c(1, 1.5, 2.5, 5, 5.2)\n\non_border(r, x, y)\n#[1] TRUE FALSE TRUE TRUE FALSE\n\nplot(r); lines(r); points(x,y, xpd=TRUE, pch=20, cex=1.5)\n to_border <- function(r, x, y) {\n i <- (x >= xmin(r)) & (x <= xmax(r)) & (y >= ymin(r)) & (y <= ymax(r))\n d <- rep(NA, length(i))\n d[i] <- (x[i] - xmin(r)) %% res(r)[1]\n d[i] <- pmin(d[i], (y[i] - ymin(r)) %% res(r)[2])\n d\n}\n\nto_border(r, x, y)\n#[1] 0.0 0.5 0.0 0.0 NA\n pts <- vect(cbind(x, y), crs=crs(r))\nrlns <- aggregate(as.lines(r))\nrelate(pts, rlns, \"intersects\")\n# [,1]\n#[1,] TRUE\n#[2,] FALSE\n#[3,] TRUE\n#[4,] TRUE\n#[5,] FALSE\n distance(pts, rlns)\n# [,1]\n#[1,] 0.0\n#[2,] 0.5\n#[3,] 0.0\n#[4,] 0.0\n#[5,] 0.2\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3227302/" ]
74,504,052
<p>My code is as follows, and you can see how it works in <a href="https://codepen.io/rongeegee/pen/BaVJjGO" rel="nofollow noreferrer">https://codepen.io/rongeegee/pen/BaVJjGO</a>:</p> <pre><code>const { useState } = React; const Counter = () =&gt; { const [data, setData] = useState({ displayData: &quot;data_one&quot;, data_one: { text: &quot;&quot; }, data_two:{ text:&quot;&quot; } }) function handleOnChange(event){ event.preventDefault(); const new_data = {...data}; if (event.target.name == &quot;displayData&quot;){ new_data.displayData = event.target.value; setData(new_data); } else{ new_data[event.target.name][&quot;text&quot;] = event.target.value;] setData(new_data); } } return ( &lt;div&gt; &lt;form onChange={handleOnChange}&gt; &lt;select name=&quot;displayData&quot; value={data.displayData}&gt; &lt;option value=&quot;data_one&quot;&gt;data_one&lt;/option&gt; &lt;option value=&quot;data_two&quot;&gt;data_two&lt;/option&gt; &lt;/select&gt; &lt;br/&gt; { data.displayData == &quot;data_one&quot; ? &lt;&gt;data One: &lt;input name=&quot;data_one&quot; defaultValue={data.data_one.text} /&gt;&lt;/&gt; : &lt;&gt;data two: &lt;input name=&quot;data_two&quot; defaultValue={data.data_two.text} /&gt;&lt;/&gt; } &lt;/form&gt; &lt;/div&gt; ) } ReactDOM.render(&lt;Counter /&gt;, document.getElementById('app')) </code></pre> <p>If I type something in the input of data_one, toggle between the values between &quot;data_one&quot; and &quot;data_two&quot;, the data_two input field will have the same value inside. If I change the value in data_one toggle the dropdown to &quot;data_one&quot;, data_one will have the same value again.</p> <p>This shouldn't happen since data_one input uses the value of the text field in data_one field in the data state while data_two input uses the one in data_two field. One should not take the value from another field in the state.</p>
[ { "answer_id": 74504745, "author": "Lord-JulianXLII", "author_id": 19529102, "author_profile": "https://Stackoverflow.com/users/19529102", "pm_score": 2, "selected": true, "text": "input input default Value <input key=\"1\" name=\"data_one\" defaultValue={data.data_one.text} />\n<input key=\"2\" name=\"data_two\" defaultValue={data.data_two.text} />\n" }, { "answer_id": 74507343, "author": "Lord-JulianXLII", "author_id": 19529102, "author_profile": "https://Stackoverflow.com/users/19529102", "pm_score": 0, "selected": false, "text": "data setData else data data const [stateVariable, thisIsTheCallback] = useState(initVal)" }, { "answer_id": 74513867, "author": "Mohammed Shahed", "author_id": 19067773, "author_profile": "https://Stackoverflow.com/users/19067773", "pm_score": 0, "selected": false, "text": "defaultValue <input/> value defaultValue" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6707111/" ]
74,504,058
<p>I want to run npm install in my folder and subfolder without having to run:</p> <ol> <li>npm install</li> <li>cd subfolder</li> <li>npm install</li> </ol> <p>So, in this script I would run two <code>npm install</code> in one single command in my main folder without having to <code>cd</code> into the subfolder. I know theres how to do it by placing a script on <strong>package.json</strong> but I forgot the script now.</p>
[ { "answer_id": 74504111, "author": "Arthur Secondaire", "author_id": 12608183, "author_profile": "https://Stackoverflow.com/users/12608183", "pm_score": 0, "selected": false, "text": "scripts: {\n {\n \"cmdthatyouwant\": \"nmp i; cd folder; npm i\"\n }\n}\n" }, { "answer_id": 74504218, "author": "Rodrigo", "author_id": 20515079, "author_profile": "https://Stackoverflow.com/users/20515079", "pm_score": 1, "selected": false, "text": "\"scripts\": {\n \"yourscript\": \"npm install && cd subfolder && npm install\"\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20515079/" ]
74,504,091
<p>I'm new to coding and im sure that my code is not very efficient but I just want to take the output from a variable and display it in a window. So far when you run it, it just displays the output in the console. I want it do to that and display it on the window. Hope that all makes sense.</p> <pre><code>from tkinter import * root = Tk() root.geometry(&quot;500x500&quot;) def get_input(): year = boxYear.get() p1 = (int(year) // 12) p2 = (int(year) % 12) p3 = (p2 // 4) p4 = (p1 + p2 + p3) days = ['wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'monday', 'tuesday'] p5 = (p4 // 7) if p4 &gt;= 7 and p4 &lt;= 14: p6 = (p4 - 7) elif p4 &gt;= 7 and p4 &gt; 14: p6 = (p4 - 14) else: p6 = (p4) if p6 == 7: p6 = 0 print(days[int(p6)]) # in between these two sections there is a bunch of code that's just math. its not important. # it just spits out a variable which is one of the days of the week #the variable &quot;final&quot; is that day of the week final = int(last) DOTW = (days[int(final)]) outputlabel = Label(topframe, textvariable=DOTW, font=('Arial 20 bold italic')) outputlabel.grid(row=7, columnspan=2, pady=10) #GUI stuff topframe = Frame(root) topframe.pack() bottomframe = Frame(root) bottomframe.pack(side=BOTTOM) printbutton = Button(topframe, text=&quot;Run Algorithm&quot;, command=lambda: get_input()) printbutton.grid(row= 5, columnspan=2, pady=30) boxYear = Entry(topframe) boxMonth = Entry(topframe) boxDay = Entry(topframe) boxYear.grid(row=1, column=1, padx=10, pady=10) boxMonth.grid(row=2, column=1, padx=10, pady=10) boxDay.grid(row=3, column=1, padx=10, pady=10) root.mainloop() </code></pre> <p>I tried to add code to get it to display it in the window but it just doesn't do anything and I can't find a solution anywhere.</p>
[ { "answer_id": 74504111, "author": "Arthur Secondaire", "author_id": 12608183, "author_profile": "https://Stackoverflow.com/users/12608183", "pm_score": 0, "selected": false, "text": "scripts: {\n {\n \"cmdthatyouwant\": \"nmp i; cd folder; npm i\"\n }\n}\n" }, { "answer_id": 74504218, "author": "Rodrigo", "author_id": 20515079, "author_profile": "https://Stackoverflow.com/users/20515079", "pm_score": 1, "selected": false, "text": "\"scripts\": {\n \"yourscript\": \"npm install && cd subfolder && npm install\"\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20543811/" ]
74,504,098
<p>Select all the values of objects in the array. For example,</p> <pre class="lang-js prettyprint-override"><code>tutorials = [{title:a, movie:a}, {title:b, movie:b}, {title:c, movie:c}] =&gt; a b c. </code></pre> <p>I want to find the values of the titles of all objects.</p> <p><code>Tutorials[number].title</code> was attempted, but it was impossible to obtain the value of the title of all objects.</p>
[ { "answer_id": 74504140, "author": "Zohrab Semedzade", "author_id": 18158970, "author_profile": "https://Stackoverflow.com/users/18158970", "pm_score": 1, "selected": false, "text": "let tutorials = [\n {\n title:'a', movie:'a'\n },\n {\n title:'b', movie:'b'\n }, \n {\n title:'c', movie:'c'\n }\n]\n\nfor(let i = 0; i < tutorials.length; i++) {\n console.log(tutorials[i].title);\n}\n" }, { "answer_id": 74507312, "author": "Anshu", "author_id": 18638118, "author_profile": "https://Stackoverflow.com/users/18638118", "pm_score": 1, "selected": true, "text": "let tutorials = [\n {\n title:'a', movie:'a'\n },\n {\n title:'b', movie:'b'\n }, \n {\n title:'c', movie:'c'\n }\n]\n\nconst titles = [];\nfor (tutorial of tutorials) {\n titles.push(tutorial.title)\n}\n" }, { "answer_id": 74507421, "author": "Murtaza Mehmudji", "author_id": 11224314, "author_profile": "https://Stackoverflow.com/users/11224314", "pm_score": 1, "selected": false, "text": "const titles = tutorials.map(t => t.title)\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18704259/" ]
74,504,099
<p>Im trying to lookup the index in two different datframes and return the values.</p> <p>For example, in df1 i would like to lookup in df2 and return the same index and values.</p> <p>DF1 <a href="https://i.stack.imgur.com/qxuLw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qxuLw.png" alt="enter image description here" /></a></p> <p>DF2 <a href="https://i.stack.imgur.com/qjz9N.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qjz9N.png" alt="enter image description here" /></a></p> <p>I would like my result to be like this.</p> <p>RESULTS <a href="https://i.stack.imgur.com/RRqhe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RRqhe.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74504140, "author": "Zohrab Semedzade", "author_id": 18158970, "author_profile": "https://Stackoverflow.com/users/18158970", "pm_score": 1, "selected": false, "text": "let tutorials = [\n {\n title:'a', movie:'a'\n },\n {\n title:'b', movie:'b'\n }, \n {\n title:'c', movie:'c'\n }\n]\n\nfor(let i = 0; i < tutorials.length; i++) {\n console.log(tutorials[i].title);\n}\n" }, { "answer_id": 74507312, "author": "Anshu", "author_id": 18638118, "author_profile": "https://Stackoverflow.com/users/18638118", "pm_score": 1, "selected": true, "text": "let tutorials = [\n {\n title:'a', movie:'a'\n },\n {\n title:'b', movie:'b'\n }, \n {\n title:'c', movie:'c'\n }\n]\n\nconst titles = [];\nfor (tutorial of tutorials) {\n titles.push(tutorial.title)\n}\n" }, { "answer_id": 74507421, "author": "Murtaza Mehmudji", "author_id": 11224314, "author_profile": "https://Stackoverflow.com/users/11224314", "pm_score": 1, "selected": false, "text": "const titles = tutorials.map(t => t.title)\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20250014/" ]
74,504,129
<p>For example when I run <code>gulp</code> I don't have to do <code>npx gulp</code>.</p> <p>I can omit the <code>npx</code> and just run <code>gulp</code></p> <p>How do I do this for my own package?</p> <p>I've added <code>mycommand</code> to the package npm <code>bin</code> config, but I still always have to do <code>npx mycommand</code> for it to work.</p>
[ { "answer_id": 74504363, "author": "Dimava", "author_id": 5734961, "author_profile": "https://Stackoverflow.com/users/5734961", "pm_score": 0, "selected": false, "text": "npx gulp gulp gulp.cmd gulp.ps1 gulp npx gulp" }, { "answer_id": 74504399, "author": "Peter Toth", "author_id": 7874234, "author_profile": "https://Stackoverflow.com/users/7874234", "pm_score": 0, "selected": false, "text": "npm i -g gulp gulp" }, { "answer_id": 74504410, "author": "machineghost", "author_id": 5921, "author_profile": "https://Stackoverflow.com/users/5921", "pm_score": 1, "selected": false, "text": "alias $ alias gulp=\"npx gulp\"\n $ gulp\n npx gulp alias .bashrc .profile" }, { "answer_id": 74504660, "author": "Eric Haynes", "author_id": 1057157, "author_profile": "https://Stackoverflow.com/users/1057157", "pm_score": 0, "selected": false, "text": "npm install -g gulp gulp \"bin\": {\n \"gulp\": \"./bin/gulp.js\"\n },\n devDependencies gulp tsc npx devDependencies npx alias tsc='npx --package=typescript tsc'\n npx devDependencies alias command=`npx -y gulp`\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19716678/" ]
74,504,153
<p>I know this is a very basic question but it has me very confused - there's not much documentation that I could find about the flexslider. Also, I'm very new to this language, I'm a C++ / ASM type person but trying to get a webpage setup. The page is for an internet radio station. The slider is used to show the album covers of the currently playing, next, and later albums. The image names are 'hard-coded' in the slider which is fine if the images don't need to change. The problem is that the images do change every 3 minutes but the browser caches them so even if the image file contents change, the old image data displays.</p> <p>I spent the last few weeks developing a Windows service that updates the actual image files (Playing.jpg, Next.jpg, etc.) from the SQL database (among other things) only to find out once the slider is initialized, the displayed images don't change.</p> <p>Anyway, is the slider just used for 'static' images? Any advice as to how to update the images dynamically? php / js?</p> <pre><code>&lt;li&gt; &lt;img src=&quot;Playing.jpg&quot; alt=&quot;&quot; &gt; &lt;div class=&quot;flex-caption&quot;&gt; &lt;h2&gt;Now Playing&lt;/h2&gt; &lt;/div&gt; &lt;/li&gt; </code></pre> <p>Thank you!</p> <p>Keeping the filenames the same but changing the image contents makes no difference. What's the general way of changing slider images dynamically? Code snippets would be appreciated.</p>
[ { "answer_id": 74504363, "author": "Dimava", "author_id": 5734961, "author_profile": "https://Stackoverflow.com/users/5734961", "pm_score": 0, "selected": false, "text": "npx gulp gulp gulp.cmd gulp.ps1 gulp npx gulp" }, { "answer_id": 74504399, "author": "Peter Toth", "author_id": 7874234, "author_profile": "https://Stackoverflow.com/users/7874234", "pm_score": 0, "selected": false, "text": "npm i -g gulp gulp" }, { "answer_id": 74504410, "author": "machineghost", "author_id": 5921, "author_profile": "https://Stackoverflow.com/users/5921", "pm_score": 1, "selected": false, "text": "alias $ alias gulp=\"npx gulp\"\n $ gulp\n npx gulp alias .bashrc .profile" }, { "answer_id": 74504660, "author": "Eric Haynes", "author_id": 1057157, "author_profile": "https://Stackoverflow.com/users/1057157", "pm_score": 0, "selected": false, "text": "npm install -g gulp gulp \"bin\": {\n \"gulp\": \"./bin/gulp.js\"\n },\n devDependencies gulp tsc npx devDependencies npx alias tsc='npx --package=typescript tsc'\n npx devDependencies alias command=`npx -y gulp`\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16410654/" ]
74,504,169
<p>My script .py work perfectly, but .exe sadly doesn't work. Im running on newest PyInstaller.</p> <p><a href="https://github.com/sat1ss/Printer_extension/blob/main/Printer_script.py" rel="nofollow noreferrer">Here is my script</a></p> <p>I already tried everyting that i can think of here is options that i used:</p> <p><a href="https://i.stack.imgur.com/ba1QY.png" rel="nofollow noreferrer">Options used</a></p> <ul> <li><p><strong>-w</strong> : does't have .exe file</p> </li> <li><p><strong>-- onefile -w</strong> and <strong>-F -w</strong> : <a href="https://i.stack.imgur.com/X3tTd.png" rel="nofollow noreferrer">The specified module could not be found.</a></p> </li> <li><p><strong>--F</strong> , <strong>--onefile</strong> and <strong>no option used</strong> : <a href="https://i.stack.imgur.com/A6CrN.png" rel="nofollow noreferrer">Only shows this option for like half a second</a></p> </li> </ul>
[ { "answer_id": 74504363, "author": "Dimava", "author_id": 5734961, "author_profile": "https://Stackoverflow.com/users/5734961", "pm_score": 0, "selected": false, "text": "npx gulp gulp gulp.cmd gulp.ps1 gulp npx gulp" }, { "answer_id": 74504399, "author": "Peter Toth", "author_id": 7874234, "author_profile": "https://Stackoverflow.com/users/7874234", "pm_score": 0, "selected": false, "text": "npm i -g gulp gulp" }, { "answer_id": 74504410, "author": "machineghost", "author_id": 5921, "author_profile": "https://Stackoverflow.com/users/5921", "pm_score": 1, "selected": false, "text": "alias $ alias gulp=\"npx gulp\"\n $ gulp\n npx gulp alias .bashrc .profile" }, { "answer_id": 74504660, "author": "Eric Haynes", "author_id": 1057157, "author_profile": "https://Stackoverflow.com/users/1057157", "pm_score": 0, "selected": false, "text": "npm install -g gulp gulp \"bin\": {\n \"gulp\": \"./bin/gulp.js\"\n },\n devDependencies gulp tsc npx devDependencies npx alias tsc='npx --package=typescript tsc'\n npx devDependencies alias command=`npx -y gulp`\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18529936/" ]
74,504,174
<p>I want to create an object, <code>A</code>, with <code>x</code> and <code>y</code> values without creating a class.</p> <pre class="lang-py prettyprint-override"><code>#&lt;Code I am looking for goes here.&gt; print(A.x, A.y) </code></pre> <p>Is there an easy way to do this that I am missing, or is it too hacky?</p>
[ { "answer_id": 74504232, "author": "Bituvo", "author_id": 17064640, "author_profile": "https://Stackoverflow.com/users/17064640", "pm_score": 0, "selected": false, "text": "A = type('any name', (), {'x': 15, 'y': 23})\n\nprint(A.x, A.y)\n" }, { "answer_id": 74504263, "author": "Jozef", "author_id": 10425906, "author_profile": "https://Stackoverflow.com/users/10425906", "pm_score": 2, "selected": true, "text": "import types\n\nA = types.SimpleNamespace(x=5, y=2)\nprint(A.x, A.y)\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17064640/" ]
74,504,197
<pre><code>`mysql&gt; select * from movies; +----------+-------+---------+ | movie_id | title | watched | +----------+-------+---------+ | 1 | bo | 0 | | 2 | NEW | 0 | | 3 | NEW 2 | 0 | +----------+-------+---------+ </code></pre> <pre><code>CREATE TABLE MOVIES ( movie_id INTEGER NOT NULL AUTO_INCREMENT, title VARCHAR(50) NOT NULL, watched BOOLEAN NOT NULL, PRIMARY KEY (movie_id) ); </code></pre> <p>` I am having to store the &quot;watched&quot; field as a tiny int instead of typical boolean, I am trying to find a way of converting it back to boolean when reading from table, so I dont have to loop through all responses and convert manually.</p> <p>ie. <code>{movie_id: 1, title: 'bo', watched: 0} ---&gt; {movie_id: 1, title: 'bo', watched: false}</code></p> <p>I have tried select cast but am unfamiliar with the syntax</p>
[ { "answer_id": 74504286, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 1, "selected": false, "text": "SUM CASE WHEN FILTER SELECT\n movie_id , title , \n CASE WHEN watched = 0 THEN 'False' ELSE 'True' END IF\n" }, { "answer_id": 74504295, "author": "Dave S", "author_id": 2287427, "author_profile": "https://Stackoverflow.com/users/2287427", "pm_score": 0, "selected": false, "text": "SELECT movie_id, IF (watched > 0, true, false) as bwatched, ...\n IF(expression , value / expression if true, v /e if false)" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20258676/" ]
74,504,231
<p>Trying to write a program that follows a simple pattern (x-y, x+y) as practice with recursion. Essentially taking a number, subtracting the second until reaching a negative value, then adding until reaching the original value. I understand my base case is reaching the original value, and my recursive case to subtract until negative but I can't quite figure out how to turn around and recurse back up to the original value.</p> <pre><code>void PrintNumPattern(int x, int y){ cout &lt;&lt; x &lt;&lt; &quot; &quot;; if(x == //Original value//){ cout &lt;&lt; endl; } else{ if(//has been negative//){ PrintNumPattern(x + y, y); } else{ PrintNumPattern(x - y, y); } } } int main() { int num1; int num2; cin &gt;&gt; num1; cin &gt;&gt; num2; PrintNumPattern(num1, num2); return 0; } </code></pre>
[ { "answer_id": 74504285, "author": "ChrisMM", "author_id": 10686048, "author_profile": "https://Stackoverflow.com/users/10686048", "pm_score": 3, "selected": true, "text": "void PrintNumPattern(int x, int y){\n std::cout << x << \" \"; // Print \"x\" first\n if ( x >= 0 ) { // If x is positive (or zero?) keep recursing\n PrintNumPattern( x - y, y ); // Recursive call\n std::cout << x << \" \"; // When recursive call is done, print the value again\n }\n}\n x = 100 y = 7 100 93 86 79 72 65 58 51 44 37 30 23 16 9 2 -5 2 9 16 23 30 37 44 51 58 65 72 79 86 93 100 \n" }, { "answer_id": 74504312, "author": "Botond Horváth", "author_id": 16825566, "author_profile": "https://Stackoverflow.com/users/16825566", "pm_score": 0, "selected": false, "text": "x void PrintNumPattern(int x, int y,int original,bool was_neg){\n...\n if (x==original && was_neg/*if you don't add this it will exit at the first run*/)\n...\n if (x<0) {was_neg=true;}\n if (was_neg){\n PrintNumPattern(x + y, y, original,true);\n }else{\n PrintNumPattern(x - y, y, original,false);\n }\n \n}\n...\n\n//and the call:\n`PrintNumPattern(num1, num2,num1,false);`\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20550832/" ]
74,504,234
<p>Similar to Rstudio, Atom allowed you to run code segments on interactively rather than the entire script all at once. Is there a suitable Julia language IDE that is comparable to rstudio or Atom (juno) and allows for on-the-fly execution of code blocks because Atom is being phased out?</p> <p>note: Thanks for answers in vs code to obtain interactive feature hold ctrl + return will run code.</p>
[ { "answer_id": 74504350, "author": "Przemyslaw Szufel", "author_id": 9957710, "author_profile": "https://Stackoverflow.com/users/9957710", "pm_score": 3, "selected": true, "text": "## # %% #- ##\n\n(your code goes here)\n\n##\n" }, { "answer_id": 74504376, "author": "Odilf", "author_id": 14467132, "author_profile": "https://Stackoverflow.com/users/14467132", "pm_score": 1, "selected": false, "text": "shift+enter" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7331417/" ]
74,504,267
<p>I want a python code to print greeting messages for users when logged in: if the <code>userName</code> is <code>admin</code> then it should print &quot;Hello admin you're welcome, would you want to see a status update?&quot;, and if the <code>userName</code> is other than <code>admin</code> then a different welcome message is printed:</p> <p>I tried the code below but am not getting it right:</p> <pre><code>userNames = [&quot;jack2&quot;, &quot;admin&quot;, &quot;lucy21&quot;, &quot;angeUt&quot;, &quot;lacky53&quot;] userName = &quot;admin&quot; if userName == &quot;admin&quot;: # ** print this below if admin is the userName ** print(&quot;Hello &quot; + userName + &quot; you are welcome, would you like to see a status update?&quot;) else: print(&quot;other message&quot;) # ** this should be printed when the userName is for example jack2. ** </code></pre> <p>Please note I just started python barely a week now. I just didn't get the code right because am just starting out with programming.</p> <p><a href="https://i.stack.imgur.com/KoCle.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KoCle.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74504350, "author": "Przemyslaw Szufel", "author_id": 9957710, "author_profile": "https://Stackoverflow.com/users/9957710", "pm_score": 3, "selected": true, "text": "## # %% #- ##\n\n(your code goes here)\n\n##\n" }, { "answer_id": 74504376, "author": "Odilf", "author_id": 14467132, "author_profile": "https://Stackoverflow.com/users/14467132", "pm_score": 1, "selected": false, "text": "shift+enter" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8075146/" ]
74,504,269
<p>I want to parse the JSON from nominatim from OpenStreetMap.</p> <p><a href="https://nominatim.openstreetmap.org/search?q=Tower%20Bridge&amp;format=json" rel="nofollow noreferrer">Example</a></p> <p>It's a list and I don't have a clue how I can describe the list. I am using Gson, these is my data class:</p> <pre><code>data class Destination( val lat: Double, val lon: Double, val display_name: String ) </code></pre> <p>and this is my Gson implementation:</p> <pre><code>val list = Gson().fromJson&lt;List&lt;Destination&gt;&gt;( body, Destination::class.java ) </code></pre> <p>It gives me this error:</p> <pre><code>java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $ </code></pre> <p>But I declared an Array in my Gson implementation. Anyone having an idea how to fix this?</p>
[ { "answer_id": 74504313, "author": "Julius Babies", "author_id": 16682019, "author_profile": "https://Stackoverflow.com/users/16682019", "pm_score": 1, "selected": true, "text": "Array List val list : Array<Destination> = Gson().fromJson(\n body,\n Array<Destination>::class.java\n)\n" }, { "answer_id": 74507239, "author": "Yonatan Karp-Rudin", "author_id": 3899765, "author_profile": "https://Stackoverflow.com/users/3899765", "pm_score": 1, "selected": false, "text": "val type = object : TypeToken<List<Destination>>() {}.type\nGson().fromJson<List<Destination>>(body, type)\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16682019/" ]
74,504,296
<p>I'm using TypeScript with React Native to develop a mobile app. To restore the scroll position of the previous screen, I created a variable and assign the <code>useRef()</code> to handle the scroll. What is the type for the ref prop? I'll share my code below.</p> <pre><code>const sectionListRef = useRef(); ... sectionListRef.current.ScrollToLocation // &lt;-- Property 'scrollToLocation' does not exist on type 'never'; </code></pre> <p>I have no idea which type should be... Can someone please tell me why this error happens and how I resolve this?</p>
[ { "answer_id": 74504313, "author": "Julius Babies", "author_id": 16682019, "author_profile": "https://Stackoverflow.com/users/16682019", "pm_score": 1, "selected": true, "text": "Array List val list : Array<Destination> = Gson().fromJson(\n body,\n Array<Destination>::class.java\n)\n" }, { "answer_id": 74507239, "author": "Yonatan Karp-Rudin", "author_id": 3899765, "author_profile": "https://Stackoverflow.com/users/3899765", "pm_score": 1, "selected": false, "text": "val type = object : TypeToken<List<Destination>>() {}.type\nGson().fromJson<List<Destination>>(body, type)\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4803603/" ]
74,504,314
<p>I'm sure I'm missing something in how classes work here, but basically this is my class:</p> <pre><code>import pandas as pd import numpy as np import scipy #example DF with OHLC columns and 100 rows gold = pd.DataFrame({'Open':[i for i in range(100)],'Close':[i for i in range(100)],'High':[i for i in range(100)],'Low':[i for i in range(100)]}) class Backtest: def __init__(self, ticker, df): self.ticker = ticker self.df = df self.levels = pivot_points(self.df) def pivot_points(self,df,period=30): highs = scipy.signal.argrelmax(df.High.values,order=period) lows = scipy.signal.argrelmin(df.Low.values,order=period) return list(df.High[highs[0]]) + list(df.Low[lows[0]]) inst = Backtest('gold',gold) #gold is a Pandas Dataframe with Open High Low Close columns and data inst.levels # This give me the whole dataframe (inst.df) instead of the expected output of the pivot_point function (a list of integers) </code></pre> <p>The problem is <code>inst.levels</code> returns the whole DataFrame instead of the return value of the function pivot_points (which is supposed to be a list of integers)</p> <p>When I called the pivot_points function on the same DataFrame outside this class I got the list I expected</p> <p>I expected to get the result of the pivot_points() function after assigning it to self.levels inside the <strong>init</strong> but instead I got the entire DataFrame</p>
[ { "answer_id": 74504470, "author": "Ovski", "author_id": 8610346, "author_profile": "https://Stackoverflow.com/users/8610346", "pm_score": 1, "selected": false, "text": "class Backtest:\n\n def __init__(self, ticker, df):\n self.ticker = ticker\n self.df = df\n\n # no need to define a instance variable here, you can access the method directly\n # self.levels = pivot_points(self.df)\n\n def pivot_points(self):\n period = 30\n # period is a local variable to pivot_points so I can access it directly\n print(f'period inside Backtest.pivot_points: {period}')\n # df is an instance variable and can be accessed in any method of Backtest after it is instantiated\n print(f'self.df inside Backtest.pivot_points(): {self.df}')\n # to get any values out of pivot_points we return some calcualtions\n return 1 + 1\n\n # if you do need an attribute like level to access it by inst.level you could create a property\n @property\n def level(self):\n return self.pivot_points()\n\n\ngold = 'some data'\ninst = Backtest('gold', gold) # gold is a Pandas Dataframe with Open High Low Close columns and data\nprint(f'inst.pivot_points() outside the class: {inst.pivot_points()}')\nprint(f'inst.level outside the class: {inst.level}')\n period inside Backtest.pivot_points: 30\nself.df inside Backtest.pivot_points(): some data\ninst.pivot_points() outside the class: 2\nperiod inside Backtest.pivot_points: 30\nself.df inside Backtest.pivot_points(): some data\ninst.level outside the class: 2\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16523946/" ]
74,504,341
<p>I'm using a personal access token to access Github from the command line, in place of a password when prompted for my username and password. If I make a new access token, it works just fine in place of my password the first time, but if I try to use it again, I get this error:</p> <pre><code>remote: Support for password authentication was removed on August 13, 2021. remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication. fatal: Authentication failed for &lt;my-repo&gt; </code></pre> <p>The only way I have been able to use Github from the command line has been to make a new personal access token every single time I need to use a password.</p> <p>I have tried different expiration dates, but nothing seems to change this behavior. I also have experimented with the new fine-grained tokens, but I need to be able to access private repositories that I do not own (through Github classroom) and as far as I can tell the fine-grained tokens don't allow me to do that without being provided with a token by the admin, which isn't an option for me.</p> <p>I have the same issue across multiple platforms, so I don't think it has to do with my local environment.</p>
[ { "answer_id": 74504470, "author": "Ovski", "author_id": 8610346, "author_profile": "https://Stackoverflow.com/users/8610346", "pm_score": 1, "selected": false, "text": "class Backtest:\n\n def __init__(self, ticker, df):\n self.ticker = ticker\n self.df = df\n\n # no need to define a instance variable here, you can access the method directly\n # self.levels = pivot_points(self.df)\n\n def pivot_points(self):\n period = 30\n # period is a local variable to pivot_points so I can access it directly\n print(f'period inside Backtest.pivot_points: {period}')\n # df is an instance variable and can be accessed in any method of Backtest after it is instantiated\n print(f'self.df inside Backtest.pivot_points(): {self.df}')\n # to get any values out of pivot_points we return some calcualtions\n return 1 + 1\n\n # if you do need an attribute like level to access it by inst.level you could create a property\n @property\n def level(self):\n return self.pivot_points()\n\n\ngold = 'some data'\ninst = Backtest('gold', gold) # gold is a Pandas Dataframe with Open High Low Close columns and data\nprint(f'inst.pivot_points() outside the class: {inst.pivot_points()}')\nprint(f'inst.level outside the class: {inst.level}')\n period inside Backtest.pivot_points: 30\nself.df inside Backtest.pivot_points(): some data\ninst.pivot_points() outside the class: 2\nperiod inside Backtest.pivot_points: 30\nself.df inside Backtest.pivot_points(): some data\ninst.level outside the class: 2\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15801507/" ]
74,504,345
<p>From a list of distinct numbers, I want to find the sum of the largest numbers of len(a)//3. Examples if len(a) = 9, you need to find the sum of the largest 3 numbers. If len(a)=40, you need to find the sum of the largest 13 numbers. I was able to code it as such:</p> <pre><code>def largestthree(a): max2 = 0 for i in range(len(a)//3): max1 = max(a) a.remove(max1) max2+= max1 return max2 </code></pre> <p>The problem is I need to have it as a O(nlog2n) which I do't have it as that. Could you modify it into aO(nlog2n) ? I don't want you to redo the code, just modify it to a O(nlog2n)</p> <p>Thanks in advance :)</p> <p>UPDATE:</p> <pre><code> def largestthird(a): max2 = 0 for i in range(len(a)): if len(a)&gt;=3: for j in range(len(a)//3): max1 = max(a) a.remove(max1) max2+= max1 return max2 </code></pre> <p>Would this be considered O(nlog2n) ?</p> <p>Thanks,</p>
[ { "answer_id": 74504390, "author": "user7644509", "author_id": 7644509, "author_profile": "https://Stackoverflow.com/users/7644509", "pm_score": 0, "selected": false, "text": "import heapq\nl = [100, 1,2,3,4 ,545 , 5434 , 34]\n\nminheap = []\nheapq.heapify(minheap)\n\nfor num in l:\n heapq.heappush(minheap, num)\n if len(minheap) > len(l) // 3:\n heapq.heappop(minheap)\n\nprint(minheap)\nprint(sum(minheap))\n" }, { "answer_id": 74504585, "author": "Swifty", "author_id": 20267366, "author_profile": "https://Stackoverflow.com/users/20267366", "pm_score": 1, "selected": false, "text": "sum(sorted(a, reverse=True)[:len(a)//3])\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20544212/" ]
74,504,354
<p>I have a custom button in summernote that has a dropdown of items &quot;one&quot;, &quot;two&quot;, &quot;three&quot; when I click on for example the text &quot;one&quot; the text is added at the start which is fine. But then when I click on &quot;two&quot; afterwards the text is also added at the start which produces this result.</p> <pre><code>twoone </code></pre> <p>I would like to have the following result</p> <pre><code>one two </code></pre> <p>Update when I use this line</p> <pre><code>context.invoke(&quot;editor.pasteHTML&quot;, context.modules.editor.$editable[0].innerText ? &quot;&lt;br&gt;&quot; + $(this).html() : $(this).html() ); </code></pre> <p>instead of</p> <pre><code>context.invoke('editor.insertText', $(this).html()); </code></pre> <p>I get the following result wihch is better but the order is still incorrect</p> <pre><code>two one </code></pre> <p>Here you can fiddle with my code</p> <p><a href="https://stackblitz.com/edit/angular-summernote-demo-n7xn2n?file=src%2Fapp%2Fapp.component.ts" rel="nofollow noreferrer">https://stackblitz.com/edit/angular-summernote-demo-n7xn2n?file=src%2Fapp%2Fapp.component.ts</a></p> <p>Otherwise here is my code for the button that inserts the text</p> <pre><code>function customButtonGenerator(lstQuoteComments, title) { return function (context) { const ui = ($ as any).summernote.ui; var i; var listHtml = ''; for (i = 0; i &lt; lstQuoteComments.length; i++) { listHtml += '&lt;li&gt;' + lstQuoteComments[i] + '&lt;/li&gt;'; } const button = ui.buttonGroup([ ui.button({ className: 'dropdown-toggle', contents: '&lt;i class=&quot;fa fa-comments text-primary&quot;/&gt;&lt;span id=&quot;summernot-caret&quot; class=&quot;caret text-primary&quot;&gt;&lt;/span&gt;', //tooltip: 'Comments', //Not working when howver over it top is not defined data: { toggle: 'dropdown', }, }), ui.dropdown({ className: 'drop-default summernote-list', contents: '&lt;div id=&quot;container-comentario&quot;&gt;&lt;div id=&quot;dialog&quot; title=&quot;' + title + '&quot; &gt;&lt;h1 class=&quot;header-comentario&quot;&gt;' + title + '&lt;/h1&gt;&lt;ul id=&quot;summernote-list&quot;&gt;&lt;ul&gt;' + listHtml + '&lt;/ul&gt;&lt;/div&gt;&lt;/div&gt;', callback: function ($dropdown) { $dropdown.find('li').each(function () { $(this).click(function () { context.invoke('editor.insertText', $(this).html()); }); }); }, }), ]); return button.render(); }; } </code></pre> <p>Thank you for your help.</p>
[ { "answer_id": 74505045, "author": "Dori Rina", "author_id": 11858157, "author_profile": "https://Stackoverflow.com/users/11858157", "pm_score": 1, "selected": false, "text": "customButtonGenerator context.invoke('editor.insertText', $(this).html());\n context.invoke('editor.pasteHTML', $(this).html());\n context.invoke('editor.pasteHTML', '<div>' + $(this).html() + '</div>');\n" }, { "answer_id": 74638300, "author": "Fida Khattak", "author_id": 4240953, "author_profile": "https://Stackoverflow.com/users/4240953", "pm_score": 1, "selected": false, "text": "context.invoke('editor.insertText', $(this).html());\n context.invoke(\"code\", context.modules.editor.$editable[0].innerHTML + '<br>' + $(this).html());\n" }, { "answer_id": 74655905, "author": "sidverma", "author_id": 7721497, "author_profile": "https://Stackoverflow.com/users/7721497", "pm_score": 0, "selected": false, "text": "$('#summernote').summernote('insertText', 'My text from the dropdown menu', 'code');\n" }, { "answer_id": 74657819, "author": "dangarfield", "author_id": 3265253, "author_profile": "https://Stackoverflow.com/users/3265253", "pm_score": 2, "selected": true, "text": "...\ncallback: function ($dropdown) {\n $dropdown.find('li').each(function () {\n $(this).click(function () {\n let newHtml = context.modules.editor.$editable[0].innerHTML\n if (newHtml !== '') {\n newHtml += '<br>'\n }\n newHtml += $(this).html()\n context.invoke('code', newHtml)\n })\n })\n}\n...\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10152435/" ]
74,504,383
<p>i am trying to add different styles for every listbox.Item in my project. Can anyone help me about that?</p> <p>`</p> <pre><code> foreach (var item in orderList) { var itm = new ListBoxItem(); if (item.CustomOrder) { itm.Content = item; itm.Style = customOrderStyle; listbox.Items.Add(itm); } else { itm.Content = item; itm.Style = newOrderStyle; listbox.Items.Add(itm); } } </code></pre> <p>`</p> <p><a href="https://i.stack.imgur.com/xZua0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xZua0.png" alt="My content doesnt shown like this." /></a></p> <p>I know that i am adding Listbox item to the listbox, that's why content is doesnt shown. I try some different things too but still dont know how to solve it.</p>
[ { "answer_id": 74508458, "author": "EldHasp", "author_id": 13349759, "author_profile": "https://Stackoverflow.com/users/13349759", "pm_score": 1, "selected": true, "text": "namespace Core2022.SO.Ali.ListBoxItemStyleSelector\n{\n public class OrderItem\n {\n public bool CustomOrder { get; set; }\n\n public int Id { get; set; }\n }\n}\n using System.Collections.ObjectModel;\n\nnamespace Core2022.SO.Ali.ListBoxItemStyleSelector\n{\n public class OrderViewModel\n {\n public ObservableCollection<OrderItem> Orders { get; } = new ObservableCollection<OrderItem>();\n\n public OrderViewModel()\n {\n for (int i = 0; i < 10; i++)\n {\n Orders.Add(new OrderItem() { Id = i, CustomOrder = i % 2 == 0 });\n }\n }\n }\n}\n using System;\nusing System.Windows;\nusing System.Windows.Controls;\n\nnamespace Core2022.SO.Ali.ListBoxItemStyleSelector\n{\n public class CustomOrderStyleSelector : StyleSelector\n {\n public Style? CustomOrderTrue { get; set; }\n public Style? CustomOrderFalse { get; set; }\n\n public override Style SelectStyle(object item, DependencyObject container)\n {\n if (item is OrderItem order)\n {\n return (order.CustomOrder ? CustomOrderTrue : CustomOrderFalse)\n ?? throw new NullReferenceException(); ;\n }\n return base.SelectStyle(item, container);\n }\n }\n}\n <Window x:Class=\"Core2022.SO.Ali.ListBoxItemStyleSelector.OrdersWindow\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:d=\"http://schemas.microsoft.com/expression/blend/2008\"\n xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\"\n xmlns:local=\"clr-namespace:Core2022.SO.Ali.ListBoxItemStyleSelector\"\n mc:Ignorable=\"d\"\n Title=\"OrdersWindow\" Height=\"300\" Width=\"200\"\n DataContext=\"{DynamicResource vm}\">\n <FrameworkElement.Resources>\n <local:OrderViewModel x:Key=\"vm\"/>\n <local:CustomOrderStyleSelector x:Key=\"customOrderStyleSelector\">\n <local:CustomOrderStyleSelector.CustomOrderTrue>\n <Style TargetType=\"ListBoxItem\">\n <Setter Property=\"Foreground\" Value=\"Green\"/>\n <Setter Property=\"FontSize\" Value=\"15\"/>\n </Style>\n </local:CustomOrderStyleSelector.CustomOrderTrue>\n <local:CustomOrderStyleSelector.CustomOrderFalse>\n <Style TargetType=\"ListBoxItem\">\n <Setter Property=\"Background\" Value=\"Coral\"/>\n <Setter Property=\"HorizontalContentAlignment\" Value=\"Center\"/>\n </Style>\n </local:CustomOrderStyleSelector.CustomOrderFalse>\n </local:CustomOrderStyleSelector>\n </FrameworkElement.Resources>\n <Grid>\n <ListBox ItemsSource=\"{Binding Orders}\"\n DisplayMemberPath=\"Id\"\n ItemContainerStyleSelector=\"{DynamicResource customOrderStyleSelector}\"/>\n </Grid>\n</Window>\n" }, { "answer_id": 74508533, "author": "BionicCode", "author_id": 3141792, "author_profile": "https://Stackoverflow.com/users/3141792", "pm_score": 1, "selected": false, "text": "DataTemplate DataTemplate.DataType x:Key ListBoxItem DataTemplate CustomOrder DefaultOrder CustomOrder ListBox interface IOrder\n{\n ...\n}\n class DefaultOrder : IOrder\n{\n ...\n}\n class CustomOrder : IOrder\n{\n ...\n}\n <Window>\n <ListBox x:Name=\"OrdersOverview\">\n <ListBox.Resources>\n <DataTemplate DataType=\"{x:Type local:DefaultOrder}\">\n ...\n </DataTemplate>\n\n <DataTemplate DataType=\"{x:Type local:CustomOrder}\">\n ...\n </DataTemplate>\n </ListBox.Resources>\n </ListBox>\n</Window>\n prtial class MainWindow : Window\n{\n private ObservableCollection<IOrder> Orders { get; }\n\n public MainWindow()\n {\n InitializeComponent();\n\n this.Orders = new ObservableCollection<IOrder>();\n this.OrdersOverview.ItemsSource = this.Orders;\n }\n\n private void CreateDefaultOrder()\n {\n var newOrder = new DefaultOrder();\n\n // Show the new order in the ListBox\n this.Orders.Add(newOrder);\n }\n\n\n private void CreateCustomOrder()\n {\n var newOrder = new CustomOrder();\n\n // Show the new order in the ListBox\n this.Orders.Add(newOrder);\n }\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19202039/" ]
74,504,388
<p>From The C++ programming language book by Bjarne Stroustrup:</p> <p><a href="https://i.stack.imgur.com/QIg7y.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QIg7y.jpg" alt="The C++ programming language| STL containers" /></a></p> <p>Does using a <code>rep</code> pointer to element representation in a container imply that the implementation of the STL containers is flexible and can be customized?</p>
[ { "answer_id": 74504464, "author": "Nicol Bolas", "author_id": 734069, "author_profile": "https://Stackoverflow.com/users/734069", "pm_score": 2, "selected": false, "text": "rep #define" }, { "answer_id": 74504477, "author": "Sam Varshavchik", "author_id": 3943312, "author_profile": "https://Stackoverflow.com/users/3943312", "pm_score": 2, "selected": false, "text": "std::list begin() end() std::list int std::map" }, { "answer_id": 74505926, "author": "Ranoiaetep", "author_id": 12861639, "author_profile": "https://Stackoverflow.com/users/12861639", "pm_score": 1, "selected": false, "text": "std::map" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12137626/" ]
74,504,395
<p>If my request returns a JSON object like this</p> <pre><code>{&quot;autocomplete&quot;:[&quot;abc&quot;, &quot;asd&quot;]} </code></pre> <p>How can I get the array in the JSON and turn it into java ArrayList?</p> <p>I find some methods like getString, getInt. But I don't find a method that could get the array.</p>
[ { "answer_id": 74504464, "author": "Nicol Bolas", "author_id": 734069, "author_profile": "https://Stackoverflow.com/users/734069", "pm_score": 2, "selected": false, "text": "rep #define" }, { "answer_id": 74504477, "author": "Sam Varshavchik", "author_id": 3943312, "author_profile": "https://Stackoverflow.com/users/3943312", "pm_score": 2, "selected": false, "text": "std::list begin() end() std::list int std::map" }, { "answer_id": 74505926, "author": "Ranoiaetep", "author_id": 12861639, "author_profile": "https://Stackoverflow.com/users/12861639", "pm_score": 1, "selected": false, "text": "std::map" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20550913/" ]
74,504,396
<p>I have the following two arrays of objects and I want to filter all elements of first array whose &quot;stage&quot; value is same in any of the element of second array.</p> <pre><code>const arr1 = [ { id: '1', name: 'Ahmad', title: 'Manager', stage: 'Open', }, { id: '2', name: 'Ahmad', title: 'Manager', stage: 'Open', }, { id: '3', name: 'Ahmad', title: 'Manager', stage: 'Open', }, { id: '4', name: 'Bakshi', title: 'Accountant', stage: 'Closed Won', }, { id: '5', name: 'Rehmat', title: 'Chancellor', stage: 'Open', }]; const arr2 = [ {id: '2', stage: 'Closed', selected: false}, {id: '3', stage: 'Closed Won', selected: false}, {id: '4', stage: 'Open Won', selected: false}, {id: '5', stage: 'Completed', selected: false}, {id: '1', stage: 'Open', selected: false} ]; </code></pre> <p>I have used the following logic</p> <pre><code>const changedObjects = Object.keys(arr1).filter(index =&gt; arr1[index].stage === arr2[index].stage).map(index =&gt; arr1[index]); </code></pre> <p>But the problem here is that it only filters last element of arr1 which matches exactly with element of last index of arr2. I want it to display all elements of arr1 whose stage=&quot;Open&quot;.</p> <p>I have tried multiple logic but still unable to get the required output</p>
[ { "answer_id": 74504437, "author": "Georgemff", "author_id": 9716786, "author_profile": "https://Stackoverflow.com/users/9716786", "pm_score": 2, "selected": false, "text": "let filteredArr = arr1.filter((o1) => {\n return arr2.some((o2) => o2.stage === o1.stage);\n});\n" }, { "answer_id": 74506143, "author": "Ping", "author_id": 20288037, "author_profile": "https://Stackoverflow.com/users/20288037", "pm_score": 0, "selected": false, "text": "const arr1 = [\n {id: '1',name: 'Ahmad',title: 'Manager',stage: 'Open',},\n {id: '2',name: 'Ahmad',title: 'Manager',stage: 'Open',},\n {id: '3',name: 'Ahmad',title: 'Manager',stage: 'Open',},\n {id: '4',name: 'Bakshi',title: 'Accountant',stage: 'Closed Won',},\n {id: '5',name: 'Rehmat',title: 'Chancellor',stage: 'Open',}\n ];\n\nconst arr2 = [\n {id: '2', stage: 'Closed', selected: false},\n {id: '3', stage: 'Closed Won', selected: false},\n {id: '4', stage: 'Open Won', selected: false},\n {id: '5', stage: 'Completed', selected: false},\n {id: '1', stage: 'Open', selected: false},\n ];\n\nconst objectKeysOfarr1 = Object.keys(arr1);\nconsole.log(`objectKeysOfarr1: ${objectKeysOfarr1}`);\n/**\noutput:\nobjectKeysOfarr1: 0,1,2,3,4\n*/\n\nconst filterObjectKeysOfarr1 = objectKeysOfarr1\n .filter(index => {\n console.log(`arr1[index].stage: ${arr1[index].stage}`);\n console.log(`arr2[index].stage: ${arr2[index].stage}`);\n console.log(`arr1[index].stage === arr2[index].stage: ${arr1[index].stage === arr2[index].stage}`);\n return arr1[index].stage === arr2[index].stage;\n });\nconsole.log(`filterObjectKeysOfarr1: ${filterObjectKeysOfarr1}`);\n/**\noutput:\n arr1[index].stage: Open\n arr2[index].stage: Closed\n arr1[index].stage === arr2[index].stage: false\n arr1[index].stage: Open\n arr2[index].stage: Closed Won\n arr1[index].stage === arr2[index].stage: false\n arr1[index].stage: Open\n arr2[index].stage: Open Won\n arr1[index].stage === arr2[index].stage: false\n arr1[index].stage: Closed Won\n arr2[index].stage: Completed\n arr1[index].stage === arr2[index].stage: false\n arr1[index].stage: Open\n arr2[index].stage: Open\n arr1[index].stage === arr2[index].stage: true\n filterObjectKeysOfarr1: 4\n*/\n\nconst changedObjects = filterObjectKeysOfarr1\n .map(index => {\n console.log(`arr1[index]: ${JSON.stringify(arr1[index])}`);\n return arr1[index];\n });\nconsole.log(`changedObjects: ${JSON.stringify(changedObjects)}`);\n/**\noutput:\n arr1[index]: {\"id\":\"5\",\"name\":\"Rehmat\",\"title\":\"Chancellor\",\"stage\":\"Open\"}\n changedObjects: [{\"id\":\"5\",\"name\":\"Rehmat\",\"title\":\"Chancellor\",\"stage\":\"Open\"}]\n*/\n\n// As shown in the log, the reason why you are only getting one output, is beacuse the filter you write compares only the object of the same index in 'arr1' and 'arr2', which apparently won't return all 'Open stage' of the arr1.\n// actually, you don't need to compare two arrays if you are only trying to get all 'Open stage' from 'arr1', such as:\n\nconst result1 = arr1.filter(o => o.stage === 'Open');\nconsole.log(`get all open:\\n${JSON.stringify(result1)}`);\n/**\noutput:\n get all open:\n [\n {\"id\":\"1\",\"name\":\"Ahmad\",\"title\":\"Manager\",\"stage\":\"Open\"},\n {\"id\":\"2\",\"name\":\"Ahmad\",\"title\":\"Manager\",\"stage\":\"Open\"},\n {\"id\":\"3\",\"name\":\"Ahmad\",\"title\":\"Manager\",\"stage\":\"Open\"},\n {\"id\":\"5\",\"name\":\"Rehmat\",\"title\":\"Chancellor\",\"stage\":\"Open\"}\n ]\n*/\n\n// let's say if what you want to do is to compare arr1 with arr2 which the stage of arr1 is 'included' in selected stages of arr2, this is how you should do:\n\n// triggerStage(): trigger true/false switch of the 'select' value of the object of the given ID, accept 'id' as number, string or array.\nconst triggerStage = (arr,id) => {\n let ids = [];\n if (!Array.isArray(id)) ids.push(id);\n else ids = id;\n return arr.map(o => ids.some(id => id == o.id) ? (o.selected = !o.selected) && o : o);\n}\n\n// selectedStages(): returns an array of the 'stage' that is being selected.\nconst selectedStages = (arr) => arr.filter(o => o.selected).map(o => o.stage);\n\n// the follow example shows switching on id:1 and 2.\nconst newArr2 = triggerStage(arr2,[1,'2']);\nconsole.log(`newArr2:\\n${JSON.stringify(newArr2)}`);\n/**\noutput:\n newArr2:\n [\n {\"id\": \"2\",\"stage\": \"Closed\",\"selected\": true},\n {\"id\": \"3\",\"stage\": \"Closed Won\",\"selected\": false},\n {\"id\": \"4\",\"stage\": \"Open Won\",\"selected\": false},\n {\"id\": \"5\",\"stage\": \"Completed\",\"selected\": false},\n {\"id\": \"1\",\"stage\": \"Open\",\"selected\": true}\n ]\n*/\n\nconst selected = selectedStages(newArr2);\nconsole.log(`selected: ${JSON.stringify(selected)}`);\n\n/**\noutput: selected: [\"Closed\",\"Open\"]\n*/\n\n// filter 'arr1' to for objects which the 'stage' matches the 'selected' stage of 'arr2':\nconst result2 = arr1.filter(o => selected.some(stage => stage === o.stage));\nconsole.log(`result2:\\n${JSON.stringify(result2)}`);\n/**\noutput:\n result2:\n [\n {\"id\":\"1\",\"name\":\"Ahmad\",\"title\":\"Manager\",\"stage\":\"Open\"},\n {\"id\":\"2\",\"name\":\"Ahmad\",\"title\":\"Manager\",\"stage\":\"Open\"},\n {\"id\":\"3\",\"name\":\"Ahmad\",\"title\":\"Manager\",\"stage\":\"Open\"},\n {\"id\":\"5\",\"name\":\"Rehmat\",\"title\":\"Chancellor\",\"stage\":\"Open\"}\n ]\n*/" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12032346/" ]
74,504,413
<p>I have an API JSON response like below. I want to decode the JSON to get an array of dictionary <code>[String:Double]</code>, like <code>[{&quot;2020-01-01&quot; : 0.891186}, {&quot;2020-01-02&quot; : 0.891186}]</code>.</p> <pre><code>{ &quot;rates&quot;: { &quot;2020-01-01&quot;: { &quot;EUR&quot;: 0.891186 }, &quot;2020-01-02&quot;: { &quot;EUR&quot;: 0.891186 }, &quot;2020-01-03&quot;: { &quot;EUR&quot;: 0.895175 }, &quot;2020-01-04&quot;: { &quot;EUR&quot;: 0.895175 } } } </code></pre> <p>I have written decode code like below:</p> <pre><code>do { let data = try Data(contentsOf: appURL) let decoder = JSONDecoder() let response = try decoder.decode(Rates.self, from: data) response.rates } catch let jsonError { print(jsonError) } </code></pre> <p>And I have tried to define a struct:</p> <pre><code>struct Rates: Codable, Hashable { let rates: Point } struct Point { } </code></pre> <p>But I don't have an idea about what I should write in <code>struct Point</code> because the date is not a consistent field.</p>
[ { "answer_id": 74504437, "author": "Georgemff", "author_id": 9716786, "author_profile": "https://Stackoverflow.com/users/9716786", "pm_score": 2, "selected": false, "text": "let filteredArr = arr1.filter((o1) => {\n return arr2.some((o2) => o2.stage === o1.stage);\n});\n" }, { "answer_id": 74506143, "author": "Ping", "author_id": 20288037, "author_profile": "https://Stackoverflow.com/users/20288037", "pm_score": 0, "selected": false, "text": "const arr1 = [\n {id: '1',name: 'Ahmad',title: 'Manager',stage: 'Open',},\n {id: '2',name: 'Ahmad',title: 'Manager',stage: 'Open',},\n {id: '3',name: 'Ahmad',title: 'Manager',stage: 'Open',},\n {id: '4',name: 'Bakshi',title: 'Accountant',stage: 'Closed Won',},\n {id: '5',name: 'Rehmat',title: 'Chancellor',stage: 'Open',}\n ];\n\nconst arr2 = [\n {id: '2', stage: 'Closed', selected: false},\n {id: '3', stage: 'Closed Won', selected: false},\n {id: '4', stage: 'Open Won', selected: false},\n {id: '5', stage: 'Completed', selected: false},\n {id: '1', stage: 'Open', selected: false},\n ];\n\nconst objectKeysOfarr1 = Object.keys(arr1);\nconsole.log(`objectKeysOfarr1: ${objectKeysOfarr1}`);\n/**\noutput:\nobjectKeysOfarr1: 0,1,2,3,4\n*/\n\nconst filterObjectKeysOfarr1 = objectKeysOfarr1\n .filter(index => {\n console.log(`arr1[index].stage: ${arr1[index].stage}`);\n console.log(`arr2[index].stage: ${arr2[index].stage}`);\n console.log(`arr1[index].stage === arr2[index].stage: ${arr1[index].stage === arr2[index].stage}`);\n return arr1[index].stage === arr2[index].stage;\n });\nconsole.log(`filterObjectKeysOfarr1: ${filterObjectKeysOfarr1}`);\n/**\noutput:\n arr1[index].stage: Open\n arr2[index].stage: Closed\n arr1[index].stage === arr2[index].stage: false\n arr1[index].stage: Open\n arr2[index].stage: Closed Won\n arr1[index].stage === arr2[index].stage: false\n arr1[index].stage: Open\n arr2[index].stage: Open Won\n arr1[index].stage === arr2[index].stage: false\n arr1[index].stage: Closed Won\n arr2[index].stage: Completed\n arr1[index].stage === arr2[index].stage: false\n arr1[index].stage: Open\n arr2[index].stage: Open\n arr1[index].stage === arr2[index].stage: true\n filterObjectKeysOfarr1: 4\n*/\n\nconst changedObjects = filterObjectKeysOfarr1\n .map(index => {\n console.log(`arr1[index]: ${JSON.stringify(arr1[index])}`);\n return arr1[index];\n });\nconsole.log(`changedObjects: ${JSON.stringify(changedObjects)}`);\n/**\noutput:\n arr1[index]: {\"id\":\"5\",\"name\":\"Rehmat\",\"title\":\"Chancellor\",\"stage\":\"Open\"}\n changedObjects: [{\"id\":\"5\",\"name\":\"Rehmat\",\"title\":\"Chancellor\",\"stage\":\"Open\"}]\n*/\n\n// As shown in the log, the reason why you are only getting one output, is beacuse the filter you write compares only the object of the same index in 'arr1' and 'arr2', which apparently won't return all 'Open stage' of the arr1.\n// actually, you don't need to compare two arrays if you are only trying to get all 'Open stage' from 'arr1', such as:\n\nconst result1 = arr1.filter(o => o.stage === 'Open');\nconsole.log(`get all open:\\n${JSON.stringify(result1)}`);\n/**\noutput:\n get all open:\n [\n {\"id\":\"1\",\"name\":\"Ahmad\",\"title\":\"Manager\",\"stage\":\"Open\"},\n {\"id\":\"2\",\"name\":\"Ahmad\",\"title\":\"Manager\",\"stage\":\"Open\"},\n {\"id\":\"3\",\"name\":\"Ahmad\",\"title\":\"Manager\",\"stage\":\"Open\"},\n {\"id\":\"5\",\"name\":\"Rehmat\",\"title\":\"Chancellor\",\"stage\":\"Open\"}\n ]\n*/\n\n// let's say if what you want to do is to compare arr1 with arr2 which the stage of arr1 is 'included' in selected stages of arr2, this is how you should do:\n\n// triggerStage(): trigger true/false switch of the 'select' value of the object of the given ID, accept 'id' as number, string or array.\nconst triggerStage = (arr,id) => {\n let ids = [];\n if (!Array.isArray(id)) ids.push(id);\n else ids = id;\n return arr.map(o => ids.some(id => id == o.id) ? (o.selected = !o.selected) && o : o);\n}\n\n// selectedStages(): returns an array of the 'stage' that is being selected.\nconst selectedStages = (arr) => arr.filter(o => o.selected).map(o => o.stage);\n\n// the follow example shows switching on id:1 and 2.\nconst newArr2 = triggerStage(arr2,[1,'2']);\nconsole.log(`newArr2:\\n${JSON.stringify(newArr2)}`);\n/**\noutput:\n newArr2:\n [\n {\"id\": \"2\",\"stage\": \"Closed\",\"selected\": true},\n {\"id\": \"3\",\"stage\": \"Closed Won\",\"selected\": false},\n {\"id\": \"4\",\"stage\": \"Open Won\",\"selected\": false},\n {\"id\": \"5\",\"stage\": \"Completed\",\"selected\": false},\n {\"id\": \"1\",\"stage\": \"Open\",\"selected\": true}\n ]\n*/\n\nconst selected = selectedStages(newArr2);\nconsole.log(`selected: ${JSON.stringify(selected)}`);\n\n/**\noutput: selected: [\"Closed\",\"Open\"]\n*/\n\n// filter 'arr1' to for objects which the 'stage' matches the 'selected' stage of 'arr2':\nconst result2 = arr1.filter(o => selected.some(stage => stage === o.stage));\nconsole.log(`result2:\\n${JSON.stringify(result2)}`);\n/**\noutput:\n result2:\n [\n {\"id\":\"1\",\"name\":\"Ahmad\",\"title\":\"Manager\",\"stage\":\"Open\"},\n {\"id\":\"2\",\"name\":\"Ahmad\",\"title\":\"Manager\",\"stage\":\"Open\"},\n {\"id\":\"3\",\"name\":\"Ahmad\",\"title\":\"Manager\",\"stage\":\"Open\"},\n {\"id\":\"5\",\"name\":\"Rehmat\",\"title\":\"Chancellor\",\"stage\":\"Open\"}\n ]\n*/" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17625058/" ]
74,504,447
<p>I have this data class written:</p> <pre class="lang-kotlin prettyprint-override"><code>package com.my.app data class User( var uid: String, var nickname: String, var email: String, var description: String = &quot;&quot;, var avatar: String = &quot;default&quot;, var banReason: String = &quot;&quot;, var bannedBy: String = &quot;&quot;, var pin: String = &quot;&quot;, // encrypted var isBanned: Boolean = false, var isVerified: Boolean = false, var isPremiumAccount: Boolean = false, var isAdministrator: Boolean = false, var isModerator: Boolean = false, var isPinEnabled: Boolean = false, var bannedTo: Long = 0, var createdAt: Long = 0 ){ constructor(): this( &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;default&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, false, false, false, false, false, false, 0, java.sql.Timestamp(System.currentTimeMillis()).time ) } </code></pre> <p>and I used that data class to parse documents into that class with this code:</p> <pre><code>val user = userDocumentReference.toObject(User::class.java) </code></pre> <p>and everything worked until I added <code>likedPosts</code> collection to the user document - then <code>val user</code> is always <code>null</code></p> <p>Question - is there any way to put this collection into a data class with a code similar to, for example:</p> <pre class="lang-kotlin prettyprint-override"><code>data class User( var uid: String, var nickname: String, [...] var likedPosts: MutableList&lt;String&gt; // List with liked posts uid's from likedPosts Collection </code></pre> <p>or maybe</p> <pre class="lang-kotlin prettyprint-override"><code>data class User( var uid: String, var nickname: String, [...] var likedPosts: LikedPosts() // LikedPosts() is another data class </code></pre> <p>Or maybe is there a workaround? I can't put everything in one document due to the document size limitation of 1 MB.</p> <p>Or maybe I have to go back to manually assigning values from documents?</p> <pre><code>Firestore-root | --- users (collection) | | (document) (collection) --- $userId ------------------- likedPosts | | --- username: &quot;user&quot; $postUid --- postUid: &quot;xxxxxxxxxxxxxxxa&quot; | | --- avatar: &quot;default&quot; $postUid --- postUid: &quot;xxxxxxxxxxxxxxxb&quot; | | --- isBanned: false $postUid --- postUid: &quot;xxxxxxxxxxxxxxxc&quot; | --- isVerified: true </code></pre> <p><strong>EDIT</strong></p> <p><strong>The value was <code>null</code> because I made a mistake and my app was looking for a user document that does not exist - anyway, is it possible to access the <code>likedPosts</code> collection that is in the document, in one data class?</strong></p>
[ { "answer_id": 74504437, "author": "Georgemff", "author_id": 9716786, "author_profile": "https://Stackoverflow.com/users/9716786", "pm_score": 2, "selected": false, "text": "let filteredArr = arr1.filter((o1) => {\n return arr2.some((o2) => o2.stage === o1.stage);\n});\n" }, { "answer_id": 74506143, "author": "Ping", "author_id": 20288037, "author_profile": "https://Stackoverflow.com/users/20288037", "pm_score": 0, "selected": false, "text": "const arr1 = [\n {id: '1',name: 'Ahmad',title: 'Manager',stage: 'Open',},\n {id: '2',name: 'Ahmad',title: 'Manager',stage: 'Open',},\n {id: '3',name: 'Ahmad',title: 'Manager',stage: 'Open',},\n {id: '4',name: 'Bakshi',title: 'Accountant',stage: 'Closed Won',},\n {id: '5',name: 'Rehmat',title: 'Chancellor',stage: 'Open',}\n ];\n\nconst arr2 = [\n {id: '2', stage: 'Closed', selected: false},\n {id: '3', stage: 'Closed Won', selected: false},\n {id: '4', stage: 'Open Won', selected: false},\n {id: '5', stage: 'Completed', selected: false},\n {id: '1', stage: 'Open', selected: false},\n ];\n\nconst objectKeysOfarr1 = Object.keys(arr1);\nconsole.log(`objectKeysOfarr1: ${objectKeysOfarr1}`);\n/**\noutput:\nobjectKeysOfarr1: 0,1,2,3,4\n*/\n\nconst filterObjectKeysOfarr1 = objectKeysOfarr1\n .filter(index => {\n console.log(`arr1[index].stage: ${arr1[index].stage}`);\n console.log(`arr2[index].stage: ${arr2[index].stage}`);\n console.log(`arr1[index].stage === arr2[index].stage: ${arr1[index].stage === arr2[index].stage}`);\n return arr1[index].stage === arr2[index].stage;\n });\nconsole.log(`filterObjectKeysOfarr1: ${filterObjectKeysOfarr1}`);\n/**\noutput:\n arr1[index].stage: Open\n arr2[index].stage: Closed\n arr1[index].stage === arr2[index].stage: false\n arr1[index].stage: Open\n arr2[index].stage: Closed Won\n arr1[index].stage === arr2[index].stage: false\n arr1[index].stage: Open\n arr2[index].stage: Open Won\n arr1[index].stage === arr2[index].stage: false\n arr1[index].stage: Closed Won\n arr2[index].stage: Completed\n arr1[index].stage === arr2[index].stage: false\n arr1[index].stage: Open\n arr2[index].stage: Open\n arr1[index].stage === arr2[index].stage: true\n filterObjectKeysOfarr1: 4\n*/\n\nconst changedObjects = filterObjectKeysOfarr1\n .map(index => {\n console.log(`arr1[index]: ${JSON.stringify(arr1[index])}`);\n return arr1[index];\n });\nconsole.log(`changedObjects: ${JSON.stringify(changedObjects)}`);\n/**\noutput:\n arr1[index]: {\"id\":\"5\",\"name\":\"Rehmat\",\"title\":\"Chancellor\",\"stage\":\"Open\"}\n changedObjects: [{\"id\":\"5\",\"name\":\"Rehmat\",\"title\":\"Chancellor\",\"stage\":\"Open\"}]\n*/\n\n// As shown in the log, the reason why you are only getting one output, is beacuse the filter you write compares only the object of the same index in 'arr1' and 'arr2', which apparently won't return all 'Open stage' of the arr1.\n// actually, you don't need to compare two arrays if you are only trying to get all 'Open stage' from 'arr1', such as:\n\nconst result1 = arr1.filter(o => o.stage === 'Open');\nconsole.log(`get all open:\\n${JSON.stringify(result1)}`);\n/**\noutput:\n get all open:\n [\n {\"id\":\"1\",\"name\":\"Ahmad\",\"title\":\"Manager\",\"stage\":\"Open\"},\n {\"id\":\"2\",\"name\":\"Ahmad\",\"title\":\"Manager\",\"stage\":\"Open\"},\n {\"id\":\"3\",\"name\":\"Ahmad\",\"title\":\"Manager\",\"stage\":\"Open\"},\n {\"id\":\"5\",\"name\":\"Rehmat\",\"title\":\"Chancellor\",\"stage\":\"Open\"}\n ]\n*/\n\n// let's say if what you want to do is to compare arr1 with arr2 which the stage of arr1 is 'included' in selected stages of arr2, this is how you should do:\n\n// triggerStage(): trigger true/false switch of the 'select' value of the object of the given ID, accept 'id' as number, string or array.\nconst triggerStage = (arr,id) => {\n let ids = [];\n if (!Array.isArray(id)) ids.push(id);\n else ids = id;\n return arr.map(o => ids.some(id => id == o.id) ? (o.selected = !o.selected) && o : o);\n}\n\n// selectedStages(): returns an array of the 'stage' that is being selected.\nconst selectedStages = (arr) => arr.filter(o => o.selected).map(o => o.stage);\n\n// the follow example shows switching on id:1 and 2.\nconst newArr2 = triggerStage(arr2,[1,'2']);\nconsole.log(`newArr2:\\n${JSON.stringify(newArr2)}`);\n/**\noutput:\n newArr2:\n [\n {\"id\": \"2\",\"stage\": \"Closed\",\"selected\": true},\n {\"id\": \"3\",\"stage\": \"Closed Won\",\"selected\": false},\n {\"id\": \"4\",\"stage\": \"Open Won\",\"selected\": false},\n {\"id\": \"5\",\"stage\": \"Completed\",\"selected\": false},\n {\"id\": \"1\",\"stage\": \"Open\",\"selected\": true}\n ]\n*/\n\nconst selected = selectedStages(newArr2);\nconsole.log(`selected: ${JSON.stringify(selected)}`);\n\n/**\noutput: selected: [\"Closed\",\"Open\"]\n*/\n\n// filter 'arr1' to for objects which the 'stage' matches the 'selected' stage of 'arr2':\nconst result2 = arr1.filter(o => selected.some(stage => stage === o.stage));\nconsole.log(`result2:\\n${JSON.stringify(result2)}`);\n/**\noutput:\n result2:\n [\n {\"id\":\"1\",\"name\":\"Ahmad\",\"title\":\"Manager\",\"stage\":\"Open\"},\n {\"id\":\"2\",\"name\":\"Ahmad\",\"title\":\"Manager\",\"stage\":\"Open\"},\n {\"id\":\"3\",\"name\":\"Ahmad\",\"title\":\"Manager\",\"stage\":\"Open\"},\n {\"id\":\"5\",\"name\":\"Rehmat\",\"title\":\"Chancellor\",\"stage\":\"Open\"}\n ]\n*/" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13680873/" ]
74,504,448
<p><a href="https://i.stack.imgur.com/HpkfS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HpkfS.png" alt="" /></a></p> <p>I have a task to take values from a prompt and put them like in the picture, but I don’t really understand how to make everything on the same level, for example, so that the '|' was always under the plus, not paying attention to the length of the word.</p> <p>My result:</p> <p><a href="https://i.stack.imgur.com/qv0UP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qv0UP.png" alt="" /></a></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 arr = [] for (var i = 0; i &gt;= 0; i++) { var input = prompt('Enter any value (enter end to complete the operation) '); if (input === 'end') break; arr[i] = input; } console.log(arr) for (var i = 0; i &lt; arr.length; i++) { console.log(`+-----------------+---------------------+ \n| ${arr[i]} |`) }</code></pre> </div> </div> </p>
[ { "answer_id": 74504437, "author": "Georgemff", "author_id": 9716786, "author_profile": "https://Stackoverflow.com/users/9716786", "pm_score": 2, "selected": false, "text": "let filteredArr = arr1.filter((o1) => {\n return arr2.some((o2) => o2.stage === o1.stage);\n});\n" }, { "answer_id": 74506143, "author": "Ping", "author_id": 20288037, "author_profile": "https://Stackoverflow.com/users/20288037", "pm_score": 0, "selected": false, "text": "const arr1 = [\n {id: '1',name: 'Ahmad',title: 'Manager',stage: 'Open',},\n {id: '2',name: 'Ahmad',title: 'Manager',stage: 'Open',},\n {id: '3',name: 'Ahmad',title: 'Manager',stage: 'Open',},\n {id: '4',name: 'Bakshi',title: 'Accountant',stage: 'Closed Won',},\n {id: '5',name: 'Rehmat',title: 'Chancellor',stage: 'Open',}\n ];\n\nconst arr2 = [\n {id: '2', stage: 'Closed', selected: false},\n {id: '3', stage: 'Closed Won', selected: false},\n {id: '4', stage: 'Open Won', selected: false},\n {id: '5', stage: 'Completed', selected: false},\n {id: '1', stage: 'Open', selected: false},\n ];\n\nconst objectKeysOfarr1 = Object.keys(arr1);\nconsole.log(`objectKeysOfarr1: ${objectKeysOfarr1}`);\n/**\noutput:\nobjectKeysOfarr1: 0,1,2,3,4\n*/\n\nconst filterObjectKeysOfarr1 = objectKeysOfarr1\n .filter(index => {\n console.log(`arr1[index].stage: ${arr1[index].stage}`);\n console.log(`arr2[index].stage: ${arr2[index].stage}`);\n console.log(`arr1[index].stage === arr2[index].stage: ${arr1[index].stage === arr2[index].stage}`);\n return arr1[index].stage === arr2[index].stage;\n });\nconsole.log(`filterObjectKeysOfarr1: ${filterObjectKeysOfarr1}`);\n/**\noutput:\n arr1[index].stage: Open\n arr2[index].stage: Closed\n arr1[index].stage === arr2[index].stage: false\n arr1[index].stage: Open\n arr2[index].stage: Closed Won\n arr1[index].stage === arr2[index].stage: false\n arr1[index].stage: Open\n arr2[index].stage: Open Won\n arr1[index].stage === arr2[index].stage: false\n arr1[index].stage: Closed Won\n arr2[index].stage: Completed\n arr1[index].stage === arr2[index].stage: false\n arr1[index].stage: Open\n arr2[index].stage: Open\n arr1[index].stage === arr2[index].stage: true\n filterObjectKeysOfarr1: 4\n*/\n\nconst changedObjects = filterObjectKeysOfarr1\n .map(index => {\n console.log(`arr1[index]: ${JSON.stringify(arr1[index])}`);\n return arr1[index];\n });\nconsole.log(`changedObjects: ${JSON.stringify(changedObjects)}`);\n/**\noutput:\n arr1[index]: {\"id\":\"5\",\"name\":\"Rehmat\",\"title\":\"Chancellor\",\"stage\":\"Open\"}\n changedObjects: [{\"id\":\"5\",\"name\":\"Rehmat\",\"title\":\"Chancellor\",\"stage\":\"Open\"}]\n*/\n\n// As shown in the log, the reason why you are only getting one output, is beacuse the filter you write compares only the object of the same index in 'arr1' and 'arr2', which apparently won't return all 'Open stage' of the arr1.\n// actually, you don't need to compare two arrays if you are only trying to get all 'Open stage' from 'arr1', such as:\n\nconst result1 = arr1.filter(o => o.stage === 'Open');\nconsole.log(`get all open:\\n${JSON.stringify(result1)}`);\n/**\noutput:\n get all open:\n [\n {\"id\":\"1\",\"name\":\"Ahmad\",\"title\":\"Manager\",\"stage\":\"Open\"},\n {\"id\":\"2\",\"name\":\"Ahmad\",\"title\":\"Manager\",\"stage\":\"Open\"},\n {\"id\":\"3\",\"name\":\"Ahmad\",\"title\":\"Manager\",\"stage\":\"Open\"},\n {\"id\":\"5\",\"name\":\"Rehmat\",\"title\":\"Chancellor\",\"stage\":\"Open\"}\n ]\n*/\n\n// let's say if what you want to do is to compare arr1 with arr2 which the stage of arr1 is 'included' in selected stages of arr2, this is how you should do:\n\n// triggerStage(): trigger true/false switch of the 'select' value of the object of the given ID, accept 'id' as number, string or array.\nconst triggerStage = (arr,id) => {\n let ids = [];\n if (!Array.isArray(id)) ids.push(id);\n else ids = id;\n return arr.map(o => ids.some(id => id == o.id) ? (o.selected = !o.selected) && o : o);\n}\n\n// selectedStages(): returns an array of the 'stage' that is being selected.\nconst selectedStages = (arr) => arr.filter(o => o.selected).map(o => o.stage);\n\n// the follow example shows switching on id:1 and 2.\nconst newArr2 = triggerStage(arr2,[1,'2']);\nconsole.log(`newArr2:\\n${JSON.stringify(newArr2)}`);\n/**\noutput:\n newArr2:\n [\n {\"id\": \"2\",\"stage\": \"Closed\",\"selected\": true},\n {\"id\": \"3\",\"stage\": \"Closed Won\",\"selected\": false},\n {\"id\": \"4\",\"stage\": \"Open Won\",\"selected\": false},\n {\"id\": \"5\",\"stage\": \"Completed\",\"selected\": false},\n {\"id\": \"1\",\"stage\": \"Open\",\"selected\": true}\n ]\n*/\n\nconst selected = selectedStages(newArr2);\nconsole.log(`selected: ${JSON.stringify(selected)}`);\n\n/**\noutput: selected: [\"Closed\",\"Open\"]\n*/\n\n// filter 'arr1' to for objects which the 'stage' matches the 'selected' stage of 'arr2':\nconst result2 = arr1.filter(o => selected.some(stage => stage === o.stage));\nconsole.log(`result2:\\n${JSON.stringify(result2)}`);\n/**\noutput:\n result2:\n [\n {\"id\":\"1\",\"name\":\"Ahmad\",\"title\":\"Manager\",\"stage\":\"Open\"},\n {\"id\":\"2\",\"name\":\"Ahmad\",\"title\":\"Manager\",\"stage\":\"Open\"},\n {\"id\":\"3\",\"name\":\"Ahmad\",\"title\":\"Manager\",\"stage\":\"Open\"},\n {\"id\":\"5\",\"name\":\"Rehmat\",\"title\":\"Chancellor\",\"stage\":\"Open\"}\n ]\n*/" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20502283/" ]
74,504,455
<p>I have the following data frame:</p> <pre><code>A1_Q1 &lt;- c(1, 2, 3) A1_Q2 &lt;- c(4, 5, 6) A1_Q3 &lt;- c(7, 8, 9) A1_Q4 &lt;- c(10, 11, 12) A1_Q5 &lt;- c(13, 14, 15) A1_Q6 &lt;- c(16, 17, 18) A2_Q1 &lt;- c(1, 2, 3) A2_Q2 &lt;- c(4, 5, 6) A2_Q3 &lt;- c(7, 8, 9) A2_Q4 &lt;- c(10, 11, 12) A2_Q5 &lt;- c(13, 14, 15) A2_Q6 &lt;- c(16, 17, 18) df &lt;- data.frame(A1_Q1, A1_Q2, A1_Q3, A1_Q4, A1_Q5, A1_Q6, A2_Q1, A2_Q2, A2_Q3, A2_Q4, A2_Q5, A2_Q6) </code></pre> <p>I want to create additional variables called <code>col1a, col1b, col1c</code>.</p> <pre><code>df &lt;- df %&gt;% unite(&quot;col1a&quot;, A1_Q1, A1_Q2, sep=&quot;-&quot;, remove = FALSE) %&gt;% unite(&quot;col1b&quot;, A1_Q3, A1_Q4, sep=&quot;-&quot;, remove = FALSE) %&gt;% unite(&quot;col1c&quot;, A1_Q5, A1_Q6, sep=&quot;-&quot;, remove = FALSE) </code></pre> <p>I also want to do the same thing for the A2 variables.</p> <p>Is there any way I can also create variables called <code>col2a, col2b, col2c</code> in one go? I'm envisioning a for loop that looks something like this:</p> <pre><code>for (i in 1:2) { df &lt;- df %&gt;% unite(&quot;colia&quot;, Ai_Q1, Ai_Q2, sep=&quot;-&quot;, remove = FALSE) %&gt;% unite(&quot;colib&quot;, Ai_Q3, Ai_Q4, sep=&quot;-&quot;, remove = FALSE) %&gt;% unite(&quot;colic&quot;, Ai_Q5, Ai_Q6, sep=&quot;-&quot;, remove = FALSE) } </code></pre>
[ { "answer_id": 74504493, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": -1, "selected": false, "text": "list split.default gl list lapply paste list do.call list nm1 <- paste0(\"col\", rep(unique( sub(\".(\\\\d+)_.*\", \"\\\\1\", \n names(df))), each = 3), letters[1:3])\ndf[nm1] <- lapply(split.default(df, as.integer(gl(ncol(df), 2, ncol(df)))), \n function(x) do.call(paste, c(x, sep = '-')))\n > df\n A1_Q1 A1_Q2 A1_Q3 A1_Q4 A1_Q5 A1_Q6 A2_Q1 A2_Q2 A2_Q3 A2_Q4 A2_Q5 A2_Q6 col1a col1b col1c col2a col2b col2c\n1 1 4 7 10 13 16 1 4 7 10 13 16 1-4 7-10 13-16 1-4 7-10 13-16\n2 2 5 8 11 14 17 2 5 8 11 14 17 2-5 8-11 14-17 2-5 8-11 14-17\n3 3 6 9 12 15 18 3 6 9 12 15 18 3-6 9-12 15-18 3-6 9-12 15-18\n tidyverse pivot_longer separate case_when unite pivot_wider library(dplyr)\nlibrary(tidyr)\nlibrary(stringr)\ndf %>% \n mutate(rn = row_number()) %>%\n pivot_longer(cols = -rn) %>%\n separate(name, into = c(\"name1\", \"name2\")) %>%\n mutate( name2 = case_when(name2 %in% c(\"Q1\", \"Q2\") ~ \"a\", \n name2 %in% c(\"Q3\", \"Q4\") ~ \"b\", TRUE ~ \"c\")) %>% \n group_by(rn, name1, name2) %>% \n summarise(value = str_c(value, collapse = '-'), .groups = 'drop') %>%\n mutate(name1 = str_replace(name1, \"\\\\D+\", \"col\")) %>%\n unite(name, name1, name2, sep = \"\") %>% \n pivot_wider(names_from = name, values_from = value) %>% \n select(-rn) %>% \n bind_cols(df, .)\n A1_Q1 A1_Q2 A1_Q3 A1_Q4 A1_Q5 A1_Q6 A2_Q1 A2_Q2 A2_Q3 A2_Q4 A2_Q5 A2_Q6 col1a col1b col1c col2a col2b col2c\n1 1 4 7 10 13 16 1 4 7 10 13 16 1-4 7-10 13-16 1-4 7-10 13-16\n2 2 5 8 11 14 17 2 5 8 11 14 17 2-5 8-11 14-17 2-5 8-11 14-17\n3 3 6 9 12 15 18 3 6 9 12 15 18 3-6 9-12 15-18 3-6 9-12 15-18\n Map paste df[nm1] <- Map(function(x, y) paste(x, y, sep = \"-\"), df[c(TRUE, FALSE)], \n df[c(FALSE, TRUE)])\n > df\n A1_Q1 A1_Q2 A1_Q3 A1_Q4 A1_Q5 A1_Q6 A2_Q1 A2_Q2 A2_Q3 A2_Q4 A2_Q5 A2_Q6 col1a col1b col1c col2a col2b col2c\n1 1 4 7 10 13 16 1 4 7 10 13 16 1-4 7-10 13-16 1-4 7-10 13-16\n2 2 5 8 11 14 17 2 5 8 11 14 17 2-5 8-11 14-17 2-5 8-11 14-17\n3 3 6 9 12 15 18 3 6 9 12 15 18 3-6 9-12 15-18 3-6 9-12 15-18\n" }, { "answer_id": 74506763, "author": "jay.sf", "author_id": 6574038, "author_profile": "https://Stackoverflow.com/users/6574038", "pm_score": 0, "selected": false, "text": "^A1 ^A2 grep sb lapply 1:2 sprintf A1 A2 paste0 sb[(1:2) + x] sb 2 ncol(sb) paste0 col x letters setNames cbind res <- lapply(1:2, \\(x) {\n sb <- df[grep(sprintf('^A%s', x), names(df))]\n lapply((0:((ncol(sb) - 1)/2))*2, \\(x) Reduce(\\(y, z) paste0(y, '-', z), sb[(1:2) + x])) |>\n setNames(paste0('col', x, letters[seq_len((ncol(sb))/2)]))\n}) |> cbind(df)\n\nres\n# col1a col1b col1c col2a col2b col2c A1_Q1 A1_Q2 A1_Q3 A1_Q4 A1_Q5 A1_Q6 A2_Q1\n# 1 1-4 7-10 13-16 1-4 7-10 13-16 1 4 7 10 13 16 1\n# 2 2-5 8-11 14-17 2-5 8-11 14-17 2 5 8 11 14 17 2\n# 3 3-6 9-12 15-18 3-6 9-12 15-18 3 6 9 12 15 18 3\n# A2_Q2 A2_Q3 A2_Q4 A2_Q5 A2_Q6\n# 1 4 7 10 13 16\n# 2 5 8 11 14 17\n# 3 6 9 12 15 18\n A* Q res <- cbind(lapply(1:2, function(x) {\n sb <- df[grep(sprintf('^A%s', x), names(df))]\n lapply((0:((ncol(sb) - 1)/2))*2, function(x) Reduce(function(y, z) paste0(y, '-', z), sb[(1:2) + x])) |>\n setNames(paste0('col', x, letters[seq_len((ncol(sb))/2)]))\n}), df)\n" }, { "answer_id": 74513704, "author": "Santiago", "author_id": 13507658, "author_profile": "https://Stackoverflow.com/users/13507658", "pm_score": 1, "selected": false, "text": "paste0 [[ map_dfc .x map_dfc mutate library(tidyverse)\n\nA1_Q1 <- c(1, 2, 3)\nA1_Q2 <- c(4, 5, 6)\nA1_Q3 <- c(7, 8, 9)\nA1_Q4 <- c(10, 11, 12)\nA1_Q5 <- c(13, 14, 15)\nA1_Q6 <- c(16, 17, 18)\n\nA2_Q1 <- c(1, 2, 3)\nA2_Q2 <- c(4, 5, 6)\nA2_Q3 <- c(7, 8, 9)\nA2_Q4 <- c(10, 11, 12)\nA2_Q5 <- c(13, 14, 15)\nA2_Q6 <- c(16, 17, 18)\n\ndf <- data.frame(A1_Q1, A1_Q2, A1_Q3, A1_Q4, A1_Q5, A1_Q6,\n A2_Q1, A2_Q2, A2_Q3, A2_Q4, A2_Q5, A2_Q6)\n\ndf %>%\n mutate(\n map_dfc(\n 1:2,\n ~ {\n cols <- list(\n paste(\n df[[paste0(\"A\", .x, \"_Q1\")]],\n df[[paste0(\"A\", .x, \"_Q2\")]],\n sep = \"-\"\n ),\n paste(\n df[[paste0(\"A\", .x, \"_Q3\")]],\n df[[paste0(\"A\", .x, \"_Q4\")]],\n sep = \"-\"\n ),\n paste(\n df[[paste0(\"A\", .x, \"_Q5\")]],\n df[[paste0(\"A\", .x, \"_Q6\")]],\n sep = \"-\"\n )\n )\n \n names(cols) <- c(\n paste0(\"col\", .x, \"a\"),\n paste0(\"col\", .x, \"b\"),\n paste0(\"col\", .x, \"c\")\n )\n \n cols\n \n }\n )\n )\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4937644/" ]
74,504,488
<p>T1 T2 T3 T4 T5 1 1 NA NA 1 NA NA 1 1 1 NA 1 NA NA NA NA NA NA NA 1</p> <p>suppose my dataframe is like this (plz see the picture below, sorry I don't know how to replicate this data in stackoverflow). T1 stands for the first period,T5 stands for the last.</p> <p><a href="https://i.stack.imgur.com/LsBxj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LsBxj.png" alt="enter image description here" /></a></p> <p>For each row, I want to find a longest spread such that between this two index, there isn't NA appears.</p> <p>So the outcome for the first row should be from T1 To T2 (index 1 to index2)</p> <p>the outcome for row 2 should be T3 - T5 the outcome for row 3 should be 0, since there isn't such a satisfied outcome.</p> <p>and I would like all results to be put into the dataframe, because I have actually tons of rows, so I hope my final dataset would be like:</p> <p><a href="https://i.stack.imgur.com/WeqA7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WeqA7.png" alt="enter image description here" /></a></p> <p>THANK YOU SO MUCH</p>
[ { "answer_id": 74504493, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": -1, "selected": false, "text": "list split.default gl list lapply paste list do.call list nm1 <- paste0(\"col\", rep(unique( sub(\".(\\\\d+)_.*\", \"\\\\1\", \n names(df))), each = 3), letters[1:3])\ndf[nm1] <- lapply(split.default(df, as.integer(gl(ncol(df), 2, ncol(df)))), \n function(x) do.call(paste, c(x, sep = '-')))\n > df\n A1_Q1 A1_Q2 A1_Q3 A1_Q4 A1_Q5 A1_Q6 A2_Q1 A2_Q2 A2_Q3 A2_Q4 A2_Q5 A2_Q6 col1a col1b col1c col2a col2b col2c\n1 1 4 7 10 13 16 1 4 7 10 13 16 1-4 7-10 13-16 1-4 7-10 13-16\n2 2 5 8 11 14 17 2 5 8 11 14 17 2-5 8-11 14-17 2-5 8-11 14-17\n3 3 6 9 12 15 18 3 6 9 12 15 18 3-6 9-12 15-18 3-6 9-12 15-18\n tidyverse pivot_longer separate case_when unite pivot_wider library(dplyr)\nlibrary(tidyr)\nlibrary(stringr)\ndf %>% \n mutate(rn = row_number()) %>%\n pivot_longer(cols = -rn) %>%\n separate(name, into = c(\"name1\", \"name2\")) %>%\n mutate( name2 = case_when(name2 %in% c(\"Q1\", \"Q2\") ~ \"a\", \n name2 %in% c(\"Q3\", \"Q4\") ~ \"b\", TRUE ~ \"c\")) %>% \n group_by(rn, name1, name2) %>% \n summarise(value = str_c(value, collapse = '-'), .groups = 'drop') %>%\n mutate(name1 = str_replace(name1, \"\\\\D+\", \"col\")) %>%\n unite(name, name1, name2, sep = \"\") %>% \n pivot_wider(names_from = name, values_from = value) %>% \n select(-rn) %>% \n bind_cols(df, .)\n A1_Q1 A1_Q2 A1_Q3 A1_Q4 A1_Q5 A1_Q6 A2_Q1 A2_Q2 A2_Q3 A2_Q4 A2_Q5 A2_Q6 col1a col1b col1c col2a col2b col2c\n1 1 4 7 10 13 16 1 4 7 10 13 16 1-4 7-10 13-16 1-4 7-10 13-16\n2 2 5 8 11 14 17 2 5 8 11 14 17 2-5 8-11 14-17 2-5 8-11 14-17\n3 3 6 9 12 15 18 3 6 9 12 15 18 3-6 9-12 15-18 3-6 9-12 15-18\n Map paste df[nm1] <- Map(function(x, y) paste(x, y, sep = \"-\"), df[c(TRUE, FALSE)], \n df[c(FALSE, TRUE)])\n > df\n A1_Q1 A1_Q2 A1_Q3 A1_Q4 A1_Q5 A1_Q6 A2_Q1 A2_Q2 A2_Q3 A2_Q4 A2_Q5 A2_Q6 col1a col1b col1c col2a col2b col2c\n1 1 4 7 10 13 16 1 4 7 10 13 16 1-4 7-10 13-16 1-4 7-10 13-16\n2 2 5 8 11 14 17 2 5 8 11 14 17 2-5 8-11 14-17 2-5 8-11 14-17\n3 3 6 9 12 15 18 3 6 9 12 15 18 3-6 9-12 15-18 3-6 9-12 15-18\n" }, { "answer_id": 74506763, "author": "jay.sf", "author_id": 6574038, "author_profile": "https://Stackoverflow.com/users/6574038", "pm_score": 0, "selected": false, "text": "^A1 ^A2 grep sb lapply 1:2 sprintf A1 A2 paste0 sb[(1:2) + x] sb 2 ncol(sb) paste0 col x letters setNames cbind res <- lapply(1:2, \\(x) {\n sb <- df[grep(sprintf('^A%s', x), names(df))]\n lapply((0:((ncol(sb) - 1)/2))*2, \\(x) Reduce(\\(y, z) paste0(y, '-', z), sb[(1:2) + x])) |>\n setNames(paste0('col', x, letters[seq_len((ncol(sb))/2)]))\n}) |> cbind(df)\n\nres\n# col1a col1b col1c col2a col2b col2c A1_Q1 A1_Q2 A1_Q3 A1_Q4 A1_Q5 A1_Q6 A2_Q1\n# 1 1-4 7-10 13-16 1-4 7-10 13-16 1 4 7 10 13 16 1\n# 2 2-5 8-11 14-17 2-5 8-11 14-17 2 5 8 11 14 17 2\n# 3 3-6 9-12 15-18 3-6 9-12 15-18 3 6 9 12 15 18 3\n# A2_Q2 A2_Q3 A2_Q4 A2_Q5 A2_Q6\n# 1 4 7 10 13 16\n# 2 5 8 11 14 17\n# 3 6 9 12 15 18\n A* Q res <- cbind(lapply(1:2, function(x) {\n sb <- df[grep(sprintf('^A%s', x), names(df))]\n lapply((0:((ncol(sb) - 1)/2))*2, function(x) Reduce(function(y, z) paste0(y, '-', z), sb[(1:2) + x])) |>\n setNames(paste0('col', x, letters[seq_len((ncol(sb))/2)]))\n}), df)\n" }, { "answer_id": 74513704, "author": "Santiago", "author_id": 13507658, "author_profile": "https://Stackoverflow.com/users/13507658", "pm_score": 1, "selected": false, "text": "paste0 [[ map_dfc .x map_dfc mutate library(tidyverse)\n\nA1_Q1 <- c(1, 2, 3)\nA1_Q2 <- c(4, 5, 6)\nA1_Q3 <- c(7, 8, 9)\nA1_Q4 <- c(10, 11, 12)\nA1_Q5 <- c(13, 14, 15)\nA1_Q6 <- c(16, 17, 18)\n\nA2_Q1 <- c(1, 2, 3)\nA2_Q2 <- c(4, 5, 6)\nA2_Q3 <- c(7, 8, 9)\nA2_Q4 <- c(10, 11, 12)\nA2_Q5 <- c(13, 14, 15)\nA2_Q6 <- c(16, 17, 18)\n\ndf <- data.frame(A1_Q1, A1_Q2, A1_Q3, A1_Q4, A1_Q5, A1_Q6,\n A2_Q1, A2_Q2, A2_Q3, A2_Q4, A2_Q5, A2_Q6)\n\ndf %>%\n mutate(\n map_dfc(\n 1:2,\n ~ {\n cols <- list(\n paste(\n df[[paste0(\"A\", .x, \"_Q1\")]],\n df[[paste0(\"A\", .x, \"_Q2\")]],\n sep = \"-\"\n ),\n paste(\n df[[paste0(\"A\", .x, \"_Q3\")]],\n df[[paste0(\"A\", .x, \"_Q4\")]],\n sep = \"-\"\n ),\n paste(\n df[[paste0(\"A\", .x, \"_Q5\")]],\n df[[paste0(\"A\", .x, \"_Q6\")]],\n sep = \"-\"\n )\n )\n \n names(cols) <- c(\n paste0(\"col\", .x, \"a\"),\n paste0(\"col\", .x, \"b\"),\n paste0(\"col\", .x, \"c\")\n )\n \n cols\n \n }\n )\n )\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20318210/" ]
74,504,496
<p>I have <code>df1</code>:</p> <pre><code> x y no. 0 -17.7 -0.785430 y1 1 -15.0 -3820.085000 y4 2 -12.5 2.138833 y3 .. .... ........ .. 40 15.6 5.486901 y2 41 19.2 1.980686 y3 42 19.6 9.364718 y2 </code></pre> <p>and <code>df2</code>:</p> <pre><code> delta y x 0 0.053884 -17.7 1 0.085000 -15.0 2 0.143237 -12.5 .. ........ .... 40 0.113099 15.6 41 0.102245 19.2 42 0.235282 19.6 </code></pre> <p>They both have 43 rows, and <code>x</code> column is exactly the same on both.</p> <p>Somehow when I merge them on <code>x</code> I get a df with 123 rows:</p> <pre><code> x y no. delta y 0 -17.7 -0.785430 y1 0.053884 1 -15.0 -3820.085000 y4 0.085000 2 -12.5 2.138833 y3 0.143237 3 -12.4 1.721205 y3 0.251180 4 -12.1 2.227343 y2 0.127343 .. ... ... .. ... 118 12.1 1.642526 y3 0.143886 119 14.4 2576.435000 y4 0.171000 120 15.6 5.486901 y2 0.113099 121 19.2 1.980686 y3 0.102245 122 19.6 9.364718 y2 0.235282 </code></pre> <p>My input: <code>final = df1.merge(df2, on=&quot;x&quot;)</code> x float64 y float64 no. object dtype: object</p> <p>delta y float64 x float64 dtype: object</p> <p>x float64 y float64 no. object dtype: object</p> <p>delta y float64 x float64 dtype: object</p> <p>x float64 y float64 no. object dtype: object</p> <p>delta y float64 x float64 dtype: object</p> <p>df1 = pd.DataFrame({'x': {0: -17.7, 1: -15.0, 2: -12.5, 3: -12.4, 4: -12.1, 5: -11.2, 6: -8.9, 7: -7.5, 8: -7.5, 9: -6.0, 10: -6.0, 11: -4.7, 12: -4.1, 13: -3.8, 14: -3.4, 15: -3.4, 16: -1.9, 17: -1.5, 18: -1.1, 19: -0.4, 20: -0.1, 21: 3.5, 22: 3.8, 23: 5.3, 24: 5.3, 25: 5.3, 26: 5.3, 27: 5.3, 28: 5.3, 29: 5.3, 30: 5.3, 31: 5.3, 32: 6.4, 33: 6.8, 34: 6.8, 35: 10.2, 36: 10.3, 37: 11.9, 38: 12.1, 39: 14.4, 40: 15.6, 41: 19.2, 42: 19.6}, 'y': {0: -0.7854295, 1: -3820.085, 2: 2.1388333, 3: 1.7212046, 4: 2.227343, 5: 0.04315967, 6: -0.9616607, 7: -1.9878536, 8: -0.52237016, 9: -283.27216, 10: -282.5332, 11: -0.4335017, 12: -1.1585577, 13: -0.008831219, 14: 848.92303, 15: -57.407845, 16: -9.010686, 17: -3.2473037, 18: 0.5536767, 19: 1.8351307, 20: 4.8347697, 21: -6.45842, 22: -1.5683812, 23: 0.9338831, 24: 0.9338831, 25: 97.65833, 26: 1.6500127, 27: 1.6500127, 28: 97.65833, 29: 97.65833, 30: 1.6500127, 31: 97.65833, 32: -3.655422, 33: 1.9058462, 34: 227.5592, 35: 857.7455, 36: -0.68584794, 37: 1.6785516, 38: 1.6425261, 39: 2576.435, 40: 5.4869013, 41: 1.9806856, 42: 9.364718}, 'no.': {0: 'y1', 1: 'y4', 2: 'y3', 3: 'y3', 4: 'y2', 5: 'y3', 6: 'y2', 7: 'y2', 8: 'y2', 9: 'y4', 10: 'y4', 11: 'y1', 12: 'y3', 13: 'y1', 14: 'y4', 15: 'y4', 16: 'y4', 17: 'y4', 18: 'y1', 19: 'y3', 20: 'y4', 21: 'y2', 22: 'y3', 23: 'y3', 24: 'y3', 25: 'y4', 26: 'y3', 27: 'y3', 28: 'y4', 29: 'y3', 30: 'y4', 31: 'y4', 32: 'y2', 33: 'y3', 34: 'y3', 35: 'y4', 36: 'y3', 37: 'y3', 38: 'y3', 39: 'y4', 40: 'y2', 41: 'y3', 42: 'y2'}})</p> <p>df2 = pd.DataFrame({'delta y': {0: 0.05388353000000001, 1: 0.08500000000003638, 2: 0.14323679999999994, 3: 0.25117999999999996, 4: 0.12734299999999976, 5: 0.36285006000000003, 6: 0.13833930000000005, 7: 0.5121464, 8: 1.97762984, 9: 0.2721599999999853, 10: 0.4667999999999779, 11: 0.2692114, 12: 0.00890970000000002, 13: 0.314458351, 14: 906.34703, 15: 0.0161549999999977, 16: 0.06831400000000087, 17: 0.3723036999999998, 18: 0.2988478, 19: 0.006991300000000145, 20: 0.14423030000000026, 21: 0.04157999999999973, 22: 0.013554200000000183, 23: 0.17486560000000007, 24: 0.17486560000000007, 25: 0.03866999999999621, 26: 0.541264, 27: 0.541264, 28: 0.03866999999999621, 29: 96.5495813, 30: 96.0469873, 31: 0.03866999999999621, 32: 0.05542200000000008, 33: 0.1670513, 34: 225.82040510000002, 35: 0.38250000000005, 36: 0.59580486, 37: 0.10641100000000003, 38: 0.14388610000000002, 39: 0.17099999999982174, 40: 0.11309869999999922, 41: 0.10224489999999986, 42: 0.23528199999999977}, 'x': {0: -17.7, 1: -15.0, 2: -12.5, 3: -12.4, 4: -12.1, 5: -11.2, 6: -8.9, 7: -7.5, 8: -7.5, 9: -6.0, 10: -6.0, 11: -4.7, 12: -4.1, 13: -3.8, 14: -3.4, 15: -3.4, 16: -1.9, 17: -1.5, 18: -1.1, 19: -0.4, 20: -0.1, 21: 3.5, 22: 3.8, 23: 5.3, 24: 5.3, 25: 5.3, 26: 5.3, 27: 5.3, 28: 5.3, 29: 5.3, 30: 5.3, 31: 5.3, 32: 6.4, 33: 6.8, 34: 6.8, 35: 10.2, 36: 10.3, 37: 11.9, 38: 12.1, 39: 14.4, 40: 15.6, 41: 19.2, 42: 19.6}})</p> <p><code>final = df1.merge(df2, on=&quot;x&quot;)</code></p>
[ { "answer_id": 74504493, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": -1, "selected": false, "text": "list split.default gl list lapply paste list do.call list nm1 <- paste0(\"col\", rep(unique( sub(\".(\\\\d+)_.*\", \"\\\\1\", \n names(df))), each = 3), letters[1:3])\ndf[nm1] <- lapply(split.default(df, as.integer(gl(ncol(df), 2, ncol(df)))), \n function(x) do.call(paste, c(x, sep = '-')))\n > df\n A1_Q1 A1_Q2 A1_Q3 A1_Q4 A1_Q5 A1_Q6 A2_Q1 A2_Q2 A2_Q3 A2_Q4 A2_Q5 A2_Q6 col1a col1b col1c col2a col2b col2c\n1 1 4 7 10 13 16 1 4 7 10 13 16 1-4 7-10 13-16 1-4 7-10 13-16\n2 2 5 8 11 14 17 2 5 8 11 14 17 2-5 8-11 14-17 2-5 8-11 14-17\n3 3 6 9 12 15 18 3 6 9 12 15 18 3-6 9-12 15-18 3-6 9-12 15-18\n tidyverse pivot_longer separate case_when unite pivot_wider library(dplyr)\nlibrary(tidyr)\nlibrary(stringr)\ndf %>% \n mutate(rn = row_number()) %>%\n pivot_longer(cols = -rn) %>%\n separate(name, into = c(\"name1\", \"name2\")) %>%\n mutate( name2 = case_when(name2 %in% c(\"Q1\", \"Q2\") ~ \"a\", \n name2 %in% c(\"Q3\", \"Q4\") ~ \"b\", TRUE ~ \"c\")) %>% \n group_by(rn, name1, name2) %>% \n summarise(value = str_c(value, collapse = '-'), .groups = 'drop') %>%\n mutate(name1 = str_replace(name1, \"\\\\D+\", \"col\")) %>%\n unite(name, name1, name2, sep = \"\") %>% \n pivot_wider(names_from = name, values_from = value) %>% \n select(-rn) %>% \n bind_cols(df, .)\n A1_Q1 A1_Q2 A1_Q3 A1_Q4 A1_Q5 A1_Q6 A2_Q1 A2_Q2 A2_Q3 A2_Q4 A2_Q5 A2_Q6 col1a col1b col1c col2a col2b col2c\n1 1 4 7 10 13 16 1 4 7 10 13 16 1-4 7-10 13-16 1-4 7-10 13-16\n2 2 5 8 11 14 17 2 5 8 11 14 17 2-5 8-11 14-17 2-5 8-11 14-17\n3 3 6 9 12 15 18 3 6 9 12 15 18 3-6 9-12 15-18 3-6 9-12 15-18\n Map paste df[nm1] <- Map(function(x, y) paste(x, y, sep = \"-\"), df[c(TRUE, FALSE)], \n df[c(FALSE, TRUE)])\n > df\n A1_Q1 A1_Q2 A1_Q3 A1_Q4 A1_Q5 A1_Q6 A2_Q1 A2_Q2 A2_Q3 A2_Q4 A2_Q5 A2_Q6 col1a col1b col1c col2a col2b col2c\n1 1 4 7 10 13 16 1 4 7 10 13 16 1-4 7-10 13-16 1-4 7-10 13-16\n2 2 5 8 11 14 17 2 5 8 11 14 17 2-5 8-11 14-17 2-5 8-11 14-17\n3 3 6 9 12 15 18 3 6 9 12 15 18 3-6 9-12 15-18 3-6 9-12 15-18\n" }, { "answer_id": 74506763, "author": "jay.sf", "author_id": 6574038, "author_profile": "https://Stackoverflow.com/users/6574038", "pm_score": 0, "selected": false, "text": "^A1 ^A2 grep sb lapply 1:2 sprintf A1 A2 paste0 sb[(1:2) + x] sb 2 ncol(sb) paste0 col x letters setNames cbind res <- lapply(1:2, \\(x) {\n sb <- df[grep(sprintf('^A%s', x), names(df))]\n lapply((0:((ncol(sb) - 1)/2))*2, \\(x) Reduce(\\(y, z) paste0(y, '-', z), sb[(1:2) + x])) |>\n setNames(paste0('col', x, letters[seq_len((ncol(sb))/2)]))\n}) |> cbind(df)\n\nres\n# col1a col1b col1c col2a col2b col2c A1_Q1 A1_Q2 A1_Q3 A1_Q4 A1_Q5 A1_Q6 A2_Q1\n# 1 1-4 7-10 13-16 1-4 7-10 13-16 1 4 7 10 13 16 1\n# 2 2-5 8-11 14-17 2-5 8-11 14-17 2 5 8 11 14 17 2\n# 3 3-6 9-12 15-18 3-6 9-12 15-18 3 6 9 12 15 18 3\n# A2_Q2 A2_Q3 A2_Q4 A2_Q5 A2_Q6\n# 1 4 7 10 13 16\n# 2 5 8 11 14 17\n# 3 6 9 12 15 18\n A* Q res <- cbind(lapply(1:2, function(x) {\n sb <- df[grep(sprintf('^A%s', x), names(df))]\n lapply((0:((ncol(sb) - 1)/2))*2, function(x) Reduce(function(y, z) paste0(y, '-', z), sb[(1:2) + x])) |>\n setNames(paste0('col', x, letters[seq_len((ncol(sb))/2)]))\n}), df)\n" }, { "answer_id": 74513704, "author": "Santiago", "author_id": 13507658, "author_profile": "https://Stackoverflow.com/users/13507658", "pm_score": 1, "selected": false, "text": "paste0 [[ map_dfc .x map_dfc mutate library(tidyverse)\n\nA1_Q1 <- c(1, 2, 3)\nA1_Q2 <- c(4, 5, 6)\nA1_Q3 <- c(7, 8, 9)\nA1_Q4 <- c(10, 11, 12)\nA1_Q5 <- c(13, 14, 15)\nA1_Q6 <- c(16, 17, 18)\n\nA2_Q1 <- c(1, 2, 3)\nA2_Q2 <- c(4, 5, 6)\nA2_Q3 <- c(7, 8, 9)\nA2_Q4 <- c(10, 11, 12)\nA2_Q5 <- c(13, 14, 15)\nA2_Q6 <- c(16, 17, 18)\n\ndf <- data.frame(A1_Q1, A1_Q2, A1_Q3, A1_Q4, A1_Q5, A1_Q6,\n A2_Q1, A2_Q2, A2_Q3, A2_Q4, A2_Q5, A2_Q6)\n\ndf %>%\n mutate(\n map_dfc(\n 1:2,\n ~ {\n cols <- list(\n paste(\n df[[paste0(\"A\", .x, \"_Q1\")]],\n df[[paste0(\"A\", .x, \"_Q2\")]],\n sep = \"-\"\n ),\n paste(\n df[[paste0(\"A\", .x, \"_Q3\")]],\n df[[paste0(\"A\", .x, \"_Q4\")]],\n sep = \"-\"\n ),\n paste(\n df[[paste0(\"A\", .x, \"_Q5\")]],\n df[[paste0(\"A\", .x, \"_Q6\")]],\n sep = \"-\"\n )\n )\n \n names(cols) <- c(\n paste0(\"col\", .x, \"a\"),\n paste0(\"col\", .x, \"b\"),\n paste0(\"col\", .x, \"c\")\n )\n \n cols\n \n }\n )\n )\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20458338/" ]
74,504,497
<p>I'm noticing the following weird behaviour for the <code>toTimeString</code> method.</p> <pre><code>const date1 = new Date(&quot;2022-09-23T00:00:00.00Z&quot;) const date2 = new Date() date1.toTimeString() //17:00:00 GMT-0700 (Pacific Daylight Saving Time) date2.toTimeString() // 15:06:43 GMT-0800 (Pacific Standard Time) </code></pre> <p>I've also noticed that result for <code>date1</code> even depends on the device region settings (for Mac at least)</p> <pre><code>date1.toTimeString() // if region is set to Canada // 17:00:00 GMT-0700 (Pacific Daylight Saving Time) // if region is set to United States // 17:00:00 GMT-0700 (Pacific Daylight Time) </code></pre> <p>Another observation</p> <pre><code>date2.toTimeString() // this is the result for both United States and Canada // 15:06:43 GMT-0800 (Pacific Standard Time) </code></pre> <p>A couple of questions</p> <ol> <li><p>Why does the result depend on how the date is constructed? (<code>new Date(&quot;2022-09-23T00:00:00.00Z&quot;)</code> vs <code>new Date</code>)</p> </li> <li><p>For <code>new Date(&quot;2022-09-23T00:00:00.00Z&quot;)</code>, why does the result depend on the device setting?</p> </li> <li><p>The result seems consistent when no arguments are passed e.g <code>new Date()</code>. Can we assume that this will produce a consistent timezone name regardless of device settings?</p> </li> </ol> <p>Note: I also noticed a same behaviour with <code>date-fns-tz</code></p> <p>EDIT: added one more example above.</p> <p>Another question: 4.In contrary to question 2, <code>new Date().toTimeString()</code> is not influenced by region setting. Why is that the case</p> <p>EDIT 2: I figured it out. For countries with day light savings. The behaviour of <code>toTimeString()</code> will produce different timezone based on when the timestamp falls in.</p> <p>Leaving this thread here since it might be helpful to others</p>
[ { "answer_id": 74504493, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": -1, "selected": false, "text": "list split.default gl list lapply paste list do.call list nm1 <- paste0(\"col\", rep(unique( sub(\".(\\\\d+)_.*\", \"\\\\1\", \n names(df))), each = 3), letters[1:3])\ndf[nm1] <- lapply(split.default(df, as.integer(gl(ncol(df), 2, ncol(df)))), \n function(x) do.call(paste, c(x, sep = '-')))\n > df\n A1_Q1 A1_Q2 A1_Q3 A1_Q4 A1_Q5 A1_Q6 A2_Q1 A2_Q2 A2_Q3 A2_Q4 A2_Q5 A2_Q6 col1a col1b col1c col2a col2b col2c\n1 1 4 7 10 13 16 1 4 7 10 13 16 1-4 7-10 13-16 1-4 7-10 13-16\n2 2 5 8 11 14 17 2 5 8 11 14 17 2-5 8-11 14-17 2-5 8-11 14-17\n3 3 6 9 12 15 18 3 6 9 12 15 18 3-6 9-12 15-18 3-6 9-12 15-18\n tidyverse pivot_longer separate case_when unite pivot_wider library(dplyr)\nlibrary(tidyr)\nlibrary(stringr)\ndf %>% \n mutate(rn = row_number()) %>%\n pivot_longer(cols = -rn) %>%\n separate(name, into = c(\"name1\", \"name2\")) %>%\n mutate( name2 = case_when(name2 %in% c(\"Q1\", \"Q2\") ~ \"a\", \n name2 %in% c(\"Q3\", \"Q4\") ~ \"b\", TRUE ~ \"c\")) %>% \n group_by(rn, name1, name2) %>% \n summarise(value = str_c(value, collapse = '-'), .groups = 'drop') %>%\n mutate(name1 = str_replace(name1, \"\\\\D+\", \"col\")) %>%\n unite(name, name1, name2, sep = \"\") %>% \n pivot_wider(names_from = name, values_from = value) %>% \n select(-rn) %>% \n bind_cols(df, .)\n A1_Q1 A1_Q2 A1_Q3 A1_Q4 A1_Q5 A1_Q6 A2_Q1 A2_Q2 A2_Q3 A2_Q4 A2_Q5 A2_Q6 col1a col1b col1c col2a col2b col2c\n1 1 4 7 10 13 16 1 4 7 10 13 16 1-4 7-10 13-16 1-4 7-10 13-16\n2 2 5 8 11 14 17 2 5 8 11 14 17 2-5 8-11 14-17 2-5 8-11 14-17\n3 3 6 9 12 15 18 3 6 9 12 15 18 3-6 9-12 15-18 3-6 9-12 15-18\n Map paste df[nm1] <- Map(function(x, y) paste(x, y, sep = \"-\"), df[c(TRUE, FALSE)], \n df[c(FALSE, TRUE)])\n > df\n A1_Q1 A1_Q2 A1_Q3 A1_Q4 A1_Q5 A1_Q6 A2_Q1 A2_Q2 A2_Q3 A2_Q4 A2_Q5 A2_Q6 col1a col1b col1c col2a col2b col2c\n1 1 4 7 10 13 16 1 4 7 10 13 16 1-4 7-10 13-16 1-4 7-10 13-16\n2 2 5 8 11 14 17 2 5 8 11 14 17 2-5 8-11 14-17 2-5 8-11 14-17\n3 3 6 9 12 15 18 3 6 9 12 15 18 3-6 9-12 15-18 3-6 9-12 15-18\n" }, { "answer_id": 74506763, "author": "jay.sf", "author_id": 6574038, "author_profile": "https://Stackoverflow.com/users/6574038", "pm_score": 0, "selected": false, "text": "^A1 ^A2 grep sb lapply 1:2 sprintf A1 A2 paste0 sb[(1:2) + x] sb 2 ncol(sb) paste0 col x letters setNames cbind res <- lapply(1:2, \\(x) {\n sb <- df[grep(sprintf('^A%s', x), names(df))]\n lapply((0:((ncol(sb) - 1)/2))*2, \\(x) Reduce(\\(y, z) paste0(y, '-', z), sb[(1:2) + x])) |>\n setNames(paste0('col', x, letters[seq_len((ncol(sb))/2)]))\n}) |> cbind(df)\n\nres\n# col1a col1b col1c col2a col2b col2c A1_Q1 A1_Q2 A1_Q3 A1_Q4 A1_Q5 A1_Q6 A2_Q1\n# 1 1-4 7-10 13-16 1-4 7-10 13-16 1 4 7 10 13 16 1\n# 2 2-5 8-11 14-17 2-5 8-11 14-17 2 5 8 11 14 17 2\n# 3 3-6 9-12 15-18 3-6 9-12 15-18 3 6 9 12 15 18 3\n# A2_Q2 A2_Q3 A2_Q4 A2_Q5 A2_Q6\n# 1 4 7 10 13 16\n# 2 5 8 11 14 17\n# 3 6 9 12 15 18\n A* Q res <- cbind(lapply(1:2, function(x) {\n sb <- df[grep(sprintf('^A%s', x), names(df))]\n lapply((0:((ncol(sb) - 1)/2))*2, function(x) Reduce(function(y, z) paste0(y, '-', z), sb[(1:2) + x])) |>\n setNames(paste0('col', x, letters[seq_len((ncol(sb))/2)]))\n}), df)\n" }, { "answer_id": 74513704, "author": "Santiago", "author_id": 13507658, "author_profile": "https://Stackoverflow.com/users/13507658", "pm_score": 1, "selected": false, "text": "paste0 [[ map_dfc .x map_dfc mutate library(tidyverse)\n\nA1_Q1 <- c(1, 2, 3)\nA1_Q2 <- c(4, 5, 6)\nA1_Q3 <- c(7, 8, 9)\nA1_Q4 <- c(10, 11, 12)\nA1_Q5 <- c(13, 14, 15)\nA1_Q6 <- c(16, 17, 18)\n\nA2_Q1 <- c(1, 2, 3)\nA2_Q2 <- c(4, 5, 6)\nA2_Q3 <- c(7, 8, 9)\nA2_Q4 <- c(10, 11, 12)\nA2_Q5 <- c(13, 14, 15)\nA2_Q6 <- c(16, 17, 18)\n\ndf <- data.frame(A1_Q1, A1_Q2, A1_Q3, A1_Q4, A1_Q5, A1_Q6,\n A2_Q1, A2_Q2, A2_Q3, A2_Q4, A2_Q5, A2_Q6)\n\ndf %>%\n mutate(\n map_dfc(\n 1:2,\n ~ {\n cols <- list(\n paste(\n df[[paste0(\"A\", .x, \"_Q1\")]],\n df[[paste0(\"A\", .x, \"_Q2\")]],\n sep = \"-\"\n ),\n paste(\n df[[paste0(\"A\", .x, \"_Q3\")]],\n df[[paste0(\"A\", .x, \"_Q4\")]],\n sep = \"-\"\n ),\n paste(\n df[[paste0(\"A\", .x, \"_Q5\")]],\n df[[paste0(\"A\", .x, \"_Q6\")]],\n sep = \"-\"\n )\n )\n \n names(cols) <- c(\n paste0(\"col\", .x, \"a\"),\n paste0(\"col\", .x, \"b\"),\n paste0(\"col\", .x, \"c\")\n )\n \n cols\n \n }\n )\n )\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15161914/" ]
74,504,504
<p>I was thinking about how to code TailwindCSS cleaner in React. Since Tailwind is utility-first, it makes us inevitably end up with components (ex: <code>className=&quot;w-full bg-red-500&quot;</code>). So, I tried to create a utility like this:<br /> <code>utils/tailwind.ts</code></p> <pre><code>const tw = (...classes: string[]) =&gt; classes.join(' ') </code></pre> <p>and call it inside:<br /> <code>components/Example.tsx</code></p> <pre><code>import { useState } from 'react' import tw from '../utils/tailwind' const Example = () =&gt; { const [text, setText] = useState('') return ( &lt;div&gt; &lt;input onChange={(e: any) =&gt; setText(e.target.value)} /&gt; &lt;div className={tw( 'w-full', 'h-full', 'bg-red-500' )} &gt; hello &lt;/div&gt; &lt;/div&gt; ) } </code></pre> <p>But, it will cause <code>tw()</code> to be re-called as always as <code>text</code> state is updated.</p> <p>So, I decided to wrap <code>tw()</code> function using <code>useMemo</code> to prevent re-call since the <code>tw()</code> always returns the same value. But the code is like this:</p> <pre><code>import { useState, useMemo } from 'react' import tw from '../utils/tailwind' const Example = () =&gt; { const [text, setText] = useState('') return ( &lt;div&gt; &lt;input onChange={(e: any) =&gt; setText(e.target.value)} /&gt; &lt;div className={useMemo(() =&gt; tw( 'w-full', 'h-full', 'bg-red-500' ), [])} &gt; hello &lt;/div&gt; &lt;/div&gt; ) } </code></pre> <p>Is it correct or good practice if I put <code>useMemo</code> like that? Thank you .</p>
[ { "answer_id": 74504599, "author": "kind user", "author_id": 6695924, "author_profile": "https://Stackoverflow.com/users/6695924", "pm_score": 3, "selected": true, "text": "yes useMemo useMemo useMemo tw App className useMemo tw className App useMemo export default function App() {\n const [_, s] = useState(0);\n\n return (\n <div className=\"App\">\n <div className={tw(false, 'w-full', 'h-full', 'bg-red-500')}>div1</div>\n <div\n className={useMemo(\n () => tw(true, 'w-full', 'h-full', 'bg-red-500'),\n [],\n )}\n >\n div2\n </div>\n\n <button onClick={() => s(Math.random())}>re-render</button>\n </div>\n );\n}\n" }, { "answer_id": 74504607, "author": "Tomer_Ra", "author_id": 11971765, "author_profile": "https://Stackoverflow.com/users/11971765", "pm_score": -1, "selected": false, "text": "const Example = () => {\n\n const onInputChange = (e) => {\n const text = e.target.value\n\n // do something with text\n }\n\n\n return (\n <div>\n <input onChange={(e: any) => onInputChange(e)} />\n <div\n className={useMemo(() => tw(\n 'w-full',\n 'h-full',\n 'bg-red-500'\n ), [])}\n >\n hello\n </div>\n </div>\n )\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3639728/" ]