qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,617,819
|
<p>This is a code that prompts the user for the amount of months they want to budget analyze, prompts for the budget the user has, prompts for how much the user spent that month, and then calculates if the user is over or under their budget. When code is run, it prompts user one twice, and then creates errors:</p>
<pre class="lang-py prettyprint-override"><code> Traceback (most recent call last):
File "C:\Users\\Desktop\", line 53, in <module>
main()
File "C:\Users\\Desktop\", line 51, in main
AnalyzeBudget(months)
File "C:\Users\\Desktop\", line 46, in AnalyzeBudget
MoBudget,MoSpent = GetMonthBudgetandSpent(month)
File "C:\Users\\Desktop\", line 40, in GetMonthBudgetandSpent
return int(Mobudget, MoSpent)
TypeError: 'str' object cannot be interpreted as an integer
</code></pre>
<p>any help is appreciated.</p>
<pre><code>def DescribeProgram():
print("""\
This program uses a for loop to monitor your budget.
The program will prompt you to enter your budget, and amount spent
for a certain month and calculate if your were under or over budget.
You will have the option of choosing how many months you would like to
monitor.\n""")
def GetMonths():
Months = input("Enter the number of months you want to analyze")
return int(Months)
def GetMonthBudgetandSpent(month):
Mobudget = input("Enter the budget you have for the month")
MoSpent = input("Enter the amount you spent this month")
return int(Mobudget, MoSpent)
def AnalyzeBudget(months):
for month in range(1,months+1):
print("\nMonth",month,":")
print("=======")
MoBudget,MoSpent = GetMonthBudgetandSpent(month)
def main():
DescribeProgram()
months = GetMonths()
AnalyzeBudget(months)
main()
</code></pre>
|
[
{
"answer_id": 74629506,
"author": "Gaz83",
"author_id": 1255136,
"author_profile": "https://Stackoverflow.com/users/1255136",
"pm_score": 0,
"selected": false,
"text": "string invite_policy = builder.Configuration.GetSection(\"AzureAdB2C\")[\"SignUpSignInPolicyId\"];\nbuilder.Services.AddAuthentication(options => {\n options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;\n options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;\n})\n.AddOpenIdConnect(invite_policy, GetOpenIdSignUpOptions(invite_policy, builder.Configuration))\n.AddMicrosoftIdentityWebApp(options =>{ \n\nbuilder.Configuration.Bind(\"AzureAd\", options);\n\noptions.ResponseType = OpenIdConnectResponseType.IdToken;\n\noptions.Events = new CustomOpenIdConnectEvents();\noptions.DataProtectionProvider = protector;\n\n// Thanks to Nan Yu for the folowing to fix the null name after login\n//https://stackoverflow.com/questions/54444747/user-identity-name-is-null-after-federated-azure-ad-login-with-aspnetcore-2-2\noptions.TokenValidationParameters = new TokenValidationParameters() { NameClaimType = \"name\" };\n\n}, subscribeToOpenIdConnectMiddlewareDiagnosticsEvents: true); // don't need this, for debugging.\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20391565/"
] |
74,617,836
|
<p>I am getting the following warning:</p>
<p>warning: incompatible pointer types passing 'char (<em>)' to parameter of type 'char (</em>)[5]' [-Wincompatible-pointer-types]
printField(field[5]);</p>
<p>The printField function looks like this:</p>
<pre><code>void printField(char (*field)[5])
{
...
}
</code></pre>
<p>and the field I am giving to it is defined as follows:</p>
<pre><code>char (*field) = get_field(input);
</code></pre>
<p>Here is the function call:</p>
<pre><code>printField(field);
</code></pre>
<p>Now, I do understand, that there is obviously some sort of mismatch happening, but I can't tell what to change for it not to be there anymore. I would appreciate it very much, if someone could help me.</p>
|
[
{
"answer_id": 74617945,
"author": "Some programmer dude",
"author_id": 440558,
"author_profile": "https://Stackoverflow.com/users/440558",
"pm_score": 1,
"selected": false,
"text": "get_field char s[5];\n &a[0] &s &s[0] char * &s char (*)[5] field printField char * void printField(char *field);\n"
},
{
"answer_id": 74617950,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 0,
"selected": false,
"text": "char *ptr; char char (*ptr)[5];"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10795491/"
] |
74,617,838
|
<p>I have a CSV file like this</p>
<pre><code>>cat test.in
1|aaa|bbb
1|ccc|ddd
2|xxx|yyy
2|www|zzz
2|www|ttt
</code></pre>
<p>and I want to split it in separate files:</p>
<ul>
<li>the naming convention should be <code>prefix.FIELD1.FIELD2.out</code></li>
<li>FIELD1 should not be in the output file</li>
<li>every output file should have a header</li>
</ul>
<p>Is there a neat way to do it in one go with <code>awk</code>?</p>
<p>So far I've managed to have <code>awk</code> create the output files but I can't make it add the header, so I just loop over the output files and add it afterwards</p>
<pre><code>>cat script.sh
#!/bin/bash
FIELD_SEPARATOR="|"
OUTPUT_HEADER="Key|Value"
awk '{FS=OFS="'${FIELD_SEPARATOR}'"; print $2,$3> "prefix." $1 "." $2 ".out"}' test.in
# add the header to all the output files
echo $OUTPUT_HEADER > header
for filename in $(ls prefix.*.out 2>/dev/null); do
cat header $filename > $filename.tmp && mv $filename.tmp $filename
done
rm header
</code></pre>
<p>which gives the expected output</p>
<pre><code>>ls prefix.*.out
prefix.1.aaa.out prefix.1.ccc.out prefix.2.www.out prefix.2.xxx.out
>cat prefix.1.aaa.out
Key|Value
aaa|bbb
>cat prefix.1.ccc.out
Key|Value
ccc|ddd
>cat prefix.2.www.out
Key|Value
www|zzz
www|ttt
>cat prefix.2.xxx.out
Key|Value
xxx|yyy
</code></pre>
|
[
{
"answer_id": 74619508,
"author": "Paul Hodges",
"author_id": 8656552,
"author_profile": "https://Stackoverflow.com/users/8656552",
"pm_score": 1,
"selected": false,
"text": "for filename in $(ls prefix.*.out 2>/dev/null)\n for filename in prefix.*.out\n awk $: awk -v sep='|' 'BEGIN{FS=OFS=sep} { f=\"prefix.\"$1\".\"$2\".out\"; print \"Key\",\"Value\" > f; print $2,$3 > f; }' test.in\n\n$: grep . prefix*\nprefix.1.aaa.out:Key|Value\nprefix.1.aaa.out:aaa|bbb\nprefix.1.ccc.out:Key|Value\nprefix.1.ccc.out:ccc|ddd\nprefix.2.www.out:Key|Value\nprefix.2.www.out:www|zzz\nprefix.2.www.out:Key|Value\nprefix.2.www.out:www|ttt\nprefix.2.xxx.out:Key|Value\nprefix.2.xxx.out:xxx|yyy\n $: awk -v sep='|' 'BEGIN{FS=OFS=sep} { f=\"prefix.\"$1\".\"$2\".out\"; if (!header[f]) { header[f]=1; print \"Key\",\"Value\" > f; } print $2,$3 > f; }' test.in\n\n$: grep . prefix*\nprefix.1.aaa.out:Key|Value\nprefix.1.aaa.out:aaa|bbb\nprefix.1.aaa.out:aaa|bbb\nprefix.1.aaa.out:aaa|bbb\nprefix.1.ccc.out:Key|Value\nprefix.1.ccc.out:ccc|ddd\nprefix.1.ccc.out:ccc|ddd\nprefix.1.ccc.out:ccc|ddd\nprefix.2.www.out:Key|Value\nprefix.2.www.out:www|zzz\nprefix.2.www.out:www|ttt\nprefix.2.www.out:www|zzz\nprefix.2.www.out:www|ttt\nprefix.2.www.out:www|zzz\nprefix.2.www.out:www|ttt\nprefix.2.xxx.out:Key|Value\nprefix.2.xxx.out:xxx|yyy\nprefix.2.xxx.out:xxx|yyy\nprefix.2.xxx.out:xxx|yyy\n $: awk -v sep='|' 'BEGIN{FS=OFS=sep; lst=\"\";}\n { f=\"prefix.\"$1\".\"$2\".out\";\n if (lst !~ f) { lst=f\"\\n\"lst; print \"Key\",\"Value\" > f; }\n print $2,$3 > f; }' test.in\n"
},
{
"answer_id": 74619777,
"author": "David C. Rankin",
"author_id": 3422102,
"author_profile": "https://Stackoverflow.com/users/3422102",
"pm_score": 2,
"selected": false,
"text": "awk awk -F\"|\" '\n BEGIN { hdr=\"Key|Value\"; OFS=FS } \n NF==3 { \n ofn=\"prefix.\" $1 \".\" $2 \".out\"\n if (! (ofn in arr)) { \n print hdr > ofn \n }\n arr[ofn] = 1\n print $2,$3 >> ofn \n }\n' test.in\n awk -F\"|\" 'BEGIN {hdr=\"Key|Value\"; OFS=FS} NF==3 { ofn=\"prefix.\" $1 \".\" $2 \".out\"; if (! (ofn in arr)) { print hdr > ofn } arr[ofn] = 1; print $2,$3 >> ofn }' test.in\n $ awk -F\"|\" 'BEGIN {hdr=\"Key|Value\"; OFS=FS} NF==3 { ofn=\"prefix.\" $1 \".\" $2 \".out\"; if (! (ofn in arr)) { print hdr > ofn } arr[ofn] = 1; print $2,$3 >> ofn }' test.in\n $ l\ntotal 28\ndrwxr-xr-x 2 david david 4096 Nov 29 14:07 .\ndrwxr-xr-x 7 david david 4096 Nov 29 13:57 ..\n-rw-r--r-- 1 david david 18 Nov 29 14:07 prefix.1.aaa.out\n-rw-r--r-- 1 david david 18 Nov 29 14:07 prefix.1.ccc.out\n-rw-r--r-- 1 david david 36 Nov 29 14:07 prefix.2.www.out\n-rw-r--r-- 1 david david 18 Nov 29 14:07 prefix.2.xxx.out\n-rw-r--r-- 1 david david 50 Nov 29 13:58 test.in\n $ for i in prefix*; do printf \"\\nfile: %s\\n\" \"$i\"; cat \"$i\"; done\n\nfile: prefix.1.aaa.out\nKey|Value\naaa|bbb\n\nfile: prefix.1.ccc.out\nKey|Value\nccc|ddd\n\nfile: prefix.2.www.out\nKey|Value\nwww|zzz\nwww|ttt\n\nfile: prefix.2.xxx.out\nKey|Value\nxxx|yyy\n awk indx in arr indx in array awk indx in array awk awk --version :) awk -F\"|\" '\n BEGIN { hdr=\"Key|Value\"; OFS=FS } \n NF==3 { \n ofn = \"prefix.\" $1 \".\" $2 \".out\"\n exists = 0\n for (i=0; i<n; i++) { # loop index arr checking for ofn\n if (arr[i] == ofn) { # if already in arr\n exists = 1 # set exists flag, break\n break\n }\n }\n if (exists == 0) { # if not in arr, output header, add to arr\n print hdr > ofn\n arr[n++] = ofn\n }\n print $2,$3 >> ofn # output data to file\n }\n' test.in\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12479265/"
] |
74,617,865
|
<p>I am trying to upload a file to S3 using apps script.</p>
<p>I have been trying to use <a href="https://github.com/viuinsight/google-apps-script-for-aws" rel="nofollow noreferrer">https://github.com/viuinsight/google-apps-script-for-aws</a></p>
<pre><code>S3.init();
S3.putObject("bucket123", 'Tacofile.txt', content, 'ca-central-1')
</code></pre>
<ol>
<li>I retrieve a file from Google Workspace, where 'Tacofile' is a .txt file</li>
<li>The file successfully loads to S3</li>
</ol>
<p>The file, however, somehow gets converted to json? How to keep the file as a csv or is there a way to specify the MIME type somewhere before the upload?</p>
<p>thanks in advance</p>
<p>CB</p>
|
[
{
"answer_id": 74619508,
"author": "Paul Hodges",
"author_id": 8656552,
"author_profile": "https://Stackoverflow.com/users/8656552",
"pm_score": 1,
"selected": false,
"text": "for filename in $(ls prefix.*.out 2>/dev/null)\n for filename in prefix.*.out\n awk $: awk -v sep='|' 'BEGIN{FS=OFS=sep} { f=\"prefix.\"$1\".\"$2\".out\"; print \"Key\",\"Value\" > f; print $2,$3 > f; }' test.in\n\n$: grep . prefix*\nprefix.1.aaa.out:Key|Value\nprefix.1.aaa.out:aaa|bbb\nprefix.1.ccc.out:Key|Value\nprefix.1.ccc.out:ccc|ddd\nprefix.2.www.out:Key|Value\nprefix.2.www.out:www|zzz\nprefix.2.www.out:Key|Value\nprefix.2.www.out:www|ttt\nprefix.2.xxx.out:Key|Value\nprefix.2.xxx.out:xxx|yyy\n $: awk -v sep='|' 'BEGIN{FS=OFS=sep} { f=\"prefix.\"$1\".\"$2\".out\"; if (!header[f]) { header[f]=1; print \"Key\",\"Value\" > f; } print $2,$3 > f; }' test.in\n\n$: grep . prefix*\nprefix.1.aaa.out:Key|Value\nprefix.1.aaa.out:aaa|bbb\nprefix.1.aaa.out:aaa|bbb\nprefix.1.aaa.out:aaa|bbb\nprefix.1.ccc.out:Key|Value\nprefix.1.ccc.out:ccc|ddd\nprefix.1.ccc.out:ccc|ddd\nprefix.1.ccc.out:ccc|ddd\nprefix.2.www.out:Key|Value\nprefix.2.www.out:www|zzz\nprefix.2.www.out:www|ttt\nprefix.2.www.out:www|zzz\nprefix.2.www.out:www|ttt\nprefix.2.www.out:www|zzz\nprefix.2.www.out:www|ttt\nprefix.2.xxx.out:Key|Value\nprefix.2.xxx.out:xxx|yyy\nprefix.2.xxx.out:xxx|yyy\nprefix.2.xxx.out:xxx|yyy\n $: awk -v sep='|' 'BEGIN{FS=OFS=sep; lst=\"\";}\n { f=\"prefix.\"$1\".\"$2\".out\";\n if (lst !~ f) { lst=f\"\\n\"lst; print \"Key\",\"Value\" > f; }\n print $2,$3 > f; }' test.in\n"
},
{
"answer_id": 74619777,
"author": "David C. Rankin",
"author_id": 3422102,
"author_profile": "https://Stackoverflow.com/users/3422102",
"pm_score": 2,
"selected": false,
"text": "awk awk -F\"|\" '\n BEGIN { hdr=\"Key|Value\"; OFS=FS } \n NF==3 { \n ofn=\"prefix.\" $1 \".\" $2 \".out\"\n if (! (ofn in arr)) { \n print hdr > ofn \n }\n arr[ofn] = 1\n print $2,$3 >> ofn \n }\n' test.in\n awk -F\"|\" 'BEGIN {hdr=\"Key|Value\"; OFS=FS} NF==3 { ofn=\"prefix.\" $1 \".\" $2 \".out\"; if (! (ofn in arr)) { print hdr > ofn } arr[ofn] = 1; print $2,$3 >> ofn }' test.in\n $ awk -F\"|\" 'BEGIN {hdr=\"Key|Value\"; OFS=FS} NF==3 { ofn=\"prefix.\" $1 \".\" $2 \".out\"; if (! (ofn in arr)) { print hdr > ofn } arr[ofn] = 1; print $2,$3 >> ofn }' test.in\n $ l\ntotal 28\ndrwxr-xr-x 2 david david 4096 Nov 29 14:07 .\ndrwxr-xr-x 7 david david 4096 Nov 29 13:57 ..\n-rw-r--r-- 1 david david 18 Nov 29 14:07 prefix.1.aaa.out\n-rw-r--r-- 1 david david 18 Nov 29 14:07 prefix.1.ccc.out\n-rw-r--r-- 1 david david 36 Nov 29 14:07 prefix.2.www.out\n-rw-r--r-- 1 david david 18 Nov 29 14:07 prefix.2.xxx.out\n-rw-r--r-- 1 david david 50 Nov 29 13:58 test.in\n $ for i in prefix*; do printf \"\\nfile: %s\\n\" \"$i\"; cat \"$i\"; done\n\nfile: prefix.1.aaa.out\nKey|Value\naaa|bbb\n\nfile: prefix.1.ccc.out\nKey|Value\nccc|ddd\n\nfile: prefix.2.www.out\nKey|Value\nwww|zzz\nwww|ttt\n\nfile: prefix.2.xxx.out\nKey|Value\nxxx|yyy\n awk indx in arr indx in array awk indx in array awk awk --version :) awk -F\"|\" '\n BEGIN { hdr=\"Key|Value\"; OFS=FS } \n NF==3 { \n ofn = \"prefix.\" $1 \".\" $2 \".out\"\n exists = 0\n for (i=0; i<n; i++) { # loop index arr checking for ofn\n if (arr[i] == ofn) { # if already in arr\n exists = 1 # set exists flag, break\n break\n }\n }\n if (exists == 0) { # if not in arr, output header, add to arr\n print hdr > ofn\n arr[n++] = ofn\n }\n print $2,$3 >> ofn # output data to file\n }\n' test.in\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10409118/"
] |
74,617,957
|
<p>If I have two different JavaScript files in the HTML document. Is it possible to toggle between them according to the screen size?</p>
<p>This means script1 is turned off in desktop, script2 is on. On the smartphone, at for example 850px, script2 turns on and script1 off.</p>
<pre><code>script src="script1"></script
script src="script2"></script
</code></pre>
<p>Is there any possibility?</p>
<p>I thought about giving the script a class and use
<code>@media only screen and (max-width: 850px)</code>, but I did not come much further.</p>
|
[
{
"answer_id": 74617999,
"author": "haduki",
"author_id": 18229792,
"author_profile": "https://Stackoverflow.com/users/18229792",
"pm_score": 1,
"selected": false,
"text": "<script>\nif (screen.width > 500) {\n var head = document.getElementsByTagName('head')[0];\n var script = document.createElement('script');\n script.type = 'text/javascript';\n script.src = 'helper.js';\n head.appendChild(script);\n}\n</script>\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20554918/"
] |
74,617,963
|
<p>I'm trying to make a logo portfolio carousel that scrolls horizontally in an infinite way.</p>
<p>I almost have it done, but it will break the animation and not be seamless. I need it to be really an infinite animation with no breaks.</p>
<p><a href="https://jsfiddle.net/nha3grjL/#&togetherjs=sy1LFN4qOJ" rel="nofollow noreferrer">https://jsfiddle.net/nha3grjL/#&togetherjs=sy1LFN4qOJ</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
margin: 0;
}
.scroll {
position: relative;
width: 100vw;
background-color: $boxify-bg-light-dark;
overflow: hidden;
z-index: 1;
margin: 0;
padding: 0;
}
.m-scroll {
overflow: hidden;
height: 100%;
white-space: nowrap;
animation: scrollText 10s infinite linear;
margin: 0;
font-size: 0;
display: flex;
justify-content: space-between;
width: 250%;
}
span {
display: inline-block;
margin: 0;
padding: 0;
color: white;
}
@keyframes scrollText {
from {
transform: translateX(0%);
}
to {
transform: translateX(-50%);
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="scroll">
<div class="m-scroll">
<span><img src="https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png"></span>
<span><img src="https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png"></span>
<span><img src="https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png"></span>
<span><img src="https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png"></span>
<span><img src="https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png"></span>
<span><img src="https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png"></span>
<span><img src="https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png"></span>
<span><img src="https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png"></span>
<span><img src="https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png"></span>
<span><img src="https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png"></span>
<span><img src="https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png"></span>
<span><img src="https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png"></span>
</div>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74618135,
"author": "A Haworth",
"author_id": 10867454,
"author_profile": "https://Stackoverflow.com/users/10867454",
"pm_score": 3,
"selected": true,
"text": "body {\n margin: 0;\n}\n\n.scroll {\n position: relative;\n width: 100vw;\n background-color: $boxify-bg-light-dark;\n overflow: hidden;\n z-index: 1;\n margin: 0;\n padding: 0;\n}\n\n.m-scroll {\n overflow: hidden;\n height: 100%;\n white-space: nowrap;\n animation: scrollText 10s infinite linear;\n margin: 0;\n font-size: 0;\n display: flex;\n justify-content: space-between;\n width: fit-content;\n}\n\nspan {\n display: inline-block;\n margin: 0;\n padding: 0;\n color: white;\n}\n\n@keyframes scrollText {\n from {\n transform: translateX(0%);\n }\n to {\n transform: translateX(-50%);\n }\n} <div class=\"scroll\">\n <div class=\"m-scroll\">\n <span><img src=\"https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png\" ></span>\n <span><img src=\"https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png\"></span>\n <span><img src=\"https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png\"></span>\n <span><img src=\"https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png\"></span>\n <span><img src=\"https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png\"></span>\n <span><img src=\"https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png\"></span>\n <span><img src=\"https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png\" ></span>\n <span><img src=\"https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png\"></span>\n <span><img src=\"https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png\"></span>\n <span><img src=\"https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png\"></span>\n <span><img src=\"https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png\"></span>\n <span><img src=\"https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png\"></span>\n </div>\n</div>"
},
{
"answer_id": 74618147,
"author": "wodosharlatan",
"author_id": 20630897,
"author_profile": "https://Stackoverflow.com/users/20630897",
"pm_score": 1,
"selected": false,
"text": "@keyframes scrollText {\n 0% {\n transform: translate3d(0, 0, 0);\n }\n 100% {\n transform: translate3d(/* Your image width */, 0, 0); \n }\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3074558/"
] |
74,617,982
|
<p>This is my code:</p>
<pre><code>mapping = {"ISTJ":1, "ISTP":2, "ISFJ":3, "ISFP":4, "INFP":6, "INTJ":7, "INTP":8, "ESTP":9, "ESTJ":10, "ESFP":11, "ESFJ":12, "ENFP":13, "ENFJ":14, "ENTP":15, "ENTJ":16, "NaN": 17}
q20 = castaway_details["personality_type"]
q20["personality_type"] = q20["personality_type"].map(mapping)
</code></pre>
<p>the data frame is like this</p>
<pre><code> personality_type
0 INTP
1 INFP
2 INTJ
3 ISTJ
4 NAN
5 ESFP
</code></pre>
<p>I want the output like this:</p>
<pre><code> personality_type
0 8
1 6
2 7
3 1
4 17
5 11
</code></pre>
<p>however, what I get from my code is all NANs</p>
|
[
{
"answer_id": 74618135,
"author": "A Haworth",
"author_id": 10867454,
"author_profile": "https://Stackoverflow.com/users/10867454",
"pm_score": 3,
"selected": true,
"text": "body {\n margin: 0;\n}\n\n.scroll {\n position: relative;\n width: 100vw;\n background-color: $boxify-bg-light-dark;\n overflow: hidden;\n z-index: 1;\n margin: 0;\n padding: 0;\n}\n\n.m-scroll {\n overflow: hidden;\n height: 100%;\n white-space: nowrap;\n animation: scrollText 10s infinite linear;\n margin: 0;\n font-size: 0;\n display: flex;\n justify-content: space-between;\n width: fit-content;\n}\n\nspan {\n display: inline-block;\n margin: 0;\n padding: 0;\n color: white;\n}\n\n@keyframes scrollText {\n from {\n transform: translateX(0%);\n }\n to {\n transform: translateX(-50%);\n }\n} <div class=\"scroll\">\n <div class=\"m-scroll\">\n <span><img src=\"https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png\" ></span>\n <span><img src=\"https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png\"></span>\n <span><img src=\"https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png\"></span>\n <span><img src=\"https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png\"></span>\n <span><img src=\"https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png\"></span>\n <span><img src=\"https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png\"></span>\n <span><img src=\"https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png\" ></span>\n <span><img src=\"https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png\"></span>\n <span><img src=\"https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png\"></span>\n <span><img src=\"https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png\"></span>\n <span><img src=\"https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png\"></span>\n <span><img src=\"https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png\"></span>\n </div>\n</div>"
},
{
"answer_id": 74618147,
"author": "wodosharlatan",
"author_id": 20630897,
"author_profile": "https://Stackoverflow.com/users/20630897",
"pm_score": 1,
"selected": false,
"text": "@keyframes scrollText {\n 0% {\n transform: translate3d(0, 0, 0);\n }\n 100% {\n transform: translate3d(/* Your image width */, 0, 0); \n }\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17113383/"
] |
74,618,024
|
<p>Initially, I have this dataframe:</p>
<p><a href="https://i.stack.imgur.com/HcU9q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HcU9q.png" alt="dataframe 1" /></a></p>
<p>I save this as a csv file by using:</p>
<p><code>df.to_csv('Frequency.csv')</code></p>
<p>The problem lies with when I try to read the csv file again with:</p>
<p><code>pd.read_csv("Frequency.csv")</code></p>
<p>The dataframe then looks like this:</p>
<p><a href="https://i.stack.imgur.com/gsjRD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gsjRD.png" alt="dataframe 2" /></a></p>
<p>Why is there an extra column added and why did the index change? I suppose it has something the do with the way how you should save the dataframe as a csv file, but I am not sure.</p>
|
[
{
"answer_id": 74618130,
"author": "unltd_J",
"author_id": 13063755,
"author_profile": "https://Stackoverflow.com/users/13063755",
"pm_score": 0,
"selected": false,
"text": "df.to_csv('Frequency.csv', index=False)\n"
},
{
"answer_id": 74618170,
"author": "Ayush Raj",
"author_id": 14264760,
"author_profile": "https://Stackoverflow.com/users/14264760",
"pm_score": 2,
"selected": true,
"text": "#if you don't want to save the index column in the first place\ndf.to_csv('Frequency.csv', index=False) \n# drop the extra column if any while reading\npd.read_csv(\"Frequency.csv\",index_col=0)\n import pandas as pd\n\ndata = {\n \"calories\": [420, 380, 390],\n \"duration\": [50, 40, 45]\n}\ndf1 = pd.DataFrame(data)\n\ndf1.to_csv('calories.csv', index=False)\npd.read_csv(\"calories.csv\",index_col=0)\n df1.to_csv('calories.csv', index=False)\npd.read_csv(\"calories.csv\",index_col=0)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7081354/"
] |
74,618,038
|
<p>Im expecting to get the value of the pointer that pp is pointing to</p>
<p>this is my struct</p>
<pre><code>struct game
{
int rank;
int year;
char *name;
char *platform;
char *genre;
char *publisher;
// sales below represented in millions
float NA_sales;
float EU_sales;
float JP_sales;
float other_sales;
float global_sales;
} Game;
</code></pre>
<p>i got the array of pointer to pointer as</p>
<pre><code>struct Game **arr[MAX_NUM]; // max num is 100
</code></pre>
<p>and i assign</p>
<pre><code>arr[counter] = &new_game; // new_game is calloc as struct game *new_game = calloc(1, sizeof(struct game));
</code></pre>
<p>i tried with</p>
<pre><code>arr[counter]->publisher
</code></pre>
<p>but it return as</p>
<pre><code>'*arr[counter]' is a pointer; did you mean to use '->'?
printf("%s", arr[counter]->new_game->publisher);
</code></pre>
|
[
{
"answer_id": 74618130,
"author": "unltd_J",
"author_id": 13063755,
"author_profile": "https://Stackoverflow.com/users/13063755",
"pm_score": 0,
"selected": false,
"text": "df.to_csv('Frequency.csv', index=False)\n"
},
{
"answer_id": 74618170,
"author": "Ayush Raj",
"author_id": 14264760,
"author_profile": "https://Stackoverflow.com/users/14264760",
"pm_score": 2,
"selected": true,
"text": "#if you don't want to save the index column in the first place\ndf.to_csv('Frequency.csv', index=False) \n# drop the extra column if any while reading\npd.read_csv(\"Frequency.csv\",index_col=0)\n import pandas as pd\n\ndata = {\n \"calories\": [420, 380, 390],\n \"duration\": [50, 40, 45]\n}\ndf1 = pd.DataFrame(data)\n\ndf1.to_csv('calories.csv', index=False)\npd.read_csv(\"calories.csv\",index_col=0)\n df1.to_csv('calories.csv', index=False)\npd.read_csv(\"calories.csv\",index_col=0)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20636016/"
] |
74,618,047
|
<p>I am modifying some JSP files, and every time I upload a new version, if people don't update the cache, the styles are not rendered as they should be; it is looking not good and without styles applied.</p>
<p>To solve this problem, I have followed an example from Stack Overflow that adds a numeric value to the CSS file, preventing it from being cached in the browser. The specific link I've seen is this one:</p>
<p><a href="https://wpreset.com/force-reload-cached-css/" rel="nofollow noreferrer">https://wpreset.com/force-reload-cached-css/</a></p>
<p>But I've found that whenever I press F5 or navigate to other JSP's that apply the same stylesheet, the files that are part of that CSS file are always seen just before rendering. I added a GIF with a dummy example to exhibit what I mean:</p>
<p><a href="https://i.stack.imgur.com/TK9km.gif" rel="nofollow noreferrer">Animated GIF demonstrating the problem</a></p>
<p>How could I avoid this?</p>
|
[
{
"answer_id": 74618130,
"author": "unltd_J",
"author_id": 13063755,
"author_profile": "https://Stackoverflow.com/users/13063755",
"pm_score": 0,
"selected": false,
"text": "df.to_csv('Frequency.csv', index=False)\n"
},
{
"answer_id": 74618170,
"author": "Ayush Raj",
"author_id": 14264760,
"author_profile": "https://Stackoverflow.com/users/14264760",
"pm_score": 2,
"selected": true,
"text": "#if you don't want to save the index column in the first place\ndf.to_csv('Frequency.csv', index=False) \n# drop the extra column if any while reading\npd.read_csv(\"Frequency.csv\",index_col=0)\n import pandas as pd\n\ndata = {\n \"calories\": [420, 380, 390],\n \"duration\": [50, 40, 45]\n}\ndf1 = pd.DataFrame(data)\n\ndf1.to_csv('calories.csv', index=False)\npd.read_csv(\"calories.csv\",index_col=0)\n df1.to_csv('calories.csv', index=False)\npd.read_csv(\"calories.csv\",index_col=0)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13594702/"
] |
74,618,054
|
<p>I'm trying to create a grouping using multiple window function on SQL, the objective is to discern between different groups if there are some other groups in the middle. see below table</p>
<pre><code>Part | time | expected result |
a | 11-29-2022 00:05:00.000 | 1 |
a | 11-29-2022 00:05:00.010 | 1 |
b | 11-29-2022 00:06:00.000 | 2 |
c | 11-29-2022 00:15:00.000 | 3 |
c | 11-29-2022 00:15:00.000 | 3 |
b | 11-29-2022 00:40:00.010 | 4 |
b | 11-29-2022 00:40:00.020 | 4 |
b | 11-29-2022 00:40:00.020 | 4 |
b | 11-29-2022 00:40:00.030 | 4 |
</code></pre>
<p>I'm doing something like:</p>
<pre><code>Select part, time, count(*) over(Partition by Part order by time )
</code></pre>
<p>Lets focus in part "b", first occurrence is at minute 6, after that appears different parts and part b appears again at minute 40 so I need something like a time range to create the grouping</p>
<p>Also notice that sometimes the time is different in milliseconds even if the parts are consecutive (part b), those must belong to the same group.
Was trying to use the <code>Rank</code> window function but with 'range between' wasn't able to get that result.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 74618154,
"author": "Learn Hadoop",
"author_id": 8726488,
"author_profile": "https://Stackoverflow.com/users/8726488",
"pm_score": 0,
"selected": false,
"text": "Select part, time, dense_rank() over(Partition by Part ) \n Select part, time, dense_rank() over(Partition by Part order by time rows between unbounded preceding and unbounded following ) \n"
},
{
"answer_id": 74618406,
"author": "John Cappelletti",
"author_id": 1570000,
"author_profile": "https://Stackoverflow.com/users/1570000",
"pm_score": 3,
"selected": true,
"text": "Select * \n ,NewValue = dense_rank() over (order by convert(varchar(25),[Time],120))\n From YourTable\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7293251/"
] |
74,618,062
|
<p>Is there a way to execute SQL Query on Databricks SQL Warehouse using Rest API?</p>
<p>I can see in the documentation that there are APIs to create a qery but don't see any api to run an query.</p>
|
[
{
"answer_id": 74618154,
"author": "Learn Hadoop",
"author_id": 8726488,
"author_profile": "https://Stackoverflow.com/users/8726488",
"pm_score": 0,
"selected": false,
"text": "Select part, time, dense_rank() over(Partition by Part ) \n Select part, time, dense_rank() over(Partition by Part order by time rows between unbounded preceding and unbounded following ) \n"
},
{
"answer_id": 74618406,
"author": "John Cappelletti",
"author_id": 1570000,
"author_profile": "https://Stackoverflow.com/users/1570000",
"pm_score": 3,
"selected": true,
"text": "Select * \n ,NewValue = dense_rank() over (order by convert(varchar(25),[Time],120))\n From YourTable\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14430564/"
] |
74,618,069
|
<p>I have an application that runs fine in AWS App Runner and can be found here: <a href="https://iyarles.net" rel="nofollow noreferrer">https://iyarles.net</a></p>
<p>However, it's not accessible via the naked domain name iyarles.net.
Clarification comment: If I goto iyarles.net in my browser (edge), the request times out. If I goto iyarles.net, my website loads fine.</p>
<p>The App Runner service has a custom domain configured and my hosted zone has the 2 certificate validation records and the alias record pointing to my service.</p>
<p>A few weeks ago I transferred my domain from Google Domains to Route 53. It was originally a redirect from iyarles.net or any other subdomain (with or without https://) to the default domain for my service.</p>
<p>How can I replicate the previous behavior? What exactly are these alias records doing?</p>
|
[
{
"answer_id": 74618228,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 2,
"selected": true,
"text": "https: http://iyarles.net"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13101880/"
] |
74,618,104
|
<p>So I have the following tables (simplified here):</p>
<p>this is Ost_data</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Raumeinheit</th>
<th>Langzeitarbeitslose</th>
</tr>
</thead>
<tbody>
<tr>
<td>Hamburg</td>
<td>22</td>
</tr>
<tr>
<td>Koln</td>
<td>45</td>
</tr>
</tbody>
</table>
</div>
<p>This is West_data</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Raumeinheit</th>
<th>Langzeitarbeitslose</th>
</tr>
</thead>
<tbody>
<tr>
<td>Hamburg</td>
<td>42</td>
</tr>
<tr>
<td>Koln</td>
<td>11</td>
</tr>
</tbody>
</table>
</div>
<p>Ost_data has 76 rows and West_data has 324 rows.</p>
<p>I am tasked with proving my hypothesis that the Variable "Langzeitarbeitslose" is statistically, significantly higher in Ost_data than in West_data. Because that variable is not normally distributed I am trying to use Pearson's Chi Square Test.</p>
<p>I tried</p>
<p><code>chisq.test(Ost_data$Langzeitarbeitslose, West_data$Langzeitarbeitslose)</code></p>
<p>but that just retuns that it can't be performed because x and y differs in length.</p>
<p>Is there a way to navigate around that problem and perform the Chi Square test regardless with my two tables which have varying lengths?</p>
|
[
{
"answer_id": 74618228,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 2,
"selected": true,
"text": "https: http://iyarles.net"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20575692/"
] |
74,618,111
|
<p>I have a pipeline in Azure Data Factory to take in incoming CSV files and save them to SQL server database, and I use a copy activity to take the wrangled CSV file and call a stored procedure to save it the data base table.</p>
<p>However, it is not unusual that some records in the CSV file have missing value at some columns. Such missing value will fail copy activity and below is the error message:</p>
<blockquote>
<p>ErrorCode=InvalidParameter,'Type=Microsoft.DataTransfer.Common.Shared.HybridDeliveryException,Message=The value of the property '' is invalid: 'Cannot set Column 'col 1' to be null. Please use DBNull instead.'</p>
</blockquote>
<p>The copy activity runs correctly when there is no missing value in the incoming data.</p>
<p>Below is the snippet of the stored procedure that fails the execution when encounter missing value(s).</p>
<pre><code>INSERT INTO target_table(
[Id],
[col 1],
[col 2],
[col 3]
)
SELECT
[source Id],
[column 1],
[column 2],
[column 3]
FROM source_table
</code></pre>
<p><strong>My question is what I can do to convert the missing value in CSV file into a null value that SQL server understand.</strong></p>
<p>I orignally thought the problem is at the database side, so I created a test table in SQL Server and put some test data intentionally with missing values into a test table, then I run the stored procedure. These records with missing value get saved to the target table correctly. So I realized that the problem lies when the copy activity takes in the CSV file and pass it to the stored procedure, and the missing values didn't get translated well into a null value that SQL Server can understand.</p>
|
[
{
"answer_id": 74618228,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 2,
"selected": true,
"text": "https: http://iyarles.net"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7734596/"
] |
74,618,115
|
<p>I have a date/time string variable that looks like this:</p>
<pre><code>> dput(df$starttime)
c("12/16/20 7:24", "6/21/21 13:20", "1/22/20 9:03", "1/07/20 17:19",
"11/8/21 10:14", NA, NA, "10/26/21 7:19", "3/14/22 9:48", "5/12/22 13:29"
</code></pre>
<p>I basically want to create a column that only has the year (2020, 2021, 2022) and the year + month (e.g., "Jan 2022)</p>
|
[
{
"answer_id": 74618228,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 2,
"selected": true,
"text": "https: http://iyarles.net"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20152268/"
] |
74,618,168
|
<p>I have just starting learning python and as I creating this program, which asks user to input two numbers, which then adds them to together using a simple <code>if-elif-else </code> statement, however the else part of the code just seems to not work if, an user types out the six, for example, in words instead of the number.</p>
<pre><code>num_1 = int(input("Enter the first number: "))
num_2 = int(input("Enter the second number: "))
Total = num_1 + num_2
print("The total is: ",Total)
if num_1 > num_2:
print("num_1 is greater then num_2")
elif num_2 > num_1:
print("num_2 is greater then num_1")
elif num_1 == num_2:
print("Equal")
else:
if num_1 == str:
if num_2 == str:
print("invalid")
</code></pre>
|
[
{
"answer_id": 74618422,
"author": "He1senberg_10",
"author_id": 16262060,
"author_profile": "https://Stackoverflow.com/users/16262060",
"pm_score": 1,
"selected": false,
"text": "try:\n num_1 = int(input(\"Enter the first number: \"))\n num_2 = int(input(\"Enter the second number: \"))\nexcept ValueError:\n print(\"invalid\")\n exit()\nTotal = num_1 + num_2\nprint(\"The total is: \", Total)\n\nif num_1 > num_2:\n print(\"num_1 is greater then num_2\")\nelif num_2 > num_1:\n print(\"num_2 is greater then num_1\")\nelse:\n print(\"Equal\")\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17851996/"
] |
74,618,182
|
<p>I learnt, the <strong>parquet file format</strong> stores a bunch of metadata and uses various compressions to store data in an efficient way, when it comes to size and query-speed.</p>
<p>And it possibly generates multiple files out of, let's say: one input, like from a Panda dataframe.</p>
<p>Now, I have a <strong>large CSV</strong> file and I want to <strong>convert it into a parquet</strong> file format. Naively, I would remove the header (store elsewhere for later) and chunk the file up in blocks with n lines. Then turn each chunk into parquet (here Python):</p>
<pre><code>table = pyarrow.csv.read_csv(fileName)
pyarrow.parquet.write_table(table, fileName.replace('csv', 'parquet'))
</code></pre>
<p>I guess the method doesn't much matter. From what I see, at least with a small <strong>test data set and no extra context</strong>, I get one parquet file per csv file <strong>(1:1)</strong>.</p>
<p>For now that is all I need, <strong>as I am not doing queries</strong> on "the whole", logical data set. I use the raw files, as input to a further cleaning step that is nifty to do with the csv format. And I haven't yet tried reading the files...</p>
<p><strong>Do I have to readd the header to each CSV chunk at the least?</strong></p>
<p>Is this as straight-forward as I think, or am I missing something?</p>
|
[
{
"answer_id": 74645490,
"author": "Michael Delgado",
"author_id": 3888719,
"author_profile": "https://Stackoverflow.com/users/3888719",
"pm_score": 1,
"selected": false,
"text": "dask.dataframe dask.dataframe.read_csv import dask.dataframe\n\n# here, the block size will determine the partition boundaries, which will\n# be preserved in the parquet file. So if you have a 5 GB file, this would\n# write 50 partitions:\ndf = dask.dataframe.read_csv(fileName, blocksize=\"100MB\")\ndf.to_parquet(fileName.replace(\".csv\", \".parquet\"))\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/132396/"
] |
74,618,192
|
<p>I'm making a method called fillList. The method will require an arrayList in order to work and the output will be void.
What the method is supposed to do is to fill the gaps between the numbers of the List.</p>
<p>Example:</p>
<p>Input:</p>
<pre><code>4 8 5 9
</code></pre>
<p>Output:</p>
<pre><code>4 5 6 7 8 7 6 5 6 7 8 9
</code></pre>
<p>The code I have so far is this:</p>
<pre><code>public static void fillList(ArrayList<Integer> List) {
for(int i = 0; i < List.size(); i++) {
if(List.get(i) < List.get(i+1) ) {
List.add(List.get(i+1));
} else if(List.get(i) > List.get(i+1)) {
List.add(List.get(i-1));
}
}
}
</code></pre>
<p>My idea was to add 1 to the value of the first element if the first element was less than the second element in the List. For example if the first element is <code>4</code> then the code would add a <code>5</code> to the list and stop once the number added was equal to one less than the second element. And basically do the opposite if the first element was more than the second element.</p>
<p>I don't know how to stop this loop until the numbers that are being added reach the second element of the list. I am not confident about my code as well I'm pretty sure I am making an error I'm not seeing.</p>
|
[
{
"answer_id": 74618385,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 3,
"selected": true,
"text": "List.add(int index, E element) 1 left + 1 1 left - 1 public static void fillList(List<Integer> list) {\n for (int i = 0; i < list.size() - 1; i++) {\n int left = list.get(i);\n int right = list.get(i + 1);\n if (left < right && left + 1 != right) {\n list.add(i + 1, left + 1);\n } else if (left > right && left - 1 != right) {\n list.add(i + 1, left - 1);\n }\n }\n}\n main() public static void main(String[] args) {\n List<Integer> list1 = new ArrayList<>(List.of(4, 8, 5, 9));\n fillList(list1);\n System.out.println(list1);\n}\n [4, 5, 6, 7, 8, 7, 6, 5, 6, 7, 8, 9]\n"
},
{
"answer_id": 74618561,
"author": "yezper",
"author_id": 16560836,
"author_profile": "https://Stackoverflow.com/users/16560836",
"pm_score": 2,
"selected": false,
"text": "list List list.add(5) list.add(4, 5)"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20187389/"
] |
74,618,194
|
<p>So this is in german, but I have to write a function in C but it does not work out. Can you tell me where my mistake is?</p>
<p>The task is the one Iam writing down now.</p>
<p>Write a function "time_converter( )" which converts the time from one unit to another. The function is passed the case (i.e. which conversion is to be performed) and the number to be converted in exactly this order.
The case is given a number between 1 and 6 and the number to be converted is given as a natural number. The result of the conversion is to be returned to 2 digits exactly at the end of the function.
The following cases are to be implemented:</p>
<ol>
<li><p>from second to minute</p>
</li>
<li><p>from second to hour</p>
</li>
<li><p>from minute to hour</p>
</li>
<li><p>from hour to minute</p>
</li>
<li><p>from hour to second</p>
</li>
<li><p>from minute to second</p>
<pre><code> int zeit_umrechner(float z, char e, char ee ){
if (e==sekunde && ee==minute)
{return z/60;}
if (e==sekunde && ee== stunde)
{return z/3600;}
if (e==minute && ee== stunde)
{return z/60;}
if (e==stunde && ee== minute)
{return z*60;}
if (e==stunde && ee== sekunde)
{return z*3600;}
if (e==minute && ee== sekunde)
{return z*60;}
return 0;
</code></pre>
<p>}</p>
</li>
</ol>
<p>I tried, but it does not work out.</p>
|
[
{
"answer_id": 74618385,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 3,
"selected": true,
"text": "List.add(int index, E element) 1 left + 1 1 left - 1 public static void fillList(List<Integer> list) {\n for (int i = 0; i < list.size() - 1; i++) {\n int left = list.get(i);\n int right = list.get(i + 1);\n if (left < right && left + 1 != right) {\n list.add(i + 1, left + 1);\n } else if (left > right && left - 1 != right) {\n list.add(i + 1, left - 1);\n }\n }\n}\n main() public static void main(String[] args) {\n List<Integer> list1 = new ArrayList<>(List.of(4, 8, 5, 9));\n fillList(list1);\n System.out.println(list1);\n}\n [4, 5, 6, 7, 8, 7, 6, 5, 6, 7, 8, 9]\n"
},
{
"answer_id": 74618561,
"author": "yezper",
"author_id": 16560836,
"author_profile": "https://Stackoverflow.com/users/16560836",
"pm_score": 2,
"selected": false,
"text": "list List list.add(5) list.add(4, 5)"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20636420/"
] |
74,618,203
|
<p>I am trying to execute my databricks note book and linked service as execution Pool type of connection, also I have upload the Append libraries option for wheel format library in ADF but unable to execute our notebook via ADF and getting below error.</p>
<p>Run result unavailable: job failed with error message Library installation failed for library due to user error for whl:</p>
<blockquote>
<p>"dbfs:/FileStore/jars/xxxxxxxxxxxxxxxxxxxx/prophet-1.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl"
. Error messages: Library installation attempted on the driver node of
cluster 1129-161441-xwjfzl6k and failed. Please refer to the following
error message to fix the library or contact Databricks support. Error
Code: DRIVER_LIBRARY_INSTALLATION_FAILURE. Error Message:
org.apache.spark.SparkException: Process List(bash,
/local_disk0/.ephemeral_nfs/cluster_libraries/python/python_start_clusterwide.sh,
/local_disk0/.ephemeral_nfs/cluster_libraries/python/bin/pip, install,
--upgrade, --find-links=/local_disk0/.ephemeral_nfs/cluster_libraries/python/lib/python3.9/site-packages,
/local_disk0/.ephemeral_nfs/cluster_libraries/python/lib/python3.9/site-packages/prophet-1.1-cp38-cp38-manylinux_2_17_x86_6
... *<strong>WARNING: message truncated. Skipped 195 bytes of output</strong></p>
</blockquote>
<p>Kindly help us. and in linked in service, there is three types of option we have(Select cluster),
1.new job cluster
2.exixting interactive cluster
3.Existing instance pool</p>
<p>in production perspective which is the best, we do not have any job created in databricks and plan note book needs to trigger in adf to success the execution. please advice</p>
|
[
{
"answer_id": 74618385,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 3,
"selected": true,
"text": "List.add(int index, E element) 1 left + 1 1 left - 1 public static void fillList(List<Integer> list) {\n for (int i = 0; i < list.size() - 1; i++) {\n int left = list.get(i);\n int right = list.get(i + 1);\n if (left < right && left + 1 != right) {\n list.add(i + 1, left + 1);\n } else if (left > right && left - 1 != right) {\n list.add(i + 1, left - 1);\n }\n }\n}\n main() public static void main(String[] args) {\n List<Integer> list1 = new ArrayList<>(List.of(4, 8, 5, 9));\n fillList(list1);\n System.out.println(list1);\n}\n [4, 5, 6, 7, 8, 7, 6, 5, 6, 7, 8, 9]\n"
},
{
"answer_id": 74618561,
"author": "yezper",
"author_id": 16560836,
"author_profile": "https://Stackoverflow.com/users/16560836",
"pm_score": 2,
"selected": false,
"text": "list List list.add(5) list.add(4, 5)"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2878290/"
] |
74,618,241
|
<p>I have seen a lot of posts suggesting that private fields ought to be accessible from outside via properties (or at least get/set methods).
I wonder are there any cases in which we should access our private fields inside the class by properties as well? Or should we just interact with our private fields directly thinking in terms "it only takes processing resources to approach them by properties"?</p>
|
[
{
"answer_id": 74618385,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 3,
"selected": true,
"text": "List.add(int index, E element) 1 left + 1 1 left - 1 public static void fillList(List<Integer> list) {\n for (int i = 0; i < list.size() - 1; i++) {\n int left = list.get(i);\n int right = list.get(i + 1);\n if (left < right && left + 1 != right) {\n list.add(i + 1, left + 1);\n } else if (left > right && left - 1 != right) {\n list.add(i + 1, left - 1);\n }\n }\n}\n main() public static void main(String[] args) {\n List<Integer> list1 = new ArrayList<>(List.of(4, 8, 5, 9));\n fillList(list1);\n System.out.println(list1);\n}\n [4, 5, 6, 7, 8, 7, 6, 5, 6, 7, 8, 9]\n"
},
{
"answer_id": 74618561,
"author": "yezper",
"author_id": 16560836,
"author_profile": "https://Stackoverflow.com/users/16560836",
"pm_score": 2,
"selected": false,
"text": "list List list.add(5) list.add(4, 5)"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19830764/"
] |
74,618,270
|
<p>I'm trying to make an object with a property that depends of another property.</p>
<p>This is a very simplified example of what i tried so far.<br />
I expected <code>T</code> to be infered from <code>name</code>. <code>value</code> should then be limited to the valid value in <code>TypeA</code>.</p>
<pre><code>type TypeA = {
some: 'some2';
thing: 'thing2';
};
type TypeAUnion = keyof TypeA;
type TestType<T extends TypeAUnion = TypeAUnion> = {
name: T;
value: TypeA[T];
};
const test1: TestType = {
name: 'some',
value: 'some2',
};
const test2: TestType = {
name: 'some',
value: 'thing2', // shouldn't be allowed here
};
</code></pre>
<h3>EDIT:</h3>
<p>A better example of what i'm trying to do.</p>
<pre><code>type StateType = {
thingA: string;
thingB: number;
};
type StateKeysUnion = keyof StateType;
const state: StateType = {
thingA: 'somestring',
thingB: 10,
};
type PayloadType<T extends StateKeysUnion = StateKeysUnion> = {
key: T;
value: StateType[T];
};
const setThing = (payload: PayloadType) => {
state[payload.key] = payload.value;
};
setThing({
key: 'thingA',
// expected to only accept string
value: true,
});
setThing({
key: 'thingB',
// expected to only accept number
value: 'asdas',
});
</code></pre>
|
[
{
"answer_id": 74618385,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 3,
"selected": true,
"text": "List.add(int index, E element) 1 left + 1 1 left - 1 public static void fillList(List<Integer> list) {\n for (int i = 0; i < list.size() - 1; i++) {\n int left = list.get(i);\n int right = list.get(i + 1);\n if (left < right && left + 1 != right) {\n list.add(i + 1, left + 1);\n } else if (left > right && left - 1 != right) {\n list.add(i + 1, left - 1);\n }\n }\n}\n main() public static void main(String[] args) {\n List<Integer> list1 = new ArrayList<>(List.of(4, 8, 5, 9));\n fillList(list1);\n System.out.println(list1);\n}\n [4, 5, 6, 7, 8, 7, 6, 5, 6, 7, 8, 9]\n"
},
{
"answer_id": 74618561,
"author": "yezper",
"author_id": 16560836,
"author_profile": "https://Stackoverflow.com/users/16560836",
"pm_score": 2,
"selected": false,
"text": "list List list.add(5) list.add(4, 5)"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1163673/"
] |
74,618,271
|
<pre><code><body>
<h1>Insert here:</h1>
<button>Try</button>
<input name='myName' type="text">
<h2>No one here</h2>
<script>
let button = document.querySelector('button');
let h2 = document.querySelector('h2');
let myName = document.querySelector('input');
function sayHi(name = 'Stranger'){
h2.innerHTML = `Hello ${name}`;
}
button.addEventListener('click', ()=>{
sayHi(myName.value);
});
</script>
</body>
</code></pre>
<p>So, I recently started JS and I was trying simple functions, just to practice. This code basically should take whatever you write and print "hello (whatyouwrite)" or simply print "hello Stranger" if you write nothing. However I cannot manage to use the default parameter and when I write nothing and press the button it prints "Hello " whith a blank space after hello. I realize the "nothing" I send is still something but I cannot figure out what it is or how to do it properly.</p>
<p>Lastly, I've been following this tutorials:
<a href="https://youtu.be/WyC678zya3E?list=PLP5MAKLy8lP9FUx06-avV66mS8LXz7_Bb&t=489" rel="nofollow noreferrer">https://youtu.be/WyC678zya3E?list=PLP5MAKLy8lP9FUx06-avV66mS8LXz7_Bb&t=489</a>
which writes the exact same code and, for him, works as it should...</p>
|
[
{
"answer_id": 74618327,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": " button.addEventListener('click', ()=>{\n sayHi(myName.value);\n sayHi();//this will invoke default parameter\n });\n function sayHi(name){\n if (name.length === 0)\n name = 'Stranger';\n h2.innerHTML = `Hello ${name}`;\n }\n \n"
},
{
"answer_id": 74618497,
"author": "bar_ok",
"author_id": 16731729,
"author_profile": "https://Stackoverflow.com/users/16731729",
"pm_score": 0,
"selected": false,
"text": "button.addEventListener(\"click\", () => {\n if (myName.value) {\n sayHi(myName.value);\n } else {\n sayHi();\n }\n});\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8272374/"
] |
74,618,291
|
<p>I'd like to create a namespace in c# that can be found in any project. Not just the one that it is located in. like the system namespace. Is that possible and if yes I'd like to know how.
I already googled and didn't find anything</p>
|
[
{
"answer_id": 74618470,
"author": "StriplingWarrior",
"author_id": 120955,
"author_profile": "https://Stackoverflow.com/users/120955",
"pm_score": 0,
"selected": false,
"text": "System System.String IObservable<> using"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19217076/"
] |
74,618,312
|
<p>When converting from double to a string using [string], strange rounding behavior seems to occur in PowerShell 5.1.</p>
<p>Converting 0.114338713266919499 to a string becomes 0.11433871326919, indicating that it rounds the ...499 down to zero and truncates. This behavior doesn't seem to match rounding in C# , so I am struggling to duplicate this behavior as the rounding doesn't seem to follow any convention I can find. I found the <a href="https://learn.microsoft.com/en-us/powershell/scripting/lang-spec/chapter-06?view=powershell-7.3" rel="nofollow noreferrer">conversions page</a> for powershell but it has no details on how the conversion works under the hood. I am trying to duplicate the values generated by a script using a double to string conversion in C# and cannot change the script. Any details on the conversion process would be appreciated.</p>
<p>I tried a variety of double values and it seems to keep 15 digits after the decimal not including zeroes after the decimal but before non-zero values. However, when I go to C# and ask it to round the 15th decimal place, I find different results. I understand the floating point numbers are not exact values, but it seems since they are the same range in C# and PowerShell for doubles that I should be able to duplicate the behavior.</p>
|
[
{
"answer_id": 74618545,
"author": "MD Zand",
"author_id": 5118861,
"author_profile": "https://Stackoverflow.com/users/5118861",
"pm_score": 1,
"selected": true,
"text": "double myVar = 22.3;\nConsole.WriteLine((myVar + .1) == 22.4);\n 22.3"
},
{
"answer_id": 74622402,
"author": "HAL9256",
"author_id": 2150063,
"author_profile": "https://Stackoverflow.com/users/2150063",
"pm_score": 1,
"selected": false,
"text": "R /platform:x64 /platform:anycpu $a 19 R 1949 G17 1949 PS C:\\> [double] $a = '0.114338713266919499'\nPS C:\\> $a\n0.114338713266919\n\nPS C:\\> '{0:R} R' -f $a\n0.11433871326691949 R\nPS C:\\> '{0:G} G' -f $a\n0.114338713266919 G\nPS C:\\> '{0:G15} G15' -f $a\n0.114338713266919 G15\nPS C:\\> '{0:G16} G16' -f $a\n0.1143387132669195 G16\nPS C:\\> '{0:G17} G17' -f $a\n0.11433871326691949 G17\n $a 19 R 195 G17 195 PS C:\\> [double] $a = '0.114338713266919499'\nPS C:\\> $a\n0.114338713266919\n\nPS C:\\> '{0:R} R' -f $a\n0.1143387132669195 R\nPS C:\\> '{0:G} G' -f $a\n0.114338713266919 G\nPS C:\\> '{0:G15} G15' -f $a\n0.114338713266919 G15\nPS C:\\> '{0:G16} G16' -f $a\n0.1143387132669195 G16\nPS C:\\> '{0:G17} G17' -f $a\n0.1143387132669195 G17\n $a 19 R 1949 G17 1949 PS C:\\> [double] $a = '0.114338713266919499'\nPS C:\\> $a\n0.114338713266919\n\nPS C:\\> '{0:R} R' -f $a\n0.11433871326691949 R\nPS C:\\> '{0:G} G' -f $a\n0.114338713266919 G\nPS C:\\> '{0:G15} G15' -f $a\n0.114338713266919 G15\nPS C:\\> '{0:G16} G16' -f $a\n0.1143387132669195 G16\nPS C:\\> '{0:G17} G17' -f $a\n0.11433871326691949 G17\n $a 19 R 195 G17 1949 PS C:\\> [double] $a = '0.114338713266919499'\nPS C:\\> $a\n0.114338713266919\n\nPS C:\\> '{0:R} R' -f $a\n0.1143387132669195 R\nPS C:\\> '{0:G} G' -f $a\n0.1143387132669195 G\nPS C:\\> '{0:G15} G15' -f $a\n0.114338713266919 G15\nPS C:\\> '{0:G16} G16' -f $a\n0.1143387132669195 G16\nPS C:\\> '{0:G17} G17' -f $a\n0.11433871326691949 G17\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19034611/"
] |
74,618,335
|
<p>I am looking for a regex or a regex flag in python/BigQuery that enables me to find overlapping occurrences.</p>
<p>For example, I have the string <code>1.2.5.6.8.10.12</code></p>
<p>and I would like to extract:
<code>[1., 1.2., 1.2.5., 1.2.5.6., ..., 1.2.5.6.8.10.12]</code></p>
<p>I tried running the python code
<code>re.findall("^(\d+(?:\.|$))+", string)</code>
and it resulted in ['12']</p>
|
[
{
"answer_id": 74618545,
"author": "MD Zand",
"author_id": 5118861,
"author_profile": "https://Stackoverflow.com/users/5118861",
"pm_score": 1,
"selected": true,
"text": "double myVar = 22.3;\nConsole.WriteLine((myVar + .1) == 22.4);\n 22.3"
},
{
"answer_id": 74622402,
"author": "HAL9256",
"author_id": 2150063,
"author_profile": "https://Stackoverflow.com/users/2150063",
"pm_score": 1,
"selected": false,
"text": "R /platform:x64 /platform:anycpu $a 19 R 1949 G17 1949 PS C:\\> [double] $a = '0.114338713266919499'\nPS C:\\> $a\n0.114338713266919\n\nPS C:\\> '{0:R} R' -f $a\n0.11433871326691949 R\nPS C:\\> '{0:G} G' -f $a\n0.114338713266919 G\nPS C:\\> '{0:G15} G15' -f $a\n0.114338713266919 G15\nPS C:\\> '{0:G16} G16' -f $a\n0.1143387132669195 G16\nPS C:\\> '{0:G17} G17' -f $a\n0.11433871326691949 G17\n $a 19 R 195 G17 195 PS C:\\> [double] $a = '0.114338713266919499'\nPS C:\\> $a\n0.114338713266919\n\nPS C:\\> '{0:R} R' -f $a\n0.1143387132669195 R\nPS C:\\> '{0:G} G' -f $a\n0.114338713266919 G\nPS C:\\> '{0:G15} G15' -f $a\n0.114338713266919 G15\nPS C:\\> '{0:G16} G16' -f $a\n0.1143387132669195 G16\nPS C:\\> '{0:G17} G17' -f $a\n0.1143387132669195 G17\n $a 19 R 1949 G17 1949 PS C:\\> [double] $a = '0.114338713266919499'\nPS C:\\> $a\n0.114338713266919\n\nPS C:\\> '{0:R} R' -f $a\n0.11433871326691949 R\nPS C:\\> '{0:G} G' -f $a\n0.114338713266919 G\nPS C:\\> '{0:G15} G15' -f $a\n0.114338713266919 G15\nPS C:\\> '{0:G16} G16' -f $a\n0.1143387132669195 G16\nPS C:\\> '{0:G17} G17' -f $a\n0.11433871326691949 G17\n $a 19 R 195 G17 1949 PS C:\\> [double] $a = '0.114338713266919499'\nPS C:\\> $a\n0.114338713266919\n\nPS C:\\> '{0:R} R' -f $a\n0.1143387132669195 R\nPS C:\\> '{0:G} G' -f $a\n0.1143387132669195 G\nPS C:\\> '{0:G15} G15' -f $a\n0.114338713266919 G15\nPS C:\\> '{0:G16} G16' -f $a\n0.1143387132669195 G16\nPS C:\\> '{0:G17} G17' -f $a\n0.11433871326691949 G17\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11946953/"
] |
74,618,349
|
<pre><code>let f x =
match x with
((2, 4)::xr) -> 42
| [(1, y); (_, 3); (_, 4)] -> 5
| [(x, _); (u, w)] -> u + x
| [(44, 11); (12, 3)] -> 42
| (x::xr) -> fst (hd xr)
</code></pre>
<p>I've tried running <code>f[(2, 4)]</code> for example.</p>
<p>ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ</p>
|
[
{
"answer_id": 74618479,
"author": "Jeffrey Scofield",
"author_id": 821679,
"author_profile": "https://Stackoverflow.com/users/821679",
"pm_score": 2,
"selected": false,
"text": "hd List List.hd hd # hd;;\nError: Unbound value hd\n# List.hd;;\n- : 'a list -> 'a = <fun>\n# \n"
},
{
"answer_id": 74618829,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 1,
"selected": false,
"text": "List.hd x let f x = \n match x with \n (2, 4)::xr -> 42\n | [(1, y); (_, 3); (_, 4)] -> 5 \n | [(x, _); (u, w)] -> u + x \n | [(44, 11); (12, 3)] -> 42\n | _::(x, _)::_ -> x\n hd List.hd (2, 4)::xr (2, 4)"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15131002/"
] |
74,618,389
|
<p>I would like to assign each unique combination of variables a value and list those values in a new column called ID, as shown below. For example I would like patients who are Ta cancer, N0 lymph, and 1 immunotherapy ID'd as 1. Patients who are TA, NX, and 1 as ID 2 and so on... Below is a table of what the data looks like before, and what I would like it to look like as after. Data was loaded from .csv</p>
<pre><code>So to summarize:
Patients TA, N0, 1 ID = 1
Patients TA, N0, 2 ID = 2
Patients TA, Nx, 0 ID = 3
Patients TA, Nx, 1 ID = 4
Patients TA, N0, 0 ID = 5
Patients TA, Nx, 2 ID = 6
</code></pre>
<p>Before:</p>
<pre><code>| Cancer | Lymph |Immunotherapy
| -------- | -------- |---------
| TA | N0 |1
| TA | N0 |2
| TA | N0 |1
| TA | Nx |0
| TA | Nx |1
| TA | N0 |0
| TA | Nx |1
| TA | Nx |2
</code></pre>
<p>After:</p>
<pre><code>
| Cancer | Lymph |Immunotherapy|ID
| -------- | -------- |--------- |-------
| TA | N0 |1 | 1
| TA | N0 |2 | 2
| TA | N0 |1 | 1
| TA | Nx |0 | 3
| TA | Nx |1 | 4
| TA | N0 |0 | 5
| TA | Nx |1 | 4
| TA | Nx |2 | 6
</code></pre>
<p>I attempted to use group_by() dplyr and mutate with no luck. Any help would be much appreciated. Thanks!</p>
|
[
{
"answer_id": 74618462,
"author": "Jon Spring",
"author_id": 6851825,
"author_profile": "https://Stackoverflow.com/users/6851825",
"pm_score": 0,
"selected": false,
"text": "library(dplyr)\ndf %>%\n group_by(Cancer, Lymph, Immunotherapy) %>%\n mutate(ID = cur_group_id()) %>%\n ungroup()\n df %>%\n left_join(df %>% \n distinct(Cancer,Lymph,Immunotherapy) %>% \n mutate(ID = row_number())\n )\n"
},
{
"answer_id": 74618501,
"author": "onyambu",
"author_id": 8380272,
"author_profile": "https://Stackoverflow.com/users/8380272",
"pm_score": 1,
"selected": false,
"text": "d <- do.call(paste, df)\ncbind(df, id = as.numeric(factor(d, unique(d))))\n\n Cancer Lymph Immunotherapy id\n1 TA N0 1 1\n2 TA N0 2 2\n3 TA N0 1 1\n4 TA Nx 0 3\n5 TA Nx 1 4\n6 TA N0 0 5\n7 TA Nx 1 4\n8 TA Nx 2 6\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20636182/"
] |
74,618,396
|
<p>I'm trying to write this in C#. The requirement is very straightforward - check if a string input is a value within the range from 0 to 100.</p>
<ol>
<li>I want to make sure the string is either an integer value in the range of 0 to 100 or</li>
<li>a double that's within the same range as well.</li>
</ol>
<p>So for example, these are the accepted values:</p>
<pre><code>0
50
100
0.1
50.7
100.0
</code></pre>
<p>I checked the double.parse method here but not sure if it's the one I'm looking for: <a href="https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-7.0#system-double-tryparse(system-string-system-iformatprovider-system-double@)" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-7.0#system-double-tryparse(system-string-system-iformatprovider-system-double@)</a></p>
<p>The reason is that it can also parse string like this one: 0.64e2 (which is 64)</p>
<p>Is this something that can be achieved with built-in library already?</p>
|
[
{
"answer_id": 74618581,
"author": "Charles Yang",
"author_id": 13101880,
"author_profile": "https://Stackoverflow.com/users/13101880",
"pm_score": 3,
"selected": true,
"text": "// C# function to check if string is a percentage between 0 and 100\npublic static bool IsPercentage(string s)\n{\n // regex check if s is a string with only numbers or decimal point\n if (Regex.IsMatch(s, @\"^\\d+\\.?\\d*$\"))\n {\n double d = Convert.ToDouble(s);\n return d >= 0 && d <= 100;\n }\n return false;\n}\n"
},
{
"answer_id": 74618923,
"author": "Falco Alexander",
"author_id": 5273580,
"author_profile": "https://Stackoverflow.com/users/5273580",
"pm_score": 0,
"selected": false,
"text": "static bool IsPercentage(string s)\n{\n\n if (Single.TryParse(s, NumberStyles.AllowLeadingSign |\n NumberStyles.AllowDecimalPoint, NumberFormatInfo.InvariantInfo, out Single n))\n return n >= 0 && n <= 100;\n\nreturn false;\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9010054/"
] |
74,618,404
|
<p>script will need to check if aaa-new-ui-dev and bbb-java-new-ui-dev namespace exist - and if it exists - it needs to delete them and wait until delete operation is complete</p>
<p>I am trying to create a shell script which check if namespace is exist and if it exists then it should delete the kubectl namespace.</p>
|
[
{
"answer_id": 74619191,
"author": "Justin Pierce",
"author_id": 6431503,
"author_profile": "https://Stackoverflow.com/users/6431503",
"pm_score": 3,
"selected": true,
"text": "# For each namespace to delete.\nfor ns in aaa-new-ui-dev bbb-java-new-ui-dev ; do \n # If 'get' returns 0, then the namespace exists. \n if kubectl get namespace/$ns ; then\n # Issue delete. \n kubectl delete namespace/$ns\n # Wait up to 30 seconds for deletion.\n kubectl wait --for=delete namespace/$ns --timeout=30s\n else\n # Get returned an error. Assume namespace does not exist.\n echo \"$project does not exist; skipping delete\"\n fi\ndone\n"
},
{
"answer_id": 74619484,
"author": "Guillermo Alvarado",
"author_id": 1154952,
"author_profile": "https://Stackoverflow.com/users/1154952",
"pm_score": 0,
"selected": false,
"text": "ns_to_delete=(aaa-new-ui-dev bbb-java-new-ui-dev)\n\n# For each namespace to delete.\nfor ns in ${ns_to_delete[@]} ; do \n if ! output=$(kubectl delete namespace/$ns 2>&1); then\n printf \"$ns does not exists, not need to delete it\\n\" >&2\n else\n printf \"Deleting $ns \\n\" >&2\n while sleep 0.1; do printf \".\"; done &\n kubectl wait --for=delete namespace/$ns\n kill $!\n echo \"Deleted!\"\n fi\ndone\n aaa-new-ui-dev Deleting aaa-new-ui-dev \n...........Deleted!\nbbb-java-new-ui-dev does not exists, not need to delete it\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5232420/"
] |
74,618,408
|
<p>How can set the filename to today's date?</p>
<pre class="lang-js prettyprint-override"><code>$("#download").on("click", function() {
html2canvas(document.querySelector("#to_save")).then(canvas => {
canvas.toBlob(function(blob) {
window.saveAs(blob, #);
});
});
});
</code></pre>
<p>I couldn't find a solution.</p>
|
[
{
"answer_id": 74619191,
"author": "Justin Pierce",
"author_id": 6431503,
"author_profile": "https://Stackoverflow.com/users/6431503",
"pm_score": 3,
"selected": true,
"text": "# For each namespace to delete.\nfor ns in aaa-new-ui-dev bbb-java-new-ui-dev ; do \n # If 'get' returns 0, then the namespace exists. \n if kubectl get namespace/$ns ; then\n # Issue delete. \n kubectl delete namespace/$ns\n # Wait up to 30 seconds for deletion.\n kubectl wait --for=delete namespace/$ns --timeout=30s\n else\n # Get returned an error. Assume namespace does not exist.\n echo \"$project does not exist; skipping delete\"\n fi\ndone\n"
},
{
"answer_id": 74619484,
"author": "Guillermo Alvarado",
"author_id": 1154952,
"author_profile": "https://Stackoverflow.com/users/1154952",
"pm_score": 0,
"selected": false,
"text": "ns_to_delete=(aaa-new-ui-dev bbb-java-new-ui-dev)\n\n# For each namespace to delete.\nfor ns in ${ns_to_delete[@]} ; do \n if ! output=$(kubectl delete namespace/$ns 2>&1); then\n printf \"$ns does not exists, not need to delete it\\n\" >&2\n else\n printf \"Deleting $ns \\n\" >&2\n while sleep 0.1; do printf \".\"; done &\n kubectl wait --for=delete namespace/$ns\n kill $!\n echo \"Deleted!\"\n fi\ndone\n aaa-new-ui-dev Deleting aaa-new-ui-dev \n...........Deleted!\nbbb-java-new-ui-dev does not exists, not need to delete it\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20636416/"
] |
74,618,424
|
<p>I am a beginner, and I was working on a simple credit program. I want it to work so every time I add an input of a number it gets stored in a variable that shows my total balance. The problem right now is that the program is only a one use program so the input i enter does not get saved into a variable so that when I enter another value it gets added onto a previous input. Code is below:</p>
<pre><code>Purchase = int(input("How much was your purchase? "))
credit_balance = 0
credit_limit = 2000
Total = credit_balance + Purchase
print("Your account value right now: ", Total)
if Total == credit_limit:
print("You have reached your credit limit!", Total)
</code></pre>
|
[
{
"answer_id": 74618496,
"author": "Charles Yang",
"author_id": 13101880,
"author_profile": "https://Stackoverflow.com/users/13101880",
"pm_score": 0,
"selected": false,
"text": "credit_balance = 0\ncredit_limit = 2000\n\nwhile True:\n purchase = int(input(\"How much was your purchase? \"))\n credit_balance += purchase # add purchase to credit_balance\n \n print(\"Your account value right now: \", credit_balance)\n \n if credit_balance >= credit_limit:\n print(\"You have reached/exceeded your credit limit!\", Total)\n"
},
{
"answer_id": 74618529,
"author": "forgebench",
"author_id": 19839670,
"author_profile": "https://Stackoverflow.com/users/19839670",
"pm_score": 1,
"selected": false,
"text": "credit_limit = 2000\ncredit_balance = 0\n\nwhile True:\n\n print('Welcome to the Credit Card Company')\n Purchase = int(input(\"How much was your purchase? \"))\n Total = credit_balance + Purchase\n\n print(\"Your account value right now: \", Total)\n\n if Total >= credit_limit:\n print(\"You have reached your credit limit!\", Total)\n print('Welcome to the Credit Card Company')\n Purchase = int(input(\"How much was your purchase? Or type Exit to exit.\"))\n if Purchase == 'Exit':\n exit()\n credit_limit = 2000\ncurrent_balance = 0\n\nwhile True:\n\n print('Welcome to the Credit Card Company')\n Purchase = int(input(\"How much was your purchase? \"))\n current_balance = current_balance + Purchase\n\n print(\"Your account value right now: \", current_balance)\n\n if current_balance == credit_limit:\n print(\"You have reached your credit limit!\", current_balance)\n\n"
},
{
"answer_id": 74618583,
"author": "Nimrod Shanny",
"author_id": 20631164,
"author_profile": "https://Stackoverflow.com/users/20631164",
"pm_score": 1,
"selected": false,
"text": "credit_balance = 0\ncredit_limit = 2000\n\nwhile True:\n purchase = int(input(\"How much was your purchase? \"))\n Total = credit_balance + purchase\n print(\"Your account value right now: \", Total)\n if Total == credit_limit:\n print(\"You have reached your credit limit!\", Total)\n Purchase purchase"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16467204/"
] |
74,618,430
|
<p>I keep getting this error when I try to create new react app:</p>
<p><a href="https://i.stack.imgur.com/gjRQE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gjRQE.png" alt="enter image description here" /></a></p>
<p>Although I have latest Node and NPM I keep getting this error when I try to install with Create React App.</p>
|
[
{
"answer_id": 74618674,
"author": "DᴀʀᴛʜVᴀᴅᴇʀ",
"author_id": 1952287,
"author_profile": "https://Stackoverflow.com/users/1952287",
"pm_score": 0,
"selected": false,
"text": "curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.2/install.sh | bash\n export NVM_DIR=\"$([ -z \"${XDG_CONFIG_HOME-}\" ] && printf %s \"${HOME}/.nvm\" || printf %s \"${XDG_CONFIG_HOME}/nvm\")\"\n[ -s \"$NVM_DIR/nvm.sh\" ] && \\. \"$NVM_DIR/nvm.sh\" # This loads nvm\n nvm use 18.12.1\n nvm alias default 18.12.1\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8331346/"
] |
74,618,456
|
<p>Can I use tuples when writing to a csv file?</p>
<p>I am trying to reduce memory footprint by using tuple instead of a class instance.</p>
<p>The documentation does mention dynamic and anonymous types; but I don't see for value tuple. Also, how do I handle headers and custom formatting?</p>
|
[
{
"answer_id": 74618674,
"author": "DᴀʀᴛʜVᴀᴅᴇʀ",
"author_id": 1952287,
"author_profile": "https://Stackoverflow.com/users/1952287",
"pm_score": 0,
"selected": false,
"text": "curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.2/install.sh | bash\n export NVM_DIR=\"$([ -z \"${XDG_CONFIG_HOME-}\" ] && printf %s \"${HOME}/.nvm\" || printf %s \"${XDG_CONFIG_HOME}/nvm\")\"\n[ -s \"$NVM_DIR/nvm.sh\" ] && \\. \"$NVM_DIR/nvm.sh\" # This loads nvm\n nvm use 18.12.1\n nvm alias default 18.12.1\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2896780/"
] |
74,618,474
|
<p>I want to describe a network graph of vertices and edges with JSON Schema.</p>
<p>An example JSON could look like this:</p>
<pre class="lang-json prettyprint-override"><code>{
"V": [
"1",
"2",
"3"
],
"E": [
{
"v1": "1",
"v2": "2"
},
{
"v1": "2",
"v2": "3"
}
]
}
</code></pre>
<p>I have a set of 3 vertices and 2 edges to connect them. I want all vertices to have an arbitrary string identifier, so it could also be "node1" or "panda". However, is there a way to validate that the endpoints of my edges only point to existing vertices?</p>
<p>I.e.: Should NOT pass:</p>
<pre class="lang-json prettyprint-override"><code>{
"V": [
"n1",
"n2",
"n3"
],
"E": [
{
"v1": "n1",
"v2": "IdThatDoesNotExistAbove"
}
]
}
</code></pre>
<p>I looked at ENUMs, however, I struggle to have them point at data from a JSON that I want to validate rather than to the specification itself.</p>
|
[
{
"answer_id": 74618674,
"author": "DᴀʀᴛʜVᴀᴅᴇʀ",
"author_id": 1952287,
"author_profile": "https://Stackoverflow.com/users/1952287",
"pm_score": 0,
"selected": false,
"text": "curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.2/install.sh | bash\n export NVM_DIR=\"$([ -z \"${XDG_CONFIG_HOME-}\" ] && printf %s \"${HOME}/.nvm\" || printf %s \"${XDG_CONFIG_HOME}/nvm\")\"\n[ -s \"$NVM_DIR/nvm.sh\" ] && \\. \"$NVM_DIR/nvm.sh\" # This loads nvm\n nvm use 18.12.1\n nvm alias default 18.12.1\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6843456/"
] |
74,618,487
|
<ol>
<li>Why pointer to custom struct doesn't work in that code?</li>
<li>Why I'm getting warning in that line with p->x = x?</li>
<li>Why I'm getting second warning in line with strcpy_s?</li>
</ol>
<pre><code>#include <stdlib.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct sptr {
int x;
char* s;
struct sptr* next;
} ptr;
void add(ptr* p, int x, const char* s) {
ptr* o = p;
p = (ptr*) malloc(sizeof(ptr));
p->x = x; // warning
p->s = (char*)malloc(20 * sizeof(char));
strcpy_s(p->s, 20, (char*)s); // warning
p->next = o;
}
void show(ptr* p) {
ptr* o = p;
while (o != NULL) {
printf("%d %s\n", o -> x, o -> s);
o = o->next;
}
}
int main() {
ptr* p = NULL;
add(p, 5, "xcvxvxv");
add(p, 7, "adadad");
show(p);
return 0;
}
</code></pre>
|
[
{
"answer_id": 74618869,
"author": "Oka",
"author_id": 2505965,
"author_profile": "https://Stackoverflow.com/users/2505965",
"pm_score": 2,
"selected": true,
"text": "add p add malloc p main int int * void change(int *val)\n{ \n *val = 10;\n} \n \nint main(void) \n{\n int a = 5; \n change(&a);\n}\n int * int ** #include <stdlib.h>\n\nvoid change(int **val)\n{\n *val = malloc(sizeof **val);\n}\n\nint main(void)\n{\n int *a;\n change(&a);\n}\n malloc NULL malloc #include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct node {\n int x;\n char *s;\n struct node *next;\n} Node;\n\nvoid add(Node **p, int x, const char *s) {\n Node *new_node = malloc(sizeof *new_node);\n\n if (!new_node) {\n perror(\"allocating node\");\n exit(EXIT_FAILURE);\n }\n\n new_node->s = malloc(1 + strlen(s));\n\n if (!new_node->s) {\n perror(\"allocating node string\");\n exit(EXIT_FAILURE);\n }\n\n new_node->x = x;\n strcpy(new_node->s, s);\n\n new_node->next = *p;\n *p = new_node;\n}\n\nvoid show(Node *p) {\n while (p) {\n printf(\"%d %s\\n\", p->x, p->s);\n p = p->next;\n }\n}\n\nint main(void) {\n Node *list = NULL;\n\n add(&list, 5, \"xcvxvxv\");\n add(&list, 7, \"adadad\");\n\n show(list);\n}\n"
},
{
"answer_id": 74619017,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 0,
"selected": false,
"text": "malloc() NULL"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12726204/"
] |
74,618,512
|
<p>I have a dataframe with stores and its invoices numbers and I need to find the missing consecutive invoices numbers per Store, for example:</p>
<pre><code>df1 = pd.DataFrame()
df1['Store'] = ['A','A','A','A','A','B','B','B','B','C','C','C','D','D']
df1['Invoice'] = ['1','2','5','6','8','20','23','24','30','200','202','203','204','206']
</code></pre>
<pre><code> Store Invoice
0 A 1
1 A 2
2 A 5
3 A 6
4 A 8
5 B 20
6 B 23
7 B 24
8 B 30
9 C 200
10 C 202
11 C 203
12 D 204
13 D 206
</code></pre>
<p>And I want a dataframe like this:</p>
<pre><code> Store MissInvoice
0 A 3
1 A 4
2 A 7
3 B 21
4 B 22
5 B 25
6 B 26
7 B 27
8 B 28
9 B 29
10 C 201
11 D 205
</code></pre>
<p>Thanks in advance!</p>
|
[
{
"answer_id": 74618770,
"author": "Ben Grossmann",
"author_id": 2476977,
"author_profile": "https://Stackoverflow.com/users/2476977",
"pm_score": 1,
"selected": false,
"text": "import pandas as pd\nimport numpy as np\n\ndf1 = pd.DataFrame()\ndf1['Store'] = ['A','A','A','A','A','B','B','B','B','C','C','C']\ndf1['Invoice'] = ['1','2','5','6','8','20','23','24','30','200','202','203']\ndf1['Invoice'] = df1['Invoice'].astype(int)\n\ndf2 = df1.groupby('Store')['Invoice'].agg(['min','max'])\ndf2['MissInvoice'] = [[]]*len(df2)\nfor store,row in df2.iterrows():\n df2.at[store,'MissInvoice'] = np.setdiff1d(np.arange(row['min'],row['max']+1), \n df1.loc[df1['Store'] == store, 'Invoice'])\ndf2 = df2.explode('MissInvoice').drop(columns = ['min','max']).reset_index()\n Store MissInvoice\n0 A 3\n1 A 4\n2 A 7\n3 B 21\n4 B 22\n5 B 25\n6 B 26\n7 B 27\n8 B 28\n9 B 29\n10 C 201\n"
},
{
"answer_id": 74618879,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "groupby.apply set range min max explode (df1.astype({'Invoice': int})\n .groupby('Store')['Invoice']\n .apply(lambda s: set(range(s.min(), s.max())).difference(s))\n .explode().reset_index()\n)\n lambda s: sorted(set(range(s.min(), s.max())).difference(s)) Store Invoice\n0 A 3\n1 A 4\n2 A 7\n3 B 21\n4 B 22\n5 B 25\n6 B 26\n7 B 27\n8 B 28\n9 B 29\n10 C 201\n11 D 205\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15887213/"
] |
74,618,535
|
<p>I have a form that takes file uploads and it currently has a limit of 10 files per upload. There are PHP validations in the backend for this too.</p>
<p>When more than 10 files are attached, I currently have a JavaScript <code>slice(0, 10)</code> method inside a <code>change</code> event for the file input element, which removes any files (and their preview image thumbnails) when the number attached is more than 10 files.</p>
<pre><code>// For each added file, add it to submitData (the DataTransfer Object), if not already present
[...e.target.files].slice(0,10).forEach((file) => {
if (currentSubmitData.every((currFile) => currFile.name !== file.name)) {
submitData.items.add(file);
}
});
</code></pre>
<p><strong>The Issue</strong></p>
<p>What I can’t seem to do though is work out a way to <code>slice()</code> the files array in a compound attachment situation, i.e. if 8 files are attached initially, and then the user decides to add another 4 prior to submitting the form, taking the total to 12. The current slice only happens when more than 10 are added in one go.</p>
<p>I have a <code>decode()</code> method that runs inside a loop (for every image attached) that carries out frontend validations, and a <code>promiseAllSettled()</code> method that waits for the last image to be attached prior to outputting a main error message telling the user to check the specific errors on the page.</p>
<p><strong>Question</strong></p>
<p>How do I slice the array on the total number of files appended, if the user has initially attached a file count less than 10, then attaches further files taking it more than 10 prior to form submission?</p>
<pre><code>const attachFiles = document.getElementById('attach-files'), // file input element
dropZone = document.getElementById('dropzone'),
submitData = new DataTransfer();
dropZone.addEventListener('click', () => {
// assigns the dropzone to the hidden 'files' input element/file picker
attachFiles.click();
});
attachFiles.addEventListener('change', (e) => {
const currentSubmitData = Array.from(submitData.files);
console.log(e.target.files.length);
// For each added file, add it to 'submitData' if not already present (maximum of 10 files with slice(0, 10)
[...e.target.files].slice(0,10).forEach((file) => {
if (currentSubmitData.every((currFile) => currFile.name !== file.name)) {
submitData.items.add(file);
}
});
// Sync attachFiles FileList with submitData FileList
attachFiles.files = submitData.files;
// Clear the previewWrapper before generating new previews
previewWrapper.replaceChildren();
// the 'decode()' function inside the 'showFiles()' function is returned
// we wait for all of the promises for each image to settle
Promise.allSettled([...submitData.files].map(showFiles)).then((results) => {
// output main error message at top of page alerting user to error messages attached to images
});
}); // end of 'change' event listener
function showFiles(file) {
// code to generate image previews and append them to the 'previewWrapper'
// then use the decode() method that returns a promise and do JS validations on the preview images
return previewImage.decode().then(() => {
// preform JS validations and append
}).catch((error) => {
console.log(error)
});
} // end of showfiles(file)
</code></pre>
|
[
{
"answer_id": 74618770,
"author": "Ben Grossmann",
"author_id": 2476977,
"author_profile": "https://Stackoverflow.com/users/2476977",
"pm_score": 1,
"selected": false,
"text": "import pandas as pd\nimport numpy as np\n\ndf1 = pd.DataFrame()\ndf1['Store'] = ['A','A','A','A','A','B','B','B','B','C','C','C']\ndf1['Invoice'] = ['1','2','5','6','8','20','23','24','30','200','202','203']\ndf1['Invoice'] = df1['Invoice'].astype(int)\n\ndf2 = df1.groupby('Store')['Invoice'].agg(['min','max'])\ndf2['MissInvoice'] = [[]]*len(df2)\nfor store,row in df2.iterrows():\n df2.at[store,'MissInvoice'] = np.setdiff1d(np.arange(row['min'],row['max']+1), \n df1.loc[df1['Store'] == store, 'Invoice'])\ndf2 = df2.explode('MissInvoice').drop(columns = ['min','max']).reset_index()\n Store MissInvoice\n0 A 3\n1 A 4\n2 A 7\n3 B 21\n4 B 22\n5 B 25\n6 B 26\n7 B 27\n8 B 28\n9 B 29\n10 C 201\n"
},
{
"answer_id": 74618879,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "groupby.apply set range min max explode (df1.astype({'Invoice': int})\n .groupby('Store')['Invoice']\n .apply(lambda s: set(range(s.min(), s.max())).difference(s))\n .explode().reset_index()\n)\n lambda s: sorted(set(range(s.min(), s.max())).difference(s)) Store Invoice\n0 A 3\n1 A 4\n2 A 7\n3 B 21\n4 B 22\n5 B 25\n6 B 26\n7 B 27\n8 B 28\n9 B 29\n10 C 201\n11 D 205\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19208136/"
] |
74,618,551
|
<p>I want to apply a custom function to every column of <code>df</code> and assign the value that function returns to a new column in that dataframe.
My function takes a vector of values from chosen columns (in my case values from columns 12:17 will be used), and returns a calculated value (diversity index).
The function is defined as:</p>
<pre><code>shannon <- function(p){
if (0 %in% p) {
p = replace(p,p==0,0.0001)
} else {
p
}
H = -sum(p*log(p))
return (H)
}
</code></pre>
<p>A random row from the dataset looks like this:</p>
<pre><code>p <- df[3000,12:17]
x1 x2 x3 x4 x5 x6
0.5777778 0.1777778 0.1555556 0.2888889 0.02222222 0
</code></pre>
<p>When I apply the custom function to this row, like this:</p>
<pre><code>shannon(as.vector(t(p)))
</code></pre>
<p>It returns the correctly calculated value of <code>1.357692</code>.</p>
<p>Now, I want to make this value into a new column of my dataset, by applying the custom function to the specific columns form my dataset. I try to do it using <code>mutate</code> and <code>sapply</code> by running:</p>
<pre><code>df <- mutate(df, shannon = sapply(as.vector(t(census[,12:17])), shannon))
</code></pre>
<p>but it returns</p>
<pre><code>Error in `mutate()`:
! Problem while computing `shannonVal = sapply(as.vector(t(census[, 12:17])), shannon)`.
✖ `shannonVal` must be size 9467 or 1, not 56802.
</code></pre>
<p>The number of rows in my dataset is 9467, so the sapply is returning something that's 6 times as long. But why, and how can I fix it?</p>
|
[
{
"answer_id": 74618770,
"author": "Ben Grossmann",
"author_id": 2476977,
"author_profile": "https://Stackoverflow.com/users/2476977",
"pm_score": 1,
"selected": false,
"text": "import pandas as pd\nimport numpy as np\n\ndf1 = pd.DataFrame()\ndf1['Store'] = ['A','A','A','A','A','B','B','B','B','C','C','C']\ndf1['Invoice'] = ['1','2','5','6','8','20','23','24','30','200','202','203']\ndf1['Invoice'] = df1['Invoice'].astype(int)\n\ndf2 = df1.groupby('Store')['Invoice'].agg(['min','max'])\ndf2['MissInvoice'] = [[]]*len(df2)\nfor store,row in df2.iterrows():\n df2.at[store,'MissInvoice'] = np.setdiff1d(np.arange(row['min'],row['max']+1), \n df1.loc[df1['Store'] == store, 'Invoice'])\ndf2 = df2.explode('MissInvoice').drop(columns = ['min','max']).reset_index()\n Store MissInvoice\n0 A 3\n1 A 4\n2 A 7\n3 B 21\n4 B 22\n5 B 25\n6 B 26\n7 B 27\n8 B 28\n9 B 29\n10 C 201\n"
},
{
"answer_id": 74618879,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "groupby.apply set range min max explode (df1.astype({'Invoice': int})\n .groupby('Store')['Invoice']\n .apply(lambda s: set(range(s.min(), s.max())).difference(s))\n .explode().reset_index()\n)\n lambda s: sorted(set(range(s.min(), s.max())).difference(s)) Store Invoice\n0 A 3\n1 A 4\n2 A 7\n3 B 21\n4 B 22\n5 B 25\n6 B 26\n7 B 27\n8 B 28\n9 B 29\n10 C 201\n11 D 205\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13221062/"
] |
74,618,594
|
<p>I am new to ReactJS and pairing it with Material UI is really causing me some roadblocks. I have created a reusable search filter component for my data tables and it worked exactly the way I wanted, but now I want to add a button to clear the field and show the unfiltered results, as well as return the InputSearch component back to its default state so it will display the label inside the field again, not up in the field’s border as these Material UI TextFields do then they are focused or have a current value. This is where I am hitting my roadblock. I have tried multiple solutions I found online, like using the inputRef/useCallback method to change the values, but it didn’t seem to work…or maybe I misunderstood and did it wrong. I was also recommended to put my search values to state. As happens with state my searches are now always one render behind (I.E. , results matching ‘US’ for ‘USA’ , ‘USA’ for ‘USAF’, etc…). Then when I run the handleFilterReset function to set the filter values back to an empty string, nothing happens. I just want my search filter to work instantly (like it did before I moved the value to state [commented out]) and be able to be cleared, resetting the table back to its default display.<br />
Can someone please help me figure this out? Suggestions are appreciated, but code snippets are much more helpful since I am really new to React and especially Material UI.</p>
<p><em><strong>dataTable.js</strong></em></p>
<pre><code>const [inputValue, setInputValue] = useState('')
const [searchFn, setSearchFn,] = useState({ fn: items => { return items; } });
// Searching Data
const handleSearch = e => {
setInputValue(e.target.value) // value displayed in input field
let query = (e.target.value).toString().toLowerCase();
setSearchFn({
fn: items => {
if (query === "")
return items;
else
return items.filter(x =>
(x.tankName !== null && x.tankName.toLowerCase().includes(query)) ||
(x.dimensions !== null && x.dimensions.toLowerCase().includes(query))
)
}
})
}
// Clearing Filters
const handleFilterReset = () => {
setInputValue('');
setSearchFn({fn: items => {return items;}})
};
// Search and filter Inputs
<div>
<InputSearch
value={inputValue}
onChange={handleSearch}
/>
<Button
text="Reset"
onClick={handleFilterReset}
/>
</div>
</code></pre>
<p><em><strong>InputSearch.js</strong></em></p>
<pre><code>export default function InputSearch(props) {
const { inputRef, name, value, error=null, onChange, ...other } = props;
return (
<TextField
label="Search..."
name={name}
value={value}
onChange={onChange}
{...other}
{...(error && {error:true, helperText:error})}
>
</TextField>
)
}
</code></pre>
|
[
{
"answer_id": 74618770,
"author": "Ben Grossmann",
"author_id": 2476977,
"author_profile": "https://Stackoverflow.com/users/2476977",
"pm_score": 1,
"selected": false,
"text": "import pandas as pd\nimport numpy as np\n\ndf1 = pd.DataFrame()\ndf1['Store'] = ['A','A','A','A','A','B','B','B','B','C','C','C']\ndf1['Invoice'] = ['1','2','5','6','8','20','23','24','30','200','202','203']\ndf1['Invoice'] = df1['Invoice'].astype(int)\n\ndf2 = df1.groupby('Store')['Invoice'].agg(['min','max'])\ndf2['MissInvoice'] = [[]]*len(df2)\nfor store,row in df2.iterrows():\n df2.at[store,'MissInvoice'] = np.setdiff1d(np.arange(row['min'],row['max']+1), \n df1.loc[df1['Store'] == store, 'Invoice'])\ndf2 = df2.explode('MissInvoice').drop(columns = ['min','max']).reset_index()\n Store MissInvoice\n0 A 3\n1 A 4\n2 A 7\n3 B 21\n4 B 22\n5 B 25\n6 B 26\n7 B 27\n8 B 28\n9 B 29\n10 C 201\n"
},
{
"answer_id": 74618879,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "groupby.apply set range min max explode (df1.astype({'Invoice': int})\n .groupby('Store')['Invoice']\n .apply(lambda s: set(range(s.min(), s.max())).difference(s))\n .explode().reset_index()\n)\n lambda s: sorted(set(range(s.min(), s.max())).difference(s)) Store Invoice\n0 A 3\n1 A 4\n2 A 7\n3 B 21\n4 B 22\n5 B 25\n6 B 26\n7 B 27\n8 B 28\n9 B 29\n10 C 201\n11 D 205\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10982789/"
] |
74,618,601
|
<p>I have a probem with typing this line of code initialState[a][b].</p>
<p>I got this error:</p>
<p>Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ food: { pizza: boolean; chicken: boolean; }; transport: { bus: boolean; car: boolean; }; }'</p>
<pre><code>function testTypescript(a: string, b: string) {
const initialState = {
food: {
pizza: false,
chicken: false,
},
transport: {
bus: false,
car: false,
},
};
const newData = !initialState[a][b]; // How can I type this line?
const newState = { ...initialState, [a]: newData };
return newState;
}
</code></pre>
|
[
{
"answer_id": 74618653,
"author": "OTMANƏ EL",
"author_id": 15025720,
"author_profile": "https://Stackoverflow.com/users/15025720",
"pm_score": 1,
"selected": false,
"text": "function testTypescript(a: string, b: string) {\n const initialState: { [a: string]: { [b: string]: boolean; } } = {\n food: {\n pizza: false,\n chicken: false,\n },\n transport: {\n bus: false,\n car: false,\n },\n };\n const newData: boolean = !initialState[a][b];\n const newState = { ...initialState, [a]: { [b]: newData } };\n return newState;\n}\n"
},
{
"answer_id": 74618717,
"author": "Yury Tarabanko",
"author_id": 351705,
"author_profile": "https://Stackoverflow.com/users/351705",
"pm_score": 2,
"selected": false,
"text": "type State = {\n food: {\n pizza: boolean;\n chicken: boolean;\n };\n\n transport: {\n bus: boolean;\n car: boolean;\n }\n}\n\nfunction testTypescript<T extends keyof State>(a: T, b: keyof State[T]) {\n const initialState: State = {\n food: {\n pizza: false,\n chicken: false,\n },\n transport: {\n bus: false,\n car: false,\n },\n };\n const newData = !initialState[a][b]; // How can I type this line?\n const newState = { ...initialState, [a]: newData };\n return newState;\n}\n\n// @ts-expect-error\ntestTypescript('notThere', 'value')\n\n// @ts-expect-error\ntestTypescript('food', 'rice')\n\ntestTypescript('transport', 'bus')\n"
},
{
"answer_id": 74619119,
"author": "serg Ks",
"author_id": 14408255,
"author_profile": "https://Stackoverflow.com/users/14408255",
"pm_score": 0,
"selected": false,
"text": "type initial = {\n [key: string] : any;\n}\n\nfunction testTypescript(a: string, b: string) {\n const initialState : initial = {\n food: {\n pizza: false,\n chicken: false,\n },\n transport: {\n bus: false,\n car: false,\n },\n };\n const newData = !initialState[a][b]; // How can I type this line?\n const newState = { ...initialState, [a]: newData };\n return newState;\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17194532/"
] |
74,618,655
|
<p>I'm using a while to try to show all the rows in the database table that contain the card number equal to the one entered, it's not working, it's just reading the first line.</p>
<pre><code>private static string getExtrato(string query)
{
using (var cn = new SqlConnection("Data Source=MAD-PC-023\\SQLEXPRESS;Database=bank;Trusted_Connection=True;"))
{
cn.Open();
using (var cmd = new SqlCommand() { Connection = cn, CommandText = query })
{
var reader = cmd.ExecuteReader();
while (reader.Read() == true)
{
if (reader.GetString(1) == null)
{
return "\n O cartão nº " + reader.GetString(0) + " levantou: " + reader.GetString(2) + " euros " + " às: " + reader.GetDateTime(3);
}
else
{
return "\n O cartão nº " + reader.GetString(0) + " depositou: " + reader.GetString(1) + " euros " + " às: " + reader.GetDateTime(3);
}
}
return "";
}
}
}
private static string extratoOperacao(string numeroCartao)
{
return getExtrato($@"SELECT CardNumber, Deposit, Withdraw, DataHora FROM MoveInfo WHERE CardNumber = '{numeroCartao}'");
}
</code></pre>
<p>I don't know what I have to change to work</p>
|
[
{
"answer_id": 74618768,
"author": "David",
"author_id": 328193,
"author_profile": "https://Stackoverflow.com/users/328193",
"pm_score": 3,
"selected": true,
"text": "private static string getExtrato(string query)\n private static IEnumerable<string> getExtrato(string query)\n var result = new List<string>();\nwhile (reader.Read() == true)\n{\n if (reader.GetString(1) == null)\n {\n result.Add(\"\\n O cartão nº \" + reader.GetString(0) + \" levantou: \" + reader.GetString(2) + \" euros \" + \" às: \" + reader.GetDateTime(3));\n }\n else\n {\n result.Add(\"\\n O cartão nº \" + reader.GetString(0) + \" depositou: \" + reader.GetString(1) + \" euros \" + \" às: \" + reader.GetDateTime(3));\n }\n}\nreturn result;\n"
},
{
"answer_id": 74618860,
"author": "Desenfoque",
"author_id": 736643,
"author_profile": "https://Stackoverflow.com/users/736643",
"pm_score": 0,
"selected": false,
"text": " while (reader.Read() == true)\n {\n if (condition is met)\n {\n return \"something\";\n }\n else //If condition is not met\n {\n return \"something else\"\n }\n }\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20571251/"
] |
74,618,656
|
<p>I'm trying to handle CORS issue and add necessary strings to respond's headers:
`</p>
<pre><code>var express = require('express');
const app = express();
var router = express.Router();
router.options('/*', function(req, res, next){
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
res.sendStatus(200);
console.log(res.getHeaders());
});
</code></pre>
<p>`
But it doesn't work - console.log(res.getHeaders()) shows standard header:</p>
<pre><code>[Object: null prototype] {
'x-powered-by': 'Express',
'content-type': 'text/plain; charset=utf-8',
'content-length': '2',
etag: 'W/"2-nOO9QiTIwXgNtWtBJezz8kv3SLc"'
}
</code></pre>
<p>What might prevent triggering this function?</p>
<p>In despair, I tried this construction:
`</p>
<pre><code>router.options('/*', function(req, res, next){
const respond = async function() {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
}
respond()
res.sendStatus(200);
console.log(res.getHeaders());
});
</code></pre>
<p>`
And it does work:</p>
<pre><code>[Object: null prototype] {
'x-powered-by': 'Express',
'access-control-allow-origin': '*',
'access-control-allow-headers': 'Origin, X-Requested-With, Content-Type, Accept',
'content-type': 'text/plain; charset=utf-8',
'content-length': '2',
etag: 'W/"2-nOO9QiTIwXgNtWtBJezz8kv3SLc"'
}
OPTIONS /email 200 4.345 ms - 2
</code></pre>
<p>What I'm doing wrong and where to look for the error</p>
|
[
{
"answer_id": 74618768,
"author": "David",
"author_id": 328193,
"author_profile": "https://Stackoverflow.com/users/328193",
"pm_score": 3,
"selected": true,
"text": "private static string getExtrato(string query)\n private static IEnumerable<string> getExtrato(string query)\n var result = new List<string>();\nwhile (reader.Read() == true)\n{\n if (reader.GetString(1) == null)\n {\n result.Add(\"\\n O cartão nº \" + reader.GetString(0) + \" levantou: \" + reader.GetString(2) + \" euros \" + \" às: \" + reader.GetDateTime(3));\n }\n else\n {\n result.Add(\"\\n O cartão nº \" + reader.GetString(0) + \" depositou: \" + reader.GetString(1) + \" euros \" + \" às: \" + reader.GetDateTime(3));\n }\n}\nreturn result;\n"
},
{
"answer_id": 74618860,
"author": "Desenfoque",
"author_id": 736643,
"author_profile": "https://Stackoverflow.com/users/736643",
"pm_score": 0,
"selected": false,
"text": " while (reader.Read() == true)\n {\n if (condition is met)\n {\n return \"something\";\n }\n else //If condition is not met\n {\n return \"something else\"\n }\n }\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20242821/"
] |
74,618,661
|
<p>I want to add and remove items in MutableLiveData<ArrayList<String>>. Adding items to the list is working fine and UI is also updating. But removal from array list is not working properly.</p>
<pre><code>@HiltViewModel
class SecondViewModel @Inject constructor() : ViewModel() {
private var _languagesList : MutableLiveData<ArrayList<String>> = MutableLiveData()
val languagesList : LiveData<ArrayList<String>> get() = _languagesList
fun addInList() {
val a = arrayListOf<String>()
a.add("c++")
_languagesList.postValue(a)
}
fun removeFromList() {
_languagesList.value?.removeAt(0);
//How to notify UI here
}
}
</code></pre>
|
[
{
"answer_id": 74618768,
"author": "David",
"author_id": 328193,
"author_profile": "https://Stackoverflow.com/users/328193",
"pm_score": 3,
"selected": true,
"text": "private static string getExtrato(string query)\n private static IEnumerable<string> getExtrato(string query)\n var result = new List<string>();\nwhile (reader.Read() == true)\n{\n if (reader.GetString(1) == null)\n {\n result.Add(\"\\n O cartão nº \" + reader.GetString(0) + \" levantou: \" + reader.GetString(2) + \" euros \" + \" às: \" + reader.GetDateTime(3));\n }\n else\n {\n result.Add(\"\\n O cartão nº \" + reader.GetString(0) + \" depositou: \" + reader.GetString(1) + \" euros \" + \" às: \" + reader.GetDateTime(3));\n }\n}\nreturn result;\n"
},
{
"answer_id": 74618860,
"author": "Desenfoque",
"author_id": 736643,
"author_profile": "https://Stackoverflow.com/users/736643",
"pm_score": 0,
"selected": false,
"text": " while (reader.Read() == true)\n {\n if (condition is met)\n {\n return \"something\";\n }\n else //If condition is not met\n {\n return \"something else\"\n }\n }\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14861313/"
] |
74,618,694
|
<p>I am hiding and showing forms through Form Collection as a user timeout feature and need to call a public method in each form as I am showing it again to update the form with the logged in user (in the event it changes).</p>
<p>I am, however, having issue with this as it does not seem that I am able to do this direct from the iteration of the form collection. Does anyone have any recommendations?</p>
<p>Here is the code that I am working off of. Any help is very much appreciated!</p>
<pre><code>FormCollection fc = Application.OpenForms;
foreach (Form frm in fc)
{
if (frm.Visible == false && frm.Name != "FStart" && frm.Name != "FMain")
{
//Here I would like to call frm.UpdateUser(.....);
frm.Show();
}
}
</code></pre>
<p>I appreciate everyone's help. The method is a public void in each form.</p>
<p>I've tried to access the public method from the form collection and I've tried to access the method directly.</p>
|
[
{
"answer_id": 74620991,
"author": "Jonathan Barraone",
"author_id": 17957703,
"author_profile": "https://Stackoverflow.com/users/17957703",
"pm_score": -1,
"selected": false,
"text": "UpdateUser FormCollection fc = Application.OpenForms;\n\nforeach (dynamic frm in fc)\n{\n if (frm.Name != \"FStart\" && frm.Name != \"FMain\")\n {\n frm.UpdateUser(); //You will still have to add the arguments....\n frm.Show();\n }\n }\n dynamic"
},
{
"answer_id": 74621337,
"author": "IVSoftware",
"author_id": 5438626,
"author_profile": "https://Stackoverflow.com/users/5438626",
"pm_score": 0,
"selected": false,
"text": "Application.OpenForms Visible==false Application.OpenForms false frm.Show() public partial class MainForm : Form\n{\n /// <summary>\n /// Mixed list of Form references where \"some\" will implement `UpdateUser`\n /// </summary>\n List<Form> AllForms = new List<Form>();\n\n public MainForm()\n {\n InitializeComponent();\n }\n protected override void OnLoad(EventArgs e)\n {\n base.OnLoad(e);\n AllForms.Add(this);\n AllForms.Add(new UserFormA());\n AllForms.Add(new UserFormB());\n }\n}\n Form foreach (Form frm in fc)... Form UserUpdate UpdateUser UpdateUser IUpdatableUserForm Form interface IUpdatableUserForm\n{\n void UpdateUser();\n string Name { get; set; }\n bool Visible { get; set; }\n public void Show(IWin32Window owner);\n}\npublic class UserFormA : Form, IUpdatableUserForm\n{\n public UserFormA()\n {\n Name = nameof(UserFormA);\n }\n public void UpdateUser()\n {\n Size = new Size(500, 300);\n Text = Name;\n }\n}\n is dynamic Form UpdateUser private void onTest()\n{\n foreach (Form frm in AllForms)\n {\n if (frm is IUpdatableUserForm safeForm)\n {\n if (!safeForm.Visible)\n {\n switch (safeForm.Name)\n {\n case \"FStart\":\n case \"FMain\":\n break;\n default:\n // Here I would like to call frm.UpdateUser(.....);\n safeForm.UpdateUser();\n safeForm.Show(this);\n break;\n }\n }\n }\n }\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10609304/"
] |
74,618,698
|
<p>According to <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement#remarks" rel="nofollow noreferrer">MSDN</a> and <a href="https://stackoverflow.com/a/278924">this accepted answer</a>,</p>
<pre><code>using (T resource = expression)
embedded-statement
</code></pre>
<p>is translated by the compiler as the following code:</p>
<pre><code>{
T resource = expression;//Shouldn't this statement be moved inside the try block?
try
{
embedded-statement
}
finally
{
if (resource != null)
((IDisposable)resource).Dispose();
}
}
</code></pre>
<p>My question is: Why is there an extra <code>{}</code> around the try block? Shouldn't the first statement be moved inside the try block?</p>
<p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement#remarks" rel="nofollow noreferrer">MSDN</a> explains:</p>
<blockquote>
<p>The code example earlier expands to the following code at compile time
<strong>(note the extra curly braces to create the limited scope for the object)</strong>:</p>
</blockquote>
<p>But according to another <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-finally" rel="nofollow noreferrer">MSDN</a> page,</p>
<blockquote>
<p>By using a finally block, you can clean up any resources that are
allocated <em><strong>in a try block</strong></em></p>
</blockquote>
<p>Updated:
If variable visibility is the reason, then how about we declare the variable first and assign it null, then initialize it inside the try block? Is this better than the original code?</p>
<pre><code>{
T resource = null;//Now it is visible in the try block
try
{
resource =expression;// in case an exception is thrown here
embedded-statement
}
finally
{
if (resource != null)
((IDisposable)resource).Dispose();
}
}
</code></pre>
|
[
{
"answer_id": 74618739,
"author": "Olivier Jacot-Descombes",
"author_id": 880990,
"author_profile": "https://Stackoverflow.com/users/880990",
"pm_score": 0,
"selected": false,
"text": "class Resource : IDisposable\n{\n public void Dispose()\n {\n Console.WriteLine(\"disposing\");\n }\n\n public override string ToString() => \"not null\";\n}\n private static Resource Throw()\n{\n throw new NotImplementedException();\n}\n Resource resource = new();\ntry {\n using (resource = Throw()) {\n Console.WriteLine(\"inside using block\");\n }\n Console.WriteLine(\"after using block\");\n} catch {\n Console.WriteLine($\"catch: resource is {resource}\");\n}\n disposing catch: resource is not null\n using finally null try try-finally"
},
{
"answer_id": 74618893,
"author": "Sweeper",
"author_id": 5133585,
"author_profile": "https://Stackoverflow.com/users/5133585",
"pm_score": 3,
"selected": false,
"text": "{} using T resource = expression;\ntry\n{\n embedded-statement\n}\nfinally\n{\n if (resource != null)\n ((IDisposable)resource).Dispose();\n}\n\n// resource is still in scope here!\n resource using resource Console.WriteLine(resource); using using {} using try try resource finally try"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2930744/"
] |
74,618,712
|
<p>I want to read the data on an excel file within a F drive. I am using python on Visual Studio Code to try achieve this however I am getting an error as seen in the pictures below. I installed pandas but I still get an error. How can I fix this issue?</p>
<p><a href="https://i.stack.imgur.com/XFyH4.png" rel="nofollow noreferrer">Coding Error</a></p>
<p><a href="https://i.stack.imgur.com/p1aiN.png" rel="nofollow noreferrer">Installed Pandas Library</a></p>
<p>I tried closing and opening visual studio. I tried uninstalling and reinstalling pandas.</p>
<p><a href="https://i.stack.imgur.com/d3xEp.png" rel="nofollow noreferrer">Python on Computer</a></p>
|
[
{
"answer_id": 74618732,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "pip freeze pip3 freeze"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20636206/"
] |
74,618,714
|
<p>I'm trying to create a program that reads some string, but when I test a very long string, an overflow occurs, and all the solutions I've already seen do not work. The following code is:</p>
<pre><code>#include <stdio.h>
int main()
{
char nome[201] = {0};
char cpf[15] = {0};
char senha[101] = {0};
scanf("%200s", nome);
scanf("%14s", cpf);
scanf("%100s", senha);
printf("nome: %s\n", nome);
printf("cpf: %s\n", cpf);
printf("senha: %s\n", senha);
return 0;
}
</code></pre>
<p>This code is supposed to prevent the overflow, but the following string:</p>
<pre><code>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaassssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss
</code></pre>
<p>I'm trying to put the string in all inputs and when it comes to the second the program is finished and the overflow content goes to the third string.</p>
|
[
{
"answer_id": 74618812,
"author": "Silvio Mayolo",
"author_id": 2288659,
"author_profile": "https://Stackoverflow.com/users/2288659",
"pm_score": 2,
"selected": false,
"text": "std::getline scanf(\"%200s%*[^\\n]\", nome);\n * [^\\n]"
},
{
"answer_id": 74619351,
"author": "Andreas Wenzel",
"author_id": 12149471,
"author_profile": "https://Stackoverflow.com/users/12149471",
"pm_score": 1,
"selected": false,
"text": "nome scanf(\"%200s\", nome);\n scanf(\"%14s\", cpf);\n scanf(\"%100s\", senha);\n senha scanf( \"%*[^\\n]\" );\n scanf %s scanf fgets fgets get_line_from_user fgets #include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nvoid get_line_from_user( char *buffer, int buffer_size );\n\nint main()\n{\n char nome[201] = {0};\n char cpf[15] = {0};\n char senha[101] = {0};\n\n printf( \"Input Phase: \\n\\n\" );\n\n //read inputs\n printf( \"Nome: \" );\n get_line_from_user( nome, sizeof nome );\n printf( \"Cpf: \" );\n get_line_from_user( cpf, sizeof cpf );\n printf( \"Senha: \" );\n get_line_from_user( senha, sizeof senha );\n\n printf( \"\\n\\nOutput Phase: \\n\\n\" );\n\n //output the results\n printf(\"nome: %s\\n\", nome);\n printf(\"cpf: %s\\n\", cpf);\n printf(\"senha: %s\\n\", senha);\n\n return 0;\n}\n\n//This function will read exactly one line of input from the\n//user and discard the newline character. If the line does\n//not fit into the buffer, it will also discard the rest of\n//the line from the input stream.\nvoid get_line_from_user( char *buffer, int buffer_size )\n{\n char *p;\n\n //attempt to read one line of input\n if ( fgets( buffer, buffer_size, stdin ) == NULL )\n {\n printf( \"Error reading from input\\n\" );\n exit( EXIT_FAILURE );\n }\n\n //attempt to find newline character\n p = strchr( buffer, '\\n' );\n\n //determine whether entire line was read in (i.e. whether\n //the buffer was too small to store the entire line)\n if ( p == NULL )\n {\n int c;\n\n //discard remainder of line from input stream\n do\n {\n c = getchar();\n \n } while ( c != EOF && c != '\\n' );\n }\n else\n {\n //remove newline character by overwriting it with\n //null character\n *p = '\\0';\n }\n}\n Input Phase: \n\nNome: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaassssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\nCpf: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaassssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\nSenha: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaassssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\n\n\nOutput Phase: \n\nnome: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaassssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\ncpf: aaaaaaaaaaaaaa\nsenha: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaassssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\n Input Phase: \n\nNome: This is a test \nCpf: Another test\nSenha: Yet another test\n\n\nOutput Phase: \n\nnome: This is a test\ncpf: Another test\nsenha: Yet another test\n"
},
{
"answer_id": 74620033,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 2,
"selected": true,
"text": "fgets() // Return 1 on success.\n// Return EOF on input error or end-of-file with no input.\n// Return 0 when input exceeds buffer space.\n// A line's \\n is read, but not saved.\n// If using explicitly C needs to include stdbool.h library\nint read1line(size_t n, char * restrict s, FILE * restrict stream) {\n if (fgets(s, n, stream) == NULL) {\n return EOF;\n }\n size_t len = strlen(s);\n // Was a \\n read?\n if (len > 0 && s[len-1] == '\\n') {\n s[--len] = '\\0';\n }\n // Potentially more?\n if (len + 1 == n) {\n int ch;\n bool more_read = false;\n while ((ch = fgetc(stream)) != '\\n' && ch != EOF) {\n more_read = true;\n }\n if (ch == EOF && !feof(stream)) {\n return EOF;\n }\n if (more_read) {\n return 0;\n }\n } \n return 1;\n}\n len s == NULL n <= 0 n > INT_MAX CHAR_MAX > INT_MAX"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10912555/"
] |
74,618,724
|
<p>I'm trying to define an array and add elements to it, but there's a problem with that</p>
<pre><code> $prodectsum = array();
</code></pre>
<pre><code> $prodectsum->push((object)['name' => 'mmm', 'color' => 'red']);
</code></pre>
<p>Define an array in Laravel</p>
|
[
{
"answer_id": 74619779,
"author": "Christopher Furman",
"author_id": 10287952,
"author_profile": "https://Stackoverflow.com/users/10287952",
"pm_score": 0,
"selected": false,
"text": "$newArray = array()\n$newArray[] = $someObject;\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18505964/"
] |
74,618,748
|
<p>So basically when I try to log a user in and I type the password or username wrong and then I try to log in with correct credentials I get this error.</p>
<pre><code>Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:371:5)
at ServerResponse.setHeader (node:_http_outgoing:576:11)
at ServerResponse.header (D:\ecom website\ecom backend\node_modules\express\lib\response.js:794:10)
at ServerResponse.send (D:\ecom website\ecom backend\node_modules\express\lib\response.js:174:12)
at ServerResponse.json (D:\ecom website\ecom backend\node_modules\express\lib\response.js:278:15)
at D:\ecom website\ecom backend\routes\auth.js:57:21
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ERR_HTTP_HEADERS_SENT'
}
[nodemon] app crashed - waiting for file changes before starting...
</code></pre>
<p>And this is my code in auth.js</p>
<pre><code>
//LOGIN
router.post('/login', async (req, res) => {
try {
const user = await User.findOne({
username: req.body.username,
});
!user && res.status(401).json('Wrong User Name');
const hashedPassword = CryptoJS.AES.decrypt(
user.password,
process.env.PASS_SEC
);
const originalPassword = hashedPassword.toString(CryptoJS.enc.Utf8);
const inputPassword = req.body.password;
originalPassword != inputPassword && res.status(401).json('Wrong Password');
const accessToken = jwt.sign(
{
id: user._id,
isAdmin: user.isAdmin,
},
process.env.JWT_SEC,
{ expiresIn: '3d' }
);
const { password, ...others } = user._doc;
res.status(200).json({ ...others, accessToken });
} catch (err) {
res.status(500).json(err);
}
});
</code></pre>
<p>What should I do? Is something wrong with my code?</p>
|
[
{
"answer_id": 74618808,
"author": "Guss",
"author_id": 53538,
"author_profile": "https://Stackoverflow.com/users/53538",
"pm_score": 1,
"selected": false,
"text": "res.status(code).json(content)"
},
{
"answer_id": 74619008,
"author": "derpirscher",
"author_id": 3776927,
"author_profile": "https://Stackoverflow.com/users/3776927",
"pm_score": 3,
"selected": true,
"text": "!user && res.status(401).json('Wrong User Name'); res.status(...) if (!user) {\n return res.status(401).json('Wrong User Name');\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17933699/"
] |
74,618,753
|
<pre><code>builder: (context, state) {
if(state.status == RecievingState.success && state.userData != null){
return Column(
children: [ Vibration.vibrate(); //error
],)
},
}
</code></pre>
<p>as soon as the data is changed from API. I want the phone to vibrate within same page...</p>
|
[
{
"answer_id": 74618844,
"author": "sasikumar",
"author_id": 3710865,
"author_profile": "https://Stackoverflow.com/users/3710865",
"pm_score": 0,
"selected": false,
"text": "Column(\nchildren: <Widget>[\nconst Text('hello'),\nconst Text('world'),\n] )\n"
},
{
"answer_id": 74618914,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 2,
"selected": false,
"text": "if builder: (context, state) {\n if(state.status == RecievingState.success && state.userData != null){\n Vibration.vibrate();\n return Column(\n children: [ \n bool build"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20637078/"
] |
74,618,779
|
<p>I have two arrays as follows,</p>
<p><strong>columnNames</strong> = ['KEY_ID', 'SOURCE_ID', 'MTNAME', 'MTNO', 'PLANTS']</p>
<p><strong>columnValues</strong> = [{col0:"719801", col1: "4198", col2: "010", col3: "200887", col4: "6LLA"},
{col0:"719901", col1: "5198", col2: "011", col3: "207887", col4: "6PPA"}]</p>
<p>My expected output is,</p>
<p><strong>outputArray</strong> = [{KEY_ID:"719801", SOURCE_ID: "4198", MTNAME: "010", MTNO: "200887", PLANTS: "6LLA"},
{KEY_ID:"719901", SOURCE_ID: "5198", MTNAME: "011", MTNO: "207887", PLANTS: "6PPA"}]</p>
<p>The number of items and contents of both arrays change dynamically i.e., <strong>columnNames</strong> can have different names and <strong>columnValues</strong> can have any number of values. Any inputs to obtain the final <strong>outputArray</strong> will be highly helpful.
I have tried using <em>reduce</em>. It either requires multiple iterations or the <strong>columnNames</strong> array to be constant.</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>let renameKeys = (columnValues, object) =>
Object.keys(object).reduce(
(acc, key) => ({
...acc,
...{ [columnValues[key] || key]: object[key] },
}),
{}
);
console.log(renameKeys(columnNames,columnValues))</code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74618916,
"author": "mplungjan",
"author_id": 295783,
"author_profile": "https://Stackoverflow.com/users/295783",
"pm_score": 0,
"selected": false,
"text": "const columnNames = ['KEY_ID', 'SOURCE_ID', 'MTNAME', 'MTNO', 'PLANTS'],\ncolumnValues = {col0:\"719801\", col1: \"4198\", col2: \"010\", col3: \"200887\", col4: \"6LLA\"}\nlet renameKeys = (columnValues, object) => \n Object.values(object).reduce((acc, val, i) => {\n acc[columnNames[i]] = val;\n return acc}, \n {});\n\n\nconsole.log(renameKeys(columnNames, columnValues))"
},
{
"answer_id": 74627076,
"author": "Aakash Govardhane",
"author_id": 17251507,
"author_profile": "https://Stackoverflow.com/users/17251507",
"pm_score": 1,
"selected": false,
"text": "let columnNames = ['KEY_ID', 'SOURCE_ID', 'MTNAME', 'MTNO', 'PLANTS']\nlet columnValues = [{col0:\"719801\", col1: \"4198\", col2: \"010\", col3: \"200887\", col4: \"6LLA\"}, {col0:\"719901\", col1: \"5198\", col2: \"011\", col3: \"207887\", col4: \"6PPA\"}]\n\nrenameKey = (obj, old_key, new_key) => { \n // check if old key = new key \n if (old_key !== new_key) { \n Object.defineProperty(obj, new_key, // modify old key\n // fetch description from object\n Object.getOwnPropertyDescriptor(obj, old_key));\n delete obj[old_key]; // delete old key\n }\n }\n\ncolumnValues.map((cv)=>{\nObject.keys(cv).map((keys,index)=>{\n renameKey(cv,keys,columnNames[index])\n })\n})\nconsole.log(columnValues)"
},
{
"answer_id": 74629141,
"author": "Rohìt Jíndal",
"author_id": 4116300,
"author_profile": "https://Stackoverflow.com/users/4116300",
"pm_score": 2,
"selected": true,
"text": "Array.forEach() const columnNames = ['KEY_ID', 'SOURCE_ID', 'MTNAME', 'MTNO', 'PLANTS'];\n\nconst columnValues = [{col0:\"719801\", col1: \"4198\", col2: \"010\", col3: \"200887\", col4: \"6LLA\"}, {col0:\"719901\", col1: \"5198\", col2: \"011\", col3: \"207887\", col4: \"6PPA\"}];\n\ncolumnValues.forEach(obj => {\n Object.keys(obj).forEach((key, index) => {\n obj[columnNames[index]] = obj[key]\n delete obj[key];\n });\n});\n\nconsole.log(columnValues);"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1367592/"
] |
74,618,800
|
<p>For each variable in var1, I want its interaction with each variable in var2. In Stata, I can simply use a nested foreach loop to do this but I am not able to replicate the logic in R.</p>
<p>Stata code:</p>
<pre><code>foreach var1 in
gdp_g gdp_g_l GPCP_g GPCP_g_l
{;
foreach var2 in
polity2l y_0 ethfrac Oil lmtnest
{;
quietly gen `var1'_`var2' = `var1'*`var2';
};
};
</code></pre>
<p>Not sure about the intuition in R.</p>
<pre><code>vars1 <- list("gdp_g", "gdp_g_l", "GPCP_g", "GPCP_g_l")
vars2 <- list("polity2l", "y_0", "ethfrac", "Oil", "lmtnest")
multiplyit <- function(x){
paste(x, collapse = "*")
}
for(i in 1:length(vars1)) {
for(j in 1:length(var2)){
vars1[i]*vars2[j]
}
}
</code></pre>
<p>Maybe I need to use a formula to multiply each unique combination of variables.</p>
|
[
{
"answer_id": 74618916,
"author": "mplungjan",
"author_id": 295783,
"author_profile": "https://Stackoverflow.com/users/295783",
"pm_score": 0,
"selected": false,
"text": "const columnNames = ['KEY_ID', 'SOURCE_ID', 'MTNAME', 'MTNO', 'PLANTS'],\ncolumnValues = {col0:\"719801\", col1: \"4198\", col2: \"010\", col3: \"200887\", col4: \"6LLA\"}\nlet renameKeys = (columnValues, object) => \n Object.values(object).reduce((acc, val, i) => {\n acc[columnNames[i]] = val;\n return acc}, \n {});\n\n\nconsole.log(renameKeys(columnNames, columnValues))"
},
{
"answer_id": 74627076,
"author": "Aakash Govardhane",
"author_id": 17251507,
"author_profile": "https://Stackoverflow.com/users/17251507",
"pm_score": 1,
"selected": false,
"text": "let columnNames = ['KEY_ID', 'SOURCE_ID', 'MTNAME', 'MTNO', 'PLANTS']\nlet columnValues = [{col0:\"719801\", col1: \"4198\", col2: \"010\", col3: \"200887\", col4: \"6LLA\"}, {col0:\"719901\", col1: \"5198\", col2: \"011\", col3: \"207887\", col4: \"6PPA\"}]\n\nrenameKey = (obj, old_key, new_key) => { \n // check if old key = new key \n if (old_key !== new_key) { \n Object.defineProperty(obj, new_key, // modify old key\n // fetch description from object\n Object.getOwnPropertyDescriptor(obj, old_key));\n delete obj[old_key]; // delete old key\n }\n }\n\ncolumnValues.map((cv)=>{\nObject.keys(cv).map((keys,index)=>{\n renameKey(cv,keys,columnNames[index])\n })\n})\nconsole.log(columnValues)"
},
{
"answer_id": 74629141,
"author": "Rohìt Jíndal",
"author_id": 4116300,
"author_profile": "https://Stackoverflow.com/users/4116300",
"pm_score": 2,
"selected": true,
"text": "Array.forEach() const columnNames = ['KEY_ID', 'SOURCE_ID', 'MTNAME', 'MTNO', 'PLANTS'];\n\nconst columnValues = [{col0:\"719801\", col1: \"4198\", col2: \"010\", col3: \"200887\", col4: \"6LLA\"}, {col0:\"719901\", col1: \"5198\", col2: \"011\", col3: \"207887\", col4: \"6PPA\"}];\n\ncolumnValues.forEach(obj => {\n Object.keys(obj).forEach((key, index) => {\n obj[columnNames[index]] = obj[key]\n delete obj[key];\n });\n});\n\nconsole.log(columnValues);"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13416745/"
] |
74,618,838
|
<p>So I admit, I am a complete noob with bash scripting and this assignment is completely dominating me. It is stated above. I believe I managed to figure out the first part in regard to the user input, printing out the amount of terms, and carrying out the correct operation. However, feel free to make suggestions if you notice an error or something that is not best practice. What I am struggling to figure out how to print the sum of the terms that the user has input. Any assistance is appreciated, thank you. My code this far along which is only tasked 1 is listed below; thanks in advance.</p>
<blockquote>
<p>Task 3: Find the terms of a sequence given by the rule <code>Term = an² + bn + c</code>, where <code>a</code> and <code>b</code> and <code>c</code> are integers specified by the user and <code>n</code> is a positive integer. This task should give the user two options:</p>
<ul>
<li><strong>Option 1)</strong> Find a limited number of terms of the sequence and print them in order (for example, if the user choses <code>a=3</code>, <code>b=4</code>, and <code>c=1</code> the first few terms of this sequence are: <code>8</code>, <code>21</code>, <code>40</code>, <code>65</code>, <code>96</code>… ). The user also specifies how many terms the program should print. In addition, the program should print the sum of the terms found.</li>
<li><strong>Option 2)</strong> Find a term in a position chosen by the user and determine whether this term is a multiple of a number chosen also by the user. For example, for the above sequence where <code>a=3</code>, <code>b=4</code> and <code>c=1</code>, if the user requires to print the 10th term and to check whether this term is a multiple of <code>3</code>, the program should print:
<br>
<code>341 is not a multiple of 3.</code></li>
</ul>
</blockquote>
<pre class="lang-bash prettyprint-override"><code>#!/bin/bash
#user selects values for a, b, c
read -p "Please provide value to a:" a
read -p "Please provide value to b:" b
read -p "Please provide value to c:" c
#menu begins
echo "SELECT ONE OPTION";
echo "1. Option1- Find Limited Number of terms of the sequence"
echo "2. Option2- Find a term in a position"
echo -n "Enter your menu choice [1-2]:"
#menu ends
read choice
case $choice in
1) read -p "please provide number of terms to print:" num
n=1
arr=()
while [ $n -le $num ]
do
echo term=$(($a*$n^2+$b*$n+$c))
n=$(( n + 1))
arr+=("$term")
done
;;
</code></pre>
<p>After 10 hours of trying to figure out how to execute this task, I've tried quite a few things. However, as I stated I was a noob, I believe they were all just from lack of experience and definitely errors on my end.</p>
|
[
{
"answer_id": 74620056,
"author": "Eric Marceau",
"author_id": 9716110,
"author_profile": "https://Stackoverflow.com/users/9716110",
"pm_score": 1,
"selected": false,
"text": "a=\"\"\nwhile [ -z \"${a}\" ]\ndo\n echo \"\"\n read -p \"Please provide value to a => \" a\n if [ -n \"${a}\" ]\n then\n if [ $a -lt 0 ]\n then\n echo \"\\t Invalid integer input. Please try again ...\"\n a=\"\"\n fi\n fi\ndone\n"
},
{
"answer_id": 74620465,
"author": "Eric Marceau",
"author_id": 9716110,
"author_profile": "https://Stackoverflow.com/users/9716110",
"pm_score": 0,
"selected": false,
"text": "#!/bin/bash\n#Question: https://stackoverflow.com/questions/74618838/how-to-print-sum-of-user-terms-that-was-produced-using-a-formula-where-user-sele/74620056#74620056\nget_a(){\n a=\"\"\n while [ -z \"${a}\" ]\n do\n echo \"\"\n read -p \"Please provide value to a => \" a\n if [ -n \"${a}\" ]\n then\n if [ $a -lt 0 ]\n then\n echo -e \"\\t Invalid integer input. Please try again ...\"\n a=\"\"\n fi\n fi\n done\n}\n#get_a\na=3\nb=4\nc=1\n# Expect Sequence: 8, 21, 40, 65, 96… \n#read choice\nchoice=1\ncase $choice in\n 1 ) #read -p \"How many terms would you like to print => \" num\n num=3\n n=1\n arr=()\n while [ ${n} -le ${num} ]\n do\n printf \"\\n\\t n = ${n} ...\\n\"\n printf \"\\t\\t$(( ${a}*${n}**2 )) \\n\\t\\t$(( ${b}*${n} )) \\n\\t\\t$(( ${c} ))\\n\"\n term=$(( ${a}*${n}**2 + ${b}*${n} + ${c} ))\n printf \"\\t term = ${term} ...\\n\"\n arr[${n}]=${term}\n n=$(( n+1 ))\n done\n echo \"\"\n for i in ${!arr[@]};\n do\n echo \" arr[${i}] = ${arr[${i}]}\"\n done\n ;;\n * ) ;;\nesac\n ericthered@OasisMega1:/0__WORK$ ./test_61.sh\n\n n = 1 ...\n 3 \n 4 \n 1\n term = 8 ...\n\n n = 2 ...\n 12 \n 8 \n 1\n term = 21 ...\n\n n = 3 ...\n 27 \n 12 \n 1\n term = 40 ...\n\n arr[1] = 8\n arr[2] = 21\n arr[3] = 40\nericthered@OasisMega1:/0__WORK$ \n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20392134/"
] |
74,618,850
|
<p>It has been a ling time since i have had to code.</p>
<p>My situation is, i need to make a button that open an HTML file that I have located on my website. The HTML file is a interactive course that will open in a new window.</p>
<p>I have tried <code><a href="home/file.html" target="_blank"><button>launch Course</button></a></code> but I get a "page not found" error.</p>
|
[
{
"answer_id": 74620056,
"author": "Eric Marceau",
"author_id": 9716110,
"author_profile": "https://Stackoverflow.com/users/9716110",
"pm_score": 1,
"selected": false,
"text": "a=\"\"\nwhile [ -z \"${a}\" ]\ndo\n echo \"\"\n read -p \"Please provide value to a => \" a\n if [ -n \"${a}\" ]\n then\n if [ $a -lt 0 ]\n then\n echo \"\\t Invalid integer input. Please try again ...\"\n a=\"\"\n fi\n fi\ndone\n"
},
{
"answer_id": 74620465,
"author": "Eric Marceau",
"author_id": 9716110,
"author_profile": "https://Stackoverflow.com/users/9716110",
"pm_score": 0,
"selected": false,
"text": "#!/bin/bash\n#Question: https://stackoverflow.com/questions/74618838/how-to-print-sum-of-user-terms-that-was-produced-using-a-formula-where-user-sele/74620056#74620056\nget_a(){\n a=\"\"\n while [ -z \"${a}\" ]\n do\n echo \"\"\n read -p \"Please provide value to a => \" a\n if [ -n \"${a}\" ]\n then\n if [ $a -lt 0 ]\n then\n echo -e \"\\t Invalid integer input. Please try again ...\"\n a=\"\"\n fi\n fi\n done\n}\n#get_a\na=3\nb=4\nc=1\n# Expect Sequence: 8, 21, 40, 65, 96… \n#read choice\nchoice=1\ncase $choice in\n 1 ) #read -p \"How many terms would you like to print => \" num\n num=3\n n=1\n arr=()\n while [ ${n} -le ${num} ]\n do\n printf \"\\n\\t n = ${n} ...\\n\"\n printf \"\\t\\t$(( ${a}*${n}**2 )) \\n\\t\\t$(( ${b}*${n} )) \\n\\t\\t$(( ${c} ))\\n\"\n term=$(( ${a}*${n}**2 + ${b}*${n} + ${c} ))\n printf \"\\t term = ${term} ...\\n\"\n arr[${n}]=${term}\n n=$(( n+1 ))\n done\n echo \"\"\n for i in ${!arr[@]};\n do\n echo \" arr[${i}] = ${arr[${i}]}\"\n done\n ;;\n * ) ;;\nesac\n ericthered@OasisMega1:/0__WORK$ ./test_61.sh\n\n n = 1 ...\n 3 \n 4 \n 1\n term = 8 ...\n\n n = 2 ...\n 12 \n 8 \n 1\n term = 21 ...\n\n n = 3 ...\n 27 \n 12 \n 1\n term = 40 ...\n\n arr[1] = 8\n arr[2] = 21\n arr[3] = 40\nericthered@OasisMega1:/0__WORK$ \n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20637193/"
] |
74,618,862
|
<p>the content of the table is this
<a href="https://i.stack.imgur.com/dGZI8.jpg" rel="nofollow noreferrer">enter image description here</a></p>
<pre><code>@section scripts{
<script>
function adddata() {
$.ajax({
type: "POST",
url: '?handler=GetItems',
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
data: { Id: $("#IdSelectIdPuesto").val() },
success: function (data) {
for (var i = 0; i < data.length; i++) {
$("#IdSelectlocalidad").append("<option value='" + data[i].value +
"' selected>" + data[i].text + "</option>");
}
},
error: function (result) {
alert("fail");
}
})
}
</script>
}
</code></pre>
<pre><code>
public JsonResult OnPostGetItems(int Id)
{
//displaydata1 = rTDBContext.Turnos.ToList();
var displayda = (from c in displaydata1
select c.LocNombre).Distinct().ToList();
return new JsonResult(new List<SelectListItem> = { new SelectListItem { Value = "1", Text = "LOcalidad" + 1 }, new SelectListItem { Value = "2", Text = "LOcalidad" + 2 } });
}
</code></pre>
<p>i'm trying a select distinct and add to the specified select the id and the locNombre to the text</p>
|
[
{
"answer_id": 74620056,
"author": "Eric Marceau",
"author_id": 9716110,
"author_profile": "https://Stackoverflow.com/users/9716110",
"pm_score": 1,
"selected": false,
"text": "a=\"\"\nwhile [ -z \"${a}\" ]\ndo\n echo \"\"\n read -p \"Please provide value to a => \" a\n if [ -n \"${a}\" ]\n then\n if [ $a -lt 0 ]\n then\n echo \"\\t Invalid integer input. Please try again ...\"\n a=\"\"\n fi\n fi\ndone\n"
},
{
"answer_id": 74620465,
"author": "Eric Marceau",
"author_id": 9716110,
"author_profile": "https://Stackoverflow.com/users/9716110",
"pm_score": 0,
"selected": false,
"text": "#!/bin/bash\n#Question: https://stackoverflow.com/questions/74618838/how-to-print-sum-of-user-terms-that-was-produced-using-a-formula-where-user-sele/74620056#74620056\nget_a(){\n a=\"\"\n while [ -z \"${a}\" ]\n do\n echo \"\"\n read -p \"Please provide value to a => \" a\n if [ -n \"${a}\" ]\n then\n if [ $a -lt 0 ]\n then\n echo -e \"\\t Invalid integer input. Please try again ...\"\n a=\"\"\n fi\n fi\n done\n}\n#get_a\na=3\nb=4\nc=1\n# Expect Sequence: 8, 21, 40, 65, 96… \n#read choice\nchoice=1\ncase $choice in\n 1 ) #read -p \"How many terms would you like to print => \" num\n num=3\n n=1\n arr=()\n while [ ${n} -le ${num} ]\n do\n printf \"\\n\\t n = ${n} ...\\n\"\n printf \"\\t\\t$(( ${a}*${n}**2 )) \\n\\t\\t$(( ${b}*${n} )) \\n\\t\\t$(( ${c} ))\\n\"\n term=$(( ${a}*${n}**2 + ${b}*${n} + ${c} ))\n printf \"\\t term = ${term} ...\\n\"\n arr[${n}]=${term}\n n=$(( n+1 ))\n done\n echo \"\"\n for i in ${!arr[@]};\n do\n echo \" arr[${i}] = ${arr[${i}]}\"\n done\n ;;\n * ) ;;\nesac\n ericthered@OasisMega1:/0__WORK$ ./test_61.sh\n\n n = 1 ...\n 3 \n 4 \n 1\n term = 8 ...\n\n n = 2 ...\n 12 \n 8 \n 1\n term = 21 ...\n\n n = 3 ...\n 27 \n 12 \n 1\n term = 40 ...\n\n arr[1] = 8\n arr[2] = 21\n arr[3] = 40\nericthered@OasisMega1:/0__WORK$ \n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20007897/"
] |
74,618,868
|
<p>I have an application, in which the Frontend is through Vue and the backend is FastAPI, the communication is done through websocket.</p>
<p>Currently, the frontend allows the user to enter a term, which is sent to the backend to generate the autocomplete and also perform a search on a URL that returns a json. In which, I save this json in the frontend folder. After that, the backend returns the autocomplete data for the term in question to the frontend. The frontend displays the aucomplete along with the json data.</p>
<p>However, when I studied a little more, I noticed that there is a way to send the json returned by the request url to Vue (frontend), without having to save it locally, avoiding giving an error of not allowing to execute this process more than once.</p>
<p>My current code is as follows. For FastAPI (backend):</p>
<pre><code>@app.websocket("/")
async def predict_question(websocket: WebSocket):
await websocket.accept()
while True:
input_text = await websocket.receive_text()
autocomplete_text = text_gen.generate_text(input_text)
autocomplete_text = re.sub(r"[\([{})\]]", "", autocomplete_text)
autocomplete_text = autocomplete_text.split()
autocomplete_text = autocomplete_text[0:2]
resp = req.get('www.description_url_search_='+input_text+'')
datajson = resp.json()
with open('/home/user/backup/AutoComplete/frontend/src/data.json', 'w', encoding='utf-8') as f:
json.dump(datajson, f, ensure_ascii=False, indent=4)
await websocket.send_text(' '.join(autocomplete_text))
</code></pre>
<p>File App.vue (frontend):</p>
<pre><code><template>
<div class="main-container">
<h1 style="color:#0072c6;">Title</h1>
<p style="text-align:center; color:#0072c6;">
Version 0.1
<br>
</p>
<Autocomplete />
<br>
</div>
<div style="color:#0072c6;">
<JsonArq />
</div>
<div style="text-align:center;">
<img src="./components/logo-1536.png" width=250 height=200 alt="Logo" >
</div>
</template>
<script>
import Autocomplete from './components/Autocomplete.vue'
import JsonArq from './components/EstepeJSON.vue'
export default {
name: 'App',
components: {
Autocomplete,
JsonArq: JsonArq
}
}
</script>
<style>
.main-container {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
font-family: 'Fredoka', sans-serif;
}
h1 {
font-size: 3rem;
}
@import url('https://fonts.googleapis.com/css2?family=Fredoka&display=swap');
</style>
</code></pre>
<p>Autocomplete.vue file in the components directory:</p>
<pre><code><template>
<div class="pad-container">
<div tabindex="1" @focus="setCaret" class="autocomplete-container">
<span @input="sendText" @keypress="preventInput" ref="editbar" class="editable" contenteditable="true"></span>
<span class="placeholder" contenteditable="false">{{autoComplete}}</span>
</div>
</div>
</template>
<script>
export default {
name: 'Autocomplete',
data: function() {
return {
autoComplete: "",
maxChars: 75,
connection: null
}
},
mounted() {
const url = "ws://localhost:8000/"
this.connection = new WebSocket(url);
this.connection.onopen = () => console.log("connection established");
this.connection.onmessage = this.receiveText;
},
methods: {
setCaret() {
const range= document.createRange()
const sel = window.getSelection();
const parentNode = this.$refs.editbar;
if (parentNode.firstChild == undefined) {
const emptyNode = document.createTextNode("");
parentNode.appendChild(emptyNode);
}
range.setStartAfter(this.$refs.editbar.firstChild);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
},
preventInput(event) {
let prevent = false;
// handles capital letters, numbers, and punctuations input
if (event.key == event.key.toUpperCase()) {
prevent = true;
}
// exempt spacebar input
if (event.code == "Space") {
prevent = false;
}
// handle input overflow
const nChars = this.$refs.editbar.textContent.length;
if (nChars >= this.maxChars) {
prevent = true;
}
if (prevent == true) {
event.preventDefault();
}
},
sendText() {
const inputText = this.$refs.editbar.textContent;
this.connection.send(inputText);
},
receiveText(event) {
this.autoComplete = event.data;
}
}
}
</script>
</code></pre>
<p>EstepeJSON.ue file in the components directory:</p>
<pre><code><template>
<div width="80%" v-for="regList in myJson" :key="regList" class="container">
<table>
<thead>
<tr>
<th>Documento</th>
</tr>
</thead>
<tbody>
<tr v-for="countryList in regList[2]" :key="countryList">
<td style="visibility: visible">{{ countryList}}</td>
</tr>
</tbody>
</table>
</div>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"
/>
</template>
<script>
import json from "@/data.json";
export default {
name: "EstepeJson",
data() {
return {
myJson: json,
};
},
};
</script>
</code></pre>
<p>Example of the JSON returned by the URL:</p>
<pre><code>[
{
"Title": "SOFT-STARTER",
"Cod": "Produto: 15775931",
"Description": "A soft-starter SSW7000 permite o controle de partida/parada e proteção de motores.",
"Technical_characteristics": ["Corrente nominal", "600 A", "Tensão nominal", "4,16 kV", "Tensão auxiliar", "200-240 V", "Grau de proteção", "IP41", "Certificação", "CE"]
},
{
"Title": "SOFT-STARTER SSW",
"Cod": "Produto: 14223395",
"Description": "A soft-starter SSW7000 permite o controle de partida/parada e proteção de motores de indução trifásicos de média tensão.",
"Technical_characteristics": ["Corrente nominal", "125 A", "Tensão nominal", "6,9 kV", "Tensão auxiliar", "200-240 V", "Grau de proteção", "IP54/NEMA12", "Certificação", "CE"]
}
]
</code></pre>
|
[
{
"answer_id": 74619411,
"author": "Charles Yang",
"author_id": 13101880,
"author_profile": "https://Stackoverflow.com/users/13101880",
"pm_score": 0,
"selected": false,
"text": "json.dumps(mydata)"
},
{
"answer_id": 74639030,
"author": "Chris",
"author_id": 17865804,
"author_profile": "https://Stackoverflow.com/users/17865804",
"pm_score": 1,
"selected": false,
"text": "requests httpx data await websocket.send_json(data) websockets text = json.dumps(data) data send_json() dict requests httpx .json() data send_json() from fastapi import FastAPI, WebSocket\nfrom fastapi.responses import HTMLResponse\nimport httpx\n\napp = FastAPI()\n\nhtml = \"\"\"\n<!DOCTYPE html>\n<html>\n <head>\n <title>Chat</title>\n </head>\n <body>\n <h1>WebSocket Chat</h1>\n <form action=\"\" onsubmit=\"sendMessage(event)\">\n <input type=\"text\" id=\"messageText\" autocomplete=\"off\"/>\n <button>Send</button>\n </form>\n <ul id='messages'>\n </ul>\n <script>\n var ws = new WebSocket(\"ws://localhost:8000/ws\");\n ws.onmessage = function(event) {\n var messages = document.getElementById('messages')\n var message = document.createElement('li')\n var content = document.createTextNode(event.data)\n message.appendChild(content)\n messages.appendChild(message)\n };\n function sendMessage(event) {\n var input = document.getElementById(\"messageText\")\n ws.send(input.value)\n input.value = ''\n event.preventDefault()\n }\n </script>\n </body>\n</html>\n\"\"\"\n\n\n@app.get('/')\nasync def get():\n return HTMLResponse(html)\n \n\n@app.websocket('/ws')\nasync def websocket_endpoint(websocket: WebSocket):\n await websocket.accept()\n while True:\n data = await websocket.receive_text()\n # here use httpx to issue a request as demonstrated in the linked answers above\n # r = await client.send(... \n await websocket.send_json(r.json())\n"
},
{
"answer_id": 74655712,
"author": "CH97",
"author_id": 13728565,
"author_profile": "https://Stackoverflow.com/users/13728565",
"pm_score": 1,
"selected": true,
"text": "async def predict_question(websocket: WebSocket):\n await manager.connect(websocket)\n input_text = await websocket.receive_text()\n if not input_text:\n await manager.send_personal_message(json.dumps([]), websocket)\n else:\n autocomplete_text = text_gen.generate_text(input_text)\n autocomplete_text = re.sub(r\"[\\([{})\\]]\", \"\", autocomplete_text)\n autocomplete_text = autocomplete_text.split()\n autocomplete_text = autocomplete_text[0:2]\n resp = client.build_request(\"GET\", 'www.description_url_search_='+input_text+'')\n r = await client.send(resp)\n datajson = r.json()\n datajson.insert(0, ' '.join(autocomplete_text))\n await manager.send_personal_message(json.dumps(datajson), websocket)\n <template>\n<div class=\"pad-container\">\n <div tabindex=\"1\" @focus=\"setCaret\" class=\"autocomplete-container\">\n <span @input=\"sendText\" @keypress=\"preventInput\" ref=\"editbar\" class=\"editable\" contenteditable=\"true\"></span>\n <span class=\"placeholder\" data-ondeleteId=\"#editx\" contenteditable=\"false\">{{autoComplete}}</span> \n </div>\n</div>\n<div v-for=\"regList in myJson\" :key=\"regList\" class=\"container\" >\n <table>\n <thead>\n <tr>\n <th>Documento</th>\n </tr>\n </thead>\n <tbody>\n <tr v-for=\"countryList in regList[2]\" :key=\"countryList\">\n <td style=\"visibility: visible\">{{ countryList}}</td>\n </tr>\n </tbody>\n </table>\n </div>\n</template>\n\n<script>\n...\ndata: function() {\n return {\n autoComplete: \"\",\n maxChars: 75,\n connection: null, \n myJson: []\n }\n },\n.....\n...\n receiveText(event) {\n let result = JSON.parse(event.data)\n this.autoComplete = result.shift();\n this.myJson = result\n }\n</script>\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13728565/"
] |
74,618,895
|
<p>Is it possible to loop 1, 4, 7, 10 sequence directly in ngFor from an array?</p>
<p>I tried in ts like regular for loop with i+=3. But need 1,4,7,10 pattern directly in ngFor without a loop in ts file.</p>
|
[
{
"answer_id": 74619084,
"author": "Crystal Campbell",
"author_id": 19246117,
"author_profile": "https://Stackoverflow.com/users/19246117",
"pm_score": 1,
"selected": false,
"text": " <div *ngFor=\"item in itemlist, let i = index\">\n <div *ngIf=\"i % 3 === 0\">\n{{item}}\n </div>\n </div>\n"
},
{
"answer_id": 74621317,
"author": "islam elbadawy",
"author_id": 8652329,
"author_profile": "https://Stackoverflow.com/users/8652329",
"pm_score": 0,
"selected": false,
"text": " <div *ngFor=\"item of items, let i = index\">\n <div *ngIf=\"i % 3 === 1\">\n {{item}}\n </div>\n </div>\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20637255/"
] |
74,618,899
|
<p>The following object contains a list of recipients and subscriptions, I wish to create a new array with a different structure such as below.</p>
<blockquote>
<p>[{"recipientId":"13251376",
"services":"3218143,15656200,3721"},{"recipientId":"13251316",
"services":"3218143"}</p>
</blockquote>
<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>let serviceSubscriptions = [{"recipientId":"13251316","serviceId":"3218143"},{"recipientId":"13251376","serviceId":"3218143"},{"recipientId":"13251376","serviceId":"15656200"},{"recipientId":"13251376","serviceId":"3721"}]
let testArr = [];
serviceSubscriptions.forEach(serviceSubscriptions => {
for (const [key, value] of Object.entries(serviceSubscriptions)) {
//console.log(`${key}: ${value}`);
testArr.push(`${key}:${value}`);
}
});
console.log(testArr);</code></pre>
</div>
</div>
</p>
<p>Here is a list of things I've tried - <a href="https://jsfiddle.net/v5azdysg/2/" rel="nofollow noreferrer">https://jsfiddle.net/v5azdysg/2/</a></p>
<p><strong>update 30/11/22 19:08</strong>
I am trying to integrate @Mr. Polywhirl your answer with my idea, but I cannot get far as I am not skilled in this area, here is what I have so far. <a href="https://jsfiddle.net/aectk8v1/4/" rel="nofollow noreferrer">https://jsfiddle.net/aectk8v1/4/</a> What I need is to add a new key called essentially services/subscriptions with the list of ids of the subscriptions, but this should be appended to the existing list of keys and also a key which shows if subscriptions exist, true or false, on the other hand another version I need is to list all the services keys and add the value of true or false under a single key such as <code>"subscriptions":{12345:true,123456:false}</code></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>;let recipients = [
{"id":"666777","lawfulBasis":"0","jurisdiction":"AMER","name":"David G"},
{"id":"888999","lawfulBasis":"1","jurisdiction":"ASIA","name":"Mike A"},
{"id":"444555","lawfulBasis":"2","jurisdiction":"EUR","name":"John No Sub"}
];
let serviceSubscriptions = [
{"recipientId":"666777","serviceId":"3218143"},
{"recipientId":"666777","serviceId":"8956799"},
{"recipientId":"888999","serviceId":"15656200"},
{"recipientId":"000000","serviceId":"3721"}
];
/* return subscribed */
//.map method creates new array populated with result of call
//.some performs test true|false
// ... dot notation copies all parts from 1 array to another merge/join
var result = recipients.map(Obj1 => {
return { ...Obj1,
isSubscribed:serviceSubscriptions.some(Obj2 => Obj1.id == Obj2.recipientId),
services1:serviceSubscriptions.map(Obj2 => Obj1.id == Obj2.recipientId),
services:serviceSubscriptions.map(Obj2 => Obj2.serviceId),
}
});
console.log(result)</code></pre>
</div>
</div>
</p>
<p><a href="https://i.stack.imgur.com/ePyE1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ePyE1.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74619084,
"author": "Crystal Campbell",
"author_id": 19246117,
"author_profile": "https://Stackoverflow.com/users/19246117",
"pm_score": 1,
"selected": false,
"text": " <div *ngFor=\"item in itemlist, let i = index\">\n <div *ngIf=\"i % 3 === 0\">\n{{item}}\n </div>\n </div>\n"
},
{
"answer_id": 74621317,
"author": "islam elbadawy",
"author_id": 8652329,
"author_profile": "https://Stackoverflow.com/users/8652329",
"pm_score": 0,
"selected": false,
"text": " <div *ngFor=\"item of items, let i = index\">\n <div *ngIf=\"i % 3 === 1\">\n {{item}}\n </div>\n </div>\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1206087/"
] |
74,618,920
|
<p>I have been trying all day to change the color but it's not working properly.
The color change but the icon is replaced with a square with an X in it.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#product1 .pro .cart-color{
width: 40px;
height: 40px;
line-height: 40px;
border-radius: 50px;
background-color: #F9D6D7;
color: #953246;
border: 1px solid #F9D6D7;
position: absolute;
bottom: 20px;
right: 10px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<a href="#"><i class="fas fa-regular fa-cart-shopping cart-color"></i></a></code></pre>
</div>
</div>
</p>
<p>this is what i get:</p>
<p><a href="https://i.stack.imgur.com/DS2uR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DS2uR.png" alt="https://i.stack.imgur.com/DS2uR.png" /></a></p>
<p>I also have these included:</p>
<pre><code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css"/>`
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
</code></pre>
|
[
{
"answer_id": 74619084,
"author": "Crystal Campbell",
"author_id": 19246117,
"author_profile": "https://Stackoverflow.com/users/19246117",
"pm_score": 1,
"selected": false,
"text": " <div *ngFor=\"item in itemlist, let i = index\">\n <div *ngIf=\"i % 3 === 0\">\n{{item}}\n </div>\n </div>\n"
},
{
"answer_id": 74621317,
"author": "islam elbadawy",
"author_id": 8652329,
"author_profile": "https://Stackoverflow.com/users/8652329",
"pm_score": 0,
"selected": false,
"text": " <div *ngFor=\"item of items, let i = index\">\n <div *ngIf=\"i % 3 === 1\">\n {{item}}\n </div>\n </div>\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20637200/"
] |
74,618,937
|
<p>Im interested in replacing all of my rows in an MxN matrix with values from 1 to N.</p>
<p>For example:
[[4,6,8,9,3],[5,1,2,5,6],[1,9,4,5,7],[3,8,8,2,5],[1,4,2,2,7]]</p>
<p>To:
[[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]</p>
<p>I've tried using loops going through each row individually but struggle to replace elements.</p>
|
[
{
"answer_id": 74619084,
"author": "Crystal Campbell",
"author_id": 19246117,
"author_profile": "https://Stackoverflow.com/users/19246117",
"pm_score": 1,
"selected": false,
"text": " <div *ngFor=\"item in itemlist, let i = index\">\n <div *ngIf=\"i % 3 === 0\">\n{{item}}\n </div>\n </div>\n"
},
{
"answer_id": 74621317,
"author": "islam elbadawy",
"author_id": 8652329,
"author_profile": "https://Stackoverflow.com/users/8652329",
"pm_score": 0,
"selected": false,
"text": " <div *ngFor=\"item of items, let i = index\">\n <div *ngIf=\"i % 3 === 1\">\n {{item}}\n </div>\n </div>\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20637261/"
] |
74,618,968
|
<p>I am performing a http call and subscribing to it.
If I close that component, the subscription is not destroyed, and it runs once.
Shouldn't the http subscriptions be removed automatically once I destroy a component?</p>
<p>Here's the method that is being called</p>
<pre><code>getCubes() {
this.loading_cubes = true;
this.urlService.getCubes().subscribe({
next:(data:any) => {
if (data.success) {
this.cubesDataArray = data.data[0].response;
} else {
Swal.fire(data.status_message);
console.log(data.error_message);
}
this.loading_cubes = false;
},
error:(err:any) => {
console.log(err);
Swal.fire('Opps an error occured');
this.loading_cubes = false;
}
});
}
</code></pre>
<p>And here's the service function that's returning the http observable.</p>
<pre><code> getCubes() {
return this.http.get(this.serviceURL + '/cubes', this.options);
}
</code></pre>
<p>This is just an single case, It's happening with every req I make.
The pop ups keep coming up even after I closed the component.</p>
<p>Also it it possible that it is some setting in the tsconfig.json?</p>
|
[
{
"answer_id": 74619044,
"author": "Mathew Berg",
"author_id": 973651,
"author_profile": "https://Stackoverflow.com/users/973651",
"pm_score": 2,
"selected": false,
"text": "\nexport MyComponent extends OnDestroy {\n mySubscription = null\n ...\n\n getCubes() {\n this.mySubscription = this.urlService.getCubes().subscribe({\n ...\n });\n }\n ngOnDestroy() {\n this.mySubscription.unsubscribe();\n } \n}\n\n"
},
{
"answer_id": 74628374,
"author": "Łukasz Piotr Łuczak",
"author_id": 20633817,
"author_profile": "https://Stackoverflow.com/users/20633817",
"pm_score": 0,
"selected": false,
"text": "pipe(take(1)) firstValueFrom cold observables this.urlService.getCubes()\n .pipe(retry(3))\n .subscribe({\n ...\n });\n retry cold observables cancelation token"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74618968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20012119/"
] |
74,619,007
|
<pre class="lang-py prettyprint-override"><code>total_task=float(input("Enter the assigned total task length(in half-hour(s)):"))
total_len=total_task*2
leng=int(total_len)
payments=[]
hours=[]
for i in range(leng):
print("Enter the payment value( in TL) for task portion ID ",(i+1)," having length ",((i+1)*0.5)," hour(s):")
portionLen=int(input())
payments.append(portionLen)
hours.append(portionLen)
paymentsTable=[]
for i in range(leng):
paymentsRow=[]
for j in range(leng):
paymentsRow.append(0)
paymentsTable.append(paymentsRow)
for i in range(leng):
paymentsTable[i][i]=payments[i]
for i in range(leng):
for j in range(1,leng+1):
maxPayment=0
for k in range(j):
pay=paymentsTable[i][k]+paymentsTable[k+1][j]
if(pay>maxPayment):
maxPayment=pay
paymentsTable[i][j]=maxPayment
idTable=[]
for i in range(leng):
idTableRow=[]
for j in range(leng):
idTableRow.append(0)
idTable.append(idTableRow)
for i in range(leng):
idTable[i][i]=i+1
for i in range(leng):
for j in range(1,leng+1):
maxPayment=0
for k in range(j):
pay = paymentsTable[i][k] + paymentsTable[k + 1][j]
if (pay > maxPayment):
maxPayment = pay
paymentsTable[i][j] = maxPayment
for i in range(leng):
for j in range(1,leng+1):
maxPayment=0
for k in range(j):
pay = paymentsTable[i][k] + paymentsTable[k + 1][j]
if (pay > maxPayment):
maxPayment = pay
idTable[i][j]=k+1
</code></pre>
<p><strong>My Sample input</strong></p>
<pre><code>Enter the assigned total task length(in half-hour(s)):**2**
Enter the payment value( in TL) for task portion ID 1 having length 0.5 hour(s):
**100**
Enter the payment value( in TL) for task portion ID 2 having length 1.0 hour(s):
**400**
Enter the payment value( in TL) for task portion ID 3 having length 1.5 hour(s):
**500**
Enter the payment value( in TL) for task portion ID 4 having length 2.0 hour(s):
**600**
</code></pre>
<p><strong>and my sample error</strong></p>
<pre class="lang-py prettyprint-override"><code>line 23, in <module>
pay=paymentsTable[i][k]+paymentsTable[k+1][j]
IndexError: list index out of range
</code></pre>
|
[
{
"answer_id": 74619229,
"author": "Rodrigo Rodrigues",
"author_id": 2938526,
"author_profile": "https://Stackoverflow.com/users/2938526",
"pm_score": 2,
"selected": false,
"text": "paymentsTable[i][k] paymentsTable[k+1][j] paymentsTable leng 0 leng-1 paymentsTable[i] leng 0 leng-1 i range(leng) j (range(1, leng + 1)) 1 leng for j in range(1,leng+1) j leng paymentsTable[i] leng-1 k+1 leng paymentsTable leng"
},
{
"answer_id": 74619425,
"author": "quagrain",
"author_id": 19064311,
"author_profile": "https://Stackoverflow.com/users/19064311",
"pm_score": 0,
"selected": false,
"text": "paymentsRow idTableRow paymentsRow idTableRow total_task=float(input(\"Enter the assigned total task length(in half-hour(s)):\"))\ntotal_len=total_task*2\nleng=int(total_len)\npayments=[]\nhours=[]\nfor i in range(leng):\n print(\"Enter the payment value( in TL) for task portion ID \",(i+1),\" having length \",((i+1)*0.5),\" hour(s):\")\n portionLen=int(input())\n payments.append(portionLen)\n hours.append(portionLen)\npaymentsTable=[]\npaymentsRow=[]\nfor i in range(leng):\n for j in range(leng):\n paymentsRow.append(0)\n paymentsTable.append(paymentsRow)\nfor i in range(leng):\n paymentsTable[i][i]=payments[i]\nfor i in range(leng):\n for j in range(1,leng):\n maxPayment=0\n for k in range(j):\n pay=paymentsTable[i][k]+paymentsTable[k+1][j]\n if(pay>maxPayment):\n maxPayment=pay\n paymentsTable[i][j]=maxPayment\nidTable=[]\nidTableRow=[]\n\nfor i in range(leng):\n for j in range(leng):\n idTableRow.append(0)\n idTable.append(idTableRow)\nfor i in range(leng):\n idTable[i][i]=i+1\nfor i in range(leng):\n for j in range(1,leng):\n maxPayment=0\n for k in range(j):\n pay = paymentsTable[i][k] + paymentsTable[k + 1][j]\n if (pay > maxPayment):\n maxPayment = pay\n paymentsTable[i][j] = maxPayment\nfor i in range(leng):\n for j in range(1,leng):\n maxPayment=0\n for k in range(j):\n pay = paymentsTable[i][k] + paymentsTable[k + 1][j]\n if (pay > maxPayment):\n maxPayment = pay\n idTable[i][j]=k+1\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16814178/"
] |
74,619,038
|
<p>So I am scraping a website and the code gives me all the information I want however when scraping it also gives me the "€" symbol with the price. So I want to be able to have the price as a int and remove the "€" symbol so I can Calculate the average car price per year. It does give me the ValueError: invalid literal for int() with base 10: 'price' but when I try look at other questions on this website with the answer the solutions don't work for me. Year is also a string so would it make sense to convert the year to an int as well so I can do equations?</p>
<pre><code>import requests
import pandas as pd
from bs4 import BeautifulSoup
url = "https://jammer.ie/used-cars?page={}&per-page=12"
all_data = []
for page in range(1, 4): # <-- increase number of pages here
soup = BeautifulSoup(requests.get(url.format(page)).text, "html.parser")
for car in soup.select(".car"):
info = car.select_one(".top-info").get_text(strip=True, separator="|")
info = info.split("|")
if len(info) == 4:
make, model, year, price = info
else:
make, year, price = info
model = "N/A"
dealer_name = car.select_one(".dealer-name h6").get_text(
strip=True, separator=" "
)
address = car.select_one(".address").get_text(strip=True)
features = {}
for feature in car.select(".car--features li"):
k = feature.img["src"].split("/")[-1].split(".")[0]
v = feature.span.text
features[f"feature_{k}"] = v
all_data.append(
{
"make": make,
"model": model,
"year": year,
"price": price,
"dealer_name": dealer_name,
"address": address,
"url": "https://jammer.ie"
+ car.select_one("a[href*=vehicle]")["href"],
**features,
}
)
df = pd.DataFrame(all_data)
# prints sample data to screen:
print(df.tail().to_markdown(index=False))
# saves all data to CSV
df.to_csv("data.csv", index=False)
</code></pre>
<p>I tired converting using</p>
<pre><code>df = pd.read_csv('data.csv', usecols= ['price','year'])
print(type("price"))
print(int("price"))
</code></pre>
<p>But this did not work out for me. I also tired converting it to a float as well which did not work too.</p>
|
[
{
"answer_id": 74619229,
"author": "Rodrigo Rodrigues",
"author_id": 2938526,
"author_profile": "https://Stackoverflow.com/users/2938526",
"pm_score": 2,
"selected": false,
"text": "paymentsTable[i][k] paymentsTable[k+1][j] paymentsTable leng 0 leng-1 paymentsTable[i] leng 0 leng-1 i range(leng) j (range(1, leng + 1)) 1 leng for j in range(1,leng+1) j leng paymentsTable[i] leng-1 k+1 leng paymentsTable leng"
},
{
"answer_id": 74619425,
"author": "quagrain",
"author_id": 19064311,
"author_profile": "https://Stackoverflow.com/users/19064311",
"pm_score": 0,
"selected": false,
"text": "paymentsRow idTableRow paymentsRow idTableRow total_task=float(input(\"Enter the assigned total task length(in half-hour(s)):\"))\ntotal_len=total_task*2\nleng=int(total_len)\npayments=[]\nhours=[]\nfor i in range(leng):\n print(\"Enter the payment value( in TL) for task portion ID \",(i+1),\" having length \",((i+1)*0.5),\" hour(s):\")\n portionLen=int(input())\n payments.append(portionLen)\n hours.append(portionLen)\npaymentsTable=[]\npaymentsRow=[]\nfor i in range(leng):\n for j in range(leng):\n paymentsRow.append(0)\n paymentsTable.append(paymentsRow)\nfor i in range(leng):\n paymentsTable[i][i]=payments[i]\nfor i in range(leng):\n for j in range(1,leng):\n maxPayment=0\n for k in range(j):\n pay=paymentsTable[i][k]+paymentsTable[k+1][j]\n if(pay>maxPayment):\n maxPayment=pay\n paymentsTable[i][j]=maxPayment\nidTable=[]\nidTableRow=[]\n\nfor i in range(leng):\n for j in range(leng):\n idTableRow.append(0)\n idTable.append(idTableRow)\nfor i in range(leng):\n idTable[i][i]=i+1\nfor i in range(leng):\n for j in range(1,leng):\n maxPayment=0\n for k in range(j):\n pay = paymentsTable[i][k] + paymentsTable[k + 1][j]\n if (pay > maxPayment):\n maxPayment = pay\n paymentsTable[i][j] = maxPayment\nfor i in range(leng):\n for j in range(1,leng):\n maxPayment=0\n for k in range(j):\n pay = paymentsTable[i][k] + paymentsTable[k + 1][j]\n if (pay > maxPayment):\n maxPayment = pay\n idTable[i][j]=k+1\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20637309/"
] |
74,619,051
|
<p>I am deploying a Django project on AWS. I am running Postgres, Redis, Nginx as well as my project on Docker there.</p>
<p>Everything is working fine, but when I change something on my local machine, push changes to git and then pull them on the AWS instance, the code is changing, files are updated but they are not showing on the website. Only the static files are updating automatically (I guess because of Nginx). Here is my docker-compose config:</p>
<pre class="lang-yaml prettyprint-override"><code>version: '3.9'
services:
redis:
image: redis
command: redis-server
ports:
- "6379:6379"
postgres:
image: postgres
environment:
- POSTGRES_USER=
- POSTGRES_PASSWORD=
- POSTGRES_DB=
ports:
- "5432:5432"
web:
image: image_name
build: .
restart: always
command: gunicorn project.wsgi:application --bind 0.0.0.0:8000
env_file:
- envs/.env.prod
ports:
- "8000:8000"
volumes:
- ./staticfiles/:/tmp/project/staticfiles
depends_on:
- postgres
- redis
nginx:
image: nginx
ports:
- "80:80"
- "443:443"
volumes:
- ./staticfiles:/home/app/web/staticfiles
- ./nginx/conf.d:/etc/nginx/conf.d
- ./nginx/logs:/var/log/nginx
- ./certbot/www:/var/www/certbot/:ro
- ./certbot/conf/:/etc/nginx/ssl/:ro
depends_on:
- web
</code></pre>
<p>Can you please tell me what to do?</p>
<p>I tried deleting everything from docker and compose up again but nothing happened.
I looked all over in here but I still don't understand... instance restart is not working as well. I tried cleaning redis cache because I have template caching and still nothing.</p>
|
[
{
"answer_id": 74619229,
"author": "Rodrigo Rodrigues",
"author_id": 2938526,
"author_profile": "https://Stackoverflow.com/users/2938526",
"pm_score": 2,
"selected": false,
"text": "paymentsTable[i][k] paymentsTable[k+1][j] paymentsTable leng 0 leng-1 paymentsTable[i] leng 0 leng-1 i range(leng) j (range(1, leng + 1)) 1 leng for j in range(1,leng+1) j leng paymentsTable[i] leng-1 k+1 leng paymentsTable leng"
},
{
"answer_id": 74619425,
"author": "quagrain",
"author_id": 19064311,
"author_profile": "https://Stackoverflow.com/users/19064311",
"pm_score": 0,
"selected": false,
"text": "paymentsRow idTableRow paymentsRow idTableRow total_task=float(input(\"Enter the assigned total task length(in half-hour(s)):\"))\ntotal_len=total_task*2\nleng=int(total_len)\npayments=[]\nhours=[]\nfor i in range(leng):\n print(\"Enter the payment value( in TL) for task portion ID \",(i+1),\" having length \",((i+1)*0.5),\" hour(s):\")\n portionLen=int(input())\n payments.append(portionLen)\n hours.append(portionLen)\npaymentsTable=[]\npaymentsRow=[]\nfor i in range(leng):\n for j in range(leng):\n paymentsRow.append(0)\n paymentsTable.append(paymentsRow)\nfor i in range(leng):\n paymentsTable[i][i]=payments[i]\nfor i in range(leng):\n for j in range(1,leng):\n maxPayment=0\n for k in range(j):\n pay=paymentsTable[i][k]+paymentsTable[k+1][j]\n if(pay>maxPayment):\n maxPayment=pay\n paymentsTable[i][j]=maxPayment\nidTable=[]\nidTableRow=[]\n\nfor i in range(leng):\n for j in range(leng):\n idTableRow.append(0)\n idTable.append(idTableRow)\nfor i in range(leng):\n idTable[i][i]=i+1\nfor i in range(leng):\n for j in range(1,leng):\n maxPayment=0\n for k in range(j):\n pay = paymentsTable[i][k] + paymentsTable[k + 1][j]\n if (pay > maxPayment):\n maxPayment = pay\n paymentsTable[i][j] = maxPayment\nfor i in range(leng):\n for j in range(1,leng):\n maxPayment=0\n for k in range(j):\n pay = paymentsTable[i][k] + paymentsTable[k + 1][j]\n if (pay > maxPayment):\n maxPayment = pay\n idTable[i][j]=k+1\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20637393/"
] |
74,619,057
|
<p>I have the following task statement:</p>
<p>In this task we want to simulate random variables with density</p>
<p><a href="https://i.stack.imgur.com/knKi1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/knKi1.png" alt="enter image description here" /></a></p>
<p>To do this, write a function r_density(n) that simulates n of such random variables.
Then use this function to simulate N = 1000 of such random variables. Using geom_density() you can now estimate the density from the simulated random variables. We can compare this estimate with the real density. To do this, create a graph that looks like this:</p>
<p><a href="https://i.stack.imgur.com/rCA7v.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rCA7v.jpg" alt="Expected Plot" /></a></p>
<p>Problem is, however, that I don't understand why my output looks like this:</p>
<p><a href="https://i.stack.imgur.com/p47se.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/p47se.jpg" alt="My Plot" /></a></p>
<p>Why is the raked density plotted in such a weird way? Can someone explain to me why it looks like that and how to get the estimated density from the expected image?</p>
<p>This is the corresponding code I wrote for the above plot:</p>
<pre><code>library(tidyverse)
N <- 1000
r_density <- function(n){
exp(-abs(n))/2
}
x <- runif(N)
tb <- tibble(
x = x,
density_fkt = r_density(x)
)
ggplot() +
geom_density(
data = tb,
mapping = aes(
x = density_fkt,
y = ..scaled..
)
) +
geom_function(
fun = r_density,
xlim = c(-6,6),
color = "red",
size = 1
) +
theme_minimal() +
labs(
x = "x",
y = "Dichtefunktion f(x)",
title = "Geschätzte (schwarz) vs echte (rot) Dichte"
)
</code></pre>
|
[
{
"answer_id": 74619612,
"author": "Vons",
"author_id": 2303235,
"author_profile": "https://Stackoverflow.com/users/2303235",
"pm_score": 3,
"selected": true,
"text": "library(tidyverse)\n\nN <- 1000\n\nr_density <- function(n){\n exp(-abs(n))/2\n}\n\nx = c()\nwhile (length(x) < N) {\n y = rnorm(1)\n while (y > 6 | y < -6) {\n y = rnorm(1)\n }\n u = runif(1)\n if (u < r_density(y)/(dnorm(y) * 3)) {\n x=append(x, y)\n }\n}\n\n\ntb <- tibble(\n x = x,\n density_fkt = r_density(x)\n)\n\nggplot() +\n geom_density(\n data = tb,\n mapping = aes(\n x = x,\n y = ..density..\n )\n ) +\n geom_function(\n fun = r_density,\n xlim = c(-6,6),\n color = \"red\",\n size = 1\n ) +\n theme_minimal() +\n labs(\n x = \"x\",\n y = \"Dichtefunktion f(x)\",\n title = \"Geschätzte (schwarz) vs echte (rot) Dichte\"\n ) \n\n"
},
{
"answer_id": 74619697,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 1,
"selected": false,
"text": "r_density <- function(n) {\n\n cdf <- function(x) {\n 1/4 * exp(-x) * (-1 + 2 * exp(x) + exp(2*x) - (-1 + exp(x))^2 * sign(x))\n }\n\n sapply(runif(n), function(i) {\n uniroot(function(x) cdf(x) - i, c(-30, 20))$root\n })\n}\n ggplot() +\n geom_density(aes(r_density(1000))) +\n geom_function(\n fun = function(x) exp(-abs(x))/2,\n xlim = c(-6,6),\n color = \"red\",\n size = 1\n ) +\n theme_minimal() +\n labs(\n x = \"x\",\n y = \"Dichtefunktion f(x)\",\n title = \"Geschätzte (schwarz) vs echte (rot) Dichte\"\n ) \n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20433442/"
] |
74,619,098
|
<p>I am having an issue when trying to run JavaScript inside an Ajax loaded content on a webpage. I keep getting an error "Cannot set properties of null". If I move the output of the script to the footer for example which is outside of the Ajax loaded content, the script works fine.</p>
<p>This is the piece of code where the ajax is loaded into on the main webpage:</p>
<pre class="lang-html prettyprint-override"><code><main>
<article class="ext-content">
</article>
</main>
</code></pre>
<p>This is the JavaScript code to load the ajax content:</p>
<pre class="lang-js prettyprint-override"><code>$('section li').click(function() {
$.ajax({
type: 'GET',
url: 'includes/ext-content/'+$(this).data('content')+'.html',
dataType: 'html',
success: function(response) {
$('.ext-content').html(response);
}
});
});
</code></pre>
<p>This is part of the ajax loaded content where when a user selects the amount of items, they are shown the price of the item * the amount selected. The <code>shopOutput</code> is where the price will be shown on the webpage: (If I move the <code>shopOutput</code> outside of the Ajax content the script works fine.)</p>
<pre class="lang-html prettyprint-override"><code> <tr>
<td colspan="3" class="shop-qty-select">
<select onchange="addElements(this)">
<option value="0">Select aantal:</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<p id="shopOutput"></p>
</td>
</tr>
</code></pre>
<p>This is the JavaScript which takes the amount selected and shows the user how much the total price will be:</p>
<pre class="lang-js prettyprint-override"><code>let shopOutput = document.getElementById("shopOutput");
const priceFractal = 10;
function addElements(selectElement) {
let valueNumbers = selectElement.value;
shopOutput.innerHTML = "";
let yourTotal = valueNumbers * priceFractal;
shopOutput.textContent = yourTotal;
}
</code></pre>
<p>Any help is much appreciated.</p>
<p>Like I mentioned I know that this code works if I just move the output outside of the Ajax loaded content. But when it is inside the Ajax content, I get an error "Cannot set properties of null (setting 'innerHTML')"</p>
|
[
{
"answer_id": 74619123,
"author": "David",
"author_id": 328193,
"author_profile": "https://Stackoverflow.com/users/328193",
"pm_score": 3,
"selected": true,
"text": "let shopOutput = document.getElementById(\"shopOutput\");\n #shopOutput shopOutput null null function addElements(selectElement) {\n let shopOutput = document.getElementById(\"shopOutput\");\n // the rest of the function...\n}\n"
},
{
"answer_id": 74619231,
"author": "Thomas Skubicki",
"author_id": 4647867,
"author_profile": "https://Stackoverflow.com/users/4647867",
"pm_score": -1,
"selected": false,
"text": "$( document ).ready(function() {\n //your code here\n});\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20637346/"
] |
74,619,140
|
<p>I am trying to fix these photos to be a tiny more centered. Maybe shift down a little and to the left. I am using all bootstrap and do not have any css attached to this. It is all working within the ul tags. Any help appreciated.</p>
<p><a href="https://i.stack.imgur.com/BpoJq.png" rel="nofollow noreferrer">Page Screen Shot</a></p>
<pre class="lang-html prettyprint-override"><code><ul>
<li>
<a href="https://example.com" class="dropdown-header">
<strong>Example</strong><br />
<span class="megasubheader">| NEWS AND CONTENT </span>
</a>
</li>
<li class="dropdown-divider"></li>
<li class="list-group">
<a href="https://example.com" class="list-group-item mt-2" aria-current="true">
<div class="d-flex w-100 justify-content-between">
<img id="imgsrc1" width="75px" height="75px" class="rounded mx-2">
<span id="Htitle1" style="font-size: 14px"></span>
</div>
</a>
<a href="https://example.com" class="list-group-item mt-2" aria-current="true">
<div class="d-flex w-100 justify-content-between">
<img id="imgsrc2" width="75px" height="75px" class="rounded mx-2">
<span id="Htitle2" style="font-size: 14px"></span>
</div>
</a>
<a href="https://example.com" class="list-group-item mt-2" aria-current="true">
<div class="d-flex w-100 justify-content-between">
<img id="imgsrc3" width="75px" height="75px" class="rounded mx-2">
<span id="Htitle3" style="font-size: 14px"></span>
</div>
</a>
</li>
</ul>
</code></pre>
|
[
{
"answer_id": 74619123,
"author": "David",
"author_id": 328193,
"author_profile": "https://Stackoverflow.com/users/328193",
"pm_score": 3,
"selected": true,
"text": "let shopOutput = document.getElementById(\"shopOutput\");\n #shopOutput shopOutput null null function addElements(selectElement) {\n let shopOutput = document.getElementById(\"shopOutput\");\n // the rest of the function...\n}\n"
},
{
"answer_id": 74619231,
"author": "Thomas Skubicki",
"author_id": 4647867,
"author_profile": "https://Stackoverflow.com/users/4647867",
"pm_score": -1,
"selected": false,
"text": "$( document ).ready(function() {\n //your code here\n});\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20626872/"
] |
74,619,161
|
<p>I just want to use the instantiated GameObject in another function but it always says
The name 'newObject' does not exist in the current context</p>
<pre><code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Deletenow : MonoBehaviour
{
public Transform Player;
public GameObject myObject;
public Vector2 thisVector;
void Start()
{
thisFunction();
}
void Update()
{
thisVector = newObject.transform.position;
}
public void thisFunction()
{
GameObject newObject = Instantiate(myObject, Player.transform.position, Player.rotation);
}
}
</code></pre>
<p>I couldn't find any source that could help me</p>
|
[
{
"answer_id": 74619123,
"author": "David",
"author_id": 328193,
"author_profile": "https://Stackoverflow.com/users/328193",
"pm_score": 3,
"selected": true,
"text": "let shopOutput = document.getElementById(\"shopOutput\");\n #shopOutput shopOutput null null function addElements(selectElement) {\n let shopOutput = document.getElementById(\"shopOutput\");\n // the rest of the function...\n}\n"
},
{
"answer_id": 74619231,
"author": "Thomas Skubicki",
"author_id": 4647867,
"author_profile": "https://Stackoverflow.com/users/4647867",
"pm_score": -1,
"selected": false,
"text": "$( document ).ready(function() {\n //your code here\n});\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20504646/"
] |
74,619,167
|
<p>I have two elements, a circle and a square (2 different div). The square is on top of the circle, but it <strong>blocks the hover effect of the element underneath</strong> (the circle turns blue, for example).
Applying the hover effect to the square doesn't work, because the hover effect applies to every part of the circle.</p>
<p>In the real example (see second image), you can see that the circle is <strong>divided with the skew and rotate transformation</strong>.</p>
<p>I don't want to use JavaScript, just CSS and HTML.</p>
<hr />
<p>I simplified the problem in this CodePen: codepen.io/tuurtie/pen/XWYPWEb.
<br>
<a href="https://i.stack.imgur.com/3RngP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3RngP.png" alt="enter image description here" /></a>
<br>
This is an image of the actual result (red is what blocks the hover effect of the circle):
<a href="https://i.stack.imgur.com/QZXIX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QZXIX.png" alt="enter image description here" /></a></p>
<p>I have played around with the overflow of both, and I have tried to make a hole in the square, but this still blocks the hover. I know I'm close!</p>
<p>I also added a hover effect to the red square itself, but then the hover effect doesn't work (the hover effect applies to every part of the circle).</p>
|
[
{
"answer_id": 74619123,
"author": "David",
"author_id": 328193,
"author_profile": "https://Stackoverflow.com/users/328193",
"pm_score": 3,
"selected": true,
"text": "let shopOutput = document.getElementById(\"shopOutput\");\n #shopOutput shopOutput null null function addElements(selectElement) {\n let shopOutput = document.getElementById(\"shopOutput\");\n // the rest of the function...\n}\n"
},
{
"answer_id": 74619231,
"author": "Thomas Skubicki",
"author_id": 4647867,
"author_profile": "https://Stackoverflow.com/users/4647867",
"pm_score": -1,
"selected": false,
"text": "$( document ).ready(function() {\n //your code here\n});\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18250923/"
] |
74,619,175
|
<p>I want to convert my datetime object into seconds</p>
<pre><code>0 49:36.5
1 50:13.7
2 50:35.8
3 50:37.4
4 50:39.3
...
92 1:00:47.8
93 1:01:07.7
94 1:02:15.3
95 1:05:03.0
96 1:05:29.6
Name: Finish, Length: 97, dtype: object
</code></pre>
<p>the problem is that the format changes at index 92 which results in an error: ValueError: expected hh:mm:ss format before .</p>
<p>This error is caused when I try to convert the column to seconds</p>
<pre><code>filt_data["F"] = pd.to_timedelta('00:'+filt_data["Finish"]).dt.total_seconds()
</code></pre>
<p>when I do the conversion in two steps it works but results in two different column which I don't know how to merge nor does it seem really efficient:</p>
<pre><code>filt_data["F1"] = pd.to_timedelta('00:'+filt_data["Finish"].loc[0:89]).dt.total_seconds()
filt_data["F2"] = pd.to_timedelta('0'+filt_data["Finish"].loc[90:97]).dt.total_seconds()
</code></pre>
<p>the above code does not cause any error and gets the job done but results in two different columns. Any idea how to do this?</p>
<p>Ideally I would like to loop through the column and based on the format i.E. "50:39.3" or "1:00:47.8" add "00:" or "0" to the object.</p>
|
[
{
"answer_id": 74619635,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "str.replace pd.to_timedelta(df['Finish'].str.replace('^(\\d+:\\d+\\.\\d+)', r'0:\\1', regex=True))\n str.count map pd.to_timedelta(df['Finish'].str.count(':').map({1: '0:', 2: ''}).add(df['Finish']))\n 0 0 days 00:49:36.500000\n1 0 days 00:50:13.700000\n2 0 days 00:50:35.800000\n3 0 days 00:50:37.400000\n4 0 days 00:50:39.300000\n92 0 days 01:00:47.800000\n93 0 days 01:01:07.700000\n94 0 days 01:02:15.300000\n95 0 days 01:05:03\n96 0 days 01:05:29.600000\nName: Finish, dtype: timedelta64[ns]\n"
},
{
"answer_id": 74619708,
"author": "DataFace",
"author_id": 10761390,
"author_profile": "https://Stackoverflow.com/users/10761390",
"pm_score": 1,
"selected": true,
"text": "import pandas as pd\n\ntimes = [\n \"49:36.5\",\n \"50:13.7\",\n \"50:35.8\",\n \"50:37.4\",\n \"50:39.3\",\n \"1:00:47.8\",\n \"1:01:07.7\",\n \"1:02:15.3\",\n \"1:05:03.0\",\n \"1:05:29.6\",\n]\n\ndf = pd.DataFrame({'time': times})\ndf\n def format_time(time):\n time = time.split('.')[0]\n time = time.split(':')\n if(len(time) < 3):\n time.insert(0, \"0\")\n return \":\".join(time)\n\n\ndf[\"formatted_time\"] = df.time.apply(format_time) \ndf\n df[\"time_datetime\"] = pd.to_datetime(df.formatted_time, infer_datetime_format=True)\ndf[\"time_seconds\"] = (df.time_datetime - pd.Timestamp(\"1970-01-01\")) // pd.Timedelta('1s')\ndf\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19225090/"
] |
74,619,184
|
<p>Data</p>
<pre><code>pcadata <- structure(list(sample = c("1-1", "1-2", "1-3", "2-1", "2-2",
"2-3", "3-1", "3-2", "3-3", "4-1", "4-2", "4-3", "1-1", "1-2",
"1-3", "2-1", "2-2", "3-2", "4-1", "4-2", "4-3"), compound = c("Linalool",
"Linalool", "Linalool", "Linalool", "Linalool", "Linalool", "Linalool",
"Linalool", "Linalool", "Linalool", "Linalool", "Linalool", "Acetic Acid",
"Acetic Acid", "Acetic Acid", "Acetic Acid", "Acetic Acid", "Acetic Acid",
"Acetic Acid", "Acetic Acid", "Acetic Acid"), conc = c(82855,
74398, 59563, 117635, 118724, 75271, 95219, 50870, 67546, 58063,
86610, 88594, 263774, 99287, 79800, 529503, 666771, 117253, 101193,
65006, 221687), code = c("1", "1", "1", "2", "2", "2", "3", "3",
"3", "4", "4", "4", "1", "1", "1", "2", "2", "3", "4", "4", "4"
)), class = c("grouped_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA,
-21L), groups = structure(list(sample = c("1-1", "1-1", "1-2",
"1-2", "1-3", "1-3", "2-1", "2-1", "2-2", "2-2", "2-3", "3-1",
"3-2", "3-2", "3-3", "4-1", "4-1", "4-2", "4-2", "4-3", "4-3"
), compound = c("Acetic Acid", "Linalool", "Acetic Acid", "Linalool",
"Acetic Acid", "Linalool", "Acetic Acid", "Linalool", "Acetic Acid",
"Linalool", "Linalool", "Linalool", "Acetic Acid", "Linalool",
"Linalool", "Acetic Acid", "Linalool", "Acetic Acid", "Linalool",
"Acetic Acid", "Linalool"), .rows = structure(list(13L, 1L, 14L,
2L, 15L, 3L, 16L, 4L, 17L, 5L, 6L, 7L, 18L, 8L, 9L, 19L,
10L, 20L, 11L, 21L, 12L), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), row.names = c(NA, -21L), class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE))
</code></pre>
<p>Code</p>
<pre><code>pacman::p_load(tidyverse)
codes_vector <- c("code1", "code2", "code3", "code4", "code5")
colors_vector <- c("#1B9E77","#D95F02","#7570B3","#E7298A","#66A61E","#E6AB02","#A6761D", "#666666")
analysis1 <- pcadata %>%
filter(code %in% c(1, 2)) %>%
arrange(code, 4) %>%
group_by(sample, compound) %>%
pivot_wider(names_from = compound,
values_from = conc,
values_fill = 0) %>%
ungroup() %>%
column_to_rownames(var = "sample") %>%
mutate(code = recode(code,
`1` = codes_vector[1],
`2` = codes_vector[2],
`3` = codes_vector[3],
`4` = codes_vector[4],
`5` = codes_vector[5])) %>%
mutate(color = case_when(code == codes_vector[1] ~ "#1B9E77",
code == codes_vector[2] ~ "#D95F02",
code == codes_vector[3] ~ "#7570B3",
code == codes_vector[4] ~ "#E7298A",
code == codes_vector[5] ~ "#66A61E",
code == codes_vector[6] ~ "#E6AB02",
code == codes_vector[7] ~ "#A6761D",
code == codes_vector[8] ~ "#666666")) %>%
mutate(color=as.factor(color)) %>%
relocate(color, .after = code)
</code></pre>
<p>Question
Is there a way for me to replicate this <code>case_when()</code> work without so much copy and pasting? How can I iterate these operations more concisely or programatically? With all the sequencing I expect there is a way.</p>
<p>Something like this pseudo code:</p>
<pre><code>mutate(code = recode(code[i] = codes_vector[i]))
</code></pre>
<p>and</p>
<pre><code>mutate(color = case_when(code == codes(vector[i] ~ colors_vector[i])))
</code></pre>
<p>Desired output</p>
<pre><code>structure(list(code = c("hybrid", "hybrid", "hybrid", "plant based",
"plant based", "plant based"), color = structure(c(1L, 1L, 1L,
2L, 2L, 2L), levels = c("#1B9E77", "#D95F02"), class = "factor"),
Linalool = c(82855, 74398, 59563, 117635, 118724, 75271),
Nonanal = c(45433, 27520, 28883, 0, 0, 52454), `Acetic Acid` = c(263774,
99287, 79800, 529503, 666771, 0)), row.names = c("1-1", "1-2",
"1-3", "2-1", "2-2", "2-3"), class = "data.frame")
</code></pre>
|
[
{
"answer_id": 74619236,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "code integer color library(dplyr)\nlibrary(tidyr)\npcadata %>%\n ungroup %>%\n mutate(code = codes_vector[as.integer(code)],\n color = setNames(colors_vector, codes_vector)[code])%>% \n pivot_wider(names_from = compound, values_from = conc, values_fill = 0)\n # A tibble: 12 × 5\n sample code color Linalool `Acetic Acid`\n <chr> <chr> <chr> <dbl> <dbl>\n 1 1-1 code1 #1B9E77 82855 263774\n 2 1-2 code1 #1B9E77 74398 99287\n 3 1-3 code1 #1B9E77 59563 79800\n 4 2-1 code2 #D95F02 117635 529503\n 5 2-2 code2 #D95F02 118724 666771\n 6 2-3 code2 #D95F02 75271 0\n 7 3-1 code3 #7570B3 95219 0\n 8 3-2 code3 #7570B3 50870 117253\n 9 3-3 code3 #7570B3 67546 0\n10 4-1 code4 #E7298A 58063 101193\n11 4-2 code4 #E7298A 86610 65006\n12 4-3 code4 #E7298A 88594 221687\n"
},
{
"answer_id": 74619270,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 3,
"selected": true,
"text": "match pcadata %>% \n filter(code %in% c(1, 2)) %>% \n arrange(code, 4) %>%\n group_by(sample, compound) %>% \n pivot_wider(names_from = compound,\n values_from = conc,\n values_fill = 0) %>% \n ungroup() %>% \n column_to_rownames(var = \"sample\") %>% \n mutate(code = codes_vector[match(code, 1:5)]) %>% \n mutate(color = colors_vector[match(code, codes_vector)]) %>% \n mutate(color=as.factor(color)) %>% \n relocate(color, .after = code)\n#> code color Linalool Acetic Acid\n#> 1-1 code1 #1B9E77 82855 263774\n#> 1-2 code1 #1B9E77 74398 99287\n#> 1-3 code1 #1B9E77 59563 79800\n#> 2-1 code2 #D95F02 117635 529503\n#> 2-2 code2 #D95F02 118724 666771\n#> 2-3 code2 #D95F02 75271 0\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16085883/"
] |
74,619,187
|
<p>The CSV file contains name and Values</p>
<p>i want any value more than 1000 converted to 1000 in same file or in differentt file. mostly using shell script. what is the best way to it?</p>
<p>for example the values are as follows</p>
<pre><code>Name Value
ABV 1200
CCD 1000
CAD 500
DDD 1800
</code></pre>
<p>and i want it as</p>
<pre><code>Name Value
ABV 1000
CCD 1000
CAD 500
DDD 1000
</code></pre>
<p>i tried awk function but it didnt work any other alteernatives</p>
|
[
{
"answer_id": 74619399,
"author": "James Brown",
"author_id": 4162356,
"author_profile": "https://Stackoverflow.com/users/4162356",
"pm_score": 2,
"selected": false,
"text": "$ awk '{print $1,($2+0>1000?1000:$2)}' file\n Name Value\nABV 1000\nCCD 1000\nCAD 500\nDDD 1000\n"
},
{
"answer_id": 74619434,
"author": "markp-fuso",
"author_id": 7366100,
"author_profile": "https://Stackoverflow.com/users/7366100",
"pm_score": 1,
"selected": false,
"text": "-gt awk > -F, awk 'NR==1 {print $0; next} {if ($2 > 1000) {$2=1000} {print $0}}' book1.csv\n awk 'NR>1 && ($2>1000) {$2=1000} 1' book1.csv\n Name Value\nABV 1000\nCCD 1000\nCAD 500\nDDD 1000\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20637171/"
] |
74,619,193
|
<p>I want to have some input boxes which contain an text for the user to know what is required to enter. This text should disappear when the user clicks on it. How do i know which box the user clicked?</p>
<pre><code>class window():
def handleEvent(self,event):
self.text.set("")
def handleEvent2(self,event):
a = self.efeld.get()
print(a)
def page0(self):
self.text = tk.StringVar(None)
self.text.set("Enter text here")
self.efeld = ttk.Entry(fenster, textvariable=self.text)
self.efeld.place(x=5, y=20)
self.efeld.bind("<Button-1>",self.handleEvent)
self.efeld.bind("<Return>",self.handleEvent2)
self.text2 = tk.StringVar(None)
self.text2.set("Enter text 2 here")
self.efeld2 = ttk.Entry(fenster, textvariable=self.text2)
self.efeld2.place(x=5, y=50)
self.efeld2.bind("<Button-1>",self.handleEvent)
self.efeld2.bind("<Return>",self.handleEvent2)
fenster = tk.Tk()
fenster.title("Test")
fenster.geometry("500x350")
fenster.resizable(False,False)
window().page0()
fenster.mainloop()
</code></pre>
|
[
{
"answer_id": 74619217,
"author": "JRiggles",
"author_id": 8512262,
"author_profile": "https://Stackoverflow.com/users/8512262",
"pm_score": 2,
"selected": true,
"text": "event.widget"
},
{
"answer_id": 74619223,
"author": "Bryan Oakley",
"author_id": 7432,
"author_profile": "https://Stackoverflow.com/users/7432",
"pm_score": 2,
"selected": false,
"text": "widget event def handleEvent2(self,event):\n a = event.widget.get()\n print(a)\n"
},
{
"answer_id": 74619347,
"author": "Vadim Sayfi",
"author_id": 7916062,
"author_profile": "https://Stackoverflow.com/users/7916062",
"pm_score": 0,
"selected": false,
"text": "event.widget"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19542770/"
] |
74,619,214
|
<p>I have a set of patents that I have titles and abstracts on and would like to search in such a way that their final search algorithm requires the keyword “software” to be present, and none of the keywords “chip”, “semiconductor”, “bus”, “circuit” or “circuit” to be present.
i did This:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT distinct
tls201_appln.docdb_family_id
, tls201_appln.appln_id
, [appln_auth]
, [appln_nr]
, [appln_kind]
, [appln_filing_date]
, [receiving_office]
, [earliest_publn_date]
, [granted]
, [nb_citing_docdb_fam]
, [nb_applicants]
, [nb_inventors]
, tls202_appln_title.appln_title
FROM tls201_appln
INNER JOIN tls202_appln_title ON tls201_appln.appln_id = tls202_appln_title.appln_id
INNER JOIN tls203_appln_abstr ON tls201_appln.appln_id = tls203_appln_abstr.appln_id
WHERE (appln_title like '%software%'
or appln_abstract like '%software%')
AND appln_title not like '%chip%'
or '%semiconductor%'
or '%circuity%'
or '%circuitry%'
or '%bus'%'
or appln_abstract not like '%chip%'
or '%semiconductor%'
or '%circuity%'
or '%circuitry%'
or '%bus'%'
AND appln_filing_year between 2003 and 2008
</code></pre>
<p>but im getting this error <code>An expression of non-boolean type specified in a context where a condition is expected, near 'or'.</code> What should i do?</p>
|
[
{
"answer_id": 74619217,
"author": "JRiggles",
"author_id": 8512262,
"author_profile": "https://Stackoverflow.com/users/8512262",
"pm_score": 2,
"selected": true,
"text": "event.widget"
},
{
"answer_id": 74619223,
"author": "Bryan Oakley",
"author_id": 7432,
"author_profile": "https://Stackoverflow.com/users/7432",
"pm_score": 2,
"selected": false,
"text": "widget event def handleEvent2(self,event):\n a = event.widget.get()\n print(a)\n"
},
{
"answer_id": 74619347,
"author": "Vadim Sayfi",
"author_id": 7916062,
"author_profile": "https://Stackoverflow.com/users/7916062",
"pm_score": 0,
"selected": false,
"text": "event.widget"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19971208/"
] |
74,619,215
|
<p><code>xtabs</code> can make a summary table, combined with <code>cbind</code> to summarize over multiple variables, and grouped by the remaining variable:</p>
<pre><code>df<-data.frame(publication_date=c("2015 Jul","2015 Jul","2015 Aug","2015 Aug"),
Asym=c(3,5,1,2),
Auth=c(5,7,2,3),
Cert=c(1,2,3,4))
xtabs(cbind(Auth, Asym, Cert)~., data=df)
#publication_date Auth Asym Cert
# 2015 Aug 5 3 7
# 2015 Jul 12 8 3
</code></pre>
<p>Is there a way to programatically cbind all but one variable, specifically, not writing out all the variable names, (for example, if df has many more than 3 columns).</p>
<p>I tried</p>
<pre><code>xtabs(cbind(df[2:4])~., data=df)
xtabs(cbind(names(df[2:4]))~., data=df)
#Error in ... variable lengths differ
</code></pre>
|
[
{
"answer_id": 74619217,
"author": "JRiggles",
"author_id": 8512262,
"author_profile": "https://Stackoverflow.com/users/8512262",
"pm_score": 2,
"selected": true,
"text": "event.widget"
},
{
"answer_id": 74619223,
"author": "Bryan Oakley",
"author_id": 7432,
"author_profile": "https://Stackoverflow.com/users/7432",
"pm_score": 2,
"selected": false,
"text": "widget event def handleEvent2(self,event):\n a = event.widget.get()\n print(a)\n"
},
{
"answer_id": 74619347,
"author": "Vadim Sayfi",
"author_id": 7916062,
"author_profile": "https://Stackoverflow.com/users/7916062",
"pm_score": 0,
"selected": false,
"text": "event.widget"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10276092/"
] |
74,619,234
|
<p>I'm quite 'green' into WPF and I appreciate if you could share some starting point example or help me fixing my own code.
I have tree UserControl (Component, ComponentTop, ComponentBottom) that share the same ViewModel class 'ComponentViewModel'.
Instead of using this tree UserControl I would like to use just 'Component' to host the Style and DataContext (ComponentViewModel) and create 3 styles (Base,Top and Bottom) and then I just need to set Component.Style to alternate component visualization.</p>
<p>I've try to declare a style in a resource dictionary but the binding doesn't work.
And from the UserControl I can set the style "Style={StaticResource Base}" but after building the project I get error code saying 'Resource not found'.</p>
<p>The Style:</p>
<pre class="lang-xml prettyprint-override"><code><Style x:Key="Base" TargetType="UserControl">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<Border BorderThickness="0.5" BorderBrush="Gray">
<Grid>
<Grid.RowDefinitions>
<RowDefinition x:Name="Head" Height="Auto"/>
<RowDefinition x:Name="Content" Height="Auto"/>
</Grid.RowDefinitions>
<Border Grid.Column="0" Margin="1" BorderThickness="0.25" BorderBrush="Black" Background="{Binding StatusColor}">
<Grid HorizontalAlignment="Stretch">
<TextBlock Margin="1,0,1,0" Text="{Binding Name, FallbackValue=######}" VerticalAlignment="Center" HorizontalAlignment="Center"/>
<Image HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="0,0,0,1" Width="10" Height="10" Source="{Binding PriorityImage}" Visibility="{Binding PriorityImageVisibility}"></Image>
</Grid>
</Border>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<layout:TagsContainer Margin="2,0,0,0" Grid.Column="0" VerticalAlignment="Top" HorizontalAlignment="Left" DataContext="{Binding TagsContainerDataContext}"/>
<layout:ControlTagsContainer Margin="5,0,2,0" Grid.Column="1" VerticalAlignment="Top" HorizontalAlignment="Left" DataContext="{Binding ControlTagsContainerDataContext}"/>
</Grid>
<Image Grid.Row="1" Grid.RowSpan="2" HorizontalAlignment="Center" VerticalAlignment="Center" Width="25" Height="25" MaxHeight="35" MaxWidth="35" Source="{Binding StatusImage}" Visibility="{Binding StatusImageVisibility}" ></Image>
</Grid>
</Border>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</code></pre>
<p>The UserControl:</p>
<pre class="lang-xml prettyprint-override"><code><UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:ProjectX.UI.Layout"
xmlns:ViewModels="clr-namespace:ProjectX.UI.Layout.ViewModels"
x:Class="ProjectX.UI.Layout.Component"
mc:Ignorable="d" Cursor="" x:Name="Root" Height="auto" MinHeight="10" MinWidth="10" FontSize="10" Width="auto" Style="{ StaticResource Base }" >
<UserControl.DataContext>
<ViewModels:ComponentViewModel/>
</UserControl.DataContext>
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source= "Components.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
</code></pre>
<p>TheViewModel:</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectX.Model.Component;
using DevExpress.Mvvm;
using System.Windows.Media;
using ProjectX.Model.Tag;
using ProjectX.UI.Tag;
using AppContext = ProjectX.Model.Tag.AppContext;
using System.Windows;
using System.Windows.Media.Imaging;
using ProjectX.Model.Component.Components;
namespace ProjectX.UI.Layout.ViewModels
{
public class ComponentViewModel : ViewModelBase
{
private ComponentBase DataModel = new ComponentBase();
public string? Name
{
get { return GetValue<string>(); }
private set { SetValue(value); }
}
public Brush StatusColor
{
get { return GetValue<Brush>(); }
private set { SetValue(value); }
}
public ImageSource StatusImage
{
get { return GetValue<ImageSource>(); }
private set { SetValue(value); }
}
public Visibility StatusImageVisibility
{
get { return GetValue<Visibility>(); }
private set { SetValue(value); }
}
public ImageSource PriorityImage
{
get { return GetValue<ImageSource>(); }
private set { SetValue(value); }
}
public Visibility PriorityImageVisibility
{
get { return GetValue<Visibility>(); }
private set { SetValue(value); }
}
public Visibility SHControlsVisibility
{
get { return GetValue<Visibility>(); }
private set { SetValue(value); }
}
public TagsContainerViewModel TagsContainerDataContext
{
get { return GetValue<TagsContainerViewModel>(); }
private set { SetValue(value); }
}
public ControlTagsContainerViewModel ControlTagsContainerDataContext
{
get { return GetValue<ControlTagsContainerViewModel>();}
private set { SetValue(value); }
}
private List<RuntimeTagViewModel>? Tags = null;
private List<RuntimeTagViewModel>? ControlTags = null;
public ComponentViewModel()
{
Name = "COMPONENT X";
TagsContainerDataContext = new TagsContainerViewModel();
ControlTagsContainerDataContext = new ControlTagsContainerViewModel();
Init();
}
public ComponentViewModel(ComponentBase datamodel)
{
DataModel = datamodel;
Name = datamodel.Label;
Tags = DataModel.Tags.Where(x => x.AppContext == AppContext.Layout && x.Scope == Scope.User).Select(x => new RuntimeTagViewModel(x)).ToList();
ControlTags = DataModel.Tags.Where(x => x.AppContext == AppContext.Control && x.Scope == Scope.User).Select(x => new RuntimeTagViewModel(x)).ToList();
TagsContainerDataContext = new TagsContainerViewModel(Tags);
ControlTagsContainerDataContext = new ControlTagsContainerViewModel(ControlTags);
Init();
}
private void Init()
{
StatusColor = Brushes.Gray;
SetStatusImage(StatusEnum.Warning);
SHControlsVisibility = Visibility.Collapsed;
PriorityImageVisibility = Visibility.Collapsed;
if (DataModel.Interface == nameof(IDamper))
{
PriorityImage = Global.Resources.Images.Priority;
PriorityImageVisibility = Visibility.Visible;
}
if (DataModel.Interface == nameof(ISystemHandler))
{
SHControlsVisibility = Visibility.Visible;
}
}
public void SetStatusImage(StatusEnum status = StatusEnum.None)
{
switch (status)
{
case StatusEnum.None:
StatusImage = Global.Resources.Images.Warning;
break;
case StatusEnum.Error:
StatusImage = Global.Resources.Images.Error;
break;
case StatusEnum.Warning:
StatusImage = Global.Resources.Images.Warning;
break;
case StatusEnum.Info:
StatusImage = Global.Resources.Images.Info;
break;
default:
throw new NotImplementedException();
}
if (status != StatusEnum.None)
{
StatusImageVisibility = Visibility.Visible;
}
else
{
StatusImageVisibility = Visibility.Hidden;
}
}
}
}
</code></pre>
<p>Thank you!</p>
|
[
{
"answer_id": 74619217,
"author": "JRiggles",
"author_id": 8512262,
"author_profile": "https://Stackoverflow.com/users/8512262",
"pm_score": 2,
"selected": true,
"text": "event.widget"
},
{
"answer_id": 74619223,
"author": "Bryan Oakley",
"author_id": 7432,
"author_profile": "https://Stackoverflow.com/users/7432",
"pm_score": 2,
"selected": false,
"text": "widget event def handleEvent2(self,event):\n a = event.widget.get()\n print(a)\n"
},
{
"answer_id": 74619347,
"author": "Vadim Sayfi",
"author_id": 7916062,
"author_profile": "https://Stackoverflow.com/users/7916062",
"pm_score": 0,
"selected": false,
"text": "event.widget"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13103927/"
] |
74,619,251
|
<p>I want to use a formula to find the highest N values in each group in a Google Spread Sheets.</p>
<p>I tried this formula from <a href="https://infoinspired.com/google-docs/spreadsheet/find-the-highest-n-values-in-each-group/" rel="nofollow noreferrer">infoinspired.com</a> (credit to Prashanth):</p>
<blockquote>
<p>=ArrayFormula(QUERY({SORT(A2:B;1;true;2;false);IFERROR(row(A2:A)-match(query(SORT(A2:B;1;true;2;false);"Select Col1");query(SORT(A2:B;1;true;2;false);"Select Col1");0))};"Select Col1,Col2 where Col3<3"))</p>
</blockquote>
<p>But all it return is an Array_Literal error:
<a href="https://i.stack.imgur.com/RRC4H.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RRC4H.png" alt="error" /></a></p>
<p>This is what I expect:
<a href="https://i.stack.imgur.com/NOPl3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NOPl3.png" alt="expected" /></a></p>
<p>What is wrong with it?</p>
|
[
{
"answer_id": 74619557,
"author": "Martín",
"author_id": 20363318,
"author_profile": "https://Stackoverflow.com/users/20363318",
"pm_score": 2,
"selected": true,
"text": "=ArrayFormula(QUERY({SORT(A2:B,1,true,2,false),IFERROR(row(A2:A)-match(query(SORT(A2:B,1,true,2,false),\"Select Col1\"),query(SORT(A2:B,1,true,2,false),\"Select Col1\"),0))},\"Select Col1,Col2 where Col3<3\"))\n"
},
{
"answer_id": 74620699,
"author": "rockinfreakshow",
"author_id": 5479575,
"author_profile": "https://Stackoverflow.com/users/5479575",
"pm_score": 0,
"selected": false,
"text": "=QUERY(SORT({{A2:B}\\MAP(A2:A;B2:B;lambda(ax;bx;IFERROR(Rank(bx;Filter(B$2:$B;A$2:$A=ax);0);IFERROR(1/0))))};1;0;3;1);\"Select Col1, Col2 Where Col3<3\")"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17988705/"
] |
74,619,261
|
<p>I am unable to connect my index.js file with Django and index.html
Django is connected to index.html fine but not to index.js. I have attached my settings.py, urls.py, index.html, webpack.config.js, and index.js files below.</p>
<p>settings.py:</p>
<pre><code>from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
STATICFILES_DIR = os.path.join(BASE_DIR, 'static')
TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates')
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = 'static/'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [STATICFILES_DIR,TEMPLATES_DIR,],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
</code></pre>
<p>In settings.py DEBUG=True</p>
<p>urls.py:</p>
<pre><code>from django.contrib import admin
from django.urls import path
from django.views.generic import TemplateView
urlpatterns = [
path('admin/', admin.site.urls),
path('hello/', TemplateView.as_view(template_name='index.html'))
]
</code></pre>
<p>index.html:</p>
<pre><code>{% load static %}
<!doctype html>
<html>
<head>
<title>NEPTUNE Analytics</title>
</head>
<body>
<script src="{% static 'index-bundle.js' %}"></script>
</body>
</html>
</code></pre>
<p>webpack.config.js:</p>
<pre><code>const path = require('path');
module.exports = {
entry: './js/index.js', // path to our input file
output: {
path: path.resolve(__dirname, './static'), // path to our Django static directory
filename: 'index-bundle.js', // output bundle file name
},
};
</code></pre>
<p>index.js:</p>
<pre><code>
function component() {
const element = document.createElement('div');
element.innerHTML = 'Hello World';
return element;
}
document.body.appendChild(component())
</code></pre>
<p>I have tried changing DIRS in settings.py to</p>
<pre><code>STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'templates'),
os.path.join(BASE_DIR, 'static'),
]
</code></pre>
<p>but I get a list error, and if I change it to a tuple, I get a tuple error.</p>
|
[
{
"answer_id": 74619557,
"author": "Martín",
"author_id": 20363318,
"author_profile": "https://Stackoverflow.com/users/20363318",
"pm_score": 2,
"selected": true,
"text": "=ArrayFormula(QUERY({SORT(A2:B,1,true,2,false),IFERROR(row(A2:A)-match(query(SORT(A2:B,1,true,2,false),\"Select Col1\"),query(SORT(A2:B,1,true,2,false),\"Select Col1\"),0))},\"Select Col1,Col2 where Col3<3\"))\n"
},
{
"answer_id": 74620699,
"author": "rockinfreakshow",
"author_id": 5479575,
"author_profile": "https://Stackoverflow.com/users/5479575",
"pm_score": 0,
"selected": false,
"text": "=QUERY(SORT({{A2:B}\\MAP(A2:A;B2:B;lambda(ax;bx;IFERROR(Rank(bx;Filter(B$2:$B;A$2:$A=ax);0);IFERROR(1/0))))};1;0;3;1);\"Select Col1, Col2 Where Col3<3\")"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9931072/"
] |
74,619,297
|
<p>I have a parant that contains a child and a function within the parent that I wish to run form the child. However with the current code what is happening is the function is ran instantly instead of when the button is pressed on the child component. any ideas? Here is the code:</p>
<pre><code>const Parent = () => {
const [showPayment, setShowPayment] = useState(true);
const [showSignupComplete, setShowSignupComplete] = useState(false);
const CompleteSignup = () => {
setShowPayment(false);
setShowSignupComplete(true);
}
return (
<div>
{showPayment ?(
<Payment paymentChange={CompleteSignup}/>
):null }
{showSignupComplete ?(
<div> Sign up complete </div>
):null }
</div>
}
const Payment = ({paymentChange}) => {
const handleSubmitSub = async (event) => {
paymentChange
}
return (
<div>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className="submit"
onClick={handleSubmitSub}
>
Complete Payment
</Button>
</div>
)
</code></pre>
<p>}</p>
<p>I've updated the code with the suggestions below. however get the error: paymentChange is not a function</p>
|
[
{
"answer_id": 74619605,
"author": "LiquiD.S1nn3r",
"author_id": 15175112,
"author_profile": "https://Stackoverflow.com/users/15175112",
"pm_score": 0,
"selected": false,
"text": "const Button = ({onClick as fn}) => {\n\n/// your code here.....\n\nreturn (\n<button onClick={fn}>YOUR BUTTON TEXT</button>\n)\n\n}\n"
},
{
"answer_id": 74620394,
"author": "Getsumi3",
"author_id": 13022536,
"author_profile": "https://Stackoverflow.com/users/13022536",
"pm_score": 2,
"selected": true,
"text": "completeSignup Payment Parent handleSubmitSub Payment handleSubmitSub paymentChange const handleSubmitSub = async (event) => {paymentChange()} const Parent = () => {\n const [showPayment, setShowPayment] = useState(true);\n const [showSignupComplete, setShowSignupComplete] = useState(false);\n\n const completeSignup = () => {\n setShowPayment(false);\n setShowSignupComplete(true);\n }\n\n return (\n <div>\n {showPayment && <Payment paymentChange={completeSignup}/>}\n {\n showSignupComplete && \n <div> Sign up complete </div>\n }\n </div>\n ) \n}\n\nconst Payment = ({paymentChange}) => { \n const handleSubmitSub = async (event) => {paymentChange()}\n\n return (\n <div>\n <button\n type=\"submit\"\n fullWidth\n variant=\"contained\"\n color=\"primary\"\n className=\"submit\"\n onClick={handleSubmitSub}\n >\n Complete Payment\n </button>\n </div>\n )\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3827252/"
] |
74,619,303
|
<p>So I have a dictionary that looks something like the following:</p>
<pre class="lang-py prettyprint-override"><code>{
"tigj09j32f0j2": {
"car": {
"lead": {
"version": "1.1"
}
},
"bike": {
"lead": {
"version": "2.2"
}
},
"jet_ski": {
"lead": {
"version": "3.3"
}
}
},
"fj983j2r9jfjf": {
"car": {
"lead": {
"version": "1.1"
}
},
"bike": {
"lead": {
"version": "2.3"
}
},
"jet_ski": {
"lead": {
"version": "3.3"
}
}
}
}
</code></pre>
<p>The number of different dictionaries that contain <code>car</code>, <code>bike</code> and <code>jet_ski</code> can be huge and not just two as in my example. The number of different vehicle types can also be much larger. My goal is to find a mismatch in a given type of vehicle <code>version</code> between the different dictionaries. For example for <code>bike</code> the <code>version</code> is different between the two dictionaries.</p>
<p>The way I currently do it is by iterating through all sub-dictionaries in my dictionary and then looking for the version. I save the version in a class dictionary that contains the vehicle type and version and then start comparing to it. I am sure there is a much more elegant and pythonic way to go about this and would appreciate any feedback!</p>
<p>Here is more or less what I am doing:</p>
<pre class="lang-py prettyprint-override"><code>def is_version_issue(vehicle_type: str, object_json: dict):
issue = False
for object_id in object_json:
current_object = object_json.get(object_id)
if vehicle_type in current_object:
current_vehicle_version = current_object.get(vehicle_type).get("lead").get("version")
# vehicles is a class dictionary that contains the vehicles I am looking for
if self.vehicles[vehicle_type]:
if self.vehicles[vehicle_type] == current_vehicle_version:
issue = False
continue
else:
return True
self.vehicles[vehicle_type] = current_vehicle_version
issue = False
return issue
</code></pre>
|
[
{
"answer_id": 74619428,
"author": "CrabBucket",
"author_id": 19730434,
"author_profile": "https://Stackoverflow.com/users/19730434",
"pm_score": 1,
"selected": false,
"text": "def is_version_issue(vehicle_type: str, object_json: dict):\n current_object = object_json[object_id]\n for object_id in current_object:\n if vehicle_type in object_json[object_id]:\n current_vehicle_version = current_object[vehicle_type][\"lead\"][\"version\"]\n # vehicles is a class dictionary that contains the vehicles I am looking for\n if self.vehicles[vehicle_type]:\n if self.vehicles[vehicle_type] != current_vehicle_version:\n return True\n return False\n"
},
{
"answer_id": 74619543,
"author": "Daniil Fajnberg",
"author_id": 19770795,
"author_profile": "https://Stackoverflow.com/users/19770795",
"pm_score": 3,
"selected": true,
"text": "object_id dict.values issue continue vehicle_type lead version dict.get None [] True False dict[str, Any] version ver KEY_LEAD = \"lead\"\nKEY_VERSION = \"version\"\n\ndef versions_consistent(\n vehicle_type: str,\n data: dict[str, dict[str, dict[str, dict[str, str]]]]\n) -> bool:\n version_found: str | None = None\n for vehicles in data.values():\n vehicle = vehicles.get(vehicle_type)\n if vehicle is None:\n continue\n if version_found is None:\n version_found = vehicle[KEY_LEAD][KEY_VERSION]\n elif version_found != vehicle[KEY_LEAD][KEY_VERSION]:\n return False\n return True\n version_found None vehicle_type bool ALLOWED_VEHICLES = {\"car\", \"bike\", \"jet_ski\"}\n\ndef get_version_id_mapping(\n vehicle_type: str,\n data: dict[str, dict[str, dict[str, dict[str, str]]]]\n) -> dict[str, set[str]]:\n if vehicle_type not in ALLOWED_VEHICLES:\n raise ValueError(f\"{vehicle_type} is not a valid vehicle type\")\n version_id_map: dict[str, set[str]] = {}\n for obj_id, vehicles in data.items():\n vehicle = vehicles.get(vehicle_type)\n if vehicle is None:\n continue\n ids = version_id_map.setdefault(vehicle[\"lead\"][\"version\"], set())\n ids.add(obj_id)\n return version_id_map\n get_version_id_mapping(\"bike\", d) d jet_ski > 1 def vehicle_type_versions(\n data: dict[str, dict[str, dict[str, dict[str, str]]]]\n) -> dict[str, dict[str, set[str]]]:\n output: dict[str, dict[str, set[str]]] = {}\n for obj_id, vehicles in data.items():\n for vehicle_type, vehicle_data in vehicles.items():\n sub_dict = output.setdefault(vehicle_type, {})\n ids = sub_dict.setdefault(vehicle_data[\"lead\"][\"version\"], set())\n ids.add(obj_id)\n return output\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12057138/"
] |
74,619,340
|
<p>I am having trouble at the end of the test. The test is to login in a user and the screen on successful login should refresh and a list appears on the screen. The login is successful, but the list is not showing. Do I need to do a rerender or something? The screen.debug() at the bottom is what I am using to verify that the list is not showing. I can see the login screen appear.</p>
<pre><code>describe("<App />", () => {
let server: any = null;
beforeEach(() => {
server = makeServer({ environment : "test" });
});
afterEach(() => {
server.shutdown()
});
test("Login", async () => {
render(<App />);
const btnLogin = screen.getByText(/Login/i) as HTMLButtonElement;
expect(btnLogin.disabled).toBe(false);
const user = userEvent.setup();
await user.click(btnLogin);
let btnOk = screen.getByText(/OK/i) as HTMLButtonElement;
expect(btnOk.disabled).toBe(true);
let btnCancel = screen.getByText(/Cancel/i) as HTMLButtonElement;
expect(btnCancel.disabled).toBe(false);
const txt = screen.getByLabelText(/Access Code/i) as HTMLInputElement;
fireEvent.change(txt, { target: { value: 'USER' } });
await user.click(btnOk);
screen.debug();
});
});
</code></pre>
|
[
{
"answer_id": 74619428,
"author": "CrabBucket",
"author_id": 19730434,
"author_profile": "https://Stackoverflow.com/users/19730434",
"pm_score": 1,
"selected": false,
"text": "def is_version_issue(vehicle_type: str, object_json: dict):\n current_object = object_json[object_id]\n for object_id in current_object:\n if vehicle_type in object_json[object_id]:\n current_vehicle_version = current_object[vehicle_type][\"lead\"][\"version\"]\n # vehicles is a class dictionary that contains the vehicles I am looking for\n if self.vehicles[vehicle_type]:\n if self.vehicles[vehicle_type] != current_vehicle_version:\n return True\n return False\n"
},
{
"answer_id": 74619543,
"author": "Daniil Fajnberg",
"author_id": 19770795,
"author_profile": "https://Stackoverflow.com/users/19770795",
"pm_score": 3,
"selected": true,
"text": "object_id dict.values issue continue vehicle_type lead version dict.get None [] True False dict[str, Any] version ver KEY_LEAD = \"lead\"\nKEY_VERSION = \"version\"\n\ndef versions_consistent(\n vehicle_type: str,\n data: dict[str, dict[str, dict[str, dict[str, str]]]]\n) -> bool:\n version_found: str | None = None\n for vehicles in data.values():\n vehicle = vehicles.get(vehicle_type)\n if vehicle is None:\n continue\n if version_found is None:\n version_found = vehicle[KEY_LEAD][KEY_VERSION]\n elif version_found != vehicle[KEY_LEAD][KEY_VERSION]:\n return False\n return True\n version_found None vehicle_type bool ALLOWED_VEHICLES = {\"car\", \"bike\", \"jet_ski\"}\n\ndef get_version_id_mapping(\n vehicle_type: str,\n data: dict[str, dict[str, dict[str, dict[str, str]]]]\n) -> dict[str, set[str]]:\n if vehicle_type not in ALLOWED_VEHICLES:\n raise ValueError(f\"{vehicle_type} is not a valid vehicle type\")\n version_id_map: dict[str, set[str]] = {}\n for obj_id, vehicles in data.items():\n vehicle = vehicles.get(vehicle_type)\n if vehicle is None:\n continue\n ids = version_id_map.setdefault(vehicle[\"lead\"][\"version\"], set())\n ids.add(obj_id)\n return version_id_map\n get_version_id_mapping(\"bike\", d) d jet_ski > 1 def vehicle_type_versions(\n data: dict[str, dict[str, dict[str, dict[str, str]]]]\n) -> dict[str, dict[str, set[str]]]:\n output: dict[str, dict[str, set[str]]] = {}\n for obj_id, vehicles in data.items():\n for vehicle_type, vehicle_data in vehicles.items():\n sub_dict = output.setdefault(vehicle_type, {})\n ids = sub_dict.setdefault(vehicle_data[\"lead\"][\"version\"], set())\n ids.add(obj_id)\n return output\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1730289/"
] |
74,619,352
|
<p>I want to get the <code>name</code> of the user, using the <strong>Reserves</strong> model, because that's the one I can display. The **User ** model is referenced in the **Reserve ** model. and the only thing I can get is the Object ID.</p>
<p>How can I get other field values from the User model through the reference?</p>
<p>Here is the code for the user model:</p>
<pre><code>const mongoose = require('mongoose')
const userSchema = mongoose.Schema({
name: {
type: String,
required: [true, 'Please add a name']
},
idnum: {
type: String,
required: [true, 'Please add an id number'],
unique: true
},
password: {
type: String,
required: [true, 'Please add a password']
},
role: {
type: String,
required: [true, 'Please select a role'],
enum: ["Faculty", "Student Officer", "Admin"]
},
org: {
type: String,
required: [true, 'Please add an organization'],
},
dept: {
type: String,
required: [true, 'Please add a deparment'],
},
}, {
timestamps: true
})
module.exports = mongoose.model('User', userSchema)
</code></pre>
<p>Here is the code for the Reserve model:</p>
<pre><code>const mongoose = require('mongoose')
const reserveSchema = mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Users'
},
purpose: {
type: String,
required: [true, 'Please add a purpose']
},
dept: {
type: String,
required: [true, 'Please choose a department']
},
org: {
type: String,
required: [true, 'Please choose an organization']
},
bldg: {
type: String,
required: [true, 'Please choose a building']
},
room: {
type: String,
required: [true, 'Please add a room']
},
date: {
type: String,
required: [true, 'Please add a date']
},
time_in: {
type: String,
required: [true, 'Please add a starting time']
},
time_out: {
type: String,
required: [true, 'Please add an ending time']
},
status: {
type: String,
},
}, {
timestamps: true,
})
module.exports = mongoose.model('Reserve', reserveSchema)
</code></pre>
<p>Then, here is the code in fetching the from the database, using the model</p>
<pre><code>function ReservesContent({reserves}) {
return (
<div class='info-container'>
<p id='requestor'>{reserves.user}</p>
<p id='purpose'>{reserves.purpose}</p>
<p id='building'>{reserves.bldg}</p>
<p id='room'>{reserves.room}</p>
<p id='time_in'>{reserves.time_in}</p>
<p id='time_out'>{reserves.time_out}</p>
</div>
);
}
export default ReservesContent
</code></pre>
<pre><code>{reserves.length > 0 ? (
<div>
{reserves.map((reserve) => (
<ReservesContent key={reserve._id} reserves={reserve} />
))}
</div>
) : (<h3>No Reservations Found</h3>)}
</code></pre>
|
[
{
"answer_id": 74619428,
"author": "CrabBucket",
"author_id": 19730434,
"author_profile": "https://Stackoverflow.com/users/19730434",
"pm_score": 1,
"selected": false,
"text": "def is_version_issue(vehicle_type: str, object_json: dict):\n current_object = object_json[object_id]\n for object_id in current_object:\n if vehicle_type in object_json[object_id]:\n current_vehicle_version = current_object[vehicle_type][\"lead\"][\"version\"]\n # vehicles is a class dictionary that contains the vehicles I am looking for\n if self.vehicles[vehicle_type]:\n if self.vehicles[vehicle_type] != current_vehicle_version:\n return True\n return False\n"
},
{
"answer_id": 74619543,
"author": "Daniil Fajnberg",
"author_id": 19770795,
"author_profile": "https://Stackoverflow.com/users/19770795",
"pm_score": 3,
"selected": true,
"text": "object_id dict.values issue continue vehicle_type lead version dict.get None [] True False dict[str, Any] version ver KEY_LEAD = \"lead\"\nKEY_VERSION = \"version\"\n\ndef versions_consistent(\n vehicle_type: str,\n data: dict[str, dict[str, dict[str, dict[str, str]]]]\n) -> bool:\n version_found: str | None = None\n for vehicles in data.values():\n vehicle = vehicles.get(vehicle_type)\n if vehicle is None:\n continue\n if version_found is None:\n version_found = vehicle[KEY_LEAD][KEY_VERSION]\n elif version_found != vehicle[KEY_LEAD][KEY_VERSION]:\n return False\n return True\n version_found None vehicle_type bool ALLOWED_VEHICLES = {\"car\", \"bike\", \"jet_ski\"}\n\ndef get_version_id_mapping(\n vehicle_type: str,\n data: dict[str, dict[str, dict[str, dict[str, str]]]]\n) -> dict[str, set[str]]:\n if vehicle_type not in ALLOWED_VEHICLES:\n raise ValueError(f\"{vehicle_type} is not a valid vehicle type\")\n version_id_map: dict[str, set[str]] = {}\n for obj_id, vehicles in data.items():\n vehicle = vehicles.get(vehicle_type)\n if vehicle is None:\n continue\n ids = version_id_map.setdefault(vehicle[\"lead\"][\"version\"], set())\n ids.add(obj_id)\n return version_id_map\n get_version_id_mapping(\"bike\", d) d jet_ski > 1 def vehicle_type_versions(\n data: dict[str, dict[str, dict[str, dict[str, str]]]]\n) -> dict[str, dict[str, set[str]]]:\n output: dict[str, dict[str, set[str]]] = {}\n for obj_id, vehicles in data.items():\n for vehicle_type, vehicle_data in vehicles.items():\n sub_dict = output.setdefault(vehicle_type, {})\n ids = sub_dict.setdefault(vehicle_data[\"lead\"][\"version\"], set())\n ids.add(obj_id)\n return output\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20637623/"
] |
74,619,360
|
<p>I am trying to create a formula that totals the number of tardies for a student in column b when I insert a new column each day between column b and c (see example sheet <a href="https://docs.google.com/spreadsheets/d/1axI2nI7IgCDViEi_ZHKlz_h1N8kGBb4j-gXtp9bRyGQ/edit?usp=sharing" rel="nofollow noreferrer">here</a>)</p>
<p>when I use =sum(C2:2) it works until I add the column but then the formula changes to =sum(D2:2) and the new data is not counted.</p>
<p>I tried to use =sum(indirect("C2"):D2:2) but when I do that and drag the formula down the column it adds the row and adds it to the total of all the cells above (in this case B4 would be 6+3 = 9 and the student after if there was one would by 9 plus how every many tardies the following student has.</p>
<p>I'm sure this is an easy thing to do but I am stumped. Any help would be much appreciated.</p>
<p>I tried to use =sum(indirect("C2"):D2:2) but when I do that and drag the formula down the column it adds the row and adds it to the total of all the cells above (in this case B4 would be 6+3 = 9 and the student after if there was one would by 9 plus how every many tardies the following student has.</p>
<p>I'm sure this is an easy thing to do but I am stumped. Any help would be much appreciated.</p>
|
[
{
"answer_id": 74619428,
"author": "CrabBucket",
"author_id": 19730434,
"author_profile": "https://Stackoverflow.com/users/19730434",
"pm_score": 1,
"selected": false,
"text": "def is_version_issue(vehicle_type: str, object_json: dict):\n current_object = object_json[object_id]\n for object_id in current_object:\n if vehicle_type in object_json[object_id]:\n current_vehicle_version = current_object[vehicle_type][\"lead\"][\"version\"]\n # vehicles is a class dictionary that contains the vehicles I am looking for\n if self.vehicles[vehicle_type]:\n if self.vehicles[vehicle_type] != current_vehicle_version:\n return True\n return False\n"
},
{
"answer_id": 74619543,
"author": "Daniil Fajnberg",
"author_id": 19770795,
"author_profile": "https://Stackoverflow.com/users/19770795",
"pm_score": 3,
"selected": true,
"text": "object_id dict.values issue continue vehicle_type lead version dict.get None [] True False dict[str, Any] version ver KEY_LEAD = \"lead\"\nKEY_VERSION = \"version\"\n\ndef versions_consistent(\n vehicle_type: str,\n data: dict[str, dict[str, dict[str, dict[str, str]]]]\n) -> bool:\n version_found: str | None = None\n for vehicles in data.values():\n vehicle = vehicles.get(vehicle_type)\n if vehicle is None:\n continue\n if version_found is None:\n version_found = vehicle[KEY_LEAD][KEY_VERSION]\n elif version_found != vehicle[KEY_LEAD][KEY_VERSION]:\n return False\n return True\n version_found None vehicle_type bool ALLOWED_VEHICLES = {\"car\", \"bike\", \"jet_ski\"}\n\ndef get_version_id_mapping(\n vehicle_type: str,\n data: dict[str, dict[str, dict[str, dict[str, str]]]]\n) -> dict[str, set[str]]:\n if vehicle_type not in ALLOWED_VEHICLES:\n raise ValueError(f\"{vehicle_type} is not a valid vehicle type\")\n version_id_map: dict[str, set[str]] = {}\n for obj_id, vehicles in data.items():\n vehicle = vehicles.get(vehicle_type)\n if vehicle is None:\n continue\n ids = version_id_map.setdefault(vehicle[\"lead\"][\"version\"], set())\n ids.add(obj_id)\n return version_id_map\n get_version_id_mapping(\"bike\", d) d jet_ski > 1 def vehicle_type_versions(\n data: dict[str, dict[str, dict[str, dict[str, str]]]]\n) -> dict[str, dict[str, set[str]]]:\n output: dict[str, dict[str, set[str]]] = {}\n for obj_id, vehicles in data.items():\n for vehicle_type, vehicle_data in vehicles.items():\n sub_dict = output.setdefault(vehicle_type, {})\n ids = sub_dict.setdefault(vehicle_data[\"lead\"][\"version\"], set())\n ids.add(obj_id)\n return output\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20637647/"
] |
74,619,361
|
<p>I have this function that is supposed to return an array of prime numbers from 2 to <em>n</em>, but sometimes it doesn't return anything and just says "exited with code=3221225477", specificaly, if I enter a value over 3 or 4. When it does work, it skips over the number 5 and prints "2 3 29541 7 11 ...".</p>
<p>Can someone point out what's wrong with it?</p>
<pre><code>#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int *primes_in_range(int stop){
int *array_primes = malloc(sizeof(int));
int size = 1;
int aim;
int prime;
array_primes[0] = 2;
for (int number = 3; number <= stop; number += 2){
aim = sqrt(number);
for (int index = 0; index < size; index++){
prime = array_primes[index];
if ((number % prime) == 0){
break;
}
else if (prime >= aim){
array_primes = realloc(array_primes, sizeof(int)*size);
array_primes[size] = number;
size += 1;
break;
}
}
}
return array_primes;
}
int main(){
int *result = primes_in_range(8);
for (int i=0; i<8; i++) printf("%d\n", result[i]);
free(result);
return 0;
}
</code></pre>
<p>I wrote a program following the same algorithm in python and it didn't skip any numbers, so it must be for a different reason that it doesn't work unless I missed something.</p>
<p>I'll leave the working python code here:</p>
<pre><code>def primes_in_range(stop: int = None):
prms = [2]
for num in range(3, stop+1, 2):
aim = num**0.5
for prm in prms:
if not num % prm:
break
elif prm >= aim:
prms.append(num)
break
if stop >= 2:
return prms
else:
return []
print(primes_in_range(13))
</code></pre>
|
[
{
"answer_id": 74619438,
"author": "Nelfeal",
"author_id": 3854570,
"author_profile": "https://Stackoverflow.com/users/3854570",
"pm_score": 2,
"selected": false,
"text": "array_primes = realloc(array_primes, sizeof(int)*size);\narray_primes[size] = number;\nsize += 1;\n size += 1; // first increase the size\narray_primes = realloc(array_primes, sizeof(int)*size); // realloc to new size\narray_primes[size-1] = number; // access last element, as usual\n"
},
{
"answer_id": 74619481,
"author": "Adrian Mole",
"author_id": 10871073,
"author_profile": "https://Stackoverflow.com/users/10871073",
"pm_score": 3,
"selected": true,
"text": "size realloc size - 1 array_primes[size] int* printf #include<stdio.h>\n#include<stdlib.h>\n#include<math.h>\n\nint* primes_in_range(int stop, int* found) {\n int* array_primes = malloc(sizeof(int));\n int size = 1;\n int aim;\n int prime;\n\n array_primes[0] = 2;\n\n for (int number = 3; number <= stop; number += 2) {\n aim = sqrt(number);\n\n for (int index = 0; index < size; index++) {\n prime = array_primes[index];\n\n if ((number % prime) == 0) {\n break;\n }\n else if (prime >= aim) {\n size += 1; // Increase size BEFORE reallocating!\n array_primes = realloc(array_primes, sizeof(int) * size);\n array_primes[size - 1] = number; // The last (new) entry is at index \"n - 1\"\n break;\n }\n }\n }\n *found = size; // So we know how many were found\n return array_primes;\n}\n\nint main() {\n int total = 0;\n int* result = primes_in_range(8, &total);\n\n for (int i = 0; i < total; i++) printf(\"%d\\n\", result[i]); // Stop at found number\n free(result);\n\n return 0;\n}\n\n"
},
{
"answer_id": 74619785,
"author": "Gilbert",
"author_id": 693294,
"author_profile": "https://Stackoverflow.com/users/693294",
"pm_score": 1,
"selected": false,
"text": " int *array_primes = calloc(stop+1, sizeof(int));\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19163263/"
] |
74,619,432
|
<p>The following script is working fine. But need to add one more item in array without built-in function. Is it possible to do without <code>Resize()</code> ?</p>
<pre><code>string[] data = {"item-1", "item-2"};
Array.Resize(ref data, 3);
data[2] = "item-3";
foreach(string i in data) {
Console.WriteLine(i);
}
</code></pre>
|
[
{
"answer_id": 74619469,
"author": "julealgon",
"author_id": 1946412,
"author_profile": "https://Stackoverflow.com/users/1946412",
"pm_score": 2,
"selected": false,
"text": "List<T>"
},
{
"answer_id": 74619491,
"author": "Charles Yang",
"author_id": 13101880,
"author_profile": "https://Stackoverflow.com/users/13101880",
"pm_score": 3,
"selected": true,
"text": "string[] data = {\"item-1\", \"item-2\"};\nstring[] newData = new string[data.Length + 1];\n\nint i;\nfor (i = 0; i < data.Length; i++) {\n newData[i] = data[i];\n}\nnewData[i] = \"item-3\";\nConsole.WriteLine(newData[2]);\n"
},
{
"answer_id": 74619568,
"author": "AchoVasilev",
"author_id": 12541118,
"author_profile": "https://Stackoverflow.com/users/12541118",
"pm_score": 2,
"selected": false,
"text": "public class List<T> : IAbstractList<T>\n{\n private const int DEFAULT_CAPACITY = 4;\n private T[] _items;\n\n public List()\n : this(DEFAULT_CAPACITY) {\n }\n\n public List(int capacity)\n {\n if (capacity < 0)\n {\n throw new ArgumentOutOfRangeException(nameof(capacity));\n }\n\n this._items = new T[capacity];\n }\n\n public T this[int index]\n {\n get\n {\n this.ValidateIndex(index);\n return this._items[index];\n }\n set\n {\n this.ValidateIndex(index);\n this._items[index] = value;\n }\n }\n\n public int Count { get; private set; }\n\n public void Add(T item)\n {\n this.GrowIfNecessary();\n\n this._items[this.Count++] = item;\n }\n\n public bool Contains(T item)\n {\n for (int i = 0; i < this.Count; i++)\n {\n if (this._items[i].Equals(item))\n {\n return true;\n }\n }\n\n return false;\n }\n\n public int IndexOf(T item)\n {\n for (int i = 0; i < this.Count; i++)\n {\n if (this._items[i].Equals(item))\n {\n return i;\n }\n }\n\n return -1;\n }\n\n public void Insert(int index, T item)\n {\n this.ValidateIndex(index);\n this.GrowIfNecessary();\n\n for (int i = this.Count - 1; i > index; i--)\n {\n this._items[i] = this._items[i - 1];\n }\n\n this._items[index] = item;\n this.Count++;\n }\n\n public bool Remove(T item)\n {\n var index = this.IndexOf(item);\n if (index == - 1)\n {\n return false;\n }\n\n this.RemoveAt(index);\n return true;\n }\n\n public void RemoveAt(int index)\n {\n this.ValidateIndex(index);\n for(int i = index; i < this.Count - 1; i++)\n {\n this._items[i] = this._items[i + 1];\n }\n\n this._items[this.Count - 1] = default;\n this.Count--;\n }\n\n public IEnumerator<T> GetEnumerator()\n {\n for (int i = 0; i < this.Count; i++)\n {\n yield return this._items[i];\n }\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n => this.GetEnumerator();\n\n private void ValidateIndex(int index)\n {\n if (index < 0 || index >= this.Count)\n {\n throw new IndexOutOfRangeException(nameof(index));\n }\n }\n\n private void GrowIfNecessary()\n {\n if (this.Count == this._items.Length)\n {\n var array = new T[this.Count * 2];\n Array.Copy(this._items, array, this._items.Length);\n\n this._items = array;\n }\n }\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7186739/"
] |
74,619,458
|
<p>Let's say I have a class <code>Bitmap</code> that has a static cache map <code>textures</code> that holds pointers to all images that have been registered.</p>
<pre class="lang-cpp prettyprint-override"><code>class Bitmap {
public:
Bitmap(const std::string &filename);
// ... functionality ...
private:
// ... image data ...
std::string filename;
static std::map<std::string, std::unique_ptr<Bitmap>> images;
}
</code></pre>
<p>Is it possible for the constructor of <code>Bitmap</code> to search the cache for an existing object with the same <code>filename</code> and then return a reference to that?</p>
<p>I've tried something like</p>
<pre class="lang-cpp prettyprint-override"><code>if (images.find(filename) != images.end()) {
*this = images[filename].get();
return;
}
</code></pre>
<p>but that doesn't seem to work. Is there a way at all to achieve this effect using the constructor?</p>
|
[
{
"answer_id": 74619536,
"author": "HolyBlackCat",
"author_id": 2752075,
"author_profile": "https://Stackoverflow.com/users/2752075",
"pm_score": 1,
"selected": false,
"text": "std::shared_ptr Bitmap"
},
{
"answer_id": 74619683,
"author": "paddy",
"author_id": 1553090,
"author_profile": "https://Stackoverflow.com/users/1553090",
"pm_score": 3,
"selected": true,
"text": "class Bitmap {\npublic:\n static Bitmap& Get(const std::string &filename);\n\nprivate:\n Bitmap(const std::string &filename)\n : filename(filename)\n {\n std::cout << \"Construct \" << filename << \"\\n\";\n }\n\n std::string filename;\n static std::map<std::string, std::unique_ptr<Bitmap>> images;\n};\n\nstd::map<std::string, std::unique_ptr<Bitmap>> Bitmap::images;\n\nBitmap& Bitmap::Get(const std::string &filename)\n{\n auto it = images.find(filename);\n if (it == images.end())\n {\n std::unique_ptr<Bitmap> ptr(new Bitmap(filename));\n it = images.insert(std::make_pair(filename, std::move(ptr))).first;\n }\n return *(it->second);\n}\n int main()\n{\n auto a = Bitmap::Get(\"foo\");\n auto b = Bitmap::Get(\"bar\");\n auto c = Bitmap::Get(\"foo\");\n}\n Construct foo\nConstruct bar\n Bitmap BitmapManager"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10640346/"
] |
74,619,494
|
<p>I have a filter applied to a sheet. I want to return just the data from the filter and not the entire range of the sheet.</p>
<pre><code> const sheet = SpreadsheetApp.openById(SHEET_ID).getSheetByName(SHEET_NAME)
const filter = sheet.getFilter();
// This returns the entire sheet's range rather than the filtered range.
const range = filter.getRange().getValues();
</code></pre>
<p>Based on the code above, why aren't I getting the desired behaviour according to <a href="https://developers.google.com/apps-script/reference/spreadsheet/filter#getRange()" rel="nofollow noreferrer">docs</a> from Google?</p>
|
[
{
"answer_id": 74619536,
"author": "HolyBlackCat",
"author_id": 2752075,
"author_profile": "https://Stackoverflow.com/users/2752075",
"pm_score": 1,
"selected": false,
"text": "std::shared_ptr Bitmap"
},
{
"answer_id": 74619683,
"author": "paddy",
"author_id": 1553090,
"author_profile": "https://Stackoverflow.com/users/1553090",
"pm_score": 3,
"selected": true,
"text": "class Bitmap {\npublic:\n static Bitmap& Get(const std::string &filename);\n\nprivate:\n Bitmap(const std::string &filename)\n : filename(filename)\n {\n std::cout << \"Construct \" << filename << \"\\n\";\n }\n\n std::string filename;\n static std::map<std::string, std::unique_ptr<Bitmap>> images;\n};\n\nstd::map<std::string, std::unique_ptr<Bitmap>> Bitmap::images;\n\nBitmap& Bitmap::Get(const std::string &filename)\n{\n auto it = images.find(filename);\n if (it == images.end())\n {\n std::unique_ptr<Bitmap> ptr(new Bitmap(filename));\n it = images.insert(std::make_pair(filename, std::move(ptr))).first;\n }\n return *(it->second);\n}\n int main()\n{\n auto a = Bitmap::Get(\"foo\");\n auto b = Bitmap::Get(\"bar\");\n auto c = Bitmap::Get(\"foo\");\n}\n Construct foo\nConstruct bar\n Bitmap BitmapManager"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20637783/"
] |
74,619,499
|
<p>I've been wanting to make a custom calculator for finding odds in a game but I'm running into a problem with having the denominator printing</p>
<p>`</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<title>Roaming Odds</title>
<meta charset=utf-8>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script type="text/javascript">
var CharmMultiplier=1
var BoostMultiplier=1
function Multiply()
{
var Charm, Boost, RoamingAmount, Denominator, RoamingCalc, CharmMultiplier, BoostMultiplier;
// checking to see if the user has charm or boost
// having the charm halves the chance of finding a roaming (1/1024 becomes 1/512)
switch(Charm) {
case true:
CharmMultiplier = 0.5
break;
case false:
CharmMultiplier = 1
break;
default:
CharmMultiplier = 1
}
// having the boost decreases the chance by 4 (1/1024 becomes 1/256)
// having both the boost and chance is supposed to make the odds go from 1/1024 to 1/128 (decreased by 8x)
switch(Boost) {
case true:
BoostMultiplier = 0.25
break;
case false:
BoostMultiplier = 1
break;
default:
BoostMultiplier = 1
}
Result = 1024*CharmMultiplier*BoostMultiplier/RoamingAmount;
document.RoamingCalc.Denominator.value=Result;
}
</script>
<form name="RoamingCalc">
<!-- all the factors to account for when calculating odds-->
<label for="RoamingName">Roaming (optional):</label>
<input type="text" id="RoamingName" name="RoamingName">
<label for="Charm">Charm</label>
<input type="checkbox" id="Charm">
<label for="Boost">Boost</label>
<input type="checkbox" id="Boost">
<label for="RoamingAmount">Amount of Roamings Unlocked: </label>
<input type="number" id="RoamingAmount" name="RoamingAmount">
<label for="Denominator">Result: 1 in </label>
<input type="number" id="Denominator" name="Denominator"><br>
<input type="button" value="Calculate" onclick="Multiply()">
</form>
</body>
</html>
</code></pre>
<p>`</p>
<p>The error I keep on getting is: The specified value "NaN" cannot be parsed, or is out of range.
Multiply @ RoamingOdds.html:43
onclick @ RoamingOdds.html:66</p>
<p>I've tried rewriting line 43 since thats what keeps on highlighting but Im new to Javascript so Im probably doing a terrible job at it</p>
<p>Edit 3/12: code now works with help from you guys + changes</p>
<pre><code><html lang="en">
<head>
<title>Roaming Odds</title>
<meta charset=utf-8>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script type="text/javascript">
var CharmMultiplier=1
var BoostMultiplier=1
function Multiply()
{
var Charm, Boost, RoamingAmount, Denominator, RoamingCalc, CharmMultiplier, BoostMultiplier;
// checking to see if the user has charm or boost
// having the charm halves the chance of finding a roaming (1/1024 becomes 1/512)
if (document.getElementById("CharmID").checked){
CharmMultiplier = 0.5 ;
}else{
CharmMultiplier = 1 ;
}
// having the boost decreases the chance by 4 (1/1024 becomes 1/256)
// having both the boost and chance is supposed to make the odds go from 1/1024 to 1/128 (decreased by 8x)
if (document.getElementById("BoostID").checked){
BoostMultiplier = 0.25 ;
}else{
BoostMultiplier = 1 ;
}
if (document.getElementById("RoamingNameID"))
RoamingAmount = Number(document.getElementById("RoamingAmountID").value) || 1;
Result = 1024*BoostMultiplier*CharmMultiplier*RoamingAmount
document.RoamingCalc.Denominator.value=Result;
}
</script>
<form name="RoamingCalc">
<!-- all the factors to account for when calculating odds-->
<label for="RoamingNameID">Roaming (optional):</label>
<input type="text" id="RoamingNameID" name="RoamingName">
<label for="CharmID">Charm</label>
<input type="checkbox" id="CharmID" name="Charm">
<label for="BoostID">Boost</label>
<input type="checkbox" id="BoostID" name="Boost">
<label for="RoamingAmountID">Amount of Roamings Unlocked: </label>
<input type="number" id="RoamingAmountID" name="RoamingAmount">
<label for="DenominatorID">Result: 1 in </label>
<input type="number" id="DenominatorID" name="Denominator"><br>
<input type="button" value="Calculate" onclick="Multiply()">
</form>
</body>
</html>```
</code></pre>
|
[
{
"answer_id": 74619536,
"author": "HolyBlackCat",
"author_id": 2752075,
"author_profile": "https://Stackoverflow.com/users/2752075",
"pm_score": 1,
"selected": false,
"text": "std::shared_ptr Bitmap"
},
{
"answer_id": 74619683,
"author": "paddy",
"author_id": 1553090,
"author_profile": "https://Stackoverflow.com/users/1553090",
"pm_score": 3,
"selected": true,
"text": "class Bitmap {\npublic:\n static Bitmap& Get(const std::string &filename);\n\nprivate:\n Bitmap(const std::string &filename)\n : filename(filename)\n {\n std::cout << \"Construct \" << filename << \"\\n\";\n }\n\n std::string filename;\n static std::map<std::string, std::unique_ptr<Bitmap>> images;\n};\n\nstd::map<std::string, std::unique_ptr<Bitmap>> Bitmap::images;\n\nBitmap& Bitmap::Get(const std::string &filename)\n{\n auto it = images.find(filename);\n if (it == images.end())\n {\n std::unique_ptr<Bitmap> ptr(new Bitmap(filename));\n it = images.insert(std::make_pair(filename, std::move(ptr))).first;\n }\n return *(it->second);\n}\n int main()\n{\n auto a = Bitmap::Get(\"foo\");\n auto b = Bitmap::Get(\"bar\");\n auto c = Bitmap::Get(\"foo\");\n}\n Construct foo\nConstruct bar\n Bitmap BitmapManager"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20575774/"
] |
74,619,500
|
<p>How can I calculate the average value of the properties of an object?</p>
<p>I have this object:</p>
<pre class="lang-js prettyprint-override"><code>let components = {
co: [235, 465, 78],
no: [409, 589, 98],
nh3: [54, 76, 39]
};
</code></pre>
<p>I need to separately calculate the average for <code>co</code>, <code>no</code>, and <code>nh3</code>.</p>
|
[
{
"answer_id": 74619682,
"author": "mplungjan",
"author_id": 295783,
"author_profile": "https://Stackoverflow.com/users/295783",
"pm_score": 0,
"selected": false,
"text": "... const components = {\n \"co\": [235, 465, 78],\n \"no\": [409, 589, 98],\n \"nh3\": [54, 76, 39]\n}\n\nconst avgs = Object\n .assign({}, \n ...Object.entries(components)\n .map(([key,values]) => \n ({[key]: +(values\n .reduce((a,b)=>a+b)/values.length)\n .toFixed(2)})\n )\n );\nconsole.log(avgs)"
},
{
"answer_id": 74619793,
"author": "Dream Bold",
"author_id": 12743692,
"author_profile": "https://Stackoverflow.com/users/12743692",
"pm_score": 0,
"selected": false,
"text": "object let components = {\n co: [235, 465, 78],\n no: [409, 589, 98],\n nh3: [54, 76, 39]\n};\n\nlet result = [];\nObject.keys(components).forEach(function (key) {\n avg = components[key].reduce((a, b) => a + b, 0) / components[key].length;\n result.push(avg);\n});\n\nconsole.log(result);"
},
{
"answer_id": 74619814,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 1,
"selected": false,
"text": "const\n getAverage = array => array.reduce((a, b) => a + b) / array.length,\n components = { co: [235, 465, 78], no: [409, 589, 98], nh3: [54, 76, 39] },\n result = Object.fromEntries(Object\n .entries(components)\n .map(([k, v]) => [k, getAverage(v)])\n );\n \nconsole.log(result);"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20624416/"
] |
74,619,517
|
<p>There are probably multiple ways to do this or frame this question</p>
<p>I have two tables I would like to join.</p>
<p>Table A</p>
<pre><code>ID Column1A Column2A
56ade9.mobile.app. 1A_data 2A_data
ko9j77:web.source. 1A_data 2A_data
9eej:mobile.app. 1A_data 2A_data
pdfg6334df.web.source 1A_data 2A_data
gyu8ssl 1A_data 2A_data
</code></pre>
<p>Table B</p>
<pre><code>ID Column1B Column2B
9eej 1B_data 2B_data
56ade9 1B_data 2B_data
gyu8ssl 1B_data 2B_data
pdfg6334df 1B_data 2B_data
ko9j77 1B_data 2B_data
</code></pre>
<p>And I'd like to join on the ID columns for a result of: (the row order doesn't matter)</p>
<pre><code>ID Column1A Column2A Column1B Column2B
9eej
56ade9
pdfg633df
gyu8ssl
ko9j77
</code></pre>
<p>However the ID column in table A has additional, superfluous string characters which are delimitated by either a <code>.</code> or a <code>:</code>.</p>
<p>Some IDs in Table A will not have the superfluous strings added to the ID, such as the last row in Table A with ID <code>gyu8ssl</code></p>
<p>The superfluous string sequence after the actual id in Table A is not consistent, and can be more than the examples I listed.</p>
<p>The actual id is not uniform in character length; however the first break in the alpha numeric sequence with a punctuation indicates the end of the actual ID which should be joined on.</p>
<p>Attempt:</p>
<p>I'm a bit stumped on how to approach this. I was looking at <code>STRING_SPLIT</code> but it seems to only take in one delimiter at a time and I don't think that will get me what I want. I'm actually kind of stymied.</p>
<p>Any suggestions?</p>
|
[
{
"answer_id": 74619653,
"author": "dougp",
"author_id": 9937026,
"author_profile": "https://Stackoverflow.com/users/9937026",
"pm_score": 3,
"selected": true,
"text": "select b.ID\n, a.ColumnA1\n, a.ColumnA1\n, b.ColumnB1\n, b.ColumnB2\nfrom TableB b\n inner join TableA a\n on case \n when replace(a.ID, ':', '.') like '%.%'\n then substring(a.ID, charindex('.', replace(a.ID, ':', '.')))\n else a.ID\n end = b.ID\n"
},
{
"answer_id": 74619733,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "SELECT ID ON SELECT PERSISTED"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9840684/"
] |
74,619,524
|
<p>I am struggling with what is hopefully a simple problem. Haven't been able to find a clear cut answer online.</p>
<p>The program given, asks for a user input (n) and then produces an n-sized square matrix. The matrix will only be made of 0s and 1s. I am attempting to count the arrays (I have called this x) that contain a number, or those that do not only contain only 0s.</p>
<p>Example output:</p>
<pre><code>n = 3
[0, 0, 0] [1, 0, 0] [0, 1, 0]
In this case, x should = 2.
n = 4
[0, 0, 0, 0] [1, 0, 0, 0] [0, 1, 0, 0] [0, 0, 0, 0]
In this case, x should also be 2.
</code></pre>
<pre><code>def xArrayCount(MX):
x = 0
count = 0
for i in MX:
if i in MX[0 + count] == 0:
x += 0
count += 1
else:
x += 1
count += 1
return(x)
</code></pre>
<p>Trying to count the number of 0s/1s in each index of the matrix but I am going wrong somewhere, could someone explain how this should work?</p>
<p>(Use of extra python modules is disallowed)</p>
<p>Thank you</p>
|
[
{
"answer_id": 74619739,
"author": "thicchead",
"author_id": 19815385,
"author_profile": "https://Stackoverflow.com/users/19815385",
"pm_score": 0,
"selected": false,
"text": "def xArrayCount(MX):\n x = 0\n count = 0\n\n for i in matrix:\n if MX[count][count] == 0:\n count += 1\n else:\n x += 1\n count += 1\n\n return x\n"
},
{
"answer_id": 74619766,
"author": "Nimrod Shanny",
"author_id": 20631164,
"author_profile": "https://Stackoverflow.com/users/20631164",
"pm_score": 4,
"selected": true,
"text": "def count_none_zero_items(matrix):\n count = 0\n for row in matrix:\n if 1 in row:\n count += 1\n return count\n\n\nx = [[0, 0, 0, 0], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0]]\ncount_none_zero_items(x)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20555664/"
] |
74,619,549
|
<p>I am planning a .NET application that will be used in different countries. This application contains a web API and a single page front end. The application will also use a database table with a datetime column. The values in the table will be for the UTC timezone.</p>
<p>I am confused about handling these values. My users may be in any country. Where can I convert the local time to UTC time? Database data goes via an API to the front end application. User data comes from a single page application to the database via web API.</p>
|
[
{
"answer_id": 74620366,
"author": "Matt Johnson-Pint",
"author_id": 634824,
"author_profile": "https://Stackoverflow.com/users/634824",
"pm_score": 2,
"selected": false,
"text": "{\n \"id\": 123\n \"timestamp\": \"2022-12-31T23:59:59.9999999Z\"\n}\n timestamp Z new Date(timestamp).toString()\n toLocaleString TimeZoneInfo Intl"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/694716/"
] |
74,619,577
|
<p>I have written a program that extracts data from an SQL table:</p>
<pre><code>String url = "jdbc:mysql://localhost/petcare";
String password = "ParkSideRoad161997";
String username = "root";
// Step 2: Making connection using
// Connection type and inbuilt function on
// Connection con = null;
PreparedStatement p = null;
ResultSet rs = null;
// Try block to catch exception/s
try {
Connection con = DriverManager.getConnection(url, username, password);
// SQL command data stored in String datatype
String sql = "select * from inbox";
p = con.prepareStatement(sql);
rs = p.executeQuery();
// Printing ID, name, email of customers
// of the SQL command above
System.out.println("inboxId");
int inboxId;
// Condition check
while (rs.next()) {
inboxId = rs.getInt("InboxId");
// System.out.println(inboxId);
}
String sql2 = "select * from message where inboxId = int";//this is where i need help
p = con.prepareStatement(sql2);
rs = p.executeQuery();
// Printing ID, name, email of customers
// of the SQL command above
System.out.println("Inbox:");
}
// Catch block to handle exception
catch (SQLException e) {
// Print exception pop-up on screen
System.out.println(e);
}
</code></pre>
<p>Once I get the inboxId, I want to run sql2 and pass inboxId as int. How can I do this. Each user will have a different inboxId so thats why to get the user inbox I want to extract and messages in the message table that are meant for inboxId of the user.</p>
<p>I tried the query string sql and it works now I just need to fix String sql2.</p>
|
[
{
"answer_id": 74620366,
"author": "Matt Johnson-Pint",
"author_id": 634824,
"author_profile": "https://Stackoverflow.com/users/634824",
"pm_score": 2,
"selected": false,
"text": "{\n \"id\": 123\n \"timestamp\": \"2022-12-31T23:59:59.9999999Z\"\n}\n timestamp Z new Date(timestamp).toString()\n toLocaleString TimeZoneInfo Intl"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20286317/"
] |
74,619,586
|
<p>I have an eventEmitter that I'm using to show a Child Component and also pass information. I have a parent class that contains uses two components, and , and the parent class will take the value from 's eventemitter and use that as a sign to show and pass in information. Unfortunately, the method to update the boolean is not working in the parent class.</p>
<p>This is the parent component</p>
<pre><code>@Component({
selector: 'parent',
template: '
<search-box (emitter)="(setBoolean($event))"></search-box>
<table-component *ngIf="tableBoolean"></table-component>
',
})
@Injectable({
providedIn: 'root',
})
export class SearchComponent implements OnInit {
tableBoolean = false;
constructor() {
}
setBoolean(valueEmitted: any){
this.tableBoolean = true;
console.log(this.tableBoolean)
console.log(valueEmitted)
}
ngOnInit(): void {
}
}
</code></pre>
<p>This is the searchbox component</p>
<pre><code>@Component({
selector: 'search-box',
templateUrl: './search-box.component.html',
styleUrls: ['./search-box.component.css']
})
export class SearchBoxComponent implements OnInit {
@Output() emitter = new EventEmitter<string>();
constructor(private _renderer2: Renderer2,
@Inject(DOCUMENT) private _document: Document) {
}
emit(){
this.emitter.emit("TEST");
}
ngOnInit(): void {
let script = this._renderer2.createElement('script');
script.src = urls.prod;
this._renderer2.appendChild(this._document.body, script);
}
}
</code></pre>
<p>and table component is just a table, why is my eventEmitter not working? I have that the emit() function runs when I click the button, but the method setBoolean() is not running.</p>
|
[
{
"answer_id": 74620366,
"author": "Matt Johnson-Pint",
"author_id": 634824,
"author_profile": "https://Stackoverflow.com/users/634824",
"pm_score": 2,
"selected": false,
"text": "{\n \"id\": 123\n \"timestamp\": \"2022-12-31T23:59:59.9999999Z\"\n}\n timestamp Z new Date(timestamp).toString()\n toLocaleString TimeZoneInfo Intl"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11489736/"
] |
74,619,587
|
<p>I have been wondering how is it possible to scrap Wikipedia information. For example, I have a list of world cities and want to obtain their approximate latitude and longitude. Take Miami as an example. When I type <code>curl https://en.wikipedia.org/wiki/Miami | grep -E '(latitude|longitude)'</code>, somewhere in the HTML there will be a tag mark like below.</p>
<p><code><span class="latitude">25°46′31″N</span> <span class="longitude">80°12′31″W</span></code></p>
<p>I know I can extract it with some regex string, but I speak a very poor regexish. Can some of you help me on this?</p>
|
[
{
"answer_id": 74620366,
"author": "Matt Johnson-Pint",
"author_id": 634824,
"author_profile": "https://Stackoverflow.com/users/634824",
"pm_score": 2,
"selected": false,
"text": "{\n \"id\": 123\n \"timestamp\": \"2022-12-31T23:59:59.9999999Z\"\n}\n timestamp Z new Date(timestamp).toString()\n toLocaleString TimeZoneInfo Intl"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16251726/"
] |
74,619,610
|
<p>Below code converts all values text to number except values with prefix 0 I.E. 002A.
Problem: This code works great on small data files but crashes excel on every large file even though I turn off calculation before code runs.
Please suggest a method which I can use?</p>
<pre><code>Sub Text2Number()
On Error GoTo EH
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
Set Rng = ActiveSheet.UsedRange
Rng.Cells(1, 1).Select
For i = 1 To Rng.Rows.Count
For j = 1 To Rng.Columns.Count
If Rng.Cells(i, j) <> "" Then
Union(Selection, Rng.Cells(i, j)).Select
End If
Next j
Next i
For Each c In Rng.Cells
If IsNumeric(c.Value) And Left$(c.Value, 1) <> "0" Then
c.NumberFormat = "General"
c.Value = c.Value
End If
Next
Rng.HorizontalAlignment = xlLeft
CleanUp:
On Error Resume Next
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
Exit Sub
EH:
' Do error handling
Resume CleanUp
End Sub
</code></pre>
|
[
{
"answer_id": 74626762,
"author": "usmanhaq",
"author_id": 10498111,
"author_profile": "https://Stackoverflow.com/users/10498111",
"pm_score": 1,
"selected": false,
"text": "Sub Text2Number_v2()\n\nApplication.Calculation = xlCalculationManual\nlast_col = ActiveSheet.UsedRange.Columns.Count\n\nFor col = 1 To last_col\n\n Columns(col).TextToColumns Destination:=Cells(1, col), DataType:=xlDelimited, _\n TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _\n Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _\n :=Array(1, 1), TrailingMinusNumbers:=True\n \nNext\n\nApplication.Calculation = xlCalculationAutomatic\n\nEnd Sub\n"
},
{
"answer_id": 74659464,
"author": "Alvi",
"author_id": 10442755,
"author_profile": "https://Stackoverflow.com/users/10442755",
"pm_score": 1,
"selected": true,
"text": "Sub Text2Number()\n On Error GoTo EH\n\n Application.ScreenUpdating = False\n Application.Calculation = xlCalculationManual\n Application.EnableEvents = False\n\nDim Rng As Range\n\nSet Rng = Application.Selection\nSet Rng = Application.InputBox(\"Range\", xTitleId, Rng.Address, Type:=8)\n\nFor Each c In Rng.Cells\n If IsNumeric(c.Value) And Left$(c.Value, 1) <> \"0\" Then\n c.NumberFormat = \"General\"\n c.Value = c.Value\n End If\nNext\nRng.HorizontalAlignment = xlLeft\nCleanUp:\n On Error Resume Next\n Application.ScreenUpdating = True\n Application.Calculation = xlCalculationAutomatic\n Application.EnableEvents = True\nExit Sub\nEH:\n ' Do error handling\n Resume CleanUp\nEnd Sub\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10442755/"
] |
74,619,615
|
<p>I have a Flask web application running as a Docker image that is deployed to a Kubernetes pod running on GKE. There are a few environment variables necessary for the application which are included in the docker-compose.yaml like so:</p>
<pre class="lang-yaml prettyprint-override"><code>...
services:
my-app:
build:
...
environment:
VAR_1: foo
VAR_2: bar
...
</code></pre>
<p>I want to keep these environment variables in the <code>docker-compose.yaml</code> so I can run the application locally if necessary. However, when I go to deploy this using a Kubernetes deployment, these variables are missing from the pod and it throws an error. The only way I have found to resolve this is to add the following to my <code>deployment.yaml</code>:</p>
<pre class="lang-yaml prettyprint-override"><code>containers:
- name: my-app
...
env:
- name: VAR_1
value: foo
- name: VAR_2
value: bar
...
</code></pre>
<p>Is there a way to migrate the values of these environment variables directly from the Docker container image into the Kubernetes pod?</p>
<p>I have tried researching this in Kubernetes and Docker documentation and Google searching and the only solutions I can find say to just include the environment variables in the <code>deployment.yaml</code>, but I'd like to retain them in the <code>docker-compose.yaml</code> for the purposes of running the container locally. I couldn't find anything that explained how Docker container environment variables and Kubernetes environment variables interacted.</p>
|
[
{
"answer_id": 74620335,
"author": "David Maze",
"author_id": 10008173,
"author_profile": "https://Stackoverflow.com/users/10008173",
"pm_score": 0,
"selected": false,
"text": "docker-compose.yml docker-compose ENV VAR_1=foo\nENV VAR_2=bar\n# and don't mention either variable in either Compose or Kubernetes config\n"
},
{
"answer_id": 74620404,
"author": "Mohammad omar",
"author_id": 12397662,
"author_profile": "https://Stackoverflow.com/users/12397662",
"pm_score": 1,
"selected": true,
"text": "FROM alpine:latest\n\n# this is how you hardcode it\nENV VAR_1 foo\n\nCOPY helloworld.sh .\n\nRUN chmod +x /helloworld.sh\n\nCMD [\"/helloworld.sh\"]\n app1:\n image: ACRHOST/app1:latest\n env_file:\n - .env\n kubectl create configmap <map-name> <data-source>\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20637746/"
] |
74,619,620
|
<p>I have a data frame that looks like this:</p>
<pre><code> x
A B
0 0 1
1 2 3
2 4 5
3 6 7
4 8 9
</code></pre>
<p>When I want to add another level to the multi-level columns using the following code</p>
<pre><code>x.columns = pd.MultiIndex.from_product([['D'], x.columns])
</code></pre>
<p>it gives me the following error</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\adel.moustafa\DashBoard\main.py", line 262, in <module>
calculate_yield()
File "C:\Users\adel.moustafa\DashBoard\main.py", line 204, in calculate_yield
Analyzer.yield_analyzer_by(yield_data, all_data_df, df_info['P/F Criteria'], 'batch')
File "C:\Users\adel.moustafa\DashBoard\Modules\Analyzer.py", line 163, in yield_analyzer_by
x.columns = pd.MultiIndex.from_product([['D'], x.columns])
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\multi.py", line 621, in from_product
codes, levels = factorize_from_iterables(iterables)
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\arrays\categorical.py", line 2881, in factorize_from_iterables
codes, categories = zip(*(factorize_from_iterable(it) for it in iterables))
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\arrays\categorical.py", line 2881, in <genexpr>
codes, categories = zip(*(factorize_from_iterable(it) for it in iterables))
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\arrays\categorical.py", line 2854, in factorize_from_iterable
cat = Categorical(values, ordered=False)
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\arrays\categorical.py", line 451, in __init__
dtype = CategoricalDtype(categories, dtype.ordered)
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\dtypes\dtypes.py", line 183, in __init__
self._finalize(categories, ordered, fastpath=False)
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\dtypes\dtypes.py", line 337, in _finalize
categories = self.validate_categories(categories, fastpath=fastpath)
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\dtypes\dtypes.py", line 530, in validate_categories
if categories.hasnans:
File "pandas\_libs\properties.pyx", line 37, in pandas._libs.properties.CachedProperty.__get__
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 2681, in hasnans
return bool(self._isnan.any())
File "pandas\_libs\properties.pyx", line 37, in pandas._libs.properties.CachedProperty.__get__
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 2666, in _isnan
return isna(self)
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\dtypes\missing.py", line 144, in isna
return _isna(obj)
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\dtypes\missing.py", line 169, in _isna
raise NotImplementedError("isna is not defined for MultiIndex")
NotImplementedError: isna is not defined for MultiIndex
</code></pre>
<p>I have checked that there is no Na values in my column nor its values, I have also looked at this <a href="https://stackoverflow.com/questions/66320329/add-multi-level-column-to-dataframe">post</a> and <a href="https://fixexception.com/pandas/isna-is-not-defined-for-multiindex/" rel="nofollow noreferrer">this post</a> and finally <a href="https://stackoverflow.com/questions/68041624/seaborn-barplot-isna-is-not-defined-for-multiindex">this</a> but with no results</p>
<p>here is reproducible code</p>
<pre><code>import pandas as pd
import numpy as np
x = pd.DataFrame(np.arange(10).reshape(5, 2), columns=pd.MultiIndex.from_product([['x'], ['A', 'B']]))
x.columns = pd.MultiIndex.from_product([['D'], x.columns])
</code></pre>
<p>can any one point to what is wrong and how fix it?</p>
|
[
{
"answer_id": 74619824,
"author": "SomeDude",
"author_id": 1410303,
"author_profile": "https://Stackoverflow.com/users/1410303",
"pm_score": 3,
"selected": true,
"text": " x.columns = pd.MultiIndex.from_product([['D'], *x.columns.levels])\n x.columns.levels * from_product"
},
{
"answer_id": 74620026,
"author": "Pierre D",
"author_id": 758174,
"author_profile": "https://Stackoverflow.com/users/758174",
"pm_score": 0,
"selected": false,
"text": "x[('y', 'C')] = x[('x', 'A')] + 1\nx[('x', 'D')] = 0\n\n>>> x\n x y x\n A B C D\n0 0 1 1 0\n1 2 3 3 0\n2 4 5 5 0\n3 6 7 7 0\n4 8 9 9 0\n x = x.sort_index(axis=1)\n\n>>> x\n x y\n A B D C\n0 0 1 0 1\n1 2 3 0 3\n2 4 5 0 5\n3 6 7 0 7\n4 8 9 0 9\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12260015/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.