qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,586,890
<p>I'm trying to write a tail recursive function contains(tree,element) that returns true if the element exists in the Binary tree, false otherwise.</p> <p>I wrote the recursive function, the problem is that I don't know how to make it tail recursive</p> <pre><code>let leaf = { val: 6 } let tree = { val: 10, sx: { val: 5, sx: { val: 13 }, dx: leaf }, dx: { val: 32, sx: null, dx: null } } function contains(t,x) { if(t.val == x) return 1; let res = 0 ; if(t.sx) res += contains(t.sx,x) if(t.dx) res += contains(t.dx,x) return Boolean(res) } console.log(contains(tree,6)) </code></pre>
[ { "answer_id": 74586914, "author": "CertainPerformance", "author_id": 9515207, "author_profile": "https://Stackoverflow.com/users/9515207", "pm_score": 3, "selected": true, "text": "val true res let leaf = {\n val: 6\n}\nlet tree = {\n val: 10,\n sx: {\n val: 5,\n sx: {\n val: 13\n },\n dx: leaf\n },\n dx: {\n val: 32,\n sx: null,\n dx: null\n }\n}\n\nfunction contains(t, x) {\n if (t.val == x) {\n return true;\n }\n // Recursive, but not tail recursive:\n if (t.sx && contains(t.sx, x)) {\n return true;\n }\n // Tail recursive:\n return !t.dx ? false : contains(t.dx, x);\n}\n\nconsole.log(contains(tree, 6))" }, { "answer_id": 74587044, "author": "Grinza", "author_id": 13137584, "author_profile": "https://Stackoverflow.com/users/13137584", "pm_score": 1, "selected": false, "text": "let leaf = { val: 7}\nlet tree = {\n val: 10,\n sx: {\n val: 5,\n sx: {\n val: 4\n },\n dx: leaf\n },\n dx: {\n val: 32,\n sx: null,\n dx: null\n }\n}\n\nfunction _contains(t,x) {\n \n if(t.val == x)\n return 1;\n \n\n if(x < t.val && t.sx)\n return _contains(t.sx,x)\n else if(t.dx)\n return _contains(t.dx,x) \n}\nfunction contains(t,x){\n \n return Boolean(_contains(t,x));\n}\n" }, { "answer_id": 74602142, "author": "Scott Sauyet", "author_id": 1243641, "author_profile": "https://Stackoverflow.com/users/1243641", "pm_score": 1, "selected": false, "text": "null const _contains = ([t, ...ts], x) =>\n t == undefined\n ? false\n : t .val == x\n ? true\n : _contains (ts .concat (t .sx || []) .concat (t .dx || []), x)\n\nconst contains = (t, x) => \n _contains ([t], x)\n\n\nlet tree = {val: 10, sx: {val: 5, sx: {val: 13}, dx: {val: 6}}, dx: {val: 32, sx: null, dx: null}};\n\n[10, 12, 13, 32, 42] .forEach (x => console .log (`${x} --> ${contains (tree, x)}`)) const push = (x) => (xs) => \n x ? ((xs .push (x)), xs) : xs\n\nconst _contains = (ts, i, x) =>\n i >= ts .length\n ? false\n : ts [i] .val == x\n ? true\n : _contains (push (ts [i] .dx) (push (ts [i] .sx) (ts)), i + 1, x)\n\nconst contains = (t, x) =>\n _contains ([t], 0, x)\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74586890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13137584/" ]
74,586,936
<p>I need to create multiple datasets and assign a service account to each, giving access with the BigQuery Admin role.</p> <p>variables.tf</p> <pre><code>variable &quot;project_id&quot; { type = string default = &quot;&lt;projectid&gt;&quot; } variable &quot;set_location&quot; { type = string default = &quot;southamerica-east1&quot; } variable &quot;dataset_name&quot; { type = list default = [&quot;firs-dataset&quot;, &quot;second-dataset&quot;] } </code></pre> <p>main.tf</p> <pre><code>resource &quot;google_bigquery_dataset&quot; &quot;dataset&quot; { dataset_id = &quot;${var.dataset_name[count.index]}&quot; count = length(&quot;${var.dataset_name}&quot;) location = &quot;${var.set_location}&quot; access { role = &quot;roles/bigquery.admin&quot; user_by_email = &quot;&lt;service-account&gt;&quot; } } </code></pre> <p>With that I can create multiple datasets, but this way I can put permission on just one service account for all datasets.</p> <p>I need each dataset to have a specific service account with the BigQueryAdmin role.</p>
[ { "answer_id": 74586914, "author": "CertainPerformance", "author_id": 9515207, "author_profile": "https://Stackoverflow.com/users/9515207", "pm_score": 3, "selected": true, "text": "val true res let leaf = {\n val: 6\n}\nlet tree = {\n val: 10,\n sx: {\n val: 5,\n sx: {\n val: 13\n },\n dx: leaf\n },\n dx: {\n val: 32,\n sx: null,\n dx: null\n }\n}\n\nfunction contains(t, x) {\n if (t.val == x) {\n return true;\n }\n // Recursive, but not tail recursive:\n if (t.sx && contains(t.sx, x)) {\n return true;\n }\n // Tail recursive:\n return !t.dx ? false : contains(t.dx, x);\n}\n\nconsole.log(contains(tree, 6))" }, { "answer_id": 74587044, "author": "Grinza", "author_id": 13137584, "author_profile": "https://Stackoverflow.com/users/13137584", "pm_score": 1, "selected": false, "text": "let leaf = { val: 7}\nlet tree = {\n val: 10,\n sx: {\n val: 5,\n sx: {\n val: 4\n },\n dx: leaf\n },\n dx: {\n val: 32,\n sx: null,\n dx: null\n }\n}\n\nfunction _contains(t,x) {\n \n if(t.val == x)\n return 1;\n \n\n if(x < t.val && t.sx)\n return _contains(t.sx,x)\n else if(t.dx)\n return _contains(t.dx,x) \n}\nfunction contains(t,x){\n \n return Boolean(_contains(t,x));\n}\n" }, { "answer_id": 74602142, "author": "Scott Sauyet", "author_id": 1243641, "author_profile": "https://Stackoverflow.com/users/1243641", "pm_score": 1, "selected": false, "text": "null const _contains = ([t, ...ts], x) =>\n t == undefined\n ? false\n : t .val == x\n ? true\n : _contains (ts .concat (t .sx || []) .concat (t .dx || []), x)\n\nconst contains = (t, x) => \n _contains ([t], x)\n\n\nlet tree = {val: 10, sx: {val: 5, sx: {val: 13}, dx: {val: 6}}, dx: {val: 32, sx: null, dx: null}};\n\n[10, 12, 13, 32, 42] .forEach (x => console .log (`${x} --> ${contains (tree, x)}`)) const push = (x) => (xs) => \n x ? ((xs .push (x)), xs) : xs\n\nconst _contains = (ts, i, x) =>\n i >= ts .length\n ? false\n : ts [i] .val == x\n ? true\n : _contains (push (ts [i] .dx) (push (ts [i] .sx) (ts)), i + 1, x)\n\nconst contains = (t, x) =>\n _contains ([t], 0, x)\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74586936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20610099/" ]
74,586,939
<p>I have the below code that is just a basic function but I get this error and I'm not sure why.</p> <p>&quot;&gt; stats(mtcars,mpg) [1] NA Warning messages: 1: In min(df$variable) : no non-missing arguments to min; returning Inf 2: In max(df$variable) : no non-missing arguments to max; returning -Inf 3: In mean.default(df$variable) : argument is not numeric or logical: returning NA&quot;</p> <pre><code>stats &lt;- function(dataset, variable){ min(dataset$variable) max(dataset$variable) median(dataset$variable) mean(dataset$variable) sd(dataset$variable) } stats(mtcars,mpg) </code></pre> <p>I tried putting mtcars into a dataframe and that didn't work. I am inexperienced with R so I do not know how to trouble shoot well.</p>
[ { "answer_id": 74586952, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 1, "selected": true, "text": "[[ $ deparse/substitute [[ return list vector c stats <- function(dataset, variable){\n variable <- deparse(substitute(variable))\n list(Min = min(dataset[[variable]], na.rm = TRUE),\n Max = max(dataset[[variable]], na.rm = TRUE),\n Median = median(dataset[[variable]], na.rm = TRUE),\n Mean = mean(dataset[[variable]], na.rm = TRUE),\n SD = sd(dataset[[variable]], na.rm = TRUE))\n}\n > stats(mtcars, mpg)\n$Min\n[1] 10.4\n\n$Max\n[1] 33.9\n\n$Median\n[1] 19.2\n\n$Mean\n[1] 20.09062\n\n$SD\n[1] 6.026948\n" }, { "answer_id": 74587049, "author": "AndS.", "author_id": 9778513, "author_profile": "https://Stackoverflow.com/users/9778513", "pm_score": 1, "selected": false, "text": "library(tidyverse)\n\n\nstats <- function(dataset, variable){\n dataset |>\n summarise(across({{variable}}, list(min = min, max = max, median = median, \n mean = mean, sd = sd), .names = \"{.fn}\"))|>\n as.list.data.frame()\n}\n\nstats(mtcars, mpg) \n#> $min\n#> [1] 10.4\n#> \n#> $max\n#> [1] 33.9\n#> \n#> $median\n#> [1] 19.2\n#> \n#> $mean\n#> [1] 20.09062\n#> \n#> $sd\n#> [1] 6.026948\n stats <- function(dataset, variable){\n map(c(min, max, median, mean, sd), \\(f) f(pull(dataset, {{variable}}))) |>\n set_names(c(\"min\", \"max\", \"median\", \"mean\", \"sd\"))\n}\n\nstats(mtcars, mpg) \n#> $min\n#> [1] 10.4\n#> \n#> $max\n#> [1] 33.9\n#> \n#> $median\n#> [1] 19.2\n#> \n#> $mean\n#> [1] 20.09062\n#> \n#> $sd\n#> [1] 6.026948\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74586939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20610746/" ]
74,586,964
<p>Newbie question: I'm trying to put a photo on the right side of a website, have the text wrap around on the left, and have a photographer credit directly under the photo.</p> <p>The credit is showing up on the left side above the text header instead of under the photo on the right.</p> <p>Here's my html:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset='UTF-8'/&gt; &lt;link rel='stylesheet' href='test.css'/&gt; &lt;/head&gt; &lt;body&gt; &lt;picture&gt; &lt;img class='pic' src='images\str_pic1.JPG' alt=&quot;Person in blue shirt&quot; /&gt; &lt;figcaption class='pic'&gt;Photo Credit: Photographer&lt;/figcaption&gt; &lt;/picture&gt; &lt;div&gt; &lt;h2&gt;Title&lt;/h2&gt; &lt;p&gt;Text text text etc. this is the text body&lt;/p&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Here's my CSS:</p> <pre><code>.page { font-size: 100%; background-color: #777; display: flex; flex-wrap: wrap; justify-content: center; } .pic { width: 35%; float: right; margin-left: 20px; } </code></pre> <p>I tried putting the pic and credit in a div box &amp; using:</p> <pre><code>.pic-box { display: flex; flex-direction: column; } </code></pre> <p>in the CSS. This did not work.</p> <p>First time asking a question here, please let me know if I can improve!</p>
[ { "answer_id": 74587134, "author": "John", "author_id": 11111119, "author_profile": "https://Stackoverflow.com/users/11111119", "pm_score": 1, "selected": true, "text": "<picture> figcaption div <picture> picwrap figcaption piccap pic .picwrap {\n float: right;\n text-align: center;\n}\n\n.pic {\n max-width: 35vw;\n}\n .page {\n font-size: 100%;\n background-color: #777;\n display: flex;\n flex-wrap: wrap;\n justify-content: center;\n}\n\n.picwrap {\n float: right;\n text-align: center;\n}\n\n.pic {\n max-width: 35vw;\n} <!DOCTYPE html>\n<html>\n <head>\n <meta charset='UTF-8'/>\n <link rel='stylesheet' href='test.css'/>\n </head>\n <body>\n <div class=\"picwrap\">\n <img class='pic' src='https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2F3.bp.blogspot.com%2F-h0-QmJgoc0A%2FUynUaTP3h1I%2FAAAAAAAACOI%2FrmJPmSiM388%2Fs1600%2Fjavanes2.jpg&f=1&nofb=1&ipt=2d9c6496df9f3008cb82378322a186661b08e10918f56fd1458cf7d8db784cfe&ipo=images' alt=\"Person in blue shirt\" />\n <div class='piccap'>Photo Credit: Photographer</div>\n </div>\n <div>\n <h2>Title</h2>\n <p>Text text text etc. this is the text body Text text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text bodyText text text etc. this is the text body</p>\n </div>\n </body>\n</html>" }, { "answer_id": 74587364, "author": "Sudesh", "author_id": 20138824, "author_profile": "https://Stackoverflow.com/users/20138824", "pm_score": -1, "selected": false, "text": ".pic {\n width: 35%;\n float: center;\n margin-left: 20px;\n }\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74586964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19590444/" ]
74,587,063
<p>I seem to have a problem with my rendering. When I render to a framebuffer and then to screen, the images just seem less vibrant and kind of faded. Even simple ones.</p> <p><a href="https://i.stack.imgur.com/pRV6h.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pRV6h.png" alt="enter image description here" /></a></p> <p>In the picture above, the pink box on the right is rendered directly onto the screen buffer and the ones on the left are first rendered onto a framebuffer and then onto the screen.</p> <p>I am using a multisampled framebuffer and it seems to have made no difference. I tried only blending once by using GL_RGB on the framebuffer color texture that also didn't help. Any ideas?</p>
[ { "answer_id": 74587746, "author": "Summit", "author_id": 12651320, "author_profile": "https://Stackoverflow.com/users/12651320", "pm_score": -1, "selected": false, "text": "glGenTextures(1, &w_textureMsaaId);\nglBindTexture(GL_TEXTURE_2D_MULTISAMPLE, &w_textureMsaaId);\nglTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, w_msaa, GL_RGBA8, 1920, 1080, true);\nglBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0);\n glGenFramebuffers(1, &w_fboMsaaId);\nglGenRenderbuffers(1, &w_rboDepthId);\n \nglBindFramebuffer(GL_FRAMEBUFFER, w_fboMsaaId);\nglBindRenderbuffer(GL_RENDERBUFFER, w_rboDepthId);\nglRenderbufferStorageMultisample(GL_RENDERBUFFER, w_msaa, GL_DEPTH24_STENCIL8, 1920, 1080);\n// attach msaa RBOs to FBO attachment points \nglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, w_textureMsaaId[i], 0);\nglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, w_rboDepthId[i]);\n\n Blit this to a Frame buffer\n\nglBindFramebuffer(GL_READ_FRAMEBUFFER, w_fboMsaaId);\n glBindFramebuffer(GL_DRAW_FRAMEBUFFER, w_fboId);\n glBlitFramebuffer(0, 0, 1920, 1080, // src rect\n 0, 0, 1920, 1080, // dst rect\n GL_COLOR_BUFFER_BIT, // buffer mask\n GL_LINEAR);\n }\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3193075/" ]
74,587,064
<p>What would be the values after performing this operation?</p> <pre><code>#include &lt;stdio.h&gt; int main() { int *a = 0; int *b = 3; *a++ = *b++; printf(&quot;%d&quot;, a); printf(&quot;%d&quot;, b); return 0; } </code></pre> <p>The code above gives me a segmentation fault.</p>
[ { "answer_id": 74587086, "author": "Andrew Henle", "author_id": 4756299, "author_profile": "https://Stackoverflow.com/users/4756299", "pm_score": 1, "selected": false, "text": "#include <stdio.h>\nint main() {\n int *a = 0;\n int *b = 3;\n *a++ = *b++;\n printf(\"%d\", a);\n printf(\"%d\", b);\n return 0;\n}\n *a *b a b 3 printf(\"%d\", a); int * %d int printf(\"%p\", ( void * ) a);\n" }, { "answer_id": 74587110, "author": "ikegami", "author_id": 589924, "author_profile": "https://Stackoverflow.com/users/589924", "pm_score": 2, "selected": false, "text": "*a++ = *b++ *a++ = *b++;\n *(a++) = *(b++);\n x++ x *a = *b; // Copy the `int` to which `b` points into the `int` to which `a` points.\na = a + 1; // Make `a` point to the following `int`.\nb = b + 1; // Make `b` point to the following `int`.\n Before: After:\n\na a\n+----------+ +----------+ +----------+ +----------+\n| ---------->| x | | ------+ | p |\n+----------+ +----------+ +----------+ | +----------+\n | y | +--->| y |\n +----------+ +----------+\n | | | |\n\n\nb b\n+----------+ +----------+ +----------+ +----------+\n| ---------->| p | | ------+ | p |\n+----------+ +----------+ +----------+ | +----------+\n | q | +--->| q |\n +----------+ +----------+\n | | | |\n a b 0 3" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5293039/" ]
74,587,070
<p>Should numbers in scheme be quoted?</p> <p>In the following examples (tested in ikarus), it seems that quoting numbers does not matter while too much quoting creates problems.</p> <pre><code>&gt; (+ '1 1) 2 &gt; (+ '1 '1) 2 &gt; (+ '1 ''1) 1 </code></pre> <p><em>What is the standard way to use numbers (e.g. in the definition of a function body)? quoted or not quoted?</em></p>
[ { "answer_id": 74593591, "author": "Sylwester", "author_id": 1565698, "author_profile": "https://Stackoverflow.com/users/1565698", "pm_score": 2, "selected": false, "text": "(some 1) (#%app call-with-values (lambda () (#%app some (quote 1))) print-values))\n nil () () nil '()" }, { "answer_id": 74677679, "author": "alinsoar", "author_id": 1419272, "author_profile": "https://Stackoverflow.com/users/1419272", "pm_score": 0, "selected": false, "text": "(quote <datum>)‌‌ <Datum> (quote <datum>) <datum> '\"aa\" '123 sexp S-Expression datun quotation A Micro-Manual for Lisp" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4196578/" ]
74,587,071
<p>I am trying to run the following python script to extract data from google scholar.However, when I run the code,I am getting an empty list as a json response.Note that all necessary libraries are installed.</p> <pre><code>headers = { 'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36' } params = { 'q': 'Machine learning', 'hl': 'en' } html = requests.get('https://scholar.google.com/scholar', headers=headers, params=params).text soup = BeautifulSoup(html, 'lxml') # JSON data will be collected here data = [] # Container where all needed data is located for result in soup.select('.gs_r.gs_or.gs_scl'): title = result.select_one('.gs_rt').text title_link = result.select_one('.gs_rt a')['href'] publication_info = result.select_one('.gs_a').text snippet = result.select_one('.gs_rs').text cited_by = result.select_one('#gs_res_ccl_mid .gs_nph+ a')['href'] related_articles = result.select_one('a:nth-child(4)')['href'] try: all_article_versions = result.select_one('a~ a+ .gs_nph')['href'] except: all_article_versions = None try: pdf_link = result.select_one('.gs_or_ggsm a:nth-child(1)')['href'] except: pdf_link = None data.append({ 'title': title, 'title_link': title_link, 'publication_info': publication_info, 'snippet': snippet, 'cited_by': f'https://scholar.google.com{cited_by}', 'related_articles': f'https://scholar.google.com{related_articles}', 'all_article_versions': f'https://scholar.google.com{all_article_versions}', &quot;pdf_link&quot;: pdf_link }) print(json.dumps(data, indent = 2, ensure_ascii = False)) </code></pre> <p>Output: []</p>
[ { "answer_id": 74593591, "author": "Sylwester", "author_id": 1565698, "author_profile": "https://Stackoverflow.com/users/1565698", "pm_score": 2, "selected": false, "text": "(some 1) (#%app call-with-values (lambda () (#%app some (quote 1))) print-values))\n nil () () nil '()" }, { "answer_id": 74677679, "author": "alinsoar", "author_id": 1419272, "author_profile": "https://Stackoverflow.com/users/1419272", "pm_score": 0, "selected": false, "text": "(quote <datum>)‌‌ <Datum> (quote <datum>) <datum> '\"aa\" '123 sexp S-Expression datun quotation A Micro-Manual for Lisp" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15545208/" ]
74,587,080
<p>Sorry I am still a beginner but slowly getting there. I want to change all the &quot;base-purchase-prices&quot; by a % all at once? I am tearing my hair out trying to work out how to do it. There are 7000 line items so simply saying &quot;get a calculator&quot; is not going to work</p> <pre class="lang-json prettyprint-override"><code>{ &quot;tradeable-code&quot;: &quot;Scissors_01&quot;, &quot;base-purchase-price&quot;: &quot;110&quot;, &quot;base-sell-price&quot;: &quot;12&quot;, &quot;delta-price&quot;: &quot;-1.0&quot;, &quot;can-be-purchased&quot;:&quot;default&quot; }, { &quot;tradeable-code&quot;: &quot;Scissors_Plastic&quot;, &quot;base-purchase-price&quot;: &quot;88&quot;, &quot;base-sell-price&quot;: &quot;9&quot;, &quot;delta-price&quot;: &quot;-1.0&quot;, &quot;can-be-purchased&quot;:&quot;default&quot; }, </code></pre>
[ { "answer_id": 74593591, "author": "Sylwester", "author_id": 1565698, "author_profile": "https://Stackoverflow.com/users/1565698", "pm_score": 2, "selected": false, "text": "(some 1) (#%app call-with-values (lambda () (#%app some (quote 1))) print-values))\n nil () () nil '()" }, { "answer_id": 74677679, "author": "alinsoar", "author_id": 1419272, "author_profile": "https://Stackoverflow.com/users/1419272", "pm_score": 0, "selected": false, "text": "(quote <datum>)‌‌ <Datum> (quote <datum>) <datum> '\"aa\" '123 sexp S-Expression datun quotation A Micro-Manual for Lisp" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20610878/" ]
74,587,092
<p>I am trying to make my bot send a welcome message when someone joins a specific server.</p> <p>Code:</p> <pre><code>if member.guild.id == 928443083660607549: new = nextcord.utils.get(member.guild.roles, name=&quot;new&quot;) channel = bot.get_channel(996767690091925584) embed = nextcord.Embed(title=&quot;welcome to ikari!&quot;, description=&quot;・make sure to read the rules in &lt;#928443083698360397&gt; \n ・for more questions refer to &lt;#928507764714651698&gt;&quot;, color=0x303136) embed.set_author(name=f&quot;{member.name}#{member.discriminator}&quot;, icon_url=member.display_avatar_url) embed.set_thumbnail(url=member.guild.icon.url) await channel.send(f&quot;{member.mention}!&quot;, embed=embed) await member.add_roles(new)Error: </code></pre> <p>Error:</p> <p><code>AttributeError: 'Member' object has no attribute 'display_avatar_url'</code></p>
[ { "answer_id": 74593997, "author": "Sham", "author_id": 15574114, "author_profile": "https://Stackoverflow.com/users/15574114", "pm_score": 1, "selected": false, "text": ".avatar_url .avatar.url .icon_url .icon.url member.display_avatar.url .avatar_with_size(...) .avatar.with_size(...)" }, { "answer_id": 74620003, "author": "judee", "author_id": 14523864, "author_profile": "https://Stackoverflow.com/users/14523864", "pm_score": 0, "selected": false, "text": "embed.set_author(name=f\"{member.name}#{member.discriminator}\", icon_url=member.display_avatar_url) embed.set_author(name=f\"{member.name}#{member.discriminator}\", icon_url=member.display_avatar.url)" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20090591/" ]
74,587,124
<p>I am trying to shortern my code by using functions and <code>for</code> loops.</p> <p>For the example below, I would like to create 5 different objects and then apply <code>raster</code> to each object that is created. How can I do this with loops and functions?</p> <pre><code>#Defining variables of interest url = &quot;https://files.isric.org/soilgrids/latest/data/&quot; # Path to the webDAV data. voi1 = &quot;sand&quot; voi2 = &quot;clay&quot; voi3 = &quot;silt&quot; voi4 = &quot;phh2o&quot; voi5 = &quot;soc&quot; depth = &quot;5-15cm&quot; quantile = &quot;mean&quot; # prediction uncertainty quantified by probability distribution. Using mean of distribution voi_layer1 = paste(paste(paste(url, voi1, &quot;/&quot;, voi1, sep=&quot;&quot;), depth, quantile, sep=&quot;_&quot;), '.vrt', sep=&quot;&quot;) voi_layer2 = paste(paste(paste(url, voi2, &quot;/&quot;, voi2, sep=&quot;&quot;), depth, quantile, sep=&quot;_&quot;), '.vrt', sep=&quot;&quot;) voi_layer3 = paste(paste(paste(url, voi3, &quot;/&quot;, voi3, sep=&quot;&quot;), depth, quantile, sep=&quot;_&quot;), '.vrt', sep=&quot;&quot;) voi_layer4 = paste(paste(paste(url, voi4, &quot;/&quot;, voi4, sep=&quot;&quot;), depth, quantile, sep=&quot;_&quot;), '.vrt', sep=&quot;&quot;) voi_layer5 = paste(paste(paste(url, voi5, &quot;/&quot;, voi5, sep=&quot;&quot;), depth, quantile, sep=&quot;_&quot;), '.vrt', sep=&quot;&quot;) #Apply 'raster' so can derive descriptions of each layer sand = raster(voi_layer1) clay = raster(voi_layer2) silt = raster(voi_layer3) ph = raster(voi_layer4) org_carb = raster(voi_layer5) </code></pre>
[ { "answer_id": 74587416, "author": "jdobres", "author_id": 6436545, "author_profile": "https://Stackoverflow.com/users/6436545", "pm_score": 2, "selected": false, "text": "voi base_url <- \"https://files.isric.org/soilgrids/latest/data/\" # Path to the webDAV data.\nvoi <- c('sand', 'clay', 'silt', 'phh2o', 'soc')\ndepth <- \"5-15cm\"\nquantile <- \"mean\" \n sprintf urls <- sprintf('%s%s/%s_%s_%s.vrt', base_url, voi, voi, depth, quantile)\nnames(urls) <- voi\n sand \n \"https://files.isric.org/soilgrids/latest/data/sand/sand_5-15cm_mean.vrt\" \n clay \n \"https://files.isric.org/soilgrids/latest/data/clay/clay_5-15cm_mean.vrt\" \n silt \n \"https://files.isric.org/soilgrids/latest/data/silt/silt_5-15cm_mean.vrt\" \n phh2o \n\"https://files.isric.org/soilgrids/latest/data/phh2o/phh2o_5-15cm_mean.vrt\" \n soc \n \"https://files.isric.org/soilgrids/latest/data/soc/soc_5-15cm_mean.vrt\" \n lapply raster() lapply rasters <- lapply(urls, raster)\n urls rasters rasters[1] rasters['sand']" }, { "answer_id": 74587429, "author": "Bei", "author_id": 16569807, "author_profile": "https://Stackoverflow.com/users/16569807", "pm_score": 1, "selected": false, "text": "assign glue paste raster library(glue)\n\nraster_object <- function(url, voi, depth, quantile){\n return(raster(glue(\"{url}/{voi}/{voi}_{depth}_{quantile}.vrt\")))\n}\n\nfor (voi in c(\"sand\", \"clay\")){\n assign(glue(\"raster_{voi}\"), raster_object(url = \"https://files.isric.org/soilgrids/latest/data\", voi, depth = \"5-15cm\", quantile = \"mean\"))\n}\n\n" }, { "answer_id": 74595463, "author": "Robert Hijmans", "author_id": 635245, "author_profile": "https://Stackoverflow.com/users/635245", "pm_score": 2, "selected": true, "text": "url = \"https://files.isric.org/soilgrids/latest/data/\"\nvoi = c(\"sand\", \"clay\", \"silt\", \"phh2o\", \"soc\")\ndepth = \"5-15cm\"\nquantile = \"mean\"\n\nf <- paste0(url, voi, \"/\", paste(voi, depth, quantile, sep=\"_\"), '.vrt')\n library(terra)\nx <- sds(f)\n y <- lapply(f, rast)\n geodata::soil_world geodata::soil_world_vsi" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7093872/" ]
74,587,172
<p>I am writing a flutter program that gets user details. Unfortunately even though my TextEditing Controllers are set up correctly. Everytime I click a button or a radio button, textboxes are cleared instantly even though I did not have any code that clears them</p> <p>Here is the code</p> <pre><code> import 'package:flutter/material.dart'; import 'NavDrawer.dart'; class proFile extends StatelessWidget { static const String routeName = '/profile'; const proFile({super.key}); @override build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text(&quot;Profile&quot;), ), drawer: const NavDrawer(), body: ProfileScreen()); } } class ProfileScreen extends StatefulWidget { const ProfileScreen({super.key}); @override _ProfileScreenState createState() { return _ProfileScreenState(); } } enum Gender { male, female } String getGender=&quot;&quot;; class _ProfileScreenState extends State&lt;ProfileScreen&gt; { @override Gender? _gender = Gender.male; Widget build(BuildContext context1) { TextEditingController getUsername = TextEditingController(); TextEditingController getFName = TextEditingController(); TextEditingController getLName = TextEditingController(); TextEditingController getPass = TextEditingController(); TextEditingController getCPass = TextEditingController(); TextEditingController getEmail = TextEditingController(); TextEditingController var5 = TextEditingController(); return SingleChildScrollView( child: Column( children: &lt;Widget&gt;[ Row( children: &lt;Widget&gt;[ Container( margin: EdgeInsets.all(20), child: Text(&quot;Enter Your Profile&quot;, style: TextStyle(fontSize: 40, color: Colors.black)), ), ], ), //row2 Row( mainAxisAlignment: MainAxisAlignment.center, children: &lt;Widget&gt;[ Container( height: 50, width: 500, margin: EdgeInsets.all(10), child: TextField( keyboardType: TextInputType.text, controller: getUsername, decoration: InputDecoration( border: const OutlineInputBorder( borderSide: const BorderSide(color: Colors.lightGreen)), labelText: &quot;Enter Your UserName&quot;)), ) ], ), //row3 Row( mainAxisAlignment: MainAxisAlignment.center, children: &lt;Widget&gt;[ Container( height: 50, width: 500, margin: EdgeInsets.all(10), child: TextField( controller: getFName, keyboardType: TextInputType.text, decoration: InputDecoration( border: const OutlineInputBorder( borderSide: const BorderSide(color: Colors.lightGreen)), labelText: &quot;Enter Your First Name&quot;)), ) ], ), //row4 Row( mainAxisAlignment: MainAxisAlignment.center, children: &lt;Widget&gt;[ Container( height: 50, width: 500, margin: EdgeInsets.all(10), child: TextField( controller: getLName, keyboardType: TextInputType.text, decoration: InputDecoration( border: const OutlineInputBorder( borderSide: const BorderSide(color: Colors.lightGreen)), labelText: &quot;Enter Your Last Name&quot;)), ) ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: &lt;Widget&gt;[ Container( height: 50, width: 500, margin: EdgeInsets.all(10), child: TextField( controller: getPass, keyboardType: TextInputType.text, decoration: InputDecoration( border: const OutlineInputBorder( borderSide: const BorderSide(color: Colors.lightGreen)), labelText: &quot;Enter Your Password&quot;)), ) ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: &lt;Widget&gt;[ Container( height: 50, width: 500, margin: EdgeInsets.all(10), child: TextField( controller: getCPass, keyboardType: TextInputType.text, decoration: InputDecoration( border: const OutlineInputBorder(), labelText: &quot;Confirm Your Password&quot;)), ) ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: &lt;Widget&gt;[ Container( height: 50, width: 500, margin: EdgeInsets.all(10), child: TextField( controller: getEmail, keyboardType: TextInputType.text, decoration: InputDecoration( border: const OutlineInputBorder(), labelText: &quot;Enter Your Email&quot;)), ) ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: &lt;Widget&gt;[ Container( height: 50, width: 400, child:ListTile( title: const Text('Male'), leading: Radio( value: Gender.male, groupValue: _gender, onChanged: (Gender? value) { setState(() { _gender = value; }); }, ), ), ), Container( height: 50, width: 400, child:ListTile( title: const Text('Female'), leading: Radio( value: Gender.female, groupValue: _gender, onChanged: (Gender? value) { setState(() { _gender = value; }); }, ), ), ) ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: &lt;Widget&gt;[ Container( height: 100, width: 500, margin: EdgeInsets.all(1), child: TextField( maxLines: 8, controller: var5, keyboardType: TextInputType.text, decoration: InputDecoration( border: const UnderlineInputBorder(borderSide: const BorderSide(color: Colors.lightGreen)), labelText: &quot;&quot;)), ) ], ), Row( //button children: &lt;Widget&gt;[ const SizedBox(height: 55.0, width: 20.0), SizedBox( width: 250.0, height: 70, child: ElevatedButton( child: const Text(&quot;Submit!&quot;), style: ElevatedButton.styleFrom( backgroundColor: Colors.green, padding: EdgeInsets.all(20), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20))), onPressed: () { setState(() { String name = getUsername.text; String fname = getFName.text; String lname = getLName.text; String pass = getPass.text; String cpass = getCPass.text; String email = getEmail.text; var5.text=&quot;Inputted Result:\nName=$name\nFirst Name=$fname\nLast Name=$lname\nEmail=$email&quot;; }); }, ), ), ]), ], ), ); } } </code></pre> <p>I tried clearing the radio button to see if it is the root of the issue but it still happens on the button</p>
[ { "answer_id": 74588290, "author": "TimeToCode", "author_id": 14454875, "author_profile": "https://Stackoverflow.com/users/14454875", "pm_score": 0, "selected": false, "text": "onPressed(){} var5.text =\"Inputted Result:\\nName=${getUsername.text}\\nFirst Name=${getFName.text}\\nLast Name=${getLName.text}\\nEmail=${getEmail.text}\";\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10691734/" ]
74,587,191
<p>Input file is minified css file:</p> <pre><code>.class{margin:0px}.class1,.class2{margin 0px}@media{.class{color:blue}.class1,.class2{color:red}}@media{.classA.classB,.classC{margin:0px}}@media{.classD,.classE{color:blue}.class1,.class2{color:red}}@media only screen and (min-width: 1441px){.classX(color:blue}}@media only screen and (min-width: 1441px){.class{color:blue}.class1,.class2{color:red}}@media only screen and (min-width: 1441px){.classA.classB,.classC{margin:0px}}@media only screen and (inverted-colors){.classD,.classE{color:blue}.class1,.class2{color:red}.classV{color:red}.classR{color:red}.classU{color:red}.classS{color:red}.classT{color:red}}.classNew{margin: 10px} </code></pre> <p>Expected result:</p> <pre><code>.class{margin:0px} .class1,.class2{margin 0px} @media{.class{color:blue}.class1,.class2{color:red}} @media{.classA.classB,.classC{margin:0px}} @media{.classD,.classE{color:blue}.class1,.class2{color:red}} @media only screen and (min-width: 1441px){.classX(color:blue}} @media only screen and (min-width: 1441px){.class{color:blue}.class1,.class2{color:red}} @media only screen and (min-width: 1441px){.classA.classB,.classC{margin:0px}} @media only screen and (inverted-colors){.classD,.classE{color:blue}.class1,.class2{color:red}.classV{color:red}.classR{color:red}.classU{color:red}.classS{color:red}.classT{color:red}} .classNew{margin: 10px} </code></pre> <p>When I use this:</p> <pre><code>awk '{gsub(/\t?}/, &quot;}\n&quot;); print}' </code></pre> <p>It gives following result which does not match with expected result above:</p> <pre><code>.class{margin:0px} .class1,.class2{margin 0px} @media{.class{color:blue} .class1,.class2{color:red} } @media{.classA.classB,.classC{margin:0px} } @media{.classD,.classE{color:blue} .class1,.class2{color:red} } @media only screen and (min-width: 1441px){.classX(color:blue} } @media only screen and (min-width: 1441px){.class{color:blue} .class1,.class2{color:red} } @media only screen and (min-width: 1441px){.classA.classB,.classC{margin:0px} } @media only screen and (inverted-colors){.classD,.classE{color:blue} .class1,.class2{color:red} .classV{color:red} .classR{color:red} .classU{color:red} .classS{color:red} .classT{color:red} } .classNew{margin: 10px} </code></pre> <p>Here is my idea to get expected result:</p> <p><em>find {<br /> then<br /> after that check if next char is } or {<br /> if }<br /> then<br /> add new line after }<br /> if {<br /> after that check if next char is }}<br /> if }}<br /> then<br /> add new line after }}<br /> go through the input file</em></p>
[ { "answer_id": 74588290, "author": "TimeToCode", "author_id": 14454875, "author_profile": "https://Stackoverflow.com/users/14454875", "pm_score": 0, "selected": false, "text": "onPressed(){} var5.text =\"Inputted Result:\\nName=${getUsername.text}\\nFirst Name=${getFName.text}\\nLast Name=${getLName.text}\\nEmail=${getEmail.text}\";\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16645747/" ]
74,587,197
<p>I'm trying to create a spreadsheet that sorts a list of assignments by their due date simply by clicking a checkbox and marking it true. I'm very new to JavaScript and using spreadsheets, but I do have some coding background, mainly Java and Python.</p> <p>My code so far is this. The checkbox is in the top left (cell A1) and I have the dates in column C (column 3). Theres a lot of unused variables and other extra things because I copied some lines from other places and posts. As of right now it does nothing when I press the checkbox. Idk what half of this does, so any advice is welcome. Just don't roast me too much plz haha</p> <pre><code>function SortbyCheck(input) { var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange(&quot;A3:E&quot;); const DateRange = [A3:E] // Sorts by the values in the second column (B) //range.sort(3); if(s.getName() == &quot;Sheet1&quot; &amp;&amp; r.getColumn() == 1 &amp;&amp; r.getRow() == 1 &amp;&amp; r.getValue() == true) { // Sorts descending by column B DateRange.sort(3); } } </code></pre>
[ { "answer_id": 74588290, "author": "TimeToCode", "author_id": 14454875, "author_profile": "https://Stackoverflow.com/users/14454875", "pm_score": 0, "selected": false, "text": "onPressed(){} var5.text =\"Inputted Result:\\nName=${getUsername.text}\\nFirst Name=${getFName.text}\\nLast Name=${getLName.text}\\nEmail=${getEmail.text}\";\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20610988/" ]
74,587,213
<h1>i have two class</h1> <pre><code>public class Person { public String name = &quot;person&quot;; public String getName(){ return name; }; } </code></pre> <pre><code>public class Teacher extends Person{ public String name =&quot;teacher&quot;; public static void main(String[] args) { Teacher teacher = new Teacher(); System.out.println(teacher.getName()); } } </code></pre> <ol> <li>the output of the code teacher.getName() is &quot;person&quot; why?</li> </ol> <p>**not matter the modify of the name property is private or public the result always is &quot;person&quot; but what i learn so far told me that if a subclass extends from a superClass it also entends the methods from superClass so when i call the method of subclass object, the name in method should be this.name and this should be teacher right?,but why i still get the name of superClass? **</p>
[ { "answer_id": 74587322, "author": "JasonTrue", "author_id": 13433, "author_profile": "https://Stackoverflow.com/users/13433", "pm_score": 0, "selected": false, "text": "private protected return \"teacher\"; super(name)" }, { "answer_id": 74587356, "author": "tgdavies", "author_id": 11002, "author_profile": "https://Stackoverflow.com/users/11002", "pm_score": 1, "selected": false, "text": "name name class Person {\n private final String name;\n\n public Person(String name) {\n this.name = name;\n }\n\n public String getName() {\n return this.name;\n }\n}\n\n\nclass Teacher extends Person {\n public Teacher(String name) {\n super(name);\n }\n\n public static void main(String[] args) {\n Teacher teacher = new Teacher(\"teacher\");\n System.out.println(teacher.getName());\n }\n}\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16768357/" ]
74,587,219
<p>I have that HTML:</p> <pre><code>&lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;cell left&quot;&gt;A&lt;/div&gt; &lt;div class=&quot;cell left&quot;&gt;B&lt;/div&gt; &lt;div class=&quot;cell right&quot;&gt;C&lt;/div&gt; &lt;div class=&quot;cell left&quot;&gt;D&lt;/div&gt; &lt;div class=&quot;cell right&quot;&gt;E&lt;/div&gt; &lt;div class=&quot;cell left&quot;&gt;F&lt;/div&gt; &lt;/div&gt; </code></pre> <p>I want to obtain that:</p> <p><a href="https://i.stack.imgur.com/wINpp.png" rel="nofollow noreferrer">Example:</a></p> <p>All &quot;cell left&quot; have to be align to left and top. All &quot;cell right&quot; have to be align to right and top.</p> <p>The layout of the HTML must remain as is. How to define CSS using FLEX or FLOAT? The order or number of cells in each row is not known or regular.</p> <p>I tried to do it using FLEX or FLOAT, but the right cells are not top-aligned.</p>
[ { "answer_id": 74587241, "author": "Mohammed", "author_id": 7932650, "author_profile": "https://Stackoverflow.com/users/7932650", "pm_score": 0, "selected": false, "text": "<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width\">\n <title>JS Bin</title>\n <style>\n .row {\n display: flex;\n flex-direction: column;\n width: 200px;\n }\n .left {\n align-self: flex-start;\n }\n \n .right {\n align-self: flex-end;\n }\n </style>\n</head>\n<body>\n<div class=\"row\">\n <div class=\"cell left\">A</div>\n <div class=\"cell left\">B</div>\n <div class=\"cell right\">C</div>\n <div class=\"cell left\">D</div>\n <div class=\"cell right\">E</div>\n <div class=\"cell left\">F</div>\n</div>\n</body>\n</html>" }, { "answer_id": 74587503, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 2, "selected": true, "text": "display: grid display: grid /* In 2 columns of same size, auto place item by row and fill gaps */\n\ngrid-template-columns: repeat(2, 1fr);\ngrid-auto-flow: row dense;\n left right grid-column div .row {\n display: grid;\n width: 500px;\n grid-template-columns: repeat(2, 1fr);\n grid-auto-flow: row dense;\n gap: 12px;\n outline: 2px solid #000;\n padding: 12px;\n}\n\n.cell {\n padding: 12px;\n}\n\n.left {\n grid-column: 1 / span 1;\n background-color: pink;\n}\n\n.right {\n grid-column: 2 / span 1;\n background-color: lightgreen;\n} <div class=\"row\">\n <div class=\"cell left\">A</div>\n <div class=\"cell left\">B</div>\n <div class=\"cell right\">C</div>\n <div class=\"cell left\">D</div>\n <div class=\"cell right\">E</div>\n <div class=\"cell left\">F</div>\n</div>" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20611008/" ]
74,587,238
<p>I have a dataframe of transactions with the unique ID of a product, seller and buyer. I want to keep a record whether someone has bought a product and later resold it. Here's a simplified view of my dataset:</p> <pre><code> prod_id seller buyer 0 cc_123 x y 1 cc_111 d y 2 cc_025 y x 3 cc_806 d m 4 cc_963 a b 5 cc_235 o h 6 cc_806 m t 7 cc_555 z w 8 cc_444 s q </code></pre> <p>My initial idea was to group by id and compare consecutive rows in the grouped dataframe, by checking if the seller of the current row is the same person as the buyer of the previous row for a given product, e.g., transaction 6 is a resale because the same person &quot;m&quot; previously bought and is now selling product cc_806:</p> <pre><code> prod_id seller buyer 3 cc_806 d m 6 cc_806 m t </code></pre> <p>So the final dataset would look like this:</p> <pre><code> prod_id seller buyer resale 0 cc_123 x y 0 1 cc_111 d y 0 2 cc_025 y x 0 3 cc_806 d m 0 4 cc_963 a b 0 5 cc_235 o h 0 6 cc_806 m t 1 7 cc_555 z w 0 8 cc_444 s q 0 </code></pre> <p>Where 1 means yes/true and 0 means no/false. My attempt is not working:</p> <pre><code>df['resale'] = df.groupby('prod_id')['seller'] == df.groupby('prod_id')['buyer'].shift(1) </code></pre> <p>Is there an efficient solution for this?</p>
[ { "answer_id": 74587302, "author": "JayPeerachai", "author_id": 12135518, "author_profile": "https://Stackoverflow.com/users/12135518", "pm_score": 3, "selected": true, "text": "groupby df['resale'] = df.groupby('prod_id')['buyer'].shift(1) == df['seller']\ndf['resale'] = df['resale'].astype(int)\ndf\n prod_id seller buyer resale\n0 cc_123 x y 0\n1 cc_111 d y 0\n2 cc_025 y x 0\n3 cc_806 d m 0\n4 cc_963 a b 0\n5 cc_235 o h 0\n6 cc_806 m t 1\n7 cc_555 z w 0\n8 cc_444 s q 0\n" }, { "answer_id": 74587482, "author": "wrbp", "author_id": 16662333, "author_profile": "https://Stackoverflow.com/users/16662333", "pm_score": 1, "selected": false, "text": "df[\"resale\"]=df.apply(lambda x: len(df[(df[\"prod_id\"]==x[\"prod_id\"])& (df[\"buyer\"]==x[\"seller\"])]),axis=1)\n prod_id seller buyer resale\n0 cc_123 x y 0\n1 cc_111 d y 0\n2 cc_025 y x 0\n3 cc_806 d m 0\n4 cc_963 a b 0\n5 cc_235 o h 0\n6 cc_806 m t 1\n7 cc_555 z w 0\n8 cc_444 s q 0\n\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5249282/" ]
74,587,297
<p>I have a dataframe which looks like:</p> <pre><code>df &lt;- data.frame(col1 = c(2,3,6,1,8,4,8,2,4,5,7,4,2,7),col2 = c(rep(1,4),rep(2,3),rep(3,4),rep(4,3))) </code></pre> <p>Now I want a column <code>rem_val</code> which starts with a starting value 40 grouped by column <code>col2</code>, and subtracts the previous row from <code>col1</code> from this value.</p> <p>So the dataframe should look like:</p> <p><img src="https://i.stack.imgur.com/Xg8Dq.png" alt="" /></p> <p>I thought of reverse cumulative frequency but I want to have a starting value which is defined by the user, like 40 here.</p>
[ { "answer_id": 74587332, "author": "Jon Spring", "author_id": 6851825, "author_profile": "https://Stackoverflow.com/users/6851825", "pm_score": 3, "selected": true, "text": "library(dplyr)\ndf %>%\n group_by(col2) %>%\n mutate(rem_val = 40 - cumsum(lag(col1, default = 0))) %>% \n ungroup()\n" }, { "answer_id": 74587381, "author": "AndS.", "author_id": 9778513, "author_profile": "https://Stackoverflow.com/users/9778513", "pm_score": 0, "selected": false, "text": "library(tidyverse)\n\ndf |> \n group_by(col2) |>\n mutate(rem_val = Reduce(\"-\", head(col1, n()-1), accumulate = TRUE, init = 40))\n#> # A tibble: 14 x 3\n#> # Groups: col2 [4]\n#> col1 col2 rem_val\n#> <dbl> <dbl> <dbl>\n#> 1 2 1 40\n#> 2 3 1 38\n#> 3 6 1 35\n#> 4 1 1 29\n#> 5 8 2 40\n#> 6 4 2 32\n#> 7 8 2 28\n#> 8 2 3 40\n#> 9 4 3 38\n#> 10 5 3 34\n#> 11 7 3 29\n#> 12 4 4 40\n#> 13 2 4 36\n#> 14 7 4 34\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20565621/" ]
74,587,299
<p>What are the best practices for resolving JPA bidirectional circular references?</p> <p>I experienced an error falling into infinite recursion due to JPA bidirectional circular reference.</p> <p>At this time, it was said that the problem could be solved in the following way.</p> <ol> <li><p>Ignore using <code>@JsonIgnore</code> -&gt; I ruled out this option because I need all the data.</p> </li> <li><p>Use <code>@JsonBackReference</code>, <code>@JsonManagedReference</code>. -&gt; Currently, I have solved my problem using this method.</p> </li> </ol> <p>I'm wondering if there's a better way to solve the problem, so I'm leaving a question like this.</p> <p>best regards!</p>
[ { "answer_id": 74614213, "author": "Simon Martinelli", "author_id": 1045142, "author_profile": "https://Stackoverflow.com/users/1045142", "pm_score": 1, "selected": true, "text": "@JsonBackReference @JsonManagedReference @JsonIngore" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20598738/" ]
74,587,327
<p>Say I have an array of 5000 elements. Somewhere in the middle of the array, say from a[4200] through a[4300], is data. Values outside of this range return null.</p> <p>What is the most efficient way to find the first and last entry containing data, <strong>while querying the array as few times as possible</strong>? Is there a name for what I'm trying to do?</p>
[ { "answer_id": 74590746, "author": "Matt Timmermans", "author_id": 5483526, "author_profile": "https://Stackoverflow.com/users/5483526", "pm_score": 1, "selected": false, "text": "def findData(A):\n if (len(A)<1):\n return None\n q = [(0,len(A))]\n pos = 0\n while pos < len(q):\n (s,e) = q[pos]\n pos += 1\n mid = s + (e-s)//2\n if A[mid] == None:\n # Didn't find data. Subdivide range\n if mid > s:\n q.append((s,mid))\n if mid+1 < e:\n q.append((mid+1,e))\n continue\n\n # Found data\n maxs = mid # max start pos\n mine = mid+1 # min end pos\n\n # Binary search to find start\n while s < maxs:\n mid = s + (maxs-s)//2\n if A[mid] == None:\n s = mid+1\n else:\n maxs = mid\n \n # Binary search to find end\n while mine < e:\n mid = mine + (e-mine)//2\n if A[mid] == None:\n e = mid\n else:\n mine = mid+1\n \n return(s,e)\n \n # Searched the whole array and found no data\n return None\n $> print(findData([\n None,None,None,1,2,3,4,5,None\n]))\n(3,8)\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/864499/" ]
74,587,328
<p>My code generates 5 random numbers and I want the user to guess these numbers after 5 seconds of flashing it.</p> <pre><code>#include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; #include&lt;stdbool.h&gt; main() { menuchoose1(); } int menuchoose1(){ int menu1choose; int score=0; int mode,i,j; int n=5; printf(&quot;1.Continuous Mode\n&quot;); printf(&quot;2.Stage Mode\n&quot;); scanf(&quot;%d&quot;,&amp;menu1choose); switch(menu1choose){ int answers; case 1: srand(time(NULL)* getpid() ); int a[5]; unique(a,5,10,99); int i; printf(&quot;You have 5 seconds to remember these numbers\n&quot;); for(i=0;i&lt;5;i++) printf(&quot;%d\t&quot;,a[i]); sleep(5); system(&quot;cls&quot;); scanf(&quot;%d&quot;,&amp;answers); if(answers==a[i]){ printf(&quot;Correct&quot;); }else printf(&quot;Incorrect&quot;); break; } return; } void unique(int array[], int length, int min, int max){ int new_randomnum; bool unique; int i; for(i=0;i&lt;length;i++){ do{ new_randomnum = (rand()%(max - min + 1 )) + min; unique = true; int j; for(j=0;j&lt;0;j++) if(array[j] == new_randomnum) unique = false; }while(!unique); array[i] = new_randomnum; } } </code></pre> <p>I've tried using scanf but it always ends up incorrect and generating it one by one then checking it one by one would be inefficient.</p>
[ { "answer_id": 74590746, "author": "Matt Timmermans", "author_id": 5483526, "author_profile": "https://Stackoverflow.com/users/5483526", "pm_score": 1, "selected": false, "text": "def findData(A):\n if (len(A)<1):\n return None\n q = [(0,len(A))]\n pos = 0\n while pos < len(q):\n (s,e) = q[pos]\n pos += 1\n mid = s + (e-s)//2\n if A[mid] == None:\n # Didn't find data. Subdivide range\n if mid > s:\n q.append((s,mid))\n if mid+1 < e:\n q.append((mid+1,e))\n continue\n\n # Found data\n maxs = mid # max start pos\n mine = mid+1 # min end pos\n\n # Binary search to find start\n while s < maxs:\n mid = s + (maxs-s)//2\n if A[mid] == None:\n s = mid+1\n else:\n maxs = mid\n \n # Binary search to find end\n while mine < e:\n mid = mine + (e-mine)//2\n if A[mid] == None:\n e = mid\n else:\n mine = mid+1\n \n return(s,e)\n \n # Searched the whole array and found no data\n return None\n $> print(findData([\n None,None,None,1,2,3,4,5,None\n]))\n(3,8)\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20586932/" ]
74,587,344
<p>I'm coding a discord bot and it works fine until I try and use one of the ! commands (Like !hello) and then It comes up with this</p> <pre><code>ERROR discord.client Ignoring exception in on_message Traceback (most recent call last): File &quot;C:\Users\vanti\PycharmProjects\discordbot4thtry\venv\Lib\site-packages\discord\client.py&quot;, line 409, in _run_event await coro(*args, **kwargs) File &quot;C:\Users\vanti\PycharmProjects\discordbot4thtry\bot.py&quot;, line 33, in on_message if user_message[0] == '%': ~~~~~~~~~~~~^^^ IndexError: string index out of range </code></pre> <p>The % is supposed to make the bot send you the response in a DM e.g. if I do !hello it would reply in the channel with &quot;Hello there!&quot; but if I put %hello it would send &quot;Hello There!&quot; as a DM</p> <pre><code>import discord import responses async def send_message(message, user_message, is_private): try: response = responses.handle_response(user_message) await message.author.send(response) if is_private else await message.channel.send(response) except Exception as e: print(e) def run_discord_bot(): TOKEN = 'This is where the bots token would go' client = discord.Client(intents=discord.Intents.default()) @client.event async def on_ready(): print(f'{client.user} is now running!') @client.event async def on_message(message): if message.author == client.user: return username = str(message.author) user_message = str(message.content) channel = str(message.channel) print(f&quot;{username} said: '{user_message}' ({channel})&quot;) if user_message[0] == '%': user_message = user_message[1:] await send_message(message, user_message, is_private=True) else: await send_message(message, user_message, is_private=False) client.run(TOKEN) </code></pre>
[ { "answer_id": 74587382, "author": "ScottC", "author_id": 20174226, "author_profile": "https://Stackoverflow.com/users/20174226", "pm_score": -1, "selected": false, "text": "if len(user_message) > 0:\n @client.event\n async def on_message(message):\n if message.author == client.user:\n return\n\n username = str(message.author)\n user_message = str(message.content)\n channel = str(message.channel)\n\n print(f\"{username} said: '{user_message}' ({channel})\")\n\n if len(user_message) > 0:\n if user_message[0] == '%':\n user_message = user_message[1:]\n await send_message(message, user_message, is_private=True)\n else:\n await send_message(message, user_message, is_private=False)\n\n client.run(TOKEN)\n" }, { "answer_id": 74587383, "author": "Soumendra", "author_id": 5014656, "author_profile": "https://Stackoverflow.com/users/5014656", "pm_score": 1, "selected": false, "text": "message_content intents.message_content = True\n def run_discord_bot():\n TOKEN = 'This is where the bots token would go'\n intents = discord.Intents.default()\n intents.message_content = True\n client = discord.Client(intents=intents)\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20611218/" ]
74,587,345
<p>Is there any fast function to do the following code?</p> <pre><code>ArrayList&lt;Double&gt; A = new ArrayList&lt;&gt;(); ArrayList&lt;Double&gt; B = new ArrayList&lt;&gt;(); //ignore adding steps // A = [1,2,3,4,5] // B = [0,1,2,3,4] C = A - B // get C = [1,1,1,1,1] </code></pre>
[ { "answer_id": 74587382, "author": "ScottC", "author_id": 20174226, "author_profile": "https://Stackoverflow.com/users/20174226", "pm_score": -1, "selected": false, "text": "if len(user_message) > 0:\n @client.event\n async def on_message(message):\n if message.author == client.user:\n return\n\n username = str(message.author)\n user_message = str(message.content)\n channel = str(message.channel)\n\n print(f\"{username} said: '{user_message}' ({channel})\")\n\n if len(user_message) > 0:\n if user_message[0] == '%':\n user_message = user_message[1:]\n await send_message(message, user_message, is_private=True)\n else:\n await send_message(message, user_message, is_private=False)\n\n client.run(TOKEN)\n" }, { "answer_id": 74587383, "author": "Soumendra", "author_id": 5014656, "author_profile": "https://Stackoverflow.com/users/5014656", "pm_score": 1, "selected": false, "text": "message_content intents.message_content = True\n def run_discord_bot():\n TOKEN = 'This is where the bots token would go'\n intents = discord.Intents.default()\n intents.message_content = True\n client = discord.Client(intents=intents)\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9940949/" ]
74,587,346
<p>Consider the following code:</p> <pre><code>static void statefullParallelLambdaSet() { Set&lt;Integer&gt; s = new HashSet&lt;&gt;( Arrays.asList(1, 2, 3, 4, 5, 6) ); List&lt;Integer&gt; list = new ArrayList&lt;&gt;(); int sum = s.parallelStream().mapToInt(e -&gt; { // pipeline start if (list.size() &lt;= 3) { // list.size() changes while the pipeline operation is executing. list.add(e); // mapToInt's lambda expression depends on this value, so it's stateful. return e; } else return 0; }).sum(); // terminal operation System.out.println(sum); } </code></pre> <p>In the code above, it says that <code>list.size()</code> changes while the pipe operation is running, but I don't understand.</p> <p>Since <code>list.add(e)</code> is executed at once in multiple threads because it is executed in parallel, is it correct to assume that the value changes each time it is executed?</p> <p>The reason why the value changes even if it is executed as a serial stream is that there is no order because it is a set, so the number drawn is different each time it is executed...</p> <p>Am I right?</p>
[ { "answer_id": 74587382, "author": "ScottC", "author_id": 20174226, "author_profile": "https://Stackoverflow.com/users/20174226", "pm_score": -1, "selected": false, "text": "if len(user_message) > 0:\n @client.event\n async def on_message(message):\n if message.author == client.user:\n return\n\n username = str(message.author)\n user_message = str(message.content)\n channel = str(message.channel)\n\n print(f\"{username} said: '{user_message}' ({channel})\")\n\n if len(user_message) > 0:\n if user_message[0] == '%':\n user_message = user_message[1:]\n await send_message(message, user_message, is_private=True)\n else:\n await send_message(message, user_message, is_private=False)\n\n client.run(TOKEN)\n" }, { "answer_id": 74587383, "author": "Soumendra", "author_id": 5014656, "author_profile": "https://Stackoverflow.com/users/5014656", "pm_score": 1, "selected": false, "text": "message_content intents.message_content = True\n def run_discord_bot():\n TOKEN = 'This is where the bots token would go'\n intents = discord.Intents.default()\n intents.message_content = True\n client = discord.Client(intents=intents)\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20611237/" ]
74,587,376
<p>I know that when a function gets called, a stack frame is created for it which contains(local variables,return address,frame pointer...) and pushed on to the program stack. We are able to use the passed aurguments randomly.</p> <pre><code>Void func(int a,int b,int c){ //a,b,c //c,b,a //a,c,b } </code></pre> <p>In the above function the arguments can be use randomly, I know that the stack is LIFO(last in first out), for now I just want to know, is the stack frame random access? Because we are able to access the variables (local variables) randomly.</p>
[ { "answer_id": 74587406, "author": "cspurposesonly", "author_id": 20332975, "author_profile": "https://Stackoverflow.com/users/20332975", "pm_score": 0, "selected": false, "text": "%rdi %rsi %rdx" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19812695/" ]
74,587,386
<p>I have a dataframe like this</p> <pre><code> datasource datavalue 0 aaaa.pdf 5 0 bbbbb.pdf 5 0 cccc.pdf 9 </code></pre> <p>I don't know if this is the reason but this seems to be messing a dash display so I would like to reindex it like</p> <pre><code> datasource datavalue 0 aaaa.pdf 5 1 bbbbb.pdf 5 2 cccc.pdf 9 </code></pre> <p>I used</p> <pre><code>data_all.reset_index() </code></pre> <p>but it is not working, the index are still 0</p> <p>how it should be done?</p> <p>EDIT1: Thanks to the two participants who made me notice my mistake. I should have put</p> <pre><code>data_all=data_all.reset_index() </code></pre> <p>Unfortunately it did not go as expected.</p> <p>Before:</p> <pre><code> datasource datavalue 0 aaaa.pdf 5 0 bbbbb.pdf 5 0 cccc.pdf 9 </code></pre> <p>Then</p> <pre><code>data_all.keys() Index(['datasource','datavalue'],dtype='object') </code></pre> <p>So data_all.reset_index()</p> <p>After</p> <pre><code> index datasource datavalue 0 0 aaaa.pdf 5 1 0 bbbbb.pdf 5 2 0 cccc.pdf 9 </code></pre> <p>data_all.keys() Index(['index','datasource','datavalue'],dtype='object')</p> <p>As you see one column &quot;index&quot; was added. I suppose I can drop that column but I was expecting something that in one step reindex the df without adding anything</p> <p>EDIT2: Turns out <code>drop=True</code> was necessary! Thanks everybody!</p>
[ { "answer_id": 74587398, "author": "ScottC", "author_id": 20174226, "author_profile": "https://Stackoverflow.com/users/20174226", "pm_score": 0, "selected": false, "text": "data_all = data_all.reset_index(drop=True)\n" }, { "answer_id": 74587446, "author": "Ahmed Aredah", "author_id": 5800005, "author_profile": "https://Stackoverflow.com/users/5800005", "pm_score": 2, "selected": true, "text": "df.reset_index(drop=True, inplace=True)\n#drop: Do not try to insert index into dataframe columns. This resets the index to the default integer index.\n# inplace: Whether to modify the DataFrame rather than creating a new one.\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4451521/" ]
74,587,411
<p><code>static int counter // will initalized to 0</code></p> <p>but if I make that variable inside a class, it's not initialized and I have to initialize it outside of class</p> <pre><code>class Test { static int counter; // not initialized }; ... Test::counter = 0; </code></pre> <p>I know the static variables are stored in BSS segment in memory and initialized by default to 0, so why is it when I make a static in class not initialized?</p>
[ { "answer_id": 74587398, "author": "ScottC", "author_id": 20174226, "author_profile": "https://Stackoverflow.com/users/20174226", "pm_score": 0, "selected": false, "text": "data_all = data_all.reset_index(drop=True)\n" }, { "answer_id": 74587446, "author": "Ahmed Aredah", "author_id": 5800005, "author_profile": "https://Stackoverflow.com/users/5800005", "pm_score": 2, "selected": true, "text": "df.reset_index(drop=True, inplace=True)\n#drop: Do not try to insert index into dataframe columns. This resets the index to the default integer index.\n# inplace: Whether to modify the DataFrame rather than creating a new one.\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055385/" ]
74,587,417
<p>Ok so I´m trying to put an explosion gif on both sides of website cause it looks cool but I can´t figure out how to do it and keep the original background color on the parts that aren´t part of the gif.</p> <pre><code>background-color: #270436; background:url(&quot;https://media.giphy.com/media/pKWCBvHevLcMU/giphy.gif&quot;) left repeat-y,url(&quot;explosion.gif&quot;) right repeat-y; </code></pre> <p>I used this from another post i saw and it didn´t work</p>
[ { "answer_id": 74587398, "author": "ScottC", "author_id": 20174226, "author_profile": "https://Stackoverflow.com/users/20174226", "pm_score": 0, "selected": false, "text": "data_all = data_all.reset_index(drop=True)\n" }, { "answer_id": 74587446, "author": "Ahmed Aredah", "author_id": 5800005, "author_profile": "https://Stackoverflow.com/users/5800005", "pm_score": 2, "selected": true, "text": "df.reset_index(drop=True, inplace=True)\n#drop: Do not try to insert index into dataframe columns. This resets the index to the default integer index.\n# inplace: Whether to modify the DataFrame rather than creating a new one.\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20611282/" ]
74,587,425
<p>Trying to exploit SQL injection for my assignment. Is it possible to execute delete or drop query after order by in select query without using the semicolon in Postgresql?</p> <p>This is my sample query:</p> <pre><code>Select * from table order by {sql injection payload} </code></pre> <p>Without using the semicolon in the payload, can we delete data or drop a table?</p> <p><a href="https://stackoverflow.com/a/6800585">https://stackoverflow.com/a/6800585</a></p> <p>Do we have similar to this Postgrsql?</p> <p>I tried</p> <p>Select * from (delete from table_name returning *) a</p> <p>But getting sql error as 'syntax error at or near from'</p>
[ { "answer_id": 74587398, "author": "ScottC", "author_id": 20174226, "author_profile": "https://Stackoverflow.com/users/20174226", "pm_score": 0, "selected": false, "text": "data_all = data_all.reset_index(drop=True)\n" }, { "answer_id": 74587446, "author": "Ahmed Aredah", "author_id": 5800005, "author_profile": "https://Stackoverflow.com/users/5800005", "pm_score": 2, "selected": true, "text": "df.reset_index(drop=True, inplace=True)\n#drop: Do not try to insert index into dataframe columns. This resets the index to the default integer index.\n# inplace: Whether to modify the DataFrame rather than creating a new one.\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20611324/" ]
74,587,427
<p>I was wondering if anyone could help me concencate two vectors of strings:</p> <p>For example: hello and hi, that repeat 130 times in a dataframe.</p> <p>When in the dataframe column I would like for the order to be hello, (130 times) followed by hi (also 130 times), then hello (130 more times), then hi (130 times) again. So they should appear 4 times total (2 times each in order)</p> <p>This is what I tried so far but it does not seem to work</p> <pre><code>hello &lt;- c(rep( &quot;hello&quot;, 130)) hi&lt;- c(rep( &quot;hi&quot;, 130)) style &lt;- c(hello, hi, hello, hi) </code></pre>
[ { "answer_id": 74587398, "author": "ScottC", "author_id": 20174226, "author_profile": "https://Stackoverflow.com/users/20174226", "pm_score": 0, "selected": false, "text": "data_all = data_all.reset_index(drop=True)\n" }, { "answer_id": 74587446, "author": "Ahmed Aredah", "author_id": 5800005, "author_profile": "https://Stackoverflow.com/users/5800005", "pm_score": 2, "selected": true, "text": "df.reset_index(drop=True, inplace=True)\n#drop: Do not try to insert index into dataframe columns. This resets the index to the default integer index.\n# inplace: Whether to modify the DataFrame rather than creating a new one.\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20596087/" ]
74,587,480
<p>Looking at this, it should work right?</p> <p>It seems like the get request is overwriting the post request return because it only renders no error.</p> <p>Why is that?</p> <hr /> <p>index.html</p> <pre><code>{% if error %} &lt;p&gt;{{ error }}&lt;/p&gt; {% else %} &lt;p&gt;no error&lt;/p&gt; {% endif %} </code></pre> <p>main.py</p> <pre><code>@app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': post_data = request.get_json(force=True) if post_data['message'] == False: return render_template('index.html', error='not detected') return render_template('index.html') </code></pre> <p>edit: still haven't found out what's wrong.</p>
[ { "answer_id": 74587398, "author": "ScottC", "author_id": 20174226, "author_profile": "https://Stackoverflow.com/users/20174226", "pm_score": 0, "selected": false, "text": "data_all = data_all.reset_index(drop=True)\n" }, { "answer_id": 74587446, "author": "Ahmed Aredah", "author_id": 5800005, "author_profile": "https://Stackoverflow.com/users/5800005", "pm_score": 2, "selected": true, "text": "df.reset_index(drop=True, inplace=True)\n#drop: Do not try to insert index into dataframe columns. This resets the index to the default integer index.\n# inplace: Whether to modify the DataFrame rather than creating a new one.\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7764497/" ]
74,587,486
<p>What I want to do is switch between my pages by using BottomAppBar in my app but it doesn't work. what make it worse is that it doesn't show me any error so I don't know where is the problem. Thank you for your help :)</p> <pre><code>import 'package:flutter/material.dart'; import 'package:testing/SecondPage.dart'; void main() { runApp(const MaterialApp( title: 'MyApp', home: MyApp(), )); } class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override State&lt;MyApp&gt; createState() =&gt; _MyAppState(); } class _MyAppState extends State&lt;MyApp&gt; { @override Widget build(BuildContext context) { return MaterialApp( home: DefaultTabController( length: 5, child: Scaffold( body: Icon(Icons.rice_bowl,size:100,color: Colors.blue,), floatingActionButton: FloatingActionButton( hoverElevation: 50, onPressed: () {}, child: const Icon(Icons.mic), ), floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, bottomNavigationBar: BottomAppBar( //color: Colors.blue, notchMargin: 10, shape: const CircularNotchedRectangle(), child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ IconButton( onPressed: () {}, icon: const Icon( Icons.contact_mail_outlined, color: Colors.grey, )), IconButton( onPressed: () {}, icon: const Icon( Icons.local_activity, color: Colors.grey, )), Container( height: 1, ), IconButton( onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) =&gt; secondPage())); }, icon: const Icon( Icons.safety_check, color: Colors.grey, )), IconButton( onPressed: () {}, icon: const Icon( Icons.read_more, color: Colors.grey, )), ], ), )), ), ); } } </code></pre> <p>here is second page:</p> <pre><code>import 'package:flutter/material.dart'; class secondPage extends StatefulWidget { const secondPage({Key? key}) : super(key: key); @override State&lt;secondPage&gt; createState() =&gt; _secondPageState(); } class _secondPageState extends State&lt;secondPage&gt; { @override Widget build(BuildContext context) { return Container( child: Icon(Icons.rice_bowl,size: 200,), ); } } </code></pre> <p>I did everything I found in flutter docs but still doesn't work.</p>
[ { "answer_id": 74587398, "author": "ScottC", "author_id": 20174226, "author_profile": "https://Stackoverflow.com/users/20174226", "pm_score": 0, "selected": false, "text": "data_all = data_all.reset_index(drop=True)\n" }, { "answer_id": 74587446, "author": "Ahmed Aredah", "author_id": 5800005, "author_profile": "https://Stackoverflow.com/users/5800005", "pm_score": 2, "selected": true, "text": "df.reset_index(drop=True, inplace=True)\n#drop: Do not try to insert index into dataframe columns. This resets the index to the default integer index.\n# inplace: Whether to modify the DataFrame rather than creating a new one.\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20318837/" ]
74,587,530
<p>I tried any workaround I can think , but still cant remove EventListener . here are all my ways of thinking I cant think of any other way to solve it . hope someone can tell me what can i do</p> <ol> <li>delete directly</li> </ol> <pre><code>function doSomething(){} const [testP, setTestP] = useState(); useEffect(() =&gt; { setTestP(document.querySelector(&quot;#test&quot;)); }, [testP]); function App(){ return( &lt;&gt; &lt;p id=&quot;test&quot;&gt;&lt;/p&gt; &lt;button onClick={ testP.addEventListener(&quot;click&quot;,doSomething); }&gt;&lt;/button&gt; &lt;button onClick={ testP.removeEventListener(&quot;click&quot;,doSomething); }&gt;&lt;/button&gt; &lt; /&gt; ); } </code></pre> <ol start="2"> <li>use one useEffect() hook</li> </ol> <pre><code>function doSomething(){} const [testP, setTestP] = useState(); useEffect(() =&gt; { setTestP(document.querySelector(&quot;#test&quot;)); }, [testP]); const [do, setDo] = useState(false); useEffect(() =&gt; { if(do === true) testP.addEventListener(&quot;click&quot;, doSomething); else testP.removeEventListener(&quot;click&quot;, doSomething); }, [do]); function App(){ return( &lt;&gt; &lt;p id=&quot;test&quot;&gt;&lt;/p&gt; &lt;button onClick={ setDo(true); }&gt;&lt;/button&gt; &lt;button onClick={ setDo(false); }&gt;&lt;/button&gt; &lt; /&gt; ); } </code></pre> <ol start="3"> <li>use two useEffect() hook</li> </ol> <pre><code>function doSomething(){} const [testP, setTestP] = useState(); useEffect(() =&gt; { setTestP(document.querySelector(&quot;#test&quot;)); }, [testP]); const [enable, setEnable] = useState(true); const [disable, setDisable] = useState(true); useEffect(() =&gt; { testP.addEventListener(&quot;click&quot;, doSomething); }, [enable]); useEffect(() =&gt; { testP.removeEventListener(&quot;click&quot;, doSomething); }, [disable]); function App(){ return( &lt;&gt; &lt;p id=&quot;test&quot;&gt;&lt;/p&gt; &lt;button onClick={ setEnable(!enable); }&gt;&lt;/button&gt; &lt;button onClick={ setDisable(!disable); }&gt;&lt;/button&gt; &lt; /&gt; ); } </code></pre> <ol start="4"> <li>use useState hook</li> </ol> <pre><code>function doSomething(){} const [foo, setFoo] = useState(); function App(){ return( &lt;&gt; &lt;p id=&quot;test&quot; onClick={foo}&gt;&lt;/p&gt; &lt;button onClick={ setFoo(doSomething); }&gt;&lt;/button&gt; &lt;button onClick={ setFoo(null); }&gt;&lt;/button&gt; &lt; /&gt; ); } </code></pre>
[ { "answer_id": 74587666, "author": "DecPK", "author_id": 9153448, "author_profile": "https://Stackoverflow.com/users/9153448", "pm_score": 1, "selected": false, "text": "p useRef useState useEffect ref p useRef CODESANDBOX LINK import { useRef } from \"react\";\n\nexport default function Comp() {\n const pRef = useRef(null);\n\n function doSomething() {\n console.log(\"Loggin from doSomething\");\n }\n\n function attachEventListener() {\n if (pRef.current) pRef.current.addEventListener(\"click\", doSomething);\n }\n\n function detachEventListener() {\n if (pRef.current) pRef.current.removeEventListener(\"click\", doSomething);\n }\n\n return (\n <>\n <p id=\"test\" ref={pRef}>\n paragraph\n </p>\n <button onClick={attachEventListener}>addEventListener</button>\n <button onClick={detachEventListener}>removeEventListener</button>\n </>\n );\n}\n onClick <button onClick={ setFoo(doSomething); }></button>\n <button onClick={ () => setFoo(doSomething) }></button>\n" }, { "answer_id": 74591894, "author": "jgurbanov", "author_id": 5589483, "author_profile": "https://Stackoverflow.com/users/5589483", "pm_score": 0, "selected": false, "text": "function doSomething() {\n console.log('Do something')\n}\n\nexport function App(props) {\n const [enabled, setEnabled] = React.useState(false)\n\n return (\n <div className='App'>\n <p onClick={enabled ? doSomething : null}>paragraph</p>\n <button onClick={() => setEnabled(true)}>Add event</button>\n <button onClick={() => setEnabled(false)}>Remove event</button>\n </div>\n );\n}\n\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20079538/" ]
74,587,535
<p>I am trying to print any number that is great than n, which is 5 in this case. It is only printing 6 and 7. I am not sure what I am doing wrong. This is my code. I am looping through the array and testing if i is greater then n (5)</p> <pre><code>list = [2, 3, 4, 5, 6, 7, 8, 9] n = 5 filter_list (list, n) def filter_list (list, n): ` `for i in range(len(list)): ` `if list[i] &gt; n: ` `print (list[i]) </code></pre> <p>the outcome is <code>only 6, 7.</code> Its not <code>6, 7, 8, 9</code> which is what I would like it</p> <p>It doesnt print the desired outcome</p>
[ { "answer_id": 74587569, "author": "Bhargav", "author_id": 15358800, "author_profile": "https://Stackoverflow.com/users/15358800", "pm_score": 1, "selected": false, "text": "end '' list = [2, 3, 4, 5, 6, 7, 8, 9]\nn = 5\n\n\ndef filter_list (list, n):\n for i in range(len(list)):\n if list[i] > n:\n print (list[i],end =' ')\n \nfilter_list (list, n)\n 6 7 8 9 \n" }, { "answer_id": 74587709, "author": "Prabhas Kumar", "author_id": 20603322, "author_profile": "https://Stackoverflow.com/users/20603322", "pm_score": 0, "selected": false, "text": "list = [2, 3, 4, 5, 6, 7, 8, 9]\nn = 5\n\n\ndef filter_list (list, n):\n for i in range(len(list)):\n if list[i] > n:\n print (list[i],end =' ')\n\nprint(filter_list (list, n))\n 6 7 8 9 list = [2, 3, 4, 5, 6, 7, 8, 9]\n\nn = 5\n\nprint(list(i for i in List if i > n))\n" }, { "answer_id": 74588522, "author": "hafshahfitri", "author_id": 20576855, "author_profile": "https://Stackoverflow.com/users/20576855", "pm_score": 0, "selected": false, "text": "list = [2, 3, 4, 5, 6, 7, 8, 9]\nn = 5\n\ndef filter_list (list, n):\n for i in range(len(list)):\n if list[i] > n:\n print (list[i])\n\nfilter_list (list, n)\n list1 = [2, 3, 4, 5, 6, 7, 8, 9]\nn = 5\n\nfor i in list1 :\n if i > n:\n print(I)\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20558579/" ]
74,587,558
<p>I need to display a pdf file in a browser, but I cannot find the solution to take the PDF for the folder media, the PDF file was save in my database, but I cannot show.</p> <p>my urls.py:</p> <pre><code>urlpatterns = [ path('uploadfile/', views.uploadFile, name=&quot;uploadFile&quot;), path('verPDF/&lt;idtermsCondition&gt;', views.verPDF, name='verPDF'), ] </code></pre> <p>my models.py:</p> <pre><code>class termsCondition(models.Model): title = models.CharField(max_length=20, verbose_name=&quot;title&quot;) uploadPDF = models.FileField( upload_to=&quot;PDF/&quot;, null=True, blank=True) dateTimeUploaded = models.DateTimeField(auto_now_add=True) deleted_at = models.DateTimeField( auto_now=False, verbose_name=&quot;Fecha eliminacion&quot;, blank=True, null=True) class Meta: verbose_name = &quot;termsCondition&quot; verbose_name_plural = &quot;termsConditions&quot; </code></pre> <p>my views.py:</p> <pre><code>def uploadFile(request): user = request.user if user.is_authenticated: if user.is_admin: if request.method == &quot;POST&quot;: # Fetching the form data fileTitle = request.POST[&quot;fileTitle&quot;] loadPDF = request.FILES[&quot;uploadPDF&quot;] # Saving the information in the database termscondition = termsCondition.objects.create( title=fileTitle, uploadPDF=loadPDF ) termscondition.save() else: listfiles = termsCondition.objects.all()[:1].get() return render(request, 'subirTerminos.html', context={ &quot;files&quot;: listfiles }) else: messages.add_message(request=request, level=messages.SUCCESS, message=&quot;No tiene suficientes permisos para ingresar a esta página&quot;) return redirect('customer') else: return redirect('login2') def verPDF(request, idtermsCondition): user = request.user if user.is_authenticated(): if user.is_admin: getPDF = termsCondition.objects.get(pk=idtermsCondition) seePDF = {'PDF': getPDF.uploadPDF} print(seePDF) return render(request, 'subirTerminos.html', {'termsCondition': getPDF, 'uploadPDF': getPDF.uploadPDF}) else: messages.error(request, 'Do not have permission') else: return redirect('login2') </code></pre> <p>my html:</p> <pre><code>&lt;div&gt; &lt;iframe id=&quot;verPDF&quot; src=&quot;media/PDF/{{ uploadPDF.url }}&quot; style=&quot;width:800px; height:800px;&quot;&gt;&lt;/iframe&gt; &lt;/div&gt; </code></pre> <p>I want to see my pdf and I cannot do, I want to know how to do, I tried many solutions, I accept js, embed iframe whatever to can solve.</p>
[ { "answer_id": 74587615, "author": "Sunderam Dubey", "author_id": 17562044, "author_profile": "https://Stackoverflow.com/users/17562044", "pm_score": 3, "selected": true, "text": "user.is_authenticated user.is_authenticated() verPDF <idtermsCondition> <int:idtermsCondition> urlpatterns = [\n path('uploadfile/', views.uploadFile, name=\"uploadFile\"),\n path('verPDF/<int:idtermsCondition>/', views.verPDF, name='verPDF'),\n]\n {{uploadPDF.url}} <embed> <div>\n <embed id=\"verPDF\" src=\"{{uploadPDF.url}}\" width=\"500\" height=\"375\" type=\"application/pdf\">\n</div>\n /" }, { "answer_id": 74595140, "author": "kevin torres", "author_id": 19171765, "author_profile": "https://Stackoverflow.com/users/19171765", "pm_score": 2, "selected": false, "text": "now, views.py:\n\n``def uploadFile(request):\n user = request.user\n if user.is_authenticated:\n if user.is_admin:\n if request.method == \"POST\":\n # Fetching the form data\n fileTitle = request.POST[\"fileTitle\"]\n loadPDF = request.FILES[\"uploadPDF\"]\n \n if termsCondition.objects.all().exists():\n listfiles = termsCondition.objects.all()[:1].get()\n listfiles.uploadPDF = loadPDF\n listfiles.save()\n else:\n # Saving the information in the database\n termscondition = termsCondition.objects.create(\n title=fileTitle,\n uploadPDF=loadPDF\n )\n return redirect('uploadFile')\n else:\n if termsCondition.objects.all().exists():\n listfiles = termsCondition.objects.all()[:1].get()\n return render(request, 'subirTerminos.html', context={\n \"files\": listfiles.uploadPDF\n })\n else:\n listfiles = {}\n return render(request, 'subirTerminos.html', context={\"files\": listfiles})\n else:\n messages.add_message(request=request, level=messages.SUCCESS,\n message=\"No tiene suficientes permisos para ingresar a esta página\")\n return redirect('customer')\n \n else:\n return redirect('login2') ``\n \n and html:\n \n <h1 class=\"title\">Visualizador de PDF</h1>\n <embed id=\"verPDF\" src=\"{{files.url}}\" width=\"500\" height=\"375\" type=\"application/pdf\">\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19171765/" ]
74,587,565
<div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> <th>Cat</th> <th>Dog</th> <th>Frog</th> <th>Pig</th> </tr> </thead> <tbody> <tr> <td>Ana</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> </tr> <tr> <td>Ana</td> <td>1</td> <td>0</td> <td>1</td> <td>0</td> </tr> </tbody> </table> </div><div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> <th>Cat</th> <th>Dog</th> <th>Frog</th> <th>Pig</th> </tr> </thead> <tbody> <tr> <td>Ana</td> <td>1</td> <td>1</td> <td>1</td> <td>0</td> </tr> </tbody> </table> </div> <p>I'd like to group these two rows by name and replace the 'zeros' by one when is filled. The output should be like this</p>
[ { "answer_id": 74587587, "author": "JayPeerachai", "author_id": 12135518, "author_profile": "https://Stackoverflow.com/users/12135518", "pm_score": 2, "selected": false, "text": "groupby max() df = df.groupby('Name').max().reset_index()\n > df\n\n Name Cat Dog Frog Pig\n0 Ana 1 1 1 0\n" }, { "answer_id": 74587630, "author": "Andrea S.", "author_id": 14895961, "author_profile": "https://Stackoverflow.com/users/14895961", "pm_score": 1, "selected": false, "text": "import pandas as pd\n\ndata = [\n ('Ana', 0, 1, 0, 0)\n, ('Ana', 1, 0, 1, 0) \n]\n\ndf = pd.DataFrame(data, columns=['Name', 'Cat', 'Dog', 'Frog', 'Pig'])\n\nprint(df.groupby(['Name']).sum())\n Cat Dog Frog Pig\nName\nAna 1 1 1 0\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20611445/" ]
74,587,583
<p>Is it possible to have a page that opens with 6 box items as nav menu, but when one is clicked to go to that area on the page, the nav becomes a standard fixed nav bar at the top of the page? Using only CSS (no JS).</p> <ul> <li>I am a VERY junior coder.</li> </ul> <p>I have been unable to find this to be possible thus far.</p>
[ { "answer_id": 74587733, "author": "adityamms", "author_id": 20446649, "author_profile": "https://Stackoverflow.com/users/20446649", "pm_score": 0, "selected": false, "text": "<div class=\"navbar\"> \n <ul><a href=\"#page1\"> page 1 </a></ul>\n <ul><a href=\"#page3\"> page 3 </a> </ul> \n</div>\n<h2 id=\"page1\">this is page 1</h2>\n<h2 id=\"page3\">this is page 3</h2>\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20384553/" ]
74,587,611
<p>I am trying to get data from a endpoint and then output this data, I can successfully get my data fetched and display it immediately using</p> <pre><code>fetch(strURL) .then(res =&gt; res.json()) .then((result) =&gt; { console.log(&quot;grabed data &quot;+ JSON.stringify(result)); </code></pre> <p>But whenever I try to set the data to my State variable <code>response</code> it fails to do so resulting in an undefined variable. I am really confused why this is occurring as I have another screen that fetches a the same endpoint but it doesn't seem to save to the state variable.</p> <p>This is the data which is returned:</p> <pre><code>[{&quot;act_id&quot;:&quot;1&quot;,&quot;act_name&quot;:&quot;A bush adventure trail ride in the blue mountains&quot;,&quot;cat_sub_category&quot;:&quot;Free riding&quot;,&quot;bus_name&quot;:&quot;Ditch the road&quot;},{&quot;act_id&quot;:&quot;2&quot;,&quot;act_name&quot;:&quot;Paddock riding in the ditch&quot;,&quot;cat_sub_category&quot;:&quot;stable riding&quot;,&quot;bus_name&quot;:&quot;Hallam horses&quot;}] </code></pre> <p>This is the working screen which fetches the data above</p> <pre><code>function ActivityDemo(props) { let [isLoading, setIsLoading] = useState(true); let [error,setError] = useState(); let [response,setResponse] = useState(); useEffect(() =&gt;{ console.log(&quot;fetch activities&quot;); fetch(&quot;https://domain/api/activities.php&quot;) .then(res =&gt; res.json()) .then((result) =&gt; { console.log(&quot;grabed data &quot;+ result); setIsLoading(false); setResponse(result); }, (error) =&gt; { setIsLoading(true); setError(error); console.error(&quot;error &quot;) }) }, []); //What renders const renderItem = ({item}) =&gt; ( &lt;ActivityWidget item={item} &gt;&lt;/ActivityWidget&gt; ); //determines what is displayed const getContent = (navigation) =&gt; { if (isLoading == true){ return &lt;ActivityIndicator size=&quot;large&quot;&gt;&lt;/ActivityIndicator&gt; } if(error == true){ return &lt;Text&gt;{error}&lt;/Text&gt; } if(isLoading ==false){ console.log(response); return ( &lt;FlatList data={response} renderItem={renderItem} keyExtractor={item =&gt; item.act_id} /&gt; ); } } return( &lt;View style={[ContainerStyle.Center]}&gt; {getContent()} &lt;/View&gt; ); } </code></pre> <p>This snippet is from the screen which doesn't work</p> <pre><code>function ActivityDetails({route},props) { //get the Route variables const {actId} = route.params; let [isLoading, setIsLoading] = useState(true); let [error, setError] = useState(); let [response, setResponse] = useState(); let strURL = &quot;https://domain/api/detailedActivity.php?actId=&quot;+actId; useEffect(() =&gt;{ console.log(&quot;fetch detailed data!&quot;); console.log(strURL); fetch(&quot;https://domain/api/activities.php&quot;) .then(res =&gt; res.json()) .then((result) =&gt; { console.log(&quot;grabed data &quot;+ JSON.stringify(result)); setIsLoading(false); setResponse(result); }, (error) =&gt; { setIsLoading(true); setError(error); console.error(&quot;error &quot;+ error) }) }, []); //determines what is displayed const getContent = () =&gt; { if (isLoading == true){ return &lt;ActivityIndicator size=&quot;large&quot;&gt;&lt;/ActivityIndicator&gt;; } if(isLoading == false){ console.log(&quot;Load response Data &quot; +response); return( &lt;View style={[ContainerStyle.Container]} &gt; &lt;Text&gt;{&quot;Name: &quot;+response[0].act_name}&lt;/Text&gt; &lt;Text&gt;{&quot;Description: &quot; +response[0].act_description}&lt;/Text&gt; &lt;Text&gt;{&quot;Bussiness: &quot;+response[0].act_name}&lt;/Text&gt; &lt;Text&gt;{&quot;Category: &quot;+response[0].act_name}&lt;/Text&gt; &lt;/View&gt; ); } if (error == true){ return &lt;Text&gt;{error}&lt;/Text&gt; } } return( &lt;View style={[ContainerStyle.Center]}&gt; {getContent()} &lt;/View&gt; ); } </code></pre> <p>This is the console logs</p> <pre><code> LOG fetch activities LOG grabed data [object Object],[object Object] LOG undefined LOG [{&quot;act_id&quot;: &quot;1&quot;, &quot;act_name&quot;: &quot;A bush adventure trail ride in the blue mountains&quot;, &quot;bus_name&quot;: &quot;Ditch the road&quot;, &quot;cat_sub_category&quot;: &quot;Free riding&quot;}, {&quot;act_id&quot;: &quot;2&quot;, &quot;act_name&quot;: &quot;Paddock riding in the ditch&quot;, &quot;bus_name&quot;: &quot;Hallam horses&quot;, &quot;cat_sub_category&quot;: &quot;stable riding&quot;}] LOG fetch detailed data! LOG https://domain/api/detailedActivity.php?actId=2 LOG grabed data [{&quot;act_id&quot;:&quot;1&quot;,&quot;act_name&quot;:&quot;A bush adventure trail ride in the blue mountains&quot;,&quot;cat_sub_category&quot;:&quot;Free riding&quot;,&quot;bus_name&quot;:&quot;Ditch the road&quot;},{&quot;act_id&quot;:&quot;2&quot;,&quot;act_name&quot;:&quot;Paddock riding in the ditch&quot;,&quot;cat_sub_category&quot;:&quot;stable riding&quot;,&quot;bus_name&quot;:&quot;Hallam horses&quot;}] LOG Load response Data undefined LOG Load response Data undefined </code></pre> <p>I'm not sure why this is not working If someone could tell me what I am doing wrong? Is it to do with the way I am setting state?</p> <p>Thank you, Andrew</p> <p>edit: I've hidden the endpoints domain</p>
[ { "answer_id": 74587733, "author": "adityamms", "author_id": 20446649, "author_profile": "https://Stackoverflow.com/users/20446649", "pm_score": 0, "selected": false, "text": "<div class=\"navbar\"> \n <ul><a href=\"#page1\"> page 1 </a></ul>\n <ul><a href=\"#page3\"> page 3 </a> </ul> \n</div>\n<h2 id=\"page1\">this is page 1</h2>\n<h2 id=\"page3\">this is page 3</h2>\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13905838/" ]
74,587,622
<p>The example:</p> <pre><code>ProductLine: ProductLineName: aa ADO_FeedsList: - organizationName: bb Project: - ProjectName: cc ProjectFeedsName: - dd - ee - ProjectName: ff ProjectFeedsName: - gg - hh OtherInfo: N/A </code></pre> <p>I expected the following output:</p> <pre><code>bb,cc,dd bb,cc,ee bb,ff,gg bb,ff,hh </code></pre> <p>I have tried :</p> <pre><code>yq -o csv '.ProductLine.ADO_FeedsList[] |[.organizationName] + (.Project[]|.ProjectName)' test.yaml </code></pre> <p>It can output:</p> <pre><code>bb,cc bb,ff </code></pre> <p>Then i tried:</p> <pre><code>yq -o csv '.ProductLine.ADO_FeedsList[] |[.organizationName] + (.Project[]|.ProjectName) + (.Project[]|.ProjectFeedsName[]|[.])' test.yaml </code></pre> <p>Error: !!seq (ProductLine.ADO_FeedsList.0.Project.0.ProjectFeedsName.0) cannot be added to a !!str (ProductLine.ADO_FeedsList.0.Project.0.ProjectName)</p> <p>How to write the ProjectFeedsName array command?</p> <p>I am a yq new user,could you share the method to format this yaml ? Or is there any other way to format this yaml to csv?</p>
[ { "answer_id": 74587771, "author": "pmf", "author_id": 2158479, "author_profile": "https://Stackoverflow.com/users/2158479", "pm_score": 2, "selected": false, "text": "yq -o csv '\n .ProductLine.ADO_FeedsList[] | [.organizationName] + (\n .Project[] | [.ProjectName] + (.ProjectFeedsName[] | [.])\n )\n' test.yaml\n bb,cc,dd\nbb,cc,ee\nbb,ff,gg\nbb,ff,hh\n" }, { "answer_id": 74589594, "author": "peak", "author_id": 997358, "author_profile": "https://Stackoverflow.com/users/997358", "pm_score": 1, "selected": false, "text": "@csv gojq -r --yaml-input '\n.ProductLine.ADO_FeedsList[]\n| [.organizationName] + \n ( .Project[] | [.ProjectName] + (.ProjectFeedsName[]|[.]) )\n| @csv\n @csv | join(\",\")" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19623474/" ]
74,587,624
<p>So, I have been studying iterative statements for a report. While I was reading, I came across the developmental history of definite iteration and eventually learn the for loop. We know that the syntax for the for loop in C,C++, and java is</p> <pre><code>for (expression1; expression2; expression3) statement </code></pre> <p>And it says here that we can omit any of the expression and that it is legal to have a for loop that look like this</p> <pre><code>for (;;) </code></pre> <p>My question is how does that work? I cant find any more resources for this one.</p>
[ { "answer_id": 74587771, "author": "pmf", "author_id": 2158479, "author_profile": "https://Stackoverflow.com/users/2158479", "pm_score": 2, "selected": false, "text": "yq -o csv '\n .ProductLine.ADO_FeedsList[] | [.organizationName] + (\n .Project[] | [.ProjectName] + (.ProjectFeedsName[] | [.])\n )\n' test.yaml\n bb,cc,dd\nbb,cc,ee\nbb,ff,gg\nbb,ff,hh\n" }, { "answer_id": 74589594, "author": "peak", "author_id": 997358, "author_profile": "https://Stackoverflow.com/users/997358", "pm_score": 1, "selected": false, "text": "@csv gojq -r --yaml-input '\n.ProductLine.ADO_FeedsList[]\n| [.organizationName] + \n ( .Project[] | [.ProjectName] + (.ProjectFeedsName[]|[.]) )\n| @csv\n @csv | join(\",\")" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16081824/" ]
74,587,629
<p>I am new to Android Studio and I am creating a custom notification app, and I wanted to use the EditText from my MainActivity class in Broadcast Receiver class. How can I do that?</p> <p>Broadcast Receiver code:</p> <pre><code>`package com.example.notificationscreator; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.widget.EditText; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { NotificationCompat.Builder Build = new NotificationCompat.Builder(context, &quot;Notified&quot;); Build.setSmallIcon(R.drawable.ic_stat_name); Build.setContentTitle(&quot;&quot;); Build.setStyle(new NotificationCompat.BigTextStyle().bigText(&quot;&quot;)); NotificationManagerCompat Managercompats = NotificationManagerCompat.from(context); Managercompats.notify(1, Build.build()); } }` </code></pre> <p>Main activity code:</p> <pre><code>`package com.example.notificationscreator; import static com.example.notificationscreator.R.*; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import android.app.AlarmManager; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.SystemClock; import android.view.View; import android.widget.Button; import android.widget.EditText; import java.util.Calendar; import java.util.Random; public class MainActivity2 extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(layout.activity_main2); Button btnmain = findViewById(R.id.button4); Button Displaynotif = findViewById(R.id.button3); EditText Timedisplay = findViewById(R.id.editTextTime); Integer Time = Integer.parseInt(Timedisplay.getText().toString()); btnmain.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Backmainpage(); } }); if(Build.VERSION.SDK_INT &gt;=Build.VERSION_CODES.O){ NotificationChannel channel = new NotificationChannel(&quot;Notified&quot;,&quot;Notification&quot;, NotificationManager.IMPORTANCE_HIGH); NotificationManager manager = getSystemService(NotificationManager.class); manager.createNotificationChannel(channel); } Displaynotif.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int Randnum = new Random().nextInt(80); Intent intent= new Intent(MainActivity2.this,MyReceiver.class); PendingIntent pendingintention = PendingIntent.getBroadcast(MainActivity2.this,0, intent,0); AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE); long timeonclick = System.currentTimeMillis(); long timeafterclick = 10000; am.set(AlarmManager.RTC_WAKEUP,timeonclick+timeafterclick,pendingintention); } }); } public void Backmainpage(){ Intent intention2 = new Intent(this,MainActivity.class); startActivity(intention2); } }` </code></pre> <p>I've tried recalling Main Activity using <code>MainActivity2 Mainactivity = new MainActivity2();</code> but I still can't access the UI from Main Activity</p>
[ { "answer_id": 74587771, "author": "pmf", "author_id": 2158479, "author_profile": "https://Stackoverflow.com/users/2158479", "pm_score": 2, "selected": false, "text": "yq -o csv '\n .ProductLine.ADO_FeedsList[] | [.organizationName] + (\n .Project[] | [.ProjectName] + (.ProjectFeedsName[] | [.])\n )\n' test.yaml\n bb,cc,dd\nbb,cc,ee\nbb,ff,gg\nbb,ff,hh\n" }, { "answer_id": 74589594, "author": "peak", "author_id": 997358, "author_profile": "https://Stackoverflow.com/users/997358", "pm_score": 1, "selected": false, "text": "@csv gojq -r --yaml-input '\n.ProductLine.ADO_FeedsList[]\n| [.organizationName] + \n ( .Project[] | [.ProjectName] + (.ProjectFeedsName[]|[.]) )\n| @csv\n @csv | join(\",\")" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10631077/" ]
74,587,657
<p>A</p> <pre><code>int *numptr = malloc(sizeof(int)*10); </code></pre> <p>B</p> <pre><code>int *numptr = malloc(sizeof(40)); </code></pre> <p>it's on the 32bit</p> <p>i can't understand what is difference. there is no information in the book i have.</p> <p>is A and B 100% same thing?</p>
[ { "answer_id": 74587676, "author": "dbush", "author_id": 1687119, "author_profile": "https://Stackoverflow.com/users/1687119", "pm_score": 3, "selected": false, "text": "sizeof(int) int malloc(sizeof(int)*10) sizeof(40) 40 int sizeof(40) malloc(sizeof(40))" }, { "answer_id": 74587703, "author": "EJoshuaS - Stand with Ukraine", "author_id": 4032703, "author_profile": "https://Stackoverflow.com/users/4032703", "pm_score": 1, "selected": false, "text": "sizeof(40) sizeof(int) sizeof(int) * 10 sizeof(40)" }, { "answer_id": 74587705, "author": "John Bode", "author_id": 134554, "author_profile": "https://Stackoverflow.com/users/134554", "pm_score": 2, "selected": false, "text": "int [-32767..32767] 10 * sizeof (int) int" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20611593/" ]
74,587,665
<p>I am trying to build an Express.js based website which, when I navigate to a certain page, grabs a list of albums, links, ids, etc. I have a service account with all permissions. My Javascript is:</p> <pre><code>const oauth2Client = new google.auth.OAuth2( config.serviceAccount.client_id, config.oAuthclientSecret, config.oAuthCallbackUrl ); google.options({auth: oauth2Client}); function getAlbumList(){ var xhr = new XMLHttpRequest(); var url = &quot;https://photoslibrary.googleapis.com/v1/albums&quot; xhr.open(&quot;GET&quot;,url,true); xhr.onreadystatechange = function () { console.log(&quot;making xhr&quot;) if (xhr.readyState == 4 &amp;&amp; xhr.status == 200) { console.log(xhr); } } xhr.addEventListener('error',function(){ console.log(xhr.statusMessage) console.log(&quot;xhr.status is &quot;, xhr.status ) console.log(&quot;ERROR&quot;); }) xhr.addEventListener('timeout',function(){ console.log(&quot;SERVER TIMEOUT&quot;) }) // Sending our request xhr.send(); } </code></pre> <p>However, I never even get a response back. I do have a service account, and my credential is:</p> <pre><code>{ &quot;type&quot;: &quot;service_account&quot;, &quot;project_id&quot;: &quot;myProj&quot;, &quot;private_key_id&quot;: &quot;8dxxxxxx46&quot;, &quot;private_key&quot;: &quot;-----BEGIN PRIVATE KEY-----\nMIIEvwIBADANBgkqhkiG9w0BAQExxxxxxxxxQ==\n-----END PRIVATE KEY-----\n&quot;, &quot;client_email&quot;: &quot;ihfphotograb@myproj.iam.gserviceaccount.com&quot;, &quot;client_id&quot;: &quot;10xxxxxxxxx6451&quot;, &quot;auth_uri&quot;: &quot;https://accounts.google.com/o/oauth2/auth&quot;, &quot;token_uri&quot;: &quot;https://oauth2.googleapis.com/token&quot;, &quot;auth_provider_x509_cert_url&quot;: &quot;https://www.googleapis.com/oauth2/v1/certs&quot;, &quot;client_x509_cert_url&quot;: &quot;https://www.googleapis.com/robot/v1/metadata/x509/proj%40myproj.iam.gserviceaccount.com&quot;} </code></pre> <p>I've looked at <a href="https://developers.google.com/photos/library/reference/rest/v1/albums/list" rel="nofollow noreferrer">this</a> but they don't tell you how to get a token and when I looked at the network tab to see the request and params going thru. I do have <code>const {google} = require('googleapis')</code> but I don't know how to get that token.</p> <p>I want the service app to do all the authentication and so my website's visitors can see the photos without authenticating.</p>
[ { "answer_id": 74587738, "author": "Dream Bold", "author_id": 12743692, "author_profile": "https://Stackoverflow.com/users/12743692", "pm_score": 1, "selected": false, "text": "401 unauthorized /* Google AUTH */\n \nconst GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;\nconst GOOGLE_CLIENT_ID = 'our-google-client-id';\nconst GOOGLE_CLIENT_SECRET = 'our-google-client-secret';\npassport.use(new GoogleStrategy({\n clientID: GOOGLE_CLIENT_ID,\n clientSecret: GOOGLE_CLIENT_SECRET,\n callbackURL: \"http://localhost:3000/auth/google/callback\"\n },\n function(accessToken, refreshToken, profile, done) {\n userProfile=profile;\n return done(null, userProfile);\n }\n));\n \napp.get('/auth/google', \n passport.authenticate('google', { scope : ['profile', 'email'] }));\n \napp.get('/auth/google/callback', \n passport.authenticate('google', { failureRedirect: '/error' }),\n function(req, res) {\n // Successful authentication, redirect success.\n res.redirect('/success');\n });\n" }, { "answer_id": 74592883, "author": "DaImTo", "author_id": 1841839, "author_profile": "https://Stackoverflow.com/users/1841839", "pm_score": 3, "selected": true, "text": "<!DOCTYPE html>\n<html>\n<head>\n <title>Photos API Quickstart</title>\n <meta charset=\"utf-8\" />\n</head>\n<body>\n<p>Photos API Quickstart</p>\n\n<!--Add buttons to initiate auth sequence and sign out-->\n<button id=\"authorize_button\" onclick=\"handleAuthClick()\">Authorize</button>\n<button id=\"signout_button\" onclick=\"handleSignoutClick()\">Sign Out</button>\n\n<pre id=\"content\" style=\"white-space: pre-wrap;\"></pre>\n\n<script type=\"text/javascript\">\n /* exported gapiLoaded */\n /* exported gisLoaded */\n /* exported handleAuthClick */\n /* exported handleSignoutClick */\n\n // TODO(developer): Set to client ID and API key from the Developer Console\n const CLIENT_ID = '<YOUR_CLIENT_ID>';\n const API_KEY = '<YOUR_API_KEY>';\n\n // Discovery doc URL for APIs used by the quickstart\n const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/photoslibrary/v1/rest';\n\n // Authorization scopes required by the API; multiple scopes can be\n // included, separated by spaces.\n const SCOPES = 'https://www.googleapis.com/auth/photoslibrary.readonly';\n\n let tokenClient;\n let gapiInited = false;\n let gisInited = false;\n\n document.getElementById('authorize_button').style.visibility = 'hidden';\n document.getElementById('signout_button').style.visibility = 'hidden';\n\n /**\n * Callback after api.js is loaded.\n */\n function gapiLoaded() {\n gapi.load('client', initializeGapiClient);\n }\n\n /**\n * Callback after the API client is loaded. Loads the\n * discovery doc to initialize the API.\n */\n async function initializeGapiClient() {\n await gapi.client.init({\n apiKey: API_KEY,\n discoveryDocs: [DISCOVERY_DOC],\n });\n gapiInited = true;\n maybeEnableButtons();\n }\n\n /**\n * Callback after Google Identity Services are loaded.\n */\n function gisLoaded() {\n tokenClient = google.accounts.oauth2.initTokenClient({\n client_id: CLIENT_ID,\n scope: SCOPES,\n callback: '', // defined later\n });\n gisInited = true;\n maybeEnableButtons();\n }\n\n /**\n * Enables user interaction after all libraries are loaded.\n */\n function maybeEnableButtons() {\n if (gapiInited && gisInited) {\n document.getElementById('authorize_button').style.visibility = 'visible';\n }\n }\n\n /**\n * Sign in the user upon button click.\n */\n function handleAuthClick() {\n tokenClient.callback = async (resp) => {\n if (resp.error !== undefined) {\n throw (resp);\n }\n document.getElementById('signout_button').style.visibility = 'visible';\n document.getElementById('authorize_button').innerText = 'Refresh';\n await listAlbums();\n };\n\n if (gapi.client.getToken() === null) {\n // Prompt the user to select a Google Account and ask for consent to share their data\n // when establishing a new session.\n tokenClient.requestAccessToken({prompt: 'consent'});\n } else {\n // Skip display of account chooser and consent dialog for an existing session.\n tokenClient.requestAccessToken({prompt: ''});\n }\n }\n\n /**\n * Sign out the user upon button click.\n */\n function handleSignoutClick() {\n const token = gapi.client.getToken();\n if (token !== null) {\n google.accounts.oauth2.revoke(token.access_token);\n gapi.client.setToken('');\n document.getElementById('content').innerText = '';\n document.getElementById('authorize_button').innerText = 'Authorize';\n document.getElementById('signout_button').style.visibility = 'hidden';\n }\n }\n\n /**\n * Print metadata for first 10 Albums.\n */\n async function listAlbums() {\n let response;\n try {\n response = await gapi.client.photoslibrary.albums.list({\n 'pageSize': 10,\n 'fields': 'albums(id,title)',\n });\n } catch (err) {\n document.getElementById('content').innerText = err.message;\n return;\n }\n const albums = response.result.albums;\n if (!albums || albums.length == 0) {\n document.getElementById('content').innerText = 'No albums found.';\n return;\n }\n // Flatten to string to display\n const output = albums.reduce(\n (str, album) => `${str}${album.title} (${album.id}\\n`,\n 'albums:\\n');\n document.getElementById('content').innerText = output;\n }\n</script>\n<script async defer src=\"https://apis.google.com/js/api.js\" onload=\"gapiLoaded()\"></script>\n<script async defer src=\"https://accounts.google.com/gsi/client\" onload=\"gisLoaded()\"></script>\n</body>\n</html>\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5927871/" ]
74,587,672
<p>I'm trying to take a list that can be size 1 or greater and convert it to a string with formatting <code>&quot;val1, val2, val3 and val4&quot;</code> where you can have different list lengths and the last value will be formatted with an and before it instead of a comma.</p> <p>My current code:</p> <pre><code>inputlist = [&quot;val1&quot;, &quot;val2&quot;, &quot;val3&quot;] outputstr = &quot;&quot; for i in range(len(inputlist)-1): if i == len(inputlist)-1: outputstr = outputstr + inputlist[i] elif i == len(inputlist)-2: outputstr = f&quot;{outputstr + inputlist[i]} and &quot; else: outputstr = f&quot;{outputstr + inputlist[i]}, &quot; print(f&quot;Formatted list is: {outputstr}&quot;) </code></pre> <p>Expected result:</p> <pre><code>Formatted list is: val1, val2 and val3 </code></pre>
[ { "answer_id": 74587708, "author": "jwal", "author_id": 6242321, "author_profile": "https://Stackoverflow.com/users/6242321", "pm_score": 1, "selected": false, "text": "join for inputlist in [[\"1\"], [\"one\", \"two\"], [\"val1\", \"val2\", \"val3\"]]:\n if len(inputlist) <= 1:\n outputstr = \"\".join(inputlist)\n else:\n outputstr = \" and \".join([\", \".join(inputlist[:-1]), inputlist[-1]])\n print(f\"Formatted list is: {outputstr}\")\n Formatted list is: 1\nFormatted list is: one and two\nFormatted list is: val1, val2 and val3\n" }, { "answer_id": 74587715, "author": "Sanjay Muthu", "author_id": 14661402, "author_profile": "https://Stackoverflow.com/users/14661402", "pm_score": 0, "selected": false, "text": "inputlist = [\"val1\", \"val2\", \"val3\"]\noutputstr = \"\"\n\nfor i in range(len(inputlist)):\n if i == len(inputlist)-1:\n outputstr = outputstr + inputlist[i]\n elif i == len(inputlist)-2:\n outputstr = f\"{outputstr + inputlist[i]} and \"\n else:\n outputstr = f\"{outputstr + inputlist[i]}, \"\nprint(f\"Formatted list is: {outputstr}\")\n" }, { "answer_id": 74593588, "author": "Subroutine7901", "author_id": 20545089, "author_profile": "https://Stackoverflow.com/users/20545089", "pm_score": 0, "selected": false, "text": "outputstr = str(inputlist).replace(\"'\", \"\").strip(\"[]\")[::-1].replace(\",\", \" and\"[::-1], 1)[::-1]\n print(f\"With the following codes enabled: {outputstr}\")\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20545089/" ]
74,587,685
<p>So I am trying to have the while loop end when inputting a blank for the input, but the problem is that the input takes 2 values separated by &quot;, &quot;. It is necessary for me to keep the input like that rather than separating them so how to fix this?</p> <pre><code>print(&quot; Input the productIDs and quantities (input blank to complete transaction)&quot;) productID, quantity = input().split(&quot;, &quot;) quantity = int(quantity) while quantity &gt;= 1: self.addProductToTransaction(productID, quantity) print(&quot;why u here bro u ain't buyin nothin&quot;) </code></pre> <p>When input is blank:</p> <pre><code>ValueError: not enough values to unpack (expected 2, got 1) </code></pre>
[ { "answer_id": 74587696, "author": "Glasses_", "author_id": 13788411, "author_profile": "https://Stackoverflow.com/users/13788411", "pm_score": -1, "selected": false, "text": "print(\" Input the productIDs and quantities (input blank to complete transaction)\")\n try:\n productID, quantity = input().split(\", \")\n quantity = int(quantity)\n while quantity >= 1:\n self.addProductToTransaction(productID, quantity) \n except:\n print(\"why u here bro u ain't buyin nothin\")\n" }, { "answer_id": 74587744, "author": "JayPeerachai", "author_id": 12135518, "author_profile": "https://Stackoverflow.com/users/12135518", "pm_score": 1, "selected": false, "text": "while loop try-except while True:\n try:\n productID, quantity = input(\"Input the productIDs and quantities (input blank to complete transaction)\").split(\", \")\n quantity = int(quantity)\n except ValueError:\n print(\"why u here bro u ain't buyin nothin\")\n break\n if quantity >= 1:\n self.addProductToTransaction(productID, quantity) \n" }, { "answer_id": 74587860, "author": "Bhargav", "author_id": 15358800, "author_profile": "https://Stackoverflow.com/users/15358800", "pm_score": 1, "selected": false, "text": "' print(\" Input the productIDs and quantities (input blank to complete transaction)\")\nuser_in = input()\nif user_in !='':\n\n productID, quantity = user_in.split(',')\n print(quantity)\n quantity = int(quantity)\n while quantity >= 1:\n self.addProductToTransaction(productID, quantity) \n \nelse:\n \n print(\"why u here bro u ain't buyin nothin\")\n Input the productIDs and quantities (input blank to complete transaction)\n\nwhy u here bro u ain't buyin nothin\n" }, { "answer_id": 74587865, "author": "Prabhas Kumar", "author_id": 20603322, "author_profile": "https://Stackoverflow.com/users/20603322", "pm_score": 0, "selected": false, "text": "len() try..except if while True:\n\n var = input(\"Input the productIDs and quantities (input blank to complete transaction)\")\n \n if len(var) == ‘’: \n\n print(\"why u here bro u ain't buyin nothin\")\n break\n\n productID, quantity = Var.split(\", \")\n\n\n\n quantity = int(quantity)\n if quantity >= 1:\n self.addProductToTransaction(productID, quantity) \n\n \nwhile True:\n\n var = input(\"Input the productIDs and quantities (input blank to complete transaction)\")\n \n if len(var) == 0: \n\n print(\"why u here bro u ain't buyin nothin\")\n break\n\n productID, quantity = Var.split(\", \")\n\n\n\n quantity = int(quantity)\n if quantity >= 1:\n self.addProductToTransaction(productID, quantity) \n\n \nwhile True:\n\n try:\n\n\n productID, quantity = input(\"Input the productIDs and quantities (input blank to complete transaction)\").split(\", \")\n\n quantity = int(quantity)\n if quantity >= 1:\n self.addProductToTransaction(productID, quantity) \n\n\n except ValueError:\n print(\"why u here bro u ain't buyin nothin\")\n break\n\n \"Foo..string\\n\" addProductToTransaction()" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13788411/" ]
74,587,692
<p>Look at below table. <a href="https://i.stack.imgur.com/9uRTF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9uRTF.png" alt="enter image description here" /></a></p> <p>I tried to print 'CORP_CODE' out with tuple which has same 'CORP_NAME' in it. SO, I wrote this code.</p> <pre><code>SELECT CORP_CODE FROM COMPANY_INFO WHERE CORP_NAME = '다코' </code></pre> <p>However, There is important error. The above code show ORA-00932: &quot;inconsistent datatypes: expected %s got %s&quot; I changed '' to &quot;&quot;, But It isn't helpful.</p> <p>I found more information, The column named 'CORP_NAME' is type of CLOB data. It seems that I need to use special methods for do it.</p> <p>That table, I dind't make it myself. It was just made by python pandas function 'dataframe.to_sql'.</p> <p>In this situlation, I have three questions for you.</p> <ol> <li>How can I get CORP_CODE with CLOB data 'CORP_NAME' by WHERE command or anything else?</li> <li>Should I re-make table and define 'CORP_NAME' as VARCHAR2? Is it the only way for me?</li> <li>In pandas inner function 'to_sql', Can I set detail options for making table?</li> </ol> <p>I make another table that 'CORP_NAME' as VARCHAR2(146). However, I want to know how can I select something by WHERE sentences.</p>
[ { "answer_id": 74587696, "author": "Glasses_", "author_id": 13788411, "author_profile": "https://Stackoverflow.com/users/13788411", "pm_score": -1, "selected": false, "text": "print(\" Input the productIDs and quantities (input blank to complete transaction)\")\n try:\n productID, quantity = input().split(\", \")\n quantity = int(quantity)\n while quantity >= 1:\n self.addProductToTransaction(productID, quantity) \n except:\n print(\"why u here bro u ain't buyin nothin\")\n" }, { "answer_id": 74587744, "author": "JayPeerachai", "author_id": 12135518, "author_profile": "https://Stackoverflow.com/users/12135518", "pm_score": 1, "selected": false, "text": "while loop try-except while True:\n try:\n productID, quantity = input(\"Input the productIDs and quantities (input blank to complete transaction)\").split(\", \")\n quantity = int(quantity)\n except ValueError:\n print(\"why u here bro u ain't buyin nothin\")\n break\n if quantity >= 1:\n self.addProductToTransaction(productID, quantity) \n" }, { "answer_id": 74587860, "author": "Bhargav", "author_id": 15358800, "author_profile": "https://Stackoverflow.com/users/15358800", "pm_score": 1, "selected": false, "text": "' print(\" Input the productIDs and quantities (input blank to complete transaction)\")\nuser_in = input()\nif user_in !='':\n\n productID, quantity = user_in.split(',')\n print(quantity)\n quantity = int(quantity)\n while quantity >= 1:\n self.addProductToTransaction(productID, quantity) \n \nelse:\n \n print(\"why u here bro u ain't buyin nothin\")\n Input the productIDs and quantities (input blank to complete transaction)\n\nwhy u here bro u ain't buyin nothin\n" }, { "answer_id": 74587865, "author": "Prabhas Kumar", "author_id": 20603322, "author_profile": "https://Stackoverflow.com/users/20603322", "pm_score": 0, "selected": false, "text": "len() try..except if while True:\n\n var = input(\"Input the productIDs and quantities (input blank to complete transaction)\")\n \n if len(var) == ‘’: \n\n print(\"why u here bro u ain't buyin nothin\")\n break\n\n productID, quantity = Var.split(\", \")\n\n\n\n quantity = int(quantity)\n if quantity >= 1:\n self.addProductToTransaction(productID, quantity) \n\n \nwhile True:\n\n var = input(\"Input the productIDs and quantities (input blank to complete transaction)\")\n \n if len(var) == 0: \n\n print(\"why u here bro u ain't buyin nothin\")\n break\n\n productID, quantity = Var.split(\", \")\n\n\n\n quantity = int(quantity)\n if quantity >= 1:\n self.addProductToTransaction(productID, quantity) \n\n \nwhile True:\n\n try:\n\n\n productID, quantity = input(\"Input the productIDs and quantities (input blank to complete transaction)\").split(\", \")\n\n quantity = int(quantity)\n if quantity >= 1:\n self.addProductToTransaction(productID, quantity) \n\n\n except ValueError:\n print(\"why u here bro u ain't buyin nothin\")\n break\n\n \"Foo..string\\n\" addProductToTransaction()" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20423166/" ]
74,587,719
<p>I want to extract this part. But I couldn't do it well. So I need you to tell me how to do it.</p> <p>Example) <a href="https://twitter.com/straw_berry0721/status/1596714080345415681?s=20&amp;t=1nIbnSZ2YN2m5KZaOjO5GA" rel="nofollow noreferrer">https://twitter.com/straw_berry0721/status/1596714080345415681?s=20&amp;t=1nIbnSZ2YN2m5KZaOjO5GA</a></p> <blockquote> <p>1596714080345415681</p> </blockquote> <p><a href="https://twitter.com/xxx/status/1595920708323999744" rel="nofollow noreferrer">https://twitter.com/xxx/status/1595920708323999744</a></p> <blockquote> <p>1595920708323999744</p> </blockquote> <p>・my code (failed)</p> <pre><code>final result = _controller.text; t = s.lastIndexOf('status')); s.substring(t) </code></pre>
[ { "answer_id": 74587802, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 3, "selected": true, "text": "Uri path var str =\n \"https://twitter.com/straw_berry0721/status/1596714080345415681?s=20&t=1nIbnSZ2YN2m5KZaOjO5GA\";\nUri uri = Uri.parse(str);\n\nprint(\"id= ${uri.path.substring(uri.path.lastIndexOf('/') + 1)}\");//id= 1596714080345415681\n var reg = RegExp(r'status\\/(\\d+)');\nvar result = reg.firstMatch(str)?.group(1);\nprint(\"result = $result\"); // result = 1596714080345415681\n" }, { "answer_id": 74587826, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 0, "selected": false, "text": "List<String> String extractLastNumber(String url) {\nreturn url.split(\"/\").last;\n}\n\n\nfinal extractedNumber = extractLastNumber(\"https://twitter.com/xxx/status/1595920708323999744\");\n\nprint(extractedNumber); // \"1595920708323999744\"\nprint(\"status: $extractedNumber\"); // \"status: 1595920708323999744\"\n String int int.tryParse() print(int.tryParse(extractedNumber)); // 1595920708323999744\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18096205/" ]
74,587,725
<p>I can't seem to find an answer to this that I can understand</p> <p>I have tabs and a tab block, which is a clone of <a href="https://github.com/ahsanshaheen199/guten-tab/tree/master/src/blocks" rel="nofollow noreferrer">this basic tab block plugin</a>. I'm trying to add the ability to select an &quot;icon&quot; for each tab block.</p> <p>I'm close. Using the MediaUpload component, I'm able to see the file I've selected under the <code>activeTab</code> object, but it doesn't update the parent block attribute, so I can't reference the <code>icon_url</code> attribute.</p> <p>tab/edit.js</p> <pre><code>const Edit = ({ attributes, setAttributes, clientId }) =&gt; { const { uid, activeTab } = attributes; useEffect(() =&gt; { if (!uid) { setAttributes({ uid: clientId }); } }, []); const display = activeTab === uid ? &quot;block&quot; : &quot;none&quot;; const ALLOWED_MEDIA_TYPES = [&quot;image&quot;, &quot;svg&quot;]; const setTabIcon = (icon_url) =&gt; { const parentBlock = select(&quot;core/block-editor&quot;).getBlock(clientId); dispatch(&quot;core/block-editor&quot;).updateBlockAttributes( parentBlock.clientId, { ...attributes, icon_url, } ); }; return ( &lt;div {...useBlockProps()}&gt; &lt;InspectorControls&gt; &lt;div&gt; &lt;MediaUpload allowedTypes={ALLOWED_MEDIA_TYPES} onSelect={(media) =&gt; setTabIcon(media.url)} render={({ open }) =&gt; ( &lt;button onClick={open}&gt;Open Media Library&lt;/button&gt; )} /&gt; &lt;/div&gt; &lt;/InspectorControls&gt; &lt;div className={&quot;guten-tab-panel&quot;} style={{ display }}&gt; &lt;InnerBlocks allowedBlocks={[&quot;core/heading&quot;, &quot;core/paragraph&quot;]} renderAppender={() =&gt; &lt;InnerBlocks.ButtonBlockAppender /&gt;} /&gt; &lt;/div&gt; &lt;/div&gt; ); }; export default Edit; </code></pre> <p>I would first think that using setAttributes here would also update the parent, but this only updates <code>setActive</code> in the child block. It doesn't keep the change.</p> <p>In tabs.js, I'm trying to reference tab.icon_url. icon_url doesn't exist, only <code>uid</code> and <code>title</code></p> <p>tabs/tabs.js</p> <pre><code>const Edit = ({ attributes, setAttributes, clientId }) =&gt; { const { tabs, activeTab } = attributes; const blockProps = useBlockProps({ className: `${useBlockProps().className} guten-tab-wrapper`, }); const setActiveTab = (uid) =&gt; { setAttributes({ activeTab: uid }); const parentBlock = select(&quot;core/block-editor&quot;).getBlock(clientId); parentBlock.innerBlocks.forEach((innerBlock) =&gt; { dispatch(&quot;core/block-editor&quot;).updateBlockAttributes( innerBlock.clientId, { activeTab: uid, } ); }); }; const addNewTab = () =&gt; { const tab = createBlock(&quot;ahsan03/tab&quot;); const position = tabs.length; dispatch(&quot;core/block-editor&quot;).insertBlock(tab, position, clientId); setAttributes({ tabs: [ ...tabs, { uid: tab.clientId, title: `Tab ${tabs.length + 1}`, icon_url: &quot;&quot;, }, ], }); setActiveTab(tab.clientId); }; const tabTitleChange = (newValue) =&gt; { setAttributes({ tabs: [ ...tabs.map((tab) =&gt; { return tab.uid === activeTab ? { ...tab, title: newValue, } : tab; }), ], }); }; useEffect(() =&gt; { if (tabs.length &amp;&amp; !activeTab) { setActiveTab(tabs[0].uid); } }, [tabs]); return ( &lt;&gt; &lt;div {...blockProps}&gt; &lt;div className={&quot;guten-tabs-nav&quot;}&gt; {tabs.map((tab) =&gt; { return ( &lt;div key={tab.uid} className={&quot;guten-tab-item&quot;} role=&quot;tab&quot; tabIndex=&quot;0&quot; onClick={() =&gt; setActiveTab(tab.uid)} &gt; &lt;div className={`guten-tab-link${ tab.uid === activeTab ? &quot; is-active&quot; : &quot;&quot; }`} &gt; &lt;img src={tab.icon_url} alt=&quot;&quot; /&gt; {console.log(&quot;tabs tab&quot;, { tab, })} &lt;RichText tagName=&quot;div&quot; value={tab.title} onChange={tabTitleChange} /&gt; &lt;/div&gt; &lt;/div&gt; ); })} &lt;Button variant={&quot;primary&quot;} icon={&quot;plus&quot;} onClick={addNewTab} &gt; {__(&quot;&quot;, &quot;gtt&quot;)} &lt;/Button&gt; &lt;/div&gt; &lt;div className={&quot;guten-tab-content&quot;}&gt; &lt;InnerBlocks allowedBlocks={[&quot;ahsan03/tab&quot;]} renderAppender={false} /&gt; &lt;/div&gt; &lt;/div&gt; &lt;/&gt; ); }; export default Edit; </code></pre> <p>How can I fix this so uploading an image is in the parent block attributes?</p> <p>Here's an updated setTabIcon function that I think is closer to what I need, I'm just not sure what to do after fetching the parentBlock.</p> <pre><code>const setTabIcon = (icon_url) =&gt; { const parentBlockIds = select(&quot;core/block-editor&quot;).getBlockParents(clientId); parentBlockIds.forEach((parentBlockId) =&gt; { const parentBlock = select(&quot;core/block-editor&quot;).getBlock(parentBlockId); console.log({ parentBlock }); }); }; </code></pre>
[ { "answer_id": 74587802, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 3, "selected": true, "text": "Uri path var str =\n \"https://twitter.com/straw_berry0721/status/1596714080345415681?s=20&t=1nIbnSZ2YN2m5KZaOjO5GA\";\nUri uri = Uri.parse(str);\n\nprint(\"id= ${uri.path.substring(uri.path.lastIndexOf('/') + 1)}\");//id= 1596714080345415681\n var reg = RegExp(r'status\\/(\\d+)');\nvar result = reg.firstMatch(str)?.group(1);\nprint(\"result = $result\"); // result = 1596714080345415681\n" }, { "answer_id": 74587826, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 0, "selected": false, "text": "List<String> String extractLastNumber(String url) {\nreturn url.split(\"/\").last;\n}\n\n\nfinal extractedNumber = extractLastNumber(\"https://twitter.com/xxx/status/1595920708323999744\");\n\nprint(extractedNumber); // \"1595920708323999744\"\nprint(\"status: $extractedNumber\"); // \"status: 1595920708323999744\"\n String int int.tryParse() print(int.tryParse(extractedNumber)); // 1595920708323999744\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15396919/" ]
74,587,726
<p>Due to some compliance, We are only allowed to take respective permission each time when user use that feature.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Obvious Scenario</th> <th>Required Scenario</th> </tr> </thead> <tbody> <tr> <td><a href="https://i.stack.imgur.com/8qG6U.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8qG6U.png" alt="Obvious Scenario" /></a></td> <td><a href="https://i.stack.imgur.com/monbc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/monbc.png" alt="Required Scenario" /></a></td> </tr> </tbody> </table> </div>
[ { "answer_id": 74587802, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 3, "selected": true, "text": "Uri path var str =\n \"https://twitter.com/straw_berry0721/status/1596714080345415681?s=20&t=1nIbnSZ2YN2m5KZaOjO5GA\";\nUri uri = Uri.parse(str);\n\nprint(\"id= ${uri.path.substring(uri.path.lastIndexOf('/') + 1)}\");//id= 1596714080345415681\n var reg = RegExp(r'status\\/(\\d+)');\nvar result = reg.firstMatch(str)?.group(1);\nprint(\"result = $result\"); // result = 1596714080345415681\n" }, { "answer_id": 74587826, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 0, "selected": false, "text": "List<String> String extractLastNumber(String url) {\nreturn url.split(\"/\").last;\n}\n\n\nfinal extractedNumber = extractLastNumber(\"https://twitter.com/xxx/status/1595920708323999744\");\n\nprint(extractedNumber); // \"1595920708323999744\"\nprint(\"status: $extractedNumber\"); // \"status: 1595920708323999744\"\n String int int.tryParse() print(int.tryParse(extractedNumber)); // 1595920708323999744\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5340621/" ]
74,587,740
<p><strong>Aim</strong></p> <p>Group tasks per employee/group of employees for which tasks were assigned to.</p> <p><strong>Data Context</strong></p> <ul> <li>Each task can be assigned to more than one employee</li> <li>Each employee can have multiple tasks</li> <li>Values like employee <code>type</code> or <code>name</code> are just extra data, meaning it's the <code>employee_id</code> that distinguishes them</li> </ul> <p><strong>Problem</strong></p> <p>Currently, I am able to group the tasks per employee, not group of employees. If a task is shared by more than one employee, it is repeated on the array, like the example tasks below (appear in 2 employees groups: for <code>employee_id</code> <code>111</code> and <code>999</code> if you run the last code snippet that has both the initial data and my current code).</p> <pre><code> { &quot;task_employee_id&quot;: 10001, &quot;task_name&quot;: &quot;Maintenance&quot;, &quot;task_url&quot;: &quot;www.task_url10001.com&quot;, &quot;status&quot;: &quot;incomplete&quot; }, { &quot;task_employee_id&quot;: 20002, &quot;task_name&quot;: &quot;Cleaning&quot;, &quot;task_url&quot;: &quot;www.task_url20002.com&quot;, &quot;status&quot;: &quot;completed&quot; }, </code></pre> <p><strong>Expected Result</strong></p> <p>I should have it like this</p> <pre><code>groupTasks: [ { &quot;employee_id&quot;: [{999},{111}] &quot;type&quot;: &quot;ABC&quot;, &quot;name&quot;: &quot;Lorem&quot;, &quot;tasks&quot;: [ { &quot;task_employee_id&quot;: 10001, &quot;task_name&quot;: &quot;Maintenance&quot;, &quot;task_url&quot;: &quot;www.task_url10001.com&quot;, &quot;status&quot;: &quot;incomplete&quot; }, { &quot;task_employee_id&quot;: 20002, &quot;task_name&quot;: &quot;Cleaning&quot;, &quot;task_url&quot;: &quot;www.task_url20002.com&quot;, &quot;status&quot;: &quot;completed&quot; } ] }, { &quot;employee_id&quot;: 111, &quot;type&quot;: &quot;ZHG&quot;, &quot;name&quot;: &quot;Ipsum&quot;, &quot;tasks&quot;: [ { &quot;task_employee_id&quot;: 30003, &quot;task_name&quot;: &quot;Fixing&quot;, &quot;task_url&quot;: &quot;www.task_url30003.com&quot;, &quot;status&quot;: &quot;incomplete&quot; } ] }, { &quot;employee_id&quot;: 999, &quot;type&quot;: &quot;ABC&quot;, &quot;name&quot;: &quot;Lorem&quot;, &quot;tasks&quot;: [ { &quot;task_employee_id&quot;: 40004, &quot;task_name&quot;: &quot;Checking&quot;, &quot;task_url&quot;: &quot;www.task_url40004.com&quot;, &quot;status&quot;: &quot;complete&quot; } ] ] </code></pre> <p>Sidenote: it could either be <code>&quot;employee_ids&quot;: [{&quot;employee_id&quot; :999},{&quot;employee_id&quot; : 111}]</code> or <code>&quot;employee_id&quot;: [999,111]</code></p> <p><strong>Here is the code snippet with the initial data and my current code that doesn't ouput the expected result</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const data = [ { task_id: 10001, task_name: "Maintenance", task_url: "www.task_url10001.com", status: "incomplete", employees: [ { employee_id: 999, type: "ABC", name: "Lorem" }, { employee_id: 111, type: "ZHG", name: "Ipsum" } ] }, { task_id: 20002, task_name: "Cleaning", task_url: "www.task_url20002.com", status: "completed", employees: [ { employee_id: 111, type: "ZHG", name: "Ipsum" }, { employee_id: 999, type: "ABC", name: "Lorem" } ] }, { task_id: 30003, task_name: "Fixing", task_url: "www.task_url30003.com", status: "incomplete", employees: [{ employee_id: 111, type: "ZHG", name: "Ipsum" }] }, { task_id: 40004, task_name: "Checking", task_url: "www.task_url40004.com", status: "complete", employees: [{ employee_id: 999, type: "ABC", name: "Lorem" }] } ]; // current approach const groupTasks = [ ...data .reduce( ( groupTasksEmployees, { task_id: task_employee_id, task_name, task_url, status, employees = [] } ) =&gt; { employees.forEach(({ employee_id, type, name }) =&gt; { const employees = groupTasksEmployees.get(employee_id) ?? { employee_id, type, name, tasks: [] }; employees.tasks.push({ task_employee_id, task_name, task_url, status }); groupTasksEmployees.set(employee_id, employees); }); return groupTasksEmployees; }, new Map() ) .values() ]; console.log("groupTasks: ", groupTasks);</code></pre> </div> </div> </p>
[ { "answer_id": 74587802, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 3, "selected": true, "text": "Uri path var str =\n \"https://twitter.com/straw_berry0721/status/1596714080345415681?s=20&t=1nIbnSZ2YN2m5KZaOjO5GA\";\nUri uri = Uri.parse(str);\n\nprint(\"id= ${uri.path.substring(uri.path.lastIndexOf('/') + 1)}\");//id= 1596714080345415681\n var reg = RegExp(r'status\\/(\\d+)');\nvar result = reg.firstMatch(str)?.group(1);\nprint(\"result = $result\"); // result = 1596714080345415681\n" }, { "answer_id": 74587826, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 0, "selected": false, "text": "List<String> String extractLastNumber(String url) {\nreturn url.split(\"/\").last;\n}\n\n\nfinal extractedNumber = extractLastNumber(\"https://twitter.com/xxx/status/1595920708323999744\");\n\nprint(extractedNumber); // \"1595920708323999744\"\nprint(\"status: $extractedNumber\"); // \"status: 1595920708323999744\"\n String int int.tryParse() print(int.tryParse(extractedNumber)); // 1595920708323999744\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1128912/" ]
74,587,741
<p>I have to create a program that tracks a person's motion. F represents forward B represents backward. The values are to be randomly generated between 2-20 as well as the total # of steps being randomly generated from 10-85 (total will decide when the steps will stop). The # of forward steps has to be greater than the # of backwards steps (always). My problem is that if my total is a number that's not so far from the # of steps forward, my # of backwards steps aren't even fully generated once. For example, I generated my program and it gave me an output of this: FFFFFFFFFFFFFFFFFFBBBBB 13 steps from start Forward: 18 Backward: 14 Total: 23 But the backwards steps weren't even able to be completed. How can I make it so this won't occur? Do I have to add a restriction?</p> <p>Here's my code:</p> <pre><code>import random while True: fwd= random.randint(2,20) bkwd= random.randint(2,fwd-1) total=random.randint(10,85) f= 0 b = 0 t= 0 steps_taken= 0 if bkwd &gt; fwd: break while total &gt; 0: f = 0 while fwd &gt; f: if total &gt; 0: print(&quot;F&quot;, end=&quot;&quot;) f=f+1 t=t+1 total=total-1 steps_taken= steps_taken+1 else: f = fwd b = 0 while bkwd &gt; b: if total &gt; 0: print(&quot;B&quot;, end=&quot;&quot;) t=t-1 b=b+1 total=total-1 steps_taken= steps_taken+1 else: b = bkwd if f &gt; total: break print(&quot; &quot;,t, &quot;steps from the start&quot;) #I need help here printing the right amount of total steps print(&quot;Forward:&quot;, f, &quot;Backward:&quot;, b, &quot;Total:&quot;, steps_taken ) </code></pre> <p>Here are my instructions: A person walks a random amount of steps forward, and then a different random number of steps backwards.</p> <p>The random steps are anywhere between 2 and 20 The number of steps forward is always greater than the number of steps backwards That motion of forward / backward random steps repeats itself again and again The motion is consistent (the number of forward steps stays the same throughout the motion, and the number of backwards steps stays the same throughout the motion) After making a specific amount of total steps the person is told to stop and will be a certain amount of steps forward from where they started.</p> <p>The total number of steps is generated randomly and will be between 10 and 85 You are writing a program to simulate the motion taken by the person.</p> <p>Display that motion and the number of steps he ends away from where he started. For Example:</p> <p>If the program generated the forward steps to be 4, and the backward steps to be 2, and the total number of steps to be 13, your program would display: FFFFBBFFFFBBF = 5 Steps from the start If the program generated the forward steps to be 5, and the backward steps to be 3, and the total steps to be 16, your program would display FFFFFBBBFFFFFBBB = 4 Steps from the start</p>
[ { "answer_id": 74587795, "author": "Sam", "author_id": 16660603, "author_profile": "https://Stackoverflow.com/users/16660603", "pm_score": 0, "selected": false, "text": "total fwd bkwd total=random.randint(fwd+bkwd,85)\n" }, { "answer_id": 74588061, "author": "ScottC", "author_id": 20174226, "author_profile": "https://Stackoverflow.com/users/20174226", "pm_score": 1, "selected": false, "text": "import random\n\ntotal_steps = random.randint(10, 85)\nfwd = random.randint(3,(20, total_steps-1)[total_steps<21])\nbkwd= random.randint(2,fwd-1)\n\nif (fwd+bkwd) > total_steps: \n bkwd = total_steps-fwd\n\nprint(\"Total_steps=\", total_steps, \", fwd=\", fwd, \", bkwd=\", bkwd)\n\n# Initialise step pattern to a blank string, and steps to zero.\nstep_pattern = \"\"\nsteps = 0\nwhile total_steps > 0:\n for i in range(fwd):\n step_pattern += \"F\"\n steps += 1\n total_steps -= 1\n \n if total_steps > 0:\n for j in range(bkwd):\n step_pattern += \"B\"\n steps -= 1\n total_steps -= 1\n\n# Use f-strings to insert (step_pattern) and (steps) into string\nprint(f\"{step_pattern} = {steps} steps from the start\")\n Total_steps= 45 , fwd= 5 , bkwd= 2\nFFFFFBBFFFFFBBFFFFFBBFFFFFBBFFFFFBBFFFFFBBFFF = 21 steps from the start\n Total_steps= 14 , fwd= 6 , bkwd= 5\nFFFFFFBBBBBFFF = 4 steps from the start\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20611666/" ]
74,587,742
<p>What is the proper way to sort a mat-table which has one column that displays a description rather than the code of a mat-select. Consider the following code example that is an editable mat-table which displays a description of the selected item from the mat-select column in edit mode, when not in edit mode. That means when the grid isn't in edit mode, I call a function to give me the description to display.</p> <p>In static mode:</p> <pre><code>&lt;div *ngIf=&quot;col.key == 'MGA_ServiceDescription'&quot;&gt; &lt;span &gt; {{ getServiceDescription(element[col.key]) }} &lt;/span&gt; &lt;/div&gt; </code></pre> <p>In Edit mode:</p> <pre><code>mat-form-field *ngSwitchCase=&quot;'listServiceDescriptions'&quot; &gt; &lt;mat-select [(value)]=&quot;element[col.key]&quot;&gt; &lt;mat-option *ngFor=&quot;let c of filteredServices&quot; [value]=&quot;c.SDE_CODE&quot; {{ c.SDE_DESCRIPTION}} &lt;/mat-option&gt; &lt;/mat-select&gt; /mat-form-field&gt; </code></pre> <p><a href="https://stackblitz.com/edit/angular-editable-table-part-2-7hvbyt?file=src/app/app.component.ts" rel="nofollow noreferrer">Code example</a></p>
[ { "answer_id": 74605862, "author": "Jimmy", "author_id": 4960765, "author_profile": "https://Stackoverflow.com/users/4960765", "pm_score": 2, "selected": true, "text": "sortingDataAccessor sortingDataAccessor occupationsList description (the mapped value) this.dataSource = new MatTableDataSource(USER_DATA);\n this.dataSource.sortingDataAccessor = (item, property) => {\n switch(property) {\n case 'occupation': occupationsList.find(o => o.name === item.occupation).description;\n default: return item[property];\n }\n };\n this.dataSource.sort = this.sort;\n" }, { "answer_id": 74638822, "author": "Eliseo", "author_id": 8558186, "author_profile": "https://Stackoverflow.com/users/8558186", "pm_score": 0, "selected": false, "text": " ngOnInit() {\n this.dataSource = new MatTableDataSource(\n USER_DATA.map((code: any) => {\n const serviceDescription = this.serviceDescriptions.find(\n (desc: any) => desc.SDE_CODE === code.MGA_ServiceDescription\n );\n return {\n ...code,\n description: serviceDescription? serviceDescription.SDE_DESCRIPTION: '',\n };\n })\n );\n }\n <th\n mat-header-cell\n *matHeaderCellDef\n [mat-sort-header]=\"col.key=='MGA_ServiceDescription'?'description':col.key\"\n [disabled]=\"col.key == 'isEdit'\"\n >\n compareWith serviceCompareWith=(a:any, MGA_ServiceDescription:any)=>\n a.SDE_CODE==MGA_ServiceDescription\n change(value:any,element:any)\n {\n element.MGA_ServiceDescription=value.SDE_CODE;\n element.description=value.SDE_DESCRIPTION\n }\n <mat-select [compareWith]=\"serviceCompareWith\" \n [value]=\"element.MGA_ServiceDescription\" \n (selectionChange)=\"change($event.value,element)\">\n <mat-option *ngFor=\"let service of serviceDescriptions\" [value]=\"service\">\n {{service.SDE_DESCRIPTION}}\n </mat-option>\n</mat-select>\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2966506/" ]
74,587,764
<pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;!-- If you are serving your web app in a path other than the root, change the href value below to reflect the base path you are serving from. The path provided below has to start and end with a slash &quot;/&quot; in order for it to work correctly. For more details: * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base This is a placeholder for base href that will be replaced by the value of the `--base-href` argument provided to `flutter build`. --&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta content=&quot;IE=Edge&quot; http-equiv=&quot;X-UA-Compatible&quot;&gt; &lt;meta name=&quot;description&quot; content=&quot;A new Flutter project.&quot;&gt; &lt;!-- iOS meta tags &amp; icons --&gt; &lt;meta name=&quot;apple-mobile-web-app-capable&quot; content=&quot;yes&quot;&gt; &lt;meta name=&quot;apple-mobile-web-app-status-bar-style&quot; content=&quot;black&quot;&gt; &lt;meta name=&quot;apple-mobile-web-app-title&quot; content=&quot;futurek&quot;&gt; &lt;link rel=&quot;apple-touch-icon&quot; href=&quot;icons/Icon-192.png&quot;&gt; &lt;!-- Favicon --&gt; &lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; href=&quot;favicon.png&quot; /&gt; &lt;title&gt;futurek&lt;/title&gt; &lt;link rel=&quot;manifest&quot; href=&quot;manifest.json&quot;&gt; &lt;/head&gt; &lt;body&gt; &lt;!-- This script installs service_worker.js to provide PWA functionality to application. For more information, see: https://developers.google.com/web/fundamentals/primers/service-workers --&gt; &lt;script&gt; var serviceWorkerVersion = null; var scriptLoaded = false; function loadMainDartJs() { if (scriptLoaded) { return; } scriptLoaded = true; var scriptTag = document.createElement('script'); scriptTag.src = 'main.dart.js'; scriptTag.type = 'application/javascript'; document.body.append(scriptTag); } if ('serviceWorker' in navigator) { // Service workers are supported. Use them. window.addEventListener('load', function () { // Wait for registration to finish before dropping the &lt;script&gt; tag. // Otherwise, the browser will load the script multiple times, // potentially different versions. var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion; navigator.serviceWorker.register(serviceWorkerUrl) .then((reg) =&gt; { function waitForActivation(serviceWorker) { serviceWorker.addEventListener('statechange', () =&gt; { if (serviceWorker.state == 'activated') { console.log('Installed new service worker.'); loadMainDartJs(); } }); } if (!reg.active &amp;&amp; (reg.installing || reg.waiting)) { // No active web worker and we have installed or are installing // one for the first time. Simply wait for it to activate. waitForActivation(reg.installing || reg.waiting); } else if (!reg.active.scriptURL.endsWith(serviceWorkerVersion)) { // When the app updates the serviceWorkerVersion changes, so we // need to ask the service worker to update. console.log('New service worker available.'); reg.update(); waitForActivation(reg.installing); } else { // Existing service worker is still good. console.log('Loading app from service worker.'); loadMainDartJs(); } }); // If service worker doesn't succeed in a reasonable amount of time, // fallback to plaint &lt;script&gt; tag. setTimeout(() =&gt; { if (!scriptLoaded) { console.warn( 'Failed to load app from service worker. Falling back to plain &lt;script&gt; tag.', ); loadMainDartJs(); } }, 4000); }); } else { // Service workers not supported. Just drop the &lt;script&gt; tag. loadMainDartJs(); } &lt;/script&gt; &lt;script type=&quot;module&quot;&gt; // Import the functions you need from the SDKs you need import { initializeApp } from &quot;https://www.gstatic.com/firebasejs/9.14.0/firebase-app.js&quot;; import { getAnalytics } from &quot;https://www.gstatic.com/firebasejs/9.14.0/firebase-analytics.js&quot;; // TODO: Add SDKs for Firebase products that you want to use // https://firebase.google.com/docs/web/setup#available-libraries // Your web app's Firebase configuration // For Firebase JS SDK v7.20.0 and later, measurementId is optional const firebaseConfig = { apiKey: &quot;AIzaSyCOmHqx7WK_DfPNEwdmGVPhwlGjqPvb3eo&quot;, authDomain: &quot;final-gpkart22nov2022.firebaseapp.com&quot;, projectId: &quot;final-gpkart22nov2022&quot;, storageBucket: &quot;final-gpkart22nov2022.appspot.com&quot;, messagingSenderId: &quot;331850581676&quot;, appId: &quot;1:331850581676:web:47e15890971bd243e04109&quot;, measurementId: &quot;G-TYBCD278ZL&quot; }; // Initialize Firebase const app = initializeApp(firebaseConfig); const analytics = getAnalytics(app); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>i above mentioned index.html file and here is my git repository link of project <a href="https://github.com/AbhiEntrepreneur/26nov_firebaseBlank" rel="nofollow noreferrer">https://github.com/AbhiEntrepreneur/26nov_firebaseBlank</a></p> <p>I am working on a flutter web project , after developing in vs code when i run in localhost it is working fine but after deploying in firebase on main domain it is showing white blank page on main url (Please help me out to resolve this issue ) ****</p>
[ { "answer_id": 74605862, "author": "Jimmy", "author_id": 4960765, "author_profile": "https://Stackoverflow.com/users/4960765", "pm_score": 2, "selected": true, "text": "sortingDataAccessor sortingDataAccessor occupationsList description (the mapped value) this.dataSource = new MatTableDataSource(USER_DATA);\n this.dataSource.sortingDataAccessor = (item, property) => {\n switch(property) {\n case 'occupation': occupationsList.find(o => o.name === item.occupation).description;\n default: return item[property];\n }\n };\n this.dataSource.sort = this.sort;\n" }, { "answer_id": 74638822, "author": "Eliseo", "author_id": 8558186, "author_profile": "https://Stackoverflow.com/users/8558186", "pm_score": 0, "selected": false, "text": " ngOnInit() {\n this.dataSource = new MatTableDataSource(\n USER_DATA.map((code: any) => {\n const serviceDescription = this.serviceDescriptions.find(\n (desc: any) => desc.SDE_CODE === code.MGA_ServiceDescription\n );\n return {\n ...code,\n description: serviceDescription? serviceDescription.SDE_DESCRIPTION: '',\n };\n })\n );\n }\n <th\n mat-header-cell\n *matHeaderCellDef\n [mat-sort-header]=\"col.key=='MGA_ServiceDescription'?'description':col.key\"\n [disabled]=\"col.key == 'isEdit'\"\n >\n compareWith serviceCompareWith=(a:any, MGA_ServiceDescription:any)=>\n a.SDE_CODE==MGA_ServiceDescription\n change(value:any,element:any)\n {\n element.MGA_ServiceDescription=value.SDE_CODE;\n element.description=value.SDE_DESCRIPTION\n }\n <mat-select [compareWith]=\"serviceCompareWith\" \n [value]=\"element.MGA_ServiceDescription\" \n (selectionChange)=\"change($event.value,element)\">\n <mat-option *ngFor=\"let service of serviceDescriptions\" [value]=\"service\">\n {{service.SDE_DESCRIPTION}}\n </mat-option>\n</mat-select>\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17923759/" ]
74,587,783
<p>taking for example i have two numbers JEAN : &quot;5143436111&quot; SAMI : &quot;4501897654&quot;</p> <p>I need the funtion to give me this:</p> <p>i have 7 odd digits in JEAN number i have 5 even digits in SAMI number</p> <p>I tried this function but i want to choose if i want the odd or even digits bcz in here its showing both but i want my fuction to give me the choice to choose</p> <p>`</p> <pre><code>static int countEvenOdd(int n) { int even_count = 0; int odd_count = 0; while (n &gt; 0) { int rem = n % 10; if (rem % 2 == 0) even_count++; else odd_count++; n = n / 10; } System.out.println ( &quot;Even count : &quot; + even_`your text`count); System.out.println ( &quot;Odd count : &quot; + odd_count); if (even_count % 2 == 0 &amp;&amp; odd_count % 2 != 0) return 1; else return 0; } </code></pre> <p>`</p>
[ { "answer_id": 74605862, "author": "Jimmy", "author_id": 4960765, "author_profile": "https://Stackoverflow.com/users/4960765", "pm_score": 2, "selected": true, "text": "sortingDataAccessor sortingDataAccessor occupationsList description (the mapped value) this.dataSource = new MatTableDataSource(USER_DATA);\n this.dataSource.sortingDataAccessor = (item, property) => {\n switch(property) {\n case 'occupation': occupationsList.find(o => o.name === item.occupation).description;\n default: return item[property];\n }\n };\n this.dataSource.sort = this.sort;\n" }, { "answer_id": 74638822, "author": "Eliseo", "author_id": 8558186, "author_profile": "https://Stackoverflow.com/users/8558186", "pm_score": 0, "selected": false, "text": " ngOnInit() {\n this.dataSource = new MatTableDataSource(\n USER_DATA.map((code: any) => {\n const serviceDescription = this.serviceDescriptions.find(\n (desc: any) => desc.SDE_CODE === code.MGA_ServiceDescription\n );\n return {\n ...code,\n description: serviceDescription? serviceDescription.SDE_DESCRIPTION: '',\n };\n })\n );\n }\n <th\n mat-header-cell\n *matHeaderCellDef\n [mat-sort-header]=\"col.key=='MGA_ServiceDescription'?'description':col.key\"\n [disabled]=\"col.key == 'isEdit'\"\n >\n compareWith serviceCompareWith=(a:any, MGA_ServiceDescription:any)=>\n a.SDE_CODE==MGA_ServiceDescription\n change(value:any,element:any)\n {\n element.MGA_ServiceDescription=value.SDE_CODE;\n element.description=value.SDE_DESCRIPTION\n }\n <mat-select [compareWith]=\"serviceCompareWith\" \n [value]=\"element.MGA_ServiceDescription\" \n (selectionChange)=\"change($event.value,element)\">\n <mat-option *ngFor=\"let service of serviceDescriptions\" [value]=\"service\">\n {{service.SDE_DESCRIPTION}}\n </mat-option>\n</mat-select>\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20611685/" ]
74,587,804
<p>Hello I'm technically new to vuejs and I was wondering if I can change a value of &lt;input <strong>:value=&quot;{data: data}&quot;</strong> /&gt; so in my main page template</p> <pre class="lang-html prettyprint-override"><code>&lt;titled-input width=&quot;528&quot; height=&quot;49.6&quot; fontSize=&quot;16&quot; title=&quot;Event Title&quot; :data=&quot;title&quot; &gt; &lt;/titled-input&gt; </code></pre> <p>and in my main page script</p> <pre class="lang-js prettyprint-override"><code>export default { components: { PrimaryButton, TitledInput, InputTags, }, data() { return { title: &quot;Title&quot;, }; } }; </code></pre> <p>and in my components.vue (not its real name) I added a</p> <pre class="lang-js prettyprint-override"><code>:value=&quot;{data: data}&quot; </code></pre> <p>and also in the props I added</p> <pre><code>data: String, </code></pre> <p>I thought this might work because other props work fine especially when I add a width: Number in the props and</p> <pre class="lang-js prettyprint-override"><code>:style =&quot;{ width: width + 'px'}&quot; </code></pre> <p>do this</p> <p>When I tried the code above it will give me</p> <p><a href="https://i.stack.imgur.com/BWs96.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BWs96.png" alt="enter image description here" /></a></p> <p>what I am expecting inside the input field is the word &quot;Title&quot;</p>
[ { "answer_id": 74605862, "author": "Jimmy", "author_id": 4960765, "author_profile": "https://Stackoverflow.com/users/4960765", "pm_score": 2, "selected": true, "text": "sortingDataAccessor sortingDataAccessor occupationsList description (the mapped value) this.dataSource = new MatTableDataSource(USER_DATA);\n this.dataSource.sortingDataAccessor = (item, property) => {\n switch(property) {\n case 'occupation': occupationsList.find(o => o.name === item.occupation).description;\n default: return item[property];\n }\n };\n this.dataSource.sort = this.sort;\n" }, { "answer_id": 74638822, "author": "Eliseo", "author_id": 8558186, "author_profile": "https://Stackoverflow.com/users/8558186", "pm_score": 0, "selected": false, "text": " ngOnInit() {\n this.dataSource = new MatTableDataSource(\n USER_DATA.map((code: any) => {\n const serviceDescription = this.serviceDescriptions.find(\n (desc: any) => desc.SDE_CODE === code.MGA_ServiceDescription\n );\n return {\n ...code,\n description: serviceDescription? serviceDescription.SDE_DESCRIPTION: '',\n };\n })\n );\n }\n <th\n mat-header-cell\n *matHeaderCellDef\n [mat-sort-header]=\"col.key=='MGA_ServiceDescription'?'description':col.key\"\n [disabled]=\"col.key == 'isEdit'\"\n >\n compareWith serviceCompareWith=(a:any, MGA_ServiceDescription:any)=>\n a.SDE_CODE==MGA_ServiceDescription\n change(value:any,element:any)\n {\n element.MGA_ServiceDescription=value.SDE_CODE;\n element.description=value.SDE_DESCRIPTION\n }\n <mat-select [compareWith]=\"serviceCompareWith\" \n [value]=\"element.MGA_ServiceDescription\" \n (selectionChange)=\"change($event.value,element)\">\n <mat-option *ngFor=\"let service of serviceDescriptions\" [value]=\"service\">\n {{service.SDE_DESCRIPTION}}\n </mat-option>\n</mat-select>\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20549239/" ]
74,587,809
<p>Given the dataframe:</p> <pre><code>df = data.frame(x = c(&quot;A:B&quot;,&quot;B:C&quot;,&quot;D&quot;,&quot;E&quot;,&quot;F&quot;), y = c(&quot;1&quot;,&quot;2&quot;,&quot;3&quot;,&quot;4&quot;,&quot;5&quot;)) </code></pre> <p>How do I keep just the rows that contain &quot;:&quot; in column x? Normally, I would just use <code>dplyr::filter()</code> to delete the rows containing the string but the following code doesn't seem to work:</p> <pre><code>df %&gt;% filter(x %in% &quot;:&quot;) </code></pre> <p>It seems like &quot;:&quot; may be breaking it because it deletes all rows, but I can't seem to figure out how else to indicate &quot;:&quot; in R.</p> <p><em>Edit</em>: If there are other symbols that also trigger this issue then a general solution would also be great!</p>
[ { "answer_id": 74587841, "author": "Bei", "author_id": 16569807, "author_profile": "https://Stackoverflow.com/users/16569807", "pm_score": 2, "selected": true, "text": "df %>% filter(grepl(\":\", x))\n" }, { "answer_id": 74588210, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 0, "selected": false, "text": "df[grepl(':',df$x),]\n x y\n1 A:B 1\n2 B:C 2\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10178641/" ]
74,587,821
<p>I would like to delete my DB instance.before delete I will create final manual snapshot. I understood snapshot is not full backup.it is incremental.which means that only the data that has changed after your most recent snapshot saved .</p> <p>so,I would like to know RDS restore DB from only final snapshot event if deleted other created all manual snapshot.</p> <p>Please help me.Thanks a lot.</p> <p>AWD RDS final manual snapshot are full or incremental ? final manual snapshot can be restore, event if deleted you taken all other manual snapshots</p>
[ { "answer_id": 74587841, "author": "Bei", "author_id": 16569807, "author_profile": "https://Stackoverflow.com/users/16569807", "pm_score": 2, "selected": true, "text": "df %>% filter(grepl(\":\", x))\n" }, { "answer_id": 74588210, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 0, "selected": false, "text": "df[grepl(':',df$x),]\n x y\n1 A:B 1\n2 B:C 2\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20611745/" ]
74,587,824
<p>An example to demonstrate my problem, suppose the csv file is formatted like:</p> <pre><code>2022-11-05,Female,30-39,City of London 2022-11-05,Male,60-69,City of London 2022-11-04,Female,70-79,City of London 2022-11-04,Female,60-69,City of London </code></pre> <p>Should be read into a dictionary like:</p> <pre><code>{'2022-11-05': [(Female,30-39, City of London), (Male,60-69,City of London), '2022-11-04': [(Female, 70-79, City of London), (Female, 60-69, City of London)]} </code></pre> <p>When I attempted to read it like:</p> <pre><code>vaccine_data_reader = csv.reader(vaccine_date_file) mydict = {rows[0]: [(rows[1],rows[2],rows[3])] for rows in vaccine_data_reader} </code></pre> <p>I only got one value per key, not multiple lists of tuples for each unique entry.</p>
[ { "answer_id": 74587933, "author": "Sam", "author_id": 16660603, "author_profile": "https://Stackoverflow.com/users/16660603", "pm_score": 0, "selected": false, "text": "Dictionary Comprehension dictionary for rows in vaccine_data_reader:\n if rows[0] in mydict.keys(): #Checks if the keys already exists\n mydict[rows[0]].append(tuple(rows[1:])) #Appends the value of duplicate\n continue\n mydict[rows[0]] = [tuple(rows[1:])] #Creates a new keys and adds the value\n" }, { "answer_id": 74587985, "author": "Ulisse Rubizzo", "author_id": 4412510, "author_profile": "https://Stackoverflow.com/users/4412510", "pm_score": 1, "selected": false, "text": "for row in vaccine_data_reader:\n try:\n mydict[row[0]].append(tuple(row[1:]))\n except KeyError:\n mydict[row[0]] = [tuple(row[1:])]\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20504351/" ]
74,587,836
<p>I'm not sure why its not returning the minimum difference that can be found in the binary search tree. I cant debug nor use tester which has made it more difficult to find the issue.</p> <pre><code>Instrcutions: </code></pre> <p>Implement a method called getMinimumDifference() that takes in as parameter the root of a Binary Search Tree and returns an integer denoting the minimum absolute difference of any two distinct nodes within the Binary Search Tree.</p> <p>Assumptions:</p> <p>The node values in the binary search tree are greater than or equal to zero. All node values in the binary search tree are unique. The method will never receive the root of a tree that less than 2 nodes.</p> <pre><code>tree: [4,2,6,1,3] 4 2____||____6 1___||___3 expected output: 1 </code></pre> <pre><code>public static int getMinimumDifference(BTNode&lt;Integer, Integer&gt; root) { int minHolder = 9; BTNode&lt;Integer, Integer&gt; newNode = null; recgmd(minHolder, root, newNode); return minHolder; } public static void recgmd(int minHolder,BTNode&lt;Integer, Integer&gt; currentNode, BTNode&lt;Integer, Integer&gt; prevNode) { if(currentNode == null) { return; } recgmd(minHolder, currentNode.getLeftChild(), prevNode); if(prevNode != null){ if(currentNode.getValue() - prevNode.getValue() &lt;= minHolder) { minHolder = currentNode.getValue() - prevNode.getValue(); } } prevNode = currentNode; recgmd(minHolder, currentNode.getRightChild(), prevNode); } </code></pre> <pre><code>Description of how my code works: Order: in-order Why? To be able to compare between the previous node and the current one since they will be ascending order &gt;getMinimumDifference&lt; &lt;Parameter&gt;[root] -[minHolder] Created variable that will be returned with the minimum difference found in BST. -[newNode] Created node(will function as a prevNode) that will be compared with the current node on the helper method. -Calls the helper, passing as parameters:[minHolder], [currentNode] and [prevNode]. &gt;recgmd&lt; &lt;Parameter&gt;[minHolder] Variable that will be returned with the minimum difference found in BST. &lt;Parameter&gt;[currentNode] Self-explanatory. &lt;Parameter&gt;[prevNode] Self-explanatory. -if the [currentNode] is null, returns -recursive call to left child -if its the first round(where [prevNode] is still null, skips) --Otherwise, we check if the difference between the value of the [currentNode](which will always be greater than the later) and the [prevNode] is less than the value contained in [minHolder] ---if it is, the difference is saved in [minHolder] ----Otherwise, it continues -[prevNode] is updated -recursive call to left child </code></pre>
[ { "answer_id": 74587933, "author": "Sam", "author_id": 16660603, "author_profile": "https://Stackoverflow.com/users/16660603", "pm_score": 0, "selected": false, "text": "Dictionary Comprehension dictionary for rows in vaccine_data_reader:\n if rows[0] in mydict.keys(): #Checks if the keys already exists\n mydict[rows[0]].append(tuple(rows[1:])) #Appends the value of duplicate\n continue\n mydict[rows[0]] = [tuple(rows[1:])] #Creates a new keys and adds the value\n" }, { "answer_id": 74587985, "author": "Ulisse Rubizzo", "author_id": 4412510, "author_profile": "https://Stackoverflow.com/users/4412510", "pm_score": 1, "selected": false, "text": "for row in vaccine_data_reader:\n try:\n mydict[row[0]].append(tuple(row[1:]))\n except KeyError:\n mydict[row[0]] = [tuple(row[1:])]\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20609023/" ]
74,587,875
<p>I am trying to apply a number of in place updates to a 2D matrix.</p> <p>It appears that using <code>jit</code> to the in place update does not have any effect in computation time (which is many orders of magnitude longer than the equivalent <code>numpy</code> implementation).</p> <p>Here is code that demonstrates my problem and research.</p> <pre><code>node_count = 10000 # NUMPY IMPLEMENTATION b = onp.zeros([node_count,node_count]) print(&quot;`numpy` in place update.&quot;) %timeit b[1,1] = 1. # 86.9 ns ± 1.42 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each) # JAX IN PLACE IMPLEMENTATION a = np.zeros([node_count,node_count]) print(&quot;`jax.np` in place update.&quot;) %timeit a.at[1,1].set(1.) # 112 ms ± 14.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) ## TEST JIT IMPLEMENTATION def update(mat, index, val): return mat.at[tuple(index)].set(val) update_jit = jit(update) # Run once for trace. update_jit(a, [1,1], 1.).block_until_ready() print(&quot;`jax.np` jit in place update.&quot;) %timeit update_jit(a, [1,1],1.).block_until_ready() # 99.6 ms ± 358 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) </code></pre>
[ { "answer_id": 74589535, "author": "Jérôme Richard", "author_id": 12939557, "author_profile": "https://Stackoverflow.com/users/12939557", "pm_score": -1, "selected": false, "text": "a set b.fill(42.0) b.copy()" }, { "answer_id": 74590089, "author": "jakevdp", "author_id": 2937831, "author_profile": "https://Stackoverflow.com/users/2937831", "pm_score": 2, "selected": true, "text": "update_jit = jit(update, donate_argnums=[0])\n %timeit %time # Following is run on a Colab T4 GPU runtime\n\nupdate_jit = jit(update)\n_ = update_jit(b, [1,1], 1.)\n%time _ = update_jit(b, [1,1], 1.).block_until_ready()\n# CPU times: user 607 µs, sys: 112 µs, total: 719 µs\n# Wall time: 5.89 ms\n\nupdate_jit_donate = jit(update, donate_argnums=[0])\nb = update_jit_donate(b, [1,1], 1.)\n%time _ = update_jit_donate(b, [1,1], 1.).block_until_ready()\n# CPU times: user 467 µs, sys: 86 µs, total: 553 µs\n# Wall time: 332 µs\n @jit\ndef sum(x):\n return x.sum()\n\n@jit\ndef update_and_sum(x):\n return x.at[0, 0].set(1).sum()\n\n_ = sum(b)\n%timeit sum(b).block_until_ready()\n# 1.66 ms ± 7.55 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n\n_ = update_and_sum(b)\n%timeit update_and_sum(b).block_until_ready()\n# 1.66 ms ± 20.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2426955/" ]
74,587,888
<p>Good day! First of all, sorry as this is a long (and maybe stupid) question from a new (and noob) programer.</p> <p>I am trying to do a program that multiply 2 matrices, and I wanted to use functions to do it. So far so good, I have learned how to pass 2D arrays to function using pointer. However, when I try to multiply the value of the respective row with that of the column of the 2nd matrix, I keep getting the different result from what I have calculated by myself. Here's the function:</p> <p>This one is to input value for matrices, please pay attention to the &quot;cin&quot; line.</p> <pre><code>void nhapMT (int *A, int m, int n) { for (int i = 0; i &lt; m; i++){ for (int j = 0; j &lt; n; j++){ cout &lt;&lt; &quot;\nNhap phan tu dong &quot; &lt;&lt; 1 + i &lt;&lt; &quot; cot &quot; &lt;&lt; 1 + j &lt;&lt; &quot;: &quot;; //Just inputing value of row i and column j for matrices cin &gt;&gt; *(A+i*n+j); } } } </code></pre> <p>And this one is to multiply the value of the respective row with that of the column the 2nd matrix</p> <pre><code>void MP (int *A, int *B, int *Tich, int Phu[], int m, int n, int p, int q) { //m and n is the size of row and column of matrix A; n and p is that of B and Tich is the product matrix of them int a, b, c, d; //I use a, b, c as the counter to m, n and p; d is the counter to q a = b = c = 0; q = m*n*p; Phu[q]; //q = the number of element of the resulting matrix, this array is for me to check if the result of multiplying 1 by 1 was correct before adding them to use for the result matrix for (d = 0; d &lt; q; d++) { Phu[d] = *(A+a*n+b) * *(B+b*p+c); b++; if (b == n - 1) { c++; }if (b == n - 1 &amp;&amp; c == p - 1) { a++; }if (b == n - 1 &amp;&amp; a == m - 1 &amp;&amp; c == p - 1){ break; } } for (int i = 0; i &lt; q; i++) { cout &lt;&lt; Phu[i] &lt;&lt; endl; // just checking the result } } </code></pre> <p>ummmm.... apparently I wrote the multiply function last night and delete it for the new code today so umm.... I forgot how I wrote it. This one is just the replica (the result of this version is just pure wrong), but I swear it was kinda like that. Anyhoo, the point here is: when I cout the &quot;Phu&quot; array last night, the result was decent and &quot;looks legit&quot; number. It just wasn't the correct answer. For example, the answer was: {2, 2, 3, 4, 6, 1, 9, 2}. But the cout-ed version of it was like {2, 2, 6, 9, 2, 3, 4, 1} (kinda, sry I'm stupid). I noticed they were the elements of the correct result, they were just in wrong order. I tried changing it from <code>*(A+a*n+b)</code> to <code>*((A+a)+b)</code> but the result is still the same.</p> <p>Fast forward to today, I tried to find the root of the problem, by not cout-ing the result, but the operand <code>*((A+a)+b)</code> (by incrementing a and b), and would you look at that! The result was NOT in order! Okay, I have already known a bit about the concept of &quot;multidimensional array actually is multiplie 1D arrays&quot;. I'm using two (2x2) matrices to test out this, so A = {(1,2),(3,1)} and B = {(2,3),(1,2)}. In my assumption, <code>*((A+0)+0)</code> is 1 (which is correct) and <code>*((A+1)+0)</code> should be 3. (which is not, in fact, it's &quot;2&quot; a.k.a <code>*((A+0)+1)</code> ). That made me check the rest to see if it was the same as the 3rd element (or the first element of the second 1D array). I found out that <code>*((A+0)+2)</code> is just the same as <code>*((A+2)+0)</code> <a href="https://i.stack.imgur.com/ghX1c.png" rel="nofollow noreferrer">Instead of this.</a> (I mean, <code>*((A+2)+0)</code> should have printed some gibberish or printed nothing, right?), it's like two 1D arrays is merged into one <a href="https://i.stack.imgur.com/AtzqH.png" rel="nofollow noreferrer">like this</a> (and I think it's the case here).</p> <p>Enough with the context, I'm sure at this point 99% people have left, if you're still reading, thank you. Now the question:</p> <ol> <li><p>In the &quot;NhapMT&quot; function, if I change <code>*(A+i*n+j);</code> to <code>*((A+i)+j);</code> the value of the elements inside the matrix came out different from what I have input, what's the reason between that and can someone explain the multiplying with &quot;n&quot; part in <code>*(A+i*n+j);</code> to me as I still don't get it.</p> </li> <li><p>What's the reason behind two 1D arrays being merged into one big 1D array in the &quot;MP&quot; function? Is it because I'm using the pointer directly instead of giving the pointer a name?</p> </li> </ol> <p>Again, thank you for reading that mess of the code and even if you're not going to answer this, I hope you have a nice day.</p>
[ { "answer_id": 74589535, "author": "Jérôme Richard", "author_id": 12939557, "author_profile": "https://Stackoverflow.com/users/12939557", "pm_score": -1, "selected": false, "text": "a set b.fill(42.0) b.copy()" }, { "answer_id": 74590089, "author": "jakevdp", "author_id": 2937831, "author_profile": "https://Stackoverflow.com/users/2937831", "pm_score": 2, "selected": true, "text": "update_jit = jit(update, donate_argnums=[0])\n %timeit %time # Following is run on a Colab T4 GPU runtime\n\nupdate_jit = jit(update)\n_ = update_jit(b, [1,1], 1.)\n%time _ = update_jit(b, [1,1], 1.).block_until_ready()\n# CPU times: user 607 µs, sys: 112 µs, total: 719 µs\n# Wall time: 5.89 ms\n\nupdate_jit_donate = jit(update, donate_argnums=[0])\nb = update_jit_donate(b, [1,1], 1.)\n%time _ = update_jit_donate(b, [1,1], 1.).block_until_ready()\n# CPU times: user 467 µs, sys: 86 µs, total: 553 µs\n# Wall time: 332 µs\n @jit\ndef sum(x):\n return x.sum()\n\n@jit\ndef update_and_sum(x):\n return x.at[0, 0].set(1).sum()\n\n_ = sum(b)\n%timeit sum(b).block_until_ready()\n# 1.66 ms ± 7.55 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n\n_ = update_and_sum(b)\n%timeit update_and_sum(b).block_until_ready()\n# 1.66 ms ± 20.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20278503/" ]
74,587,943
<p>I'm looking a way to extract every second (2nd) I-Frame using ffmpeg and save them as a new timelapse video.</p> <p>So far I managed to save all I-frames by the following command:</p> <p>ffmpeg -i $FILE -vf &quot;select='eq(pict_type,I)',setpts=N/FRAME_RATE/TB&quot; -r 29.97 -vcodec libx264 -b:v 62M -an ./enc/${FILE}_cnv.mp4</p> <p>but I need twice less I-frames in the resulting video. For example, if the I-frames in the original video are 1-8-16-24-32-40..., I need only 1-16-32-48... Is there a way to extract them without making a temporary video with all keyframes?</p> <p>Update: since no universal solution was found, I decided to cheat with: -vf &quot;select='eq(pict_type,I)*not(mod(n,16))',setpts=N/FRAME_RATE/TB&quot;</p>
[ { "answer_id": 74589535, "author": "Jérôme Richard", "author_id": 12939557, "author_profile": "https://Stackoverflow.com/users/12939557", "pm_score": -1, "selected": false, "text": "a set b.fill(42.0) b.copy()" }, { "answer_id": 74590089, "author": "jakevdp", "author_id": 2937831, "author_profile": "https://Stackoverflow.com/users/2937831", "pm_score": 2, "selected": true, "text": "update_jit = jit(update, donate_argnums=[0])\n %timeit %time # Following is run on a Colab T4 GPU runtime\n\nupdate_jit = jit(update)\n_ = update_jit(b, [1,1], 1.)\n%time _ = update_jit(b, [1,1], 1.).block_until_ready()\n# CPU times: user 607 µs, sys: 112 µs, total: 719 µs\n# Wall time: 5.89 ms\n\nupdate_jit_donate = jit(update, donate_argnums=[0])\nb = update_jit_donate(b, [1,1], 1.)\n%time _ = update_jit_donate(b, [1,1], 1.).block_until_ready()\n# CPU times: user 467 µs, sys: 86 µs, total: 553 µs\n# Wall time: 332 µs\n @jit\ndef sum(x):\n return x.sum()\n\n@jit\ndef update_and_sum(x):\n return x.at[0, 0].set(1).sum()\n\n_ = sum(b)\n%timeit sum(b).block_until_ready()\n# 1.66 ms ± 7.55 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n\n_ = update_and_sum(b)\n%timeit update_and_sum(b).block_until_ready()\n# 1.66 ms ± 20.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20611928/" ]
74,587,949
<p>I'm currently writing a module for Linux, and I want to pass a queue of data from kernel to user space (my program in user responsible to read this data - and then responsible write those to a file), and my approach is to get a memory location in user space and push data from kernel to it.</p> <p>How can I implement it?</p> <p>Do you have a better approach? I'm Beginner, and any guides can be nice.</p> <p>Before that, I try to push this data to user space with IOCTL and PROCFS but that approach is not a good idea and I lost some data.</p>
[ { "answer_id": 74589535, "author": "Jérôme Richard", "author_id": 12939557, "author_profile": "https://Stackoverflow.com/users/12939557", "pm_score": -1, "selected": false, "text": "a set b.fill(42.0) b.copy()" }, { "answer_id": 74590089, "author": "jakevdp", "author_id": 2937831, "author_profile": "https://Stackoverflow.com/users/2937831", "pm_score": 2, "selected": true, "text": "update_jit = jit(update, donate_argnums=[0])\n %timeit %time # Following is run on a Colab T4 GPU runtime\n\nupdate_jit = jit(update)\n_ = update_jit(b, [1,1], 1.)\n%time _ = update_jit(b, [1,1], 1.).block_until_ready()\n# CPU times: user 607 µs, sys: 112 µs, total: 719 µs\n# Wall time: 5.89 ms\n\nupdate_jit_donate = jit(update, donate_argnums=[0])\nb = update_jit_donate(b, [1,1], 1.)\n%time _ = update_jit_donate(b, [1,1], 1.).block_until_ready()\n# CPU times: user 467 µs, sys: 86 µs, total: 553 µs\n# Wall time: 332 µs\n @jit\ndef sum(x):\n return x.sum()\n\n@jit\ndef update_and_sum(x):\n return x.at[0, 0].set(1).sum()\n\n_ = sum(b)\n%timeit sum(b).block_until_ready()\n# 1.66 ms ± 7.55 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n\n_ = update_and_sum(b)\n%timeit update_and_sum(b).block_until_ready()\n# 1.66 ms ± 20.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20448829/" ]
74,587,962
<p>I try to use import(xxx) in vite to replace require(xxx), but import(xxx) will return a promise(async), how can I write like require(xxx) in vite?</p> <pre class="lang-js prettyprint-override"><code>let lang = require(`./${path}.json`) </code></pre> <p><a href="https://i.stack.imgur.com/T96sN.png" rel="nofollow noreferrer">Code Image</a></p> <p>I try to change it to import(`./${path}.json`) but it will return a Promise, so that I can't get the index with file.</p>
[ { "answer_id": 74589535, "author": "Jérôme Richard", "author_id": 12939557, "author_profile": "https://Stackoverflow.com/users/12939557", "pm_score": -1, "selected": false, "text": "a set b.fill(42.0) b.copy()" }, { "answer_id": 74590089, "author": "jakevdp", "author_id": 2937831, "author_profile": "https://Stackoverflow.com/users/2937831", "pm_score": 2, "selected": true, "text": "update_jit = jit(update, donate_argnums=[0])\n %timeit %time # Following is run on a Colab T4 GPU runtime\n\nupdate_jit = jit(update)\n_ = update_jit(b, [1,1], 1.)\n%time _ = update_jit(b, [1,1], 1.).block_until_ready()\n# CPU times: user 607 µs, sys: 112 µs, total: 719 µs\n# Wall time: 5.89 ms\n\nupdate_jit_donate = jit(update, donate_argnums=[0])\nb = update_jit_donate(b, [1,1], 1.)\n%time _ = update_jit_donate(b, [1,1], 1.).block_until_ready()\n# CPU times: user 467 µs, sys: 86 µs, total: 553 µs\n# Wall time: 332 µs\n @jit\ndef sum(x):\n return x.sum()\n\n@jit\ndef update_and_sum(x):\n return x.at[0, 0].set(1).sum()\n\n_ = sum(b)\n%timeit sum(b).block_until_ready()\n# 1.66 ms ± 7.55 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n\n_ = update_and_sum(b)\n%timeit update_and_sum(b).block_until_ready()\n# 1.66 ms ± 20.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20611990/" ]
74,587,966
<h1>Routes and Controller problem on Codeigniter 4, can't access</h1> <p>I created Controller and Routes, and I created a Navbar.php file in Controller with methods and GET in Routes, then can not be accessed with localhost CI. I need a solution because I'm just learning CI4, thank you.</p> <p>This is the code.</p> <p>Routes setting</p> <pre><code>// We get a performance increase by specifying the default // route since we don't have to scan directories. $routes-&gt;get('/', 'Home::index'); $routes-&gt;get('/about', 'Navbar::about'); $routes-&gt;get('/contact', 'Navbar::contact'); $routes-&gt;get('/faqs', 'Navbar::faqs'); </code></pre> <p>Navbar.php</p> <pre><code>&lt;?php namespace App\Controllers; class Page extends BaseController { public function about() { echo &quot;about page&quot;; } public function contact() { echo &quot;contact page&quot;; } public function faqs() { echo &quot;faqs page&quot;; } } </code></pre> <p>I want to know where's error, need to problem solving with help.</p>
[ { "answer_id": 74589535, "author": "Jérôme Richard", "author_id": 12939557, "author_profile": "https://Stackoverflow.com/users/12939557", "pm_score": -1, "selected": false, "text": "a set b.fill(42.0) b.copy()" }, { "answer_id": 74590089, "author": "jakevdp", "author_id": 2937831, "author_profile": "https://Stackoverflow.com/users/2937831", "pm_score": 2, "selected": true, "text": "update_jit = jit(update, donate_argnums=[0])\n %timeit %time # Following is run on a Colab T4 GPU runtime\n\nupdate_jit = jit(update)\n_ = update_jit(b, [1,1], 1.)\n%time _ = update_jit(b, [1,1], 1.).block_until_ready()\n# CPU times: user 607 µs, sys: 112 µs, total: 719 µs\n# Wall time: 5.89 ms\n\nupdate_jit_donate = jit(update, donate_argnums=[0])\nb = update_jit_donate(b, [1,1], 1.)\n%time _ = update_jit_donate(b, [1,1], 1.).block_until_ready()\n# CPU times: user 467 µs, sys: 86 µs, total: 553 µs\n# Wall time: 332 µs\n @jit\ndef sum(x):\n return x.sum()\n\n@jit\ndef update_and_sum(x):\n return x.at[0, 0].set(1).sum()\n\n_ = sum(b)\n%timeit sum(b).block_until_ready()\n# 1.66 ms ± 7.55 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n\n_ = update_and_sum(b)\n%timeit update_and_sum(b).block_until_ready()\n# 1.66 ms ± 20.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74587966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20611955/" ]
74,588,016
<p>I'd like to send in a list of <code>dependencies</code> as part of creating a <code>DAGNode</code>: what is the supported way to achieve a similar behavior in python - given it seems this exact syntax were not supported?</p> <pre><code>from typing import TypeVar, Generic T = TypeVar('T') class DAGNode(Generic[T]): # Apparently the `DAGNode` type does not exist yet so this fails def __init__(self, id: T, dependencies: set[DAGNode[T]]): self.id = id self.dependencies = dependencies </code></pre>
[ { "answer_id": 74588051, "author": "Ulisse Rubizzo", "author_id": 4412510, "author_profile": "https://Stackoverflow.com/users/4412510", "pm_score": 3, "selected": true, "text": "from typing import TypeVar, Generic, Set\n\nT = TypeVar('T')\nclass DAGNode(Generic[T]):\n\n # Apparently the DAGNode type does not exist yet so this fails\n def __init__(self, type_id: T, dependencies: Set['DAGNode[T]']): \n self.id = type_id\n self.dependencies = dependencies\n type_id id" }, { "answer_id": 74588114, "author": "Michael Butscher", "author_id": 987358, "author_profile": "https://Stackoverflow.com/users/987358", "pm_score": 1, "selected": false, "text": "from __future__ import annotations\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1056563/" ]
74,588,033
<p>I have a python script that scrapes data from a job website. I want to save these scraped data to MySQL database but after writing the code, it connects to the database. Now after connecting, it doesn't create table and as result couldn't insert those data into the table. Please i need my code to store these scraped data to a table in the MYSQL database.</p> <p>Here's my code</p> <pre><code>import requests from bs4 import BeautifulSoup import mysql.connector for x in range(1, 210): html_text = requests.get(f'https://www.timesjobs.com/candidate/job-search.html? from=submit&amp;actualTxtKeywords=Python&amp;searchBy=0&amp;rdoOperator=OR&amp;searchType=personalizedSearch&amp;luceneResultSize=25&amp;postWeek=60&amp;txtKeywords=Python&amp;pDate=I&amp;sequence={x}&amp;startPage=1').text soup = BeautifulSoup(html_text, 'lxml') jobs = soup.find_all('li', class_ = 'clearfix job-bx wht-shd-bx') job_list = [] for job in jobs: company_name = job.find('h3', class_ = 'joblist-comp-name').text.strip().replace(' ','') keyskill = job.find('span', class_ = 'srp-skills').text.strip().replace(' ','') all_detail = {company_name, keyskill} job_list.append(all_detail) db = mysql.connector.connect(host= 'localhost', user= 'root', password= 'Maxesafrica2') cursor = db.cursor() cursor.execute(&quot;CREATE DATABASE first_db&quot;) print(&quot;Connection to MYSQL Established!&quot;) db = mysql.connector.connect(host= 'localhost', user= 'root', password= 'Maxesafrica2', database = 'first_db' ) print(&quot;Connected to Database!&quot;) cursor = db.cursor() mysql_create_table_query = &quot;&quot;&quot;CREATE TABLE first_tbl (Company Name Varchar(300) NOT NULL, Keyskill Varchar(400) NOT NULL)&quot;&quot;&quot; result = cursor.execute(mysql_create_table_query) insert_query = &quot;&quot;&quot;INSERT INTO first_tbl (Company Name, Keyskill) VALUES (%s, %s)&quot;&quot;&quot; records_to_insert = job_list cursor = db.cursor() cursor.executemany(mysql_create_table_query, records_to_insert) db.commit() cursor.close() db.close() print('Done!') </code></pre> <p>Here's the error I get</p> <pre><code>Connection to MYSQL Established! Connected to Database! Traceback (most recent call last): File &quot;C:\Users\LP\AppData\Local\Programs\Python\Python310\lib\site-packages\mysql\connector\connection_cext.py&quot;, line 565, in cmd_query self._cmysql.query(mysql_connector.MySQLInterfaceError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Name Varchar(300) NOT NULL, ' at line 1 </code></pre>
[ { "answer_id": 74588058, "author": "Tickloop", "author_id": 12853714, "author_profile": "https://Stackoverflow.com/users/12853714", "pm_score": 2, "selected": true, "text": "CREATE TABLE first_tbl \n(\n Company_Name Varchar(300) NOT NULL,\n Keyskill Varchar(400) NOT NULL\n)\n\nINSERT INTO first_tbl \n (Company_Name, Keyskill)\nVALUES (%s, %s)\n\n" }, { "answer_id": 74588075, "author": "Ulisse Rubizzo", "author_id": 4412510, "author_profile": "https://Stackoverflow.com/users/4412510", "pm_score": 0, "selected": false, "text": "mysql_create_table_query = \"\"\"CREATE TABLE first_tbl (Company_Name Varchar(300) NOT NULL,\nKeyskill Varchar(400) NOT NULL)\"\"\"\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20188713/" ]
74,588,050
<p><strong>This is My Code</strong>.</p> <pre><code>Future&lt;void&gt; SendOrderDetails() async{ Row( children: [ FutureBuilder( future: topcart.getData(), builder: (context, AsyncSnapshot&lt;List&lt;Cart&gt;&gt; snapshot) { for(int i = 0; i&lt;itemcount; i++) { if(itemcount&gt;listModel2.data!.length) { listModel2.data?.add(Model2( ORDER_INFO_ID: 1, PRODUCT_ED_ID: 2, QTY: quantitycalcule.toString(), UNIT_PRICE:'00',// snapshot.data![i].Book_initional_price!.toString(), CHGED_BY:1, CHGED_DATE: DateTime.now().toString(), STATUS: 'P', ),); } } return const Text(''); } ), ], ); } </code></pre> <p><strong>When I Call This, &quot;FutureBuilder&quot; did not run. I need &quot;snapshot&quot; in If condition. Please Help me.</strong></p>
[ { "answer_id": 74589048, "author": "baek", "author_id": 1049200, "author_profile": "https://Stackoverflow.com/users/1049200", "pm_score": 1, "selected": false, "text": "// This needs to be outside the build method, maybe initState()\nFuture<TYPE> _gd = topcart.get() \n\n// Future Builder in the build method\nFutureBuilder<String>(\n future: _gd, \n builder: (BuildContext context, AsyncSnapshot<TYPE> snapshot) {});\n if (snapshot.connectionState == ConnectionState.waiting) {\n return // Progress indicator widget\n } else if (snapshot.connectionState == ConnectionState.done) {\n if (snapshot.hasError) {\n return // Error Widget or Text \n } else if (snapshot.hasData) {\n return // Process data here\n } else {\n return // Empty set returned\n }\n } else {\n return Text('State: ${snapshot.connectionState}');\n }\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4501300/" ]
74,588,055
<p>I have this dataset in R:</p> <pre><code>set.seed(123) myFun &lt;- function(n = 5000) { a &lt;- do.call(paste0, replicate(5, sample(LETTERS, n, TRUE), FALSE)) paste0(a, sprintf(&quot;%04d&quot;, sample(9999, n, TRUE)), sample(LETTERS, n, TRUE)) } col1 = myFun(100) col2 = myFun(100) col3 = myFun(100) col4 = myFun(100) group &lt;- c(&quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;D&quot;) group = sample(group, 100, replace=TRUE) example = data.frame(col1, col2, col3, col4, group) col1 col2 col3 col4 group 1 SKZDZ9876D BTAMF8110T LIBFV6882H ZFIPL4295E A 2 NXJRX7189Y AIZGY5809C HSMIH4556D YJGJP8022H C 3 XPTZB2035P EEKXK0873A PCPNW1021S NMROS4134O A 4 LJMCM3436S KGADK2847O SRMUI5723N RDIXI7301N B 5 ADITC6567L HUOCT5660P AQCNE3753K FUMGY1428B D 6 BAEDP8491P IAGQG4816B TXXQH6337M SDACH5752D C </code></pre> <p>I am now trying to run the following double loop:</p> <pre><code>library(stringdist) method = c(&quot;osa&quot;, &quot;lv&quot;, &quot;dl&quot;, &quot;hamming&quot;, &quot;lcs&quot;, &quot;qgram&quot;, &quot;cosine&quot;, &quot;jaccard&quot;, &quot;jw&quot;,&quot;soundex&quot;) results = list() l = length(unique(example$group)) for (j in 1:l) { for (i in 1:length(method)) { g = unique(example$group) groups_j = g[j] my_data_i = example[which(example$group == groups_j ), ] method_i = method[i] name_1_i = paste0(&quot;col1_col_2&quot;, method_i) name_2_i = paste0(&quot;col3_col_4&quot;, method_i) p1_i = stringdistmatrix(my_data_i$col1, my_data_i$col2, method = method_i, useNames = &quot;string&quot;) %&gt;% as_tibble(rownames = &quot;a&quot;) %&gt;% pivot_longer(-1, names_to = &quot;b&quot;, values_to = name_1_i) p2_i = stringdistmatrix(my_data_i$col3, my_data_i$col4, method = method_i, useNames = &quot;string&quot;) %&gt;% as_tibble(rownames = &quot;a&quot;) %&gt;% pivot_longer(-1, names_to = &quot;b&quot;, values_to = name_2_i) p1_i = p1_i[,3] p2_i = p2_i[,3] final_i = cbind(p1_i, p2_i, groups_j) results[[i]] = final_i } } final = do.call(cbind.data.frame, results) </code></pre> <p>The loop seems to run - <strong>but when I inspect the final results, I noticed that the other indices in the &quot;j&quot; loop seem to have been ignored:</strong></p> <pre><code>&gt; table(final$groups_j) A 441 </code></pre> <p>As we can see the original data, there appears to be 4 groups:</p> <pre><code>&gt; table(example$group) A B C D 21 28 19 32 </code></pre> <p><strong>Can someone please help me figure out why the other 3 groups are not being processed by my loop?</strong></p> <p>Thank you!</p>
[ { "answer_id": 74589048, "author": "baek", "author_id": 1049200, "author_profile": "https://Stackoverflow.com/users/1049200", "pm_score": 1, "selected": false, "text": "// This needs to be outside the build method, maybe initState()\nFuture<TYPE> _gd = topcart.get() \n\n// Future Builder in the build method\nFutureBuilder<String>(\n future: _gd, \n builder: (BuildContext context, AsyncSnapshot<TYPE> snapshot) {});\n if (snapshot.connectionState == ConnectionState.waiting) {\n return // Progress indicator widget\n } else if (snapshot.connectionState == ConnectionState.done) {\n if (snapshot.hasError) {\n return // Error Widget or Text \n } else if (snapshot.hasData) {\n return // Process data here\n } else {\n return // Empty set returned\n }\n } else {\n return Text('State: ${snapshot.connectionState}');\n }\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13203841/" ]
74,588,063
<p>Background: I use glog to register signal handler, but it cannot kill the init process (PID=1) with <code>kill</code> sigcall. That way, even though deadly signals like <code>SIGABRT</code> is raised, kubernetes controller manager won't be able to understand the pod is actually not functioning, thus kill the pod and restart a new one.</p> <p>My idea is to add logic into my readiness/liveness probe: check the content for current container, whether it's in healthy state.</p> <p>I'm trying to look into the logs on container's local filesystem <code>/var/log</code>, but haven't found anything useful.</p> <p>I'm wondering if it's possible to issue a HTTP request to somewhere, to get the complete log? I assume it's stored somewhere.</p>
[ { "answer_id": 74589048, "author": "baek", "author_id": 1049200, "author_profile": "https://Stackoverflow.com/users/1049200", "pm_score": 1, "selected": false, "text": "// This needs to be outside the build method, maybe initState()\nFuture<TYPE> _gd = topcart.get() \n\n// Future Builder in the build method\nFutureBuilder<String>(\n future: _gd, \n builder: (BuildContext context, AsyncSnapshot<TYPE> snapshot) {});\n if (snapshot.connectionState == ConnectionState.waiting) {\n return // Progress indicator widget\n } else if (snapshot.connectionState == ConnectionState.done) {\n if (snapshot.hasError) {\n return // Error Widget or Text \n } else if (snapshot.hasData) {\n return // Process data here\n } else {\n return // Empty set returned\n }\n } else {\n return Text('State: ${snapshot.connectionState}');\n }\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8501483/" ]
74,588,076
<h4>Class definition</h4> <pre class="lang-py prettyprint-override"><code>class Car: amount_cars = 0 def __init__(self, manufacturer, model, hp): self.manufacturer = manufacturer self.model = model self.hp = hp Car.amount_cars += 1 def print_car_amount(self): print(&quot;Amount: {}&quot;.format(Car.amount_cars)) </code></pre> <h4>Creating instance</h4> <pre class="lang-py prettyprint-override"><code>myCar1 = Car(&quot;Tesla&quot;, &quot;Model X&quot;, 525) </code></pre> <h4>Printing instance</h4> <pre class="lang-py prettyprint-override"><code>myCar1.print_info() </code></pre> <p>Output:</p> <pre><code>--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Input In [37], in &lt;cell line: 1&gt;() ----&gt; 1 myCar1.print_info() AttributeError: 'Car' object has no attribute 'print_info </code></pre> <p>Need help in finding the error</p>
[ { "answer_id": 74588092, "author": "Ni3dzwi3dz", "author_id": 12768056, "author_profile": "https://Stackoverflow.com/users/12768056", "pm_score": 3, "selected": true, "text": "print_info myCar1.print_car_amount()\n" }, { "answer_id": 74588342, "author": "su yong kim", "author_id": 20612454, "author_profile": "https://Stackoverflow.com/users/20612454", "pm_score": -1, "selected": false, "text": "class Car:\n\namount_cars = 0\n\ndef __init__(self, manufacturer, model, hp):\n self.manufacturer = manufacturer\n self.model = model\n self.hp = hp\n Car.amount_cars += 1\n\ndef print_info(self): # Changed\n print(\"Amount: {}\".format(Car.amount_cars))\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18450149/" ]
74,588,096
<p>I want to run a macro which will take a screenshot of webpage (one of the multiple tabs in the browser )open in another window and save the screenshot as png file to a folder (path and filename specified in a cell in excel sheet).</p> <p>I searched for the same on google and got the code to change the active window and take the screenshot. But the below code will paste the screenshot in the active sheet. Instead I want to save it as a png or jpg file to a specific folder with a specific file name as given in excel sheet from where the program is triggered. So everytime the screenshot is triggered it will have a different file name picked from the active excel cell with some constant prefix.</p> <pre><code>Option explicit Private Declare Sub keybd_event Lib &quot;user32&quot; (ByVal bVk As Byte, ByVal _ bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long) Private Const VK_SNAPSHOT = &amp;H2C Sub PrintScreen() appactivate(&quot;Microsoft Word&quot;,wait) keybd_event VK_SNAPSHOT, 1, 0, 0 ActiveSheet.Paste end sub </code></pre>
[ { "answer_id": 74590023, "author": "יעקב טורק", "author_id": 17839542, "author_profile": "https://Stackoverflow.com/users/17839542", "pm_score": 0, "selected": false, "text": "'***********************************************************************************************\n' * Please leave any Trademarks or Credits in place.\n' *\n' * ACKNOWLEDGEMENT TO CONTRIBUTORS :\n' * STEPHEN BULLEN, 15 November 1998 - Original PastPicture code\n' * G HUDSON, 5 April 2010 - Pause Function\n' * LUTZ GENTKOW, 23 July 2011 - Alt + PrtScrn\n' * PAUL FRANCIS, 11 April 2013 - Putting all pieces together, bridging the 32 bit and 64 bit version.\n' * CHRIS O, 12 April 2013 - Code suggestion to work on older versions of Access.\n' *\n' * DESCRIPTION: Creates a standard Picture object from whatever is on the clipboard.\n' * This object is then saved to a location on the disc. Please note, this\n' * can also be assigned to (for example) and Image control on a userform.\n' *\n' * The code requires a reference to the \"OLE Automation\" type library.\n' *\n' * The code in this module has been derived from a number of sources\n' * discovered on MSDN, Access World Forum, VBForums.\n' *\n' * To use it, just copy this module into your project, then you can use:\n' * SaveClip2Bit(\"C:\\Pics\\Sample.bmp\")\n' * to save this to a location on the Disc.\n' * (Or)\n' * Set ImageControl.Image = PastePicture\n' * to paste a picture of whatever is on the clipboard into a standard image control.\n' *\n' * PROCEDURES:\n' * PastePicture : The entry point for 'Setting' the Image\n' * CreatePicture : Private function to convert a bitmap or metafile handle to an OLE reference\n' * fnOLEError : Get the error text for an OLE error code\n' * SaveClip2Bit : The entry point for 'Saving' the Image, calls for PastePicture\n' * AltPrintScreen: Performs the automation of Alt + PrtScrn, for getting the Active Window.\n' * Pause : Makes the program wait, to make sure proper screen capture takes place.\n'**************************************************************************************************\n \nOption Explicit\nOption Compare Text\n \n'Declare a UDT to store a GUID for the IPicture OLE Interface\nPrivate Type GUID\n Data1 As Long\n Data2 As Integer\n Data3 As Integer\n Data4(0 To 7) As Byte\nEnd Type\n \n'Declare a UDT to store the bitmap information\nPrivate Type uPicDesc\n Size As Long\n Type As Long\n hPic As Long\n hPal As Long\nEnd Type\n \n'Windows API Function Declarations\n#If Win64 = 1 And VBA7 = 1 Then\n \n 'Does the clipboard contain a bitmap/metafile?\n Private Declare PtrSafe Function IsClipboardFormatAvailable Lib \"user32\" (ByVal wFormat As Integer) As Long\n \n 'Open the clipboard to read\n Private Declare PtrSafe Function OpenClipboard Lib \"user32\" (ByVal hwnd As Long) As Long\n \n 'Get a pointer to the bitmap/metafile\n Private Declare PtrSafe Function GetClipboardData Lib \"user32\" (ByVal wFormat As Integer) As Long\n \n 'Close the clipboard\n Private Declare PtrSafe Function CloseClipboard Lib \"user32\" () As Long\n \n 'Convert the handle into an OLE IPicture interface.\n Private Declare PtrSafe Function OleCreatePictureIndirect Lib \"oleaut32.dll\" (PicDesc As uPicDesc, RefIID As GUID, ByVal fPictureOwnsHandle As Long, IPic As IPicture) As Long\n \n 'Create our own copy of the metafile, so it doesn't get wiped out by subsequent clipboard updates.\n Declare PtrSafe Function CopyEnhMetaFile Lib \"gdi32\" Alias \"CopyEnhMetaFileA\" (ByVal hemfSrc As Long, ByVal lpszFile As String) As Long\n \n 'Create our own copy of the bitmap, so it doesn't get wiped out by subsequent clipboard updates.\n Declare PtrSafe Function CopyImage Lib \"user32\" (ByVal handle As Long, ByVal un1 As Long, ByVal n1 As Long, ByVal n2 As Long, ByVal un2 As Long) As Long\n \n 'Uses the Keyboard simulation\n Private Declare PtrSafe Sub keybd_event Lib \"user32\" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)\n \n#Else\n \n 'Does the clipboard contain a bitmap/metafile?\n Private Declare Function IsClipboardFormatAvailable Lib \"user32\" (ByVal wFormat As Integer) As Long\n \n 'Open the clipboard to read\n Private Declare Function OpenClipboard Lib \"user32\" (ByVal hwnd As Long) As Long\n \n 'Get a pointer to the bitmap/metafile\n Private Declare Function GetClipboardData Lib \"user32\" (ByVal wFormat As Integer) As Long\n \n 'Close the clipboard\n Private Declare Function CloseClipboard Lib \"user32\" () As Long\n \n 'Convert the handle into an OLE IPicture interface.\n Private Declare Function OleCreatePictureIndirect Lib \"oleaut32.dll\" (PicDesc As uPicDesc, RefIID As GUID, ByVal fPictureOwnsHandle As Long, IPic As IPicture) As Long\n \n 'Create our own copy of the metafile, so it doesn't get wiped out by subsequent clipboard updates.\n Declare Function CopyEnhMetaFile Lib \"gdi32\" Alias \"CopyEnhMetaFileA\" (ByVal hemfSrc As Long, ByVal lpszFile As String) As Long\n \n 'Create our own copy of the bitmap, so it doesn't get wiped out by subsequent clipboard updates.\n Declare Function CopyImage Lib \"user32\" (ByVal handle As Long, ByVal un1 As Long, ByVal n1 As Long, ByVal n2 As Long, ByVal un2 As Long) As Long\n \n 'Uses the Keyboard simulation\n Private Declare Sub keybd_event Lib \"user32\" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)\n \n#End If\n \n'The API format types we're interested in\nConst CF_BITMAP = 2\nConst CF_PALETTE = 9\nConst CF_ENHMETAFILE = 14\nConst IMAGE_BITMAP = 0\nConst LR_COPYRETURNORG = &H4\n \nPrivate Const KEYEVENTF_KEYUP = &H2\nPrivate Const VK_SNAPSHOT = &H2C\nPrivate Const VK_MENU = &H12\n \n' Subroutine : AltPrintScreen\n' Purpose : Capture the Active window, and places on the Clipboard.\n \nSub AltPrintScreen()\n keybd_event VK_MENU, 0, 0, 0\n keybd_event VK_SNAPSHOT, 0, 0, 0\n keybd_event VK_SNAPSHOT, 0, KEYEVENTF_KEYUP, 0\n keybd_event VK_MENU, 0, KEYEVENTF_KEYUP, 0\nEnd Sub\n \nSub PrintScreen()\n keybd_event VK_SNAPSHOT, 1, 0, 0\nEnd Sub\n \n \n' Subroutine : PastePicture\n' Purpose : Get a Picture object showing whatever's on the clipboard.\n \nFunction PastePicture() As IPicture\n 'Some pointers\n Dim h As Long, hPtr As Long, hPal As Long, lPicType As Long, hCopy As Long\n \n 'Check if the clipboard contains the required format\n If IsClipboardFormatAvailable(CF_BITMAP) Then\n 'Get access to the clipboard\n h = OpenClipboard(0&)\n If h > 0 Then\n 'Get a handle to the image data\n hPtr = GetClipboardData(CF_BITMAP)\n \n hCopy = CopyImage(hPtr, IMAGE_BITMAP, 0, 0, LR_COPYRETURNORG)\n \n 'Release the clipboard to other programs\n h = CloseClipboard\n 'If we got a handle to the image, convert it into a Picture object and return it\n If hPtr <> 0 Then Set PastePicture = CreatePicture(hCopy, 0, CF_BITMAP)\n End If\n End If\nEnd Function\n \n \n' Subroutine : CreatePicture\n' Purpose : Converts a image (and palette) handle into a Picture object.\n' NOTE : Requires a reference to the \"OLE Automation\" type library\n \nPrivate Function CreatePicture(ByVal hPic As Long, ByVal hPal As Long, ByVal lPicType) As IPicture\n ' IPicture requires a reference to \"OLE Automation\"\n Dim r As Long, uPicInfo As uPicDesc, IID_IDispatch As GUID, IPic As IPicture\n 'OLE Picture types\n Const PICTYPE_BITMAP = 1\n Const PICTYPE_ENHMETAFILE = 4\n ' Create the Interface GUID (for the IPicture interface)\n With IID_IDispatch\n .Data1 = &H7BF80980\n .Data2 = &HBF32\n .Data3 = &H101A\n .Data4(0) = &H8B\n .Data4(1) = &HBB\n .Data4(2) = &H0\n .Data4(3) = &HAA\n .Data4(4) = &H0\n .Data4(5) = &H30\n .Data4(6) = &HC\n .Data4(7) = &HAB\n End With\n ' Fill uPicInfo with necessary parts.\n \n With uPicInfo\n .Size = Len(uPicInfo) ' Length of structure.\n .Type = PICTYPE_BITMAP ' Type of Picture\n .hPic = hPic ' Handle to image.\n .hPal = hPal ' Handle to palette (if bitmap).\n End With\n \n ' Create the Picture object.\n r = OleCreatePictureIndirect(uPicInfo, IID_IDispatch, True, IPic)\n \n ' If an error occurred, show the description\n If r <> 0 Then Debug.Print \"Create Picture: \" & fnOLEError(r)\n \n ' Return the new Picture object.\n Set CreatePicture = IPic\nEnd Function\n \n \n' Subroutine : fnOLEError\n' Purpose : Gets the message text for standard OLE errors\n \nPrivate Function fnOLEError(lErrNum As Long) As String\n 'OLECreatePictureIndirect return values\n Const E_ABORT = &H80004004\n Const E_ACCESSDENIED = &H80070005\n Const E_FAIL = &H80004005\n Const E_HANDLE = &H80070006\n Const E_INVALIDARG = &H80070057\n Const E_NOINTERFACE = &H80004002\n Const E_NOTIMPL = &H80004001\n Const E_OUTOFMEMORY = &H8007000E\n Const E_POINTER = &H80004003\n Const E_UNEXPECTED = &H8000FFFF\n Const S_OK = &H0\n \n Select Case lErrNum\n Case E_ABORT\n fnOLEError = \" Aborted\"\n Case E_ACCESSDENIED\n fnOLEError = \" Access Denied\"\n Case E_FAIL\n fnOLEError = \" General Failure\"\n Case E_HANDLE\n fnOLEError = \" Bad/Missing Handle\"\n Case E_INVALIDARG\n fnOLEError = \" Invalid Argument\"\n Case E_NOINTERFACE\n fnOLEError = \" No Interface\"\n Case E_NOTIMPL\n fnOLEError = \" Not Implemented\"\n Case E_OUTOFMEMORY\n fnOLEError = \" Out of Memory\"\n Case E_POINTER\n fnOLEError = \" Invalid Pointer\"\n Case E_UNEXPECTED\n fnOLEError = \" Unknown Error\"\n Case S_OK\n fnOLEError = \" Success!\"\n End Select\nEnd Function\n \n' Routine : SaveClip2Bit\n' Purpose : Saves Picture object to desired location.\n' Arguments : Path to save the file\n \nPublic Sub SaveClip2Bit(savePath As String)\nOn Error GoTo errHandler:\n \n AltPrintScreen\n Pause (3)\n SavePicture PastePicture, savePath\n \nerrExit:\n Exit Sub\n \nerrHandler:\n Debug.Print \"Save Picture: (\" & Err.Number & \") - \" & Err.Description\n Resume errExit\nEnd Sub\n \n' Routine : Pause\n' Purpose : Gives a short interval for proper image capture.\n' Arguments : Seconds to wait.\n \nPublic Function Pause(NumberOfSeconds As Variant)\nOn Error GoTo Err_Pause\n Dim PauseTime As Variant, start As Variant\n PauseTime = NumberOfSeconds\n start = Timer\n Do While Timer < start + PauseTime\n DoEvents\n Loop\nExit_Pause:\n Exit Function\nErr_Pause:\n MsgBox Err.Number & \" - \" & Err.Description, vbCritical, \"Pause()\"\n Resume Exit_Pause\nEnd Function\n SaveClip2Bit \"C:\\test\\test.bmp\"\n" }, { "answer_id": 74590162, "author": "JohnM", "author_id": 11318818, "author_profile": "https://Stackoverflow.com/users/11318818", "pm_score": 2, "selected": true, "text": "AppActivate Private Declare PtrSafe Sub keybd_event Lib \"user32\" (ByVal bVk As Byte, ByVal bScan As Byte, _\n ByVal dwFlags As Long, ByVal dwExtraInfo As LongPtr)\n\nPrivate Const VK_SNAPSHOT = &H2C\nPrivate Const KEYEVENTF_KEYUP = &H2\n\nPrivate Const PREFIX As String = \"<My folder>\\\"\n\nSub PrintScreen()\n ' grab filename\n Dim fileName As String\n fileName = ActiveCell.Value\n ' activate, for example, Chrome ... this will only work if Chrome is already in \n ' a 'normal' or 'maximized' window (ie not 'minimized')\n AppActivate \"Chrome\", False\n ' take screenshot\n keybd_event VK_SNAPSHOT, 0, 0, 0\n keybd_event VK_SNAPSHOT, 0, KEYEVENTF_KEYUP, 0\n ' wait for screenshot\n Dim t As Single\n t = Timer + 0.1\n Do While Timer < t\n DoEvents\n Loop\n \n ' paste screenshot to sheet and grab it ... the active sheet must be \n ' a Worksheet for this to work\n ActiveSheet.Paste\n Dim shp As Shape\n Set shp = Selection.ShapeRange(1)\n \n ' save as file ... PNG in this case\n If ExportPicture(shp, PREFIX & fileName & \".png\", \"png\") Then\n ' do success stuff!\n Debug.Print \"Success\"\n Else\n ' do failed stuff!\n Debug.Print \"Failed\"\n End If\n \n ' optionally, if required, delete the screenshot\n shp.Delete\nEnd Sub\n\n' Export Shape, as a picture, to a file\nFunction ExportPicture(shp As Shape, sFile As String, sFilter As String) As Boolean\n On Error GoTo errExit\n Dim ch As ChartObject\n Set ch = shp.Parent.ChartObjects.Add(0, 0, shp.Width, shp.Height)\n ch.Activate\n ch.ShapeRange.Fill.Visible = msoFalse ' to allow transparency if PNG\n ch.ShapeRange.Line.Visible = msoFalse\n ch.Chart.Paste\n ch.Chart.Export sFile, sFilter\n ExportPicture = True\nerrExit:\n If Not ch Is Nothing Then ch.Delete\nEnd Function\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8583661/" ]
74,588,103
<p>I have two large dictionaries and both dictionaries have same keys, (name of images) and have different values.</p> <p>1st dict named <code>train_descriptions</code> which looks like this:</p> <pre><code>{'15970.jpg': 'Turtle Check Men Navy Blue Shirt', '39386.jpg': 'Peter England Men Party Blue Jeans', '59263.jpg': 'Titan Women Silver Watch', .... .... '1855.jpg': 'Inkfruit Mens Chain Reaction T-shirt'} </code></pre> <p>and a 2nd dict named <code>train_features</code></p> <pre><code>{'31973.jpg': array([[0.00125694, 0. , 0.03409385, ..., 0.00434341, 0.00728011, 0.01451511]], dtype=float32), '30778.jpg': array([[0.0174035 , 0.04345186, 0.00772929, ..., 0.02230316, 0. , 0.03104496]], dtype=float32), ..., ..., '38246.jpg': array([[0.00403965, 0.03701203, 0.02616892, ..., 0.02296285, 0.00930257, 0.04575242]], dtype=float32)} </code></pre> <p>The length of both dictionaries are as follows:</p> <p><code>len(train_descriptions)</code> is 44424 and <code>len(train_features)</code> is 44441</p> <p>As you can see length of <code>train_description</code> dict is less than length of <code>train_features</code>. <code>train_features</code> dictionary has more keys-values than <code>train_descriptions</code>. How do I remove the keys from <code>train_features</code> dictionary which are not in <code>train_description</code>? To make their length same.</p>
[ { "answer_id": 74588158, "author": "Prabhas Kumar", "author_id": 20603322, "author_profile": "https://Stackoverflow.com/users/20603322", "pm_score": 2, "selected": true, "text": "for loop feat = train_features.keys()\ndesc = train_description.keys()\ncommon = list(i for i in feat if i not in decc)\n\nfor i in common: del train_features[i]\n for i in train_features.keys() - train_description.keys(): del train_features[i]\n" }, { "answer_id": 74588159, "author": "JayPeerachai", "author_id": 12135518, "author_profile": "https://Stackoverflow.com/users/12135518", "pm_score": 1, "selected": false, "text": "pop() dict for key in train_descriptions.keys():\n if key not in train_features.keys():\n train_features.pop(key)\n" }, { "answer_id": 74588220, "author": "Guy", "author_id": 5168011, "author_profile": "https://Stackoverflow.com/users/5168011", "pm_score": 2, "selected": false, "text": "xor diff = train_features.keys() ^ train_descriptions.keys()\nfor k in diff:\n del train_features[k]\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15964159/" ]
74,588,108
<p>Given an array of strings, return another array containing all of its longest strings.</p> <p>Example</p> <p>For <code>inputArray = [&quot;aba&quot;, &quot;aa&quot;, &quot;ad&quot;, &quot;vcd&quot;, &quot;aba&quot;]</code>, the output should be solution(inputArray) = [&quot;aba&quot;, &quot;vcd&quot;, &quot;aba&quot;].</p> <p>[execution time limit] 4 seconds (dart)</p> <p>[input] array.string inputArray</p> <p>[input] array.string inputArray</p> <p>A non-empty array.</p> <p>Guaranteed constraints: 1 ≤ inputArray.length ≤ 10, 1 ≤ inputArray[i].length ≤ 10.</p> <p>[output] array.string</p> <p>[output] array.string</p> <p>Array of the longest strings, stored in the same order as in the inputArray.</p> <p>I know that the javascript code answer of the above question but did't know how to write it into dart. this is the javascript //</p> <pre><code> var maxLength = Math.max(...inputArray.map(s =&gt; s.length)); return inputArray.filter(s =&gt; s.length === maxLength); </code></pre>
[ { "answer_id": 74588158, "author": "Prabhas Kumar", "author_id": 20603322, "author_profile": "https://Stackoverflow.com/users/20603322", "pm_score": 2, "selected": true, "text": "for loop feat = train_features.keys()\ndesc = train_description.keys()\ncommon = list(i for i in feat if i not in decc)\n\nfor i in common: del train_features[i]\n for i in train_features.keys() - train_description.keys(): del train_features[i]\n" }, { "answer_id": 74588159, "author": "JayPeerachai", "author_id": 12135518, "author_profile": "https://Stackoverflow.com/users/12135518", "pm_score": 1, "selected": false, "text": "pop() dict for key in train_descriptions.keys():\n if key not in train_features.keys():\n train_features.pop(key)\n" }, { "answer_id": 74588220, "author": "Guy", "author_id": 5168011, "author_profile": "https://Stackoverflow.com/users/5168011", "pm_score": 2, "selected": false, "text": "xor diff = train_features.keys() ^ train_descriptions.keys()\nfor k in diff:\n del train_features[k]\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11563594/" ]
74,588,115
<p>My problem is following:</p> <p>I need to display content dynamically according to a method from a different component than the the DynamicComponent tag is in.</p> <p>Is this by design or did I do sth wrong?</p> <p>My code:</p> <p>Platform.razor:</p> <pre><code>&lt;a href=&quot;&quot; @onclick:preventDefault @onclick=&quot;@(()=&gt;ChangePage(&quot;ListLinks&quot;))&gt; </code></pre> <pre><code>public Type? selectedPage = typeof(Empty); public void ChangePage(string page) { selectedPage = page.Length &gt; 0 ? Type.GetType($&quot;Namespace.Shared.{page}&quot;) : null; } </code></pre> <p>Home.razor:</p> <p><code>Platform platform = new Platform();</code></p> <p><code>&lt;DynamicComponent Type=&quot;@platform.selectedPage&quot;&gt;&lt;/DynamicComponent&gt;</code></p> <p>When I call the method inside the same component, everything works but it's not what I need.</p>
[ { "answer_id": 74588158, "author": "Prabhas Kumar", "author_id": 20603322, "author_profile": "https://Stackoverflow.com/users/20603322", "pm_score": 2, "selected": true, "text": "for loop feat = train_features.keys()\ndesc = train_description.keys()\ncommon = list(i for i in feat if i not in decc)\n\nfor i in common: del train_features[i]\n for i in train_features.keys() - train_description.keys(): del train_features[i]\n" }, { "answer_id": 74588159, "author": "JayPeerachai", "author_id": 12135518, "author_profile": "https://Stackoverflow.com/users/12135518", "pm_score": 1, "selected": false, "text": "pop() dict for key in train_descriptions.keys():\n if key not in train_features.keys():\n train_features.pop(key)\n" }, { "answer_id": 74588220, "author": "Guy", "author_id": 5168011, "author_profile": "https://Stackoverflow.com/users/5168011", "pm_score": 2, "selected": false, "text": "xor diff = train_features.keys() ^ train_descriptions.keys()\nfor k in diff:\n del train_features[k]\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20612133/" ]
74,588,126
<p>'''</p> <pre><code>@Override public TreeMap&lt;String, List&lt;String&gt;&gt; getCityWithPincode() { List&lt;User&gt; listOfUser = findAllUser(); TreeMap&lt;String, List&lt;String&gt;&gt; tm = new TreeMap&lt;&gt;(); for(User user : listOfUser) { if(tm.isEmpty()) { tm.put(user.getCity(), Arrays.asList(user.getPincode())); } else { if(tm.containsKey(user.getCity())) { List&lt;String&gt; list = tm.get(user.getCity()); list.add(user.getPincode()); tm.put(user.getCity(), list); } else { tm.put(user.getCity(), Arrays.asList(user.getPincode())); } } } return tm; } </code></pre> <p>'''</p> <p>Im trying collect city with there city pincode and in one city have somany pincode right so i have created treemap for collecting this details and key is a city and value is a list of pincode but this not working...</p> <p>Error is :</p> <pre><code>{ &quot;timestamp&quot;: &quot;2022-11-27T06:37:21.712+00:00&quot;, &quot;status&quot;: 500, &quot;error&quot;: &quot;Internal Server Error&quot;, &quot;trace&quot;: &quot;java.lang.UnsupportedOperationException\r\n\tat java.base/java.util.AbstractList.add(AbstractList.java:153)\r\n\tat java.base/java.util.AbstractList.add(AbstractList.java:111)\r\n\tat com.admin.panel.service.UserServiceImpl.getCityWithPincode(UserServiceImpl.java:182)\r\n\tat com.admin.panel.controller.UserController.getCityWithPincode(UserController.java:167)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:568)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)\r\n\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1071)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:964)\r\n\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)\r\n\tat org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:670)\r\n\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:779)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\r\n\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\r\n\tat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\r\n\tat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\r\n\tat org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:96)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\r\n\tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\r\n\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)\r\n\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)\r\n\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)\r\n\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)\r\n\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)\r\n\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)\r\n\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360)\r\n\tat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)\r\n\tat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)\r\n\tat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)\r\n\tat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1789)\r\n\tat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)\r\n\tat org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)\r\n\tat org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)\r\n\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\r\n\tat java.base/java.lang.Thread.run(Thread.java:833)\r\n&quot;, &quot;message&quot;: &quot;No message available&quot;, &quot;path&quot;: &quot;/user/citywithpincode/cal&quot; } </code></pre>
[ { "answer_id": 74588189, "author": "user7", "author_id": 4405757, "author_profile": "https://Stackoverflow.com/users/4405757", "pm_score": 1, "selected": false, "text": "add() AbstractList UnsupportedOperationException Arrays.asList() asList() Arrays.asList ArrayList tm.put(user.getCity(), new ArrayList<>(Arrays.asList(user.getPincode())));\n" }, { "answer_id": 74588283, "author": "モキャデ", "author_id": 20607467, "author_profile": "https://Stackoverflow.com/users/20607467", "pm_score": 2, "selected": false, "text": "new ArrayList<>() Arrays.asList() Arrays.asList() Map.computeIfAbsent() public TreeMap<String, List<String>> getCityWithPincode() {\n List<User> listOfUser = findAllUser();\n\n TreeMap<String, List<String>> tm = new TreeMap<>();\n\n for(User user : listOfUser) {\n tm.computeIfAbsent(user.getCity(), k -> new ArrayList<>()).add(user.getPincode());\n }\n return tm;\n}\n" }, { "answer_id": 74588859, "author": "Nowhere Man", "author_id": 13279831, "author_profile": "https://Stackoverflow.com/users/13279831", "pm_score": 0, "selected": false, "text": "Collectors.groupingBy() Function<User, String> Supplier<Map> Collectors.mapping User::getCity TreeMap::new Collectors.mapping(User::getPinCode, Collectors.toList()) @Override\npublic TreeMap<String, List<String>> getCityWithPincode() {\n return findAllUser()\n .stream()\n .collect(Collectors.groupingBy(\n User::getCity, // key - city name\n TreeMap::new, // create TreeMap instance\n Collectors.mapping(\n User::getPinCode, Collectors.toList()\n ) // List<String> pin codes\n ));\n}\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14772343/" ]
74,588,134
<p>Whenever I tried to create an account into AdMob , I got the following error</p> <h2><strong>An error occurred. Please try again later.</strong></h2> <p><br /> Even I filled in all the information.</p>
[ { "answer_id": 74588189, "author": "user7", "author_id": 4405757, "author_profile": "https://Stackoverflow.com/users/4405757", "pm_score": 1, "selected": false, "text": "add() AbstractList UnsupportedOperationException Arrays.asList() asList() Arrays.asList ArrayList tm.put(user.getCity(), new ArrayList<>(Arrays.asList(user.getPincode())));\n" }, { "answer_id": 74588283, "author": "モキャデ", "author_id": 20607467, "author_profile": "https://Stackoverflow.com/users/20607467", "pm_score": 2, "selected": false, "text": "new ArrayList<>() Arrays.asList() Arrays.asList() Map.computeIfAbsent() public TreeMap<String, List<String>> getCityWithPincode() {\n List<User> listOfUser = findAllUser();\n\n TreeMap<String, List<String>> tm = new TreeMap<>();\n\n for(User user : listOfUser) {\n tm.computeIfAbsent(user.getCity(), k -> new ArrayList<>()).add(user.getPincode());\n }\n return tm;\n}\n" }, { "answer_id": 74588859, "author": "Nowhere Man", "author_id": 13279831, "author_profile": "https://Stackoverflow.com/users/13279831", "pm_score": 0, "selected": false, "text": "Collectors.groupingBy() Function<User, String> Supplier<Map> Collectors.mapping User::getCity TreeMap::new Collectors.mapping(User::getPinCode, Collectors.toList()) @Override\npublic TreeMap<String, List<String>> getCityWithPincode() {\n return findAllUser()\n .stream()\n .collect(Collectors.groupingBy(\n User::getCity, // key - city name\n TreeMap::new, // create TreeMap instance\n Collectors.mapping(\n User::getPinCode, Collectors.toList()\n ) // List<String> pin codes\n ));\n}\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16968554/" ]
74,588,148
<p>Though I installed skpy by pip and pip3, the error happened when I command <code>jupyter execute</code> on the terminal.</p> <p><code>Python 3.9.13 pip 22.2.2 from /Users/username/opt/anaconda3/lib/python3.9/site-packages/pip (python 3.9)</code></p> <p><strong>Proof I installed skpy</strong></p> <pre><code>(base) username@MacBook-Pro-3 test-directory % pip list Package Version ----------------------------- -------------------- ・・・ SkPy 0.10.4 ・・・ ・・・ </code></pre> <pre><code>(base) username@MacBook-Pro-3 test-directory % pip3 install skpy Requirement already satisfied: skpy in /Users/username/opt/anaconda3/lib/python3.9/site-packages (0.10.4) Requirement already satisfied: beautifulsoup4 in /Users/username/opt/anaconda3/lib/python3.9/site-packages (from skpy) (4.11.1) Requirement already satisfied: requests in /Users/username/opt/anaconda3/lib/python3.9/site-packages (from skpy) (2.28.1) Requirement already satisfied: soupsieve&gt;1.2 in /Users/username/opt/anaconda3/lib/python3.9/site-packages (from beautifulsoup4-&gt;skpy) (2.3.1) Requirement already satisfied: certifi&gt;=2017.4.17 in /Users/username/opt/anaconda3/lib/python3.9/site-packages (from requests-&gt;skpy) (2022.9.24) Requirement already satisfied: charset-normalizer&lt;3,&gt;=2 in /Users/username/opt/anaconda3/lib/python3.9/site-packages (from requests-&gt;skpy) (2.0.4) Requirement already satisfied: urllib3&lt;1.27,&gt;=1.21.1 in /Users/username/opt/anaconda3/lib/python3.9/site-packages (from requests-&gt;skpy) (1.26.11) Requirement already satisfied: idna&lt;4,&gt;=2.5 in /Users/username/opt/anaconda3/lib/python3.9/site-packages (from requests-&gt;skpy) (3.3) </code></pre> <p><strong>Execution command</strong></p> <pre><code>(base) username@MacBook-Pro-3 test-directory % /Library/Frameworks/Python.framework/Versions/3.10/bin/jupyter execute /Users/username/Desktop/job/test-directory/createNewShiftTab.ipynb </code></pre> <p><strong>The error after run above command</strong></p> <pre><code>[NbClientApp] Executing /Users/username/Desktop/job/test-directory/createNewShiftTab.ipynb [NbClientApp] Executing notebook with kernel: python3 Traceback (most recent call last): File &quot;/Library/Frameworks/Python.framework/Versions/3.10/bin/jupyter-execute&quot;, line 8, in &lt;module&gt; sys.exit(main()) File &quot;/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/jupyter_core/application.py&quot;, line 276, in launch_instance return super().launch_instance(argv=argv, **kwargs) File &quot;/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/traitlets/config/application.py&quot;, line 981, in launch_instance app.initialize(argv) File &quot;/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/traitlets/config/application.py&quot;, line 110, in inner return method(app, *args, **kwargs) File &quot;/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/nbclient/cli.py&quot;, line 113, in initialize [self.run_notebook(path) for path in self.notebooks] File &quot;/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/nbclient/cli.py&quot;, line 113, in &lt;listcomp&gt; [self.run_notebook(path) for path in self.notebooks] File &quot;/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/nbclient/cli.py&quot;, line 154, in run_notebook client.execute() File &quot;/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/nbclient/util.py&quot;, line 85, in wrapped return just_run(coro(*args, **kwargs)) File &quot;/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/nbclient/util.py&quot;, line 60, in just_run return loop.run_until_complete(coro) File &quot;/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/asyncio/base_events.py&quot;, line 646, in run_until_complete return future.result() File &quot;/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/nbclient/client.py&quot;, line 701, in async_execute await self.async_execute_cell( File &quot;/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/nbclient/client.py&quot;, line 1019, in async_execute_cell await self._check_raise_for_error(cell, cell_index, exec_reply) File &quot;/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/nbclient/client.py&quot;, line 913, in _check_raise_for_error raise CellExecutionError.from_cell_and_msg(cell, exec_reply_content) nbclient.exceptions.CellExecutionError: An error occurred while executing the following cell: --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) Cell In [1], line 9 6 from oauth2client.service_account import ServiceAccountCredentials 7 # print(sys.path) importしたモジュールの探索先ディレクトリを一覧表示 8 #Skype操作 ----&gt; 9 from skpy import Skype ModuleNotFoundError: No module named 'skpy' ModuleNotFoundError: No module named 'skpy' </code></pre> <p>But when I executed on the JupyterLab browser directly, it didn’t happen as below, so I’m confusing. <a href="https://i.stack.imgur.com/6AI36.png" rel="nofollow noreferrer">enter image description here</a></p> <p><strong>And this is the output of sys.path</strong></p> <pre><code>['/Users/username/Desktop/job/automation', '/Users/username/opt/anaconda3/lib/python39.zip', '/Users/username/opt/anaconda3/lib/python3.9', '/Users/username/opt/anaconda3/lib/python3.9/lib-dynload', '', '/Users/username/opt/anaconda3/lib/python3.9/site-packages', '/Users/username/opt/anaconda3/lib/python3.9/site-packages/aeosa', '/Users/username/opt/anaconda3/lib/python3.9/site-packages/IPython/extensions', '/Users/username/.ipython'] </code></pre> <ul> <li>Run <code>print(sys.path)</code> then confirmed the module was in the directory where python searched to use module</li> <li>Restart mac, terminal, jupyter</li> <li>fix text to &quot;SkPy&quot; from &quot;skpy&quot;</li> </ul> <p>But all of them didn’t work</p>
[ { "answer_id": 74588448, "author": "Michael Gathara", "author_id": 11009561, "author_profile": "https://Stackoverflow.com/users/11009561", "pm_score": 1, "selected": false, "text": "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/python -m pip install skpy\n where python3\n pip install <package>\nor\npython3 <file>\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20610531/" ]
74,588,170
<p>Suppose I want to make a single svg, which can be stretched to be any of these 2 boxes: <a href="https://i.stack.imgur.com/1cQyX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1cQyX.png" alt="enter image description here" /></a></p> <p>I'm trying to use this SVG as am image background in HTML/CSS.</p> <p>Notice how the bottom left corner has the same angle in both boxes, but the second one is just longer. I made this in illustrator, altering the nodes themselves. Is there any property that I can use if I make a custom SVG which will keep the bottom left corner intact while streching the other side of the file?</p> <p>I achieved something similar with clip-path: polygon() and calc, which allows usage of both % and px units, which means the corner could be 30px inset, but the bottom right corner is at 100% 100%. The problem with this solution is that polygon does not allow curves, and I need to add some later.</p>
[ { "answer_id": 74590912, "author": "ccprog", "author_id": 4996779, "author_profile": "https://Stackoverflow.com/users/4996779", "pm_score": 3, "selected": false, "text": "border-width border-image-width div {\n width:300px;\n height:150px;\n position:relative;\n overflow: hidden;\n resize:both;\n background-color:#cef;\n background-clip: content-box;\n \n border-style: solid;\n border-width: 10px;\n border-image-source: url('data:image/svg+xml,<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 40 40\"><path fill=\"none\" stroke=\"black\" stroke-width=\"2\" d=\"M1,1V30L10,39H39V1Z\" /></svg>');\n border-image-slice: 30%;\n border-image-width: 60px;\n border-image-repeat: stretch; \n} <div>" }, { "answer_id": 74591827, "author": "chrwahl", "author_id": 322084, "author_profile": "https://Stackoverflow.com/users/322084", "pm_score": 2, "selected": false, "text": "<svg xmlns=\"http://www.w3.org/2000/svg\">\n <style>\n svg {\n width: 100%;\n height: 100%;\n }\n path.tr {\n stroke: orange;\n transform: translate(calc(100% - 3px), 3px);\n stroke-width: 6px;\n }\n path.bl {\n stroke: orange;\n transform: translate(3px, calc(100% - 3px));\n stroke-width: 6px;\n }\n </style>\n <path class=\"tr\" d=\"M -5000 0 H 0 V 5000\" fill=\"none\" />\n <path class=\"bl\" d=\"M 0 -5000 V -40 C 0 -20 20 0 40 0 H 5000\" fill=\"none\" />\n</svg>\n .box {\n min-height: 100px;\n padding: 10px;\n margin: 10px;\n background-size: contain;\n background-image: url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgogIDxzdHlsZT4KICAgIHN2ZyB7CiAgICAgIHdpZHRoOiAxMDAlOwogICAgICBoZWlnaHQ6IDEwMCU7CiAgICB9CiAgICBwYXRoLnRyIHsKICAgICAgc3Ryb2tlOiBvcmFuZ2U7CiAgICAgIHRyYW5zZm9ybTogdHJhbnNsYXRlKGNhbGMoMTAwJSAtIDNweCksIDNweCk7CiAgICAgIHN0cm9rZS13aWR0aDogNnB4OwogICAgfQogICAgcGF0aC5ibCB7CiAgICAgIHN0cm9rZTogb3JhbmdlOwogICAgICB0cmFuc2Zvcm06IHRyYW5zbGF0ZSgzcHgsIGNhbGMoMTAwJSAtIDNweCkpOwogICAgICBzdHJva2Utd2lkdGg6IDZweDsKICAgIH0KICA8L3N0eWxlPgogIDxwYXRoIGNsYXNzPSJ0ciIgZD0iTSAtNTAwMCAwIEggMCBWIDUwMDAiIGZpbGw9Im5vbmUiIC8+CiAgPHBhdGggY2xhc3M9ImJsIiBkPSJNIDAgLTUwMDAgViAtNDAgQyAwIC0yMCAyMCAwIDQwIDAgSCA1MDAwIiBmaWxsPSJub25lIiAvPgo8L3N2Zz4K');\n}\n\n.small {\n width: 300px;\n}\n\n.large {\n width: 600px;\n height: 600px;\n} <div class=\"box small\">\n <p>small</p>\n <p>small</p>\n <p>small</p>\n</div>\n<div class=\"box large\">large</div>" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3530767/" ]
74,588,173
<p>I have a list of string/regex that I want to check if its matched from the string input. <br> Lets just say I have these lists:</p> <pre class="lang-php prettyprint-override"><code>$list = [ // an array list of string/regex that i want to check &quot;lorem ipsum&quot;, // a words &quot;example&quot;, // another word &quot;/(nulla)/&quot;, // a regex ]; </code></pre> <p>And the string:</p> <pre class="lang-php prettyprint-override"><code>$input_string = &quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer quam ex, vestibulum sed laoreet auctor, iaculis eget velit. Donec mattis, nulla ac suscipit maximus, leo metus vestibulum eros, nec finibus nisl dui ut est. Nam tristique varius mauris, a faucibus augue.&quot;; </code></pre> <p>And so, I want it to check like this:</p> <pre class="lang-php prettyprint-override"><code>if( $matched_string &gt;= 1 ){ // check if there was more than 1 string matched or something... // do something... // output matched string: &quot;lorem ipsum&quot;, &quot;nulla&quot; }else{ // nothing matched } </code></pre> <p>How can I do something like that?</p>
[ { "answer_id": 74590912, "author": "ccprog", "author_id": 4996779, "author_profile": "https://Stackoverflow.com/users/4996779", "pm_score": 3, "selected": false, "text": "border-width border-image-width div {\n width:300px;\n height:150px;\n position:relative;\n overflow: hidden;\n resize:both;\n background-color:#cef;\n background-clip: content-box;\n \n border-style: solid;\n border-width: 10px;\n border-image-source: url('data:image/svg+xml,<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 40 40\"><path fill=\"none\" stroke=\"black\" stroke-width=\"2\" d=\"M1,1V30L10,39H39V1Z\" /></svg>');\n border-image-slice: 30%;\n border-image-width: 60px;\n border-image-repeat: stretch; \n} <div>" }, { "answer_id": 74591827, "author": "chrwahl", "author_id": 322084, "author_profile": "https://Stackoverflow.com/users/322084", "pm_score": 2, "selected": false, "text": "<svg xmlns=\"http://www.w3.org/2000/svg\">\n <style>\n svg {\n width: 100%;\n height: 100%;\n }\n path.tr {\n stroke: orange;\n transform: translate(calc(100% - 3px), 3px);\n stroke-width: 6px;\n }\n path.bl {\n stroke: orange;\n transform: translate(3px, calc(100% - 3px));\n stroke-width: 6px;\n }\n </style>\n <path class=\"tr\" d=\"M -5000 0 H 0 V 5000\" fill=\"none\" />\n <path class=\"bl\" d=\"M 0 -5000 V -40 C 0 -20 20 0 40 0 H 5000\" fill=\"none\" />\n</svg>\n .box {\n min-height: 100px;\n padding: 10px;\n margin: 10px;\n background-size: contain;\n background-image: url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgogIDxzdHlsZT4KICAgIHN2ZyB7CiAgICAgIHdpZHRoOiAxMDAlOwogICAgICBoZWlnaHQ6IDEwMCU7CiAgICB9CiAgICBwYXRoLnRyIHsKICAgICAgc3Ryb2tlOiBvcmFuZ2U7CiAgICAgIHRyYW5zZm9ybTogdHJhbnNsYXRlKGNhbGMoMTAwJSAtIDNweCksIDNweCk7CiAgICAgIHN0cm9rZS13aWR0aDogNnB4OwogICAgfQogICAgcGF0aC5ibCB7CiAgICAgIHN0cm9rZTogb3JhbmdlOwogICAgICB0cmFuc2Zvcm06IHRyYW5zbGF0ZSgzcHgsIGNhbGMoMTAwJSAtIDNweCkpOwogICAgICBzdHJva2Utd2lkdGg6IDZweDsKICAgIH0KICA8L3N0eWxlPgogIDxwYXRoIGNsYXNzPSJ0ciIgZD0iTSAtNTAwMCAwIEggMCBWIDUwMDAiIGZpbGw9Im5vbmUiIC8+CiAgPHBhdGggY2xhc3M9ImJsIiBkPSJNIDAgLTUwMDAgViAtNDAgQyAwIC0yMCAyMCAwIDQwIDAgSCA1MDAwIiBmaWxsPSJub25lIiAvPgo8L3N2Zz4K');\n}\n\n.small {\n width: 300px;\n}\n\n.large {\n width: 600px;\n height: 600px;\n} <div class=\"box small\">\n <p>small</p>\n <p>small</p>\n <p>small</p>\n</div>\n<div class=\"box large\">large</div>" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12317203/" ]
74,588,184
<p>I want to remove bytes from an array, I don't want to remove all bytes <code>0x6f</code> I just want to remove two only of them. This is my code:</p> <pre><code>string msg = &quot;gooooooal&quot;; byte[] oldArray = Encoding.GetEncoding(1256).GetBytes(msg); byte[] newArray = oldArray.Where(b =&gt; b != 0x6f).ToArray(); </code></pre>
[ { "answer_id": 74590912, "author": "ccprog", "author_id": 4996779, "author_profile": "https://Stackoverflow.com/users/4996779", "pm_score": 3, "selected": false, "text": "border-width border-image-width div {\n width:300px;\n height:150px;\n position:relative;\n overflow: hidden;\n resize:both;\n background-color:#cef;\n background-clip: content-box;\n \n border-style: solid;\n border-width: 10px;\n border-image-source: url('data:image/svg+xml,<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 40 40\"><path fill=\"none\" stroke=\"black\" stroke-width=\"2\" d=\"M1,1V30L10,39H39V1Z\" /></svg>');\n border-image-slice: 30%;\n border-image-width: 60px;\n border-image-repeat: stretch; \n} <div>" }, { "answer_id": 74591827, "author": "chrwahl", "author_id": 322084, "author_profile": "https://Stackoverflow.com/users/322084", "pm_score": 2, "selected": false, "text": "<svg xmlns=\"http://www.w3.org/2000/svg\">\n <style>\n svg {\n width: 100%;\n height: 100%;\n }\n path.tr {\n stroke: orange;\n transform: translate(calc(100% - 3px), 3px);\n stroke-width: 6px;\n }\n path.bl {\n stroke: orange;\n transform: translate(3px, calc(100% - 3px));\n stroke-width: 6px;\n }\n </style>\n <path class=\"tr\" d=\"M -5000 0 H 0 V 5000\" fill=\"none\" />\n <path class=\"bl\" d=\"M 0 -5000 V -40 C 0 -20 20 0 40 0 H 5000\" fill=\"none\" />\n</svg>\n .box {\n min-height: 100px;\n padding: 10px;\n margin: 10px;\n background-size: contain;\n background-image: url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgogIDxzdHlsZT4KICAgIHN2ZyB7CiAgICAgIHdpZHRoOiAxMDAlOwogICAgICBoZWlnaHQ6IDEwMCU7CiAgICB9CiAgICBwYXRoLnRyIHsKICAgICAgc3Ryb2tlOiBvcmFuZ2U7CiAgICAgIHRyYW5zZm9ybTogdHJhbnNsYXRlKGNhbGMoMTAwJSAtIDNweCksIDNweCk7CiAgICAgIHN0cm9rZS13aWR0aDogNnB4OwogICAgfQogICAgcGF0aC5ibCB7CiAgICAgIHN0cm9rZTogb3JhbmdlOwogICAgICB0cmFuc2Zvcm06IHRyYW5zbGF0ZSgzcHgsIGNhbGMoMTAwJSAtIDNweCkpOwogICAgICBzdHJva2Utd2lkdGg6IDZweDsKICAgIH0KICA8L3N0eWxlPgogIDxwYXRoIGNsYXNzPSJ0ciIgZD0iTSAtNTAwMCAwIEggMCBWIDUwMDAiIGZpbGw9Im5vbmUiIC8+CiAgPHBhdGggY2xhc3M9ImJsIiBkPSJNIDAgLTUwMDAgViAtNDAgQyAwIC0yMCAyMCAwIDQwIDAgSCA1MDAwIiBmaWxsPSJub25lIiAvPgo8L3N2Zz4K');\n}\n\n.small {\n width: 300px;\n}\n\n.large {\n width: 600px;\n height: 600px;\n} <div class=\"box small\">\n <p>small</p>\n <p>small</p>\n <p>small</p>\n</div>\n<div class=\"box large\">large</div>" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14857855/" ]
74,588,223
<p>I have a query as below</p> <pre><code>|| LPAD (TRIM (TO_CHAR (RWTEXPT_STD_AMOUNT, 'FM9999999999999D00')), 15, '0') </code></pre> <p>its giving the result : <code>000011545467.00</code></p> <p>what i need is : <code>000000115454.67</code></p> <p>i have tried <code>'FM9999999999999D00'</code> and <code>'999999999999D99'</code> but it gives the same results <code>000011545467.00</code></p> <p>what i need is <code>000000115454.67</code></p>
[ { "answer_id": 74588601, "author": "d r", "author_id": 19023353, "author_profile": "https://Stackoverflow.com/users/19023353", "pm_score": 0, "selected": false, "text": "Select To_Char(14.5, 'FM000000000000D00') \"NMBR\" From Dual\n--\n-- NMBR \n-- ----------------\n-- 000000000014.50 \n Select To_Char(1467/100, 'FM000000000000D00') \"NMBR\" From Dual\n--\n-- NMBR \n-- ----------------\n-- 000000000014.67\n" }, { "answer_id": 74589241, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 1, "selected": false, "text": "SELECT TO_CHAR(\n TO_NUMBER(RWTEXPT_STD_AMOUNT)/100,\n 'FM000000000000D00'\n ) AS result\nFROM table_name\n CREATE TABLE table_name (RWTEXPT_STD_AMOUNT) AS\nSELECT '000000011545467' FROM DUAL;\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20612249/" ]
74,588,226
<p>I use express JWT with nest js and use it in gateway graphql. I want to return error when my token has error including expiration error or invalid error after calling any graphql api.</p> <p>Here is the code that I use express JWT in main file of my gateway:</p> <pre><code>app.use( graphqlUploadExpress(), expressJwt({ secret: secretCallback, algorithms: ['HS256'], credentialsRequired: false, }), ); </code></pre> <p>and the following code is my validation when token is invalid:</p> <pre><code>function (err, req, res, next) { const { ip, method, originalUrl, headers } = req; const requestMeta = { headers, ip, method, originalUrl, error: err }; if (err.message === 'jwt expired') { Logger.error('Gateway JWT Expired', requestMeta); res.send(401, { code: 'gateway-token-expired', message: 'Token is expired' }); } else if (err.code === 'invalid_token') { Logger.error('Gateway JWT Invalid', requestMeta); res.send(401, { code: 'gateway-token-invalid', message: 'Token is invalid' }); } else { next(err); } }; </code></pre> <p>I want that <code>res.status(err.status).send({ message: err.message });</code> return the error message back to user.</p>
[ { "answer_id": 74588601, "author": "d r", "author_id": 19023353, "author_profile": "https://Stackoverflow.com/users/19023353", "pm_score": 0, "selected": false, "text": "Select To_Char(14.5, 'FM000000000000D00') \"NMBR\" From Dual\n--\n-- NMBR \n-- ----------------\n-- 000000000014.50 \n Select To_Char(1467/100, 'FM000000000000D00') \"NMBR\" From Dual\n--\n-- NMBR \n-- ----------------\n-- 000000000014.67\n" }, { "answer_id": 74589241, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 1, "selected": false, "text": "SELECT TO_CHAR(\n TO_NUMBER(RWTEXPT_STD_AMOUNT)/100,\n 'FM000000000000D00'\n ) AS result\nFROM table_name\n CREATE TABLE table_name (RWTEXPT_STD_AMOUNT) AS\nSELECT '000000011545467' FROM DUAL;\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12862166/" ]
74,588,231
<p>There're these two similar options in <code>SecurityAlgorithms</code> class. Which one should be used for signing JWT token? Is there any difference?</p>
[ { "answer_id": 74588756, "author": "Collin Dauphinee", "author_id": 214796, "author_profile": "https://Stackoverflow.com/users/214796", "pm_score": 1, "selected": false, "text": "HmacSha512Signature HmacSha512 Signature" }, { "answer_id": 74588929, "author": "Dimitris Maragkos", "author_id": 10839134, "author_profile": "https://Stackoverflow.com/users/10839134", "pm_score": 3, "selected": true, "text": "alg HmacSha512 {\n \"alg\": \"HS512\",\n \"typ\": \"JWT\"\n}\n HmacSha512Signature {\n \"alg\": \"http://www.w3.org/2001/04/xmldsig-more#hmac-sha512\",\n \"typ\": \"JWT\"\n}\n http://www.w3.org/2001/04/xmldsig-more#hmac-sha512 alg HmacSha512 HmacSha512" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6841224/" ]
74,588,239
<p>The error is Uncaught TypeError: Cannot read properties of undefined (reading 'style')</p> <p>Code:</p> <pre><code>let slideIndex = 0; showSlides(); function showSlides() { let i; let slides = document.getElementsByClassName(&quot;mySlides&quot;); let dots = document.getElementsByClassName(&quot;dot&quot;); for (i = 0; i &lt; slides.length; i++) { slides[i].style.display = &quot;none&quot;; } slideIndex++; if (slideIndex &gt; slides.length) {slideIndex = 1} for (i = 0; i &lt; dots.length; i++) { dots[i].className = dots[i].className.replace(&quot; active&quot;, &quot;&quot;); } slides[slideIndex-1].style.display = &quot;block&quot;; //Error is showed at this line dots[slideIndex-1].className += &quot; active&quot;; setTimeout(showSlides, 2000); // Change image every 2 seconds } </code></pre> <p>I included my script tag in index.html of public folder Rest javascript files are working except this</p>
[ { "answer_id": 74588756, "author": "Collin Dauphinee", "author_id": 214796, "author_profile": "https://Stackoverflow.com/users/214796", "pm_score": 1, "selected": false, "text": "HmacSha512Signature HmacSha512 Signature" }, { "answer_id": 74588929, "author": "Dimitris Maragkos", "author_id": 10839134, "author_profile": "https://Stackoverflow.com/users/10839134", "pm_score": 3, "selected": true, "text": "alg HmacSha512 {\n \"alg\": \"HS512\",\n \"typ\": \"JWT\"\n}\n HmacSha512Signature {\n \"alg\": \"http://www.w3.org/2001/04/xmldsig-more#hmac-sha512\",\n \"typ\": \"JWT\"\n}\n http://www.w3.org/2001/04/xmldsig-more#hmac-sha512 alg HmacSha512 HmacSha512" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20612314/" ]
74,588,253
<p>Can use a pointer to access content of the memory location on embedded c.</p> <pre><code>int *p; p = (int*) 0x30610000; </code></pre> <p>I need to write a program that add two numbers stored in memory location.</p> <pre><code>int *p; int *q; p = (int*) 0x30610000; q = (int*) 0x30610004; int sum=(*p)+(*q) </code></pre> <p>Is the above code correct?</p> <p>I need understand how access a content of memory location on embedded c.</p>
[ { "answer_id": 74588759, "author": "Clifford", "author_id": 168986, "author_profile": "https://Stackoverflow.com/users/168986", "pm_score": 3, "selected": true, "text": "volatile volatile int* const p = (volatile int* const)0x30610000u ;\n #define p (*(volatile int*)0x30610000u)\n#define q (*(volatile int*)0x30610000u)\n\nint sum = p + q ;\n P Q" }, { "answer_id": 74599431, "author": "Lundin", "author_id": 584518, "author_profile": "https://Stackoverflow.com/users/584518", "pm_score": 2, "selected": false, "text": "volatile -fno-strict-aliasing int stdint.h u U volatile volatile uint32_t*" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14328404/" ]
74,588,256
<p>I have a requirement to slice &quot;Dev&quot; from below variable vmName in Azure logicapp</p> <p>variable information :</p> <ul> <li>Name : vmName</li> <li>Type : String</li> <li>Value : Dev-Testing-2</li> </ul> <p>When i tried with below approach/expression :</p> <pre><code>slice(split(variables('dsvmName'),'-'),1) </code></pre> <p>error : The template language function 'slice' expects its first parameter to be of type string. The provided value is of type 'Array'. Please see <a href="https://aka.ms/logicexpressions#slice" rel="nofollow noreferrer">https://aka.ms/logicexpressions#slice</a> for usage details.'.</p> <p><a href="https://i.stack.imgur.com/exGRQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/exGRQ.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74588759, "author": "Clifford", "author_id": 168986, "author_profile": "https://Stackoverflow.com/users/168986", "pm_score": 3, "selected": true, "text": "volatile volatile int* const p = (volatile int* const)0x30610000u ;\n #define p (*(volatile int*)0x30610000u)\n#define q (*(volatile int*)0x30610000u)\n\nint sum = p + q ;\n P Q" }, { "answer_id": 74599431, "author": "Lundin", "author_id": 584518, "author_profile": "https://Stackoverflow.com/users/584518", "pm_score": 2, "selected": false, "text": "volatile -fno-strict-aliasing int stdint.h u U volatile volatile uint32_t*" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7995771/" ]
74,588,259
<p>I'm new to Android, and rather new to SQL in general.</p> <p>I have a data model where I have a <code>Text</code> that consists of <code>TextMetadata</code> as well as a long string, which is the text content itself. So</p> <pre><code>Text { metadata: { author: string, title: string // more associated metadata }, textContent: long string, or potentially array of lines or paragraphs } </code></pre> <p>I'd like to load a list of the metadata for all texts on the App's landing page, without incurring the cost of reading all the long strings (or having operations be slowed down because the table has a column with a long string?).</p> <p>What is the proper pattern here? Should I use two tables, and related them? Or can I use one table/one <code>@Entity</code>, with embedded metadata, and do some fancy stuff in the DAO to just list/sort/operate on the embedded metadata?</p> <p>Most of my background is with <code>NoSQL</code> databases, so I could be thinking about this entirely wrong. Advice on the general best practices here would be helpful, but I guess I have two core questions:</p> <ol> <li>Does having a long/very long string/TEXT column cause performance considerations when operating on that specific table/row?</li> <li>Is there a clean way using Kotlin annotations to express embedded metadata that would make it easy to fetch in the DAO, without having use a long SELECT for each individual column?</li> </ol>
[ { "answer_id": 74635039, "author": "regex", "author_id": 9470979, "author_profile": "https://Stackoverflow.com/users/9470979", "pm_score": 1, "selected": false, "text": "@Entity\ndata class Text(\n @PrimaryKey val id: Long,\n val metadata: TextMetadata,\n val textContent: String\n)\n\n@Embedded\ndata class TextMetadata(\n val author: String,\n val title: String\n)\n\n Text TextMetadata TextMetadata" }, { "answer_id": 74662979, "author": "Benjamin Woolston", "author_id": 20188398, "author_profile": "https://Stackoverflow.com/users/20188398", "pm_score": 0, "selected": false, "text": "@Entity\ndata class TextMetadata(\n val author: String,\n val title: String,\n // more associated metadata\n val textContentId: Long\n)\n\n@Entity\ndata class TextContent(\n @PrimaryKey val id: Long,\n val textContent: String\n)\n\ndata class TextWithContent(\n @Embedded val metadata: TextMetadata,\n @Relation(parentColumn = \"textContentId\", entityColumn = \"id\")\n val textContent: TextContent\n)\n\n@Dao\ninterface TextDao {\n @Query(\"SELECT * FROM text_metadata LEFT JOIN text_content ON text_metadata.textContentId = text_content.id\")\n fun getAllTexts(): List<TextWithContent>\n}\n" }, { "answer_id": 74680379, "author": "ymz", "author_id": 4062197, "author_profile": "https://Stackoverflow.com/users/4062197", "pm_score": 0, "selected": false, "text": "mongo db noSQL sqLite android room sqLite android APIs Text sqLite android room object LargeDataContract {\n // all tables for handling large data will be defined here\n\n object TextEntry : BaseColumns {\n const val TABLE_NAME = \"text_entry\"\n const val COLUMN_NAME_KEY = \"key\"\n const val COLUMN_NAME_VALUE = \"value\"\n }\n}\n\n// in the future - append this \"create statement\" whenever you add more tables to your database\nprivate const val SQL_CREATE_ENTRIES =\n \"CREATE TABLE ${TextEntry.TABLE_NAME} (\" +\n \"${TextEntry.COLUMN_NAME_KEY} INTEGER PRIMARY KEY,\" +\n \"${TextEntry.COLUMN_NAME_VALUE} TEXT)\"\n\n// create a helper that will assist you to initiate your database properly\nclass LargeDataDbHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {\n override fun onCreate(db: SQLiteDatabase) {\n db.execSQL(SQL_CREATE_ENTRIES)\n }\n \n companion object {\n // If you change the database schema, you must increment the database version. Also - please read `sqLite` documentation to better understand versioning ,upgrade and downgrade operations\n const val DATABASE_VERSION = 1\n const val DATABASE_NAME = \"LargeData.db\"\n }\n}\n\n// create an instance and connect to your database\nval dbHelper = LargeDataDbHelper(context)\n\n// write an item to your database\nval db = dbHelper.writableDatabase\n\nval values = ContentValues().apply {\n put(TextEntry.COLUMN_NAME_VALUE, \"some long value goes here\")\n}\n\nval key = db?.insert(TextEntry.TABLE_NAME, null, values)\n\n// now take the key variable and store it in you entity. this is the only reference you should need\n android APIs" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/954986/" ]
74,588,266
<p>first of all im new to laravel,</p> <p>second i cloned a project from GitHub</p> <p>I'm trying to start my laravel development server with| <strong>php artisan serve</strong> but it gives me this error:</p> <pre><code> php artisan serve Starting Laravel development server: http://127.0.0.1:8000 [Sun Nov 27 08:38:27 2022] PHP 8.1.13 Development Server (http://127.0.0.1:8000) started [Sun Nov 27 08:38:36 2022] 127.0.0.1:42986 Accepted [Sun Nov 27 08:38:36 2022] PHP Warning: require_once(/home/almando/Documents/laravelPro/amazy-ecommerce/public/index.php): Failed to open stream: No such file or directory in /home/almando/Documents/laravelPro/amazy-ecommerce/server.php on line 21 [Sun Nov 27 08:38:36 2022] PHP Fatal error: Uncaught Error: Failed opening required '/home/almando/Documents/laravelPro/amazy-ecommerce/public/index.php' (include_path='.:/usr/share/php') in /home/almando/Documents/laravelPro/amazy-ecommerce/server.php:21 Stack trace: #0 {main} thrown in /home/almando/Documents/laravelPro/amazy-ecommerce/server.php on line 21 [Sun Nov 27 08:38:36 2022] 127.0.0.1:42986 Closing [Sun Nov 27 08:38:36 2022] 127.0.0.1:42992 Accepted [Sun Nov 27 08:38:36 2022] 127.0.0.1:43000 Accepted [Sun Nov 27 08:38:47 2022] PHP Warning: require_once(/home/almando/Documents/laravelPro/amazy-ecommerce/public/index.php): Failed to open stream: No such file or directory in /home/almando/Documents/laravelPro/amazy-ecommerce/server.php on line 21 [Sun Nov 27 08:38:47 2022] PHP Fatal error: Uncaught Error: Failed opening required '/home/almando/Documents/laravelPro/amazy-ecommerce/public/index.php' (include_path='.:/usr/share/php') in /home/almando/Documents/laravelPro/amazy-ecommerce/server.php:21 Stack trace: #0 {main} thrown in /home/almando/Documents/laravelPro/amazy-ecommerce/server.php on line 21 </code></pre> <p>//////////////////////////////////////////////</p> <p>In bootstrap/App.php</p> <pre><code>&lt;?php /* |-------------------------------------------------------------------------- | Create The Application |-------------------------------------------------------------------------- | | The first thing we will do is create a new Laravel application instance | which serves as the &quot;glue&quot; for all the components of Laravel, and is | the IoC container for the system binding all of the various parts. | */ $app = new Illuminate\Foundation\Application( $_ENV['APP_BASE_PATH'] ?? dirname(__DIR__) ); /* |-------------------------------------------------------------------------- | Bind Important Interfaces |-------------------------------------------------------------------------- | | Next, we need to bind some important interfaces into the container so | we will be able to resolve them when needed. The kernels serve the | incoming requests to this application from both the web and CLI. | */ $app-&gt;singleton( Illuminate\Contracts\Http\Kernel::class, App\Http\Kernel::class ); $app-&gt;singleton( Illuminate\Contracts\Console\Kernel::class, App\Console\Kernel::class ); $app-&gt;singleton( Illuminate\Contracts\Debug\ExceptionHandler::class, App\Exceptions\Handler::class ); /* |-------------------------------------------------------------------------- | Return The Application |-------------------------------------------------------------------------- | | This script returns the application instance. The instance is given to | the calling script so we can separate the building of the instances | from the actual running of the application and sending responses. | */ return $app; </code></pre> <p>/////////////////////////////////////</p> <p>in server.php</p> <pre><code>&lt;?php /** * Laravel - A PHP Framework For Web Artisans * * @package Laravel * @author Taylor Otwell &lt;taylor@laravel.com&gt; */ $uri = urldecode( parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) ); // This file allows us to emulate Apache's &quot;mod_rewrite&quot; functionality from the // built-in PHP web server. This provides a convenient way to test a Laravel // application without having installed a &quot;real&quot; web server software here. if ($uri !== '/' &amp;&amp; file_exists(__DIR__.'/public'.$uri)) { return false; } require_once __DIR__.'/public/index.php'; </code></pre> <p>///////////////////////////////////////////</p> <p>in index.php</p> <pre><code>&lt;?php use Illuminate\Contracts\Http\Kernel; use Illuminate\Http\Request; define('LARAVEL_START', microtime(true)); /* |-------------------------------------------------------------------------- | Check If Application Is Under Maintenance |-------------------------------------------------------------------------- | | If the application is maintenance / demo mode via the &quot;down&quot; command we | will require this file so that any prerendered template can be shown | instead of starting the framework, which could cause an exception. | */ if (file_exists(__DIR__.'/storage/framework/maintenance.php')) { require __DIR__.'/storage/framework/maintenance.php'; } /* |-------------------------------------------------------------------------- | Register The Auto Loader |-------------------------------------------------------------------------- | | Composer provides a convenient, automatically generated class loader for | this application. We just need to utilize it! We'll simply require it | into the script here so we don't need to manually load our classes. | */ require __DIR__.'/vendor/autoload.php'; /* |-------------------------------------------------------------------------- | Run The Application |-------------------------------------------------------------------------- | | Once we have the application, we can handle the incoming request using | the application's HTTP kernel. Then, we will send the response back | to this client's browser, allowing them to enjoy our application. | */ $app = require_once __DIR__.'/bootstrap/app.php'; $kernel = $app-&gt;make(Kernel::class); $response = tap($kernel-&gt;handle( $request = Request::capture() ))-&gt;send(); $kernel-&gt;terminate($request, $response); </code></pre> <p>////////////////////////////////////////////////////////////</p> <p>And in the browser it say :</p> <p>This page isn’t working</p> <p>127.0.0.1 is currently unable to handle this request.</p> <p>HTTP ERROR 500</p> <p>///////////////////////////////////////////////////////////////</p> <p>Like i said, I'm new to laravel, i didn't do much but i tried to read some similar issues but didn't find any solution to this problem since i don't understand it and I'm kind of confused and don't want to mess it up.</p> <p>so please help!</p>
[ { "answer_id": 74635039, "author": "regex", "author_id": 9470979, "author_profile": "https://Stackoverflow.com/users/9470979", "pm_score": 1, "selected": false, "text": "@Entity\ndata class Text(\n @PrimaryKey val id: Long,\n val metadata: TextMetadata,\n val textContent: String\n)\n\n@Embedded\ndata class TextMetadata(\n val author: String,\n val title: String\n)\n\n Text TextMetadata TextMetadata" }, { "answer_id": 74662979, "author": "Benjamin Woolston", "author_id": 20188398, "author_profile": "https://Stackoverflow.com/users/20188398", "pm_score": 0, "selected": false, "text": "@Entity\ndata class TextMetadata(\n val author: String,\n val title: String,\n // more associated metadata\n val textContentId: Long\n)\n\n@Entity\ndata class TextContent(\n @PrimaryKey val id: Long,\n val textContent: String\n)\n\ndata class TextWithContent(\n @Embedded val metadata: TextMetadata,\n @Relation(parentColumn = \"textContentId\", entityColumn = \"id\")\n val textContent: TextContent\n)\n\n@Dao\ninterface TextDao {\n @Query(\"SELECT * FROM text_metadata LEFT JOIN text_content ON text_metadata.textContentId = text_content.id\")\n fun getAllTexts(): List<TextWithContent>\n}\n" }, { "answer_id": 74680379, "author": "ymz", "author_id": 4062197, "author_profile": "https://Stackoverflow.com/users/4062197", "pm_score": 0, "selected": false, "text": "mongo db noSQL sqLite android room sqLite android APIs Text sqLite android room object LargeDataContract {\n // all tables for handling large data will be defined here\n\n object TextEntry : BaseColumns {\n const val TABLE_NAME = \"text_entry\"\n const val COLUMN_NAME_KEY = \"key\"\n const val COLUMN_NAME_VALUE = \"value\"\n }\n}\n\n// in the future - append this \"create statement\" whenever you add more tables to your database\nprivate const val SQL_CREATE_ENTRIES =\n \"CREATE TABLE ${TextEntry.TABLE_NAME} (\" +\n \"${TextEntry.COLUMN_NAME_KEY} INTEGER PRIMARY KEY,\" +\n \"${TextEntry.COLUMN_NAME_VALUE} TEXT)\"\n\n// create a helper that will assist you to initiate your database properly\nclass LargeDataDbHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {\n override fun onCreate(db: SQLiteDatabase) {\n db.execSQL(SQL_CREATE_ENTRIES)\n }\n \n companion object {\n // If you change the database schema, you must increment the database version. Also - please read `sqLite` documentation to better understand versioning ,upgrade and downgrade operations\n const val DATABASE_VERSION = 1\n const val DATABASE_NAME = \"LargeData.db\"\n }\n}\n\n// create an instance and connect to your database\nval dbHelper = LargeDataDbHelper(context)\n\n// write an item to your database\nval db = dbHelper.writableDatabase\n\nval values = ContentValues().apply {\n put(TextEntry.COLUMN_NAME_VALUE, \"some long value goes here\")\n}\n\nval key = db?.insert(TextEntry.TABLE_NAME, null, values)\n\n// now take the key variable and store it in you entity. this is the only reference you should need\n android APIs" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17677690/" ]
74,588,275
<p>Imagine the following example Strings</p> <ol> <li>‘John @ Mary John v Mary John vs Mary’</li> <li>‘John v Mary Ben v Paul John v Mary’</li> <li>‘Hello World / John v Mary John @ Mary John vs Mary’</li> <li>‘John v Mary John vs Mary John @ Mary John v Mary’</li> </ol> <p>There are 3 identified delimiters</p> <ul> <li>' @ '</li> <li>' v '</li> <li>' vs '</li> </ul> <p>For every field row in my file, I would like to iterate through each delimiter, look left and right by 4 characters, concatenate left and right together, and return the count should all concatenated substrings match.</p> <ol> <li>we would end up finding 'JohnMary' 3 times. Return = 3</li> <li>we would end up finding 'JohnMary','BenPaul' and 'JohnMary'. Return = 0</li> <li>we would end up finding 'JohnMary' 3 times. <em>note the Hello World is irrelevant as we only look 4 characters left and right</em>. Return = 3</li> <li>we would end up finding 'JohnMary' 4 times. Return = 4</li> </ol> <p>For this I'll need some sort recursive/loop query to iterate through each delimiter in each row, and count the number of matched substrings.</p> <ul> <li>note, if the first 2 substrings encountered aren't a match, we don't need to continue checking any further and can return 0 (like in example 2)</li> </ul>
[ { "answer_id": 74588889, "author": "Ulisse Rubizzo", "author_id": 4412510, "author_profile": "https://Stackoverflow.com/users/4412510", "pm_score": 1, "selected": false, "text": "!/usr/bin/python3\n\nimport re\nfrom copy import deepcopy\nfrom typing import List, Tuple, Union\n\ndef count_match(s: str, d: List[str]) -> Tuple[Union[None, str], int, int]:\n\n if len(s) == 0:\n return None, 0, 0\n\n counter = dict()\n offset = 0\n for each in d:\n match = re.search(each, s)\n if match is None:\n break\n idx = match.start()\n sub_string1 = s[idx-4: idx]\n sub_string2 = s[idx+len(each): idx+len(each)+4]\n sub_string = ''.join((sub_string1, sub_string2))\n offset = max(offset, idx+len(each)+4)\n try:\n counter[sub_string] += 1\n except KeyError:\n counter[sub_string] = 1\n if not len(counter):\n return None, 0, 0\n if len(counter.keys()) > 1:\n return None, -1, 0\n return sub_string, list(counter.values())[0], offset\n\n\nif __name__ == '__main__':\n text = 'John @ Mary John v Mary John vs Mary John @ Mary'\n delimiter = [' @ ', ' v ', ' vs ']\n count = 0\n ref_string = \"\"\n while text:\n string, partial, start = count_match(text, delimiter)\n if string != ref_string and ref_string != \"\":\n count = 0\n break\n if partial == -1:\n count = 0\n break\n if partial == 0:\n break\n ref_string = string\n count += partial\n text = text[start:]\n\n print(count)\n" }, { "answer_id": 74597229, "author": "Drewbty", "author_id": 18848633, "author_profile": "https://Stackoverflow.com/users/18848633", "pm_score": 0, "selected": false, "text": "text = '''\\\nJohn @ Mary John v Mary John vs Mary\nJohn v Mary Ben v Paul John v Mary\nHello World / John v Mary John @ Mary John vs Mary\nJohn v Mary John vs Mary John @ Mary John v Mary\n'''\n\nfrom collections import defaultdict\n\nimport re\npattern = re.compile('(.{4})( @ | v | vs )(.{4})')\n\nfor line in text.splitlines():\n found = defaultdict(lambda: 0)\n\n for before, sep, after in pattern.findall(line):\n key = before, sep, after\n found[before + after] += 1\n\n if len(found) == 1 and sum(found.values()) > 1:\n print(list(found.values())[0])\n else:\n print(0)\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18848633/" ]
74,588,293
<p>I want to add new column to see exam differences in a percentage value.</p> <pre><code>import pandas as pd exam_1 = { 'Name': ['Jonn', 'Tomas', 'Fran', 'Olga', 'Veronika', 'Stephan'], 'Mat': [85, 75, 50, 93, 88, 90], 'Science': [96, 97, 99, 87, 90, 88], 'Reading': [80, 60, 72, 86, 84, 77], 'Wiritng': [78, 82, 88, 78, 86, 82], 'Lang': [77, 79, 77, 72, 90, 92], } exam_2 = { 'Name': ['Jonn', 'Tomas', 'Fran', 'Olga', 'Veronika', 'Stephan'], 'Mat': [80, 80, 90, 90, 85, 80], 'Science': [50, 60, 85, 90, 66, 82], 'Reading': [60, 75, 55, 90, 85, 60], 'Wiritng': [56, 66, 90, 82, 60, 80], 'Lang': [80, 78, 76, 90, 77, 66], } df_1 = pd.DataFrame(exam_1) df_2 = pd.DataFrame(exam_2) #cmp = pd.merge(df_1, df_2, how=&quot;outer&quot;, on=[&quot;Name&quot;], suffixes=(&quot;_1&quot;, &quot;_2&quot;)) cmp = pd.merge( df_1, df_2, how=&quot;outer&quot;, on=[&quot;Name&quot;], suffixes=(&quot;_1&quot;, &quot;_2&quot;)).set_index(&quot;Name&quot;).sort_index(axis=1).reset_index() print(cmp) </code></pre> <p>The output of the above code is like below;</p> <pre><code> Name Lang_1 Lang_2 Mat_1 Mat_2 Reading_1 Reading_2 Science_1 Science_2 Wiritng_1 Wiritng_2 0 Jonn 77 80 85 80 80 60 96 50 78 56 1 Tomas 79 78 75 80 60 75 97 60 82 66 2 Fran 77 76 50 90 72 55 99 85 88 90 3 Olga 72 90 93 90 86 90 87 90 78 82 4 Veronika 90 77 88 85 84 85 90 66 86 60 5 Stephan 92 66 90 80 77 60 88 82 82 80 </code></pre> <p>What I want is that, add new column after compared value, is there any built-in function for that one. Because constant section like Name can be change, maybe 3 column can be constant in the future. I want to use built-in function to use reusability.</p> <p>I try to use it manually but it is not reusable.</p> <p>What I want exactly in below;</p> <pre><code> Name Lang_1 Lang_2 Lang_Res Mat_1 Mat_2 Mat_Res Reading_1 Reading_2 Reading_Res Science_1 Science_2 Science_Res Writing_1 Writing_2 Writing_Res 0 Jonn 77 80 Lang_data 85 80 Mat_data 80 60 Reading_data 96 50 Science_data 78 56 Writing_data 1 Tomas 79 78 Lang_data 75 80 Mat_data 60 75 Reading_data 97 60 Science_data 82 66 Writing_data 2 Fran 77 76 Lang_data 50 90 Mat_data 72 55 Reading_data 99 85 Science_data 88 90 Writing_data 3 Olga 72 90 Lang_data 93 90 Mat_data 86 90 Reading_data 87 90 Science_data 78 82 Writing_data 4 Veronika 90 77 Lang_data 88 85 Mat_data 84 85 Reading_data 90 66 Science_data 86 60 Writing_data 5 Stephan 92 66 Lang_data 90 80 Mat_data 77 60 Reading_data 88 82 Science_data 82 80 Writing_data </code></pre>
[ { "answer_id": 74588408, "author": "Mike L", "author_id": 10008247, "author_profile": "https://Stackoverflow.com/users/10008247", "pm_score": 0, "selected": false, "text": "prefixes = ['Lang', 'Mat', 'Reading', ...]\n _1 _2 for prefix in prefixes:\n column1 = df[f\"{prefix}_1\"]\n column2 = df[f\"{prefix}_2\"]\n averaged = (column1 + column2) / 2\n df.loc[:, f\"{prefix}_average\"] = averaged\n" }, { "answer_id": 74589034, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": 2, "selected": true, "text": "_2 pandas.DataFrame.insert pandas.Index.get_loc edge_cols= cmp.columns.str.extractall(\"(\\w+_2)\")[0].tolist()\n\n[cmp.insert(cmp.columns.get_loc(col)+1, col.split(\"_\")[0]+\"_Res\", col.split(\"_\")[0]+\"_Data\") for col in edge_cols]\n print(cmp.to_string())\n\n Name Lang_1 Lang_2 Lang_Res Mat_1 Mat_2 Mat_Res Reading_1 Reading_2 Reading_Res Science_1 Science_2 Science_Res Wiritng_1 Wiritng_2 Wiritng_Res\n0 Jonn 77 80 Lang_Data 85 80 Mat_Data 80 60 Reading_Data 96 50 Science_Data 78 56 Wiritng_Data\n1 Tomas 79 78 Lang_Data 75 80 Mat_Data 60 75 Reading_Data 97 60 Science_Data 82 66 Wiritng_Data\n2 Fran 77 76 Lang_Data 50 90 Mat_Data 72 55 Reading_Data 99 85 Science_Data 88 90 Wiritng_Data\n3 Olga 72 90 Lang_Data 93 90 Mat_Data 86 90 Reading_Data 87 90 Science_Data 78 82 Wiritng_Data\n4 Veronika 90 77 Lang_Data 88 85 Mat_Data 84 85 Reading_Data 90 66 Science_Data 86 60 Wiritng_Data\n5 Stephan 92 66 Lang_Data 90 80 Mat_Data 77 60 Reading_Data 88 82 Science_Data 82 80 Wiritng_Data\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3278860/" ]
74,588,306
<p>How do you change the values in a data.table column within a function?</p> <pre><code>DF = data.table(ID = c(&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;a&quot;,&quot;a&quot;,&quot;c&quot;), a = 1:6, b = 7:12, c = 13:18) change_it &lt;- function(data_table) { data_table[[column]] &lt;- 73 } column = 'a' change_it(DF, column) # Nothing happens because data_table is not a reference (or something) DF[[column]] &lt;- 73 # The change happens </code></pre>
[ { "answer_id": 74588449, "author": "AturSams", "author_id": 984975, "author_profile": "https://Stackoverflow.com/users/984975", "pm_score": 2, "selected": false, "text": "DF = data.table(ID = c(\"b\",\"b\",\"b\",\"a\",\"a\",\"c\"), a = 1:6, b = 7:12, c = 13:18)\n\nchange_it <- function(data_table) {\n data_table[, c('a') := 73]\n}\n\nchange_it(DF) # The change occured\n" }, { "answer_id": 74589960, "author": "B. Christian Kamgang", "author_id": 10848898, "author_profile": "https://Stackoverflow.com/users/10848898", "pm_score": 0, "selected": false, "text": "change_it <- function(data_table) {\n set(data_table, j=\"a\", value=73)\n}\n\n# apply the change\nchange_it(DF)\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/984975/" ]
74,588,308
<p>I have a file which contains string, from every string I need to append to my list every 2 digit number. Here's the file content: <a href="https://pastebin.com/N6gHRaVA" rel="nofollow noreferrer">https://pastebin.com/N6gHRaVA</a></p> <p>I need to iterate every string and check if string on index[i] and on index[i+1] is digit, if yes, append those digits to list and slice the string from those 2 digits number,</p> <p>for example the string:</p> <p>string = '7469NMPLWX8384RXXOORHKLYBTVVXKKSRWEITLOCWNHNOAQIXO' should work in this way:</p> <ol> <li>Okay I have found digit 74, add 74 to my list and slice the string from 74 to the end</li> <li>My string is now 69NMPLWX8384RXXOORHKLYBTVVXKKSRWEITLOCWNHNOAQIXO, I have found digit 69,add 69 to list and slice the string until I will find new 2-number digit. The problem is I always have error:</li> </ol> <pre><code> if string[i].isdigit() and string[i+1].isdigit(): ~~~~~~^^^^^ IndexError: string index out of range </code></pre> <pre><code>f = open(&quot;file.txt&quot;) read = f.read().split() f.close() for string in read: l = list() i = 0 print(string) while i&lt;len(string): if string[i].isdigit() and string[i+1].isdigit(): l.append(string[i] + string[i+1]) string = string[i+2:] i = 0 else: i+=1 </code></pre> <p>My program stops at string in line 31, which is the string: 'REDOHGMDPOXKFMHUDDOMLDYFAFYDLMODDUHMFKXOPDMGHODER5'</p> <p>I have no idea how to do this slice iteration, and please, don't use regex.</p>
[ { "answer_id": 74588392, "author": "Ni3dzwi3dz", "author_id": 12768056, "author_profile": "https://Stackoverflow.com/users/12768056", "pm_score": 0, "selected": false, "text": " while i < len(string) -1:" }, { "answer_id": 74588489, "author": "GaryMBloom", "author_id": 3159059, "author_profile": "https://Stackoverflow.com/users/3159059", "pm_score": 1, "selected": false, "text": " while i<len(string):\n while i<len(string)-1:\n while" }, { "answer_id": 74588524, "author": "ScottC", "author_id": 20174226, "author_profile": "https://Stackoverflow.com/users/20174226", "pm_score": 1, "selected": true, "text": "my_string = '7469NMPLWX8384RXXOORHKLYBTVVXKKSRWEITLOCWNHNOAQIXO'\nresult_list = []\n\ndef read_string(s):\n result = \"\"\n for i,j in enumerate(s):\n if i>0 and s[i-1].isdigit() and s[i].isdigit():\n result = s[i-1] + s[i]\n result_list.append(result)\n read_string(s[i+1:])\n break;\n \n return (result_list) \n \n# Call the read_string function\nx = read_string(my_string) \nprint(x) \n ['74', '69', '83', '84']\n" }, { "answer_id": 74588583, "author": "Michael Gathara", "author_id": 11009561, "author_profile": "https://Stackoverflow.com/users/11009561", "pm_score": 0, "selected": false, "text": "while I < len(string) - 1:\n f = open(\"file.txt\")\nread = f.read().split()\nf.close()\nfor string in read:\n l = list()\n i = 0\n print(string)\n while i < len(string) - 1:\n numCheck = i + 1 # You call it more than once. Set to var\n ltr = string[i] + string[numCheck] # no need to call this multiple times, just set to a var\n if ltr.isdigit():\n l.append(ltr)\n string = string[numCheck:]\n i = 0\n else:\n i += 1\n \nprint(l)\n f = open(\"file.txt\")\nread = f.read().split()\nf.close()\nl = list()\nfor string in read:\n i = 0\n print(string)\n while i < len(string) - 1:\n numCheck = i + 1 # You call it more than once. Set to var\n ltr = string[i] + string[numCheck] # no need to call this multiple times, just set to a var\n if ltr.isdigit():\n l.append(ltr)\n string = string[numCheck:]\n i = 0\n else:\n i += 1\n \nprint(l)\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19370936/" ]
74,588,318
<p><strong>Context</strong>: In a Vaadin 23.2.8 form there is a TextField and a Button.</p> <p><strong>What I want to do / expected behavior</strong>: In the ValueChangeListener of the TextField there should open a dialog. The dialog should be visible until the user closes it. The button should execute in the background (or after the user closes the dialog, which would also be fine).</p> <p><strong>Unexpected behavior</strong>: When a user types something into the TextField and clicks at the button, then the dialog pops up and vanishes after a fraction of a second. And the button is not executed.</p> <p><strong>What does work</strong>: When the user types something into the TextField, then leaves the TextField (by clicking somewhere outside the TextField) and then clicks the button, everything works as expected.</p> <p><strong>Code / Small reproducible example</strong>:</p> <pre><code>@Route(&quot;sandbox&quot;) public class SandboxView extends VerticalLayout { public SandboxView() { TextField textfield = new TextField(&quot;1. Type something&quot;); textfield.addValueChangeListener(event -&gt; { new Dialog(new Text(&quot;Some text in dialog&quot;)).open(); }); this.add(textfield); Button button = new Button(&quot;2. Click me&quot;); button.addThemeVariants(ButtonVariant.LUMO_PRIMARY); button.setDisableOnClick(true); button.addClickListener(event -&gt; { System.out.println(&quot;Button was clicked&quot;); button.setEnabled(true); }); this.add(button); } } </code></pre> <p><strong>Questions</strong>:</p> <ol> <li>Is it forbidden to open a Dialog in a ValueChangeListener in Vaadin?</li> <li>What can I do to get the expected behavior?</li> </ol>
[ { "answer_id": 74597602, "author": "Leif Åstrand", "author_id": 2376954, "author_profile": "https://Stackoverflow.com/users/2376954", "pm_score": 1, "selected": false, "text": "setCloseOnOutsideClick" }, { "answer_id": 74674771, "author": "S. Doe", "author_id": 10318272, "author_profile": "https://Stackoverflow.com/users/10318272", "pm_score": 1, "selected": true, "text": "Notification Dialog dialog.setCloseOnOutsideClick(false) setDisableOnClick(true) setEnabled(true) Details Notification" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10318272/" ]
74,588,319
<p>I have weekly data starting from week 2 in the year 2015 till week 9 in 2016, after fitting and plotting my forecast, The x-axis doesn't make sense. How can I share x-axis values in terms of months/week#. Thank you</p> <p><img src="https://i.stack.imgur.com/qxLGq.png" alt="Current Forecast Plot " /></p> <pre><code>TS1&lt;-ts(DUMMYDATA,frequency =52,start = c(2015,02),end = c(2016,09)) </code></pre> <p>I tried creating my own x-axis but I am not able to reflect it correctly in terms of Time components</p>
[ { "answer_id": 74597602, "author": "Leif Åstrand", "author_id": 2376954, "author_profile": "https://Stackoverflow.com/users/2376954", "pm_score": 1, "selected": false, "text": "setCloseOnOutsideClick" }, { "answer_id": 74674771, "author": "S. Doe", "author_id": 10318272, "author_profile": "https://Stackoverflow.com/users/10318272", "pm_score": 1, "selected": true, "text": "Notification Dialog dialog.setCloseOnOutsideClick(false) setDisableOnClick(true) setEnabled(true) Details Notification" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20612419/" ]
74,588,325
<p>I have a decorator that define property a class with a getter that return an <code>Observable</code> and setter that emit new value on subject.</p> <pre><code>import { Subject } from &quot;rxjs&quot;; export const defineDecorator = () =&gt; { return (target: object, propertyKey: string) =&gt; { Object.defineProperty(target, propertyKey, { const sub = new Subject(); const obs = sub.asObservable(); get: (): any =&gt; { return obs; }, set: (value: any) =&gt; { sub.next(value); }, enumerable: true, configurable: true, }); } }; </code></pre> <p>I want specify in typescript, &quot;value&quot; propery is <code>Observable&lt;string&gt;</code> on &quot;get&quot; and <code>string</code> on &quot;set&quot;:</p> <pre><code>export class MyComponent { @defineDecorator() value!: any; // instead of any.. what type? } </code></pre> <p>what type for &quot;value&quot;?</p>
[ { "answer_id": 74597602, "author": "Leif Åstrand", "author_id": 2376954, "author_profile": "https://Stackoverflow.com/users/2376954", "pm_score": 1, "selected": false, "text": "setCloseOnOutsideClick" }, { "answer_id": 74674771, "author": "S. Doe", "author_id": 10318272, "author_profile": "https://Stackoverflow.com/users/10318272", "pm_score": 1, "selected": true, "text": "Notification Dialog dialog.setCloseOnOutsideClick(false) setDisableOnClick(true) setEnabled(true) Details Notification" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3043248/" ]
74,588,330
<p>So i'm very new with javascript and been trying to make a function code that only work only once.</p> <p>this is my logo that i've been trying to animate it.</p> <pre><code>&lt;img src=&quot;img/logot2.png&quot; id=&quot;logoutjs&quot; onmouseover=&quot;move()&quot; alt=&quot;Logo&quot; width=&quot;100&quot; height=&quot;30&quot; class=&quot;d-inline-block align-text-top&quot; style=&quot;position: absolute; right: 8px;&quot; &gt; </code></pre> <p>and this is the javascript.</p> <pre><code>&lt;script&gt; var id = null; function move() { var elem = document.getElementById(&quot;logoutjs&quot;); var pos = 0; clearInterval(id); id = setInterval(frame, 5); function frame() { if (pos == -110) { clearInterval(id); } else { pos--; elem.style.left = pos + 'px'; } } move(){}; } &lt;/script&gt; </code></pre>
[ { "answer_id": 74597602, "author": "Leif Åstrand", "author_id": 2376954, "author_profile": "https://Stackoverflow.com/users/2376954", "pm_score": 1, "selected": false, "text": "setCloseOnOutsideClick" }, { "answer_id": 74674771, "author": "S. Doe", "author_id": 10318272, "author_profile": "https://Stackoverflow.com/users/10318272", "pm_score": 1, "selected": true, "text": "Notification Dialog dialog.setCloseOnOutsideClick(false) setDisableOnClick(true) setEnabled(true) Details Notification" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17124106/" ]
74,588,331
<pre class="lang-java prettyprint-override"><code>import java.math.BigDecimal; public class test { public static void main(String[] args) { BigDecimal b1 = new BigDecimal(&quot;0.1&quot;); BigDecimal b2 = new BigDecimal(&quot;0.2&quot;); System.out.println(b1.multiply(b2)); // the result is 0.02 System.out.println(b1.multiply(b2).equals(&quot;0.02&quot;)); // boolean is false System.out.println(b1.add(b2)); //the result is 0.3 System.out.println(b1.add(b2).equals(&quot;0.3&quot;)); // boolean is false } } </code></pre> <p>I don't know why the .equals result is always false. How to use BigDecimal .equals() in Java?</p>
[ { "answer_id": 74588378, "author": "jurez", "author_id": 8338100, "author_profile": "https://Stackoverflow.com/users/8338100", "pm_score": 3, "selected": true, "text": "BigDecimal String b1.add(b2).equals(\"0.3\")\n b1.add(b2).equals(new BigDecimal(\"0.3\"))\n" }, { "answer_id": 74588389, "author": "Vedant Kakade", "author_id": 20530242, "author_profile": "https://Stackoverflow.com/users/20530242", "pm_score": 1, "selected": false, "text": " BigDecimal b1 = new BigDecimal(\"0.1\");\n BigDecimal b2 = new BigDecimal(\"0.2\");\n System.out.println(b1.multiply(b2)); // the result is 0.02\n System.out.println(b1.multiply(b2).equals(new BigDecimal(\"0.02\"))); // boolean is true as two same datatype objects are compared and both are equal.\n System.out.println(b1.add(b2)); //the result is 0.3\n System.out.println(b1.add(b2).equals(\"0.3\")); // boolean is false because you are trying to compare a string and BigDecimal\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20612399/" ]
74,588,381
<p>I'm trying to randomly order widgets that will appear in a column.</p> <pre><code>Widget build(BuildContext context){ return Column( children: [ Question( questions[questionIndex]['singular'], ), ...(questions[questionIndex]['answers'] as List&lt;Map&lt;String, Object&gt;&gt;).map((answer) { return Answer(() =&gt; answerQuestion(answer['score']), answer['text']); }).toList() ], ); } </code></pre> <p>I want to shuffle the part of the widget that starts <code>...(questions[questionIndex]...</code> but when I do this bu adding <code>.shuffle()</code> to the list to get this error <code>Spread elements in list or set literals must implement 'Iterable'.</code> I've also tried moving the shuffling to an initState method but then the app builds but I see errors on the screen when I run the app. (<code>NoSuchMethodError: 'shuffle'</code>). Does anyone know how I can order this list of widgets randomly?</p>
[ { "answer_id": 74588414, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 3, "selected": true, "text": "Widget build(BuildContext context) {\n var answers = (questions[questionIndex]['answers'] as List<Map<String, Object>>);\n answers.shuffle();\n return Column(\n children: [\n Question(\n questions[questionIndex]['singular'],\n ),\n ...answers\n .map((answer) {\n return Answer(() => answerQuestion(answer['score']), answer['text']);\n }).toList()\n ],\n );\n }\n" }, { "answer_id": 74588460, "author": "OMi Shah", "author_id": 5882307, "author_profile": "https://Stackoverflow.com/users/5882307", "pm_score": 1, "selected": false, "text": "...((questions[questionIndex]['answers'] as List<Map<String, Object>>)..shuffle())\n Column(\n children: [\n Question(\n questions[questionIndex]['singular'],\n ),\n ...((questions[questionIndex]['answers'] as List<Map<String, Object>>)\n ..shuffle())\n .map((answer) {\n return Answer(() => answerQuestion(answer['score']), answer['text']);\n }).toList()\n ],\n)\n" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11578282/" ]
74,588,453
<pre><code>import tkinter global win1,win2, win3 def win1_open(): global win1 win1 = tkinter.Tk() win1.geometry('500x500') button_next = tkinter.Button(win1, text='Next', width=8, command=win2_open) button_next.place(x=100 * 2 + 80, y = 100) win1.mainloop() def win2_open(): global win2 win2 = tkinter.Tk() win2.geometry('500x500') button_next = tkinter.Button(win2, text='Next', width=8, command=win3_open) button_next.place(x=100 * 2 + 80, y=100) win2.mainloop() def win3_open(): global win3 win3 = tkinter.Tk() win3.geometry('500x500') button_exit = tkinter.Button(win3, text='Exit', width=8, command=exit_program) button_exit.place(x=100 * 2 + 80, y=100) win3.mainloop() def exit_program(): global win1, win2, win3 win1.quit() win2.quit() win3.quit() win1_open() </code></pre> <p>The third window has Exit button that I have used to terminate the program. It terminates the program but only after I click Exit button thrice. How to terminate the program on one button click?</p>
[ { "answer_id": 74588833, "author": "Wang Ting an", "author_id": 18938661, "author_profile": "https://Stackoverflow.com/users/18938661", "pm_score": 1, "selected": false, "text": "quit() destory() def exit_program():\n global win1, win2, win3\n win1.destroy()\n win2.destroy()\n win3.destroy()\n" }, { "answer_id": 74592811, "author": "GaryMBloom", "author_id": 3159059, "author_profile": "https://Stackoverflow.com/users/3159059", "pm_score": 0, "selected": false, "text": "exit_program() .destroy() .quit() .mainloop()" } ]
2022/11/27
[ "https://Stackoverflow.com/questions/74588453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13993793/" ]