qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,549,674
<p>In the img. below my goal is to locate the integral in area 1 / 2 / 3. In that way that I know how much area below the linear line (area 1 / 3), and how much area that are above the linear line (area 2)</p> <p>Im not looking for the exact integral, just an approximately value to measure on. an approx that would work in the same fashion for other version of the curves I have represented.</p> <p>y1: The blue line is a linear function y= -0.148x + 1301.35</p> <p>y2:The yellow line is a arbitrary curve</p> <p>Both curves share the same x axis.</p> <p><a href="https://i.stack.imgur.com/6bE9y.png" rel="nofollow noreferrer">image of curves linear &amp; arbitrary curve</a></p> <p>I have tried several methods, found here on stackoverflow, mainly theese 2 methods cought my attention:</p> <p><a href="https://stackoverflow.com/a/57827807">https://stackoverflow.com/a/57827807</a></p> <p>&amp;</p> <p><a href="https://stackoverflow.com/a/25447819">https://stackoverflow.com/a/25447819</a></p> <p>They give me the exact same output for the whole area, my issue is to seperate it above / below.</p> <p>Example of my best try: (Modified version of <a href="https://stackoverflow.com/a/25447819/20441461">https://stackoverflow.com/a/25447819/20441461</a>)</p> <p>y1 / y2 / x - is the data used for the curves in the img. above</p> <pre><code>y1 = [1298.54771845, 1298.40019417, 1298.2526699, 1298.10514563, 1297.95762136,1297.81009709, 1297.66257282, 1297.51504854] y2 = [1298.59, 1297.31, 1296.04, 1297.31, 1296.95, 1299.18, 1297.05, 1297.45] x = np.arange(len(y1)) z = y1-y2 dx = x[1:] - x[:-1] cross_test = np.sign(z[:-1] * z[1:]) x_intersect = x[:-1] - dx / (z[1:] - z[:-1]) * z[:-1] dx_intersect = - dx / (z[1:] - z[:-1]) * z[:-1] areas_pos = abs(z[:-1] + z[1:]) * 0.5 * dx # signs of both z are same areas_neg = 0.5 * dx_intersect * abs(z[:-1]) + 0.5 * (dx - dx_intersect) * abs(z[1:]) negatives = np.where(cross_test &lt; 0) negative_sum = np.sum(x_intersect[negatives]) positives = np.where(cross_test &gt;= 0) positive_sum = np.sum(x_intersect[positives])` </code></pre> <p>is give me this result:</p> <p>Negative integral = 10.15</p> <p>Positive integral = 9.97</p> <p>Just from looking at the picture, I can tell that can not be the correct value. ( there is alot more area below the linear line than above.)</p> <p>I have spend loads of time now on this, and are quite stuck - any advise or suggestion are welcome.</p>
[ { "answer_id": 74602211, "author": "Greg", "author_id": 4373753, "author_profile": "https://Stackoverflow.com/users/4373753", "pm_score": 1, "selected": true, "text": "QQmlApplicationEngine engine;\nengine.addImportPath(\":/\");\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74549674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20441461/" ]
74,549,734
<p>I have the following code to build a Shinydashboard app. I'm trying to change the background color in the box on the top of my screen to a custom color (a color hex code color), however the options for the argument <code>background</code> only allow for a set of default colors. Is there a way to change the background color of this box specifically while keeping the white background for the remainder of my boxes?</p> <pre><code>library(shiny) library(shinydashboard) ui &lt;- dashboardPage( dashboardHeader(title = 'Dashboard'), dashboardSidebar(sidebarMenu (menuItem(tabName = 'Panel1', text = 'Panel 1'), dateInput(&quot;Start_Date&quot;, &quot;Start Date&quot;, min = '2000-01-01', max = Sys.Date(), value = '2020-01-01',format = &quot;yyyy-mm-dd&quot;) ) ), dashboardBody( tabItems(tabItem(tabName = 'Panel1', fluidRow(box(selectizeInput('select_mean', 'Select Number', choices = c(12,24,36,48,60,120)),height=80,width=4, background = 'black')), fluidRow(box(width = 13, height = 655)) ) ) ) ) server &lt;- function(input, output) { } shinyApp(ui, server) </code></pre> <p><a href="https://i.stack.imgur.com/MQ8Ei.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MQ8Ei.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74549920, "author": "gdevaux", "author_id": 7972989, "author_profile": "https://Stackoverflow.com/users/7972989", "pm_score": 2, "selected": true, "text": "tags$div library(shiny)\nlibrary(shinydashboard)\n\n\nui <- dashboardPage(\n dashboardHeader(title = 'Dashboard'),\n dashboardSidebar(sidebarMenu\n (menuItem(tabName = 'Panel1', text = 'Panel 1'),\n dateInput(\"Start_Date\", \"Start Date\", min = '2000-01-01', max = Sys.Date(), value = '2020-01-01',format = \"yyyy-mm-dd\")\n )\n ),\n dashboardBody(\n \n tags$head(\n tags$style(HTML(\"\n #toto > div:nth-child(1) > div:nth-child(1) {\n background-color: rgb(128, 0, 0);\n }\"))),\n \n tabItems(tabItem(tabName = 'Panel1',\n fluidRow(\n tags$div(\n id = \"toto\",\n box(selectizeInput('select_mean', 'Select Number', \n choices = c(12,24,36,48,60,120)),height=80,width=4)\n )\n ),\n fluidRow(box(width = 13, height = 655))\n )\n )\n )\n \n)\n\n\nserver <- function(input, output) {\n \n \n}\n\n\nshinyApp(ui, server)\n" }, { "answer_id": 74550005, "author": "Stéphane Laurent", "author_id": 1100107, "author_profile": "https://Stackoverflow.com/users/1100107", "pm_score": 2, "selected": false, "text": "htmltools::tagQuery library(htmltools)\nlibrary(shinydashboard)\nlibrary(shiny)\n\nb <- box(selectInput(\"id\", \"label\", c(\"a\", \"b\", \"c\")))\nb <- tagQuery(b)$find(\".box\")$addAttrs(style = \"background-color: pink;\")$allTags()\n\nui <- dashboardPage(\n dashboardHeader(),\n dashboardSidebar(),\n dashboardBody(b)\n)\n\nserver <- function(input, output, session) {}\n\nshinyApp(ui, server)\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74549734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13954869/" ]
74,549,774
<p>I just had following piece of code, which did not compile:</p> <pre><code>public Task&lt;int&gt; Handle { var result = &lt;do_something_returning_an_int&gt;(); ... return result; } </code></pre> <p>This gives compiler error `cannot implicitly convert type 'int' to 'System.Threading.Thread.Task'.</p> <p>When I change this into:</p> <pre><code>async Task&lt;int&gt; Handle { var result = &lt;do_something_returning_an_int&gt;(); ... return result; } </code></pre> <p>... no compiler error.</p> <p>I know that <code>async</code> means that the task does not need to wait for the answer to arrive, but what does this have to do with typecasting?</p>
[ { "answer_id": 74549908, "author": "noel", "author_id": 10650696, "author_profile": "https://Stackoverflow.com/users/10650696", "pm_score": 3, "selected": false, "text": "async Task public Task<int> Handle\n{\n var result = <do_something_returning_an_int>();\n ...\n return Task.FromResult(result);\n}\n Task async public" }, { "answer_id": 74550204, "author": "Golden Lion", "author_id": 4001177, "author_profile": "https://Stackoverflow.com/users/4001177", "pm_score": 1, "selected": false, "text": "Task<int> Handle\n{\n return Task.Run(()=>\n {\n var result = <do_something_returning_an_int>();\n ...\n return result;\n }\n}\n\nList<Task<int>> tasks = new List<Task<int>>();\ntasks.Add(Handle);\nTask.WaitAll(tasks.ToArray());\nfor(int ctr = 0; ctr < tasks.Count; ctr++) {\n if (tasks[ctr].Status == TaskStatus.Faulted)\n output.WriteLine(\" Task fault occurred\");\n else\n {\n output.WriteLine(\"test sent {0}\",\n tasks[ctr].Result);\n Assert.True(true);\n }\n }\n Task<int> Handle\n{\n return Task.FromResult(do_something_returning_an_int);\n}\n" }, { "answer_id": 74557642, "author": "Jeppe Stig Nielsen", "author_id": 1336654, "author_profile": "https://Stackoverflow.com/users/1336654", "pm_score": 3, "selected": true, "text": "async async public Task<int> HandleAsync()\n{\n ...\n Task<int> result = ...;\n ...\n return result;\n}\n Task<> Task<int> result = Task.Run(GetLastDigitOfSmallestTwinPrimeWithMoreThan1000000Digits);\n await async Task<int> int await async public async Task<int> HandleAsync()\n{\n ...\n int result = await GetLastDigitOfSmallestTwinPrimeWithMoreThan1000000DigitsAsync();\n ...\n return result;\n}\n\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74549774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4279155/" ]
74,549,835
<p>Trying to get Json data to csv i am getting the values but one block is showing as one line in result, new to python so any help appriciated. Have tried the below code to do the same.</p> <pre><code>import pandas as pd with open(r'C:\Users\anath\hard.json', encoding='utf-8') as inputfile: df = pd.read_json(inputfile) df.to_csv(r'C:\Users\anath\csvfile.csv', encoding='utf-8', index=True) </code></pre> <p>Sample Json in the source file, short snippet</p> <pre><code>{ &quot;issues&quot;: [ { &quot;issueId&quot;: 110052, &quot;revision&quot;: 84, &quot;definitionId&quot;: &quot;DNS1012&quot;, &quot;subject&quot;: &quot;urn:h:domain:fitestdea.com&quot;, &quot;subjectDomain&quot;: &quot;fitestdea.com&quot;, &quot;title&quot;: &quot;Nameserver name doesn\u0027t resolve to an IPv6 address&quot;, &quot;category&quot;: &quot;DNS&quot;, &quot;severity&quot;: &quot;low&quot;, &quot;cause&quot;: &quot;urn:h:domain:ns1.gname.net&quot;, &quot;causeDomain&quot;: &quot;ns1.gname.net&quot;, &quot;open&quot;: true, &quot;status&quot;: &quot;active&quot;, &quot;auto&quot;: true, &quot;autoOpen&quot;: true, &quot;createdOn&quot;: &quot;2022-09-01T02:29:09.681451Z&quot;, &quot;lastUpdated&quot;: &quot;2022-11-23T02:26:28.785601Z&quot;, &quot;lastChecked&quot;: &quot;2022-11-23T02:26:28.785601Z&quot;, &quot;lastConfirmed&quot;: &quot;2022-11-23T02:26:28.785601Z&quot;, &quot;details&quot;: &quot;{}&quot; }, { &quot;issueId&quot;: 77881, &quot;revision&quot;: 106, &quot;definitionId&quot;: &quot;DNS2001&quot;, &quot;subject&quot;: &quot;urn:h:domain:origin-mx.stagetest.test.com.test.com&quot;, &quot;subjectDomain&quot;: &quot;origin-mx.stagetest.test.com.test.com&quot;, &quot;title&quot;: &quot;Dangling domain alias (CNAME)&quot;, &quot;category&quot;: &quot;DNS&quot;, &quot;severity&quot;: &quot;high&quot;, &quot;cause&quot;: &quot;urn:h:domain:origin-www.stagetest.test.com.test.com&quot;, &quot;causeDomain&quot;: &quot;origin-www.stagetest.test.com.test.com&quot;, &quot;open&quot;: true, &quot;status&quot;: &quot;active&quot;, &quot;auto&quot;: true, &quot;autoOpen&quot;: true, &quot;createdOn&quot;: &quot;2022-08-10T09:34:36.929071Z&quot;, &quot;lastUpdated&quot;: &quot;2022-11-23T09:33:32.553663Z&quot;, &quot;lastChecked&quot;: &quot;2022-11-23T09:33:32.553663Z&quot;, &quot;lastConfirmed&quot;: &quot;2022-11-23T09:33:32.553663Z&quot;, &quot;details&quot;: &quot;{\&quot;@type\&quot;: \&quot;hardenize/com.hardenize.schemas.dns.DanglingProblem\&quot;, \&quot;rrType\&quot;: \&quot;CNAME\&quot;, \&quot;rrDomain\&quot;: \&quot;origin-mx.stagetest.test.com.test.com\&quot;, \&quot;causeDomain\&quot;: \&quot;origin-www.stagetest.test.com.test.com\&quot;, \&quot;danglingType\&quot;: \&quot;nxdomain\&quot;, \&quot;rrEffectiveDomain\&quot;: \&quot;origin-mx.stagetest.test.com.test.com\&quot;}&quot; } } ] } </code></pre> <p>Output i am getting is as below was looking a way where could field name in header and values in a column or cell so far getting the entire record in 1 cell. Any way we can just get specific field only like title, severity or issueid not everything but only the feilds i need. <a href="https://i.stack.imgur.com/NpLp7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NpLp7.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74549965, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 2, "selected": true, "text": "import json\nimport pandas as pd\n\nwith open(\"your_file.json\", \"r\") as f_in:\n data = json.load(f_in)\n\ndf = pd.DataFrame(data[\"issues\"])\nprint(df[[\"title\", \"severity\", \"issueId\"]])\n title severity issueId\n0 Nameserver name doesn't resolve to an IPv6 address low 110052\n1 Dangling domain alias (CNAME) high 77881\n df[[\"title\", \"severity\", \"issueId\"]].to_csv('data.csv', index=False)\n" }, { "answer_id": 74550652, "author": "user3754136", "author_id": 3754136, "author_profile": "https://Stackoverflow.com/users/3754136", "pm_score": 0, "selected": false, "text": "import pandas as pd\nimport json\n\nwith open(r'C:\\Users\\anath\\hard.json', encoding='utf-8') as inputfile:\n data = json.load(inputfile)\n\n\ndf = pd.DataFrame(data[\"issues\"])\nprint(df[[\"title\", \"severity\", \"issueId\"]])\ndf[[\"title\", \"severity\", \"issueId\"]].to_csv('data.csv', index=False)\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74549835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3754136/" ]
74,549,843
<p>Using pythons keyboard library, I have two function definitions:</p> <pre><code>def start_tracking(): *code to start tracking time* def end_tracking(): *code to stop tracking time* </code></pre> <p>I then want to use the same hotkey (e.g. F1) to invoke function 1 (start tracking time) on the first press and then function 2 (end tracking time) on the subsequent press. If I press the hotkey again after that, it should repeat the process.</p> <p>Basically I want to use the same hotkey to track time and stop tracking time.</p> <p>Here's what a working solution to start tracking time and stop tracking time <strong>using two different hotkeys</strong> looks like:</p> <pre><code>keyboard.add_hotkey(&quot;F1&quot;, start_tracking) keyboard.add_hotkey(&quot;F2&quot;, end_tracking) </code></pre> <p>How can I accomplish the same thing with only one key (F1)? I don't want to use a while loop because it slows down performance quite a bit.</p>
[ { "answer_id": 74549965, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 2, "selected": true, "text": "import json\nimport pandas as pd\n\nwith open(\"your_file.json\", \"r\") as f_in:\n data = json.load(f_in)\n\ndf = pd.DataFrame(data[\"issues\"])\nprint(df[[\"title\", \"severity\", \"issueId\"]])\n title severity issueId\n0 Nameserver name doesn't resolve to an IPv6 address low 110052\n1 Dangling domain alias (CNAME) high 77881\n df[[\"title\", \"severity\", \"issueId\"]].to_csv('data.csv', index=False)\n" }, { "answer_id": 74550652, "author": "user3754136", "author_id": 3754136, "author_profile": "https://Stackoverflow.com/users/3754136", "pm_score": 0, "selected": false, "text": "import pandas as pd\nimport json\n\nwith open(r'C:\\Users\\anath\\hard.json', encoding='utf-8') as inputfile:\n data = json.load(inputfile)\n\n\ndf = pd.DataFrame(data[\"issues\"])\nprint(df[[\"title\", \"severity\", \"issueId\"]])\ndf[[\"title\", \"severity\", \"issueId\"]].to_csv('data.csv', index=False)\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74549843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14236403/" ]
74,549,872
<p>Given one txt file Im trying to make a C program that copy the content of that into other which name is passed by arguments.The program must read blocks of 512 bytes from the source file and write the bytes read in the destination file.</p> <p>My attempt:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include &lt;unistd.h&gt; #include &lt;stdlib.h&gt; #include&lt;fcntl.h&gt; int main(int argc, char* argv[]){ if(argc &lt; 2){ printf(&quot;ERROR: Missing arguments\n&quot;); exit(1); } int fdo, fdd; if((fdo = open(argv[1], O_RDONLY)) == -1){ printf(&quot;ERROR: Origin file %s can not be opened\n&quot;, argv[1]); exit(1); } if(fdd = open(argv[2], O_CREAT | O_TRUNC, 0666) == -1){ printf(&quot;ERROR: Dest. file %s can not be opened\n&quot;, argv[2]); exit(1); } char buff[512]; size_t n_bytes; while((n_bytes = read(fdo,buff,512)) &gt; 0){ if(write(fdd,buff,n_bytes) &lt; 0){ printf(&quot;Can not write buffer content in %s \n&quot;, argv[2]); exit(1); } } if(n_bytes &lt; 0){ printf(&quot;Can not read %s file \n&quot;, argv[1]); exit(1); } close(fdo); close(fdd); return 0; } </code></pre> <p>The content of the file test.txt is:</p> <pre><code>abcdef 1890 </code></pre> <p>And their permissions are:</p> <pre><code>usuarioso@usuarioso-virtualbox:~/Documentos/SO 2022/pr2/API de ficheros y directorios$ ls -l total 32 -rwxrwxr-x 1 usuarioso usuarioso 17048 nov 23 16:15 copyrf -rw-rw-r-- 1 usuarioso usuarioso 774 nov 23 16:39 copyrf.c -rw-rw-r-- 1 usuarioso usuarioso 12 nov 23 16:52 test.txt </code></pre> <p>However when I execute it I get the following:</p> <pre><code>usuarioso@usuarioso-virtualbox:~/Documentos/SO 2022/pr2/API de ficheros y directorios$ gcc -o copyrf copyrf.c usuarioso@usuarioso-virtualbox:~/Documentos/SO 2022/pr2/API de ficheros y directorios$ ./copyrf test.txt test1.txt abcdef 1890 usuarioso@usuarioso-virtualbox:~/Documentos/SO 2022/pr2/API de ficheros y directorios$ ls -l total 28 -rwxrwxr-x 1 usuarioso usuarioso 17008 nov 23 17:00 copyrf -rw-rw-r-- 1 usuarioso usuarioso 771 nov 23 16:59 copyrf.c -rw-rw-rw- 1 usuarioso usuarioso 0 nov 23 17:00 test1.txt -rw-rw-r-- 1 usuarioso usuarioso 12 nov 23 16:52 test.txt usuarioso@usuarioso-virtualbox:~/Documentos/SO 2022/pr2/API de ficheros y directorios$ cat test1.txt usuarioso@usuarioso-virtualbox:~/Documentos/SO 2022/pr2/API de ficheros y directorios$ </code></pre> <p>i.e the file test1.txt is created but is empty and the content of the file test.txt is printed in console.</p> <p>What am I missing?</p>
[ { "answer_id": 74550051, "author": "David Grayson", "author_id": 28128, "author_profile": "https://Stackoverflow.com/users/28128", "pm_score": 1, "selected": false, "text": "fdd open fdo" }, { "answer_id": 74550058, "author": "Jeremy Friesner", "author_id": 131930, "author_profile": "https://Stackoverflow.com/users/131930", "pm_score": 3, "selected": true, "text": "$ gcc temp.c\ntemp.c:19:12: warning: using the result of an assignment as a condition without parentheses [-Wparentheses]\n if(fdd = open(argv[2], O_CREAT | O_TRUNC, 0666) == -1){\n ~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\ntemp.c:19:12: note: place parentheses around the assignment to silence this warning\n if(fdd = open(argv[2], O_CREAT | O_TRUNC, 0666) == -1){\n ^\n ( )\ntemp.c:19:12: note: use '==' to turn this assignment into an equality comparison\n if(fdd = open(argv[2], O_CREAT | O_TRUNC, 0666) == -1){\n ^\n ==\n fdd (open(...) == -1) 1 open() -1 0 open() 0 1 open() write(fdd, ...) open() if((fdd = open(argv[2], O_CREAT | O_TRUNC, 0666)) == -1){\n O_WRONLY oflag open() fdd" }, { "answer_id": 74550074, "author": "msaw328", "author_id": 5457426, "author_profile": "https://Stackoverflow.com/users/5457426", "pm_score": 1, "selected": false, "text": "if((fdo = open(argv[1], O_RDONLY)) == -1)\n fdo if(fdd = open(argv[2], O_CREAT | O_TRUNC, 0666) == -1)\n == fdd" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74549872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10734426/" ]
74,549,886
<p>I have the following dataframe called df (<code>dput</code> below):</p> <pre><code># A tibble: 14 × 5 group date indicator value diff_hours &lt;chr&gt; &lt;dttm&gt; &lt;lgl&gt; &lt;dbl&gt; &lt;dbl&gt; 1 A 2022-11-01 01:00:00 FALSE 2 4 2 A 2022-11-01 02:00:00 FALSE 1 3 3 A 2022-11-01 03:00:00 FALSE 4 2 4 A 2022-11-01 04:00:00 FALSE 1 1 5 A 2022-11-01 05:00:00 TRUE 3 0 6 A 2022-11-01 06:00:00 FALSE 1 1 7 A 2022-11-01 07:00:00 FALSE 3 2 8 B 2022-11-01 01:00:00 FALSE 1 4 9 B 2022-11-01 02:00:00 FALSE 2 3 10 B 2022-11-01 03:00:00 FALSE 3 2 11 B 2022-11-01 04:00:00 FALSE 1 1 12 B 2022-11-01 05:00:00 TRUE 4 0 13 B 2022-11-01 06:00:00 FALSE 1 1 14 B 2022-11-01 07:00:00 FALSE 5 2 </code></pre> <p>I would like to calculate the slope (<code>lm(value ~ diff_hours)</code> for every n rows with respect to the conditioned rows <code>indicator == TRUE</code>. The rows with TRUE should have a slope of NA. Here is the desired output called df_desired with n = 2 (<code>dput</code> below):</p> <pre><code># A tibble: 14 × 6 # Groups: group [2] group date indicator value diff_hours slope &lt;chr&gt; &lt;dttm&gt; &lt;lgl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; 1 A 2022-11-01 01:00:00 FALSE 2 4 1 2 A 2022-11-01 02:00:00 FALSE 1 3 1 3 A 2022-11-01 03:00:00 FALSE 4 2 3 4 A 2022-11-01 04:00:00 FALSE 1 1 3 5 A 2022-11-01 05:00:00 TRUE 3 0 NA 6 A 2022-11-01 06:00:00 FALSE 1 1 2 7 A 2022-11-01 07:00:00 FALSE 3 2 2 8 B 2022-11-01 01:00:00 FALSE 1 4 -1 9 B 2022-11-01 02:00:00 FALSE 2 3 -1 10 B 2022-11-01 03:00:00 FALSE 3 2 2 11 B 2022-11-01 04:00:00 FALSE 1 1 2 12 B 2022-11-01 05:00:00 TRUE 4 0 NA 13 B 2022-11-01 06:00:00 FALSE 1 1 4 14 B 2022-11-01 07:00:00 FALSE 5 2 4 </code></pre> <p>For example, <code>lm(c(2,1)~c(4,3))=1</code> for rows 1 and 2. So I was wondering if anyone knows how to calculate the slope of every n rows with respect to the conditioned rows per group?</p> <hr /> <p><code>dput</code> of df and df_desired:</p> <pre><code>df &lt;- structure(list(group = c(&quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;B&quot;, &quot;B&quot;, &quot;B&quot;, &quot;B&quot;, &quot;B&quot;, &quot;B&quot;, &quot;B&quot;), date = structure(c(1667260800, 1667264400, 1667268000, 1667271600, 1667275200, 1667278800, 1667282400, 1667260800, 1667264400, 1667268000, 1667271600, 1667275200, 1667278800, 1667282400), class = c(&quot;POSIXct&quot;, &quot;POSIXt&quot;), tzone = &quot;&quot;), indicator = c(FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE), value = c(2, 1, 4, 1, 3, 1, 3, 1, 2, 3, 1, 4, 1, 5), diff_hours = c(4, 3, 2, 1, 0, 1, 2, 4, 3, 2, 1, 0, 1, 2)), class = c(&quot;grouped_df&quot;, &quot;tbl_df&quot;, &quot;tbl&quot;, &quot;data.frame&quot; ), row.names = c(NA, -14L), groups = structure(list(group = c(&quot;A&quot;, &quot;B&quot;), .rows = structure(list(1:7, 8:14), ptype = integer(0), class = c(&quot;vctrs_list_of&quot;, &quot;vctrs_vctr&quot;, &quot;list&quot;))), class = c(&quot;tbl_df&quot;, &quot;tbl&quot;, &quot;data.frame&quot; ), row.names = c(NA, -2L), .drop = TRUE)) df_desired &lt;- structure(list(group = c(&quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;B&quot;, &quot;B&quot;, &quot;B&quot;, &quot;B&quot;, &quot;B&quot;, &quot;B&quot;, &quot;B&quot;), date = structure(c(1667260800, 1667264400, 1667268000, 1667271600, 1667275200, 1667278800, 1667282400, 1667260800, 1667264400, 1667268000, 1667271600, 1667275200, 1667278800, 1667282400), class = c(&quot;POSIXct&quot;, &quot;POSIXt&quot;), tzone = &quot;&quot;), indicator = c(FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE), value = c(2, 1, 4, 1, 3, 1, 3, 1, 2, 3, 1, 4, 1, 5), diff_hours = c(4, 3, 2, 1, 0, 1, 2, 4, 3, 2, 1, 0, 1, 2), slope = c(1, 1, 3, 3, NA, 2, 2, -1, -1, 2, 2, NA, 4, 4)), row.names = c(NA, -14L), class = c(&quot;grouped_df&quot;, &quot;tbl_df&quot;, &quot;tbl&quot;, &quot;data.frame&quot;), groups = structure(list(group = c(&quot;A&quot;, &quot;B&quot;), .rows = structure(list(1:7, 8:14), ptype = integer(0), class = c(&quot;vctrs_list_of&quot;, &quot;vctrs_vctr&quot;, &quot;list&quot;))), class = c(&quot;tbl_df&quot;, &quot;tbl&quot;, &quot;data.frame&quot; ), row.names = c(NA, -2L), .drop = TRUE)) </code></pre>
[ { "answer_id": 74550051, "author": "David Grayson", "author_id": 28128, "author_profile": "https://Stackoverflow.com/users/28128", "pm_score": 1, "selected": false, "text": "fdd open fdo" }, { "answer_id": 74550058, "author": "Jeremy Friesner", "author_id": 131930, "author_profile": "https://Stackoverflow.com/users/131930", "pm_score": 3, "selected": true, "text": "$ gcc temp.c\ntemp.c:19:12: warning: using the result of an assignment as a condition without parentheses [-Wparentheses]\n if(fdd = open(argv[2], O_CREAT | O_TRUNC, 0666) == -1){\n ~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\ntemp.c:19:12: note: place parentheses around the assignment to silence this warning\n if(fdd = open(argv[2], O_CREAT | O_TRUNC, 0666) == -1){\n ^\n ( )\ntemp.c:19:12: note: use '==' to turn this assignment into an equality comparison\n if(fdd = open(argv[2], O_CREAT | O_TRUNC, 0666) == -1){\n ^\n ==\n fdd (open(...) == -1) 1 open() -1 0 open() 0 1 open() write(fdd, ...) open() if((fdd = open(argv[2], O_CREAT | O_TRUNC, 0666)) == -1){\n O_WRONLY oflag open() fdd" }, { "answer_id": 74550074, "author": "msaw328", "author_id": 5457426, "author_profile": "https://Stackoverflow.com/users/5457426", "pm_score": 1, "selected": false, "text": "if((fdo = open(argv[1], O_RDONLY)) == -1)\n fdo if(fdd = open(argv[2], O_CREAT | O_TRUNC, 0666) == -1)\n == fdd" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74549886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14282714/" ]
74,549,900
<pre><code>import java.util.Scanner; public class recursion_4 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int a[] = new int[n]; for (int i = 0; i &lt; n; i++) { a[i] = sc.nextInt(); } printArray(a, 0); sc.close(); } static void printArray(int arr[], int i) { if (i == arr.length) { return; } printArray(arr, ++i); System.out.println(arr[i]); } } </code></pre> <p>I am try to print array element using recursion.</p> <p>But it give error of arrayIndex Out of bound.</p>
[ { "answer_id": 74549951, "author": "Edward Peters", "author_id": 6016064, "author_profile": "https://Stackoverflow.com/users/6016064", "pm_score": 0, "selected": false, "text": "++i ++i i++ printArray i=arr.length-1 i i printArray i printArray printArray" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74549900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18364522/" ]
74,549,925
<p>Say there is a list <code>[1,2,3,4,5]</code>, I would need to get the count of all possible combinations of the elements (or 'sub-lists'), e.g. <code>1, 2, 3, 4, 5, 12, 13, 14, ..., 123, 124, ..., 12345</code>.</p> <p>I know how to get <code>nCr</code>, the count of combinations of <code>r</code> elements of a list with total <code>n</code> elements.<br /> Python 3.8 or above:</p> <pre><code>from math import comb p, r = 5, 2 print(comb(p, r)) </code></pre> <p>Then I could do <code>nC1 + nC2 +...+ nCn</code>. But is there a better/faster way?</p> <pre><code>p, result = 5, 0 for r in range(1, 6): result += comb(p, r) print(result) </code></pre> <p>Would appreciate your answers.</p>
[ { "answer_id": 74549966, "author": "C4stor", "author_id": 2404988, "author_profile": "https://Stackoverflow.com/users/2404988", "pm_score": 1, "selected": true, "text": "2^n -1" }, { "answer_id": 74550020, "author": "jprebys", "author_id": 3268228, "author_profile": "https://Stackoverflow.com/users/3268228", "pm_score": 2, "selected": false, "text": "2^n n 2^n - 1" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74549925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3135373/" ]
74,549,942
<p>I have a function that creates new Jupyter Notebook cells and I'm trying to use a loop to show value counts for each column and the specific difficulty I have is having them return with the column names in quotes. Here's what I have:</p> <pre><code>def create_new_cell(contents): shell = get_ipython() payload = dict( source='set_next_input', text=contents, replace=False, ) shell.payload_manager.write_payload(payload, single=False) def show_vc(col): col = (f'(col)') content = &quot;df[{col_name}].value_counts()&quot;\ .format(col_name=col) create_new_cell(content) </code></pre> <p>^ This returns an actual 'col' instead of what I want, which is the series name.</p> <p>I've tried replacing</p> <pre><code>col = (f'(col)') </code></pre> <p>with things like</p> <pre><code>col = str(col) </code></pre> <p>or</p> <pre><code>col = &quot;(col)&quot; </code></pre> <p>but nothing has worked for me and I'm admittedly thinking about how to properly word this in a way so it will execute properly when I'm running my next cell, which is</p> <pre><code>for x in df.columns: show_vc(x) </code></pre> <p>Any help would be appreciated.</p>
[ { "answer_id": 74549966, "author": "C4stor", "author_id": 2404988, "author_profile": "https://Stackoverflow.com/users/2404988", "pm_score": 1, "selected": true, "text": "2^n -1" }, { "answer_id": 74550020, "author": "jprebys", "author_id": 3268228, "author_profile": "https://Stackoverflow.com/users/3268228", "pm_score": 2, "selected": false, "text": "2^n n 2^n - 1" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74549942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16370131/" ]
74,549,949
<p>Flutter Streambuilder code below runs without error and returns (screenshot at bottom):</p> <pre><code>ID: AzFdOO9WsFaFbTxTQsuo Data: Instance of '_JsonDocumentSnapshot' </code></pre> <h2>How do I get to the values inside the _JsonDocumentSnapshot and display them in the Text() widget?</h2> <p>For instance, there's a string field called &quot;name&quot;, but I can't figure out how to get to it.</p> <pre><code>StreamBuilder( stream: FirebaseFirestore.instance .collection(&quot;groceries&quot;) .doc(widget.docId) .snapshots(), builder: (context, streamSnapshot) { if (streamSnapshot.connectionState == ConnectionState.waiting) { return const Text(&quot;Loading&quot;); } else if (streamSnapshot.hasData) { return Text(&quot;ID: ${widget.docId}\n&quot; &quot;Data: ${streamSnapshot.data}&quot;); } else { return const Text(&quot;No Data&quot;); } } ) </code></pre> <p><a href="https://i.stack.imgur.com/FBEke.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FBEke.png" alt="Screenshot of _JsonDocumentSnapshot" /></a></p> <p>Thanks for your help!</p>
[ { "answer_id": 74550035, "author": "BLKKKBVSIK", "author_id": 11550065, "author_profile": "https://Stackoverflow.com/users/11550065", "pm_score": 0, "selected": false, "text": "streamSnapshot.data Object dynamic streamSnapshot.data['banana']" }, { "answer_id": 74550380, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 2, "selected": true, "text": "Stream DocumentSnapshot FirebaseFirestore.instance.collection(\"groceries\").doc(widget.docId).snapshots();\n Map<String, dynamic> data() snapshot.data() StreamBuilder<DocumentSnapshot>(\nstream: FirebaseFirestore.instance\n .collection(\"groceries\")\n .doc(widget.docId)\n .snapshots(),\n builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> streamSnapshot) {\n if (streamSnapshot.connectionState == ConnectionState.waiting) {\n return const Text(\"Loading\");\n } else if (streamSnapshot.hasData) {\n return Text(\"ID: ${widget.docId}\\n\"\n \"Data: ${streamSnapshot.data.data()}\"); // added data()\n } else {\n return const Text(\"No Data\");\n }\n }\n)\n Map<String, dynamic> Text" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74549949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6188976/" ]
74,549,955
<p>Here is the preview of the drop down list</p> <p><a href="https://i.stack.imgur.com/v3etl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/v3etl.png" alt="enter image description here" /></a></p> <p>Then, when I click on the dropdown to scroll the items</p> <p><a href="https://i.stack.imgur.com/0y8ul.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0y8ul.png" alt="enter image description here" /></a></p> <p>I think it's because I have too many items in the dropdown?</p> <pre><code>&lt;div class=&quot;row row-cols-3 pt-3&quot;&gt; &lt;div class=&quot;col text-end&quot;&gt; &lt;!-- Marché --&gt; &lt;label for=&quot;filterForMarkets&quot; class=&quot;form-label&quot;&gt;Marché&lt;/label&gt; &lt;/div&gt; &lt;div class=&quot;col-4&quot;&gt; &lt;select id=&quot;filterForMarkets&quot; name=&quot;filterForMarkets&quot; style=&quot;min-width: 440px&quot; class=&quot;form-select&quot; [(ngModel)]=&quot;search.market&quot;&gt; &lt;option value=&quot;&quot;&gt; Tous les marchés &lt;/option&gt; &lt;option *ngFor=&quot;let m of markets$ | async&quot; [value]=&quot;m.marketId&quot;&gt; {{ m.name }} &lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>If for example, I display 3 items only, I have no problem.</p> <p><a href="https://i.stack.imgur.com/gWaYO.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gWaYO.jpg" alt="enter image description here" /></a></p> <pre><code>&lt;div class=&quot;row row-cols-3 pt-3&quot;&gt; &lt;div class=&quot;col text-end&quot;&gt; &lt;!-- Marché --&gt; &lt;label for=&quot;filterForMarkets&quot; class=&quot;form-label&quot;&gt;Marché&lt;/label&gt; &lt;/div&gt; &lt;div class=&quot;col-4&quot;&gt; &lt;select id=&quot;filterForMarkets&quot; name=&quot;filterForMarkets&quot; style=&quot;min-width: 440px&quot; class=&quot;form-select&quot; [(ngModel)]=&quot;search.market&quot;&gt; &lt;option value=&quot;&quot;&gt; Tous les marchés &lt;/option&gt; &lt;option value=&quot;1&quot;&gt;One&lt;/option&gt; &lt;option value=&quot;2&quot;&gt;Two&lt;/option&gt; &lt;option value=&quot;3&quot;&gt;Three&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Unfortunately, I need my loop, is there a way in css to display my items correctly, please?</p>
[ { "answer_id": 74550035, "author": "BLKKKBVSIK", "author_id": 11550065, "author_profile": "https://Stackoverflow.com/users/11550065", "pm_score": 0, "selected": false, "text": "streamSnapshot.data Object dynamic streamSnapshot.data['banana']" }, { "answer_id": 74550380, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 2, "selected": true, "text": "Stream DocumentSnapshot FirebaseFirestore.instance.collection(\"groceries\").doc(widget.docId).snapshots();\n Map<String, dynamic> data() snapshot.data() StreamBuilder<DocumentSnapshot>(\nstream: FirebaseFirestore.instance\n .collection(\"groceries\")\n .doc(widget.docId)\n .snapshots(),\n builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> streamSnapshot) {\n if (streamSnapshot.connectionState == ConnectionState.waiting) {\n return const Text(\"Loading\");\n } else if (streamSnapshot.hasData) {\n return Text(\"ID: ${widget.docId}\\n\"\n \"Data: ${streamSnapshot.data.data()}\"); // added data()\n } else {\n return const Text(\"No Data\");\n }\n }\n)\n Map<String, dynamic> Text" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74549955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18427717/" ]
74,549,960
<p><em>Program got a Syntax error as follow:</em></p> <p>elif choice == &quot;3&quot;: ^^^^ SyntaxError: invalid syntax</p> <pre><code>print(&quot;1 Addition\n2 Subtraction\n3 Multiplication\n4 Division &quot;) choice= input (&quot;WHat is you choice? : &quot;) num1 = float (input(&quot;Please enter a number: &quot;)) num2 = float( input(&quot;please enter another number: &quot;)) if choice == &quot;1&quot;: print(Num1,&quot;+&quot;, Num2, &quot;=&quot;, (Num1 + Num2)) elif choice == &quot;2&quot;: print(Num1,&quot;-&quot;, Num2, &quot;=&quot;, (Num1 - Num2)) elif choice == &quot;3&quot;: print(Num1,&quot;x&quot;, Num2, &quot;=&quot;, (Num1 * Num2)) elif choice == &quot;4&quot;: if Num2 == 0.0 print(&quot;0 error LOL&quot;) else: print(Num1, &quot;/&quot;, Num2, &quot;=&quot;, (Num1 / Num2) ) else: print(&quot;your choice is bad...&quot;) </code></pre>
[ { "answer_id": 74550083, "author": "Prime Price", "author_id": 19685980, "author_profile": "https://Stackoverflow.com/users/19685980", "pm_score": -1, "selected": false, "text": "print(\"1 Addition\\n2 Subtraction\\n3 Multiplication\\n4 Division \")\nchoice= input(\"What is you choice? : \")\nnum1 = float(input(\"Please enter a number: \"))\nnum2 = float(input(\"please enter another number: \"))\n\nif choice == \"1\":\n print(f\"{Num1}+{Num2}={Num1 + Num2}\")\nelif choice == \"2\":\n print(f\"{Num1}-{Num2}={Num1 - Num2}\")\nelif choice == \"3\":\n print(f\"{Num1}*{Num2}={Num1 * Num2}\")\nelif choice == \"4\":\n if Num2 == 0.0\n print(\"0 error LOL\")\n else:\n print(f\"{Num1}/{Num2}={Num1 / Num2}\")\nelse:\n print(\"your choice is bad...\")\n" }, { "answer_id": 74550160, "author": "michael perkins", "author_id": 19620151, "author_profile": "https://Stackoverflow.com/users/19620151", "pm_score": -1, "selected": true, "text": "print(\"1 Addition\\n2 Subtraction\\n3 Multiplication\\n4 Division \")\nchoice= input (\"WHat is you choice? : \")\nnum1 = float (input(\"Please enter a number: \"))\nnum2 = float( input(\"please enter another number: \"))\n\nif choice == \"1\":\n print(num1,\"+\", num2, \"=\", (num1 + num2))\nelif choice == \"2\":\n print(num1,\"-\", num2, \"=\", (num1 - num2))\nelif choice == \"3\":\n print(num1,\"x\", num2, \"=\", (num1 * num2))\nelif choice == \"4\":\n if num2 == 0.0:\n print(\"0 error LOL\")\n else:\n print(num1, \"/\", num2, \"=\", (num1 / num2) )\nelse:\n print(\"your choice is bad...\")\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74549960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20583723/" ]
74,549,982
<p>I am currently learning Java and received the following task, that I cannot seem to solve:</p> <p>&quot;Create a Java program that prints one random poem of 5 lines in the console. The poems must be read from a text file.&quot;</p> <p>I have copied 10 different poems inside a text file, all written underneath each other. I managed to make the program print out the very first poem (first 5 lines) in the console, but first of all, I am not sure if it's the correct way to do such, and I don't know how to make the program print out one random poem (5 lines that belong together) each time I run it.</p> <p>Here is the farthest I could get:</p> <pre><code>public static void main(String[] args) throws IOException { File file = new File(&quot;src/main/java/org/example/text.txt&quot;); Scanner scanner = null; try { scanner = new Scanner(file); int i = 0; while (scanner.hasNext()) { String line = scanner.nextLine(); if (i &lt; 5) { i++; System.out.println(line); } } } catch (Exception e) { } } </code></pre>
[ { "answer_id": 74550083, "author": "Prime Price", "author_id": 19685980, "author_profile": "https://Stackoverflow.com/users/19685980", "pm_score": -1, "selected": false, "text": "print(\"1 Addition\\n2 Subtraction\\n3 Multiplication\\n4 Division \")\nchoice= input(\"What is you choice? : \")\nnum1 = float(input(\"Please enter a number: \"))\nnum2 = float(input(\"please enter another number: \"))\n\nif choice == \"1\":\n print(f\"{Num1}+{Num2}={Num1 + Num2}\")\nelif choice == \"2\":\n print(f\"{Num1}-{Num2}={Num1 - Num2}\")\nelif choice == \"3\":\n print(f\"{Num1}*{Num2}={Num1 * Num2}\")\nelif choice == \"4\":\n if Num2 == 0.0\n print(\"0 error LOL\")\n else:\n print(f\"{Num1}/{Num2}={Num1 / Num2}\")\nelse:\n print(\"your choice is bad...\")\n" }, { "answer_id": 74550160, "author": "michael perkins", "author_id": 19620151, "author_profile": "https://Stackoverflow.com/users/19620151", "pm_score": -1, "selected": true, "text": "print(\"1 Addition\\n2 Subtraction\\n3 Multiplication\\n4 Division \")\nchoice= input (\"WHat is you choice? : \")\nnum1 = float (input(\"Please enter a number: \"))\nnum2 = float( input(\"please enter another number: \"))\n\nif choice == \"1\":\n print(num1,\"+\", num2, \"=\", (num1 + num2))\nelif choice == \"2\":\n print(num1,\"-\", num2, \"=\", (num1 - num2))\nelif choice == \"3\":\n print(num1,\"x\", num2, \"=\", (num1 * num2))\nelif choice == \"4\":\n if num2 == 0.0:\n print(\"0 error LOL\")\n else:\n print(num1, \"/\", num2, \"=\", (num1 / num2) )\nelse:\n print(\"your choice is bad...\")\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74549982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19766690/" ]
74,549,985
<p>If you use the await keyword does it have any limits or does it wait indefinitely for the task to complete?</p> <p>EDIT: The full context I have is...</p> <p>A frontend application issues a non async HTTP request to an async Web API endpoint. Ultimately the endpoint will await a call to a stored proc on a db. The frontend application hits a HTTP timeout after probably 100 seconds. If the proc takes 35 minutes to complete,</p> <ol> <li>Will the await method wait 35 minutes for the proc to complete or are there limits?</li> <li>What happens the await call when the HTTP timeout completes after 100 seconds?</li> <li>if it continues to run, what happens when the proc returns a response after 35 minutes?</li> </ol>
[ { "answer_id": 74550337, "author": "Theodor Zoulias", "author_id": 11178549, "author_profile": "https://Stackoverflow.com/users/11178549", "pm_score": 3, "selected": false, "text": "await await await await Task.Delay(Timeout.Infinite);\nthrow new UnreachableException(); // This line is unreachable.\n Task Task<TResult> WaitAsync TimeSpan timeout timeout WaitAsync TimeoutException" }, { "answer_id": 74550480, "author": "Panagiotis Kanavos", "author_id": 134204, "author_profile": "https://Stackoverflow.com/users/134204", "pm_score": 4, "selected": true, "text": "await Task.WaitAsync await await ExecuteNonQuery ExecuteNonQuery What does this mean async async" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74549985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12716922/" ]
74,550,014
<p>In the following code, I've outlined two problems (see comments):</p> <ol> <li>I need a static method to return an instance of the current class. When it is called on a subclass (without being overwritten), it should return an instance of the subclass.</li> <li>I need a generic to be more specific in a subclass (<code>Base</code> should take <code>BaseOptions</code> while <code>Sub</code> should take <code>SubOptions</code> which are a superset of <code>BaseOptions</code>).</li> </ol> <p>Solutions with <code>extends BaseOptions | SubOptions</code> don't work for me, as I cannot enumerate all of the possible, more specific types of options to keep the code generic.</p> <p>Am I approaching this the wrong way altogether or is there a solution to my problems?</p> <pre class="lang-js prettyprint-override"><code>interface BaseOptions { a: string } interface SubOptions extends BaseOptions { a: string b: string } class Base&lt;T extends BaseOptions&gt; { options: T constructor(options: T) { this.options = options; } // Problem 1: When TypeScript is concerned, this method always returns an // instance of &quot;Base&quot;, even when calling 'create' on a subclass (that does not // override 'create'). How can this be fixed? static create&lt;T extends BaseOptions&gt;(options: T): Base&lt;T&gt; { return new this(options); } } // Problem 2: Class 'Sub' requires more specific options than class 'Base', but // TypeScript does not allow me to validate it: // 2417: Class static side 'typeof Sub' // incorrectly extends base class static // side 'typeof Base'. class Sub&lt;T extends SubOptions&gt; extends Base&lt;T&gt; { static create&lt;T extends SubOptions&gt;(options: T): Sub&lt;T&gt; { return new this(options); } } </code></pre>
[ { "answer_id": 74615119, "author": "dbonev", "author_id": 4200334, "author_profile": "https://Stackoverflow.com/users/4200334", "pm_score": 0, "selected": false, "text": "interface IGenericMap<T> {\n [x: string]: T;\n}\n \nclass Base<T extends IGenericMap<string>> {\n options: T\n\n constructor(options: T) {\n this.options = options;\n }\n\n static create<T extends IGenericMap<string>>(options: T): Base<T> {\n return new this(options);\n }\n}\n\nclass Sub<T extends IGenericMap<string>> extends Base<T> {\n constructor(options: T) {\n super(options);\n }\n}\n\nconsole.log(Base.create({ a: 'one' }));\nconsole.log(Sub.create({ a: 'one', b: 'two' }));\n interface BaseOptions {\n a: string\n}\n\ninterface SubOptions extends BaseOptions {\n a: string\n b: string\n}\n \nclass Base<T extends BaseOptions> {\n options: T\n\n constructor(options: T) {\n this.options = options;\n }\n\n static create<T extends BaseOptions>(options: T): Base<T> {\n return new this(options);\n }\n}\n\nclass Sub<T extends SubOptions> extends Base<T> {\n constructor(options: T) {\n super(options);\n }\n}\n\nconsole.log(Base.create({ a: 'one' }));\nconsole.log(Sub.create({ a: 'one', b: 'two', c: '' }));\n" }, { "answer_id": 74659640, "author": "Friedrich", "author_id": 2689500, "author_profile": "https://Stackoverflow.com/users/2689500", "pm_score": 1, "selected": false, "text": "type BaseOptions = {\n a: string;\n};\n\ntype SubOptions = {\n a: string;\n b: string;\n} & BaseOptions;\n\nclass Base<BO extends BaseOptions> {\n options: BO;\n\n constructor(options: BO) {\n this.options = options;\n }\n\n static create<BO extends BaseOptions>(options: BO): Base<BO> {\n return new this(options);\n }\n}\n\nclass Sub<SO extends SubOptions> extends Base<SO> {}\n const sub = Sub.create({ a: 'a', b: 'b' }) as Sub<...>;\n sub const sub = Sub.create({ a: 'a', b: 'b' });\n Base<{ a: string, b: string } Sub<...> class Base {\n constructor(options) {\n this.options = options\n }\n\n static create(options) {\n return new this(options)\n }\n}\n\nclass Sub extends Base {}\n\nSub.create({ a: 'a', b: 'b' })\n > Sub { options: { a: 'a', b: 'b' } }\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/351756/" ]
74,550,059
<p>So I need to make it to sum numbers after 10 and add after number is summed +1 like after 10 to sum the result before with 11 and the final result should be lower than 1000 I did mistake and typed = its only &lt;. At the end it needs to console writeline the last number which was summed for example 35 to make the last number.</p> <pre><code>int i = 10; int a = 10; while (i &lt; 1000) { a = a + i; } Console.WriteLine(a); </code></pre> <p>I have tried to sum all of them in the while but it just give me 1280</p>
[ { "answer_id": 74615119, "author": "dbonev", "author_id": 4200334, "author_profile": "https://Stackoverflow.com/users/4200334", "pm_score": 0, "selected": false, "text": "interface IGenericMap<T> {\n [x: string]: T;\n}\n \nclass Base<T extends IGenericMap<string>> {\n options: T\n\n constructor(options: T) {\n this.options = options;\n }\n\n static create<T extends IGenericMap<string>>(options: T): Base<T> {\n return new this(options);\n }\n}\n\nclass Sub<T extends IGenericMap<string>> extends Base<T> {\n constructor(options: T) {\n super(options);\n }\n}\n\nconsole.log(Base.create({ a: 'one' }));\nconsole.log(Sub.create({ a: 'one', b: 'two' }));\n interface BaseOptions {\n a: string\n}\n\ninterface SubOptions extends BaseOptions {\n a: string\n b: string\n}\n \nclass Base<T extends BaseOptions> {\n options: T\n\n constructor(options: T) {\n this.options = options;\n }\n\n static create<T extends BaseOptions>(options: T): Base<T> {\n return new this(options);\n }\n}\n\nclass Sub<T extends SubOptions> extends Base<T> {\n constructor(options: T) {\n super(options);\n }\n}\n\nconsole.log(Base.create({ a: 'one' }));\nconsole.log(Sub.create({ a: 'one', b: 'two', c: '' }));\n" }, { "answer_id": 74659640, "author": "Friedrich", "author_id": 2689500, "author_profile": "https://Stackoverflow.com/users/2689500", "pm_score": 1, "selected": false, "text": "type BaseOptions = {\n a: string;\n};\n\ntype SubOptions = {\n a: string;\n b: string;\n} & BaseOptions;\n\nclass Base<BO extends BaseOptions> {\n options: BO;\n\n constructor(options: BO) {\n this.options = options;\n }\n\n static create<BO extends BaseOptions>(options: BO): Base<BO> {\n return new this(options);\n }\n}\n\nclass Sub<SO extends SubOptions> extends Base<SO> {}\n const sub = Sub.create({ a: 'a', b: 'b' }) as Sub<...>;\n sub const sub = Sub.create({ a: 'a', b: 'b' });\n Base<{ a: string, b: string } Sub<...> class Base {\n constructor(options) {\n this.options = options\n }\n\n static create(options) {\n return new this(options)\n }\n}\n\nclass Sub extends Base {}\n\nSub.create({ a: 'a', b: 'b' })\n > Sub { options: { a: 'a', b: 'b' } }\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19978292/" ]
74,550,104
<p>To try to solve the question above I tried by creating a list with the range and then a list with the variables in it. Then to check if the variables are in the list i used an if loop however it is not working and only printing out &quot;out of range...&quot;. I have also tried a while loop and it would just repeat the total 7 times. I do not know how to fix it and would please like an answer. Thank you</p> <pre><code>def main(): a = [0, 20, 40, 60, 80, 100, 120] try: userPass = int(input(&quot;Enter pass credits: &quot;)) userDefer = int(input(&quot;Enter defer credits: &quot;)) userFail = int(input(&quot;Enter fail credits: &quot;)) except: print(&quot;Invalid number.&quot;) total = userFail + userPass + userDefer aValues = [ userPass, userFail, userDefer ] if aValues in a: print(total) else: print(&quot;Out of range. Try again&quot;) if total &gt; 120: print(&quot;Total incorrect&quot;) repeat() else: if userPass &gt;= 120: print(&quot;This student has progressed.&quot;) repeat() elif userPass &gt;= 100 and total == 120: print(&quot;This student is trailing.&quot;) repeat() elif userFail &lt;= 60 and total == 120: print(&quot;This student did not progress(module retreiver).&quot;) repeat() elif userPass &lt;= userFail: print(&quot;This students program outcome is exclude.&quot;) repeat() else: print(&quot;incorrect. Try again.&quot;) repeat() def repeat(): choice = int(input(&quot;If you would like to quit type 1 or test another student write 2: &quot;)) if choice != 1 and choice != 2: repeat() else: while choice == 2: main() while choice == 1: break print(&quot;Thank you.&quot;) main() </code></pre>
[ { "answer_id": 74615119, "author": "dbonev", "author_id": 4200334, "author_profile": "https://Stackoverflow.com/users/4200334", "pm_score": 0, "selected": false, "text": "interface IGenericMap<T> {\n [x: string]: T;\n}\n \nclass Base<T extends IGenericMap<string>> {\n options: T\n\n constructor(options: T) {\n this.options = options;\n }\n\n static create<T extends IGenericMap<string>>(options: T): Base<T> {\n return new this(options);\n }\n}\n\nclass Sub<T extends IGenericMap<string>> extends Base<T> {\n constructor(options: T) {\n super(options);\n }\n}\n\nconsole.log(Base.create({ a: 'one' }));\nconsole.log(Sub.create({ a: 'one', b: 'two' }));\n interface BaseOptions {\n a: string\n}\n\ninterface SubOptions extends BaseOptions {\n a: string\n b: string\n}\n \nclass Base<T extends BaseOptions> {\n options: T\n\n constructor(options: T) {\n this.options = options;\n }\n\n static create<T extends BaseOptions>(options: T): Base<T> {\n return new this(options);\n }\n}\n\nclass Sub<T extends SubOptions> extends Base<T> {\n constructor(options: T) {\n super(options);\n }\n}\n\nconsole.log(Base.create({ a: 'one' }));\nconsole.log(Sub.create({ a: 'one', b: 'two', c: '' }));\n" }, { "answer_id": 74659640, "author": "Friedrich", "author_id": 2689500, "author_profile": "https://Stackoverflow.com/users/2689500", "pm_score": 1, "selected": false, "text": "type BaseOptions = {\n a: string;\n};\n\ntype SubOptions = {\n a: string;\n b: string;\n} & BaseOptions;\n\nclass Base<BO extends BaseOptions> {\n options: BO;\n\n constructor(options: BO) {\n this.options = options;\n }\n\n static create<BO extends BaseOptions>(options: BO): Base<BO> {\n return new this(options);\n }\n}\n\nclass Sub<SO extends SubOptions> extends Base<SO> {}\n const sub = Sub.create({ a: 'a', b: 'b' }) as Sub<...>;\n sub const sub = Sub.create({ a: 'a', b: 'b' });\n Base<{ a: string, b: string } Sub<...> class Base {\n constructor(options) {\n this.options = options\n }\n\n static create(options) {\n return new this(options)\n }\n}\n\nclass Sub extends Base {}\n\nSub.create({ a: 'a', b: 'b' })\n > Sub { options: { a: 'a', b: 'b' } }\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20583729/" ]
74,550,121
<p>I'm trying to find an easy way how to check all tables in schema where this columns doesn't exists.</p> <p>So my case: In the middle of project we started adding some technical columns that needs to be in every table in that schema and I want to get list of tables that doesn't have this column.</p> <p>Is there an easy way of doing that?</p>
[ { "answer_id": 74550446, "author": "Greg Pavlik", "author_id": 12756381, "author_profile": "https://Stackoverflow.com/users/12756381", "pm_score": 0, "selected": false, "text": "ID UUID select TABLE_NAME from\n(select TABLE_NAME, arrayagg(COLUMN_NAME) COLS from \n information_schema.columns group by TABLE_NAME)\nwhere not array_contains('ID'::variant, COLS)\n or not array_contains('UUID'::variant, COLS)\n;\n" }, { "answer_id": 74550587, "author": "Lukasz Szozda", "author_id": 5070879, "author_profile": "https://Stackoverflow.com/users/5070879", "pm_score": 2, "selected": true, "text": "QUALIFY COUNT_IF USE DATABASE <db_name>;\n\nSELECT DISTINCT c.TABLE_CATALOG, c.TABLE_SCHEMA, c.TABLE_NAME\nFROM INFORMATION_SCHEMA.COLUMNS AS c\nWHERE c.TABLE_SCHEMA ILIKE ANY ('<SCHEMA_NAME1>', '<SCHEMA_NAME2>')\nQUALIFY COUNT_IF(c.COLUMN_NAME ILIKE '<SOME_TECHNICAL_COL>')\n OVER(PARTITION BY c.TABLE_CATALOG, c.TABLE_SCHEMA, c.TABLE_NAME) = 0;\n" }, { "answer_id": 74550612, "author": "Gokhan Atil", "author_id": 12550965, "author_profile": "https://Stackoverflow.com/users/12550965", "pm_score": 0, "selected": false, "text": "select concat_ws( '.', table_catalog, table_schema, table_name) \nfrom information_Schema.tables \nwhere concat_ws( '.', table_catalog, table_schema, table_name) not in (\nselect concat_ws( '.', table_catalog, table_schema, table_name) \nfrom information_Schema.columns where column_name = 'ID');\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18282299/" ]
74,550,138
<p>I am trying to multiply 2 matrices. I have to do this multiplication a bunch of times so I created a function</p> <pre><code>float multiply_,matrix(float mat_1[R][C1], float mat_2[R][C2]) </code></pre> <p>This function returns an array which I want to store in an array declared in main. But I get an error</p> <blockquote> <p>not modifiable lvalue</p> </blockquote> <p>How can I store result of the function in a different array?</p> <p>Function :</p> <pre><code>float multiply_matrix(float mat_1[N][R1], float mat_2[N][R2]){ float temp[N][C2]; // temporary matrix for (int i = 0; i &lt; N; i++){ for (int j = 0; j &lt; R2; j++){ //since stress matrix has only one column temp[i][j] = 0; for (int a = 0; a &lt; N; a++){ //N here is the number of rows of the 2nd matrix temp[i][j] += mat_1[i][a]*mat_2[a][j]; } } } return temp[N][C2]; } </code></pre> <p>The way I'm trying to store the value in the main function:</p> <pre><code>float stress_12[N][R2]; stress_12 = multiple_matrix(T,stress_12); </code></pre> <p>I was expecting the array to be directly stored, but got an error</p> <blockquote> <p>expression must be an lvalue</p> </blockquote> <p>I did understand what an lvalue error is from <a href="https://stackoverflow.com/questions/12745601/expression-must-be-a-modifiable-lvalue">here</a>, but I couldn't think of a way to store the result of the function.</p>
[ { "answer_id": 74550446, "author": "Greg Pavlik", "author_id": 12756381, "author_profile": "https://Stackoverflow.com/users/12756381", "pm_score": 0, "selected": false, "text": "ID UUID select TABLE_NAME from\n(select TABLE_NAME, arrayagg(COLUMN_NAME) COLS from \n information_schema.columns group by TABLE_NAME)\nwhere not array_contains('ID'::variant, COLS)\n or not array_contains('UUID'::variant, COLS)\n;\n" }, { "answer_id": 74550587, "author": "Lukasz Szozda", "author_id": 5070879, "author_profile": "https://Stackoverflow.com/users/5070879", "pm_score": 2, "selected": true, "text": "QUALIFY COUNT_IF USE DATABASE <db_name>;\n\nSELECT DISTINCT c.TABLE_CATALOG, c.TABLE_SCHEMA, c.TABLE_NAME\nFROM INFORMATION_SCHEMA.COLUMNS AS c\nWHERE c.TABLE_SCHEMA ILIKE ANY ('<SCHEMA_NAME1>', '<SCHEMA_NAME2>')\nQUALIFY COUNT_IF(c.COLUMN_NAME ILIKE '<SOME_TECHNICAL_COL>')\n OVER(PARTITION BY c.TABLE_CATALOG, c.TABLE_SCHEMA, c.TABLE_NAME) = 0;\n" }, { "answer_id": 74550612, "author": "Gokhan Atil", "author_id": 12550965, "author_profile": "https://Stackoverflow.com/users/12550965", "pm_score": 0, "selected": false, "text": "select concat_ws( '.', table_catalog, table_schema, table_name) \nfrom information_Schema.tables \nwhere concat_ws( '.', table_catalog, table_schema, table_name) not in (\nselect concat_ws( '.', table_catalog, table_schema, table_name) \nfrom information_Schema.columns where column_name = 'ID');\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14672877/" ]
74,550,149
<p>I'm working on creating a ripple effect in SwiftUI similar to the one <a href="https://m2.material.io/develop/ios/supporting/ripple" rel="nofollow noreferrer">here</a>.</p> <p>Here is what I have so far:</p> <pre class="lang-swift prettyprint-override"><code>import SwiftUI // MARK: - Ripple struct Ripple: ViewModifier { // MARK: Lifecycle init(rippleColor: Color) { self.rippleColor = rippleColor } // MARK: Internal let rippleColor: Color func body(content: Content) -&gt; some View { ZStack { content if let location = touchPoint { Circle() .fill(rippleColor) .frame(width: 16.0, height: 16.0) .position(location) .clipped() .opacity(opacity) } } .fixedSize() .gesture( DragGesture(minimumDistance: 0.0) .onChanged { gesture in guard touchPoint != gesture.startLocation else { return } timer?.invalidate() opacity = 1.0 touchPoint = gesture.startLocation } .onEnded { _ in timer = Timer.scheduledTimer(withTimeInterval: 2.0, repeats: false) { _ in withAnimation { opacity = 0.0 } } } ) } // MARK: Private @State private var opacity: CGFloat = 0.0 @State private var touchPoint: CGPoint? @State private var timer: Timer? } extension View { func rippleEffect(rippleColor: Color = .accentColor.opacity(0.5)) -&gt; some View { modifier(Ripple(rippleColor: rippleColor)) } } </code></pre> <p>The next step is to do the scaling animation, but I'm having trouble figuring out how. I've tried applying scale effects and transitions with the scale modifier, but nothing seems to work correctly.</p> <p>Can someone assist me in achieving the ripple effect I'm looking for?</p> <p>Additionally, if something like this already exists, I'd be happy to just use it, but I haven't been able to find anything.</p> <p>Thanks,</p> <p>RPK</p>
[ { "answer_id": 74561422, "author": "Frederik Mrozek", "author_id": 17997003, "author_profile": "https://Stackoverflow.com/users/17997003", "pm_score": 2, "selected": false, "text": "struct ContentView: View {\n var body: some View {\n VStack {\n Image(systemName: \"globe\")\n .imageScale(.large)\n .foregroundColor(.accentColor)\n Text(\"Hello, world!\")\n }\n .rippleEffect(rippleColor: .gray)\n .frame(width: 400, height: 200)\n .padding()\n }\n}\n\nstruct Ripple: ViewModifier {\n // MARK: Lifecycle\n\n init(rippleColor: Color) {\n self.color = rippleColor\n }\n\n // MARK: Internal\n\n let color: Color\n\n @State private var scale: CGFloat = 0.5\n \n @State private var animationPosition: CGFloat = 0.0\n @State private var x: CGFloat = 0.0\n @State private var y: CGFloat = 0.0\n \n @State private var opacityFraction: CGFloat = 0.0\n \n let timeInterval: TimeInterval = 0.5\n \n func body(content: Content) -> some View {\n GeometryReader { geometry in\n ZStack {\n Rectangle()\n .foregroundColor(.gray.opacity(0.05))\n Circle()\n .foregroundColor(color)\n .opacity(0.2*opacityFraction)\n .scaleEffect(scale)\n .offset(x: x, y: y)\n content\n }\n .onTapGesture(perform: { location in\n x = location.x-geometry.size.width/2\n y = location.y-geometry.size.height/2\n opacityFraction = 1.0\n withAnimation(.linear(duration: timeInterval)) {\n scale = 3.0*(max(geometry.size.height, geometry.size.width)/min(geometry.size.height, geometry.size.width))\n opacityFraction = 0.0\n DispatchQueue.main.asyncAfter(deadline: .now() + timeInterval) {\n scale = 1.0\n opacityFraction = 0.0\n }\n }\n })\n .clipped()\n }\n }\n}\n\nextension View {\n func rippleEffect(rippleColor: Color = .accentColor.opacity(0.5)) -> some View {\n modifier(Ripple(rippleColor: rippleColor))\n }\n}\n" }, { "answer_id": 74564946, "author": "RPK", "author_id": 4408483, "author_profile": "https://Stackoverflow.com/users/4408483", "pm_score": 1, "selected": false, "text": "import SwiftUI\n\n// MARK: - ContentView\n\nstruct ContentView: View {\n var body: some View {\n VStack {\n Image(systemName: \"globe\")\n .imageScale(.large)\n .foregroundColor(.accentColor)\n Text(\"Hello, world!\")\n }\n .rippleEffect(rippleColor: .gray)\n .frame(width: 400, height: 200)\n .padding()\n }\n}\n\n// MARK: - Ripple\n\nstruct Ripple: ViewModifier {\n // MARK: Lifecycle\n\n init(rippleColor: Color) {\n color = rippleColor\n }\n\n // MARK: Internal\n\n let color: Color\n\n let timeInterval: TimeInterval = 0.5\n\n func body(content: Content) -> some View {\n GeometryReader { geometry in\n ZStack {\n Rectangle()\n .foregroundColor(.gray.opacity(0.05))\n Circle()\n .foregroundColor(color)\n .opacity(0.2 * opacityFraction)\n .scaleEffect(scale)\n .offset(x: x, y: y)\n content\n }\n .gesture(\n DragGesture(minimumDistance: 0.0)\n .onChanged { gesture in\n let location = gesture.startLocation\n\n x = location.x - geometry.size.width / 2\n y = location.y - geometry.size.height / 2\n\n opacityFraction = 1.0\n\n withAnimation(.linear(duration: timeInterval / 2.0)) {\n scale = 3.0 *\n (\n max(geometry.size.height, geometry.size.width) /\n min(geometry.size.height, geometry.size.width)\n )\n }\n }\n .onEnded { _ in\n withAnimation(.linear(duration: timeInterval / 2.0)) {\n opacityFraction = 0.0\n scale = 1.0\n }\n }\n )\n .clipped()\n }\n }\n\n // MARK: Private\n\n @State private var scale: CGFloat = 0.5\n\n @State private var animationPosition: CGFloat = 0.0\n @State private var x: CGFloat = 0.0\n @State private var y: CGFloat = 0.0\n\n @State private var opacityFraction: CGFloat = 0.0\n}\n\nextension View {\n func rippleEffect(rippleColor: Color = .accentColor.opacity(0.5)) -> some View {\n modifier(Ripple(rippleColor: rippleColor))\n }\n}\n\n// MARK: - ContentView_Previews\n\nstruct ContentView_Previews: PreviewProvider {\n static var previews: some View {\n ContentView()\n }\n}\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4408483/" ]
74,550,214
<p>Hi guys i have this code:</p> <pre><code>var sites = context.SITES.OrderBy(s =&gt; s.NAME).ToList(); if (userId != 0) sites = context.SITES.OrderBy(s =&gt; s.NAME).Where(s =&gt; s.Users.Any(x =&gt; x.ID == userId)).ToList(); </code></pre> <p>Is it possible to make the if inside the query? I need to do this code in one line</p> <pre><code>var sites = context.SITES.OrderBy(s =&gt; s.NAME) if(userId != 0) { .Where(s =&gt; s.Users.Any(x =&gt; x.ID == userId)) } .ToList(); </code></pre> <p>I want something like this</p>
[ { "answer_id": 74550279, "author": "D Stanley", "author_id": 1081897, "author_profile": "https://Stackoverflow.com/users/1081897", "pm_score": 1, "selected": true, "text": "IQueryable<Site> sites = context.SITES.OrderBy(s => s.NAME) \nif(userId != 0) {\n sites = sites.Where(s => s.Users.Any(x => x.ID == userId)) \n}\n if var sites = sites.Where(s => (userId == 0) || (s.Users.Any(x => x.ID == userId))) \n .OrderBy(s => s.NAME)\n .ToList()\n" }, { "answer_id": 74550285, "author": "DavidG", "author_id": 1663001, "author_profile": "https://Stackoverflow.com/users/1663001", "pm_score": 2, "selected": false, "text": "IQueryable IQueryable<Site> query = context.SITES;\n if(userId != 0) {\n query = query.Where(s => s.Users.Any(x => x.ID == userId)) ;\n}\n var list = query.OrderBy(s => s.NAME).ToList();\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12322107/" ]
74,550,243
<p>I have the following dataframe:</p> <pre><code>df &lt;- structure(list(Page = c(&quot;/es/import-340600-to-mx-from-de/summary&quot;, &quot;/es/import-340600-to-de-from-mx/summary&quot;, &quot;/es/import-071320-to-sv-from-cr/summary&quot;, &quot;/en/import-340111-to-ru-from-ir/summary&quot;, &quot;/en/import-870423-to-hk-from-de/summary&quot;, &quot;/es/import-392049-to-mx-from-de/summary&quot;, &quot;/es/import-080440-to-mx-from-es/summary&quot;, &quot;/es/import-340600-to-mx-from-jp/summary&quot;, &quot;/en/import-852691-to-tr-from-ua/summary&quot;, &quot;/es/import-180620-to-mx-from-us/summary&quot;), Count = c(153, 78, 72, 58, 57, 55, 48, 46, 42, 42)), class = c(&quot;tbl_df&quot;, &quot;tbl&quot;, &quot;data.frame&quot;), row.names = c(NA, -10L)) Page Count &lt;chr&gt; &lt;dbl&gt; 1 /es/import-340600-to-mx-from-de/summary 153 2 /es/import-340600-to-de-from-mx/summary 78 3 /es/import-071320-to-sv-from-cr/summary 72 4 /en/import-340111-to-ru-from-ir/summary 58 5 /en/import-870423-to-hk-from-de/summary 57 6 /es/import-392049-to-mx-from-de/summary 55 7 /es/import-080440-to-mx-from-es/summary 48 8 /es/import-340600-to-mx-from-jp/summary 46 9 /en/import-852691-to-tr-from-ua/summary 42 10 /es/import-180620-to-mx-from-us/summary 42 </code></pre> <p>For example, from this row below,how can I extract and put <strong>mx</strong> and <strong>de</strong> into 2 separate columns? And do the same for the rest of the table</p> <pre><code>1 /es/import-340600-to-mx-from-de/summary 153 </code></pre> <p>Expected output:</p> <p><a href="https://i.stack.imgur.com/77oUB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/77oUB.png" alt="enter image description here" /></a></p> <p>......</p>
[ { "answer_id": 74550293, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, "author_profile": "https://Stackoverflow.com/users/3358272", "pm_score": 3, "selected": true, "text": "strcapture (.) data.frame proto= cbind(df, strcapture(\".*-to-([^-/]*)-from-([^-/]*).*\", df$Page, proto=list(to=\"\", from=\"\")))\n# Page Count to from\n# 1 /es/import-340600-to-mx-from-de/summary 153 mx de\n# 2 /es/import-340600-to-de-from-mx/summary 78 de mx\n# 3 /es/import-071320-to-sv-from-cr/summary 72 sv cr\n# 4 /en/import-340111-to-ru-from-ir/summary 58 ru ir\n# 5 /en/import-870423-to-hk-from-de/summary 57 hk de\n# 6 /es/import-392049-to-mx-from-de/summary 55 mx de\n# 7 /es/import-080440-to-mx-from-es/summary 48 mx es\n# 8 /es/import-340600-to-mx-from-jp/summary 46 mx jp\n# 9 /en/import-852691-to-tr-from-ua/summary 42 tr ua\n# 10 /es/import-180620-to-mx-from-us/summary 42 mx us\n library(dplyr)\ndf %>%\n mutate(strcapture(\".*-to-([^-/]*)-from-([^-/]*).*\", Page, list(to=\"\", from=\"\")))\n# # A tibble: 10 x 4\n# Page Count to from \n# <chr> <dbl> <chr> <chr>\n# 1 /es/import-340600-to-mx-from-de/summary 153 mx de \n# 2 /es/import-340600-to-de-from-mx/summary 78 de mx \n# 3 /es/import-071320-to-sv-from-cr/summary 72 sv cr \n# 4 /en/import-340111-to-ru-from-ir/summary 58 ru ir \n# 5 /en/import-870423-to-hk-from-de/summary 57 hk de \n# 6 /es/import-392049-to-mx-from-de/summary 55 mx de \n# 7 /es/import-080440-to-mx-from-es/summary 48 mx es \n# 8 /es/import-340600-to-mx-from-jp/summary 46 mx jp \n# 9 /en/import-852691-to-tr-from-ua/summary 42 tr ua \n# 10 /es/import-180620-to-mx-from-us/summary 42 mx us \n df$Page[2] <- \"/es/import-340600-TO-de-from-mx/summary\" # \"TO\" not \"to\"\ndf %>%\n mutate(to = stringr::str_match(Page, \".*-to-([^/-]*)\")[,2], from = stringr::str_match(Page, \".*-from-([^/-]*)\")[,2])\n# # A tibble: 10 x 4\n# Page Count to from \n# <chr> <dbl> <chr> <chr>\n# 1 /es/import-340600-to-mx-from-de/summary 153 mx de \n# 2 /es/import-340600-TO-de-from-mx/summary 78 NA mx \n# 3 /es/import-071320-to-sv-from-cr/summary 72 sv cr \n# 4 /en/import-340111-to-ru-from-ir/summary 58 ru ir \n# 5 /en/import-870423-to-hk-from-de/summary 57 hk de \n# 6 /es/import-392049-to-mx-from-de/summary 55 mx de \n# 7 /es/import-080440-to-mx-from-es/summary 48 mx es \n# 8 /es/import-340600-to-mx-from-jp/summary 46 mx jp \n# 9 /en/import-852691-to-tr-from-ua/summary 42 tr ua \n# 10 /es/import-180620-to-mx-from-us/summary 42 mx us \n df %>%\n mutate(as.data.frame(lapply(\n setNames(nm = c(\"to\", \"from\")),\n function(ptn) stringr::str_match(Page, sprintf(\".*-%s-([^/-]*)\", ptn))[,2])\n ))\n# # A tibble: 10 x 4\n# Page Count to from \n# <chr> <dbl> <chr> <chr>\n# 1 /es/import-340600-to-mx-from-de/summary 153 mx de \n# 2 /es/import-340600-TO-de-from-mx/summary 78 NA mx \n# 3 /es/import-071320-to-sv-from-cr/summary 72 sv cr \n# 4 /en/import-340111-to-ru-from-ir/summary 58 ru ir \n# 5 /en/import-870423-to-hk-from-de/summary 57 hk de \n# 6 /es/import-392049-to-mx-from-de/summary 55 mx de \n# 7 /es/import-080440-to-mx-from-es/summary 48 mx es \n# 8 /es/import-340600-to-mx-from-jp/summary 46 mx jp \n# 9 /en/import-852691-to-tr-from-ua/summary 42 tr ua \n# 10 /es/import-180620-to-mx-from-us/summary 42 mx us \n" }, { "answer_id": 74550354, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 2, "selected": false, "text": "library(dplyr)\n\ndf %>%\n mutate(from = sub(\"^.*from-(.*)/.*$\", \"\\\\1\", Page),\n to = sub(\"^.*to-(.*?)-.*$\", \"\\\\1\", Page)) %>%\n select(-Page)\n#> # A tibble: 10 x 3\n#> Count from to \n#> <dbl> <chr> <chr>\n#> 1 153 de mx \n#> 2 78 mx de \n#> 3 72 cr sv \n#> 4 58 ir ru \n#> 5 57 de hk \n#> 6 55 de mx \n#> 7 48 es mx \n#> 8 46 jp mx \n#> 9 42 ua tr \n#> 10 42 us mx\n" }, { "answer_id": 74550368, "author": "onyambu", "author_id": 8380272, "author_profile": "https://Stackoverflow.com/users/8380272", "pm_score": 2, "selected": false, "text": "df %>%\n mutate(To = str_extract(Page, \"(?<=to-)\\\\w+\"),\n From = str_extract(Page, \"(?<=from-)\\\\w+\"))\n\n# A tibble: 10 × 4\n Page Count To From \n <chr> <dbl> <chr> <chr>\n 1 /es/import-340600-to-mx-from-de/summary 153 mx de \n 2 /es/import-340600-to-de-from-mx/summary 78 de mx \n 3 /es/import-071320-to-sv-from-cr/summary 72 sv cr \n 4 /en/import-340111-to-ru-from-ir/summary 58 ru ir \n 5 /en/import-870423-to-hk-from-de/summary 57 hk de \n 6 /es/import-392049-to-mx-from-de/summary 55 mx de \n 7 /es/import-080440-to-mx-from-es/summary 48 mx es \n 8 /es/import-340600-to-mx-from-jp/summary 46 mx jp \n 9 /en/import-852691-to-tr-from-ua/summary 42 tr ua \n10 /es/import-180620-to-mx-from-us/summary 42 mx us \n df %>%\n extract(Page, c(\"to\",\"from\"), \"to-(\\\\w+)-from-(\\\\w+)\", remove = FALSE)\n\n# A tibble: 10 × 4\n Page to from Count\n <chr> <chr> <chr> <dbl>\n 1 /es/import-340600-to-mx-from-de/summary mx de 153\n 2 /es/import-340600-to-de-from-mx/summary de mx 78\n 3 /es/import-071320-to-sv-from-cr/summary sv cr 72\n 4 /en/import-340111-to-ru-from-ir/summary ru ir 58\n 5 /en/import-870423-to-hk-from-de/summary hk de 57\n 6 /es/import-392049-to-mx-from-de/summary mx de 55\n 7 /es/import-080440-to-mx-from-es/summary mx es 48\n 8 /es/import-340600-to-mx-from-jp/summary mx jp 46\n 9 /en/import-852691-to-tr-from-ua/summary tr ua 42\n10 /es/import-180620-to-mx-from-us/summary mx us 42\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20181941/" ]
74,550,257
<p>List object1</p> <p><code>[ { &quot;empId&quot;:10001, &quot;empName&quot;:&quot;test1&quot; }, { &quot;empId&quot;:10002, &quot;empName&quot;:&quot;test2&quot; } ]</code></p> <p>List object2</p> <p><code>[ { &quot;empId&quot;:10001, &quot;emailAddress&quot;:&quot;test1@mail.com&quot; }, { &quot;empId&quot;:10002, &quot;emailAddress&quot;:&quot;test2@mail.com&quot; } ]</code></p> <pre><code> Trying to get the merge result which matches &quot;empId&quot; in both objects. </code></pre> <p>Result</p> <pre><code>[ { &quot;empId&quot;:10001, &quot;empName&quot;:&quot;test1&quot;, &quot;emailAddress&quot;:&quot;test1@mail.com&quot; }, { &quot;empId&quot;:10002, &quot;empName&quot;:&quot;test2&quot;, &quot;emailAddress&quot;:&quot;test2@mail.com&quot; } ] </code></pre> <p>I have tried <a href="https://www.newtonsoft.com/json/help/html/MergeJson.htm" rel="nofollow noreferrer">https://www.newtonsoft.com/json/help/html/MergeJson.htm</a>. but not able to do the matching logic &quot;empId&quot;</p> <pre><code></code></pre>
[ { "answer_id": 74557637, "author": "Good Night Nerd Pride", "author_id": 1025555, "author_profile": "https://Stackoverflow.com/users/1025555", "pm_score": 1, "selected": false, "text": "Merge() Join() Merge() var xs = JArray\n .Parse(@\"[\n {\"\"empId\"\": 10001, \"\"empName\"\": \"\"test1\"\"},\n {\"\"empId\"\": 10002, \"\"empName\"\": \"\"test2\"\"}\n ]\")\n .Values<JObject>();\n\nvar ys = JArray\n .Parse(@\"[\n {\"\"empId\"\": 10001, \"\"emailAddress\"\": \"\"test1@mail.com\"\"},\n {\"\"empId\"\": 10002, \"\"emailAddress\"\": \"\"test2@mail.com\"\"}\n ]\")\n .Values<JObject>();\n\nvar merged = xs.Join(\n ys,\n x => x[\"empId\"],\n y => y[\"empId\"],\n (x, y) => { x.Merge(y); return x; });\n dynamic JObject" }, { "answer_id": 74558159, "author": "Jodrell", "author_id": 659190, "author_profile": "https://Stackoverflow.com/users/659190", "pm_score": 3, "selected": true, "text": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Dynamic;\nusing System.Linq;\n\nusing Newtonsoft.Json;\n \npublic class Program\n{\n public static void Main()\n {\n var list1 = new[]\n { \n new { empId = 10001, empName = \"test1\" },\n new { empId = 10002, empName = \"test2\" }\n };\n \n var list2 = new[]\n {\n new { empId = 10001, emailAddress = \"test1@mail.com\" },\n new { empId = 10002, emailAddress = \"test2@mail.com\" }\n };\n \n var results1 = list1.MergeJoin(list2, e => e.empId);\n \n Console.WriteLine($\"{nameof(results1)}:\");\n Console.WriteLine(JsonConvert.SerializeObject(results1, Formatting.Indented));\n Console.WriteLine();\n \n IList<dynamic> dynamicList1 = new List<dynamic>\n { \n new { empId = 10001, empName = \"test1\", utterance = \"wibble\" },\n new { empId = 10002, empName = \"test2\", expression = \"bemused\" }\n };\n \n IList<dynamic> dynamicList2 = new List<dynamic>\n {\n new { empId = 10001, emailAddress = \"test1@mail.com\", IQ = \"moron\" },\n new { empId = 10002, emailAddress = \"test2@mail.com\", smell = \"cheesy\" }\n };\n \n var results2 = dynamicList1.MergeJoin(dynamicList2, e => e.empId);\n \n Console.WriteLine($\"{nameof(results2)}:\");\n Console.WriteLine(JsonConvert.SerializeObject(results2, Formatting.Indented));\n }\n}\n\npublic static class Extensions\n{\n public static IEnumerable<dynamic> MergeJoin<TKey>(\n this IEnumerable<dynamic> outer,\n IEnumerable<dynamic> inner,\n Func<dynamic, TKey> keyAccessor)\n {\n return outer.Join(\n inner,\n keyAccessor,\n keyAccessor,\n Merge);\n }\n \n public static dynamic Merge(dynamic left, dynamic right)\n {\n IDictionary<string, object> dictionary1 = GetKeyValueMap(left);\n IDictionary<string, object> dictionary2 = GetKeyValueMap(right);\n\n var result = new ExpandoObject();\n\n var d = result as IDictionary<string, object>;\n foreach (var pair in dictionary1.Concat(dictionary2))\n {\n d[pair.Key] = pair.Value;\n }\n\n return result;\n }\n\n private static IDictionary<string, object> GetKeyValueMap(object values)\n {\n if (values == null)\n {\n return new Dictionary<string, object>();\n }\n\n var map = values as IDictionary<string, object>;\n if (map != null)\n {\n return map;\n }\n\n map = new Dictionary<string, object>();\n foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(values))\n {\n map.Add(descriptor.Name, descriptor.GetValue(values));\n }\n\n return map;\n }\n}\n results1:\n[\n {\n \"empId\": 10001,\n \"empName\": \"test1\",\n \"emailAddress\": \"test1@mail.com\"\n },\n {\n \"empId\": 10002,\n \"empName\": \"test2\",\n \"emailAddress\": \"test2@mail.com\"\n }\n]\n\nresults2:\n[\n {\n \"empId\": 10001,\n \"empName\": \"test1\",\n \"utterance\": \"wibble\",\n \"emailAddress\": \"test1@mail.com\",\n \"IQ\": \"moron\"\n },\n {\n \"empId\": 10002,\n \"empName\": \"test2\",\n \"expression\": \"bemused\",\n \"emailAddress\": \"test2@mail.com\",\n \"smell\": \"cheesy\"\n }\n]\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9730042/" ]
74,550,268
<p>I am trying to take two values as parameters and return True if its value is equal to 10 and false if it isn't. The values are strictly int. Here is the code</p> <pre><code> class Solution: def twomakes10(self, no1, no2): if sum(no1, no2) == 10: return True else: return False if __name__ == &quot;__main__&quot;: p = Solution() n1 = 9 n2 = 1 print(p.twomakes10(n1, n2)) </code></pre>
[ { "answer_id": 74550313, "author": "mohammad ali", "author_id": 9545762, "author_profile": "https://Stackoverflow.com/users/9545762", "pm_score": 1, "selected": false, "text": "sum sum([no1,no2])\n" }, { "answer_id": 74550329, "author": "balderman", "author_id": 415016, "author_profile": "https://Stackoverflow.com/users/415016", "pm_score": 0, "selected": false, "text": "sum iterable class Solution:\n\n def twomakes10(self, no1, no2):\n return sum([no1, no2])\n\n\nif __name__ == \"__main__\":\n p = Solution()\n n1 = 9\n n2 = 1\n print(p.twomakes10(n1, n2))\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20502753/" ]
74,550,276
<p>I am trying to implement a Filter Feature for my Match Lobbies, but the thing is as soon as I try to search any lobbies in the CustomTextField, my phone's on-screen keyboard shows up which makes my Bottom Overflow by 121 pixels.</p> <p>I am posting a screenshot of the Filter Feature before and after the overflow to have a clear idea.</p> <p><a href="https://i.stack.imgur.com/pDvkx.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pDvkx.jpg" alt="Lobby Filter UI" /></a></p> <p><a href="https://i.stack.imgur.com/Bu1gM.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Bu1gM.jpg" alt="Bottom Overflow after Keyboard Opens" /></a></p> <p><strong>Please ignore the Circular Logo Error in the photo, that is just the logo display error due to the path not provided.</strong></p> <p>Code:</p> <pre><code>Widget build(BuildContext context) { return Padding( padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom), child: BottomSheet( onClosing: () =&gt; {}, builder: (_) { return SizedBox( height: 595.h, child: Padding( padding: EdgeInsets.symmetric(horizontal: 15.w), child: Column( children: [ Align( alignment: Alignment.centerLeft, child: Container( padding: EdgeInsets.only( top: 34.h, left: 40.w, ), child: Text( 'Filter', style: Theme.of(context).textTheme.titleMedium?.copyWith( fontSize: 28.sp, fontWeight: FontWeight.w600, ), ), ), ), Container( decoration: BoxDecoration( color: const Color(0xFF2B2B3D), borderRadius: BorderRadius.circular( 10.r, ), ), child: CustomTextField( hintText: 'Host Username', controller: _controller, onChanged: (p0) =&gt; print(p0), ), ), SizedBox( height: 12.h, ), Container( height: 150.h, decoration: BoxDecoration( color: const Color(0xFF2B2B3D), borderRadius: BorderRadius.circular( 10.r, ), ), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Expanded( child: ListView( scrollDirection: Axis.horizontal, children: [ SizedBox( width: 200.w, child: RadioListTile&lt;String&gt;( activeColor: Colors.white, title: Text( &quot;By Team&quot;, style: Theme.of(context).textTheme.bodyMedium, ), value: &quot;team&quot;, groupValue: selectedMatchFilter, onChanged: (String? value) =&gt; setState(() { selectedMatchFilter = value; }), ), ), SizedBox( width: 200.w, child: RadioListTile&lt;String&gt;( activeColor: Colors.white, title: Text( &quot;By League&quot;, style: Theme.of(context).textTheme.bodyMedium, ), value: &quot;league&quot;, groupValue: selectedMatchFilter, onChanged: (String? value) =&gt; setState(() { selectedMatchFilter = value; }), ), ), ], ), ), SizedBox( height: 100.h, child: Row( children: [ Expanded( child: ListView.builder( itemCount: 10, scrollDirection: Axis.horizontal, itemBuilder: (context, index) =&gt; SizedBox( height: 100.h, width: 125.w, child: TeamLogo( id: 1, imgPath: &quot;Barcelona&quot;, teamName: &quot;Barcelona&quot;, selected: false, notifyParent: () {}, ), ), ), ), ], ), ), ], ), ), Container( padding: EdgeInsets.only(top: 5.h), child: const Text( &quot;Matchday&quot;, textAlign: TextAlign.center, ), ), Column( children: [ RadioListTile&lt;DateTime&gt;( activeColor: Colors.white, title: Text( &quot;Today&quot;, style: Theme.of(context).textTheme.bodyMedium, ), value: widget.today, groupValue: selectedMatchDateFilter, onChanged: (DateTime? value) =&gt; setState(() { selectedMatchDateFilter = value; }), ), RadioListTile&lt;DateTime&gt;( activeColor: Colors.white, title: Text( &quot;Tomorrow&quot;, style: Theme.of(context).textTheme.bodyMedium, ), value: DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day + 1), groupValue: selectedMatchDateFilter, onChanged: (DateTime? value) =&gt; setState(() { selectedMatchDateFilter = value; }), ), RadioListTile&lt;DateTime&gt;( activeColor: Colors.white, title: Row( children: [ DropdownButton2&lt;String&gt;( isExpanded: true, buttonHeight: 30.h, buttonWidth: 220.w, items: const [ DropdownMenuItem&lt;String&gt;( value: &quot;&quot;, child: Text(&quot;Till Date&quot;), ), DropdownMenuItem&lt;String&gt;( value: &quot;&quot;, child: Text(&quot;Precise Date&quot;), ), ], ), 1 == 2 ? Checkbox( value: true, onChanged: (bool? _value) {}, ) : IconButton( icon: const Icon(Icons.calendar_today), onPressed: () =&gt; showDatePicker( context: context, initialDate: DateTime.now(), firstDate: DateTime(2022, 11, 16), lastDate: DateTime(2023, 1, 1), ), ), ], ), value: DateTime.now(), groupValue: selectedMatchDateFilter, onChanged: (value) {}, ) ], ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const Text(&quot;Premium&quot;), Switch( onChanged: (bool? s) =&gt; setState(() { isPremiumFilter = s ?? false; }), value: isPremiumFilter, activeColor: const Color(0xFF182A54), inactiveThumbColor: Colors.white, activeTrackColor: const Color(0xFFD9D9D9), inactiveTrackColor: const Color(0xFFD9D9D9), ), ], ), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ TextButton( onPressed: () {}, child: const Text(&quot;Apply&quot;), ), TextButton( onPressed: () {}, child: const Text(&quot;Clear All&quot;), ), ], ), ], ), ), ); }, ), ); } </code></pre>
[ { "answer_id": 74550313, "author": "mohammad ali", "author_id": 9545762, "author_profile": "https://Stackoverflow.com/users/9545762", "pm_score": 1, "selected": false, "text": "sum sum([no1,no2])\n" }, { "answer_id": 74550329, "author": "balderman", "author_id": 415016, "author_profile": "https://Stackoverflow.com/users/415016", "pm_score": 0, "selected": false, "text": "sum iterable class Solution:\n\n def twomakes10(self, no1, no2):\n return sum([no1, no2])\n\n\nif __name__ == \"__main__\":\n p = Solution()\n n1 = 9\n n2 = 1\n print(p.twomakes10(n1, n2))\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14075086/" ]
74,550,291
<p>I have a column of names and informations of products, i need to remove the codes from the names and every code starts with four or more zeros, some names have four zeros or more in the weight and some are joined with the name as the example below:</p> <pre><code>data = { 'Name' : ['ANOA 250g 00004689', 'ANOA 10000g 00000059884', '80%c asjw 150000001568 ', 'Shivangi000000478761'], } testdf = pd.DataFrame(data) </code></pre> <p>The correct output would be:</p> <pre><code>results = { 'Name' : ['ANOA 250g', 'ANOA 10000g', '80%c asjw 150000001568 ', 'Shivangi'], } results = pd.DataFrame(results) </code></pre>
[ { "answer_id": 74550374, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "str.replace testdf['Name'] = testdf['Name'].str.replace(r'(?:(?<=\\D)|\\s*\\b)0{4}\\d*',\n '', regex=True)\n testdf['Name'] = testdf['Name'].str.replace(r'(?<!\\d)0{4,}0{4}\\d*',\n '', regex=True)\n Name\n0 ANOA 250g\n1 ANOA 10000g\n2 80%c asjw 150000001568 \n3 Shivangi\n" }, { "answer_id": 74550431, "author": "Haleemur Ali", "author_id": 2570261, "author_profile": "https://Stackoverflow.com/users/2570261", "pm_score": 2, "selected": false, "text": "(?<!\\d)0{4,} 0 str.strip testdf.Name.str.split('(?<!\\d)0{4,}', regex=True, expand=True)[0].str.strip()[0].str.strip()\n# outputs:\n0 ANOA 250g\n1 ANOA 10000g\n2 80%c asjw 150000001568\n3 Shivangi\n" }, { "answer_id": 74550693, "author": "Prime Price", "author_id": 19685980, "author_profile": "https://Stackoverflow.com/users/19685980", "pm_score": -1, "selected": false, "text": "answer=[]\nfor i in results[\"Name\"]:\n answer.append(\"\".join([j for j in i.split() if \"0000\" not in j]))\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19742465/" ]
74,550,305
<p>In the Symfony Panther <a href="https://symfony.com/blog/introducing-symfony-panther-a-browser-testing-and-web-scrapping-library-for-php" rel="nofollow noreferrer">docs</a> it states:</p> <blockquote> <p>Even if Chrome is the default choice, Panther can control any browser supporting the WebDriver protocol. It also supports remote browser testing services such as Selenium Grid (open source), SauceLabs and Browserstack.</p> </blockquote> <p>But, there are no other documentation on how to do this.</p> <p>How do you implement BrowserStack as a remote browser for Panther?</p>
[ { "answer_id": 74550374, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "str.replace testdf['Name'] = testdf['Name'].str.replace(r'(?:(?<=\\D)|\\s*\\b)0{4}\\d*',\n '', regex=True)\n testdf['Name'] = testdf['Name'].str.replace(r'(?<!\\d)0{4,}0{4}\\d*',\n '', regex=True)\n Name\n0 ANOA 250g\n1 ANOA 10000g\n2 80%c asjw 150000001568 \n3 Shivangi\n" }, { "answer_id": 74550431, "author": "Haleemur Ali", "author_id": 2570261, "author_profile": "https://Stackoverflow.com/users/2570261", "pm_score": 2, "selected": false, "text": "(?<!\\d)0{4,} 0 str.strip testdf.Name.str.split('(?<!\\d)0{4,}', regex=True, expand=True)[0].str.strip()[0].str.strip()\n# outputs:\n0 ANOA 250g\n1 ANOA 10000g\n2 80%c asjw 150000001568\n3 Shivangi\n" }, { "answer_id": 74550693, "author": "Prime Price", "author_id": 19685980, "author_profile": "https://Stackoverflow.com/users/19685980", "pm_score": -1, "selected": false, "text": "answer=[]\nfor i in results[\"Name\"]:\n answer.append(\"\".join([j for j in i.split() if \"0000\" not in j]))\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3167915/" ]
74,550,325
<p>I have a string list of texts, when I click one of them I should color it in one color, currently my implementation colors all of the texts, what I'm doing wrong ?</p> <pre><code>var isPressed by remember { mutableStateOf(false) } val buttonColor: Color by animateColorAsState( targetValue = when (isPressed) { true -&gt; FreshGreen false -&gt; PastelPeach }, animationSpec = tween() ) LazyRow( modifier = modifier, horizontalArrangement = Arrangement.spacedBy(25.dp) ) { items(filterList) { filterName -&gt; Text( text = filterName, modifier = Modifier .background(shape = RoundedCornerShape(24.dp), color = buttonColor) .padding(horizontal = 16.dp, vertical = 8.dp) .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null ) { isPressed = !isPressed onFilterClick(filterName) } ) } } </code></pre>
[ { "answer_id": 74550563, "author": "z.y", "author_id": 19023745, "author_profile": "https://Stackoverflow.com/users/19023745", "pm_score": 3, "selected": true, "text": "re-composition @Composable\nfun MyScreen(\n modifier: Modifier = Modifier,\n filterList: SnapshotStateList<String>\n) {\n LazyRow(\n modifier = modifier,\n horizontalArrangement = Arrangement.spacedBy(25.dp)\n ) {\n\n items(filterList) { filterName ->\n FilterText(\n filterName\n )\n }\n }\n}\n\n@Composable\nfun FilterText(\n filter: String\n) {\n\n var isPressed by remember { mutableStateOf(false) }\n val buttonColor: Color by animateColorAsState(\n targetValue = when (isPressed) {\n true -> Color.Blue\n false -> Color.Green\n },\n animationSpec = tween()\n )\n\n Text(\n text = filter,\n modifier = Modifier\n .background(shape = RoundedCornerShape(24.dp), color = buttonColor)\n .padding(horizontal = 16.dp, vertical = 8.dp)\n .clickable {\n isPressed = !isPressed\n }\n )\n}\n" }, { "answer_id": 74550638, "author": "Gabriele Mariotti", "author_id": 2016562, "author_profile": "https://Stackoverflow.com/users/2016562", "pm_score": 2, "selected": false, "text": "isPressed isPressed items LazyRow(\n horizontalArrangement = Arrangement.spacedBy(25.dp)\n) {\n items(itemsList) { filterName->\n\n var isPressed by remember { mutableStateOf(false) }\n\n val buttonColor: Color by animateColorAsState(\n targetValue = when (isPressed) {\n true -> Color.Green\n false -> Color.Red\n },\n animationSpec = tween()\n )\n \n Text(\n //your code\n )\n }\n}\n" }, { "answer_id": 74550803, "author": "SNM", "author_id": 10870164, "author_profile": "https://Stackoverflow.com/users/10870164", "pm_score": 2, "selected": false, "text": "@Composable\nfun BrandCategoryFilterSection(\n modifier: Modifier,\n uiState: BrandFilterUiState,\n onBrandCategoryClick: (String) -> Unit\n) {\n var selectedIndex by remember { mutableStateOf(-1) }\n\n LazyRow(\n modifier = modifier,\n horizontalArrangement = Arrangement.spacedBy(25.dp)\n ) {\n itemsIndexed(uiState.categoryList) { index, categoryName ->\n CategoryText(\n categoryName = categoryName,\n isSelected = index == selectedIndex,\n onBrandCategoryClick = {\n selectedIndex = index\n onBrandCategoryClick(it)\n }\n )\n }\n }\n}\n\n@Composable\nprivate fun CategoryText(categoryName: String, onBrandCategoryClick: (String) -> Unit, isSelected: Boolean) {\n \n val buttonColor: Color by animateColorAsState(\n targetValue = when (isSelected) {\n true -> FreshGreen\n false -> PastelPeach\n },\n animationSpec = tween()\n )\n\n Text(\n text = categoryName,\n modifier = Modifier\n .background(shape = RoundedCornerShape(24.dp), color = buttonColor)\n .padding(horizontal = 16.dp, vertical = 8.dp)\n .clickable(\n interactionSource = remember { MutableInteractionSource() },\n indication = null\n ) {\n onBrandCategoryClick(categoryName)\n }\n )\n}\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10870164/" ]
74,550,345
<p>My secret manager is created with credential of RDS in CDK, with <strong>DatabaseCluster</strong> and credential param in it. Now i want to update some value in that secretmanager.</p> <p>How can i update secret value of secret manager in CDK?</p>
[ { "answer_id": 74635993, "author": "Bang", "author_id": 17232039, "author_profile": "https://Stackoverflow.com/users/17232039", "pm_score": 0, "selected": false, "text": "aws secretsmanager put-secret-value --secret-id your_secret_arn --secret-string your_secret\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12710436/" ]
74,550,378
<p>The following code prints: <code>-1 day, 19:00:00</code> when New York is actually 5 hours behind UTC. What is wrong and how to fix it?</p> <pre class="lang-py prettyprint-override"><code>import pytz from datetime import datetime date = datetime(2022, 11, 23, 22, 30) tz = pytz.timezone('America/New_York') print(tz.utcoffset(date)) </code></pre>
[ { "answer_id": 74635993, "author": "Bang", "author_id": 17232039, "author_profile": "https://Stackoverflow.com/users/17232039", "pm_score": 0, "selected": false, "text": "aws secretsmanager put-secret-value --secret-id your_secret_arn --secret-string your_secret\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9162463/" ]
74,550,389
<p>I created a simple application for testing, I am getting - &quot;No provider for ChildrenOutletContexts!&quot; error, i have checked different posts related to the same but of no help.</p> <p>My Structure is App Module has App Routing Module and from which i am doing lazy loading to Routing example module (which again has routing module).</p> <p>App Routing Module</p> <pre><code>const parentRoutes: Route[] = [ { path: 'test', loadChildren: () =&gt; import('./routing-example/routingexample.module').then( (x) =&gt; x.RoutingExampleModule ), }, ]; @NgModule({ imports: [RouterModule.forRoot(parentRoutes)], exports: [RouterModule], }) export class AppRoutingModule { } </code></pre> <p>App Module File</p> <pre><code>import { AppRoutingModule } from './app-routing.module'; @NgModule({ declarations: [ AppComponent, ], imports: [ BrowserModule, FormsModule, AppRoutingModule, ReactiveFormsModule, HttpClientModule, ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } </code></pre> <p>Routing Example Routing Module</p> <pre><code>import { Component1 } from &quot;./component1/component1.component&quot;; import { Component2 } from &quot;./component2/component2.component&quot;; import { RoutingExampleComponent } from &quot;./routingexample.component&quot;; export const compRoutes: Route[] = [ { path: '', component: RoutingExampleComponent, children: [ { path: 'comp1', component: Component1, pathMatch: 'full', }, { path: 'comp2', component: Component2, pathMatch: 'full', }, { path: '', redirectTo: 'comp1', pathMatch: 'full', }, ], }, ]; @NgModule({ imports: [RouterModule.forChild(compRoutes)], exports: [RouterModule], }) export class RoutingExampleRoutingModule { } </code></pre> <p>Routing example Module -</p> <pre><code>import { RoutingExampleComponent } from &quot;./routingexample.component&quot;; @NgModule({ imports: [ RoutingExampleRoutingModule ], declarations: [ RoutingExampleComponent, Component1, Component2 ], }) export class RoutingExampleModule { } </code></pre> <p>My Application html has only -</p> <pre><code>&lt;router-outlet&gt;&lt;/router-outlet&gt; </code></pre> <p>I know because of this only issue coming but dont know the exact issue though,</p> <p>Any help would be highly appreciated.</p>
[ { "answer_id": 74635993, "author": "Bang", "author_id": 17232039, "author_profile": "https://Stackoverflow.com/users/17232039", "pm_score": 0, "selected": false, "text": "aws secretsmanager put-secret-value --secret-id your_secret_arn --secret-string your_secret\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/966580/" ]
74,550,429
<p>I'm trying to make them closer like the picture that is attached. How can I change that property?</p> <p>Expected output:</p> <p><img src="https://i.stack.imgur.com/IATOA.jpg" alt="Expected output" /></p> <p>I need them to be more close with one another and to make them in the center of the page but I find it hard to do. I've tried the column-gap but its not working. please help this is my first time.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous"&gt; &lt;div class="row"&gt; &lt;div class="col"&gt; &lt;div class="card" style="width: 16.5rem"&gt; &lt;img src="https://via.placeholder.com/300x100" class="card-img-top" alt="..." /&gt; &lt;div class="card-body"&gt; &lt;center&gt; &lt;h5 class="card-title"&gt;Card title&lt;/h5&gt; &lt;p class="card-text"&gt; Some quick example text to build on the card title and make up the bulk of the card's content. &lt;/p&gt; &lt;a href="#" class="btn btn-primary"&gt;Go somewhere&lt;/a&gt; &lt;/center&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col"&gt; &lt;div class="card" style="width: 16.5rem"&gt; &lt;div class="card-body"&gt; &lt;center&gt; &lt;h5 class="card-title"&gt;Card title&lt;/h5&gt; &lt;h6 class="card-subtitle mb-2 text-muted"&gt;Card subtitle&lt;/h6&gt; &lt;p class="card-text"&gt; Some quick example text to build on the card title and make up the bulk of the card's content. &lt;/p&gt; &lt;a href="#" class="card-link"&gt;Card link&lt;/a&gt; &lt;a href="#" class="card-link"&gt;Another link&lt;/a&gt; &lt;/center&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col"&gt; &lt;div class="card" style="width: 16.5rem"&gt; &lt;div class="card-body"&gt; &lt;center&gt; &lt;h5 class="card-title"&gt;Card title&lt;/h5&gt; &lt;h6 class="card-subtitle mb-2 text-muted"&gt;Card subtitle&lt;/h6&gt; &lt;p class="card-text"&gt; Some quick example text to build on the card title and make up the bulk of the card's content. &lt;/p&gt; &lt;a href="#" class="card-link"&gt;Card link&lt;/a&gt; &lt;a href="#" class="card-link"&gt;Another link&lt;/a&gt; &lt;/center&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col"&gt; &lt;div class="card" style="width: 16.5rem"&gt; &lt;div class="card-body"&gt; &lt;center&gt; &lt;h5 class="card-title"&gt;Card title&lt;/h5&gt; &lt;h6 class="card-subtitle mb-2 text-muted"&gt;Card subtitle&lt;/h6&gt; &lt;p class="card-text"&gt; Some quick example text to build on the card title and make up the bulk of the card's content. &lt;/p&gt; &lt;a href="#" class="card-link"&gt;Card link&lt;/a&gt; &lt;a href="#" class="card-link"&gt;Another link&lt;/a&gt; &lt;/center&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74550524, "author": "Crystal", "author_id": 16255006, "author_profile": "https://Stackoverflow.com/users/16255006", "pm_score": -1, "selected": false, "text": "<div class=\"card\" style=\"width: 16.5rem; margin-left: 20px;>\n" }, { "answer_id": 74550692, "author": "isherwood", "author_id": 1264804, "author_profile": "https://Stackoverflow.com/users/1264804", "pm_score": 0, "selected": false, "text": ".col.mw-16_5 {\n max-width: 16.5rem;\n} <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css\" integrity=\"sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi\" crossorigin=\"anonymous\">\n\n<div class=\"container\">\n <div class=\"row justify-content-center\">\n <div class=\"col mw-16_5\">\n <div class=\"card\">\n <img src=\"https://via.placeholder.com/300x100\" class=\"card-img-top\" alt=\"...\" />\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"btn btn-primary\">Go somewhere</a>\n </div>\n </div>\n </div>\n\n <div class=\"col mw-16_5\">\n <div class=\"card\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n </div>\n\n <div class=\"col mw-16_5\">\n <div class=\"card\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n </div>\n\n <div class=\"col mw-16_5\">\n <div class=\"card\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n </div>\n </div>\n</div> .card.minw-10 {\n min-width: 10rem;\n}\n\n.card.maxw-16_5 {\n max-width: 16.5rem;\n} <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css\" integrity=\"sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi\" crossorigin=\"anonymous\">\n\n<div class=\"d-flex flex-wrap justify-content-center\">\n <div class=\"card m-2 minw-10 maxw-16_5\">\n <img src=\"https://via.placeholder.com/300x100\" class=\"card-img-top\" alt=\"...\" />\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"btn btn-primary\">Go somewhere</a>\n </div>\n </div>\n\n <div class=\"card m-2 minw-10 maxw-16_5\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n\n <div class=\"card m-2 minw-10 maxw-16_5\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n\n <div class=\"card m-2 minw-10 maxw-16_5\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n\n <div class=\"card m-2 minw-10 maxw-16_5\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n\n <div class=\"card m-2 minw-10 maxw-16_5\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n</div>" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20583258/" ]
74,550,481
<p>Hello i want to compare dates in laravel please tell me this code is right. I want to check it before login.</p> <ol> <li>When user is registered, user must be deactivated</li> <li>Admin must activate the user: end_date=activated_date +90 days</li> <li>Admin Deactivation : end_date=deactivated_date;</li> <li>if current_date=deactivate_date</li> </ol> <pre><code>if ($user-&gt;activated_at -&gt;gte(now()-&gt;subDays(90))) { return $this-&gt;sendError('messages.user_subscription', [], 400); } </code></pre>
[ { "answer_id": 74550524, "author": "Crystal", "author_id": 16255006, "author_profile": "https://Stackoverflow.com/users/16255006", "pm_score": -1, "selected": false, "text": "<div class=\"card\" style=\"width: 16.5rem; margin-left: 20px;>\n" }, { "answer_id": 74550692, "author": "isherwood", "author_id": 1264804, "author_profile": "https://Stackoverflow.com/users/1264804", "pm_score": 0, "selected": false, "text": ".col.mw-16_5 {\n max-width: 16.5rem;\n} <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css\" integrity=\"sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi\" crossorigin=\"anonymous\">\n\n<div class=\"container\">\n <div class=\"row justify-content-center\">\n <div class=\"col mw-16_5\">\n <div class=\"card\">\n <img src=\"https://via.placeholder.com/300x100\" class=\"card-img-top\" alt=\"...\" />\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"btn btn-primary\">Go somewhere</a>\n </div>\n </div>\n </div>\n\n <div class=\"col mw-16_5\">\n <div class=\"card\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n </div>\n\n <div class=\"col mw-16_5\">\n <div class=\"card\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n </div>\n\n <div class=\"col mw-16_5\">\n <div class=\"card\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n </div>\n </div>\n</div> .card.minw-10 {\n min-width: 10rem;\n}\n\n.card.maxw-16_5 {\n max-width: 16.5rem;\n} <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css\" integrity=\"sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi\" crossorigin=\"anonymous\">\n\n<div class=\"d-flex flex-wrap justify-content-center\">\n <div class=\"card m-2 minw-10 maxw-16_5\">\n <img src=\"https://via.placeholder.com/300x100\" class=\"card-img-top\" alt=\"...\" />\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"btn btn-primary\">Go somewhere</a>\n </div>\n </div>\n\n <div class=\"card m-2 minw-10 maxw-16_5\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n\n <div class=\"card m-2 minw-10 maxw-16_5\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n\n <div class=\"card m-2 minw-10 maxw-16_5\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n\n <div class=\"card m-2 minw-10 maxw-16_5\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n\n <div class=\"card m-2 minw-10 maxw-16_5\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n</div>" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1808731/" ]
74,550,523
<p>I have a dataframe that its format looks like this. I want to clean the df leaving a certain range of rows that starts when column 1 says &quot;country&quot; and ends two rows before it says &quot;end&quot; in column 1. I need it that way because later I have to bind the df with others dfs of the same type of sheet but from other periods, so the range differs between sheets.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Column A</th> <th>Column B</th> <th>Column C</th> </tr> </thead> <tbody> <tr> <td>-</td> <td>-</td> <td>-</td> </tr> <tr> <td>country</td> <td>number</td> <td>year</td> </tr> <tr> <td>china</td> <td>1</td> <td>2018</td> </tr> <tr> <td>japan</td> <td>2</td> <td>2019</td> </tr> <tr> <td>usa</td> <td>3</td> <td>2019</td> </tr> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td>end</td> <td></td> <td></td> </tr> </tbody> </table> </div><div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>country</th> <th>number</th> <th>year</th> </tr> </thead> <tbody> <tr> <td>china</td> <td>1</td> <td>2018</td> </tr> <tr> <td>japan</td> <td>2</td> <td>2019</td> </tr> <tr> <td>usa</td> <td>3</td> <td>2019</td> </tr> </tbody> </table> </div> <p>I want it to look like this but it hasn't worked with the code I've been trying to use:</p> <pre><code> start_position &lt;- which(df[,1]==&quot;country&quot;) end_position &lt;- which(df[,1]==&quot;end&quot;) df&lt;- df[df(start_position:(end_position-2)),] </code></pre> <p>Any help or recommendations pleasee</p>
[ { "answer_id": 74550524, "author": "Crystal", "author_id": 16255006, "author_profile": "https://Stackoverflow.com/users/16255006", "pm_score": -1, "selected": false, "text": "<div class=\"card\" style=\"width: 16.5rem; margin-left: 20px;>\n" }, { "answer_id": 74550692, "author": "isherwood", "author_id": 1264804, "author_profile": "https://Stackoverflow.com/users/1264804", "pm_score": 0, "selected": false, "text": ".col.mw-16_5 {\n max-width: 16.5rem;\n} <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css\" integrity=\"sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi\" crossorigin=\"anonymous\">\n\n<div class=\"container\">\n <div class=\"row justify-content-center\">\n <div class=\"col mw-16_5\">\n <div class=\"card\">\n <img src=\"https://via.placeholder.com/300x100\" class=\"card-img-top\" alt=\"...\" />\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"btn btn-primary\">Go somewhere</a>\n </div>\n </div>\n </div>\n\n <div class=\"col mw-16_5\">\n <div class=\"card\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n </div>\n\n <div class=\"col mw-16_5\">\n <div class=\"card\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n </div>\n\n <div class=\"col mw-16_5\">\n <div class=\"card\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n </div>\n </div>\n</div> .card.minw-10 {\n min-width: 10rem;\n}\n\n.card.maxw-16_5 {\n max-width: 16.5rem;\n} <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css\" integrity=\"sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi\" crossorigin=\"anonymous\">\n\n<div class=\"d-flex flex-wrap justify-content-center\">\n <div class=\"card m-2 minw-10 maxw-16_5\">\n <img src=\"https://via.placeholder.com/300x100\" class=\"card-img-top\" alt=\"...\" />\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"btn btn-primary\">Go somewhere</a>\n </div>\n </div>\n\n <div class=\"card m-2 minw-10 maxw-16_5\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n\n <div class=\"card m-2 minw-10 maxw-16_5\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n\n <div class=\"card m-2 minw-10 maxw-16_5\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n\n <div class=\"card m-2 minw-10 maxw-16_5\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n\n <div class=\"card m-2 minw-10 maxw-16_5\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n</div>" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20583841/" ]
74,550,582
<p>Im using coroutine to make a little break that's reloading the bullet. I don’t know why this doesn’t work, which is to say, there is no time waiting. I’m probably not using the coroutine correctly. Can somebody help me?</p> <pre><code>if (Input.GetMouseButton(0) &amp;&amp; Time.time &gt; nextFire &amp;&amp; !inventoryInterface.activeSelf) { //aimAnimator.SetTrigger(&quot;Shoot&quot;); nextFire = Time.time + fireRate; if (count &lt; gun.bulletsInAMagazine) { Vector3 mousePosition = UtilsClass.GetMouseWorldPosition(); OnShoot?.Invoke(this, new OnShootEventArgs { gunEndPointPosition = aimGunEndPointPosition.position, shootPosition = mousePosition }); count++; } else { count = 0; StartCoroutine(FireCooldown()); Debug.Log(&quot;Reloading&quot;); } //StartCoroutine(FireCooldown()); //allowFire = true; } </code></pre> <p>And the enumerator:</p> <pre class="lang-cs prettyprint-override"><code>IEnumerator FireCooldown() { yield return new WaitForSeconds(gun.reloadTime); } </code></pre>
[ { "answer_id": 74550524, "author": "Crystal", "author_id": 16255006, "author_profile": "https://Stackoverflow.com/users/16255006", "pm_score": -1, "selected": false, "text": "<div class=\"card\" style=\"width: 16.5rem; margin-left: 20px;>\n" }, { "answer_id": 74550692, "author": "isherwood", "author_id": 1264804, "author_profile": "https://Stackoverflow.com/users/1264804", "pm_score": 0, "selected": false, "text": ".col.mw-16_5 {\n max-width: 16.5rem;\n} <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css\" integrity=\"sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi\" crossorigin=\"anonymous\">\n\n<div class=\"container\">\n <div class=\"row justify-content-center\">\n <div class=\"col mw-16_5\">\n <div class=\"card\">\n <img src=\"https://via.placeholder.com/300x100\" class=\"card-img-top\" alt=\"...\" />\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"btn btn-primary\">Go somewhere</a>\n </div>\n </div>\n </div>\n\n <div class=\"col mw-16_5\">\n <div class=\"card\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n </div>\n\n <div class=\"col mw-16_5\">\n <div class=\"card\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n </div>\n\n <div class=\"col mw-16_5\">\n <div class=\"card\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n </div>\n </div>\n</div> .card.minw-10 {\n min-width: 10rem;\n}\n\n.card.maxw-16_5 {\n max-width: 16.5rem;\n} <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css\" integrity=\"sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi\" crossorigin=\"anonymous\">\n\n<div class=\"d-flex flex-wrap justify-content-center\">\n <div class=\"card m-2 minw-10 maxw-16_5\">\n <img src=\"https://via.placeholder.com/300x100\" class=\"card-img-top\" alt=\"...\" />\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"btn btn-primary\">Go somewhere</a>\n </div>\n </div>\n\n <div class=\"card m-2 minw-10 maxw-16_5\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n\n <div class=\"card m-2 minw-10 maxw-16_5\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n\n <div class=\"card m-2 minw-10 maxw-16_5\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n\n <div class=\"card m-2 minw-10 maxw-16_5\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n\n <div class=\"card m-2 minw-10 maxw-16_5\">\n <div class=\"card-body text-center\">\n <h5 class=\"card-title\">Card title</h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Card subtitle</h6>\n <p class=\"card-text\">\n Some quick example text to build on the card title and make up the bulk of the card's content.\n </p>\n <a href=\"#\" class=\"card-link\">Card link</a>\n <a href=\"#\" class=\"card-link\">Another link</a>\n </div>\n </div>\n</div>" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19359902/" ]
74,550,585
<p>I am trying to retrieve the string &quot;This is my string&quot; that belongs to <code>text id=&quot;short_name</code></p> <p>I have tried:</p> <pre><code>$SVGTemplate = Get-Content &quot;C:\temp\sample.svg $SVGTemplate = [XML]$SVGTemplate $SVGTemplateShortName = Select-Xml -Xml $SVGTemplate -XPath '/s:svg/s:g/s:g[@id=&quot;short_name&quot;]/s:text/text()' -Namespace @{s = &quot;http://www.w3.org/2000/svg&quot;} $SVGTemplateShortName.node.value </code></pre> <p>But it returns an empty value. This used to work before and recently broke because I had to redesign the svg graphic.</p> <p>I have tried to correct the XPath many times and it keeps returning an empty value. What could I be doing wrong? Below is my xml file.</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;!-- Generator: Adobe Illustrator 26.5.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) --&gt; &lt;svg version=&quot;1.1&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot; xmlns:xlink=&quot;http://www.w3.org/1999/xlink&quot; x=&quot;0px&quot; y=&quot;0px&quot; viewBox=&quot;0 0 500 500&quot; style=&quot;enable-background:new 0 0 500 500;&quot; xml:space=&quot;preserve&quot;&gt; &lt;style type=&quot;text/css&quot;&gt; .st0{fill:#E30613;} .st1{fill:#FFFFFF;} .st2{fill:#009FE3;} .st3{fill:none;} .st4{font-family:'MyriadPro-Regular';} .st5{font-size:88px;} .st6{fill:#008D36;} &lt;/style&gt; &lt;g id=&quot;background&quot;&gt; &lt;rect id=&quot;stroke&quot; class=&quot;st0&quot; width=&quot;500&quot; height=&quot;500&quot;/&gt; &lt;rect id=&quot;Fill&quot; x=&quot;12&quot; y=&quot;12&quot; class=&quot;st1&quot; width=&quot;476&quot; height=&quot;476&quot;/&gt; &lt;/g&gt; &lt;g id=&quot;short&quot;&gt; &lt;rect id=&quot;short_fill&quot; x=&quot;12&quot; y=&quot;400&quot; class=&quot;st2&quot; width=&quot;476&quot; height=&quot;100&quot;/&gt; &lt;rect y=&quot;412&quot; class=&quot;st3&quot; width=&quot;500&quot; height=&quot;88&quot;/&gt; &lt;text id=&quot;short_name&quot; transform=&quot;matrix(1 0 0 1 87.7305 474.4795)&quot; class=&quot;st1 st4 st5&quot;&gt;This is my string&lt;/text&gt; &lt;/g&gt; &lt;g id=&quot;hud&quot;&gt; &lt;rect id=&quot;left&quot; x=&quot;12&quot; y=&quot;12&quot; class=&quot;st6&quot; width=&quot;92&quot; height=&quot;76&quot;/&gt; &lt;rect id=&quot;right&quot; x=&quot;396&quot; y=&quot;12&quot; width=&quot;92&quot; height=&quot;76&quot;/&gt; &lt;/g&gt; &lt;g id=&quot;graphic&quot;&gt; &lt;g id=&quot;Card_Symbl&quot;&gt; &lt;g id=&quot;Layer_10&quot;&gt; &lt;polygon class=&quot;st0&quot; points=&quot;309.9,387.1 396.3,124.5 303.1,105.8 96.5,251.1 &quot;/&gt; &lt;/g&gt; &lt;/g&gt; &lt;/g&gt; &lt;/svg&gt; </code></pre> <pre><code> </code></pre>
[ { "answer_id": 74551088, "author": "zett42", "author_id": 7571258, "author_profile": "https://Stackoverflow.com/users/7571258", "pm_score": 2, "selected": false, "text": "$SVGTemplate.svg.g.text | Where-Object id -eq 'short_name' | ForEach-Object '#text'\n .Where $SVGTemplate.svg.g.text.Where{ $_.id -eq 'short_name'}.'#text'\n $SVGTemplate | \n Select-Xml -XPath '//s:text[@id=\"short_name\"]' -Namespace @{s = \"http://www.w3.org/2000/svg\"} | \n ForEach-Object { $_.Node.'#text' }\n $SVGTemplate | \n Select-Xml -XPath '/s:svg/s:g/s:text[@id=\"short_name\"]' -Namespace @{s = \"http://www.w3.org/2000/svg\"} | \n ForEach-Object { $_.Node.'#text' }\n" }, { "answer_id": 74552887, "author": "Ralph Sch", "author_id": 20551048, "author_profile": "https://Stackoverflow.com/users/20551048", "pm_score": 0, "selected": false, "text": "<g> $xmlDoc.tagA.tagB.tagC" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19859069/" ]
74,550,590
<p>I have an array with a set of strings and I am trying to search for these strings in another column of type string. Basically a LIKE operator kind, but with arrays.</p> <p>What I have:</p> <pre><code>I have two tables keyword_table and config_table. </code></pre> <p>Table1: &quot;keyword_table&quot;</p> <pre><code>category(STRING) keywords(ARRAY) fruits [&quot;orange&quot;, &quot;berry&quot;, &quot;apple&quot;] vegetables [&quot;bean&quot;, &quot;carrot&quot;, &quot;onion&quot;] </code></pre> <p>Table2: &quot;config_table&quot;</p> <pre><code>code(STRING) item(STRING) 001 blueberry 002 raspberry 003 white onions 004 red onions 005 onion 006 small beans 007 big beans </code></pre> <p>Expected Output:</p> <pre><code>code(STRING) category(STRING) 001 fruits 002 fruits 003 vegetables 004 vegetables 005 vegetables 006 vegetables 007 vegetables </code></pre> <p>Could someone please help me solve this.</p>
[ { "answer_id": 74551392, "author": "Mazlum Tosun", "author_id": 9261558, "author_profile": "https://Stackoverflow.com/users/9261558", "pm_score": -1, "selected": false, "text": "sql with keyword_table AS (\n select \n \"fruits\" AS category,\n [\"orange\", \"berry\", \"apple\"] AS keywords\n UNION ALL\n select \n \"vegetables\" AS category,\n [\"bean\", \"carrot\", \"onion\"] AS keywords\n),\n\nconfig_table AS (\n select \"001\" AS code, \"orange\" AS item\n UNION ALL\n select \"002\" AS code, \"raspberry\" AS item\n UNION ALL\n select \"003\" AS code, \"carrot\" AS item\n UNION ALL\n select \"004\" AS code, \"red onions\" AS item\n UNION ALL\n select \"005\" AS code, \"onion\" AS item\n UNION ALL\n select \"006\" AS code, \"small beans\" AS item\n UNION ALL\n select \"007\" AS code, \"big beans\" AS item\n)\n\nselect\n code,\n calculatedCategory as category\nfrom\n(\n select \n code,\n item,\n category,\n keywords,\n CASE WHEN item = keyword then category \n ELSE ''\n END AS calculatedCategory,\n from config_table \n cross join keyword_table,\n UNNEST(keywords) AS keyword\n)\nwhere calculatedCategory <> '';\n" }, { "answer_id": 74553757, "author": "Jaytiger", "author_id": 19039920, "author_profile": "https://Stackoverflow.com/users/19039920", "pm_score": 2, "selected": true, "text": "SELECT code, category \n FROM config_table, keyword_table\n WHERE REGEXP_CONTAINS(item, ARRAY_TO_STRING(keywords, '|'));\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13037582/" ]
74,550,635
<p>I have one column of names of children who have teamed up in class together over multiple projects / activities, like so:</p> <p>Note: This is ONE column.</p> <pre><code>Names Tom,Jack,Meave Tom,Arial Arial,Tim,Tom Neena,Meave Meave Tim,Meave </code></pre> <p>I want to use R so that I can see how many times two children have been paired over the projects they have done:</p> <p>So:</p> <pre><code>Pair Counts Meave,Jack 1 Tom,Jack 1 Meave,none 1 Tom,Arial 2 . . . </code></pre> <p>How do I go about doing this? A <code>tidy</code>-friendly solution would be appreciated.</p> <p>(Ultimately, I would like to use this data to make a circle-network graph, but that is for another question.)</p>
[ { "answer_id": 74550955, "author": "Andrew Gustar", "author_id": 7727429, "author_profile": "https://Stackoverflow.com/users/7727429", "pm_score": 0, "selected": false, "text": "df Names\n <chr>\n Tom,Jack,Meave\n Tom,Arial\n Arial,Tim,Tom\n Neena,Meave\n Meave\n Tim,Meave\n df2 <- df %>% \n mutate(ref = row_number(),\n Names = ifelse(str_count(Names, \",\") == 0, #add nobody if only one\n paste0(Names, \",nobody\"), \n Names),\n Names = str_split(Names, \",\")) %>% \n unnest(Names) %>% \n nest(data = ref) %>% #creates a list of refs for each name\n mutate(Names2 = list(Names)) %>% #add a column of second names for the pairs\n unnest(Names2) %>% \n filter(Names != Names2) %>% #remove self-pairs \n left_join({.} %>% select(Names2 = Names, data2 = data) %>% \n distinct()) %>% #create data for second column of names\n mutate(paired = map2_dbl(data, data2, ~length(intersect(.x$ref, .y$ref)))) %>% \n select(-data, -data2) %>% \n filter(paired > 0, #remove non-occurring combinations\n Names > Names2) #remove duplicates\n > df2\n# A tibble: 18 × 3\n Names Names2 paired\n <chr> <chr> <dbl>\n1 Tom Jack 1\n2 Tom Meave 1\n3 Tom Arial 2\n4 Tom Tim 1\n5 Meave Jack 1\n6 Tim Meave 1\n7 Tim Arial 1\n8 Neena Meave 1\n9 nobody Meave 1\n ref refs refs {.} left_join" }, { "answer_id": 74551166, "author": "onyambu", "author_id": 8380272, "author_profile": "https://Stackoverflow.com/users/8380272", "pm_score": 1, "selected": false, "text": "a <- tcrossprod(table(stack(setNames(strsplit(df$Names,\",\"), rownames(df)))))\na\n\n values\nvalues Arial Jack Meave Neena Tim Tom\n Arial 2 0 0 0 1 2\n Jack 0 1 1 0 0 1\n Meave 0 1 4 1 1 1\n Neena 0 0 1 1 0 0\n Tim 1 0 1 0 2 1\n Tom 2 1 1 0 1 3 \n subset(as.data.frame.table(a), \n as.character(values) > as.character(values.1) & Freq>0)\n values values.1 Freq\n5 Tim Arial 1\n6 Tom Arial 2\n9 Meave Jack 1\n12 Tom Jack 1\n16 Neena Meave 1\n17 Tim Meave 1\n18 Tom Meave 1\n30 Tom Tim 1\n df %>%\n rownames_to_column()%>%\n separate_rows(Names)%>%\n table()%>%\n crossprod()%>%\n as.data.frame.table()%>%\n filter(Freq>0 & as.character(Names) > as.character(Names.1))\n\n Names Names.1 Freq\n1 Tim Arial 1\n2 Tom Arial 2\n3 Meave Jack 1\n4 Tom Jack 1\n5 Neena Meave 1\n6 Tim Meave 1\n7 Tom Meave 1\n8 Tom Tim 1\n df <- structure(list(Names = c(\"Tom,Jack,Meave\", \"Tom,Arial\", \"Arial,Tim,Tom\", \n\"Neena,Meave\", \"Meave\", \"Tim,Meave\")), class = \"data.frame\", row.names = c(NA, \n-6L))\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12801482/" ]
74,550,722
<p>I'm a high school student, and my class and I just started exploring the world of HTML code. Yesterday, I wrote some basic HTML code and saved it on my computer. Today, I tried to open it, and instead of seeing usual HTML code, the editor showed me a preview.</p> <p>I tried :</p> <ol> <li>disabling extensions in VS Code</li> <li>opening other HTML files</li> <li>opening files with TextEdit and Whisk (both showed me the actual code)</li> </ol> <p><a href="https://i.stack.imgur.com/kTJF0.png" rel="nofollow noreferrer">screenshot of the Visual Studio Code Editor showing a preview for an HTML file</a></p> <p>I'm probably encountering a basic problem, maybe it's not even a problem, but I honestly am lost. I don't know how to get back to my code...</p>
[ { "answer_id": 74550955, "author": "Andrew Gustar", "author_id": 7727429, "author_profile": "https://Stackoverflow.com/users/7727429", "pm_score": 0, "selected": false, "text": "df Names\n <chr>\n Tom,Jack,Meave\n Tom,Arial\n Arial,Tim,Tom\n Neena,Meave\n Meave\n Tim,Meave\n df2 <- df %>% \n mutate(ref = row_number(),\n Names = ifelse(str_count(Names, \",\") == 0, #add nobody if only one\n paste0(Names, \",nobody\"), \n Names),\n Names = str_split(Names, \",\")) %>% \n unnest(Names) %>% \n nest(data = ref) %>% #creates a list of refs for each name\n mutate(Names2 = list(Names)) %>% #add a column of second names for the pairs\n unnest(Names2) %>% \n filter(Names != Names2) %>% #remove self-pairs \n left_join({.} %>% select(Names2 = Names, data2 = data) %>% \n distinct()) %>% #create data for second column of names\n mutate(paired = map2_dbl(data, data2, ~length(intersect(.x$ref, .y$ref)))) %>% \n select(-data, -data2) %>% \n filter(paired > 0, #remove non-occurring combinations\n Names > Names2) #remove duplicates\n > df2\n# A tibble: 18 × 3\n Names Names2 paired\n <chr> <chr> <dbl>\n1 Tom Jack 1\n2 Tom Meave 1\n3 Tom Arial 2\n4 Tom Tim 1\n5 Meave Jack 1\n6 Tim Meave 1\n7 Tim Arial 1\n8 Neena Meave 1\n9 nobody Meave 1\n ref refs refs {.} left_join" }, { "answer_id": 74551166, "author": "onyambu", "author_id": 8380272, "author_profile": "https://Stackoverflow.com/users/8380272", "pm_score": 1, "selected": false, "text": "a <- tcrossprod(table(stack(setNames(strsplit(df$Names,\",\"), rownames(df)))))\na\n\n values\nvalues Arial Jack Meave Neena Tim Tom\n Arial 2 0 0 0 1 2\n Jack 0 1 1 0 0 1\n Meave 0 1 4 1 1 1\n Neena 0 0 1 1 0 0\n Tim 1 0 1 0 2 1\n Tom 2 1 1 0 1 3 \n subset(as.data.frame.table(a), \n as.character(values) > as.character(values.1) & Freq>0)\n values values.1 Freq\n5 Tim Arial 1\n6 Tom Arial 2\n9 Meave Jack 1\n12 Tom Jack 1\n16 Neena Meave 1\n17 Tim Meave 1\n18 Tom Meave 1\n30 Tom Tim 1\n df %>%\n rownames_to_column()%>%\n separate_rows(Names)%>%\n table()%>%\n crossprod()%>%\n as.data.frame.table()%>%\n filter(Freq>0 & as.character(Names) > as.character(Names.1))\n\n Names Names.1 Freq\n1 Tim Arial 1\n2 Tom Arial 2\n3 Meave Jack 1\n4 Tom Jack 1\n5 Neena Meave 1\n6 Tim Meave 1\n7 Tom Meave 1\n8 Tom Tim 1\n df <- structure(list(Names = c(\"Tom,Jack,Meave\", \"Tom,Arial\", \"Arial,Tim,Tom\", \n\"Neena,Meave\", \"Meave\", \"Tim,Meave\")), class = \"data.frame\", row.names = c(NA, \n-6L))\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18709698/" ]
74,550,724
<p>Is there a way, using <a href="https://site.mockito.org/" rel="nofollow noreferrer">Mockito</a> to define an expression like this?</p> <pre><code>when(mockObject.getValuesFor(in(1, 2, 3)).thenReturn(List.of(...))); </code></pre> <p>I can't find a method like <code>in()</code> among the ones defined in <a href="https://javadoc.io/static/org.mockito/mockito-core/4.9.0/org/mockito/ArgumentMatchers.html" rel="nofollow noreferrer"><code>ArgumentMatchers</code></a> and <a href="https://javadoc.io/static/org.mockito/mockito-core/4.9.0/org/mockito/AdditionalMatchers.html" rel="nofollow noreferrer"><code>AdditionalMatchers</code></a>, so I'd like to know which is a common way to achieve what I need.</p> <p><strong>Note</strong> The method I'm mocking is declared like this:</p> <pre><code>List&lt;Integer&gt; getValuesFor(int arg) {...} </code></pre>
[ { "answer_id": 74550984, "author": "aatwork", "author_id": 14263933, "author_profile": "https://Stackoverflow.com/users/14263933", "pm_score": 0, "selected": false, "text": "List list = List.of(1, 2, 3);\nwhen(mockObject.getValuesFor(list).thenReturn(List.of(...)));\n\n//do actual test method call\n\nArgumentCaptor<List> listCaptor = ArgumentCaptor.class(List.class);\nverify(mockObject).getValuesFor(listCaptor.capture());\n\nassertEquals(3, list.getValue().size());\nassertEquals(1, list.getValue().get(0));\nassertEquals(2, list.getValue().get(1));\nassertEquals(3, list.getValue().get(2));\n" }, { "answer_id": 74552074, "author": "Lesiak", "author_id": 1570854, "author_profile": "https://Stackoverflow.com/users/1570854", "pm_score": 3, "selected": true, "text": "intThat when(mockObject.getValuesFor(intThat(x -> Set.of(1, 2, 3).contains(x))))\n .thenReturn(List.of(3, 4, 5));\n ArgumentMatcher<Integer> when(mockObject.getValuesFor(intThat(isOneOf(1, 2, 3))))\n .thenReturn(List.of(3, 4, 5));\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1061499/" ]
74,550,736
<p>I'm trying to separate the last character which should be a letter [A-F] if the the string has 3 numbers in a row somewhere previous.</p> <p>For example, 103C would return 2 separate fields 103 and C A103B would return 2 separate fields A103 and B. FX103D would return 2 separate fields FX103 and D. LOCATION2 would just return LOCATION2 and the 2nd field would be blank.</p> <p>I've done something similar before with regexp_like, but I'm new to regex in general so I'm not sure how'd I'd accomplish this.</p> <p>For a similar application, I've done regexp_like(c_lab.loc_code_from,'^\d{5}[[:alpha:]]') which looks at the first 5 characters, if they're numbers then the condition is satisfied and I split it up accordingly as shown below.</p> <pre><code>CASE WHEN regexp_like(c_lab.loc_code_from,'^\d{5}[[:alpha:]]') THEN substr(c_lab.loc_code_from, 1, 5) ELSE c_lab.loc_code_from END as &quot;From Location&quot;, CASE WHEN regexp_like(c_lab.loc_code_from,'^\d{5}[[:alpha:]]') THEN substr(c_lab.loc_code_from,6,1) ELSE 'A' END as &quot;From Level ID&quot; </code></pre>
[ { "answer_id": 74551591, "author": "psaraj12", "author_id": 1297792, "author_profile": "https://Stackoverflow.com/users/1297792", "pm_score": 1, "selected": false, "text": " WITH data\n AS (SELECT 'A103B' dt\n FROM dual\n UNION\n SELECT '103C'\n FROM dual\n UNION\n SELECT 'FX104D'\n FROM dual\n UNION\n SELECT 'Location2'\n FROM dual)\n SELECT Nvl(Substr(dt, 1, Instr(dt, Regexp_substr ( dt, '[[:digit:]]{3}' ))\n + 2), dt),\n Substr(dt, Instr(dt, Regexp_substr ( dt, '[[:digit:]]{3}' ))\n + 3)\n FROM data; \n \n" }, { "answer_id": 74551899, "author": "Gary_W", "author_id": 2543416, "author_profile": "https://Stackoverflow.com/users/2543416", "pm_score": 1, "selected": false, "text": "WITH tbl(str) AS (\n SELECT '103C' FROM dual UNION ALL\n SELECT 'A103B' FROM dual UNION ALL\n SELECT 'FX103D' FROM dual UNION ALL\n SELECT 'LOCATION2' FROM dual\n)\nSELECT str,\n REGEXP_REPLACE(str, '(.*\\d{3})[A-Z]$', '\\1') AS part_1,\n REGEXP_SUBSTR(str, '.*\\d{3}([A-Z]$)', 1, 1, NULL, 1) AS part_2\nfrom tbl;\n\n\nSTR PART_1 PART_2 \n---------- ---------- ---------\n103C 103 C \nA103B A103 B \nFX103D FX103 D \nLOCATION2 LOCATION2 \n\n4 rows selected.\n NVL(REGEXP_SUBSTR(str, '.*\\d{3}([A-Z]$)', 1, 1, NULL, 1), 'A') AS part_2\n" }, { "answer_id": 74551944, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 0, "selected": false, "text": "SELECT value,\n REGEXP_REPLACE(value, '^(.*\\d{3}.*)([A-F])$', '\\1') AS part1,\n REGEXP_SUBSTR(value, '^(.*\\d{3}.*)([A-F])$', 1, 1, NULL, 2) AS part2\nFROM table_name;\n CREATE TABLE table_name (value) AS\n SELECT 'A103B' FROM DUAL UNION ALL\n SELECT '103C' FROM DUAL UNION ALL\n SELECT 'FX104D' FROM DUAL UNION ALL\n SELECT 'Location2' FROM DUAL;\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19139960/" ]
74,550,744
<p><strong>Question:</strong></p> <p>How does <code>std::is_const</code> work on non-static member method types? Is a <code>const</code> member method not a const-qualified type?</p> <p><strong>Example:</strong></p> <pre><code>class D {}; </code></pre> <p>We will have</p> <pre><code>std::is_const_v&lt;void (D::*)() const&gt; == false </code></pre> <p><strong>Follow-up:</strong></p> <p>Can the constness of a member non-static method be determined (at compile/run time)?</p>
[ { "answer_id": 74550891, "author": "François Andrieux", "author_id": 7359094, "author_profile": "https://Stackoverflow.com/users/7359094", "pm_score": 2, "selected": false, "text": "#include <type_traits>\n\n// Base template\ntemplate<class T>\nstruct is_const_member_func_ptr;\n\n// Specialize for pointers to non-const member function\ntemplate<class T, class C, class ... A>\nstruct is_const_member_func_ptr<T (C::*)(A...)> : std::false_type {};\n\n// Specialize for pointers to const member function\ntemplate<class T, class C, class ... A>\nstruct is_const_member_func_ptr<T (C::*)(A...) const> : std::true_type {};\n\n// Convenient constant template\ntemplate<class T>\ninline constexpr bool is_const_member_func_ptr_v = is_const_member_func_ptr<T>::value;\n class D {};\n\nstatic_assert(is_const_member_func_ptr_v<void (D::*)() const> == true);\nstatic_assert(is_const_member_func_ptr_v<void (D::*)()> == false);\n // Usage\n#include <iomanip>\n#include <iostream>\n\nclass D \n{\npublic:\n void foo() {}\n void foo_c() const {}\n};\n\nint main()\n{\n std::cout << std::boolalpha << is_const_member_func_ptr_v<decltype(&D::foo)> << '\\n';\n std::cout << std::boolalpha << is_const_member_func_ptr_v<decltype(&D::foo_c)> << '\\n';\n}\n" }, { "answer_id": 74552124, "author": "Nelfeal", "author_id": 3854570, "author_profile": "https://Stackoverflow.com/users/3854570", "pm_score": 3, "selected": true, "text": "void (D::*)() const std::is_const std::is_const_v<void (D::*)() const> == false std::is_const_v<void (D::* const)()> == true #include <type_traits>\n\nstruct ArbitraryType {\n template <typename T>\n operator T & ();\n template <typename T>\n operator T && ();\n};\n\ntemplate<bool, bool, class T, class Arg, class... Args>\nstruct is_invocable_with_const_first_arg_impl : std::bool_constant<\n is_invocable_with_const_first_arg_impl<\n std::is_invocable_v<T, Arg const&, Args...> || std::is_invocable_v<T, Arg const&&, Args...>,\n std::is_invocable_v<T, Arg&, Args...> || std::is_invocable_v<T, Arg&&, Args...>,\n T, Arg, Args..., ArbitraryType\n >::value\n> {};\n\ntemplate<bool b, class T, class Arg, class... Args>\nstruct is_invocable_with_const_first_arg_impl<true, b, T, Arg, Args...> : std::true_type {};\n\ntemplate<class T, class Arg, class... Args>\nstruct is_invocable_with_const_first_arg_impl<false, true, T, Arg, Args...> : std::false_type {};\n\ntemplate<class T, class Arg>\nstruct is_invocable_with_const_first_arg : is_invocable_with_const_first_arg_impl<false, false, T, Arg> {};\n\ntemplate<class T, class Arg>\ninline constexpr bool is_invocable_with_const_first_arg_v = is_invocable_with_const_first_arg<T, Arg>::value;\n\ntemplate<class T>\nstruct is_const_member_func_ptr;\n\ntemplate<class R, class C>\nstruct is_const_member_func_ptr<R C::*> : std::bool_constant<\n is_invocable_with_const_first_arg_v<R C::*, C>\n || is_invocable_with_const_first_arg_v<R C::*, C>\n> {};\n\ntemplate<class T>\ninline constexpr bool is_const_member_func_ptr_v = is_const_member_func_ptr<T>::value;\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8474071/" ]
74,550,763
<p>I have a dictionary containing lists like</p> <pre><code>char_code = {'1':['b','f','v','p'],'2':['c','g','j','k','q','s','x','z'], '3':['d','t'], '4':['l'],'5':['m','n'], '6':['r']} </code></pre> <p>I have another list containing characters</p> <pre><code>word_list = ['r', 'v', 'p', 'c'] </code></pre> <p>I want to replace the letters in word_list with keys in the dictionary so that it should become</p> <pre><code>['6', '1', '1', '2'] </code></pre> <p>I tried some thing like</p> <pre><code>word_list[:]=[char_code.get(e,'') for e in word_list] </code></pre>
[ { "answer_id": 74550882, "author": "Always Sunny", "author_id": 1138192, "author_profile": "https://Stackoverflow.com/users/1138192", "pm_score": 1, "selected": false, "text": "for list comprehension dictionary and finally char_code = {'1':['b','f','v','p'],'2':['c','g','j','k','q','s','x','z'], '3':['d','t'], '4':['l'],'5':['m','n'], '6':['r']}\n\nword_list = ['r', 'v', 'p', 'c']\nexpected_list = []\nfor word in word_list:\n expected_list.append([k for k, v in char_code.items() if word in v][0])\nprint(expected_list)\n ['6', '1', '1', '2']\n" }, { "answer_id": 74550981, "author": "Karl Knechtel", "author_id": 523612, "author_profile": "https://Stackoverflow.com/users/523612", "pm_score": 3, "selected": true, "text": "num_code = {\n letter: digit\n for digit, letters in char_code.items()\n for letter in letters\n}\n word_list[:] = [num_code[letter] for letter in word_list]\n" }, { "answer_id": 74550983, "author": "Woodford", "author_id": 8451814, "author_profile": "https://Stackoverflow.com/users/8451814", "pm_score": 1, "selected": false, "text": ">>> letter_to_code = {letter: code for code, lst in char_code.items() for letter in lst}\n>>> [letter_to_code[letter] for letter in word_list]\n['6', '1', '1', '2']\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17939220/" ]
74,550,767
<p><a href="https://i.stack.imgur.com/RZtmP.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RZtmP.jpg" alt="enter image description here" /></a></p> <p>I have no idea whats going on but I activated venv by using <code>Scripts/activate</code> and it doesnt working yet, the <code>(venv)</code> isnt appearing</p> <p>please someone could help me? I tried everything I could find lol</p>
[ { "answer_id": 74550882, "author": "Always Sunny", "author_id": 1138192, "author_profile": "https://Stackoverflow.com/users/1138192", "pm_score": 1, "selected": false, "text": "for list comprehension dictionary and finally char_code = {'1':['b','f','v','p'],'2':['c','g','j','k','q','s','x','z'], '3':['d','t'], '4':['l'],'5':['m','n'], '6':['r']}\n\nword_list = ['r', 'v', 'p', 'c']\nexpected_list = []\nfor word in word_list:\n expected_list.append([k for k, v in char_code.items() if word in v][0])\nprint(expected_list)\n ['6', '1', '1', '2']\n" }, { "answer_id": 74550981, "author": "Karl Knechtel", "author_id": 523612, "author_profile": "https://Stackoverflow.com/users/523612", "pm_score": 3, "selected": true, "text": "num_code = {\n letter: digit\n for digit, letters in char_code.items()\n for letter in letters\n}\n word_list[:] = [num_code[letter] for letter in word_list]\n" }, { "answer_id": 74550983, "author": "Woodford", "author_id": 8451814, "author_profile": "https://Stackoverflow.com/users/8451814", "pm_score": 1, "selected": false, "text": ">>> letter_to_code = {letter: code for code, lst in char_code.items() for letter in lst}\n>>> [letter_to_code[letter] for letter in word_list]\n['6', '1', '1', '2']\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20584173/" ]
74,550,793
<p>I have a dataframe with recorded dates and event dates, I use the following script to create a new dataframe with only rows where record and event dates match.</p> <pre><code>New_df =df1.loc[(df1['record_date'] == df1['event_date'])] </code></pre> <p>However I want to include rows from dataset where record dates are +- 1 day, 2 day, 3 days from event date including above code. How can do that?</p>
[ { "answer_id": 74550882, "author": "Always Sunny", "author_id": 1138192, "author_profile": "https://Stackoverflow.com/users/1138192", "pm_score": 1, "selected": false, "text": "for list comprehension dictionary and finally char_code = {'1':['b','f','v','p'],'2':['c','g','j','k','q','s','x','z'], '3':['d','t'], '4':['l'],'5':['m','n'], '6':['r']}\n\nword_list = ['r', 'v', 'p', 'c']\nexpected_list = []\nfor word in word_list:\n expected_list.append([k for k, v in char_code.items() if word in v][0])\nprint(expected_list)\n ['6', '1', '1', '2']\n" }, { "answer_id": 74550981, "author": "Karl Knechtel", "author_id": 523612, "author_profile": "https://Stackoverflow.com/users/523612", "pm_score": 3, "selected": true, "text": "num_code = {\n letter: digit\n for digit, letters in char_code.items()\n for letter in letters\n}\n word_list[:] = [num_code[letter] for letter in word_list]\n" }, { "answer_id": 74550983, "author": "Woodford", "author_id": 8451814, "author_profile": "https://Stackoverflow.com/users/8451814", "pm_score": 1, "selected": false, "text": ">>> letter_to_code = {letter: code for code, lst in char_code.items() for letter in lst}\n>>> [letter_to_code[letter] for letter in word_list]\n['6', '1', '1', '2']\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14915169/" ]
74,550,798
<p>I'll implement dbt for pipelines in Snowflake with incremental models to save query costs but I want to manage the changes of schemas that will be quite frequent. I will have one daily ETL job for each env running a <code>dbt run</code>. Also, in qa and prod environments I'll not be able to run any cmd as I don't have access to these environments for security issues, only to dev.</p> <p>Is it possible to trigger a full refresh of a model if its schema changed?</p> <p>I saw that we can use the <code>on_schema_change</code> option with incremental models but this will just add (or drop) columns without populating them which is not exactly what I'm looking for as I'll not be able to run a force refresh manually in qa and prod.</p> <p>Thanks a lot</p>
[ { "answer_id": 74550971, "author": "Lukasz Szozda", "author_id": 5070879, "author_profile": "https://Stackoverflow.com/users/5070879", "pm_score": 0, "selected": false, "text": "$ dbt run --full-refresh --select my_incremental_model+\n {{ config(\n full_refresh = true\n) }}\n\nselect ...\n" }, { "answer_id": 74572646, "author": "Paddy Alton", "author_id": 9044370, "author_profile": "https://Stackoverflow.com/users/9044370", "pm_score": 2, "selected": true, "text": "on_schema_change on_schema_change --full-refresh v1.2.1 v1.3.0 v1.3.0-prerelease full_refresh=true v1.3.0" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15463238/" ]
74,550,801
<p>Not able to convert the below T-SQL Query part ISNULL(NAME,'N/A') to Spark-SQL Equivalent</p> <p>SELECT ID, ISNULL(NAME,'N/A') AS NAME, COMPANY FROM TEST to</p> <p>convert the below T-SQL Query part ISNULL(NAME,'N/A') to Spark-SQL Equivalent</p> <p>SELECT ID, ISNULL(NAME,'N/A') AS NAME, COMPANY FROM TEST</p>
[ { "answer_id": 74551968, "author": "Bartosz Gajda", "author_id": 6870955, "author_profile": "https://Stackoverflow.com/users/6870955", "pm_score": 1, "selected": false, "text": "df = spark.createDataFrame([(1, None), (2, None)], \"id: int, value: string\")\ndf.show()\n\n+---+-----+\n| id|value|\n+---+-----+\n| 1| null|\n| 2| null|\n+---+-----+\n\ndf.na.fill(\"N/A\", subset=[\"value\"]).show()\n\n+---+-----+\n| id|value|\n+---+-----+\n| 1| N/A|\n| 2| N/A|\n+---+-----+\n\nfrom pyspark.sql.functions import col, when\n\ndf.withColumn(\"value\", when(col(\"value\").isNull(), \"N/A\")).show()\n\n+---+-----+\n| id|value|\n+---+-----+\n| 1| N/A|\n| 2| N/A|\n+---+-----+\n" }, { "answer_id": 74556439, "author": "rainingdistros", "author_id": 13280838, "author_profile": "https://Stackoverflow.com/users/13280838", "pm_score": 1, "selected": true, "text": "CASE WHEN NAME IS NULL THEN 'N/A' ELSE NAME END AS NAME\n SELECT COALESCE(NAME,'N/A') AS NAME\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13680272/" ]
74,550,814
<p>I am trying to execute below code wherein I want to insert a key in the dictionary with a particular value on a condition where tos is greater than or less than the value of position key in the dictionary. But in the output I see the else or elif condition executed every time.</p> <pre><code>def convert_csv_to_dataframe_and_then_convert_csv_data_to_dictionary(tos): recs = {0: {'POSITION': 650886123, 'is_valid': False}, 1: {'POSITION': 650886121, 'is_valid': False}} for i in recs: if int(recs[i]['POSITION'])&gt;tos: recs[i]['is_valid']=True elif int(recs[i]['POSITION'])&lt;tos: recs[i]['is_valid'] = False print(recs) convert_csv_to_dataframe_and_then_convert_csv_data_to_dictionary(6508861232) </code></pre> <p>Below is the output.</p> <pre><code>{ 0: { 'POSITION': 650886123, 'is_valid': False}, 1: { 'POSITION': 650886121, 'is_valid': False} } </code></pre> <p>I have passed tos as 6508861232 which is greater than 650886123 and the other position key value in the dictionary but the is_valid is not added as True in the dictionary. Am I missing something in the code?</p>
[ { "answer_id": 74551968, "author": "Bartosz Gajda", "author_id": 6870955, "author_profile": "https://Stackoverflow.com/users/6870955", "pm_score": 1, "selected": false, "text": "df = spark.createDataFrame([(1, None), (2, None)], \"id: int, value: string\")\ndf.show()\n\n+---+-----+\n| id|value|\n+---+-----+\n| 1| null|\n| 2| null|\n+---+-----+\n\ndf.na.fill(\"N/A\", subset=[\"value\"]).show()\n\n+---+-----+\n| id|value|\n+---+-----+\n| 1| N/A|\n| 2| N/A|\n+---+-----+\n\nfrom pyspark.sql.functions import col, when\n\ndf.withColumn(\"value\", when(col(\"value\").isNull(), \"N/A\")).show()\n\n+---+-----+\n| id|value|\n+---+-----+\n| 1| N/A|\n| 2| N/A|\n+---+-----+\n" }, { "answer_id": 74556439, "author": "rainingdistros", "author_id": 13280838, "author_profile": "https://Stackoverflow.com/users/13280838", "pm_score": 1, "selected": true, "text": "CASE WHEN NAME IS NULL THEN 'N/A' ELSE NAME END AS NAME\n SELECT COALESCE(NAME,'N/A') AS NAME\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20262433/" ]
74,550,833
<p>I am beginner in adf and trying to update SQL table through adf in Dataflw activity,</p> <p>Source - Excel file Sink - SQL table</p> <p>Source and SinkColumns - AccountID, LegacyAccID, AccountGroupCD</p> <p>Now I only want update the record in sink if below condition matched</p> <p><strong>if(FileAccountID == DBLegacyID &amp;&amp; FileAccountID != DBAccountID)</strong></p> <p>I can map the FileAccountID == DBLegacyID in sink mapping , How can I add 2nd condition, really appreciate any help</p>
[ { "answer_id": 74551968, "author": "Bartosz Gajda", "author_id": 6870955, "author_profile": "https://Stackoverflow.com/users/6870955", "pm_score": 1, "selected": false, "text": "df = spark.createDataFrame([(1, None), (2, None)], \"id: int, value: string\")\ndf.show()\n\n+---+-----+\n| id|value|\n+---+-----+\n| 1| null|\n| 2| null|\n+---+-----+\n\ndf.na.fill(\"N/A\", subset=[\"value\"]).show()\n\n+---+-----+\n| id|value|\n+---+-----+\n| 1| N/A|\n| 2| N/A|\n+---+-----+\n\nfrom pyspark.sql.functions import col, when\n\ndf.withColumn(\"value\", when(col(\"value\").isNull(), \"N/A\")).show()\n\n+---+-----+\n| id|value|\n+---+-----+\n| 1| N/A|\n| 2| N/A|\n+---+-----+\n" }, { "answer_id": 74556439, "author": "rainingdistros", "author_id": 13280838, "author_profile": "https://Stackoverflow.com/users/13280838", "pm_score": 1, "selected": true, "text": "CASE WHEN NAME IS NULL THEN 'N/A' ELSE NAME END AS NAME\n SELECT COALESCE(NAME,'N/A') AS NAME\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4505544/" ]
74,550,856
<p>I've uploaded my video on Google Drive and Dropbox and tried to give the 'src' attribute the url copied from these platforms but the video doesn't show up. Seems like that url doesn't link up to very final video element but only to an upper level that the tag source attribute doesn't accept.</p> <p>I'm asking as I don't have my local environment where to upload the video (don't ask me why) so I'd really need to upload it somewhere remote I can successfully link to from inside the tag. In alternative, if you know a way to make a video hosted on Google Drive and Dropbox to show up via tag, I'd be happy with that one too. Thank you!</p>
[ { "answer_id": 74551968, "author": "Bartosz Gajda", "author_id": 6870955, "author_profile": "https://Stackoverflow.com/users/6870955", "pm_score": 1, "selected": false, "text": "df = spark.createDataFrame([(1, None), (2, None)], \"id: int, value: string\")\ndf.show()\n\n+---+-----+\n| id|value|\n+---+-----+\n| 1| null|\n| 2| null|\n+---+-----+\n\ndf.na.fill(\"N/A\", subset=[\"value\"]).show()\n\n+---+-----+\n| id|value|\n+---+-----+\n| 1| N/A|\n| 2| N/A|\n+---+-----+\n\nfrom pyspark.sql.functions import col, when\n\ndf.withColumn(\"value\", when(col(\"value\").isNull(), \"N/A\")).show()\n\n+---+-----+\n| id|value|\n+---+-----+\n| 1| N/A|\n| 2| N/A|\n+---+-----+\n" }, { "answer_id": 74556439, "author": "rainingdistros", "author_id": 13280838, "author_profile": "https://Stackoverflow.com/users/13280838", "pm_score": 1, "selected": true, "text": "CASE WHEN NAME IS NULL THEN 'N/A' ELSE NAME END AS NAME\n SELECT COALESCE(NAME,'N/A') AS NAME\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20584010/" ]
74,550,871
<p>I have the following dataframe :</p> <pre><code># A tibble: 15 × 2 type id &lt;chr&gt; &lt;chr&gt; 1 P A1 2 N A2 3 N A3 4 N A4 5 P A5 6 N A6 7 N A7 8 P A8 9 N A9 10 N A10 11 P A11 12 N A12 13 N A13 14 N A14 15 P A15 </code></pre> <p>The correct id for each type is the id that is where the is type = &quot;P&quot; and stays the same until another type &quot;P&quot; appears again and the following id's take it's id. basically i want the following:</p> <pre><code># A tibble: 15 × 2 type id &lt;chr&gt; &lt;chr&gt; 1 P A1 2 N A1 3 N A1 4 N A1 5 P A5 6 N A5 7 N A5 8 P A8 9 N A8 10 N A8 11 P A11 12 N A11 13 N A11 14 N A11 15 P A15 </code></pre>
[ { "answer_id": 74551968, "author": "Bartosz Gajda", "author_id": 6870955, "author_profile": "https://Stackoverflow.com/users/6870955", "pm_score": 1, "selected": false, "text": "df = spark.createDataFrame([(1, None), (2, None)], \"id: int, value: string\")\ndf.show()\n\n+---+-----+\n| id|value|\n+---+-----+\n| 1| null|\n| 2| null|\n+---+-----+\n\ndf.na.fill(\"N/A\", subset=[\"value\"]).show()\n\n+---+-----+\n| id|value|\n+---+-----+\n| 1| N/A|\n| 2| N/A|\n+---+-----+\n\nfrom pyspark.sql.functions import col, when\n\ndf.withColumn(\"value\", when(col(\"value\").isNull(), \"N/A\")).show()\n\n+---+-----+\n| id|value|\n+---+-----+\n| 1| N/A|\n| 2| N/A|\n+---+-----+\n" }, { "answer_id": 74556439, "author": "rainingdistros", "author_id": 13280838, "author_profile": "https://Stackoverflow.com/users/13280838", "pm_score": 1, "selected": true, "text": "CASE WHEN NAME IS NULL THEN 'N/A' ELSE NAME END AS NAME\n SELECT COALESCE(NAME,'N/A') AS NAME\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15453570/" ]
74,550,886
<p>I am trying to use SimpleInjector in a WPF Application (.NET Framework). We use it in exactly the same way in many of our Services but for some reason when I am attempting to implement the same logic in this WPF Application, the call to the <code>HttpClient().GetAsync</code> is hanging. We think it is because for some reason the Task is not executing.</p> <p>I am registering the objects from the <code>OnStartUp</code> element of App.xaml.cs as below. Inside the <code>SetupService</code> Constructor we call a SetupService URL (set in the SetupConfiguration Section of the App.Config) to get the <code>SetupResponse</code> to use in the app.</p> <p>It is ultimately hanging in the <code>ServiceClient.GetAsync</code> method, I have tried to show the flow below:</p> <p>All classes appear to have been injected correctly, and the <code>ServiceClient</code> is populated in exactly the same way as the same point in one of our working services. We're at a loss as to what is happening, and how to fix this.</p> <p>Finally, <code>SetupService</code> is being injected in other Classes - so I would rather get it working like this, rather than remove the call from the <code>SimpleInjector</code> mechanism.</p> <p>Any help is very much appreciated.</p> <pre><code> public partial class App : Application { private static readonly Container _container = new Container(); protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); RegisterDependencies(); _container.Verify(); } private void RegisterDependencies() { var serviceConfigSection = ServiceConfigurationSection.Get(); _container.RegisterSingle&lt;ILoggingProvider, LoggingProvider&gt;(); _container.RegisterSingle&lt;IServiceClient&gt;(() =&gt; new ServiceClient(_container.GetInstance&lt;ILoggingProvider&gt;())); _container.RegisterSingle&lt;IConfigurationSection&gt;(() =&gt; SetupConfigurationSection.Get()); _container.RegisterSingle&lt;ISetupService, SetupService&gt;(); } } </code></pre> <pre><code> public class SetupService: ISetupService { private static readonly Dictionary&lt;string, string&gt; AcceptType = new Dictionary&lt;string, string&gt; { {&quot;Accept&quot;, &quot;application/xml&quot;} }; private const string AuthenticationType = &quot;Basic&quot;; private readonly IServiceClient _serviceClient; private readonly ILoggingProvider _logger; private readonly IConfigurationSection _configuration; public SetupService(IConfigurationSection configuration, IServiceClient serviceClient, ILoggingProvider logger) { _serviceClient = serviceClient; _logger = logger; _configuration = kmsConfiguration; RefreshSetup(); } public void RefreshSetup() { try { var token = BuildIdentityToken(); var authHeaderClear = string.Format(&quot;IDENTITY_TOKEN:{0}&quot;, token); var authenticationHeaderValue = new AuthenticationHeaderValue(AuthenticationType, Convert.ToBase64String(Encoding.ASCII.GetBytes(authHeaderClear))); _serviceClient.Url = _configuration.Url; var httpResponse = _serviceClient.GetAsync(string.Empty, authenticationHeaderValue, AcceptType).Result; var responseString = httpResponse.Content.ReadAsStringAsync().Result; _response = responseString.FromXML&lt;SetupResponse&gt;(); } catch (Exception e) { throw } } </code></pre> <pre><code> public class ServiceClient : IServiceClient { private const string ContentType = &quot;application/json&quot;; private string _userAgent; private ILoggingProvider _logger; public string Url { get; set; } public string ProxyAddress { get; set; } public int TimeoutForRequestAndResponseMs { get; set; } public int HttpCode { get; private set; } public ServiceClient(ILoggingProvider logger = null) { _logger = logger; } public async Task&lt;HttpResponseMessage&gt; GetAsync(string endpoint, AuthenticationHeaderValue authenticationHeaderValue = null, IDictionary&lt;string, string&gt; additionalData = null, IDictionary&lt;string, string&gt; additionalParams = null) { using (var client = new HttpClient()) { client.BaseAddress = new Uri(Url); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(ContentType)); if (authenticationHeaderValue != null) client.DefaultRequestHeaders.Authorization = authenticationHeaderValue; ProcessHeader(client.DefaultRequestHeaders, additionalData); var paramsQueryString = ProcessParams(additionalParams); if (!string.IsNullOrEmpty(paramsQueryString)) endpoint = $&quot;{endpoint}?{paramsQueryString}&quot;; return await client.GetAsync(endpoint); **// HANGS ON THIS LINE!** } } } } </code></pre>
[ { "answer_id": 74553186, "author": "Stephen Cleary", "author_id": 263693, "author_profile": "https://Stackoverflow.com/users/263693", "pm_score": 2, "selected": false, "text": "Result Task.Run var httpResponse = Task.Run(() => _serviceClient.GetAsync(string.Empty, authenticationHeaderValue, AcceptType)).GetAwaiter().GetResult();" }, { "answer_id": 74575372, "author": "Andrew Humphries", "author_id": 15329642, "author_profile": "https://Stackoverflow.com/users/15329642", "pm_score": 1, "selected": true, "text": "static class Program\n {\n public static readonly Container _container = new Container();\n /// <summary>\n /// The main entry point for the application.\n /// </summary>\n [STAThread]\n public static void Main(){\n\n var app = new MyApp.App();\n Register();\n app.Run(_container.GetInstance<MainWindow>());\n }\n\n static void Register()\n {\n _container.Register<MainWindow>();\n MySimpleInjector.Register(_container);\n _container.Verify();\n }\n }\n public class MySimpleInjector\n {\n private readonly Container _container;\n\n public static void Register(Container container)\n {\n var injector = new MySimpleInjector(container);\n }\n\n private void RegisterDependencies()\n {\n var serviceConfigSection = ServiceConfigurationSection.Get();\n \n _container.RegisterSingle<ILoggingProvider, LoggingProvider>();\n _container.RegisterSingle<IServiceClient>(() => new ServiceClient(_container.GetInstance<ILoggingProvider>()));\n _container.RegisterSingle<IConfigurationSection>(() => SetupConfigurationSection.Get());\n _container.RegisterSingle<ISetupService, SetupService>();\n\n }\n }\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15329642/" ]
74,550,900
<p>I'm trying to build a graph with two y-axis, showing the development of homicides and share of national wealth of the bottom 50% in Sierra Leone between 2004 and 2015. I'm quite familiar with ggplot in simpler circumstances, now I'm struggeling. There have been some posts regarding this topic, but the approach via scale_y_continuous for the second y-axis won't work for me. I keep getting this error: Error: Discrete value supplied to continuous scale</p> <p>I've checked my dataframe for discrete values via is.discrete and there are none. Does anyone have some advise for me? Thanks in advance</p> <pre><code>year &lt;- c(2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2015) share &lt;- c(0.0434, 0.0446, 0.0452, 0.0458, 0.0466, 0.0472, 0.0475, 0.0479, 0.0475, 0.0465) p100kp &lt;- c(2.0611, 1.7536, 1.7326, 2.2372, 2.9999, 2.5188, 2.5407, 2.8492, 1.6834, 1.7290) df &lt;- data.frame(year, share, p100kp) PP1 &lt;- ggplot(df, aes(x = year, y = p100kp)) + geom_line(aes(color = &quot;Homicides per 100K population&quot;)) + geom_line(aes(y = share, color = &quot;Share of national wealth&quot;)) + scale_x_continuous(breaks = seq(2004, 2015)) + scale_y_continuous(sec.axis = sec_axis(~.*scale, name=&quot;Share&quot;)) + labs(x = &quot;Year&quot;, y = &quot;Homicides per 100K population&quot;, color = &quot;&quot;) + scale_color_manual(values = c(&quot;orange2&quot;, &quot;gray30&quot;)) print(PP1) </code></pre>
[ { "answer_id": 74553186, "author": "Stephen Cleary", "author_id": 263693, "author_profile": "https://Stackoverflow.com/users/263693", "pm_score": 2, "selected": false, "text": "Result Task.Run var httpResponse = Task.Run(() => _serviceClient.GetAsync(string.Empty, authenticationHeaderValue, AcceptType)).GetAwaiter().GetResult();" }, { "answer_id": 74575372, "author": "Andrew Humphries", "author_id": 15329642, "author_profile": "https://Stackoverflow.com/users/15329642", "pm_score": 1, "selected": true, "text": "static class Program\n {\n public static readonly Container _container = new Container();\n /// <summary>\n /// The main entry point for the application.\n /// </summary>\n [STAThread]\n public static void Main(){\n\n var app = new MyApp.App();\n Register();\n app.Run(_container.GetInstance<MainWindow>());\n }\n\n static void Register()\n {\n _container.Register<MainWindow>();\n MySimpleInjector.Register(_container);\n _container.Verify();\n }\n }\n public class MySimpleInjector\n {\n private readonly Container _container;\n\n public static void Register(Container container)\n {\n var injector = new MySimpleInjector(container);\n }\n\n private void RegisterDependencies()\n {\n var serviceConfigSection = ServiceConfigurationSection.Get();\n \n _container.RegisterSingle<ILoggingProvider, LoggingProvider>();\n _container.RegisterSingle<IServiceClient>(() => new ServiceClient(_container.GetInstance<ILoggingProvider>()));\n _container.RegisterSingle<IConfigurationSection>(() => SetupConfigurationSection.Get());\n _container.RegisterSingle<ISetupService, SetupService>();\n\n }\n }\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20584060/" ]
74,550,921
<p>When an interrupt service routine is being executed, is it necessary to clear global interrupts (using the cli(); command for example) to prevent another ISR from being executed or queued?</p> <p>For example, if an external interrupt INT0 is being executed and while it is executing this same external interrupt were to be triggered again. Would that interrupt be queued to be executed after the first interrupt is finished?</p> <p>would the follow code prevent an interrupt from being queued if it is executed during the current interrupt or would I need to clear an interrupt queue register?</p> <pre><code>ISR(someISR_vect){ cli(); some code... sei(); } </code></pre>
[ { "answer_id": 74553186, "author": "Stephen Cleary", "author_id": 263693, "author_profile": "https://Stackoverflow.com/users/263693", "pm_score": 2, "selected": false, "text": "Result Task.Run var httpResponse = Task.Run(() => _serviceClient.GetAsync(string.Empty, authenticationHeaderValue, AcceptType)).GetAwaiter().GetResult();" }, { "answer_id": 74575372, "author": "Andrew Humphries", "author_id": 15329642, "author_profile": "https://Stackoverflow.com/users/15329642", "pm_score": 1, "selected": true, "text": "static class Program\n {\n public static readonly Container _container = new Container();\n /// <summary>\n /// The main entry point for the application.\n /// </summary>\n [STAThread]\n public static void Main(){\n\n var app = new MyApp.App();\n Register();\n app.Run(_container.GetInstance<MainWindow>());\n }\n\n static void Register()\n {\n _container.Register<MainWindow>();\n MySimpleInjector.Register(_container);\n _container.Verify();\n }\n }\n public class MySimpleInjector\n {\n private readonly Container _container;\n\n public static void Register(Container container)\n {\n var injector = new MySimpleInjector(container);\n }\n\n private void RegisterDependencies()\n {\n var serviceConfigSection = ServiceConfigurationSection.Get();\n \n _container.RegisterSingle<ILoggingProvider, LoggingProvider>();\n _container.RegisterSingle<IServiceClient>(() => new ServiceClient(_container.GetInstance<ILoggingProvider>()));\n _container.RegisterSingle<IConfigurationSection>(() => SetupConfigurationSection.Get());\n _container.RegisterSingle<ISetupService, SetupService>();\n\n }\n }\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12780095/" ]
74,550,938
<h2><code>Http.request</code> seems to ignore <code>body</code> when the method is <code>GET</code></h2> <pre><code>init : () -&gt; ( Model, Cmd Msg ) init _ = ( Loading , Http.request { method = &quot;GET&quot; , headers = [] , url = &quot;http://127.0.0.1&quot; , body = Http.stringBody &quot;text/plain&quot; &quot;Hello World!&quot; , expect = Http.expectWhatever Sent , timeout = Nothing , tracker = Nothing } ) </code></pre> <p>The sent request has no body (when inspected with browser development tool). </p> <pre><code>init : () -&gt; ( Model, Cmd Msg ) init _ = ( Loading , Http.request { method = &quot;POST&quot; {- CHANGED TO POST -} , headers = [] , url = &quot;http://127.0.0.1&quot; , body = Http.stringBody &quot;text/plain&quot; &quot;Hello World!&quot; , expect = Http.expectWhatever Sent , timeout = Nothing , tracker = Nothing } ) </code></pre> <p>But when the method is changed to <code>&quot;POST&quot;</code>, it works ! The body contains <code>&quot;Hello World!&quot;</code>. </p> <p>The API I try to communicate with requires an <code>application/json</code> body in a <code>GET</code> request. Help me !</p> <p>PS: Here is what the documentations says:</p> <blockquote> <p><code>emptyBody : Body</code></p> <p>Create an empty body for your Request. This is useful for GET requests and POST requests where you are not sending any data.</p> </blockquote> <p>Which is not clear, because it can be interpreted in two different ways:</p> <p><em>This is useful for GET requests and { POST requests where you are not sending any data } .</em></p> <p>Or:</p> <p><em>This is useful for { GET requests and POST requests } where you are not sending any data.</em></p>
[ { "answer_id": 74551015, "author": "glennsl", "author_id": 7943564, "author_profile": "https://Stackoverflow.com/users/7943564", "pm_score": 3, "selected": false, "text": "GET GET GET" }, { "answer_id": 74577379, "author": "8n8", "author_id": 6629874, "author_profile": "https://Stackoverflow.com/users/6629874", "pm_score": 3, "selected": true, "text": "module Main exposing (main)\n\nimport Platform\nimport Http\n\nmain =\n Platform.worker\n { init = \\() -> ((), Http.request\n { method = \"GET\"\n , headers = []\n , url = \"https://catfact.ninja/fact\"\n , body = Http.stringBody \"text/plain\" \"hi\"\n , expect = Http.expectWhatever (\\_ -> ())\n , timeout = Nothing\n , tracker = Nothing\n })\n , update = \\() () -> ((), Cmd.none)\n , subscriptions = \\() -> Sub.none\n }\n index.html var xhr = new XMLHttpRequest();\n xhr.addEventListener('error', function() { done($elm$http$Http$NetworkError_); });\n xhr.addEventListener('timeout', function() { done($elm$http$Http$Timeout_); });\n xhr.addEventListener('load', function() { done(_Http_toResponse(request.expect.b, xhr)); });\n $elm$core$Maybe$isJust(request.tracker) && _Http_track(router, xhr, request.tracker.a);\n\n try {\n xhr.open(request.method, request.url, true);\n } catch (e) {\n return done($elm$http$Http$BadUrl_(request.url));\n }\n\n _Http_configureRequest(xhr, request);\n\n request.body.a && xhr.setRequestHeader('Content-Type', request.body.a);\n xhr.send(request.body.b);\n request.body.b xhr.send" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6552577/" ]
74,550,996
<p>I have a simple function that use the library <a href="https://github.com/Stuk/jszip" rel="nofollow noreferrer">jszip</a> to zip some folders and files:</p> <pre class="lang-js prettyprint-override"><code>// app.ts const runJszip = async (): Promise&lt;void&gt; =&gt; { const zip = new Jszip(); zip.folder('folder')?.file('file.txt', 'just some text'); zip.file('file.txt', 'just some text'); await zip.generateAsync({ type: 'blob' }); }; </code></pre> <p>I want to test it by spying the methods <code>folder</code> and <code>file</code>. I used for that the <a href="https://jestjs.io/docs/28.x/mock-functions#mocking-partials" rel="nofollow noreferrer">mocking partial</a> strategy to handle the default export of this library:</p> <pre class="lang-js prettyprint-override"><code>// app.test.ts import { runJszip } from './app'; const mockFile = jest.fn(); const mockFolder = jest.fn(); const mockJszip = jest.fn().mockImplementation(() =&gt; { return { folder: mockFolder, file: mockFile, }; }); jest.mock('jszip', () =&gt; { return jest.fn().mockImplementation(() =&gt; ({ __esModule: true, default: mockJszip, })); }); test('jszip', async () =&gt; { await runJszip(); expect(mockFile).toHaveBeenCalledTimes(2); expect(mockFolder).toHaveBeenCalledTimes(1); }); </code></pre> <p>Unfortunately, it seems that I can't properly mock the <code>folder</code> method as you can see in the following error message:</p> <pre><code> Message: zip.folder is not a function 4 | const zip = new Jszip(); 5 | &gt; 6 | zip.folder('folder')?.file('file.txt', 'just some text'); </code></pre> <p>So does someone have an idea how I could mock and spy on this method?</p> <p>Have a look at the <a href="https://stackblitz.com/edit/webpack-5-react-starter-hy8tyu?file=src/app.test.ts" rel="nofollow noreferrer">minimal reproducible example</a>.</p>
[ { "answer_id": 74551015, "author": "glennsl", "author_id": 7943564, "author_profile": "https://Stackoverflow.com/users/7943564", "pm_score": 3, "selected": false, "text": "GET GET GET" }, { "answer_id": 74577379, "author": "8n8", "author_id": 6629874, "author_profile": "https://Stackoverflow.com/users/6629874", "pm_score": 3, "selected": true, "text": "module Main exposing (main)\n\nimport Platform\nimport Http\n\nmain =\n Platform.worker\n { init = \\() -> ((), Http.request\n { method = \"GET\"\n , headers = []\n , url = \"https://catfact.ninja/fact\"\n , body = Http.stringBody \"text/plain\" \"hi\"\n , expect = Http.expectWhatever (\\_ -> ())\n , timeout = Nothing\n , tracker = Nothing\n })\n , update = \\() () -> ((), Cmd.none)\n , subscriptions = \\() -> Sub.none\n }\n index.html var xhr = new XMLHttpRequest();\n xhr.addEventListener('error', function() { done($elm$http$Http$NetworkError_); });\n xhr.addEventListener('timeout', function() { done($elm$http$Http$Timeout_); });\n xhr.addEventListener('load', function() { done(_Http_toResponse(request.expect.b, xhr)); });\n $elm$core$Maybe$isJust(request.tracker) && _Http_track(router, xhr, request.tracker.a);\n\n try {\n xhr.open(request.method, request.url, true);\n } catch (e) {\n return done($elm$http$Http$BadUrl_(request.url));\n }\n\n _Http_configureRequest(xhr, request);\n\n request.body.a && xhr.setRequestHeader('Content-Type', request.body.a);\n xhr.send(request.body.b);\n request.body.b xhr.send" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74550996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8583669/" ]
74,551,005
<pre><code>Does any one know how to create an array within an array in Data Factory. I need to make something like this. One Employee has multiple Customers, each Customer buys multiple products. Its coming from a flat file where Employee repeats multiple times once for each Customer then Customer repeats multiple times per Product. { &quot;employeeNumber&quot;: &quot;00001&quot;, &quot;employeeName&quot;: &quot;John Doe&quot;, &quot;customers&quot;: [ { &quot;id&quot;: &quot;99999&quot;, &quot;name&quot;: &quot;Jane Doe&quot;, &quot;products&quot;: [ { &quot;name&quot;: &quot;XYZ&quot;, &quot;price&quot;: 2.00 }, { &quot;name&quot;: &quot;ABC&quot;, &quot;price&quot;: 3.00 } ] }, { &quot;id&quot;: &quot;1111&quot;, &quot;name&quot;: &quot;John Smith&quot;, &quot;products&quot;: [ { &quot;name&quot;: &quot;RVS&quot;, &quot;price&quot;: 2.00 }, { &quot;name&quot;: &quot;GHI&quot;, &quot;price&quot;: 3.00 }, { &quot;name&quot;: &quot;QRS&quot;, &quot;price&quot;: 4.00 } ] } ] } </code></pre> <p>How to create a double nested Array -- Array within and Array from Flat Data in a Data Factory Dataflow. So much on how to &quot;flatten&quot; JSON to columns.. nothing on how to aggregate flat to &quot;Nested&quot; JSON in nested Arrays.</p> <p>I was able to get a Struct in a Derived Column to create an Array but I am struggling with how to create another array under the first Array.</p>
[ { "answer_id": 74551015, "author": "glennsl", "author_id": 7943564, "author_profile": "https://Stackoverflow.com/users/7943564", "pm_score": 3, "selected": false, "text": "GET GET GET" }, { "answer_id": 74577379, "author": "8n8", "author_id": 6629874, "author_profile": "https://Stackoverflow.com/users/6629874", "pm_score": 3, "selected": true, "text": "module Main exposing (main)\n\nimport Platform\nimport Http\n\nmain =\n Platform.worker\n { init = \\() -> ((), Http.request\n { method = \"GET\"\n , headers = []\n , url = \"https://catfact.ninja/fact\"\n , body = Http.stringBody \"text/plain\" \"hi\"\n , expect = Http.expectWhatever (\\_ -> ())\n , timeout = Nothing\n , tracker = Nothing\n })\n , update = \\() () -> ((), Cmd.none)\n , subscriptions = \\() -> Sub.none\n }\n index.html var xhr = new XMLHttpRequest();\n xhr.addEventListener('error', function() { done($elm$http$Http$NetworkError_); });\n xhr.addEventListener('timeout', function() { done($elm$http$Http$Timeout_); });\n xhr.addEventListener('load', function() { done(_Http_toResponse(request.expect.b, xhr)); });\n $elm$core$Maybe$isJust(request.tracker) && _Http_track(router, xhr, request.tracker.a);\n\n try {\n xhr.open(request.method, request.url, true);\n } catch (e) {\n return done($elm$http$Http$BadUrl_(request.url));\n }\n\n _Http_configureRequest(xhr, request);\n\n request.body.a && xhr.setRequestHeader('Content-Type', request.body.a);\n xhr.send(request.body.b);\n request.body.b xhr.send" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12608290/" ]
74,551,041
<p>I have recorded the macro below and I'd like it to work on all sheets / tables in the workbook. I've gathered that I need to replace &quot;ActiveWorkbook.Worksheets(&quot;Ramp&quot;)&quot; with &quot;ActiveWorkbook.ActiveSheet.ListObjects&quot; but I cannot figure how to get the sort to work.</p> <p>macro that works on the sheet which I recorded it on:</p> <pre><code>Sub GateSort() ' ' GateSort Macro ' Automatic sorting by Terminal &gt; Gate &gt; Subordinate value ' ' Keyboard Shortcut: Ctrl+Shift+G ' ActiveWorkbook.Worksheets(&quot;Ramp&quot;).ListObjects(&quot;Table1&quot;).Sort.SortFields.Clear ActiveWorkbook.Worksheets(&quot;Ramp&quot;).ListObjects(&quot;Table1&quot;).Sort.SortFields.Add2 _ Key:=Range(&quot;Table1[Sort Gate Leading]&quot;), SortOn:=xlSortOnValues, Order:= _ xlAscending, DataOption:=xlSortNormal ActiveWorkbook.Worksheets(&quot;Ramp&quot;).ListObjects(&quot;Table1&quot;).Sort.SortFields.Add2 _ Key:=Range(&quot;Table1[Sort Gate Number]&quot;), SortOn:=xlSortOnValues, Order:= _ xlAscending, DataOption:=xlSortNormal ActiveWorkbook.Worksheets(&quot;Ramp&quot;).ListObjects(&quot;Table1&quot;).Sort.SortFields.Add2 _ Key:=Range(&quot;Table1[Sort Gate Trailing]&quot;), SortOn:=xlSortOnValues, Order:= _ xlAscending, DataOption:=xlSortNormal With ActiveWorkbook.Worksheets(&quot;Ramp&quot;).ListObjects(&quot;Table1&quot;).Sort .Header = xlYes .MatchCase = False .Orientation = xlTopToBottom .SortMethod = xlPinYin .Apply End With End Sub </code></pre> <p>My current attempt:</p> <pre><code>Sub GateSort() ' ' GateSort Macro ' Automatic sorting by Terminal &gt; Gate &gt; Subordinate value ' ' Keyboard Shortcut: Ctrl+Shift+G ' tName = ActiveCell.ListObject.Name ActiveWorkbook.ActiveSheet.ListObjects(tName).Sort.SortFields.Clear ActiveWorkbook.ActiveSheet.ListObjects(tName).Sort.SortFields.Add2 _ Key:=Range(&quot;tName[Sort Gate Leading]&quot;), SortOn:=xlSortOnValues, Order:= _ xlAscending, DataOption:=xlSortNormal ActiveWorkbook.ActiveSheet.ListObjects(tName).Sort.SortFields.Add2 _ Key:=Range(&quot;tName[Sort Gate Number]&quot;), SortOn:=xlSortOnValues, Order:= _ xlAscending, DataOption:=xlSortNormal ActiveWorkbook.ActiveSheet.ListObjects(tName).Sort.SortFields.Add2 _ Key:=Range(&quot;tName[Sort Gate Trailing]&quot;), SortOn:=xlSortOnValues, Order:= _ xlAscending, DataOption:=xlSortNormal With ActiveWorkbook.ActiveSheet.ListObjects(tName).Sort .Header = xlYes .MatchCase = False .Orientation = xlTopToBottom .SortMethod = xlPinYin .Apply End With End Sub </code></pre> <p>I've been playing with variables as indicated above though I've not had success. This is all to avoid manually creating a multi-level sort when needed.</p>
[ { "answer_id": 74551015, "author": "glennsl", "author_id": 7943564, "author_profile": "https://Stackoverflow.com/users/7943564", "pm_score": 3, "selected": false, "text": "GET GET GET" }, { "answer_id": 74577379, "author": "8n8", "author_id": 6629874, "author_profile": "https://Stackoverflow.com/users/6629874", "pm_score": 3, "selected": true, "text": "module Main exposing (main)\n\nimport Platform\nimport Http\n\nmain =\n Platform.worker\n { init = \\() -> ((), Http.request\n { method = \"GET\"\n , headers = []\n , url = \"https://catfact.ninja/fact\"\n , body = Http.stringBody \"text/plain\" \"hi\"\n , expect = Http.expectWhatever (\\_ -> ())\n , timeout = Nothing\n , tracker = Nothing\n })\n , update = \\() () -> ((), Cmd.none)\n , subscriptions = \\() -> Sub.none\n }\n index.html var xhr = new XMLHttpRequest();\n xhr.addEventListener('error', function() { done($elm$http$Http$NetworkError_); });\n xhr.addEventListener('timeout', function() { done($elm$http$Http$Timeout_); });\n xhr.addEventListener('load', function() { done(_Http_toResponse(request.expect.b, xhr)); });\n $elm$core$Maybe$isJust(request.tracker) && _Http_track(router, xhr, request.tracker.a);\n\n try {\n xhr.open(request.method, request.url, true);\n } catch (e) {\n return done($elm$http$Http$BadUrl_(request.url));\n }\n\n _Http_configureRequest(xhr, request);\n\n request.body.a && xhr.setRequestHeader('Content-Type', request.body.a);\n xhr.send(request.body.b);\n request.body.b xhr.send" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5029603/" ]
74,551,043
<p>(Original problem description)</p> <p>Pair of points</p> <p>You are given the following</p> <p>An integer N</p> <p>A 2D array of length N denoting the points in the 2D coordinate system, that is (x, y)</p> <p>Task</p> <p>Determine the number of unordered pairs (i, j) or (j, i) and i != j such that</p> <p>The straight line connecting the points (A[i][1], A[i][2]) and (A[j][1], A[j][2]) passes through (0, 0)</p> <p>(Context, this was a coding problem on hacker earth site and I did solve it (bruteforce) method)</p> <p>My code:</p> <pre><code>def find_pairs(array, size): li = [] for i in range(size): for j in range(size): if (i, j) not in li and (j, i) not in li: if ((array[i][1] * (array[j][0] - array[i][0])) == ((array[i][0] * (array[j][1] - array[i][1]))): li.append((i,j)) return len(li) </code></pre> <p>The math the code uses is, given two points (x1, y1) and (x2, y2), their line passes through the origin if they satisfy the equation (x1 * (y2 - y1)) = (y1 * (x2 - x1))</p> <p>This code passed half the test cases (which were testing for correct answer) but failed the remaining which had time constraint. I tried to use itertools.combinations but it exceeded the memory limit</p> <p>Is there any way to write a program with less than N2 time complexity?</p>
[ { "answer_id": 74551371, "author": "Woodford", "author_id": 8451814, "author_profile": "https://Stackoverflow.com/users/8451814", "pm_score": 0, "selected": false, "text": "itertools.combinations itertools num_pairs = 0\nfor i, j in itertools.combinations(array, 2):\n if i_j_are_valid_points(): # your formula here\n num_pairs += 2 # (i, j) and (j, i) are both valid\n" }, { "answer_id": 74551515, "author": "Lakshya Khatri", "author_id": 14216315, "author_profile": "https://Stackoverflow.com/users/14216315", "pm_score": 1, "selected": false, "text": "def find_pairs(array, size):\n count = 0\n for i in range(size - 1):\n for j in range(i + 1, size):\n if ((array[i][1] * (array[j][0] - array[i][0])) == ((array[i][0] * (array[j][1] - array[i][1]))):\n count += 1\n return count\n" }, { "answer_id": 74551602, "author": "MBo", "author_id": 844416, "author_profile": "https://Stackoverflow.com/users/844416", "pm_score": 2, "selected": true, "text": "Counter n n*(n-1)/2 from collections import Counter\npts = [[1,0],[2,2],[-1,-1],[4,4],[0,2],[-2,0]]\nvert = 0\ncntr = Counter()\nfor p in pts:\n if p[0]:\n cntr[p[1]/p[0]] += 1\n else:\n vert += 1\nres = vert * (vert - 1) // 2\nfor v in cntr.values():\n res += v*(v-1) // 2\nprint(res) # 4 pairs\n from collections import Counter\npts = [[1,0],[2,2],[-1,-1],[4,4],[0,2],[-2,0],[0,0],[0,0]]\nvert = 0\nzeros = 0\ncntr = Counter()\nfor p in pts:\n if p[0]:\n cntr[p[1]/p[0]] += 1\n else:\n if p[1]:\n vert += 1\n else:\n zeros += 1\nres = vert * (vert - 1) // 2\nfor v in cntr.values():\n res += v*(v-1) // 2\nres += (len(pts) - zeros) * zeros + zeros*(zeros-1)//2\nprint(res) //17 pairs\n \n ( sign(x)*y/gcd(y,x), abs(x)/gcd(x,y) )" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11993580/" ]
74,551,056
<p>I want to make one plot with 3 scatterplots, but I have no idea how. I can plot them seperately as:</p> <pre><code>library(dplyr) library(ggplot2) kat %&gt;% filter(Sex %in% c(&quot;F&quot;)) %&gt;% ggplot(aes(x = Bwt, y = Hwt)) + geom_point() + facet_wrap(&quot;Sex&quot;) </code></pre> <p><img src="https://i.stack.imgur.com/L7ffx.png" alt="" /></p> <pre><code>kat %&gt;% filter(Sex %in% c(&quot;M&quot;)) %&gt;% ggplot(aes(x = Bwt, y = Hwt)) + geom_point() + facet_wrap(&quot;Sex&quot;) </code></pre> <p><img src="https://i.stack.imgur.com/ZwAUI.png" alt="" /></p> <pre><code>kat %&gt;% ggplot(aes(x = Bwt, y = Hwt)) + geom_point() + facet_wrap(&quot;Sex&quot;) </code></pre> <p><img src="https://i.stack.imgur.com/ZU5ox.png" alt="" /></p> <p>I have searched in previous Stack Overflow topics, but without any luck.</p>
[ { "answer_id": 74551178, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, "author_profile": "https://Stackoverflow.com/users/3358272", "pm_score": 2, "selected": false, "text": "library(dplyr)\nlibrary(ggplot2)\nmtcars %>%\n mutate(cyl = \"All\") %>%\n bind_rows(mutate(mtcars, cyl = as.character(cyl))) %>%\n ggplot(aes(mpg, disp)) +\n geom_point() +\n facet_wrap(~ cyl)\n mutate(mtcars, cyl=as.character(cyl)) cyl integer \"Sex\" character as.character factor \"All\"" }, { "answer_id": 74551889, "author": "MarBlo", "author_id": 4282026, "author_profile": "https://Stackoverflow.com/users/4282026", "pm_score": 1, "selected": true, "text": "patchwork library(MASS)\ndata(cats)\n\nlibrary(dplyr)\n\nlibrary(ggplot2)\nlibrary(patchwork)\n\np1 <- cats %>%\n filter(Sex %in% c(\"F\")) %>%\n ggplot(aes(x = Bwt, y = Hwt)) + geom_point() + facet_wrap(\"Sex\")\n\np2 <- cats %>%\n filter(Sex %in% c(\"M\")) %>%\n ggplot(aes(x = Bwt, y = Hwt)) + geom_point() + facet_wrap(\"Sex\")\n\np3 <- cats %>%\n ggplot(aes(x = Bwt, y = Hwt)) + geom_point() + facet_wrap(\"Sex\")\n\n\n(p1 | p2)/\n p3\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20314909/" ]
74,551,058
<p>Streamlit Version: 1.13.0</p> <p>in Homepage.py:</p> <pre><code>import streamlit as st st.set_page_config( page_title= &quot;Multipage App&quot;, page_icon=&quot;&quot;) st.title(&quot;Main Page&quot;) st.markdown('&lt;style&gt;div[class=&quot;css-6qob1r e1fqkh3o3&quot;] {color:black; font-weight: 900; background: url(&quot;https://media2.giphy.com/media/46hpy8xB3MiHfruixn/giphy.gif&quot;);background-repeat: no-repeat;background-size:350%;} &lt;/style&gt;', unsafe_allow_html=True) st.markdown('&lt;style&gt;div[class=&quot;css-y3drt2 e1fqkh3o5&quot;] {color:red; } &lt;/style&gt;', unsafe_allow_html=True)#NOT WORKING------------------------------------------- </code></pre> <p><a href="https://i.stack.imgur.com/zf1Dv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zf1Dv.png" alt="enter image description here" /></a></p> <p>I want to change the color, font, and position of the Homepage, Application, and Contact texts. How do I do this?</p>
[ { "answer_id": 74551178, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, "author_profile": "https://Stackoverflow.com/users/3358272", "pm_score": 2, "selected": false, "text": "library(dplyr)\nlibrary(ggplot2)\nmtcars %>%\n mutate(cyl = \"All\") %>%\n bind_rows(mutate(mtcars, cyl = as.character(cyl))) %>%\n ggplot(aes(mpg, disp)) +\n geom_point() +\n facet_wrap(~ cyl)\n mutate(mtcars, cyl=as.character(cyl)) cyl integer \"Sex\" character as.character factor \"All\"" }, { "answer_id": 74551889, "author": "MarBlo", "author_id": 4282026, "author_profile": "https://Stackoverflow.com/users/4282026", "pm_score": 1, "selected": true, "text": "patchwork library(MASS)\ndata(cats)\n\nlibrary(dplyr)\n\nlibrary(ggplot2)\nlibrary(patchwork)\n\np1 <- cats %>%\n filter(Sex %in% c(\"F\")) %>%\n ggplot(aes(x = Bwt, y = Hwt)) + geom_point() + facet_wrap(\"Sex\")\n\np2 <- cats %>%\n filter(Sex %in% c(\"M\")) %>%\n ggplot(aes(x = Bwt, y = Hwt)) + geom_point() + facet_wrap(\"Sex\")\n\np3 <- cats %>%\n ggplot(aes(x = Bwt, y = Hwt)) + geom_point() + facet_wrap(\"Sex\")\n\n\n(p1 | p2)/\n p3\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14178341/" ]
74,551,077
<p>I have the following association : <code>ProductsTable hasMany PhotosTable</code>.</p> <p>Furthermore, <code>ProductsTable</code> uses <code>Muffin/SlugBehavior</code> to build a unique slug.</p> <p>I need to automatically get <code>Photos</code> linked to <code>Products</code> each time I get a Product.</p> <p>So I use <code>contain()</code> in <code>ProductsTable::beforeFind()</code> because I want it to be independent of any <code>Controller</code>.</p> <p>Here is my <code>ProductsTable</code> :</p> <pre class="lang-php prettyprint-override"><code>// ProductsTable class ProductsTable extends Table { public function initialize(array $config): void { $this-&gt;hasMany('Photos'); $this-&gt;addBehavior('Muffin/Slug.Slug', [ 'displayField' =&gt; 'title', // 'title' is the field I want to build a unique slug from. ]); } public function beforeFind(Event $event, Query $query, ArrayObject $options, $primary) { $query-&gt;contain('Photos'); return $query; } } </code></pre> <p>In most cases it works well, but <strong>an issue happens when I try to create a Product with an already existing title (i.e with a slug that already exists)</strong>.</p> <p>I have the following <code>InvalidArgumentException</code> : Unable to load Photos association. Ensure foreign key in Products is selected. The exception is thrown in <code>Muffin/SlugBehavior::_uniqueSlug()</code> at the line <code>$this-&gt;_table-&gt;exists($conditions)</code>.</p> <p>I don't understand exactly what's the problem...</p> <p>Could anybody tell me how to fix it ?</p> <p><a href="https://i.stack.imgur.com/lcnLf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lcnLf.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74551178, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, "author_profile": "https://Stackoverflow.com/users/3358272", "pm_score": 2, "selected": false, "text": "library(dplyr)\nlibrary(ggplot2)\nmtcars %>%\n mutate(cyl = \"All\") %>%\n bind_rows(mutate(mtcars, cyl = as.character(cyl))) %>%\n ggplot(aes(mpg, disp)) +\n geom_point() +\n facet_wrap(~ cyl)\n mutate(mtcars, cyl=as.character(cyl)) cyl integer \"Sex\" character as.character factor \"All\"" }, { "answer_id": 74551889, "author": "MarBlo", "author_id": 4282026, "author_profile": "https://Stackoverflow.com/users/4282026", "pm_score": 1, "selected": true, "text": "patchwork library(MASS)\ndata(cats)\n\nlibrary(dplyr)\n\nlibrary(ggplot2)\nlibrary(patchwork)\n\np1 <- cats %>%\n filter(Sex %in% c(\"F\")) %>%\n ggplot(aes(x = Bwt, y = Hwt)) + geom_point() + facet_wrap(\"Sex\")\n\np2 <- cats %>%\n filter(Sex %in% c(\"M\")) %>%\n ggplot(aes(x = Bwt, y = Hwt)) + geom_point() + facet_wrap(\"Sex\")\n\np3 <- cats %>%\n ggplot(aes(x = Bwt, y = Hwt)) + geom_point() + facet_wrap(\"Sex\")\n\n\n(p1 | p2)/\n p3\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3045538/" ]
74,551,105
<p>I have collection: bookSchema as:</p> <pre><code>[ { _id: ObjectId(&quot;637d05dc32428ed75ea08d09&quot;), book_details: { book_name: &quot;random123&quot;, book_auth: &quot;Amber&quot; } }, { _id: ObjectId(&quot;637d0673ce0f17f6c473dee2&quot;), book_details: { book_name: &quot;random321&quot;, book_auth: &quot;Amber&quot; } }, { _id: ObjectId(&quot;637d069a3d597c8458ebe4ec&quot;), book_details: { book_name: &quot;random676&quot;, book_auth: &quot;Amber&quot; } }, { _id: ObjectId(&quot;637d06c05b32d503007bcb54&quot;), book_details: { book_name: &quot;random999&quot;, book_auth: &quot;Saurav&quot; } } ] </code></pre> <p>Desired O/P to show as:</p> <pre><code>{ score_ambr: 3, score_saurabh: 1 } </code></pre> <p>For this I tried as:</p> <pre><code>db.bookSchema.aggregate([ { &quot;$group&quot;: { &quot;_id&quot;: { &quot;$eq&quot;: [ &quot;$book_details.book_auth&quot;, &quot;Amber&quot; ] }, &quot;score_ambr&quot;: { &quot;$sum&quot;: 1 } }, }, { &quot;$group&quot;: { &quot;_id&quot;: { &quot;$eq&quot;: [ &quot;$book_details.book_auth&quot;, &quot;Saurav&quot; ] }, &quot;score_saurabh&quot;: { &quot;$sum&quot;: 1 } }, } ]) </code></pre> <p>I tried using $group to as I want to group all the matching documents in one and use $count to give the number of count for the matching documents but it doesn't seem to be working and gives the O/P as</p> <p>O/P:</p> <pre><code>[ { &quot;_id&quot;: false, &quot;score_sau&quot;: 2 } ] </code></pre> <p>MongoDB Playground: <a href="https://mongoplayground.net/p/cZ64KwAmwlv" rel="nofollow noreferrer">https://mongoplayground.net/p/cZ64KwAmwlv</a></p>
[ { "answer_id": 74551178, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, "author_profile": "https://Stackoverflow.com/users/3358272", "pm_score": 2, "selected": false, "text": "library(dplyr)\nlibrary(ggplot2)\nmtcars %>%\n mutate(cyl = \"All\") %>%\n bind_rows(mutate(mtcars, cyl = as.character(cyl))) %>%\n ggplot(aes(mpg, disp)) +\n geom_point() +\n facet_wrap(~ cyl)\n mutate(mtcars, cyl=as.character(cyl)) cyl integer \"Sex\" character as.character factor \"All\"" }, { "answer_id": 74551889, "author": "MarBlo", "author_id": 4282026, "author_profile": "https://Stackoverflow.com/users/4282026", "pm_score": 1, "selected": true, "text": "patchwork library(MASS)\ndata(cats)\n\nlibrary(dplyr)\n\nlibrary(ggplot2)\nlibrary(patchwork)\n\np1 <- cats %>%\n filter(Sex %in% c(\"F\")) %>%\n ggplot(aes(x = Bwt, y = Hwt)) + geom_point() + facet_wrap(\"Sex\")\n\np2 <- cats %>%\n filter(Sex %in% c(\"M\")) %>%\n ggplot(aes(x = Bwt, y = Hwt)) + geom_point() + facet_wrap(\"Sex\")\n\np3 <- cats %>%\n ggplot(aes(x = Bwt, y = Hwt)) + geom_point() + facet_wrap(\"Sex\")\n\n\n(p1 | p2)/\n p3\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15034865/" ]
74,551,109
<p>Imagine we are getting input from user as integer. I want my code to return minimum and maximum numbers in this integer value. For example, if user enters 56389, the code should display</p> <p>Minimum number: 3 Maximum number: 9</p> <p>If user enters single digit integer, let's say 7, the output should be:</p> <p>Minimum number: 7 Maximum number: 7</p> <p>I am trying to declare input as String instead of integer and compare all elements of the String with charAt(i) method. However, I cannot get the result.</p> <p>I would be glad if you can help me!</p>
[ { "answer_id": 74551462, "author": "bighugedev", "author_id": 17846993, "author_profile": "https://Stackoverflow.com/users/17846993", "pm_score": 0, "selected": false, "text": "charAt(int index) '0' '0' public static void main(String[] args) {\n char charNine = '9';\n int intNine = charNine - '0';\n System.out.println(intNine);\n}\n 9" }, { "answer_id": 74551521, "author": "programmerlife", "author_id": 20530585, "author_profile": "https://Stackoverflow.com/users/20530585", "pm_score": 1, "selected": false, "text": "int number = Integer.valueOf(input);\nint largest = 0;\nint smallest = 9;\n\nwhile(number != 0)\n{\n int rem = number % 10;\n largest = Math.max(rem, largest);\n smallest = Math.min(rem, smallest);\n number = number / 10;\n}\nSystem.out.println(largest + \" \" + smallest);\n" }, { "answer_id": 74551677, "author": "Ronak Jain", "author_id": 2718939, "author_profile": "https://Stackoverflow.com/users/2718939", "pm_score": 1, "selected": false, "text": "int[] getLargestAndSmallestDigits(String in){\n int n = Integer.valueOf(in);\n if (n==0) {\n return new int[]{0,0};\n }\n int[] ans = {0,9};\n \n while(n != 0)\n {\n int r = n % 10;\n ans[0] = Math.min(r, ans[0]);\n ans[1] = Math.max(r, ans[0]);\n n = n / 10;\n }\n return ans;\n}\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7122460/" ]
74,551,120
<p>Because a table is worth a thousand words, here what I would like to do:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Column A</th> <th>Column B</th> <th>Column C</th> <th>Column D</th> </tr> </thead> <tbody> <tr> <td>AMY</td> <td>1.5</td> <td>x1</td> <td>y1</td> </tr> <tr> <td>STR</td> <td>2</td> <td>x2</td> <td>y2</td> </tr> <tr> <td>AMY</td> <td>4.5</td> <td>x2</td> <td>y3</td> </tr> <tr> <td>STR</td> <td>3</td> <td>x3</td> <td>y4</td> </tr> </tbody> </table> </div> <p>I would like to reunite all data from Column B in a Column depending on their value of Column A. And each Value of column A form a column Name. This, in a new dataframe.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>AMY</th> <th>STR</th> </tr> </thead> <tbody> <tr> <td>1.5</td> <td>2</td> </tr> <tr> <td>4.5</td> <td>3</td> </tr> </tbody> </table> </div> <p>Thanks a lot !</p> <p>I tried to make it using gather() and unite(), but it didnt give me the result i was expected.</p>
[ { "answer_id": 74551462, "author": "bighugedev", "author_id": 17846993, "author_profile": "https://Stackoverflow.com/users/17846993", "pm_score": 0, "selected": false, "text": "charAt(int index) '0' '0' public static void main(String[] args) {\n char charNine = '9';\n int intNine = charNine - '0';\n System.out.println(intNine);\n}\n 9" }, { "answer_id": 74551521, "author": "programmerlife", "author_id": 20530585, "author_profile": "https://Stackoverflow.com/users/20530585", "pm_score": 1, "selected": false, "text": "int number = Integer.valueOf(input);\nint largest = 0;\nint smallest = 9;\n\nwhile(number != 0)\n{\n int rem = number % 10;\n largest = Math.max(rem, largest);\n smallest = Math.min(rem, smallest);\n number = number / 10;\n}\nSystem.out.println(largest + \" \" + smallest);\n" }, { "answer_id": 74551677, "author": "Ronak Jain", "author_id": 2718939, "author_profile": "https://Stackoverflow.com/users/2718939", "pm_score": 1, "selected": false, "text": "int[] getLargestAndSmallestDigits(String in){\n int n = Integer.valueOf(in);\n if (n==0) {\n return new int[]{0,0};\n }\n int[] ans = {0,9};\n \n while(n != 0)\n {\n int r = n % 10;\n ans[0] = Math.min(r, ans[0]);\n ans[1] = Math.max(r, ans[0]);\n n = n / 10;\n }\n return ans;\n}\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20584213/" ]
74,551,122
<p>I have a dataframe similar to below-given dataframe. I need to add a value in <strong>Validated</strong> column that matches the below condition: If there are multiple rows with the same values in State, ColorName, and Code columns then at least one row should contain a positive value in the Value column. If there is no row with a positive value in Value column, I need to add &quot;Invalid&quot; in the Validated column for all the matching rows.Is there a way I can do it without iterating over each row?</p> <pre><code>State ColorName Code Value Validated Arizona Yellow A 50 Alabama Orange A 150 Arkansas Red B -500 Kentuky Green M -40 Ohio Blue X 100 Alabama Orange A -30 Arizona Yellow A 100 California Blue C 100 California Blue C -100 Arkansas Red B 500 Ohio Yellow X 100 California Blue C 100 </code></pre>
[ { "answer_id": 74551267, "author": "Алексей Р", "author_id": 15035314, "author_profile": "https://Stackoverflow.com/users/15035314", "pm_score": 1, "selected": false, "text": "df = pd.DataFrame({'State': ['Arizona', 'Alabama', 'Arkansas', 'Kentuky', 'Ohio', 'Alabama', 'Arizona', 'California',\n 'California', 'Arkansas', 'Ohio', 'California'],\n 'ColorName': ['Yellow', 'Orange', 'Red', 'Green', 'Blue', 'Orange', 'Yellow', 'Blue', 'Blue', 'Red',\n 'Yellow', 'Blue'],\n 'Code': ['A', 'A', 'B', 'M', 'X', 'A', 'A', 'C', 'C', 'B', 'X', 'C'],\n 'Value': [50, 150, -500, -40, 100, -30, 100, 100, -100, 500, 100, 100]})\n\ndf['Validated'] = df.groupby(['State', 'ColorName', 'Code'])['Value'].transform(lambda x: 'Valid' if x.shape[0] > 1 and x.max() > 0 else 'Invalid')\nprint(df)\n State ColorName Code Value Validated\n0 Arizona Yellow A 50 Valid\n1 Alabama Orange A 150 Valid\n2 Arkansas Red B -500 Valid\n3 Kentuky Green M -40 Invalid\n4 Ohio Blue X 100 Invalid\n5 Alabama Orange A -30 Valid\n6 Arizona Yellow A 100 Valid\n7 California Blue C 100 Valid\n8 California Blue C -100 Valid\n9 Arkansas Red B 500 Valid\n10 Ohio Yellow X 100 Invalid\n11 California Blue C 100 Valid\n" }, { "answer_id": 74551360, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 0, "selected": false, "text": "g = (df.assign(flag=df['Value'].gt(0))\n .groupby(['State', 'ColorName', 'Code'])\n )\n\nm1 = g.transform('size').gt(1)\nm2 = g['flag'].transform('any')\n\ndf['Validated'] = np.where(m1&m2, 'Valid', 'Invalid')\n State ColorName Code Value Validated\n0 Arizona Yellow A 50 Valid\n1 Alabama Orange A 150 Valid\n2 Arkansas Red B -500 Valid\n3 Kentuky Green M -40 Invalid\n4 Ohio Blue X 100 Invalid\n5 Alabama Orange A -30 Valid\n6 Arizona Yellow A 100 Valid\n7 California Blue C 100 Valid\n8 California Blue C -100 Valid\n9 Arkansas Red B 500 Valid\n10 Ohio Yellow X 100 Invalid\n11 California Blue C 100 Valid\n df['Validated'] = np.where(m2, 'Valid', 'Invalid')\n State ColorName Code Value Validated\n0 Arizona Yellow A 50 Valid\n1 Alabama Orange A 150 Valid\n2 Arkansas Red B -500 Valid\n3 Kentuky Green M -40 Invalid\n4 Ohio Blue X 100 Valid\n5 Alabama Orange A -30 Valid\n6 Arizona Yellow A 100 Valid\n7 California Blue C 100 Valid\n8 California Blue C -100 Valid\n9 Arkansas Red B 500 Valid\n10 Ohio Yellow X 100 Valid\n11 California Blue C 100 Valid\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7311043/" ]
74,551,134
<p>I'm currently learning angular and how to share data between components. I understand the basic idea of parent and child component but not sure how to identify if a component is a parent or child. And whether or not if there are multiple parent components or each angular application only have one parent component and the rest is child component. I tried researching on google and watch some youtube tutorials but none seems to answer my question.</p>
[ { "answer_id": 74551267, "author": "Алексей Р", "author_id": 15035314, "author_profile": "https://Stackoverflow.com/users/15035314", "pm_score": 1, "selected": false, "text": "df = pd.DataFrame({'State': ['Arizona', 'Alabama', 'Arkansas', 'Kentuky', 'Ohio', 'Alabama', 'Arizona', 'California',\n 'California', 'Arkansas', 'Ohio', 'California'],\n 'ColorName': ['Yellow', 'Orange', 'Red', 'Green', 'Blue', 'Orange', 'Yellow', 'Blue', 'Blue', 'Red',\n 'Yellow', 'Blue'],\n 'Code': ['A', 'A', 'B', 'M', 'X', 'A', 'A', 'C', 'C', 'B', 'X', 'C'],\n 'Value': [50, 150, -500, -40, 100, -30, 100, 100, -100, 500, 100, 100]})\n\ndf['Validated'] = df.groupby(['State', 'ColorName', 'Code'])['Value'].transform(lambda x: 'Valid' if x.shape[0] > 1 and x.max() > 0 else 'Invalid')\nprint(df)\n State ColorName Code Value Validated\n0 Arizona Yellow A 50 Valid\n1 Alabama Orange A 150 Valid\n2 Arkansas Red B -500 Valid\n3 Kentuky Green M -40 Invalid\n4 Ohio Blue X 100 Invalid\n5 Alabama Orange A -30 Valid\n6 Arizona Yellow A 100 Valid\n7 California Blue C 100 Valid\n8 California Blue C -100 Valid\n9 Arkansas Red B 500 Valid\n10 Ohio Yellow X 100 Invalid\n11 California Blue C 100 Valid\n" }, { "answer_id": 74551360, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 0, "selected": false, "text": "g = (df.assign(flag=df['Value'].gt(0))\n .groupby(['State', 'ColorName', 'Code'])\n )\n\nm1 = g.transform('size').gt(1)\nm2 = g['flag'].transform('any')\n\ndf['Validated'] = np.where(m1&m2, 'Valid', 'Invalid')\n State ColorName Code Value Validated\n0 Arizona Yellow A 50 Valid\n1 Alabama Orange A 150 Valid\n2 Arkansas Red B -500 Valid\n3 Kentuky Green M -40 Invalid\n4 Ohio Blue X 100 Invalid\n5 Alabama Orange A -30 Valid\n6 Arizona Yellow A 100 Valid\n7 California Blue C 100 Valid\n8 California Blue C -100 Valid\n9 Arkansas Red B 500 Valid\n10 Ohio Yellow X 100 Invalid\n11 California Blue C 100 Valid\n df['Validated'] = np.where(m2, 'Valid', 'Invalid')\n State ColorName Code Value Validated\n0 Arizona Yellow A 50 Valid\n1 Alabama Orange A 150 Valid\n2 Arkansas Red B -500 Valid\n3 Kentuky Green M -40 Invalid\n4 Ohio Blue X 100 Valid\n5 Alabama Orange A -30 Valid\n6 Arizona Yellow A 100 Valid\n7 California Blue C 100 Valid\n8 California Blue C -100 Valid\n9 Arkansas Red B 500 Valid\n10 Ohio Yellow X 100 Valid\n11 California Blue C 100 Valid\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20584338/" ]
74,551,142
<p>I have to answer this in Visual Basic.I actually don't have any idea how to solve this, our teacher barely teaches us practical stuff. I have to submit this assignment by today too.</p> <p>I have tried to do solve it and searched the internet for it, but I could barely understand it.</p>
[ { "answer_id": 74551679, "author": "Jonathan Barraone", "author_id": 17957703, "author_profile": "https://Stackoverflow.com/users/17957703", "pm_score": 1, "selected": false, "text": "Public Sub AddTwoNumbers()\n Dim FirstNumber As String = Convert.toInt32(InputBox(\"Enter the first number.\")) 'Get the first number\n Dim SecondNumber As String = Convert.toInt32InputBox(\"Enter the second number.\")) 'Get the second number\n Dim Result As Integer = 0 'Used to store the result in\n 'Now perform the calculation.\n Result = FirstNumber + SecondNumber\n 'Then show the result in a MessageBox\n MessageBox.Show(\"The result is: \" & Result.ToString())\nEnd Sub\n" }, { "answer_id": 74554334, "author": "Idle_Mind", "author_id": 2330053, "author_profile": "https://Stackoverflow.com/users/2330053", "pm_score": 1, "selected": true, "text": "Dim value1, value2 As Integer\nDim response As String = InputBox(\"Enter first Integer:\")\nIf Integer.TryParse(response, value1) Then\n response = InputBox(\"Enter second Integer:\")\n If Integer.TryParse(response, value2) Then\n Dim sum As Integer = value1 + value2\n MessageBox.Show(\"The sum of \" & value1 & \" and \" & value2 & \" is \" & sum)\n Else\n MessageBox.Show(response & \" is not a valid Integer!\")\n End If\nElse\n MessageBox.Show(response & \" is not a valid Integer!\")\nEnd If\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20584365/" ]
74,551,170
<p>I have multiple slide decks with pictures that are too big (in pixels / resolution). I can use PowerPoint's &quot;Compress Pictures&quot; function to reduce the resolution, but there is not one single resolution that would suit all images (e.g. photos could go with 96 ppi E-mail resolution, while screenshots would require 220 ppi Print resolution). For that reason, I cannot simply apply one resolution to all pictures (by deselecting the &quot;Apply only to this picture&quot; checkbox).</p> <p>So I would fancy a macro that steps through all pictures in the slide deck, and for each picture offers the user to select the resolution for compression (with a default set to 150 ppi Web, which suits most cases).</p> <p>I was thinking of a code like this:</p> <pre><code>Sub Compress_Pictures_one_by_one() Dim shp As Shape Dim sld As Slide 'Loop through each slide in ActivePresentation: For Each sld In ActivePresentation.Slides 'Loop through each shape on the slide: For Each shp In sld.Shapes If shp.Type = msoPicture Then shp.Select 'Show the Compress Pictures&quot; dialog: Application.CommandBars.ExecuteMso &quot;PicturesCompress&quot; 'Preselect Web resolution: SendKeys &quot;%W&quot;, True End If Next shp Next sld End Sub </code></pre> <p>However, this does not wait for the user to complete the dialog (with OK or Cancel) before moving on to the next picture.</p> <p>Any idea how to solve? Or got any alternatives?</p>
[ { "answer_id": 74555234, "author": "wrbp", "author_id": 16662333, "author_profile": "https://Stackoverflow.com/users/16662333", "pm_score": 3, "selected": true, "text": "Declare PtrSafe Function FindWindow Lib \"user32\" Alias _\n\"FindWindowA\" (ByVal wClassName As Any, ByVal _\nwWindowName As Any) As LongPtr\nSub Compress_Pictures_one_by_one()\n\nDim shp As Shape\nDim sld As Slide\n\n'Loop through each slide in ActivePresentation:\nFor Each sld In ActivePresentation.Slides\n 'Loop through each shape on the slide:\n For Each shp In sld.Shapes\n If shp.Type = msoPicture Then\n shp.Select\n 'Show the Compress Pictures\" dialog:\n\n Application.CommandBars.ExecuteMso \"PicturesCompress\"\n 'Preselect Web resolution:\n SendKeys \"%W\", True\n While testDialogOpen\n DoEvents\n Wend\n End If\n Next shp\n Next sld\nEnd Sub\n\nFunction testDialogOpen()\n Dim wHandle As LongPtr\n Dim wName As String\n\n wName = \"Compress Pictures\"\n wHandle = FindWindow(0&, wName)\n If wHandle = 0 Then\n testDialogOpen = False\n Else\n testDialogOpen = True\n End If\nEnd Function\n\n" }, { "answer_id": 74560584, "author": "Dirk Hafke", "author_id": 19976007, "author_profile": "https://Stackoverflow.com/users/19976007", "pm_score": 1, "selected": false, "text": "Declare PtrSafe Function FindWindow Lib \"user32\" Alias _\n\"FindWindowA\" (ByVal wClassName As Any, ByVal _\nwWindowName As Any) As LongPtr\n\n\nSub Compress_Pictures_one_by_one()\n \n Dim shp As Shape\n Dim sld As Slide\n Dim intCounter As Integer\n Dim blnNext As Boolean\n \n 'Intro:\n If MsgBox(\"This procedure will loop through all pictures in you slide deck. \" _\n & \"For each picture it will offer you to select a compression. \" _\n & \"If you do not want to change the compression of a picture, hit the Cancel button in the Compress Pictures dialog. \" & vbCr _\n & \"After each compression setting you'll be asked whether to keep the compression setting and move on to the next picture, \" _\n & \"or to re-choose a compression for the current picture, or to stop processing. \", _\n vbInformation + vbOKCancel, \"Introduction\") = vbCancel Then Exit Sub\n \n intCounter = 0\n \n 'Loop through each slide in ActivePresentation:\n For Each sld In ActivePresentation.Slides\n 'Loop through each shape on the slide:\n For Each shp In sld.Shapes\n If shp.Type = msoPicture Then\n intCounter = intCounter + 1\n ActiveWindow.View.GotoSlide sld.SlideIndex\n shp.Select\n 'MsgBox \"Picture format: \" & shp.PictureFormat\n Do\n 'Show the Compress Pictures\" dialog:\n Application.CommandBars.ExecuteMso \"PicturesCompress\"\n 'Preselect Web resolution:\n SendKeys \"%W\", True\n While testDialogOpen\n DoEvents\n Wend\n 'Have user verify the compression result and choose how to proceed:\n Select Case MsgBox(\"Move to the next picture?\" & vbCr _\n & \"Yes: Continue with next picture.\" & vbCr _\n & \"No: Re-choose a setting for the current picture.\" & vbCr _\n & \"Cancel: Stop processing any further pictures.\", _\n vbYesNoCancel + vbQuestion, _\n \"Continue?\")\n Case vbYes\n blnNext = True\n Case vbNo\n blnNext = False\n Case vbCancel\n If MsgBox(\"You are about to cancel the task. \" & vbCr _\n & intCounter & \" picture\" & IIf(intCounter = 1, \" has\", \"s have\") & \" been touched.\" & vbCr _\n & \"No further pictures will be processed.\" & vbCr _\n & \"Are you sure you want to stop?\", _\n vbCritical + vbYesNo, \"Cancel?\") _\n = vbYes Then Exit Sub\n End Select\n Loop Until blnNext\n End If\n Next shp\n Next sld\n \n 'Finish:\n If intCounter = 0 Then\n MsgBox \"No pictures have been detected in your slides.\", vbInformation + vbOKOnly\n Else\n MsgBox \"Task completed. \" & vbCr & intCounter & \" picture\" & IIf(intCounter = 1, \" has\", \"s have\") & \" been touched.\", vbInformation, \"Compress Pictures\"\n End If\n \nEnd Sub\n\nFunction testDialogOpen()\n\n Dim wHandle As LongPtr\n Dim wName As String\n\n wName = \"Compress Pictures\"\n wHandle = FindWindow(0&, wName)\n If wHandle = 0 Then\n testDialogOpen = False\n Else\n testDialogOpen = True\n End If\n \nEnd Function\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19976007/" ]
74,551,266
<p>I have a MySQLdump generated by PHPMyAdmin, and I need to import it into a Postgresql database, but I dont know if it's even possible. I've seen people recommending pgloader but seens a little confusing on how to do it. Also I'm on windows if its relevant at all.</p> <p>I only need the tables, so I'm not concerned about the data in the old or in the new database.</p> <p>It's not that big too, only 84 tables. But big enough for me to write it.</p> <p>Thank you!</p>
[ { "answer_id": 74555234, "author": "wrbp", "author_id": 16662333, "author_profile": "https://Stackoverflow.com/users/16662333", "pm_score": 3, "selected": true, "text": "Declare PtrSafe Function FindWindow Lib \"user32\" Alias _\n\"FindWindowA\" (ByVal wClassName As Any, ByVal _\nwWindowName As Any) As LongPtr\nSub Compress_Pictures_one_by_one()\n\nDim shp As Shape\nDim sld As Slide\n\n'Loop through each slide in ActivePresentation:\nFor Each sld In ActivePresentation.Slides\n 'Loop through each shape on the slide:\n For Each shp In sld.Shapes\n If shp.Type = msoPicture Then\n shp.Select\n 'Show the Compress Pictures\" dialog:\n\n Application.CommandBars.ExecuteMso \"PicturesCompress\"\n 'Preselect Web resolution:\n SendKeys \"%W\", True\n While testDialogOpen\n DoEvents\n Wend\n End If\n Next shp\n Next sld\nEnd Sub\n\nFunction testDialogOpen()\n Dim wHandle As LongPtr\n Dim wName As String\n\n wName = \"Compress Pictures\"\n wHandle = FindWindow(0&, wName)\n If wHandle = 0 Then\n testDialogOpen = False\n Else\n testDialogOpen = True\n End If\nEnd Function\n\n" }, { "answer_id": 74560584, "author": "Dirk Hafke", "author_id": 19976007, "author_profile": "https://Stackoverflow.com/users/19976007", "pm_score": 1, "selected": false, "text": "Declare PtrSafe Function FindWindow Lib \"user32\" Alias _\n\"FindWindowA\" (ByVal wClassName As Any, ByVal _\nwWindowName As Any) As LongPtr\n\n\nSub Compress_Pictures_one_by_one()\n \n Dim shp As Shape\n Dim sld As Slide\n Dim intCounter As Integer\n Dim blnNext As Boolean\n \n 'Intro:\n If MsgBox(\"This procedure will loop through all pictures in you slide deck. \" _\n & \"For each picture it will offer you to select a compression. \" _\n & \"If you do not want to change the compression of a picture, hit the Cancel button in the Compress Pictures dialog. \" & vbCr _\n & \"After each compression setting you'll be asked whether to keep the compression setting and move on to the next picture, \" _\n & \"or to re-choose a compression for the current picture, or to stop processing. \", _\n vbInformation + vbOKCancel, \"Introduction\") = vbCancel Then Exit Sub\n \n intCounter = 0\n \n 'Loop through each slide in ActivePresentation:\n For Each sld In ActivePresentation.Slides\n 'Loop through each shape on the slide:\n For Each shp In sld.Shapes\n If shp.Type = msoPicture Then\n intCounter = intCounter + 1\n ActiveWindow.View.GotoSlide sld.SlideIndex\n shp.Select\n 'MsgBox \"Picture format: \" & shp.PictureFormat\n Do\n 'Show the Compress Pictures\" dialog:\n Application.CommandBars.ExecuteMso \"PicturesCompress\"\n 'Preselect Web resolution:\n SendKeys \"%W\", True\n While testDialogOpen\n DoEvents\n Wend\n 'Have user verify the compression result and choose how to proceed:\n Select Case MsgBox(\"Move to the next picture?\" & vbCr _\n & \"Yes: Continue with next picture.\" & vbCr _\n & \"No: Re-choose a setting for the current picture.\" & vbCr _\n & \"Cancel: Stop processing any further pictures.\", _\n vbYesNoCancel + vbQuestion, _\n \"Continue?\")\n Case vbYes\n blnNext = True\n Case vbNo\n blnNext = False\n Case vbCancel\n If MsgBox(\"You are about to cancel the task. \" & vbCr _\n & intCounter & \" picture\" & IIf(intCounter = 1, \" has\", \"s have\") & \" been touched.\" & vbCr _\n & \"No further pictures will be processed.\" & vbCr _\n & \"Are you sure you want to stop?\", _\n vbCritical + vbYesNo, \"Cancel?\") _\n = vbYes Then Exit Sub\n End Select\n Loop Until blnNext\n End If\n Next shp\n Next sld\n \n 'Finish:\n If intCounter = 0 Then\n MsgBox \"No pictures have been detected in your slides.\", vbInformation + vbOKOnly\n Else\n MsgBox \"Task completed. \" & vbCr & intCounter & \" picture\" & IIf(intCounter = 1, \" has\", \"s have\") & \" been touched.\", vbInformation, \"Compress Pictures\"\n End If\n \nEnd Sub\n\nFunction testDialogOpen()\n\n Dim wHandle As LongPtr\n Dim wName As String\n\n wName = \"Compress Pictures\"\n wHandle = FindWindow(0&, wName)\n If wHandle = 0 Then\n testDialogOpen = False\n Else\n testDialogOpen = True\n End If\n \nEnd Function\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20399210/" ]
74,551,280
<p>I am a beginner in Haskell. I am facing the error that's in the heading. Below is my Haskell code.</p> <pre><code>member atm lizt = if null lizt then False else if atm == head lizt then True else member(atm (tail lizt)) main = print(member 1 [2, 1]) </code></pre> <p>The error message</p> <pre class="lang-none prettyprint-override"><code> GHCi, version 8.10.6: https://www.haskell.org/ghc/ :? for help Loaded GHCi configuration from /home/runner/member/.ghci [1 of 1] Compiling Main ( Main.hs, interpreted ) Main.hs:1:1: error: • Couldn't match type ‘[t0 -&gt; t] -&gt; Bool’ with ‘Bool’ Expected type: t -&gt; Bool Actual type: (t0 -&gt; t) -&gt; [t0 -&gt; t] -&gt; Bool • Relevant bindings include member :: t -&gt; Bool (bound at Main.hs:1:1) | 1 | member atm lizt = if null lizt | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^... Main.hs:5:14: error: • Couldn't match expected type ‘[a1] -&gt; a0’ with actual type ‘Bool’ • The function ‘member’ is applied to two arguments, but its type ‘t1 -&gt; Bool’ has only one In the first argument of ‘print’, namely ‘(member 1 [2, 1])’ In the expression: print (member 1 [2, 1]) | 5 | main = print(member 1 [2, 1]) | ^^^^^^^^^^^^^^^ Failed, no modules loaded.  &lt;interactive&gt;:1:1: error: • Variable not in scope: main • Perhaps you meant ‘min’ (imported from Prelude)  ^C Leaving GHCi. repl process died unexpectedly: GHCi, version 8.10.6: https://www.haskell.org/ghc/ :? for help Loaded GHCi configuration from /home/runner/member/.ghci </code></pre> <p>I am trying to print true if the given integer(atm in my case) is present in the given list else false. The code is working(justing checking with the first element of the list) before I add recursion call.</p>
[ { "answer_id": 74551385, "author": "Wheat Wizard", "author_id": 4040600, "author_profile": "https://Stackoverflow.com/users/4040600", "pm_score": 3, "selected": true, "text": "member member atm (tail lizt) member(atm (tail lizt)) atm (tail lizt) atm tail lizt atm member atm tail lizt member member :: Eq a => a -> [a] -> Bool\n • Couldn't match expected type ‘Bool’\n with actual type ‘[a0] -> Bool’\n • Probable cause: ‘member’ is applied to too few arguments\n In the expression: member (atm (tail lizt))\n In the expression:\n if atm == head lizt then True else member (atm (tail lizt))\n In the expression:\n if null lizt then\n False\n else\n if atm == head lizt then True else member (atm (tail lizt))\n |\n4 | else if atm == head lizt then True else member(atm (tail lizt))\n | ^^^^^^^^^^^^\n" }, { "answer_id": 74552736, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 1, "selected": false, "text": "head lizt null head tail member _ [] = False\nmember atm (hd:tl) \n | atm == hd = True\n | otherwise = member atm tl\n elem member atm lizt = \n if null lizt then False\n else if atm == head lizt then True \n else member atm (tail lizt)\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14930767/" ]
74,551,344
<pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: organization-deployment labels: app: organization spec: selector: matchLabels: app: organization template: metadata: labels: app: organization spec: containers: - name: organization-container image: test.azurecr.io/organizationservice:latest ports: - containerPort: 9080 imagePullSecrets: - name: guidesecret # service type loadbalancer --- apiVersion: v1 kind: Service metadata: name: organization-service spec: type: LoadBalancer selector: app: organization ports: - protocol: TCP port: 9080 targetPort: 9080 </code></pre> <p>Here is my deployment.yaml file for AKS but i am unable to access pod using external ip with the port 9080.</p> <p>Can anyone suggest how to access the pod using external ip and anyone review my Deployment file if it's fine how to access pod using external ip?</p> <p><a href="https://i.stack.imgur.com/toDFR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/toDFR.png" alt="kubectl get svc" /></a></p> <p><a href="https://i.stack.imgur.com/uHVVa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uHVVa.png" alt="kubectl describe svc" /></a></p>
[ { "answer_id": 74551385, "author": "Wheat Wizard", "author_id": 4040600, "author_profile": "https://Stackoverflow.com/users/4040600", "pm_score": 3, "selected": true, "text": "member member atm (tail lizt) member(atm (tail lizt)) atm (tail lizt) atm tail lizt atm member atm tail lizt member member :: Eq a => a -> [a] -> Bool\n • Couldn't match expected type ‘Bool’\n with actual type ‘[a0] -> Bool’\n • Probable cause: ‘member’ is applied to too few arguments\n In the expression: member (atm (tail lizt))\n In the expression:\n if atm == head lizt then True else member (atm (tail lizt))\n In the expression:\n if null lizt then\n False\n else\n if atm == head lizt then True else member (atm (tail lizt))\n |\n4 | else if atm == head lizt then True else member(atm (tail lizt))\n | ^^^^^^^^^^^^\n" }, { "answer_id": 74552736, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 1, "selected": false, "text": "head lizt null head tail member _ [] = False\nmember atm (hd:tl) \n | atm == hd = True\n | otherwise = member atm tl\n elem member atm lizt = \n if null lizt then False\n else if atm == head lizt then True \n else member atm (tail lizt)\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8598874/" ]
74,551,394
<p>I am running an <code>express</code>/node application and am documenting my api using <code>&quot;swagger-ui-express&quot;: &quot;^4.5.0&quot;,</code>. I have set up a requirement of needing a <code>jsonwebtoken</code> bearer token to be sent with all requests to any endpoint in my api.</p> <p>I have the swagger docs loaded and working properly but now when trying to figure out how to pass the <code>Authorization: Bearer &lt;token&gt;</code> to all my endpoints, it doesn't seem to work. I am able to add the <code>securitySchemes</code> + child options and I get the green <code>Authorize</code> button in my swagger docs, but when I enter a bearer token and send off the request the loading spinner keeps spinning and never sends the request. I have <code>morgan</code> logging set up in my app so I can see that the request to my endpoint never gets sent or logged.</p> <p>How do I send a bearer token to requests sent from swagger UI?</p> <p>In app.js I have this route which loads properly in localhost</p> <pre><code>// Single entry point for swagger docs router.use( '/swaggerDocs', swaggerDoc.serve, swaggerDoc.setup(swaggerDocumentation), ); </code></pre> <p><code>swaggerDocumentation</code> from above snippet (config file).</p> <pre><code>import getCountryRegions from './getCountryRegions.doc.js'; export default { openapi: '3.0.3', info: { title: 'Node/express rest api app', version: '0.0.1', }, components: { securitySchemes: { bearerAuth: { type: 'http', in: 'header', name: 'Authorization', description: 'Bearer Token', scheme: 'bearer', bearerFormat: 'JWT', }, }, }, security: { bearerAuth: [], }, servers: [ { url: 'http://localhost:3010/api', description: 'Local server', }, ], paths: { ...getCountryRegions, }, }; </code></pre> <p>Modal to enter bearer token <a href="https://i.stack.imgur.com/Dy1py.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Dy1py.png" alt="enter image description here" /></a></p> <p>Adding token <a href="https://i.stack.imgur.com/UyOV1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UyOV1.png" alt="enter image description here" /></a></p> <p>Request is sent but it spins endlessly without ever sending the request <a href="https://i.stack.imgur.com/BNOrT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BNOrT.png" alt="enter image description here" /></a></p> <p>No errros in my application terminal or logging but I do see one error in the chrome browser console when sending the request: <a href="https://i.stack.imgur.com/iynlL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iynlL.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74551385, "author": "Wheat Wizard", "author_id": 4040600, "author_profile": "https://Stackoverflow.com/users/4040600", "pm_score": 3, "selected": true, "text": "member member atm (tail lizt) member(atm (tail lizt)) atm (tail lizt) atm tail lizt atm member atm tail lizt member member :: Eq a => a -> [a] -> Bool\n • Couldn't match expected type ‘Bool’\n with actual type ‘[a0] -> Bool’\n • Probable cause: ‘member’ is applied to too few arguments\n In the expression: member (atm (tail lizt))\n In the expression:\n if atm == head lizt then True else member (atm (tail lizt))\n In the expression:\n if null lizt then\n False\n else\n if atm == head lizt then True else member (atm (tail lizt))\n |\n4 | else if atm == head lizt then True else member(atm (tail lizt))\n | ^^^^^^^^^^^^\n" }, { "answer_id": 74552736, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 1, "selected": false, "text": "head lizt null head tail member _ [] = False\nmember atm (hd:tl) \n | atm == hd = True\n | otherwise = member atm tl\n elem member atm lizt = \n if null lizt then False\n else if atm == head lizt then True \n else member atm (tail lizt)\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10152171/" ]
74,551,419
<p>I have a table which records the number of times a user logs into a page, but I am trying to filter out where the user has logged in at least twice throughout the week</p> <p>Here is the table below</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>User</th> <th>Monday</th> <th>Tuesday</th> <th>Wednesday</th> <th>Thursday</th> <th>Friday</th> <th>Total</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>1</td> <td>3</td> <td>4</td> <td>6</td> <td>1</td> <td>15</td> </tr> <tr> <td>B</td> <td>0</td> <td>0</td> <td>20</td> <td>0</td> <td>0</td> <td>20</td> </tr> <tr> <td>C</td> <td>18</td> <td>1</td> <td>0</td> <td>18</td> <td>1</td> <td>38</td> </tr> <tr> <td>D</td> <td>0</td> <td>2</td> <td>0</td> <td>0</td> <td>0</td> <td>2</td> </tr> </tbody> </table> </div> <p>Here is my expected output</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>User</th> <th>Monday</th> <th>Tuesday</th> <th>Wednesday</th> <th>Thursday</th> <th>Friday</th> <th>Total</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>1</td> <td>3</td> <td>4</td> <td>6</td> <td>1</td> <td>15</td> </tr> <tr> <td>C</td> <td>18</td> <td>1</td> <td>0</td> <td>18</td> <td>1</td> <td>38</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74551507, "author": "xQbert", "author_id": 1016435, "author_profile": "https://Stackoverflow.com/users/1016435", "pm_score": 3, "selected": true, "text": "SELECT * \nFROM TABLENAME\nWHERE case when Monday > 0 then 1 else 0 end \n + case when Tuesday > 0 then 1 else 0 end \n + case when Wednesday > 0 then 1 else 0 end \n + case when Thrusday > 0 then 1 else 0 end \n + case when Friday > 0 then 1 else 0 end >=2\n" }, { "answer_id": 74554378, "author": "Mikhail Berlyant", "author_id": 5221944, "author_profile": "https://Stackoverflow.com/users/5221944", "pm_score": 1, "selected": false, "text": "select * from your_table t\nwhere array_length(regexp_extract_all(to_json_string(t), ':0')) < 2 \n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7936478/" ]
74,551,457
<p>I am a beginner in mql4 and I'm trying something out.</p> <p>I need to calculate the speed rate of price changes from one second to another. Either on mql4 or pine script. Is there a way to achieve that?</p>
[ { "answer_id": 74551507, "author": "xQbert", "author_id": 1016435, "author_profile": "https://Stackoverflow.com/users/1016435", "pm_score": 3, "selected": true, "text": "SELECT * \nFROM TABLENAME\nWHERE case when Monday > 0 then 1 else 0 end \n + case when Tuesday > 0 then 1 else 0 end \n + case when Wednesday > 0 then 1 else 0 end \n + case when Thrusday > 0 then 1 else 0 end \n + case when Friday > 0 then 1 else 0 end >=2\n" }, { "answer_id": 74554378, "author": "Mikhail Berlyant", "author_id": 5221944, "author_profile": "https://Stackoverflow.com/users/5221944", "pm_score": 1, "selected": false, "text": "select * from your_table t\nwhere array_length(regexp_extract_all(to_json_string(t), ':0')) < 2 \n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20584605/" ]
74,551,458
<p>I'm trying to get the <code>last user's position</code> but I'm in a static context.</p> <p>Here's the code</p> <pre><code>public void getLastKnownLocation() { FusedLocationProviderClient fusedLocationClient = LocationServices. getFusedLocationProviderClient(App.getContext()); fusedLocationClient.getLastLocation() .addOnSuccessListener(**activity_needed_here**, new OnSuccessListener&lt;Location&gt;() { @Override public void onSuccess(Location location) { // Got last known location. In some rare situations this can be null. if (location != null) { System.out.println(&quot;Speed is &quot; + location.getSpeed()); } } }); </code></pre> <p>The problem is that I'm in a static context and I cannot have an activity here to call. I can, however, access the <code>app context</code>.</p> <p>How can I avoid using the <code>addOnSuccessListener</code> or how can I implement this in a static context?</p>
[ { "answer_id": 74551507, "author": "xQbert", "author_id": 1016435, "author_profile": "https://Stackoverflow.com/users/1016435", "pm_score": 3, "selected": true, "text": "SELECT * \nFROM TABLENAME\nWHERE case when Monday > 0 then 1 else 0 end \n + case when Tuesday > 0 then 1 else 0 end \n + case when Wednesday > 0 then 1 else 0 end \n + case when Thrusday > 0 then 1 else 0 end \n + case when Friday > 0 then 1 else 0 end >=2\n" }, { "answer_id": 74554378, "author": "Mikhail Berlyant", "author_id": 5221944, "author_profile": "https://Stackoverflow.com/users/5221944", "pm_score": 1, "selected": false, "text": "select * from your_table t\nwhere array_length(regexp_extract_all(to_json_string(t), ':0')) < 2 \n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20557611/" ]
74,551,460
<p>I'm creating a simple webpage on React + TS with ant design library and I have a problem with types in form component. I created an array to map through them and render form.</p> <p><a href="https://codesandbox.io/s/relaxed-mountain-vb1b0e?from-embed" rel="nofollow noreferrer">https://codesandbox.io/s/relaxed-mountain-vb1b0e?from-embed</a></p> <p>That looks an element in array which gives me an error.</p> <pre><code>const FormItems = [ // { // name: 'name', // label: 'Imię/ firma', // rules: { required: true }, &lt;----- this element is good // inputType: &lt;Input /&gt;, // }, { name: 'email', label: 'Email', rules: { type: 'email', required: true }, &lt;---- this element giving an error inputType: &lt;Input /&gt;, }, ]; </code></pre> <p>ERROR / / /</p> <pre><code>Type '{ type: string; required: boolean; }' is not assignable to type 'Rule'. Type '{ type: string; required: boolean; }' is not assignable to type 'ArrayRule'. Types of property 'type' are incompatible. Type 'string' is not assignable to type '&quot;array&quot;'.ts(2322) </code></pre> <p>And this error occurs in this fragment of code:</p> <pre><code>{FormItems.map((item) =&gt; ( &lt;Form.Item name={['user', item.name]} label={item.label} rules={[item.rules]} &lt;--- item.rules are underlined &gt; {item.inputType} &lt;/Form.Item&gt; ))} </code></pre>
[ { "answer_id": 74551507, "author": "xQbert", "author_id": 1016435, "author_profile": "https://Stackoverflow.com/users/1016435", "pm_score": 3, "selected": true, "text": "SELECT * \nFROM TABLENAME\nWHERE case when Monday > 0 then 1 else 0 end \n + case when Tuesday > 0 then 1 else 0 end \n + case when Wednesday > 0 then 1 else 0 end \n + case when Thrusday > 0 then 1 else 0 end \n + case when Friday > 0 then 1 else 0 end >=2\n" }, { "answer_id": 74554378, "author": "Mikhail Berlyant", "author_id": 5221944, "author_profile": "https://Stackoverflow.com/users/5221944", "pm_score": 1, "selected": false, "text": "select * from your_table t\nwhere array_length(regexp_extract_all(to_json_string(t), ':0')) < 2 \n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15032294/" ]
74,551,469
<p>Having problems with rotating a square but keeping the number inside it not rotated.</p> <p>Ideally I would like it like this:</p> <p><a href="https://i.stack.imgur.com/7Dc9k.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7Dc9k.jpg" alt="Number inside a rotated box" /></a></p> <pre><code>.diamond { width: 0; height: 0; border: 50px solid transparent; border-bottom-color: #EB008B; position: relative; top: -50px; text-align: center; font: 40pt Arial, sans-serif; color: white; } .diamond:after { content: ''; position: absolute; left: -50px; top: 50px; width: 0; height: 0; border: 50px solid transparent; border-top-color: #EB008B; } &lt;div class=&quot;diamond&quot;&gt;1&lt;/div&gt; </code></pre>
[ { "answer_id": 74551507, "author": "xQbert", "author_id": 1016435, "author_profile": "https://Stackoverflow.com/users/1016435", "pm_score": 3, "selected": true, "text": "SELECT * \nFROM TABLENAME\nWHERE case when Monday > 0 then 1 else 0 end \n + case when Tuesday > 0 then 1 else 0 end \n + case when Wednesday > 0 then 1 else 0 end \n + case when Thrusday > 0 then 1 else 0 end \n + case when Friday > 0 then 1 else 0 end >=2\n" }, { "answer_id": 74554378, "author": "Mikhail Berlyant", "author_id": 5221944, "author_profile": "https://Stackoverflow.com/users/5221944", "pm_score": 1, "selected": false, "text": "select * from your_table t\nwhere array_length(regexp_extract_all(to_json_string(t), ':0')) < 2 \n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8105415/" ]
74,551,498
<p>i want something like this</p> <p><a href="https://i.stack.imgur.com/nHAhF.png" rel="nofollow noreferrer">Image form bootstrap</a></p> <p>but i get this instead</p> <p><a href="https://i.stack.imgur.com/mWKY6.png" rel="nofollow noreferrer">Image on my localhost</a></p> <p>And this is my code:</p> <pre><code> &lt;input type=&quot;password&quot; class=&quot;form-control&quot; placeholder=&quot;contraseña&quot; id=&quot;password-input&quot; aria-label=&quot;password input&quot; aria-describedby=&quot;password-input&quot; /&gt; &lt;span class=&quot;input-group-text&quot; id=&quot;password-input&quot;&gt;@&lt;/span&gt; </code></pre> <p>All the examples that i see in internet are the same, looks nice but i put the code in my proyect and don't work :(</p>
[ { "answer_id": 74551507, "author": "xQbert", "author_id": 1016435, "author_profile": "https://Stackoverflow.com/users/1016435", "pm_score": 3, "selected": true, "text": "SELECT * \nFROM TABLENAME\nWHERE case when Monday > 0 then 1 else 0 end \n + case when Tuesday > 0 then 1 else 0 end \n + case when Wednesday > 0 then 1 else 0 end \n + case when Thrusday > 0 then 1 else 0 end \n + case when Friday > 0 then 1 else 0 end >=2\n" }, { "answer_id": 74554378, "author": "Mikhail Berlyant", "author_id": 5221944, "author_profile": "https://Stackoverflow.com/users/5221944", "pm_score": 1, "selected": false, "text": "select * from your_table t\nwhere array_length(regexp_extract_all(to_json_string(t), ':0')) < 2 \n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16078759/" ]
74,551,584
<p>May I know on how to call an array in stored procedure? I tried to enclosed it with a bracket to put the column_name that need to be insert in the new table.</p> <pre><code>CREATE OR REPLACE PROCEDURE data_versioning_nonull(new_table_name VARCHAR(100),column_name VARCHAR(100)[], current_table_name VARCHAR(100)) language plpgsql as $$ BEGIN EXECUTE ('CREATE TABLE ' || quote_ident(new_table_name) || ' AS SELECT ' || quote_ident(column_name) || ' FROM ' || quote_ident(current_table_name)); END $$; CALL data_versioning_nonull('sales_2019_sample', ['orderid', 'product', 'address'], 'sales_2019'); </code></pre>
[ { "answer_id": 74551812, "author": "P.R", "author_id": 9846906, "author_profile": "https://Stackoverflow.com/users/9846906", "pm_score": 0, "selected": false, "text": "CREATE OR REPLACE PROCEDURE data_versioning_nonull(new_table_name VARCHAR(100),column_name VARCHAR(100)[], current_table_name VARCHAR(100))\nlanguage plpgsql\nas $$\nBEGIN\n EXECUTE ('CREATE TABLE ' || quote_ident(new_table_name) || ' AS SELECT ' || array_to_string(column_name, ',') || ' FROM ' || quote_ident(current_table_name));\nEND $$;\n CALL data_versioning_nonull('sales_2019_sample', '{\"orderid\", \"product\", \"address\"}', 'sales_2019');\n" }, { "answer_id": 74552073, "author": "Zegarek", "author_id": 5298879, "author_profile": "https://Stackoverflow.com/users/5298879", "pm_score": 3, "selected": true, "text": "execute format() quote_ident() %I %1$I ARRAY['a','b','c']::VARCHAR(100)[] '{\"a\",\"b\",\"c\"}'::VARCHAR(100)[] text CREATE TABLE sales_2019(orderid INT,product INT,address INT);\n\nCREATE OR REPLACE PROCEDURE data_versioning_nonull(\n new_table_name TEXT,\n column_names TEXT[], \n current_table_name TEXT)\nLANGUAGE plpgsql AS $$\nDECLARE\n list_of_columns_as_quoted_identifiers TEXT;\nBEGIN\n SELECT string_agg(quote_ident(name),',')\n INTO list_of_columns_as_quoted_identifiers\n FROM unnest(column_names) name;\n \n EXECUTE format('CREATE TABLE %1$I.%2$I AS SELECT %3$s FROM %1$I.%4$I',\n current_schema(),\n new_table_name,\n list_of_columns_as_quoted_identifiers,\n current_table_name);\nEND $$;\n\nCALL data_versioning_nonull(\n 'sales_2019_sample', \n ARRAY['orderid', 'product', 'address']::text[], \n 'sales_2019');\n current_schema() new_table_schema current_table_schema current_schema()" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14610361/" ]
74,551,585
<pre><code> def main(): money1 = input(&quot;Purchase price: &quot;) money2 = input(&quot;Paid amount of money: &quot;) price = int(money1) paid = int(money2) change = paid - price ten_euro = change // 10 five_euro = change % 10 // 5 two_euro = change % 5 // 2 one_euro = (change % 2) if price &lt; paid: print(&quot;Offer change:&quot;) if change &gt;= 10: print(ten_euro, &quot;ten-euro notes&quot;) if (change % 10) &gt;= 5: print(five_euro, &quot;five-euro notes&quot;) if (change % 5) &gt;= 2: print(two_euro, &quot;two-euro coins&quot;) if (change % 2) &gt;= 2: print(one_euro, &quot;one-euro coins&quot;) else: print(&quot;No change&quot;) if __name__ == &quot;__main__&quot;: main() </code></pre> <p>Create a program that asks how much purchases cost and the amount of paid money and then prints the amount of change. Simplify the program by only allowing the use of sums of 1, 2, 5, and 10 euros. Ensure that the total price is always in full euros. My problem is with the one-euro coins, as it is not showing as expected.</p> <p>Examples of how the program should work:</p> <p>Purchase price: 12 Paid amount of money: 50 Offer change: 3 ten-euro notes 1 five-euro notes 1 two-euro coins 1 one-euro coins</p> <p>Purchase price: 9 Paid amount of money: 20 Offer change: 1 ten-euro notes 1 one-euro coins</p>
[ { "answer_id": 74551812, "author": "P.R", "author_id": 9846906, "author_profile": "https://Stackoverflow.com/users/9846906", "pm_score": 0, "selected": false, "text": "CREATE OR REPLACE PROCEDURE data_versioning_nonull(new_table_name VARCHAR(100),column_name VARCHAR(100)[], current_table_name VARCHAR(100))\nlanguage plpgsql\nas $$\nBEGIN\n EXECUTE ('CREATE TABLE ' || quote_ident(new_table_name) || ' AS SELECT ' || array_to_string(column_name, ',') || ' FROM ' || quote_ident(current_table_name));\nEND $$;\n CALL data_versioning_nonull('sales_2019_sample', '{\"orderid\", \"product\", \"address\"}', 'sales_2019');\n" }, { "answer_id": 74552073, "author": "Zegarek", "author_id": 5298879, "author_profile": "https://Stackoverflow.com/users/5298879", "pm_score": 3, "selected": true, "text": "execute format() quote_ident() %I %1$I ARRAY['a','b','c']::VARCHAR(100)[] '{\"a\",\"b\",\"c\"}'::VARCHAR(100)[] text CREATE TABLE sales_2019(orderid INT,product INT,address INT);\n\nCREATE OR REPLACE PROCEDURE data_versioning_nonull(\n new_table_name TEXT,\n column_names TEXT[], \n current_table_name TEXT)\nLANGUAGE plpgsql AS $$\nDECLARE\n list_of_columns_as_quoted_identifiers TEXT;\nBEGIN\n SELECT string_agg(quote_ident(name),',')\n INTO list_of_columns_as_quoted_identifiers\n FROM unnest(column_names) name;\n \n EXECUTE format('CREATE TABLE %1$I.%2$I AS SELECT %3$s FROM %1$I.%4$I',\n current_schema(),\n new_table_name,\n list_of_columns_as_quoted_identifiers,\n current_table_name);\nEND $$;\n\nCALL data_versioning_nonull(\n 'sales_2019_sample', \n ARRAY['orderid', 'product', 'address']::text[], \n 'sales_2019');\n current_schema() new_table_schema current_table_schema current_schema()" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20584214/" ]
74,551,588
<p>How do I run it for all rows of a given product id and shop id:</p> <p>One table: ps_product_shop</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id_product</th> <th>price</th> <th>id_shop</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>1</td> <td>1</td> </tr> <tr> <td>1</td> <td>25</td> <td>3</td> </tr> <tr> <td>2</td> <td>2</td> <td>1</td> </tr> <tr> <td>2</td> <td>50</td> <td>3</td> </tr> </tbody> </table> </div> <p>THX</p> <p><strong>For one line:</strong> UPDATE ps_product_shop SET price=(SELECT price FROM ps_product_shop WHERE id_product = '1' AND id_shop = '1')*25 WHERE (id_product='1') AND (id_shop='3');</p> <p><strong>I tried but it doesn't work:</strong> UPDATE ps_product_shop SET price=(SELECT price FROM ps_product_shop WHERE id_product = ps_product_shop.id_product AND id_shop = '1')*25 WHERE ps_product_shop.id_product IN (SELECT price FROM ps_product_shop WHERE id_product = ps_product_shop.id_product AND id_shop = '3');</p>
[ { "answer_id": 74562758, "author": "Krystian Podemski", "author_id": 2895156, "author_profile": "https://Stackoverflow.com/users/2895156", "pm_score": 1, "selected": false, "text": "UPDATE ps_product p, ps_product_shop ps \nSET p.price = p.price*25, ps.price = ps.price*25\nWHERE p.id_product = 1 AND ps.id_product = 1 AND ps.id_shop = 2\n" }, { "answer_id": 74565446, "author": "Mailo", "author_id": 20584369, "author_profile": "https://Stackoverflow.com/users/20584369", "pm_score": 0, "selected": false, "text": "UPDATE ps_product_shop AS sk SET \nprice=(SELECT price FROM ps_product_shop\nWHERE id_product = sk.id_product AND id_shop = '1')*27 WHERE (sk.id_shop='3');\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20584369/" ]
74,551,612
<p>I'm not familiar with PHPUnit and just want to execute a simple method that return a DateTimeImmutable and compare it with another DateTimeImmutable.</p> <pre><code> public function testGetLunchTimesBeginHour() { $minLunchTime = \DateTimeImmutable::createFromFormat('H:i', self::MIN_BEGIN_LUNCH); $maxLunchTime = \DateTimeImmutable::createFromFormat('H:i', self::MAX_END_LUNCH); foreach($this-&gt;daysOfAppointments as $dayOfAppointments){ $appointments = $this-&gt;makeAppointmentsDatetime($dayOfAppointments); $mock = $this-&gt;getMockBuilder(GetLunchTimesBeginHour::class)-&gt;getMock(); $expected = \DateTimeImmutable::createFromFormat('H:i', $dayOfAppointments['expected']); $actualResult = $mock-&gt;expects($this-&gt;once())-&gt;method('getLunch')-&gt;with($appointments, $minLunchTime, $maxLunchTime, self::DURATION_LUNCH); $this-&gt;assertEquals( $expected, $actualResult, &quot;unexpected result&quot;); } } </code></pre> <p>I understand the problem is that $actualResult is a PHPUnit\Framework\MockObject\Builder\InvocationMocker instead of a DateTimeImmutable.</p> <p>How to just execute the method and get the result ? Must I call the real class instead of a mock ?</p>
[ { "answer_id": 74562758, "author": "Krystian Podemski", "author_id": 2895156, "author_profile": "https://Stackoverflow.com/users/2895156", "pm_score": 1, "selected": false, "text": "UPDATE ps_product p, ps_product_shop ps \nSET p.price = p.price*25, ps.price = ps.price*25\nWHERE p.id_product = 1 AND ps.id_product = 1 AND ps.id_shop = 2\n" }, { "answer_id": 74565446, "author": "Mailo", "author_id": 20584369, "author_profile": "https://Stackoverflow.com/users/20584369", "pm_score": 0, "selected": false, "text": "UPDATE ps_product_shop AS sk SET \nprice=(SELECT price FROM ps_product_shop\nWHERE id_product = sk.id_product AND id_shop = '1')*27 WHERE (sk.id_shop='3');\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7522572/" ]
74,551,613
<p>I am making my first game and want to create a score board within a .txt file, however when I try and print the score board it doesn't work.</p> <pre><code>with open(&quot;Scores.txt&quot;, &quot;r&quot;) as scores: for i in range(len(score.readlines())): print(score.readlines(i + 1)) </code></pre> <p>Instead of printing each line of the .txt file as I expected it to instead it just prints []</p> <p>The contents of the .txt file are:</p> <blockquote> <p>NAME: AGE: GENDER: SCORE:</p> </blockquote> <p>I know it's only one line but it should still work shouldn't it?</p> <p>*Note there are spaces between each word in the .txt file, though Stack Overflow formatting doesn't allow me to show that.</p>
[ { "answer_id": 74551641, "author": "Bharel", "author_id": 1658617, "author_profile": "https://Stackoverflow.com/users/1658617", "pm_score": 0, "selected": false, "text": ".readlines() [] with open(\"Scores.txt\", \"r\") as scores:\n for line in scores:\n print(line.rstrip())\n" }, { "answer_id": 74551648, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 2, "selected": true, "text": "score.readlines() with open(\"Scores.txt\", \"r\") as scores:\n scorelines = scores.readlines()\n\nfor line in scorelines:\n print(line)\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17280812/" ]
74,551,616
<p>Without any page load, I want to change the background image using JavaScript.</p> <pre class="lang-js prettyprint-override"><code>const getbg = (bgimg) =&gt; { if (body.offsetWidth &gt; 780) { body.style.backgroundImage = `url(${bgimg[0]})`; } else if (body.offsetWidth &gt; 780 &amp;&amp; body.offsetWidth &gt; 580) { body.style.backgroundImage = `url(${bgimg[1]})`; } else { body.style.backgroundImage = `url(${bgimg[2]})`; } }; </code></pre> <p>My code is not working perfectly.</p>
[ { "answer_id": 74551675, "author": "WizardOfOz", "author_id": 19668106, "author_profile": "https://Stackoverflow.com/users/19668106", "pm_score": 1, "selected": false, "text": "@media(max-width:650px){\n .your-class{\n backround-image: url('image1.jpg');\n }\n}\n\n@media(max-width:768px){\n .your-class{\n backround-image: url('image2.jpg');\n }\n}\n" }, { "answer_id": 74551972, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "/* ================= this is latest way of it. ================= */\n\nbackground-image: image-set(\n url(\"small-landscape-750x536.jpg\") 750w,\n url(\"large-landscape-2048x1536.jpg\") 20480w);\n}\n\n/* ================= this is latest way of it. ================= */" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17290967/" ]
74,551,623
<p>Today I tried to remove html file extension from my website, for example:<br /> <code>example.com/page.html</code> to <code>example.com/page</code></p> <p>I watched some tutorials, but nothing seems to work... I created <code>.htaccess</code> file in root directory<br /> Copied code (also tried different ones):</p> <pre class="lang-htaccess prettyprint-override"><code>RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.html -f RewriteRule ^(.*)$ $1.html [NC,L] </code></pre> <p>It didn't work when I opened my website as file, with Live Server (VS Code extension) or actual website (hosted on Replit)</p> <p>Any idea, why it doesn't work? Any help appreciated...<br /> See <a href="https://github.com/yungcypo/Website" rel="nofollow noreferrer">whole repository</a></p> <p>Edit: Someone said, I have to remove <code>.html</code> file extension. I get error that the file is not found</p>
[ { "answer_id": 74551857, "author": "Ricardo Aponte", "author_id": 20410575, "author_profile": "https://Stackoverflow.com/users/20410575", "pm_score": 1, "selected": false, "text": "RewriteEngine on\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteRule ^([^\\.]+)$ $1.html [NC, L]\n" }, { "answer_id": 74670741, "author": "cypo", "author_id": 18123614, "author_profile": "https://Stackoverflow.com/users/18123614", "pm_score": 0, "selected": false, "text": ".htaccess .html index.html" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18123614/" ]
74,551,663
<p>I have an class with an array of objects:</p> <pre><code>export class MyObject { sections: Section[] } </code></pre> <p>The Section class contains a Map:</p> <pre><code>export class Section { dataPoints: Map&lt;string, string&gt; } </code></pre> <p>I want to present an object of class MyObject to the user of the frontend and let the user change its content. I have a problem in the HTML code for the component for that:</p> <pre><code>&lt;ul&gt; &lt;li *ngFor=&quot;let section of this.myObject; index as sectionsIndex&quot;&gt; &lt;ul&gt; &lt;li *ngFor=&quot;let dataPoint of section.dataPoints | keyvalue&quot;&gt; &lt;mat-form-field appearance=&quot;fill&quot;&gt; &lt;mat-label&gt;Label:&lt;/mat-label&gt; &lt;input matInput placeholder=&quot;Label input field placeholder&quot; [(ngModel)]=&quot;this.myObject.sections[sectionsIndex].dataPoints[dataPoint.key]&quot;&gt; &lt;/mat-form-field&gt; &lt;mat-form-field appearance=&quot;fill&quot;&gt; &lt;mat-label&gt;Content:&lt;/mat-label&gt; &lt;input matInput placeholder=&quot;Content input field placeholder&quot; [(ngModel)]=&quot;this.myObject.sections[sectionsIndex].dataPoints[dataPoint.value]&quot;&gt; &lt;/mat-form-field&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Without the keyvalue pipe I get this error in the console: &quot;Error: NG02200: Cannot find a differ supporting object '[object Map]' of type 'object'. NgFor only supports binding to Iterables, such as Arrays. Did you mean to use the keyvalue pipe?&quot;.</p> <p>I followed <a href="https://stackoverflow.com/questions/48187362/how-to-iterate-using-ngfor-loop-map-containing-key-as-string-and-values-as-map-i">How to iterate using ngFor loop Map containing key as string and values as map iteration</a> which brought me to the keyvalue pipe, but accessing the original object via <code>[(ngModel)]=&quot;this.myObject.sections[sectionsIndex].dataPoints[dataPoint.key]&quot;</code> results in a compiler error &quot;Element implicitly has an 'any' type because type 'Map&lt;string, string&gt;' has no index signature. Did you mean to call 'get'?&quot; as well as the same error message with &quot;Did you mean to call 'set'?&quot; at the end.</p> <p>The user should be able to change the content of the <code>dataPoints</code> Map in <code>Sections</code> as well as other class variables of <code>MyObject</code> which I didn't mention in the code example, as well as add and remove Sections from the array and add and remove elements from the Map <code>dataPoints</code> by using add / remove buttons that I left out in the code as well to concentrate on the problem.</p> <p>What is best practice to deal with the problem of changing an array of objects with a Map? What leads to the error in my code?</p>
[ { "answer_id": 74552303, "author": "Rick", "author_id": 12271569, "author_profile": "https://Stackoverflow.com/users/12271569", "pm_score": 2, "selected": false, "text": "this.myObject.sections[sectionsIndex] section [(ngModel)]=\"dataPoint\"" }, { "answer_id": 74552783, "author": "Chris Hamilton", "author_id": 12914833, "author_profile": "https://Stackoverflow.com/users/12914833", "pm_score": 0, "selected": false, "text": "(ngModelChange) ngModel [(ngModel)] <ul>\n <li *ngFor=\"let section of this.myObject.sections\">\n <ul>\n <li *ngFor=\"let dataPoint of section.dataPoints | keyvalue; trackBy: trackByKey\">\n <label>{{dataPoint.key}}\n <input\n [ngModel]=\"dataPoint.value\"\n (ngModelChange)=\"section.dataPoints.set(dataPoint.key, $event)\"\n />\n </label>\n </li>\n </ul>\n </li>\n</ul>\n export class AppComponent {\n myObject: MyObject = {\n sections: [\n {\n dataPoints: new Map([\n ['k11', 'v11'],\n ['k12', 'v12'],\n ['k13', 'v13'],\n ]),\n },\n {\n dataPoints: new Map([\n ['k21', 'v21'],\n ['k22', 'v22'],\n ['k23', 'v23'],\n ]),\n },\n ],\n };\n\n trackByKey(i: number, d: { key: string; value: string }) {\n return d.key;\n }\n}\n" }, { "answer_id": 74554697, "author": "waldrabe", "author_id": 4466828, "author_profile": "https://Stackoverflow.com/users/4466828", "pm_score": 0, "selected": false, "text": "<ul>\n <li *ngFor=\"let section of this.myObject; index as sectionsIndex\">\n <ul>\n <li *ngFor=\"let dataPoint of section.dataPoints | keyvalue\">\n <mat-form-field appearance=\"fill\">\n <mat-label>Label:</mat-label>\n <input matInput placeholder=\"Label input field placeholder\"\n [(ngModel)]=\"dataPoint.key\">\n </mat-form-field>\n\n <mat-form-field appearance=\"fill\">\n <mat-label>Content:</mat-label>\n <input matInput placeholder=\"Content input field placeholder\"\n [(ngModel)]=\"dataPoint.value\">\n </mat-form-field>\n </li>\n </ul>\n </li>\n</ul>\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4466828/" ]
74,551,664
<p>N.B.: I have edited the question as it was probably unclear: I am looking for the best method to understand the type of plot in a given axis.</p> <p>QUESTION: I am trying to make a generic function which can arrange multiple figures as subplots. As I loop over the subplots to set some properties (e.g. axis range) iterating over <code>fig.axes</code>, I need to understand which type every plot is in order to determine which properties I want to set for each of them (e.g. I want to set x range on images and line plots, but not on colorbar, otherwise my plot will explode).</p> <p>My question is then how I can distinguish between different types.</p> <p>I tried to play with try and except and select on the basis of different properties for different plot types, but they seem to be the same for all of them, so, at the moment, the best way I found is to check the content of each axis: in particular <code>ax.images</code> is a non empty list if a plot is an image, and <code>ax.lines</code> is not empty if it is a line plot, (and a colorbar has both empty).</p> <p>This works for simple plots, but I wonder if this is still the best way and still working for more complex cases (e.g. insets, overlapped lines and images, subclasses)?</p> <p>This is just an example to illustrate how the different type of plots can be accessed, with the following code creating three axes <code>l</code>, <code>i</code> and <code>cb</code> (respectively line, image, colorbar):</p> <pre><code># create test figure plt.figure() b = np.arange(12).reshape([4,3]) plt.subplot(121) plt.plot([1,2,3],[4,5,6]) plt.subplot(122) plt.imshow(b) plt.colorbar() # create test objects ax=plt.gca() fig=plt.gcf() l,i,cb = fig.axes # do a simple test, images are different: for o in l,i,cb: print(len(o.images)) # this also doesn't work in finding properties not in common between lines and colobars, gives empty list. [a for a in dir(l) if a not in dir(cb)] </code></pre>
[ { "answer_id": 74552303, "author": "Rick", "author_id": 12271569, "author_profile": "https://Stackoverflow.com/users/12271569", "pm_score": 2, "selected": false, "text": "this.myObject.sections[sectionsIndex] section [(ngModel)]=\"dataPoint\"" }, { "answer_id": 74552783, "author": "Chris Hamilton", "author_id": 12914833, "author_profile": "https://Stackoverflow.com/users/12914833", "pm_score": 0, "selected": false, "text": "(ngModelChange) ngModel [(ngModel)] <ul>\n <li *ngFor=\"let section of this.myObject.sections\">\n <ul>\n <li *ngFor=\"let dataPoint of section.dataPoints | keyvalue; trackBy: trackByKey\">\n <label>{{dataPoint.key}}\n <input\n [ngModel]=\"dataPoint.value\"\n (ngModelChange)=\"section.dataPoints.set(dataPoint.key, $event)\"\n />\n </label>\n </li>\n </ul>\n </li>\n</ul>\n export class AppComponent {\n myObject: MyObject = {\n sections: [\n {\n dataPoints: new Map([\n ['k11', 'v11'],\n ['k12', 'v12'],\n ['k13', 'v13'],\n ]),\n },\n {\n dataPoints: new Map([\n ['k21', 'v21'],\n ['k22', 'v22'],\n ['k23', 'v23'],\n ]),\n },\n ],\n };\n\n trackByKey(i: number, d: { key: string; value: string }) {\n return d.key;\n }\n}\n" }, { "answer_id": 74554697, "author": "waldrabe", "author_id": 4466828, "author_profile": "https://Stackoverflow.com/users/4466828", "pm_score": 0, "selected": false, "text": "<ul>\n <li *ngFor=\"let section of this.myObject; index as sectionsIndex\">\n <ul>\n <li *ngFor=\"let dataPoint of section.dataPoints | keyvalue\">\n <mat-form-field appearance=\"fill\">\n <mat-label>Label:</mat-label>\n <input matInput placeholder=\"Label input field placeholder\"\n [(ngModel)]=\"dataPoint.key\">\n </mat-form-field>\n\n <mat-form-field appearance=\"fill\">\n <mat-label>Content:</mat-label>\n <input matInput placeholder=\"Content input field placeholder\"\n [(ngModel)]=\"dataPoint.value\">\n </mat-form-field>\n </li>\n </ul>\n </li>\n</ul>\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/766685/" ]
74,551,695
<p>I have a XML which have two parent nodes (<strong>Base, Sub</strong>). I need to write a XSLT to get the values for below condition.</p> <p><strong>Condition</strong>: If the value inside <strong>Sub</strong> contains in <strong>Base</strong> also XSLT should add that value to the output.</p> <p><strong>Input XML:</strong></p> <pre><code>&lt;?xml version=&quot;1.0 encoding=&quot;UTF-8&quot;?&gt; &lt;Data&gt; &lt;Base&gt; &lt;Student_ID&gt;1234&lt;/Student_ID&gt; &lt;Student_ID&gt;1267&lt;/Student_ID&gt; &lt;Student_ID&gt;1890&lt;/Student_ID&gt; &lt;Student_ID&gt;5678&lt;/Student_ID&gt; &lt;Student_ID&gt;6743&lt;/Student_ID&gt; &lt;Student_ID&gt;8743&lt;/Student_ID&gt; &lt;/Base&gt; &lt;Sub&gt; &lt;Student_ID&gt;5678&lt;/Student_ID&gt; &lt;Student_ID&gt;6743&lt;/Student_ID&gt; &lt;Student_ID&gt;3226&lt;/Student_ID&gt; &lt;Student_ID&gt;8123&lt;/Student_ID&gt; &lt;/Sub&gt; &lt;/Data&gt; </code></pre> <p><strong>Expected Output:</strong></p> <pre><code>&lt;?xml version=&quot;1.0 encoding=&quot;UTF-8&quot;?&gt; &lt;Data&gt; &lt;Student_ID&gt;5678&lt;/Student_ID&gt; &lt;Student_ID&gt;6743&lt;/Student_ID&gt; &lt;/Data&gt; </code></pre> <p>Since I'm new to XSLT need a help on this.</p>
[ { "answer_id": 74552303, "author": "Rick", "author_id": 12271569, "author_profile": "https://Stackoverflow.com/users/12271569", "pm_score": 2, "selected": false, "text": "this.myObject.sections[sectionsIndex] section [(ngModel)]=\"dataPoint\"" }, { "answer_id": 74552783, "author": "Chris Hamilton", "author_id": 12914833, "author_profile": "https://Stackoverflow.com/users/12914833", "pm_score": 0, "selected": false, "text": "(ngModelChange) ngModel [(ngModel)] <ul>\n <li *ngFor=\"let section of this.myObject.sections\">\n <ul>\n <li *ngFor=\"let dataPoint of section.dataPoints | keyvalue; trackBy: trackByKey\">\n <label>{{dataPoint.key}}\n <input\n [ngModel]=\"dataPoint.value\"\n (ngModelChange)=\"section.dataPoints.set(dataPoint.key, $event)\"\n />\n </label>\n </li>\n </ul>\n </li>\n</ul>\n export class AppComponent {\n myObject: MyObject = {\n sections: [\n {\n dataPoints: new Map([\n ['k11', 'v11'],\n ['k12', 'v12'],\n ['k13', 'v13'],\n ]),\n },\n {\n dataPoints: new Map([\n ['k21', 'v21'],\n ['k22', 'v22'],\n ['k23', 'v23'],\n ]),\n },\n ],\n };\n\n trackByKey(i: number, d: { key: string; value: string }) {\n return d.key;\n }\n}\n" }, { "answer_id": 74554697, "author": "waldrabe", "author_id": 4466828, "author_profile": "https://Stackoverflow.com/users/4466828", "pm_score": 0, "selected": false, "text": "<ul>\n <li *ngFor=\"let section of this.myObject; index as sectionsIndex\">\n <ul>\n <li *ngFor=\"let dataPoint of section.dataPoints | keyvalue\">\n <mat-form-field appearance=\"fill\">\n <mat-label>Label:</mat-label>\n <input matInput placeholder=\"Label input field placeholder\"\n [(ngModel)]=\"dataPoint.key\">\n </mat-form-field>\n\n <mat-form-field appearance=\"fill\">\n <mat-label>Content:</mat-label>\n <input matInput placeholder=\"Content input field placeholder\"\n [(ngModel)]=\"dataPoint.value\">\n </mat-form-field>\n </li>\n </ul>\n </li>\n</ul>\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9731640/" ]
74,551,756
<p>Can you please help me in formatting the Lookupactivity Output value from Datetime to Date type and pass into set_variable activity.</p> <p>Step 1: I am using a query in Lookup activity as SELECT CAST(MAX([DWHModifiedDate]) AS DATE) AS DWHModifiedDate FROM [Schema].[TableName]</p> <p>The output from lookup activity is like &quot;DWHModifiedDate&quot;: &quot;2022-11-18T00:00:00Z&quot;</p> <p>Step 2: Now i added a Set_variable activity and i want to store only the date from Lookup activity output for example the variable value should be only &quot;2022-11-18&quot;.</p> <p>Can you please help how to achieve this.</p>
[ { "answer_id": 74674138, "author": "Saideep Arikontham", "author_id": 18844585, "author_profile": "https://Stackoverflow.com/users/18844585", "pm_score": 0, "selected": false, "text": "@split() T yyyy-MM-dd @split(activity('Lookup1').output.firstRow.dt,'T')[0]\n yyyy-MM-dd formatDateTime" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15488631/" ]
74,551,779
<p>This is a component I'm currently working on, named <code>TextBody</code></p> <pre><code>import { HTMLAttributes } from &quot;react&quot;; import classNames from &quot;classnames&quot;; interface TextBodyProps extends HTMLAttributes&lt;HTMLParagraphElement | HTMLSpanElement&gt; { span?: boolean; type: &quot;s&quot; | &quot;m&quot;; } export const TextBody = ({ span, type, className, children, ...props }: TextBodyProps) =&gt; { const textBodyClassNames = { s: &quot;text-body-s font-light leading-relaxed max-w-sm&quot;, m: &quot;text-body-m font-light leading-relaxed max-w-sm&quot;, }; const TextBodyElement = span ? &quot;span&quot; : &quot;p&quot;; return ( &lt;TextBodyElement {...props} className={classNames(textBodyClassNames[type], className)} &gt; {children} &lt;/TextBodyElement&gt; ); }; </code></pre> <p>Is it possible to extend <code>HTMLAttributes&lt;HTMLSpanElement&gt;</code> if <code>span</code> prop is passed, and only <code>HTMLAttributes&lt;HTMLParagraphElement&gt;</code> if it's not, instead of having a union?</p>
[ { "answer_id": 74674138, "author": "Saideep Arikontham", "author_id": 18844585, "author_profile": "https://Stackoverflow.com/users/18844585", "pm_score": 0, "selected": false, "text": "@split() T yyyy-MM-dd @split(activity('Lookup1').output.firstRow.dt,'T')[0]\n yyyy-MM-dd formatDateTime" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10555569/" ]
74,551,789
<pre><code>class UserInputArea extends StatefulWidget { @override State&lt;UserInputArea&gt; createState() =&gt; _UserInputAreaState(); } class _UserInputAreaState extends State&lt;UserInputArea&gt; { @override Widget build(BuildContext context) { String convertedText=''; setState(() { convertedText = Provider.of&lt;UserText&gt;(context, listen: true).convertedText; print('convertedText :: $convertedText'); }); return Card( elevation: 10, child: Container( padding: EdgeInsets.all(10), child: TextField( decoration: InputDecoration(hintText: convertedText.isNotEmpty ? convertedText : 'Enter text'), keyboardType: TextInputType.multiline, maxLines: 5, onChanged: (value){ Provider.of&lt;UserText&gt;(context, listen: false).updateText(value); }, ), ), ); } } </code></pre> <p>Need to update <strong>hintText</strong> field whenever <strong>convertedText</strong> gets updated. This update is happening only if screen refreshed somehow (In Appbar, if click on home-button-icon the data get updated in TextField), Using Provider package that should listen the changes and update the required feild, didnot work. So converted page to Stateful widget and addedd setState() &amp; moved <strong>convertedText</strong> variable inside it. But still its not working, and not able to figure it out, what is exactly missing here? Anyhelp appreciated. Thanks in advance</p>
[ { "answer_id": 74551938, "author": "Martin Dobruský", "author_id": 20164692, "author_profile": "https://Stackoverflow.com/users/20164692", "pm_score": -1, "selected": false, "text": "SetState() onChanged Widget build class UserInputArea extends StatefulWidget {\n @override\n State<UserInputArea> createState() => _UserInputAreaState();\n }\n \n class _UserInputAreaState extends State<UserInputArea> {\n String convertedText='';\n void _updateField() {\n setState(() {\n convertedText = Provider.of<UserText>(context, listen: true).convertedText;\n print('convertedText :: $convertedText');\n });\n\n @override\n Widget build(BuildContext context) {\n return Card(\n elevation: 10,\n child: Container(\n padding: EdgeInsets.all(10),\n child: TextField(\n decoration: InputDecoration(hintText: convertedText.isNotEmpty ? convertedText : 'Enter text'),\n keyboardType: TextInputType.multiline,\n maxLines: 5,\n onChanged: (value){\n Provider.of<UserText>(context, listen: false).updateText(value);\n _updateField();\n },\n ),\n ),\n );\n }\n }\n" }, { "answer_id": 74552207, "author": "Abdullatif Eida", "author_id": 20570798, "author_profile": "https://Stackoverflow.com/users/20570798", "pm_score": 0, "selected": false, "text": " class UserInputArea extends StatefulWidget {\n @override\n State<UserInputArea> createState() => _UserInputAreaState();\n }\n \n class _UserInputAreaState extends State<UserInputArea> {\n final TextEditingController nameController = TextEditingController();\n @override\n void initState() {\n nameController.text = \"test\";\n super.initState();\n //Here you should write your func to change the controller value \n Future.delayed(const Duration(seconds: 2), () {\n nameController.text = 'test after chabging';\n });\n } \n @override\n Widget build(BuildContext context) {\n \n return Card(\n elevation: 10,\n child: Container(\n padding: EdgeInsets.all(10),\n child: TextField(\n controller: nameController,\n decoration: InputDecoration(hintText: convertedText.isNotEmpty ? convertedText : 'Enter text'),\n keyboardType: TextInputType.multiline,\n maxLines: 5,\n\n ),\n ),\n );\n }\n }\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3290584/" ]
74,551,795
<p>I'm new to unity and I'm trying to get a GameObject to change color when the game starts, but I get a error message saying &quot; 'Color' does not contain a constructor that takes 4 arguments &quot;, I've been trying to figure out what's wrong for 2 days, but I have no idea.</p> <pre><code>public class NewColor : MonoBehaviour { private Renderer rend; [SerializeField] private Color colorToTurnTo = new Color (1f, 1f, 1f, 1f); void Start() { rend = GetComponent&lt;Renderer&gt;(); rend.material.color = colorToTurnTo; } </code></pre> <p>I expected the GameObject to turn white when I started the game, but I couldn't start the game due to the errors.</p>
[ { "answer_id": 74551938, "author": "Martin Dobruský", "author_id": 20164692, "author_profile": "https://Stackoverflow.com/users/20164692", "pm_score": -1, "selected": false, "text": "SetState() onChanged Widget build class UserInputArea extends StatefulWidget {\n @override\n State<UserInputArea> createState() => _UserInputAreaState();\n }\n \n class _UserInputAreaState extends State<UserInputArea> {\n String convertedText='';\n void _updateField() {\n setState(() {\n convertedText = Provider.of<UserText>(context, listen: true).convertedText;\n print('convertedText :: $convertedText');\n });\n\n @override\n Widget build(BuildContext context) {\n return Card(\n elevation: 10,\n child: Container(\n padding: EdgeInsets.all(10),\n child: TextField(\n decoration: InputDecoration(hintText: convertedText.isNotEmpty ? convertedText : 'Enter text'),\n keyboardType: TextInputType.multiline,\n maxLines: 5,\n onChanged: (value){\n Provider.of<UserText>(context, listen: false).updateText(value);\n _updateField();\n },\n ),\n ),\n );\n }\n }\n" }, { "answer_id": 74552207, "author": "Abdullatif Eida", "author_id": 20570798, "author_profile": "https://Stackoverflow.com/users/20570798", "pm_score": 0, "selected": false, "text": " class UserInputArea extends StatefulWidget {\n @override\n State<UserInputArea> createState() => _UserInputAreaState();\n }\n \n class _UserInputAreaState extends State<UserInputArea> {\n final TextEditingController nameController = TextEditingController();\n @override\n void initState() {\n nameController.text = \"test\";\n super.initState();\n //Here you should write your func to change the controller value \n Future.delayed(const Duration(seconds: 2), () {\n nameController.text = 'test after chabging';\n });\n } \n @override\n Widget build(BuildContext context) {\n \n return Card(\n elevation: 10,\n child: Container(\n padding: EdgeInsets.all(10),\n child: TextField(\n controller: nameController,\n decoration: InputDecoration(hintText: convertedText.isNotEmpty ? convertedText : 'Enter text'),\n keyboardType: TextInputType.multiline,\n maxLines: 5,\n\n ),\n ),\n );\n }\n }\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20584799/" ]
74,551,827
<p>I have a large file called</p> <pre><code>Metadata_01.json </code></pre> <p>It consistst of blocks that following this structure:</p> <pre><code>[ { &quot;Participant_id&quot;: &quot;P04_00001&quot;, &quot;no_of_people&quot;: &quot;Multiple&quot;, &quot;apparent_gender&quot;: &quot;F&quot;, &quot;geographic_location&quot;: &quot;AUS&quot;, &quot;ethnicity&quot;: &quot;Caucasian&quot;, &quot;capture_device_used&quot;: &quot;iOS 14&quot;, &quot;camera_orientation&quot;: &quot;Portrait&quot;, &quot;camera_position&quot;: &quot;Side View&quot;, &quot;indoor_outdoor_env&quot;: &quot;Indoors&quot;, &quot;lighting_condition&quot;: &quot;Bright&quot;, &quot;Occluded&quot;: 1, &quot;category&quot;: &quot;Two Person&quot;, &quot;camera_movement&quot;: &quot;Still&quot;, &quot;action&quot;: &quot;No action&quot;, &quot;indoor_outdoor_in_moving_car_or_train&quot;: &quot;Indoor&quot;, &quot;daytime_nighttime&quot;: &quot;Nighttime&quot; }, { &quot;Participant_id&quot;: &quot;P04_00002&quot;, &quot;no_of_people&quot;: &quot;Single&quot;, &quot;apparent_gender&quot;: &quot;M&quot;, &quot;geographic_location&quot;: &quot;AUS&quot;, &quot;ethnicity&quot;: &quot;Caucasian&quot;, &quot;capture_device_used&quot;: &quot;iOS 14&quot;, &quot;camera_orientation&quot;: &quot;Portrait&quot;, &quot;camera_position&quot;: &quot;Frontal View&quot;, &quot;indoor_outdoor_env&quot;: &quot;Outdoors&quot;, &quot;lighting_condition&quot;: &quot;Bright&quot;, &quot;Occluded&quot;: &quot;None&quot;, &quot;category&quot;: &quot;Animals&quot;, &quot;camera_movement&quot;: &quot;Still&quot;, &quot;action&quot;: &quot;Small action&quot;, &quot;indoor_outdoor_in_moving_car_or_train&quot;: &quot;Outdoor&quot;, &quot;daytime_nighttime&quot;: &quot;Daytime&quot; }, </code></pre> <p>And so on... thousands of them.</p> <p>I am using the following command:</p> <pre><code>jq -cr '.[]' Metadata_01.json | awk '{print &gt; (NR &quot;.json&quot;)}' </code></pre> <p>And it's kinda doing the expected work.</p> <p><a href="https://i.stack.imgur.com/XoeZg.jpg" rel="nofollow noreferrer">From large file that is structured like this</a></p> <p><a href="https://i.stack.imgur.com/iQvqB.jpg" rel="nofollow noreferrer">I am getting tons of files that named like this</a></p> <p><a href="https://i.stack.imgur.com/1ovh2.png" rel="nofollow noreferrer">And structure like this (in one line)</a></p> <p>Instead of those results I need each json file to be named after the &quot;Participant_id&quot; (e.g. P04_00002.json) And I want to preserve the json structure to look like that for each file</p> <pre><code>{ &quot;Participant_id&quot;: &quot;P04_00002&quot;, &quot;no_of_people&quot;: &quot;Single&quot;, &quot;apparent_gender&quot;: &quot;M&quot;, &quot;geographic_location&quot;: &quot;AUS&quot;, &quot;ethnicity&quot;: &quot;Caucasian&quot;, &quot;capture_device_used&quot;: &quot;iOS 14&quot;, &quot;camera_orientation&quot;: &quot;Portrait&quot;, &quot;camera_position&quot;: &quot;Frontal View&quot;, &quot;indoor_outdoor_env&quot;: &quot;Outdoors&quot;, &quot;lighting_condition&quot;: &quot;Bright&quot;, &quot;Occluded&quot;: &quot;None&quot;, &quot;category&quot;: &quot;Animals&quot;, &quot;camera_movement&quot;: &quot;Still&quot;, &quot;action&quot;: &quot;Small action&quot;, &quot;indoor_outdoor_in_moving_car_or_train&quot;: &quot;Outdoor&quot;, &quot;daytime_nighttime&quot;: &quot;Daytime&quot; } </code></pre> <p>What adjustments should I make to the command above to achieve this? Or maybe there's an easier way to do this? Thank you!</p>
[ { "answer_id": 74551962, "author": "Abraham Zinala", "author_id": 14903754, "author_profile": "https://Stackoverflow.com/users/14903754", "pm_score": 2, "selected": true, "text": "ConvertFrom-Json .Participant_id New-Item Out-File $json = Get-Content -Path '.\\Metadata_01.json' -Raw | ConvertFrom-Json \nforeach ($json_object in $json)\n{\n New-Item -Path \".\\Desktop\\\" -Name \"$($json_object.Participant_id).json\" -Value (ConvertTo-Json -InputObject $json_object) -ItemType 'File' -Force\n}\n" }, { "answer_id": 74553210, "author": "peak", "author_id": 997358, "author_profile": "https://Stackoverflow.com/users/997358", "pm_score": 2, "selected": false, "text": "jq -cr '.[] | (.Participant_id, .)' Metadata_01.json | awk '\n NR%2==1 {fn=\"id.\" $0 \".json\"; next} {print >> fn; close(fn); }\n'\n jq . \"$FILE\" | sponge \"$FILE\" jq -cr '.[] | (.Participant_id, .)' Metadata_01.json | awk -v q=$'\\'' '\n NR%2==1 {fn = \"id.\" $0 \".json\"; next}\n { system( (\"jq . <<< \" q $0 q \" >> \\\"\" fn \"\\\"\") );\n close(fn);\n }\n'\n jq empty --stream jstream while read -r json\ndo\n fn=$(jq -r .Participant_id <<< \"$json\")\n <<< \"$json\" jq . > \"id.$fn.json\"\ndone < <(jm Metadata_01.json)\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20581715/" ]
74,551,869
<p>I need some help to automate rename files in a current directory. The following files that can exits in the directory is for example:</p> <p>AAA111<strong>A</strong>.txt</p> <p>AAA111<strong>A</strong>.pdf</p> <p>AAA111<strong>A</strong>.jpg</p> <p>BBB222<strong>B</strong>.jpg</p> <p>BBB222<strong>B</strong>.pdf</p> <p>Where the bold letter stand for the revision of the file. What I want is a PowerShell or batch file where it automatically looks what revision letter it is and then increment that revision letter with the next in the alphabet for all files.</p> <p><em>Example:</em></p> <p>AAA111<strong>A</strong>.txt -&gt; AAA111<strong>B</strong>.txt</p> <p>BBB222<strong>B</strong>.pdf -&gt; BBB222<strong>C</strong>.pdf</p> <p>etc</p> <p>The letters and numbers before the revision letter and the extension of the file can vary, so used as a wildcard? It is also possible that the file is named like: AAA111<strong>A</strong>-01.pdf or AAA111<strong>A</strong>-blabla.pdf</p> <p>Hopefully someone can make my life easier for this noobie :).</p> <p>Thank you in advance!</p>
[ { "answer_id": 74551962, "author": "Abraham Zinala", "author_id": 14903754, "author_profile": "https://Stackoverflow.com/users/14903754", "pm_score": 2, "selected": true, "text": "ConvertFrom-Json .Participant_id New-Item Out-File $json = Get-Content -Path '.\\Metadata_01.json' -Raw | ConvertFrom-Json \nforeach ($json_object in $json)\n{\n New-Item -Path \".\\Desktop\\\" -Name \"$($json_object.Participant_id).json\" -Value (ConvertTo-Json -InputObject $json_object) -ItemType 'File' -Force\n}\n" }, { "answer_id": 74553210, "author": "peak", "author_id": 997358, "author_profile": "https://Stackoverflow.com/users/997358", "pm_score": 2, "selected": false, "text": "jq -cr '.[] | (.Participant_id, .)' Metadata_01.json | awk '\n NR%2==1 {fn=\"id.\" $0 \".json\"; next} {print >> fn; close(fn); }\n'\n jq . \"$FILE\" | sponge \"$FILE\" jq -cr '.[] | (.Participant_id, .)' Metadata_01.json | awk -v q=$'\\'' '\n NR%2==1 {fn = \"id.\" $0 \".json\"; next}\n { system( (\"jq . <<< \" q $0 q \" >> \\\"\" fn \"\\\"\") );\n close(fn);\n }\n'\n jq empty --stream jstream while read -r json\ndo\n fn=$(jq -r .Participant_id <<< \"$json\")\n <<< \"$json\" jq . > \"id.$fn.json\"\ndone < <(jm Metadata_01.json)\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14845182/" ]
74,551,969
<p>I have a dictionary where the values are lists. I want to search these for a specific value. right now it returns if the value is in each list individually but i just want overall then it deletes</p> <p>Here's what it returns right now:</p> <pre><code>marie true marie false marie false tom false tom true tom false jane false jane false jane false </code></pre> <p>Here is what I want:</p> <pre><code>marie true tom true jane false </code></pre> <p>Here is the code:</p> <pre class="lang-py prettyprint-override"><code>dictionary = {'nyu': ['marie', 'taylor', 'jim'], 'msu': ['tom', 'josh'], ' csu': ['tyler', 'mark', 'john']} #made in different method in same class class example: def get_names(self, name_list): for i in range(len(name_list)): for j in dictionary: if name_list[i] in dictionary[j]: print('true') dictionary[j].remove(name_list[i]) else: print('false') def main(): name_list = ['marie', 'tom', 'jane'] e = example() e.get_names(name_list) main() </code></pre>
[ { "answer_id": 74552059, "author": "azro", "author_id": 7212686, "author_profile": "https://Stackoverflow.com/users/7212686", "pm_score": 2, "selected": true, "text": "dictionary = {'nyu': ['marie', 'taylor', 'jim'],\n 'msu': ['tom', 'josh'],\n ' csu': ['tyler', 'mark', 'john']}\n\ndef get_names(names):\n for name in names:\n name_found = False\n for dict_names in dictionary.values():\n if name in dict_names:\n name_found = True\n break\n print(name, name_found)\n\nname_list = ['marie', 'tom', 'jane']\nget_names(name_list)\n" }, { "answer_id": 74552390, "author": "user3435121", "author_id": 3435121, "author_profile": "https://Stackoverflow.com/users/3435121", "pm_score": 0, "selected": false, "text": "dictionary = {'nyu': ['marie', 'taylor', 'jim'], \n 'msu': ['tom', 'josh'], \n ' csu': ['tyler', 'mark', 'john']} \\\n#made in different method in same class\n\nclass example:\n def remove_names( self, name_list):\n dic = dictionary.copy()\n for name in name_list:\n for k in dic:\n if name in dic[k]:\n dictionary[k].remove( name)\n\ndef main():\n name_list = ['marie', 'tom', 'jane']\n e = example()\n e.remove_names(name_list)\n print(dictionary)\n\nmain()\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20579620/" ]
74,551,985
<p>We're using Code First to manage a database that uses temporal tables. After a few migrations I've run into an issue, basically we needed to make a column nullable because the original data dictionary was incorrect.</p> <p>When I try to run Update-Database it returns an error:</p> <blockquote> <p>Setting SYSTEM_VERSIONING to ON failed because column 'MyColumn' does not have the same nullability attribute in tables 'MYDB.dbo.TableName' and 'MYDB.dbo.TableNameHistory'.</p> </blockquote> <p>It seems as though the migrationBuilder is creating the new column definition, but that is not getting applied to the history table...</p> <p>In SQL you can just run an ALTER TABLE command and it updates the history table, but I can't find any documentation on modifying temporal tables in EF Core. Everything is just about creating them.</p> <p>Is there something specific we need to do to make this work, or is this a bug in EF Core 6?</p>
[ { "answer_id": 74552059, "author": "azro", "author_id": 7212686, "author_profile": "https://Stackoverflow.com/users/7212686", "pm_score": 2, "selected": true, "text": "dictionary = {'nyu': ['marie', 'taylor', 'jim'],\n 'msu': ['tom', 'josh'],\n ' csu': ['tyler', 'mark', 'john']}\n\ndef get_names(names):\n for name in names:\n name_found = False\n for dict_names in dictionary.values():\n if name in dict_names:\n name_found = True\n break\n print(name, name_found)\n\nname_list = ['marie', 'tom', 'jane']\nget_names(name_list)\n" }, { "answer_id": 74552390, "author": "user3435121", "author_id": 3435121, "author_profile": "https://Stackoverflow.com/users/3435121", "pm_score": 0, "selected": false, "text": "dictionary = {'nyu': ['marie', 'taylor', 'jim'], \n 'msu': ['tom', 'josh'], \n ' csu': ['tyler', 'mark', 'john']} \\\n#made in different method in same class\n\nclass example:\n def remove_names( self, name_list):\n dic = dictionary.copy()\n for name in name_list:\n for k in dic:\n if name in dic[k]:\n dictionary[k].remove( name)\n\ndef main():\n name_list = ['marie', 'tom', 'jane']\n e = example()\n e.remove_names(name_list)\n print(dictionary)\n\nmain()\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74551985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17145/" ]
74,552,019
<p>ı am having a problem with the parentheses ı added a photo of where it gives the error and the error code itself<a href="https://i.stack.imgur.com/nxhmI.png" rel="nofollow noreferrer">error code</a> <a href="https://i.stack.imgur.com/eqEXC.png" rel="nofollow noreferrer">my code</a></p> <p>ı was just trying to convert string to int and assigning the values for the later part of the project</p>
[ { "answer_id": 74552059, "author": "azro", "author_id": 7212686, "author_profile": "https://Stackoverflow.com/users/7212686", "pm_score": 2, "selected": true, "text": "dictionary = {'nyu': ['marie', 'taylor', 'jim'],\n 'msu': ['tom', 'josh'],\n ' csu': ['tyler', 'mark', 'john']}\n\ndef get_names(names):\n for name in names:\n name_found = False\n for dict_names in dictionary.values():\n if name in dict_names:\n name_found = True\n break\n print(name, name_found)\n\nname_list = ['marie', 'tom', 'jane']\nget_names(name_list)\n" }, { "answer_id": 74552390, "author": "user3435121", "author_id": 3435121, "author_profile": "https://Stackoverflow.com/users/3435121", "pm_score": 0, "selected": false, "text": "dictionary = {'nyu': ['marie', 'taylor', 'jim'], \n 'msu': ['tom', 'josh'], \n ' csu': ['tyler', 'mark', 'john']} \\\n#made in different method in same class\n\nclass example:\n def remove_names( self, name_list):\n dic = dictionary.copy()\n for name in name_list:\n for k in dic:\n if name in dic[k]:\n dictionary[k].remove( name)\n\ndef main():\n name_list = ['marie', 'tom', 'jane']\n e = example()\n e.remove_names(name_list)\n print(dictionary)\n\nmain()\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20584936/" ]
74,552,037
<p>I have a Requirement in which i need to store JSX/TSX For Example: <code>&lt;div&gt;Hello {name} &lt;/div&gt;</code></p> <p>in a variable, like this: <code>const Ele = &lt;&gt;&lt;div&gt;Hello {name} &lt;/div&gt;&lt;/&gt;</code> to export for another component in React.</p> <p>Well in normal Javascript it works fines! Everything.</p> <p>But Problem is TypeScript isn't allowing me to store this even after declaring it to <code>varName:any</code></p> <p>(NOTE: For my requirement creating a React Functional Component won't Work!!! It must be normal variable in .ts file)</p> <p>If anyone can help me? Thanks in advance! ;)</p> <p>I tried it with :any and different JSX matching types which is provided by default, but no luck :(</p>
[ { "answer_id": 74552059, "author": "azro", "author_id": 7212686, "author_profile": "https://Stackoverflow.com/users/7212686", "pm_score": 2, "selected": true, "text": "dictionary = {'nyu': ['marie', 'taylor', 'jim'],\n 'msu': ['tom', 'josh'],\n ' csu': ['tyler', 'mark', 'john']}\n\ndef get_names(names):\n for name in names:\n name_found = False\n for dict_names in dictionary.values():\n if name in dict_names:\n name_found = True\n break\n print(name, name_found)\n\nname_list = ['marie', 'tom', 'jane']\nget_names(name_list)\n" }, { "answer_id": 74552390, "author": "user3435121", "author_id": 3435121, "author_profile": "https://Stackoverflow.com/users/3435121", "pm_score": 0, "selected": false, "text": "dictionary = {'nyu': ['marie', 'taylor', 'jim'], \n 'msu': ['tom', 'josh'], \n ' csu': ['tyler', 'mark', 'john']} \\\n#made in different method in same class\n\nclass example:\n def remove_names( self, name_list):\n dic = dictionary.copy()\n for name in name_list:\n for k in dic:\n if name in dic[k]:\n dictionary[k].remove( name)\n\ndef main():\n name_list = ['marie', 'tom', 'jane']\n e = example()\n e.remove_names(name_list)\n print(dictionary)\n\nmain()\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12195277/" ]