qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,635,857
|
<p>I have a mutable structure in Julia</p>
<pre><code>@with_kw mutable struct Param
x::Float64 = 0.1
y::Float64 = 1/x
end
</code></pre>
<p>Now I want to change x to 0.2, so I set
<code>para = Param()</code> and <code>para.x = 0.2</code>. However, <code>para.y</code> does not change. But what I want is to change y automatically, is there any way in Julia to do this?</p>
|
[
{
"answer_id": 74636489,
"author": "vchuravy",
"author_id": 1237861,
"author_profile": "https://Stackoverflow.com/users/1237861",
"pm_score": 1,
"selected": false,
"text": "y y(p::Param) = 1/p.x\n"
},
{
"answer_id": 74656926,
"author": "Shayan",
"author_id": 11747148,
"author_profile": "https://Stackoverflow.com/users/11747148",
"pm_score": 3,
"selected": true,
"text": "getproperty julia> Base.@kwdef mutable struct Param\n x::Float64=0.1\n end\nParam\n getproperty Param julia> function Base.getproperty(the_type::Param, prop::Symbol)\n if prop == :y\n return 1/the_type.x\n end\n return getfield(the_type, prop)\n end\n Param julia> instance = Param()\nParam(0.1)\n x y getproperty julia> instance.y\n10.0\n x y julia> instance.x = 0.2\n0.2\n\njulia> instance.y\n5.0\n instance.y propertynames Param julia> Base.propertynames(the_type::Param) = (:x, :y)\n\njulia> instance. #Hit Tab\nx y\n y"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74635857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16844272/"
] |
74,635,865
|
<p>Live server do not load @media from css file with link tag.</p>
<p><a href="https://i.stack.imgur.com/1DqAP.png" rel="nofollow noreferrer">LINK</a></p>
<pre><code><head>
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<link rel="stylesheet" href="https://rohh.ru/API/style/module.css" type="text/css"/>
<link rel="stylesheet" href="https://rohh.ru/API/style/void.css" type="text/css"/>
</head>
</code></pre>
<p><a href="https://i.stack.imgur.com/l1X0p.png" rel="nofollow noreferrer">Module API code</a></p>
<pre><code>@media screen and (max-width:100vh) {
.for-desktop{display: none !important;}
.for-mobile{display: flex;}
}
@media screen and (max-height:100vw) {
.for-mobile{display: none !important;}
.for-desktop{display: flex;}
}
</code></pre>
<p>The general problem is:</p>
<p>I have two types of menus. One for mobile, another for desktop. It is <strong>not working on server only</strong>.</p>
<pre><code><menu class="for-mobile">
<menu class="for-desktop">
</code></pre>
<p><a href="https://i.stack.imgur.com/MxMk7.png" rel="nofollow noreferrer">STATIC LOCAL</a>
<a href="https://i.stack.imgur.com/b9xXV.png" rel="nofollow noreferrer">DYNAMIC LOCAL</a></p>
<p>I do not know even how to Google this issue. Also, help in comments properly retitle this problem.</p>
<ol>
<li>I was trying to make proper formatting:</li>
</ol>
<pre><code>type="text/css"/
</code></pre>
<ol start="2">
<li>Change orientation landscape to max-width 100vh ...</li>
</ol>
<pre><code>(orientation: landscape)
(max-width:100vh)
</code></pre>
<ol start="3">
<li>Load it to the proper server with WP or Apache.</li>
<li>Open in another browser and clear cache</li>
</ol>
|
[
{
"answer_id": 74636489,
"author": "vchuravy",
"author_id": 1237861,
"author_profile": "https://Stackoverflow.com/users/1237861",
"pm_score": 1,
"selected": false,
"text": "y y(p::Param) = 1/p.x\n"
},
{
"answer_id": 74656926,
"author": "Shayan",
"author_id": 11747148,
"author_profile": "https://Stackoverflow.com/users/11747148",
"pm_score": 3,
"selected": true,
"text": "getproperty julia> Base.@kwdef mutable struct Param\n x::Float64=0.1\n end\nParam\n getproperty Param julia> function Base.getproperty(the_type::Param, prop::Symbol)\n if prop == :y\n return 1/the_type.x\n end\n return getfield(the_type, prop)\n end\n Param julia> instance = Param()\nParam(0.1)\n x y getproperty julia> instance.y\n10.0\n x y julia> instance.x = 0.2\n0.2\n\njulia> instance.y\n5.0\n instance.y propertynames Param julia> Base.propertynames(the_type::Param) = (:x, :y)\n\njulia> instance. #Hit Tab\nx y\n y"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74635865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16119399/"
] |
74,635,878
|
<p>For example:</p>
<p><code>class DogOwners(object): def get_this_animal(id, dog_name): return Dog(id=id, name=dog_name)</code></p>
<p>Would this return a new object or the existing one associated to the *args of get_this_animal()?</p>
<p>It returns the data I want but I can't tell if now I have two dogs with the same data</p>
|
[
{
"answer_id": 74636489,
"author": "vchuravy",
"author_id": 1237861,
"author_profile": "https://Stackoverflow.com/users/1237861",
"pm_score": 1,
"selected": false,
"text": "y y(p::Param) = 1/p.x\n"
},
{
"answer_id": 74656926,
"author": "Shayan",
"author_id": 11747148,
"author_profile": "https://Stackoverflow.com/users/11747148",
"pm_score": 3,
"selected": true,
"text": "getproperty julia> Base.@kwdef mutable struct Param\n x::Float64=0.1\n end\nParam\n getproperty Param julia> function Base.getproperty(the_type::Param, prop::Symbol)\n if prop == :y\n return 1/the_type.x\n end\n return getfield(the_type, prop)\n end\n Param julia> instance = Param()\nParam(0.1)\n x y getproperty julia> instance.y\n10.0\n x y julia> instance.x = 0.2\n0.2\n\njulia> instance.y\n5.0\n instance.y propertynames Param julia> Base.propertynames(the_type::Param) = (:x, :y)\n\njulia> instance. #Hit Tab\nx y\n y"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74635878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20651050/"
] |
74,635,903
|
<p>I have the following code:</p>
<pre><code> $SchoolFolder = "C:\Users\MyUser\Desktop\School Folder\$StudentName\$Month. $MonthWrite\$Day. $DayWrite"
$MP4Lenght = (Get-ChildItem -Path $RenderFolder).Length -ne "0"
$MP4existsToCopy = Test-Path -Path "$RenderFolder\*.mp4"
If (($MP4existsToCopy -eq $True) -and ($MP4Lenght -eq $True)) {
Get-ChildItem $MyFolder |
Where-Object { $_.Length -gt 0KB} |
Move-Item -Destination (new-item -type directory -force ($SchoolFolder + $newSub)) -force -ea 0
Write-Host "Done!"
}
</code></pre>
<p>I would like to know how do I make all correspondence in <code>$MP4Lenght</code> be printed in the console with the format <code>$MP4Lenght + "was moved"</code>, because that way I can know which files were moved.</p>
|
[
{
"answer_id": 74637440,
"author": "postanote",
"author_id": 9132707,
"author_profile": "https://Stackoverflow.com/users/9132707",
"pm_score": 1,
"selected": false,
"text": "-verbose Move-Item -Destination (new-item -type directory -force ($SchoolFolder + $newSub)) -force -ea 0 -Verbose\n $source = 'C:\\Users\\myuser\\playground\\powershell\\Source\\'\n$destination = 'C:\\Users\\myuser\\playground\\powershell\\Destination'\n\nGet-ChildItem $source -File | \nwhere-object {$PSItem.Length -ne 0} | \nForEach-Object{\n Move-Item $PSItem.FullName -Destination '.\\Destination'\n\n if (-not(Test-Path $PSItem.FullName) -and (test-path (Join-Path -Path $destination -ChildPath $PSItem.Name))) {\n \"$($PSItem.name) has moved\"\n }\n}\n"
},
{
"answer_id": 74649168,
"author": "Tim Aitken",
"author_id": 179988,
"author_profile": "https://Stackoverflow.com/users/179988",
"pm_score": 2,
"selected": true,
"text": "$source = 'C:\\Users\\myuser\\playground\\powershell\\Source\\'\n$destination = 'C:\\Users\\myuser\\playground\\powershell\\Destination'\n$files = Get-ChildItem $source -File | where-object {$_.Length -ne 0}\n\nforeach ($file in $files) {\n\nMove-Item $file.FullName -Destination .\\Destination\n\nif (-not(Test-Path $file.FullName) -and (test-path (Join-Path -Path $destination -ChildPath $file.Name))) {\n Write-Host \"$($file.name) has moved\"\n}\n"
},
{
"answer_id": 74656700,
"author": "Tyrone Hirt",
"author_id": 19538465,
"author_profile": "https://Stackoverflow.com/users/19538465",
"pm_score": 0,
"selected": false,
"text": " $StudentName = Tyler\n $RenderFolder = \"C:\\Users\\MyUser\\Desktop\\Render\"\n $MP4existsToCopy = Get-ChildItem $RenderFolder -File | where-object {$_.Length -ne 0}\n $SchoolFolder = \"C:\\Users\\MyUser\\Desktop\\School Folder\\$StudentName\\$Month. $MonthWrite\\$Day. $DayWrite\"\n \n foreach ($file in $MP4existsToCopy) {\n \n Move-Item $file.FullName -Destination (new-item -type directory -force ($SchoolFolder)) # new-item - Serves to create the folder if it does not exist\n \n if (-not(Test-Path $file.FullName) -and (test-path (Join-Path -Path $SchoolFolder -ChildPath $file.Name))) {\n Write-Host \"$($file.name) was moved!\"\n }\n\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74635903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19538465/"
] |
74,635,930
|
<p>If I have 4 booleans e.g</p>
<p><code>if ((a(x) == True) and (b(x) == True) and (c(x) == True) and (d(x) == True)</code></p>
<p>then I want to do something different for each combination including when only 3 of them are true (including which ones), 2..., then only each 1... etc...</p>
<p>Is there a quicker way than writing a bunch of elifs?</p>
<p>Possibly using a loop</p>
|
[
{
"answer_id": 74635988,
"author": "chrslg",
"author_id": 20037042,
"author_profile": "https://Stackoverflow.com/users/20037042",
"pm_score": 0,
"selected": false,
"text": "numTrue = (a(x) == True) + (b(x) == True) + (c(x) == True) + (d(x) == True)\nif numTrue==4:\n # foo\nelif numTrue==3:\n # bar\nelif numTrue==2:\n # ...\nelif numTrue==1:\n #...\nelse:\n # ...\n x==True x a(x) True False"
},
{
"answer_id": 74636024,
"author": "Peter Wood",
"author_id": 1084416,
"author_profile": "https://Stackoverflow.com/users/1084416",
"pm_score": 2,
"selected": false,
"text": "dict lookup = {(True, True, True, True): func_1,\n (True, True, True, False): func_2,\n (True, True, False, True): func_3,\n ... etc.\n }\nfunc = lookup[a(x), b(x), c(x), d(x)]\nfunc()\n"
},
{
"answer_id": 74636034,
"author": "J_H",
"author_id": 8431111,
"author_profile": "https://Stackoverflow.com/users/8431111",
"pm_score": 0,
"selected": false,
"text": "vals = a(x), b(x), c(x), d(x)\nnum_true = sum(map(bool, vals))\n 2 ** 4 == 16 dict d k = \" \".join(map(str, map(int, map(bool, vals))))\nprint(d[k])\n k = \" \".join(sorted(map(str, map(int, map(bool, vals)))))\n"
},
{
"answer_id": 74636042,
"author": "Sriram M.",
"author_id": 19073682,
"author_profile": "https://Stackoverflow.com/users/19073682",
"pm_score": 1,
"selected": true,
"text": "if (a(x)):\n if(b(x):\n if(c(x)):\n if(d(x)):\n #do x\n else:\n #do y\n else:\n if (d(x)):\n #do z\n else:\n #do w\n #...\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74635930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20594886/"
] |
74,635,931
|
<p>I am trying to convert simple DynamoDB Object string:</p>
<pre class="lang-json prettyprint-override"><code>{
"Item": {
"Id": {
"S": "db31"
},
"CreateTime": {
"N": "1647882237618915000"
}
}
</code></pre>
<p>to either <code>dynamodb.AttributeValue</code> and then map to a go object (go type structure) or convert to a simple JSON go object.</p>
<p>I think, there are similar answers (<a href="https://stackoverflow.com/questions/51333945/converting-dynamodb-json-document-to-json-object-in-java">1</a>, <a href="https://stackoverflow.com/questions/60510274/how-to-convert-between-json-and-mapstring-attributevalue-in">2</a>, <a href="https://stackoverflow.com/questions/49163647/convert-dynamodb-special-json-text-to-normal-json">3</a>) in Java, but I didn't find a similar implementation in Golang.</p>
|
[
{
"answer_id": 74636273,
"author": "Brian Pursley",
"author_id": 5074828,
"author_profile": "https://Stackoverflow.com/users/5074828",
"pm_score": 1,
"selected": false,
"text": "json.Unmarshal package main\n\nimport (\n \"encoding/json\"\n \"fmt\"\n \"os\"\n)\n\ntype Record struct {\n Item struct {\n Id struct {\n S string\n }\n CreateTime struct {\n N string\n }\n }\n}\n\nfunc main() {\n\n str := `{\n \"Item\": {\n \"Id\": {\n \"S\": \"db31\"\n },\n \"CreateTime\": {\n \"N\": \"1647882237618915000\"\n }\n }\n}`\n\n var record Record\n if err := json.Unmarshal([]byte(str), &record); err != nil {\n fmt.Fprintf(os.Stderr, \"unmarshal failed: %v\", err)\n os.Exit(1)\n }\n\n fmt.Printf(\"%s %s\", record.Item.Id.S, record.Item.CreateTime.N)\n}\n\n package main\n\nimport (\n \"fmt\"\n \"github.com/tidwall/gjson\"\n)\n\ntype Record struct {\n Id string\n CreateTime string\n}\n\nfunc main() {\n\n str := `{\n \"Item\": {\n \"Id\": {\n \"S\": \"db31\"\n },\n \"CreateTime\": {\n \"N\": \"1647882237618915000\"\n }\n }\n}`\n\n values := gjson.GetMany(str, \"Item.Id.S\", \"Item.CreateTime.N\")\n\n record := Record{\n Id: values[0].Str,\n CreateTime: values[1].Str,\n }\n\n fmt.Printf(\"%s %s\", record.Id, record.CreateTime)\n}\n"
},
{
"answer_id": 74660674,
"author": "Manas Paldhe",
"author_id": 1683651,
"author_profile": "https://Stackoverflow.com/users/1683651",
"pm_score": 0,
"selected": false,
"text": "// Import the necessary packages\nimport (\n \"encoding/json\"\n \"fmt\"\n)\n\n// Define a struct to represent the DynamoDB object\ntype DynamoDBObject struct {\n Item struct {\n Id struct {\n S string `json:\"S\"`\n } `json:\"Id\"`\n CreateTime struct {\n N string `json:\"N\"`\n } `json:\"CreateTime\"`\n } `json:\"Item\"`\n}\n\nfunc main() {\n // Define the DynamoDB object string\n dynamoDBObjectString := `{\n \"Item\": {\n \"Id\": {\n \"S\": \"db31\"\n },\n \"CreateTime\": {\n \"N\": \"1647882237618915000\"\n }\n }\n }`\n\n // Unmarshal the DynamoDB object string into a DynamoDBObject struct\n var dynamoDBObject DynamoDBObject\n json.Unmarshal([]byte(dynamoDBObjectString), &dynamoDBObject)\n\n // Marshal the DynamoDBObject struct into a JSON object\n jsonObject, _ := json.Marshal(dynamoDBObject)\n\n // Print the JSON object\n fmt.Println(string(jsonObject))\n}\n {\"Item\":{\"Id\":{\"S\":\"db31\"},\"CreateTime\":{\"N\":\"1647882237618915000\"}}}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74635931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3981486/"
] |
74,635,967
|
<p>I having quite a trouble changing the colors of some icons inside a menu. They have two different colors, so i'm passing different classes to them... But (as always) it won't obbey...</p>
<p>My menuItemsSet function:</p>
<pre><code>loadMenuItems(){
this.menuItems = [
{ label: 'Whatsapp', icon: 'pi pi-whatsapp', iconClass: 'green-icon', command: () => this.openWhatsappHistory(this.selectedItem) },
{ label: 'E-mail', icon: 'pi pi-envelope', iconClass: 'red-icon'},
{ label: 'Excluir', icon: 'pi pi-trash', iconClass: 'red-icon', command: () => this.deleteBudget(this.selectedItem)},
{ label: 'Cancelar', icon: 'pi pi-times',iconClass: 'red-icon', command: () => this.cancelBudget(this.selectedItem)},
]
}
</code></pre>
<p>My css:</p>
<pre><code>.p-menu.p-menuitem-link.p-menuitem-icon.green-icon{
color: rgb(21, 158, 21) !important;
}
.p-menu.p-menuitem-link.p-menuitem-icon.red-icon{
color: rgb(242, 66, 66);
}
</code></pre>
<p>There's not much to see in html...:</p>
<pre><code><p-menu appendTo="body" #menu [model]="menuItems" [popup]="true" [showTransitionOptions]="'150ms'" [hideTransitionOptions]="'150ms'"></p-menu>
<button (click)="menu.toggle($event); changeSelectedItem(order)" pButton type="button" icon="pi pi-ellipsis-v" class="p-button-text p-button-rounded p-button-lg"></button>
</code></pre>
|
[
{
"answer_id": 74636273,
"author": "Brian Pursley",
"author_id": 5074828,
"author_profile": "https://Stackoverflow.com/users/5074828",
"pm_score": 1,
"selected": false,
"text": "json.Unmarshal package main\n\nimport (\n \"encoding/json\"\n \"fmt\"\n \"os\"\n)\n\ntype Record struct {\n Item struct {\n Id struct {\n S string\n }\n CreateTime struct {\n N string\n }\n }\n}\n\nfunc main() {\n\n str := `{\n \"Item\": {\n \"Id\": {\n \"S\": \"db31\"\n },\n \"CreateTime\": {\n \"N\": \"1647882237618915000\"\n }\n }\n}`\n\n var record Record\n if err := json.Unmarshal([]byte(str), &record); err != nil {\n fmt.Fprintf(os.Stderr, \"unmarshal failed: %v\", err)\n os.Exit(1)\n }\n\n fmt.Printf(\"%s %s\", record.Item.Id.S, record.Item.CreateTime.N)\n}\n\n package main\n\nimport (\n \"fmt\"\n \"github.com/tidwall/gjson\"\n)\n\ntype Record struct {\n Id string\n CreateTime string\n}\n\nfunc main() {\n\n str := `{\n \"Item\": {\n \"Id\": {\n \"S\": \"db31\"\n },\n \"CreateTime\": {\n \"N\": \"1647882237618915000\"\n }\n }\n}`\n\n values := gjson.GetMany(str, \"Item.Id.S\", \"Item.CreateTime.N\")\n\n record := Record{\n Id: values[0].Str,\n CreateTime: values[1].Str,\n }\n\n fmt.Printf(\"%s %s\", record.Id, record.CreateTime)\n}\n"
},
{
"answer_id": 74660674,
"author": "Manas Paldhe",
"author_id": 1683651,
"author_profile": "https://Stackoverflow.com/users/1683651",
"pm_score": 0,
"selected": false,
"text": "// Import the necessary packages\nimport (\n \"encoding/json\"\n \"fmt\"\n)\n\n// Define a struct to represent the DynamoDB object\ntype DynamoDBObject struct {\n Item struct {\n Id struct {\n S string `json:\"S\"`\n } `json:\"Id\"`\n CreateTime struct {\n N string `json:\"N\"`\n } `json:\"CreateTime\"`\n } `json:\"Item\"`\n}\n\nfunc main() {\n // Define the DynamoDB object string\n dynamoDBObjectString := `{\n \"Item\": {\n \"Id\": {\n \"S\": \"db31\"\n },\n \"CreateTime\": {\n \"N\": \"1647882237618915000\"\n }\n }\n }`\n\n // Unmarshal the DynamoDB object string into a DynamoDBObject struct\n var dynamoDBObject DynamoDBObject\n json.Unmarshal([]byte(dynamoDBObjectString), &dynamoDBObject)\n\n // Marshal the DynamoDBObject struct into a JSON object\n jsonObject, _ := json.Marshal(dynamoDBObject)\n\n // Print the JSON object\n fmt.Println(string(jsonObject))\n}\n {\"Item\":{\"Id\":{\"S\":\"db31\"},\"CreateTime\":{\"N\":\"1647882237618915000\"}}}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74635967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13536950/"
] |
74,635,970
|
<p>I have a simple code that:</p>
<p>Read a trajectory file that can be seen as a list of 2D arrays (list of positions in space) stored in Y</p>
<p>I then want to compute for each pair (scipy.pdist style) the RMSD</p>
<p>My code works fine:</p>
<pre><code>trajectory = read("test.lammpstrj", index="::")
m = len(trajectory)
#.get_positions() return a 2d numpy array
Y = np.array([snapshot.get_positions() for snapshot in trajectory])
b = [np.sqrt(((((Y[i]- Y[j])**2))*3).mean()) for i in range(m) for j in range(i + 1, m)]
</code></pre>
<p>This code execute in 0.86 seconds using python3.10, using Julia1.8 the same kind of code execute in 0.46 seconds</p>
<p>I plan to have trajectory much larger (~ 200,000 elements), would it be possible to get a speed-up using python or should I stick to Julia?</p>
|
[
{
"answer_id": 74637773,
"author": "Mercury",
"author_id": 10229754,
"author_profile": "https://Stackoverflow.com/users/10229754",
"pm_score": 4,
"selected": true,
"text": "snapshot.get_positions() (p, q) Y (m, p, q) m m m=1000 import numpy as np\n\n# dummy inputs\nm = 1000\np, q = 4, 5\nY = np.random.randn(m, p, q)\n\n# your current method\ndef foo():\n return [np.sqrt(((((Y[i]- Y[j])**2))*3).mean()) for i in range(m) for j in range(i + 1, m)]\n\n# vectorized approach -> compute the upper triangle of the pairwise distance matrix\ndef bar():\n u, v = np.triu_indices(Y.shape[0], 1)\n return np.sqrt((3 * (Y[u] - Y[v]) ** 2).mean(axis=(-1, -2)))\n\n# Check for correctness\n\nout_1 = foo()\nout_2 = bar()\nprint(np.allclose(out_1, out_2))\n# True\n %timeit -n 10 -r 3 foo()\n# 3.16 s ± 50.3 ms per loop (mean ± std. dev. of 3 runs, 10 loops each)\n %timeit -n 10 -r 3 bar()\n# 97.5 ms ± 405 µs per loop (mean ± std. dev. of 3 runs, 10 loops each)\n Y bar jax.numpy import jax\nimport jax.numpy as jnp\n\n@jax.jit\ndef jit_bar(Y):\n u, v = jnp.triu_indices(Y.shape[0], 1)\n return jnp.sqrt((3 * (Y[u] - Y[v]) ** 2).mean(axis=(-1, -2)))\n\n# check for correctness\n\nprint(np.allclose(bar(), jit_bar(Y)))\n# True\n %timeit -n 10 -r 3 jit_bar(Y)\n# 10.6 ms ± 678 µs per loop (mean ± std. dev. of 3 runs, 10 loops each)\n bar()"
},
{
"answer_id": 74642843,
"author": "DNF",
"author_id": 2749865,
"author_profile": "https://Stackoverflow.com/users/2749865",
"pm_score": 2,
"selected": false,
"text": "SMatrix sumdiff2(A, B) = sum((A[i] - B[i])^2 for i in eachindex(A, B))\nfunction dists(Y)\n M = length(Y)\n V = Vector{float(eltype(eltype(Y)))}(undef, sum(1:M-1))\n Threads.@threads for i in eachindex(Y)\n ii = sum(M-i+1:M-1) # don't worry about this sum\n for j in i+1:lastindex(Y)\n ind = ii + (j-i)\n V[ind] = sqrt(3 * sumdiff2(Y[i], Y[j])/length(Y[i]))\n end\n end\n return V\nend\n\nusing Random: randn\nusing StaticArrays: SMatrix\nYs = [randn(SMatrix{4,5,Float64}) for _ in 1:1000];\n # single-threaded\njulia> using BenchmarkTools\njulia> @btime dists($Ys);\n 6.561 ms (2 allocations: 3.81 MiB)\n\n# multi-threaded with 6 cores\njulia> @btime dists($Ys);\n 1.606 ms (75 allocations: 3.82 MiB)\n foo: 5.5seconds\nbar: 179ms\n foo"
},
{
"answer_id": 74647492,
"author": "Jérôme Richard",
"author_id": 12939557,
"author_profile": "https://Stackoverflow.com/users/12939557",
"pm_score": 1,
"selected": false,
"text": "m-i i+1 m+1 import numba as nb\nimport numpy as np\n\n@nb.njit(inline='always', fastmath=True)\ndef compute_line(tmp, res, i, m):\n offset = (i * (2 * m - i - 1)) // 2\n factor = 3.0 / n\n for j in range(i + 1, m):\n s = 0.0\n for k in range(n):\n s += (tmp[i, k] - tmp[j, k]) ** 2\n res[offset] = np.sqrt(s * factor)\n offset += 1\n return res\n\n@nb.njit('()', parallel=True, fastmath=True)\ndef fastest():\n m, n = Y.shape[0], Y.shape[1] * Y.shape[2]\n res = np.empty(m*(m-1)//2)\n tmp = Y.reshape(m, n)\n for i in nb.prange(m//2):\n compute_line(tmp, res, i, m)\n compute_line(tmp, res, m-i-1, m)\n if m % 2 == 1:\n compute_line(tmp, res, (m+1)//2, m)\n return res\n\n# [...] same as others\n%timeit -n 100 fastest()\n foo (seq, Python, Mercury): 4910.7 ms\nbar (seq, Python, Mercury): 134.2 ms\njit_bar (seq, Python, Mercury): ???\ndists (seq, Julia, DNF) 6.9 ms\ndists (par, Julia, DNF) 2.2 ms\nfastest (par, Python, me): 1.5 ms <-----\n (200_000,4,5)"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74635970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5623007/"
] |
74,635,979
|
<p>I'm having trouble putting background image on MS Outlook. I already searched on Google and found out that you can put background on Outlook via VML.</p>
<p>The first background <code>fruit-bg.jpg</code> is working, but when I put the nested background <code>yellow-bg.png</code> its not appearing. And also the whole email design is destroyed. Can someone help me with this?</p>
<p>I'm using testi to test email on Outlook: <a href="https://testi.at/proj/kEpTkBrFm51uk54c6Pwh3xRcY" rel="nofollow noreferrer">https://testi.at/proj/kEpTkBrFm51uk54c6Pwh3xRcY</a></p>
<p>Here's my email HTML:</p>
<pre><code><html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<style>
body {
font-family: 'Georgia', 'Arial', sans-serif;
color: #000;
}
h1 {
font-family: 'Georgia', 'Arial', sans-serif;
font-size: 30px;
font-weight: bold;
color: #000;
}
p {
font-size: 13px;
}
h5 {
font-size: 11px;
font-weight: normal;
}
a.link, a.link:visited {
font-size: 13px;
color: #2b4a9c;
text-decoration: none;
border: 1px solid #2b4a9c;
padding: 5px;
}
a.link:hover {
font-size: 13px;
color: #ffac16;
text-decoration: none;
border: 1px solid #ffac16;
padding: 5px;
}
</style>
</head>
<body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<table style="text-align: center;" width="100%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td style="width: 600px;">
<table width="600" style="width: 600px; text-align: center;" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td width="600" background="https://i.ibb.co/cNR3dvy/fruit-bg.jpg" style="background: url('https://i.ibb.co/cNR3dvy/fruit-bg.jpg') no-repeat center center; background-size: cover; padding-bottom: 35px;">
<!--[if gte mso 9]>
<v:image xmlns:v="urn:schemas-microsoft-com:vml" src="https://i.ibb.co/cNR3dvy/fruit-bg.jpg" style="width: 600px; height: 610px; border: 0; display: inline-block; " fill="true" stroke="false" />
<v:rect xmlns:v="urn:schemas-microsoft-com:vml" fill="true" stroke="false" style="border: 0; display: inline-block; position: absolute; width: 600px; height:610px;">
<v:fill opacity="0%" color="#FFFFFF" />
<v:textbox inset="0,0,0,0">
<![endif]-->
<table width="600" style="width: 600px;" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td style="padding: 50px 25px 0;">
<table width="550" style="width: 550px; padding: 0;" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td width="550" background="https://i.ibb.co/RT5r3Ys/yellow-bg.png" style="background: url('https://i.ibb.co/RT5r3Ys/yellow-bg.png') no-repeat center center; background-size: cover; width: 550px; border-radius: 20px 60px 20px 60px; padding: 45px 40px 60px; box-shadow: -7px 8px 10px 3px #afafafb3; text-align: center;">
<!--[if gte mso 9]>
<v:image xmlns:v="urn:schemas-microsoft-com:vml" src="https://i.ibb.co/RT5r3Ys/yellow-bg.png" style="width: 550px; height: 500px; border: 0; display: inline-block; border-radius: 20px 60px 20px 60px; box-shadow: -7px 8px 10px 3px #afafafb3;" fill="true" stroke="false" />
<v:rect xmlns:v="urn:schemas-microsoft-com:vml" fill="true" stroke="false" style="border: 0; display: inline-block; position: absolute; width: 550px; height:500px;">
<v:fill opacity="0%" color="#FFFFFF" />
<v:textbox inset="0,0,0,0">
<![endif]-->
<table style="margin: auto; position; relative;" width="470" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td style="text-align: center;">
<img style="display: inline-block; width: 140px; margin-bottom: 15px;" src="https://i.ibb.co/YXG85jF/some-photo.jpg" />
</td>
<td style="text-align: center; padding-left: 30px;">
<img style="width: 100%; margin-bottom: 15px;" src="https://i.ibb.co/YXG85jF/some-photo.jpg" />
<p style="font-family: 'Georgia', 'Arial', sans-serif; font-size: 14px; line-height: 23px; padding: 0 30px; color: #000;">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi.
</p>
</td>
</tr>
</table>
<!--[if gte mso 9]>
</v:textbox>
</v:fill>
</v:rect>
</v:image>
<![endif]-->
</td>
</tr>
</table>
</td>
</tr>
</table>
<!--[if gte mso 9]>
</v:textbox>
</v:fill>
</v:rect>
</v:image>
<![endif]-->
</td>
</tr>
<tr style="background-color: #ffd000;">
<td style="padding: 35px 50px 55px;">
<p style="font-family: 'Georgia', 'Arial', sans-serif; font-size: 12px; color: #000;">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p style="font-family: 'Georgia', 'Arial', sans-serif; font-size: 12px; color: #000;">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua.
</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
</code></pre>
|
[
{
"answer_id": 74637773,
"author": "Mercury",
"author_id": 10229754,
"author_profile": "https://Stackoverflow.com/users/10229754",
"pm_score": 4,
"selected": true,
"text": "snapshot.get_positions() (p, q) Y (m, p, q) m m m=1000 import numpy as np\n\n# dummy inputs\nm = 1000\np, q = 4, 5\nY = np.random.randn(m, p, q)\n\n# your current method\ndef foo():\n return [np.sqrt(((((Y[i]- Y[j])**2))*3).mean()) for i in range(m) for j in range(i + 1, m)]\n\n# vectorized approach -> compute the upper triangle of the pairwise distance matrix\ndef bar():\n u, v = np.triu_indices(Y.shape[0], 1)\n return np.sqrt((3 * (Y[u] - Y[v]) ** 2).mean(axis=(-1, -2)))\n\n# Check for correctness\n\nout_1 = foo()\nout_2 = bar()\nprint(np.allclose(out_1, out_2))\n# True\n %timeit -n 10 -r 3 foo()\n# 3.16 s ± 50.3 ms per loop (mean ± std. dev. of 3 runs, 10 loops each)\n %timeit -n 10 -r 3 bar()\n# 97.5 ms ± 405 µs per loop (mean ± std. dev. of 3 runs, 10 loops each)\n Y bar jax.numpy import jax\nimport jax.numpy as jnp\n\n@jax.jit\ndef jit_bar(Y):\n u, v = jnp.triu_indices(Y.shape[0], 1)\n return jnp.sqrt((3 * (Y[u] - Y[v]) ** 2).mean(axis=(-1, -2)))\n\n# check for correctness\n\nprint(np.allclose(bar(), jit_bar(Y)))\n# True\n %timeit -n 10 -r 3 jit_bar(Y)\n# 10.6 ms ± 678 µs per loop (mean ± std. dev. of 3 runs, 10 loops each)\n bar()"
},
{
"answer_id": 74642843,
"author": "DNF",
"author_id": 2749865,
"author_profile": "https://Stackoverflow.com/users/2749865",
"pm_score": 2,
"selected": false,
"text": "SMatrix sumdiff2(A, B) = sum((A[i] - B[i])^2 for i in eachindex(A, B))\nfunction dists(Y)\n M = length(Y)\n V = Vector{float(eltype(eltype(Y)))}(undef, sum(1:M-1))\n Threads.@threads for i in eachindex(Y)\n ii = sum(M-i+1:M-1) # don't worry about this sum\n for j in i+1:lastindex(Y)\n ind = ii + (j-i)\n V[ind] = sqrt(3 * sumdiff2(Y[i], Y[j])/length(Y[i]))\n end\n end\n return V\nend\n\nusing Random: randn\nusing StaticArrays: SMatrix\nYs = [randn(SMatrix{4,5,Float64}) for _ in 1:1000];\n # single-threaded\njulia> using BenchmarkTools\njulia> @btime dists($Ys);\n 6.561 ms (2 allocations: 3.81 MiB)\n\n# multi-threaded with 6 cores\njulia> @btime dists($Ys);\n 1.606 ms (75 allocations: 3.82 MiB)\n foo: 5.5seconds\nbar: 179ms\n foo"
},
{
"answer_id": 74647492,
"author": "Jérôme Richard",
"author_id": 12939557,
"author_profile": "https://Stackoverflow.com/users/12939557",
"pm_score": 1,
"selected": false,
"text": "m-i i+1 m+1 import numba as nb\nimport numpy as np\n\n@nb.njit(inline='always', fastmath=True)\ndef compute_line(tmp, res, i, m):\n offset = (i * (2 * m - i - 1)) // 2\n factor = 3.0 / n\n for j in range(i + 1, m):\n s = 0.0\n for k in range(n):\n s += (tmp[i, k] - tmp[j, k]) ** 2\n res[offset] = np.sqrt(s * factor)\n offset += 1\n return res\n\n@nb.njit('()', parallel=True, fastmath=True)\ndef fastest():\n m, n = Y.shape[0], Y.shape[1] * Y.shape[2]\n res = np.empty(m*(m-1)//2)\n tmp = Y.reshape(m, n)\n for i in nb.prange(m//2):\n compute_line(tmp, res, i, m)\n compute_line(tmp, res, m-i-1, m)\n if m % 2 == 1:\n compute_line(tmp, res, (m+1)//2, m)\n return res\n\n# [...] same as others\n%timeit -n 100 fastest()\n foo (seq, Python, Mercury): 4910.7 ms\nbar (seq, Python, Mercury): 134.2 ms\njit_bar (seq, Python, Mercury): ???\ndists (seq, Julia, DNF) 6.9 ms\ndists (par, Julia, DNF) 2.2 ms\nfastest (par, Python, me): 1.5 ms <-----\n (200_000,4,5)"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74635979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1191749/"
] |
74,635,981
|
<p>i try to design a table in cassandra, but im getting a lot of large partition messages.
Any ideas how i could improve this "design" to prevent overloading and still can use a query like this:</p>
<pre><code>select * from analytics where domain='test' and tld='com'
</code></pre>
<pre><code>CREATE TABLE analytics (
domain text,
tld text,
subdomain text,
a text,
PRIMARY KEY ((domain, tld), subdomain)
)
</code></pre>
<p>Also im loading this table with</p>
<pre><code>update analytics set a='a' where domain='test' and tld='com' and subdomain='b';
</code></pre>
<p>Some partitions are over 1million rows</p>
|
[
{
"answer_id": 74651376,
"author": "Erick Ramirez",
"author_id": 4269535,
"author_profile": "https://Stackoverflow.com/users/4269535",
"pm_score": 1,
"selected": false,
"text": "sub.domainsr.us su CREATE TABLE subdomains_by_domain_tld_prefix (\n domain text,\n tld text,\n prefix text,\n subdomain text,\n a text,\n PRIMARY KEY ((domain, tld, prefix), subdomain)\n)\n prefix cassandra"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74635981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17149861/"
] |
74,635,994
|
<p>Trying to learn about the built-in <a href="https://docs.python.org/3/library/multiprocessing.html" rel="nofollow noreferrer"><code>multiprocessing</code></a> and <a href="https://pytorch.org/docs/stable/multiprocessing.html" rel="nofollow noreferrer">Pytorch's <code>multiprocessing</code></a> packages, I have observed a different behavior between both. I find this to be strange since <a href="https://pytorch.org/docs/stable/multiprocessing.html#:%7E:text=The%20API%20is%20100%25%20compatible%20with%20the%20original%20module" rel="nofollow noreferrer">Pytorch's package is fully-compatible</a> with the built-in package.</p>
<p>Concretely, I'm refering to the way variables are shared between processes. In Pytorch, tensor's are moved to shared_memory via the inplace operation <a href="https://pytorch.org/docs/stable/generated/torch.Tensor.share_memory_.html#torch.Tensor.share_memory_" rel="nofollow noreferrer"><code>share_memory_()</code></a>. On the other hand, we can get the same result with the built-in package by using the <a href="https://docs.python.org/3/library/multiprocessing.shared_memory.html" rel="nofollow noreferrer"><code>shared_memory</code></a> module.</p>
<p>The <strong>difference</strong> between both that I'm struggling to understand is that, with the built-in version, we have to explicitely access the shared memory-block inside the launched process. However, we don't need to do that with the Pytorch version.</p>
<p>Here is a <strong>Pytorch</strong>'s toy example showing this:</p>
<pre class="lang-py prettyprint-override"><code>import time
import torch
# the same behavior happens when importing:
# import multiprocessing as mp
import torch.multiprocessing as mp
def get_time(s):
return round(time.time() - s, 1)
def foo(a):
# wait ~1sec to print the value of the tensor.
time.sleep(1.0)
with lock:
#-------------------------------------------------------------------
# WITHOUT explicitely accessing the shared memory block, we can observe
# that the tensor has changed:
#-------------------------------------------------------------------
print(f"{__name__}\t{get_time(s)}\t\t{a}")
# global variables.
lock = mp.Lock()
s = time.time()
if __name__ == '__main__':
print("Module\t\tTime\t\tValue")
print("-"*50)
# create tensor and assign it to shared memory.
a = torch.zeros(2).share_memory_()
print(f"{__name__}\t{get_time(s)}\t\t{a}")
# start child process.
p0 = mp.Process(target=foo, args=(a,))
p0.start()
# modify the value of the tensor after ~0.5sec.
time.sleep(0.5)
with lock:
a[0] = 1.0
print(f"{__name__}\t{get_time(s)}\t\t{a}")
time.sleep(1.5)
p0.join()
</code></pre>
<p>which outputs (as expected):</p>
<pre class="lang-bash prettyprint-override"><code>Module Time Value
--------------------------------------------------
__main__ 0.0 tensor([0., 0.])
__main__ 0.5 tensor([1., 0.])
__mp_main__ 1.0 tensor([1., 0.])
</code></pre>
<p>And here is a toy example with the <strong>built-in</strong> package:</p>
<pre class="lang-py prettyprint-override"><code>import time
import multiprocessing as mp
from multiprocessing import shared_memory
import numpy as np
def get_time(s):
return round(time.time() - s, 1)
def foo(shm_name, shape, type_):
#-------------------------------------------------------------------
# WE NEED TO explicitely access the shared memory block to observe
# that the array has changed:
#-------------------------------------------------------------------
existing_shm = shared_memory.SharedMemory(name=shm_name)
a = np.ndarray(shape, type_, buffer=existing_shm.buf)
# wait ~1sec to print the value.
time.sleep(1.0)
with lock:
print(f"{__name__}\t{get_time(s)}\t\t{a}")
# global variables.
lock = mp.Lock()
s = time.time()
if __name__ == '__main__':
print("Module\t\tTime\t\tValue")
print("-"*35)
# create numpy array and shared memory block.
a = np.zeros(2,)
shm = shared_memory.SharedMemory(create=True, size=a.nbytes)
a_shared = np.ndarray(a.shape, a.dtype, buffer=shm.buf)
a_shared[:] = a[:]
print(f"{__name__}\t{get_time(s)}\t\t{a_shared}")
# start child process.
p0 = mp.Process(target=foo, args=(shm.name, a.shape, a.dtype))
p0.start()
# modify the value of the vaue after ~0.5sec.
time.sleep(0.5)
with lock:
a_shared[0] = 1.0
print(f"{__name__}\t{get_time(s)}\t\t{a_shared}")
time.sleep(1.5)
p0.join()
</code></pre>
<p>which equivalently outputs, as expected:</p>
<pre class="lang-bash prettyprint-override"><code>Module Time Value
-----------------------------------
__main__ 0.0 [0. 0.]
__main__ 0.5 [1. 0.]
__mp_main__ 1.0 [1. 0.]
</code></pre>
<p>So what I'm strugging to understand is why we don't need to follow the same steps in both versions, built-in and Pytorch's, i.e. how Pytorch is able to avoid the need to explicitely access the shared memory-block?</p>
<p>P.S. I'm using a Windows OS and Python 3.9</p>
|
[
{
"answer_id": 74636147,
"author": "J_H",
"author_id": 8431111,
"author_profile": "https://Stackoverflow.com/users/8431111",
"pm_score": 2,
"selected": false,
"text": "d d d multiprocessing d d d"
},
{
"answer_id": 74638164,
"author": "Ahmed AEK",
"author_id": 15649230,
"author_profile": "https://Stackoverflow.com/users/15649230",
"pm_score": 2,
"selected": true,
"text": "__getstate__ __setstate__ bar import time\nimport multiprocessing as mp\nfrom multiprocessing import shared_memory\nimport numpy as np\n\nclass bar:\n def __init__(self):\n self._size = 10\n self._type = np.uint8\n self.shm = shared_memory.SharedMemory(create=True, size=self._size)\n self._mem_name = self.shm.name\n self.arr = np.ndarray([self._size], self._type, buffer=self.shm.buf)\n\n def __getstate__(self):\n \"\"\"Return state values to be pickled.\"\"\"\n return (self._mem_name, self._size, self._type)\n\n def __setstate__(self, state):\n \"\"\"Restore state from the unpickled state values.\"\"\"\n self._mem_name, self._size, self._type = state\n self.shm = shared_memory.SharedMemory(self._mem_name)\n self.arr = np.ndarray([self._size], self._type, buffer=self.shm.buf)\n\ndef get_time(s):\n return round(time.time() - s, 1)\n\ndef foo(shm, lock):\n # -------------------------------------------------------------------\n # without explicitely access the shared memory block we observe\n # that the array has changed:\n # -------------------------------------------------------------------\n a = shm\n\n # wait ~1sec to print the value.\n time.sleep(1.0)\n with lock:\n print(f\"{__name__}\\t{get_time(s)}\\t\\t{a.arr}\")\n\n# global variables.\ns = time.time()\n\nif __name__ == '__main__':\n lock = mp.Lock() # to work on windows/mac.\n\n print(\"Module\\t\\tTime\\t\\tValue\")\n print(\"-\" * 35)\n\n # create numpy array and shared memory block.\n a = bar()\n print(f\"{__name__}\\t{get_time(s)}\\t\\t{a.arr}\")\n\n # start child process.\n p0 = mp.Process(target=foo, args=(a, lock))\n p0.start()\n\n # modify the value of the vaue after ~0.5sec.\n time.sleep(0.5)\n with lock:\n a.arr[0] = 1.0\n\n print(f\"{__name__}\\t{get_time(s)}\\t\\t{a.arr}\")\n time.sleep(1.5)\n\n p0.join()\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74635994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17867420/"
] |
74,636,003
|
<p>I have the following FastAPI application:</p>
<pre class="lang-py prettyprint-override"><code>from fastapi import FastAPI
import socket
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
@app.get("/healthcheck")
def health_check():
result = some_network_operation()
return result
def some_network_operation():
HOST = "192.168.30.12" # This host does not exist so the connection will time out
PORT = 4567
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(10)
s.connect((HOST, PORT))
s.sendall(b"Are you ok?")
data = s.recv(1024)
print(data)
</code></pre>
<p>This is a simple application with two routes:</p>
<ul>
<li><code>/</code> handler that is async</li>
<li><code>/healthcheck</code> handler that is sync</li>
</ul>
<p>With this particular example, if you call <code>/healthcheck</code>, it won't complete until after 10 seconds because the socket connection will timeout. However, if you make a call to <code>/</code> in the meantime, it will return the response right away because FastAPI's main thread is not blocked. This makes sense because according to the docs, FastAPI runs sync handlers on an external threadpool.</p>
<p>My question is, if it is at all possible for us to block the application (block FastAPI's main thread) by doing something inside the <code>health_check</code> method.</p>
<ul>
<li>Perhaps by acquiring the global interpreter lock?</li>
<li>Some other kind of lock?</li>
</ul>
|
[
{
"answer_id": 74636147,
"author": "J_H",
"author_id": 8431111,
"author_profile": "https://Stackoverflow.com/users/8431111",
"pm_score": 2,
"selected": false,
"text": "d d d multiprocessing d d d"
},
{
"answer_id": 74638164,
"author": "Ahmed AEK",
"author_id": 15649230,
"author_profile": "https://Stackoverflow.com/users/15649230",
"pm_score": 2,
"selected": true,
"text": "__getstate__ __setstate__ bar import time\nimport multiprocessing as mp\nfrom multiprocessing import shared_memory\nimport numpy as np\n\nclass bar:\n def __init__(self):\n self._size = 10\n self._type = np.uint8\n self.shm = shared_memory.SharedMemory(create=True, size=self._size)\n self._mem_name = self.shm.name\n self.arr = np.ndarray([self._size], self._type, buffer=self.shm.buf)\n\n def __getstate__(self):\n \"\"\"Return state values to be pickled.\"\"\"\n return (self._mem_name, self._size, self._type)\n\n def __setstate__(self, state):\n \"\"\"Restore state from the unpickled state values.\"\"\"\n self._mem_name, self._size, self._type = state\n self.shm = shared_memory.SharedMemory(self._mem_name)\n self.arr = np.ndarray([self._size], self._type, buffer=self.shm.buf)\n\ndef get_time(s):\n return round(time.time() - s, 1)\n\ndef foo(shm, lock):\n # -------------------------------------------------------------------\n # without explicitely access the shared memory block we observe\n # that the array has changed:\n # -------------------------------------------------------------------\n a = shm\n\n # wait ~1sec to print the value.\n time.sleep(1.0)\n with lock:\n print(f\"{__name__}\\t{get_time(s)}\\t\\t{a.arr}\")\n\n# global variables.\ns = time.time()\n\nif __name__ == '__main__':\n lock = mp.Lock() # to work on windows/mac.\n\n print(\"Module\\t\\tTime\\t\\tValue\")\n print(\"-\" * 35)\n\n # create numpy array and shared memory block.\n a = bar()\n print(f\"{__name__}\\t{get_time(s)}\\t\\t{a.arr}\")\n\n # start child process.\n p0 = mp.Process(target=foo, args=(a, lock))\n p0.start()\n\n # modify the value of the vaue after ~0.5sec.\n time.sleep(0.5)\n with lock:\n a.arr[0] = 1.0\n\n print(f\"{__name__}\\t{get_time(s)}\\t\\t{a.arr}\")\n time.sleep(1.5)\n\n p0.join()\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18615570/"
] |
74,636,013
|
<p>I'm trying to solve a question where your code is supposed to determine if a given number is a palindrome or not, and I don't understand why it isn't working.</p>
<p>(You can skip this and just read the code if you want) The idea was that I create a string with the value of the integer, and create a for loop using the length of said string that uses % 10 to reverse the integer and store it in a separate string. I would then compare the 2 strings to determine if the number is a palindrome or not</p>
<pre class="lang-java prettyprint-override"><code>public static boolean isPalindrome(int x) {
String s = String.valueOf(x);
int count = s.length();
String palindrome = "";
for(int i = 0; i < count; i++){
palindrome += x % 10;
}
System.out.print(palindrome);
if(palindrome == s){
return true;
}
else{
return false;
}
}
</code></pre>
<p>The problem is that the code only returns false, and when I added a print statement to check what the reversed number (String palindrome) is, I got a different number.</p>
<p>For ex. I used 121 to test it and after the for loop the print statement outputted 111.</p>
<p><em><strong>I'm not really looking for a solution</strong></em>, I just want to understand why it's behaving like this. Thanks in advance.</p>
|
[
{
"answer_id": 74636041,
"author": "access violation",
"author_id": 19322069,
"author_profile": "https://Stackoverflow.com/users/19322069",
"pm_score": 1,
"selected": false,
"text": " for(int i = 0; i < count; i++){\n palindrome += x % 10;\n }\n x x palindrome s x"
},
{
"answer_id": 74644494,
"author": "MaicolAntali",
"author_id": 20631377,
"author_profile": "https://Stackoverflow.com/users/20631377",
"pm_score": -1,
"selected": false,
"text": "x public static boolean isPalindrome(int x) {\n String numStr = String.valueOf(x);\n StringBuilder palindrome = new StringBuilder();\n\n for(; x>0; x /=10) {\n palindrome.append(x % 10);\n }\n\n return palindrome.toString().equals(numStr);\n }\n while (x>0) {\n palindrome.append(x % 10);\n x /= 10;\n}\n equals() true StringBuilder +="
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14827134/"
] |
74,636,046
|
<p>I am trying to launch a new process as <code>NT AUTHORITY\Network Service</code> from a process that is running as <code>NT AUTHORITY\System</code>.</p>
<p>I have looked at other questions, such as the following, which does not provide a working example: <a href="https://stackoverflow.com/questions/5629383/">CreateProcess running as user: "NT AUTHORITY/Network Service" without knowing the credentials?</a></p>
<p>And, I have come across some posts which talk about copying a token from a process that is already running as <code>NT AUTHORITY\Network Service</code>: <a href="https://0x00-0x00.github.io/research/2018/10/17/Windows-API-and-Impersonation-Part1.html" rel="nofollow noreferrer">Windows API and Impersonation Part 1 - How to get SYSTEM using Primary Tokens</a>.</p>
<p>I wonder, is there a way to launch a process without having to depend on another process to copy a token from? Is there a way to hand-craft a token that can help launch a process as <code>NT AUTHORITY\Network Service</code> using <a href="https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessasuserw" rel="nofollow noreferrer"><code>CreateProcessAsUserW()</code></a>, for example?</p>
|
[
{
"answer_id": 74636041,
"author": "access violation",
"author_id": 19322069,
"author_profile": "https://Stackoverflow.com/users/19322069",
"pm_score": 1,
"selected": false,
"text": " for(int i = 0; i < count; i++){\n palindrome += x % 10;\n }\n x x palindrome s x"
},
{
"answer_id": 74644494,
"author": "MaicolAntali",
"author_id": 20631377,
"author_profile": "https://Stackoverflow.com/users/20631377",
"pm_score": -1,
"selected": false,
"text": "x public static boolean isPalindrome(int x) {\n String numStr = String.valueOf(x);\n StringBuilder palindrome = new StringBuilder();\n\n for(; x>0; x /=10) {\n palindrome.append(x % 10);\n }\n\n return palindrome.toString().equals(numStr);\n }\n while (x>0) {\n palindrome.append(x % 10);\n x /= 10;\n}\n equals() true StringBuilder +="
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/147613/"
] |
74,636,058
|
<p>Recently, I ran into a problem where I got a warning for updating UI on background task.</p>
<pre><code>func didInit() async {
listOfTodo = await interactor.getTodos()
}
</code></pre>
<p>I tried to wrap the function body inside DispatchQue.main.async {}, but I got an error.</p>
<p>I then found a solution which I have to put @MainActor on top of my function, but I feel like there are other solutions that would make more sense, or this is the only way to work with async/await on Main Thread?</p>
<pre><code>@MainActor
func didInit() async {
listOfTodo = await interactor.getTodos()
}
</code></pre>
|
[
{
"answer_id": 74636305,
"author": "Rob Napier",
"author_id": 97337,
"author_profile": "https://Stackoverflow.com/users/97337",
"pm_score": 2,
"selected": false,
"text": "interactor.getTodos() @MainActor didInit @MainActor MainActor.run {...}"
},
{
"answer_id": 74637330,
"author": "teja_D",
"author_id": 9109095,
"author_profile": "https://Stackoverflow.com/users/9109095",
"pm_score": 1,
"selected": false,
"text": "@MainActor\nfunc updateUI() async {\n // Code to update your UI\n}\n func didInit() {\n Task.detached { // or specify a priority with Task.detached(priority: .background)\n listOfTodo = interactor.getTodos()\n await self.updateUI()\n }\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16731401/"
] |
74,636,064
|
<p>I have data stored in Firestore and i would like to get data from a collection, filter it and publish it in HTML template.</p>
<p>I am using Django as the framework.</p>
<p><strong>VIEWS.py</strong></p>
<pre><code>from django.shortcuts import render
import pyrebase
from firebase_admin import firestore
import datetime
db = firestore.Client()
config = {
"apiKey": "xxxxxx",
"authDomain": "xxxxxx.firebaseapp.com",
"databaseURL": "https://xxxxxx.firebaseio.com",
"projectId": "xxxxxx",
"storageBucket": "xxxxxx.appspot.com",
"messagingSenderId": "xxxxxx",
"appId": "xxxxxx",
"measurementId": "xxxxxx",
"serviceAccount": "xxxxxx.json",
}
# DATABASE
firebase = pyrebase.initialize_app(config)
authe = firebase.auth()
database = firebase.database()
print(database)
# TIME & DATE
today_date = datetime.datetime.now()
tomorrow_date = today_date + datetime.timedelta(days=1)
games_today = today_date.strftime("%Y-%m-%d")
games_tomorrow = tomorrow_date.strftime("%Y-%m-%d")
print(games_today)
print(games_tomorrow)
# NBA EVENT DATA
def xxxxx_basketball_nba_events(request):
nba_events = db.collection('xxxx_au').document('basketball_nba').collection('event_info').stream()
event_info = [doc.to_dict() for doc in nba_events]
nba_games = sorted(event_info, key=lambda k: k['event_start'], reverse=True)
# print(nba_games)
for nba_game in nba_games:
if nba_game['event_start'][:10] == games_tomorrow:
event_id = nba_game['event_id']
event_name = nba_game['event_name']
event_status = nba_game['event_status']
competition = nba_game['competition']
event_start = nba_game['event_start'][:10]
timestamp = nba_game['timestamp']
print(event_id, event_name, event_status, competition, event_start, timestamp)
data = ({
u'event_id': event_id,
u'event_name': event_name,
u'event_status': event_status,
u'competition': competition,
u'event_start': event_start,
u'timestamp': timestamp,
})
return render(request, 'html/nba.html', {'nba_games': data})
</code></pre>
<p><strong>nba_games variable content</strong></p>
<pre><code>[{'timestamp': DatetimeWithNanoseconds(2022, 12, 1, 1, 0, 2, 195000, tzinfo=datetime.timezone.utc), 'event_name': 'Los Angeles Lakers - Portland Trail Blazers', 'event_id': 1018936256, 'event_status': 'NOT_STARTED', 'event_start': '2022-12-01T03:30:00Z', 'competition': 'NBA'}, {'event_start': '2022-12-01T03:00:00Z', 'event_name': 'Sacramento Kings - Indiana Pacers', 'competition': 'NBA', 'timestamp': DatetimeWithNanoseconds(2022, 12, 1, 1, 0, 2, 175000, tzinfo=datetime.timezone.utc), 'event_status': 'NOT_STARTED', 'event_id': 1018936251}, {'timestamp': DatetimeWithNanoseconds(2022, 12, 1, 1, 0, 2, 130000, tzinfo=datetime.timezone.utc), 'event_status': 'NOT_STARTED', 'event_id': 1018936209, 'event_start': '2022-12-01T02:00:00Z', 'event_name': 'Phoenix Suns - Chicago Bulls', 'competition': 'NBA'}, {'timestamp': DatetimeWithNanoseconds(2022, 12, 1, 1, 0, 2, 148000, tzinfo=datetime.timezone.utc), 'event_start': '2022-12-01T02:00:00Z', 'event_name': 'Utah Jazz - Los Angeles Clippers', 'event_status': 'NOT_STARTED', 'competition': 'NBA', 'event_id': 1018936229}, {'event_id': 1018936241, 'timestamp': DatetimeWithNanoseconds(2022, 12, 1, 1, 0, 2, 110000, tzinfo=datetime.timezone.utc), 'event_start': '2022-12-01T02:00:00Z', 'event_status': 'NOT_STARTED', 'competition': 'NBA', 'event_name': 'Denver Nuggets - Houston Rockets'}, {'timestamp': DatetimeWithNanoseconds(2022, 12, 1, 1, 0, 2, 92000, tzinfo=datetime.timezone.utc), 'event_name': 'Oklahoma City Thunder - San Antonio Spurs', 'event_start': '2022-12-01T01:00:00Z', 'event_status': 'NOT_STARTED', 'event_id': 1018936233, 'competition': 'NBA'}, {'event_id': 1018936246, 'timestamp': DatetimeWithNanoseconds(2022, 12, 1, 1, 0, 2, 53000, tzinfo=datetime.timezone.utc), 'event_start': '2022-12-01T01:00:00Z', 'event_status': 'NOT_STARTED', 'competition': 'NBA', 'event_name': 'Minnesota Timberwolves - Memphis Grizzlies'}, {'event_name': 'New Orleans Pelicans - Toronto Raptors', 'event_id': 1018936258, 'event_start': '2022-12-01T01:00:00Z', 'timestamp': DatetimeWithNanoseconds(2022, 12, 1, 1, 0, 2, 76000, tzinfo=datetime.timezone.utc), 'event_status': 'NOT_STARTED', 'competition': 'NBA'}, {'competition': 'NBA', 'timestamp': DatetimeWithNanoseconds(2022, 12, 1, 1, 0, 2, 33000, tzinfo=datetime.timezone.utc), 'event_id': 1018936245, 'event_name': 'New York Knicks - Milwaukee Bucks', 'event_start': '2022-12-01T00:41:56Z', 'event_status': 'STARTED'}, {'timestamp': DatetimeWithNanoseconds(2022, 12, 1, 1, 0, 2, 15000, tzinfo=datetime.timezone.utc), 'event_start': '2022-12-01T00:40:58Z', 'event_name': 'Boston Celtics - Miami Heat', 'event_status': 'STARTED', 'competition': 'NBA', 'event_id': 1018936268}, {'competition': 'NBA', 'event_status': 'STARTED', 'event_id': 1018936243, 'event_start': '2022-12-01T00:40:43Z', 'timestamp': DatetimeWithNanoseconds(2022, 12, 1, 1, 0, 1, 996000, tzinfo=datetime.timezone.utc), 'event_name': 'Brooklyn Nets - Washington Wizards'}, {'competition': 'NBA', 'event_id': 1018936226, 'timestamp': DatetimeWithNanoseconds(2022, 12, 1, 1, 0, 1, 978000, tzinfo=datetime.timezone.utc), 'event_start': '2022-12-01T00:10:25Z', 'event_name': 'Cleveland Cavaliers - Philadelphia 76ers', 'event_status': 'STARTED'}, {'event_name': 'Orlando Magic - Atlanta Hawks', 'event_status': 'STARTED', 'event_id': 1018936242, 'event_start': '2022-12-01T00:10:19Z', 'competition': 'NBA', 'timestamp': DatetimeWithNanoseconds(2022, 12, 1, 1, 0, 1, 960000, tzinfo=datetime.timezone.utc)}, {'event_start': '2022-11-30T03:00:00Z', 'event_name': 'Portland Trail Blazers - Los Angeles Clippers', 'competition': 'NBA', 'timestamp': DatetimeWithNanoseconds(2022, 11, 29, 19, 30, 5, 436000, tzinfo=datetime.timezone.utc), 'event_status': 'NOT_STARTED', 'event_id': 1018936272}, {'event_id': 1018936236, 'event_start': '2022-11-30T00:30:00Z', 'timestamp': DatetimeWithNanoseconds(2022, 11, 29, 19, 30, 5, 419000, tzinfo=datetime.timezone.utc), 'event_name': 'Dallas Mavericks - Golden State Warriors', 'competition': 'NBA', 'event_status': 'NOT_STARTED'}, {'timestamp': DatetimeWithNanoseconds(2022, 11, 29, 19, 30, 5, 403000, tzinfo=datetime.timezone.utc), 'event_status': 'NOT_STARTED', 'event_id': 1018936230, 'event_start': '2022-11-30T00:00:00Z', 'event_name': 'Detroit Pistons - New York Knicks', 'competition': 'NBA'}, {'event_id': 1018936255, 'event_start': '2022-11-29T03:30:00Z', 'timestamp': DatetimeWithNanoseconds(2022, 11, 28, 19, 30, 5, 681000, tzinfo=datetime.timezone.utc), 'competition': 'NBA', 'event_name': 'Los Angeles Lakers - Indiana Pacers', 'event_status': 'NOT_STARTED'}, {'timestamp': DatetimeWithNanoseconds(2022, 11, 28, 19, 30, 5, 664000, tzinfo=datetime.timezone.utc), 'event_status': 'NOT_STARTED', 'event_id': 1018936259, 'event_start': '2022-11-29T03:00:00Z', 'event_name': 'Sacramento Kings - Phoenix Suns', 'competition': 'NBA'}, {'timestamp': DatetimeWithNanoseconds(2022, 11, 28, 19, 30, 5, 619000, tzinfo=datetime.timezone.utc), 'competition': 'NBA', 'event_id': 1018936225, 'event_status': 'NOT_STARTED', 'event_start': '2022-11-29T02:00:00Z', 'event_name': 'Denver Nuggets - Houston Rockets'}, {'timestamp': DatetimeWithNanoseconds(2022, 11, 28, 19, 30, 5, 635000, tzinfo=datetime.timezone.utc), 'event_name': 'Utah Jazz - Chicago Bulls', 'event_status': 'NOT_STARTED', 'event_start': '2022-11-29T02:00:00Z', 'event_id': 1018936240, 'competition': 'NBA'}, {'event_name': 'New Orleans Pelicans - Oklahoma City Thunder', 'event_id': 1018936249, 'event_start': '2022-11-29T01:00:00Z', 'event_status': 'NOT_STARTED', 'competition': 'NBA', 'timestamp': DatetimeWithNanoseconds(2022, 11, 28, 19, 30, 5, 583000, tzinfo=datetime.timezone.utc)}, {'competition': 'NBA', 'timestamp': DatetimeWithNanoseconds(2022, 11, 28, 19, 30, 5, 569000, tzinfo=datetime.timezone.utc), 'event_id': 1018936264, 'event_name': 'Toronto Raptors - Cleveland Cavaliers', 'event_start': '2022-11-29T00:30:00Z', 'event_status': 'NOT_STARTED'}, {'event_start': '2022-11-29T00:30:00Z', 'event_name': 'Boston Celtics - Charlotte Hornets', 'timestamp': DatetimeWithNanoseconds(2022, 11, 28, 19, 30, 5, 492000, tzinfo=datetime.timezone.utc), 'competition': 'NBA', 'event_id': 1018936266, 'event_status': 'NOT_STARTED'}, {'event_status': 'NOT_STARTED', 'competition': 'NBA', 'event_name': 'Brooklyn Nets - Orlando Magic', 'event_id': 1018936275, 'event_start': '2022-11-29T00:30:00Z', 'timestamp': DatetimeWithNanoseconds(2022, 11, 28, 19, 30, 5, 533000, tzinfo=datetime.timezone.utc)}, {'event_name': 'Philadelphia 76ers - Atlanta Hawks', 'event_id': 1018936215, 'event_start': '2022-11-29T00:00:00Z', 'timestamp': DatetimeWithNanoseconds(2022, 11, 28, 19, 30, 5, 414000, tzinfo=datetime.timezone.utc), 'event_status': 'NOT_STARTED', 'competition': 'NBA'}, {'event_id': 1018936237, 'event_status': 'NOT_STARTED', 'event_start': '2022-11-29T00:00:00Z', 'competition': 'NBA', 'timestamp': DatetimeWithNanoseconds(2022, 11, 28, 19, 30, 5, 463000, tzinfo=datetime.timezone.utc), 'event_name': 'Washington Wizards - Minnesota Timberwolves'}, {'competition': 'NBA', 'event_name': 'Milwaukee Bucks - Dallas Mavericks', 'timestamp': DatetimeWithNanoseconds(2022, 11, 27, 19, 30, 6, 585000, tzinfo=datetime.timezone.utc), 'event_id': 1018936297, 'event_start': '2022-11-28T01:00:00Z', 'event_status': 'NOT_STARTED'}, {'event_id': 1018936274, 'event_start': '2022-11-27T23:00:00Z', 'timestamp': DatetimeWithNanoseconds(2022, 11, 27, 19, 30, 6, 524000, tzinfo=datetime.timezone.utc), 'competition': 'NBA', 'event_name': 'Boston Celtics - Washington Wizards', 'event_status': 'NOT_STARTED'}, {'event_id': 1018936279, 'event_start': '2022-11-27T23:00:00Z', 'timestamp': DatetimeWithNanoseconds(2022, 11, 27, 19, 30, 6, 570000, tzinfo=datetime.timezone.utc), 'event_name': 'Orlando Magic - Philadelphia 76ers', 'competition': 'NBA', 'event_status': 'NOT_STARTED'}, {'timestamp': DatetimeWithNanoseconds(2022, 11, 27, 19, 30, 6, 540000, tzinfo=datetime.timezone.utc), 'event_start': '2022-11-27T23:00:00Z', 'event_name': 'Detroit Pistons - Cleveland Cavaliers', 'competition': 'NBA', 'event_status': 'NOT_STARTED', 'event_id': 1018936306}, {'timestamp': DatetimeWithNanoseconds(2022, 11, 27, 19, 30, 6, 555000, tzinfo=datetime.timezone.utc), 'event_status': 'NOT_STARTED', 'event_id': 1018936310, 'event_start': '2022-11-27T23:00:00Z', 'event_name': 'New York Knicks - Memphis Grizzlies', 'competition': 'NBA'}, {'competition': 'NBA', 'timestamp': DatetimeWithNanoseconds(2022, 11, 27, 19, 30, 6, 508000, tzinfo=datetime.timezone.utc), 'event_id': 1018936287, 'event_status': 'NOT_STARTED', 'event_start': '2022-11-27T22:00:00Z', 'event_name': 'Atlanta Hawks - Miami Heat'}, {'event_name': 'Los Angeles Clippers - Indiana Pacers', 'event_status': 'NOT_STARTED', 'event_id': 1018936294, 'event_start': '2022-11-27T21:00:00Z', 'competition': 'NBA', 'timestamp': DatetimeWithNanoseconds(2022, 11, 27, 19, 30, 6, 487000, tzinfo=datetime.timezone.utc)}, {'event_start': '2022-11-27T20:30:00Z', 'event_name': 'Minnesota Timberwolves - Golden State Warriors', 'competition': 'NBA', 'timestamp': DatetimeWithNanoseconds(2022, 11, 27, 19, 30, 6, 465000, tzinfo=datetime.timezone.utc), 'event_status': 'NOT_STARTED', 'event_id': 1018936267}, {'timestamp': DatetimeWithNanoseconds(2022, 11, 27, 19, 30, 6, 448000, tzinfo=datetime.timezone.utc), 'event_name': 'Brooklyn Nets - Portland Trail Blazers', 'event_status': 'NOT_STARTED', 'event_id': 1018936300, 'event_start': '2022-11-27T20:00:00Z', 'competition': 'NBA'}, {'event_name': 'Phoenix Suns - Utah Jazz', 'event_id': 1018936305, 'event_start': '2022-11-27T02:00:00Z', 'event_status': 'NOT_STARTED', 'competition': 'NBA', 'timestamp': DatetimeWithNanoseconds(2022, 11, 26, 19, 30, 6, 126000, tzinfo=datetime.timezone.utc)}, {'event_id': 1018936280, 'event_status': 'NOT_STARTED', 'event_start': '2022-11-27T01:00:00Z', 'competition': 'NBA', 'timestamp': DatetimeWithNanoseconds(2022, 11, 26, 19, 30, 6, 80000, tzinfo=datetime.timezone.utc), 'event_name': 'Houston Rockets - Oklahoma City Thunder'}, {'competition': 'NBA', 'event_name': 'San Antonio Spurs - Los Angeles Lakers', 'event_id': 1018936288, 'timestamp': DatetimeWithNanoseconds(2022, 11, 26, 19, 30, 6, 106000, tzinfo=datetime.timezone.utc), 'event_start': '2022-11-27T01:00:00Z', 'event_status': 'NOT_STARTED'}, {'event_start': '2022-11-26T22:00:00Z', 'event_name': 'Toronto Raptors - Dallas Mavericks', 'timestamp': DatetimeWithNanoseconds(2022, 11, 26, 19, 30, 6, 57000, tzinfo=datetime.timezone.utc), 'competition': 'NBA', 'event_id': 1018936289, 'event_status': 'NOT_STARTED'}, {'timestamp': DatetimeWithNanoseconds(2022, 11, 26, 4, 49, 39, 510000, tzinfo=datetime.timezone.utc), 'event_name': 'Los Angeles Clippers - Denver Nuggets', 'competition': 'NBA', 'event_status': 'STARTED', 'event_id': 1018936316, 'event_start': '2022-11-26T03:41:14Z'}, {'competition': 'NBA', 'event_status': 'STARTED', 'event_name': 'Golden State Warriors - Utah Jazz', 'event_id': 1018936308, 'event_start': '2022-11-26T03:10:44Z', 'timestamp': DatetimeWithNanoseconds(2022, 11, 26, 4, 49, 39, 417000, tzinfo=datetime.timezone.utc)}, {'event_start': '2022-11-26T02:00:00Z', 'event_name': 'Phoenix Suns - Detroit Pistons', 'timestamp': DatetimeWithNanoseconds(2022, 11, 25, 22, 41, 18, 448000, tzinfo=datetime.timezone.utc), 'competition': 'NBA', 'event_id': 1018936262, 'event_status': 'NOT_STARTED'}, {'event_id': 1018936276, 'event_start': '2022-11-26T01:00:00Z', 'timestamp': DatetimeWithNanoseconds(2022, 11, 25, 22, 41, 18, 248000, tzinfo=datetime.timezone.utc), 'competition': 'NBA', 'event_name': 'Houston Rockets - Atlanta Hawks', 'event_status': 'NOT_STARTED'}, {'competition': 'NBA', 'event_name': 'Indiana Pacers - Brooklyn Nets', 'event_id': 1018936285, 'timestamp': DatetimeWithNanoseconds(2022, 11, 25, 22, 41, 18, 292000, tzinfo=datetime.timezone.utc), 'event_start': '2022-11-26T01:00:00Z', 'event_status': 'NOT_STARTED'}, {'timestamp': DatetimeWithNanoseconds(2022, 11, 25, 22, 41, 18, 433000, tzinfo=datetime.timezone.utc), 'event_start': '2022-11-26T01:00:00Z', 'event_name': 'San Antonio Spurs - Los Angeles Lakers', 'competition': 'NBA', 'event_status': 'NOT_STARTED', 'event_id': 1018936286}, {'competition': 'NBA', 'event_name': 'Miami Heat - Washington Wizards', 'timestamp': DatetimeWithNanoseconds(2022, 11, 25, 22, 41, 18, 338000, tzinfo=datetime.timezone.utc), 'event_id': 1018936295, 'event_start': '2022-11-26T01:00:00Z', 'event_status': 'NOT_STARTED'}, {'event_start': '2022-11-26T01:00:00Z', 'event_name': 'Boston Celtics - Sacramento Kings', 'competition': 'NBA', 'timestamp': DatetimeWithNanoseconds(2022, 11, 25, 22, 41, 18, 230000, tzinfo=datetime.timezone.utc), 'event_status': 'NOT_STARTED', 'event_id': 1018936302}, {'event_start': '2022-11-26T01:00:00Z', 'event_name': 'Oklahoma City Thunder - Chicago Bulls', 'timestamp': DatetimeWithNanoseconds(2022, 11, 25, 22, 41, 18, 407000, tzinfo=datetime.timezone.utc), 'competition': 'NBA', 'event_id': 1018936319, 'event_status': 'NOT_STARTED'}, {'event_name': 'Milwaukee Bucks - Cleveland Cavaliers', 'event_id': 1018936322, 'event_start': '2022-11-26T01:00:00Z', 'timestamp': DatetimeWithNanoseconds(2022, 11, 25, 22, 41, 18, 375000, tzinfo=datetime.timezone.utc), 'event_status': 'NOT_STARTED', 'competition': 'NBA'}, {'event_id': 1018936329, 'event_start': '2022-11-26T01:00:00Z', 'timestamp': DatetimeWithNanoseconds(2022, 11, 25, 22, 41, 18, 325000, tzinfo=datetime.timezone.utc), 'competition': 'NBA', 'event_name': 'Memphis Grizzlies - New Orleans Pelicans', 'event_status': 'NOT_STARTED'}, {'event_start': '2022-11-26T00:30:00Z', 'timestamp': DatetimeWithNanoseconds(2022, 11, 25, 22, 41, 18, 199000, tzinfo=datetime.timezone.utc), 'event_name': 'New York Knicks - Portland Trail Blazers', 'competition': 'NBA', 'event_status': 'NOT_STARTED', 'event_id': 1018936292}, {'event_start': '2022-11-26T00:00:00Z', 'event_name': 'Orlando Magic - Philadelphia 76ers', 'competition': 'NBA', 'timestamp': DatetimeWithNanoseconds(2022, 11, 25, 22, 41, 18, 177000, tzinfo=datetime.timezone.utc), 'event_status': 'NOT_STARTED', 'event_id': 1018936265}, {'event_start': '2022-11-25T22:10:31Z', 'event_name': 'Charlotte Hornets - Minnesota Timberwolves', 'competition': 'NBA', 'timestamp': DatetimeWithNanoseconds(2022, 11, 25, 22, 41, 18, 121000, tzinfo=datetime.timezone.utc), 'event_status': 'STARTED', 'event_id': 1018936312}, {'competition': 'NBA', 'event_status': 'STARTED', 'event_name': 'Golden State Warriors - Los Angeles Clippers', 'event_id': 1018936278, 'event_start': '2022-11-24T03:10:36Z', 'timestamp': DatetimeWithNanoseconds(2022, 11, 24, 4, 9, 50, 895000, tzinfo=datetime.timezone.utc)}, {'event_start': '2022-11-24T02:10:29Z', 'event_name': 'Utah Jazz - Detroit Pistons', 'timestamp': DatetimeWithNanoseconds(2022, 11, 24, 4, 9, 50, 831000, tzinfo=datetime.timezone.utc), 'competition': 'NBA', 'event_id': 1018936303, 'event_status': 'STARTED'}, {'competition': 'NBA', 'timestamp': DatetimeWithNanoseconds(2022, 11, 24, 2, 55, 28, 44000, tzinfo=datetime.timezone.utc), 'event_id': 1018936301, 'event_name': 'Oklahoma City Thunder - Denver Nuggets', 'event_start': '2022-11-24T01:10:18Z', 'event_status': 'STARTED'}, {'competition': 'NBA', 'event_id': 1018936299, 'timestamp': DatetimeWithNanoseconds(2022, 11, 24, 2, 55, 28, 8000, tzinfo=datetime.timezone.utc), 'event_start': '2022-11-24T01:10:16Z', 'event_name': 'Milwaukee Bucks - Chicago Bulls', 'event_status': 'STARTED'}, {'event_name': 'San Antonio Spurs - New Orleans Pelicans', 'event_id': 1018936281, 'event_start': '2022-11-24T01:10:15Z', 'timestamp': DatetimeWithNanoseconds(2022, 11, 24, 2, 55, 27, 968000, tzinfo=datetime.timezone.utc), 'event_status': 'STARTED', 'competition': 'NBA'}, {'timestamp': DatetimeWithNanoseconds(2022, 11, 24, 2, 55, 27, 923000, tzinfo=datetime.timezone.utc), 'competition': 'NBA', 'event_id': 1018936284, 'event_status': 'STARTED', 'event_start': '2022-11-24T00:43:40Z', 'event_name': 'Miami Heat - Washington Wizards'}, {'competition': 'NBA', 'event_status': 'NOT_STARTED', 'event_name': 'Toronto Raptors - Brooklyn Nets', 'event_id': 1018936293, 'event_start': '2022-11-24T00:30:00Z', 'timestamp': DatetimeWithNanoseconds(2022, 11, 23, 23, 16, 36, 183000, tzinfo=datetime.timezone.utc)}, {'event_start': '2022-11-24T00:30:00Z', 'event_name': 'Atlanta Hawks - Sacramento Kings', 'timestamp': DatetimeWithNanoseconds(2022, 11, 23, 23, 16, 36, 75000, tzinfo=datetime.timezone.utc), 'competition': 'NBA', 'event_id': 1018936311, 'event_status': 'NOT_STARTED'}, {'event_status': 'NOT_STARTED', 'competition': 'NBA', 'event_name': 'Boston Celtics - Dallas Mavericks', 'event_id': 1018936314, 'event_start': '2022-11-24T00:30:00Z', 'timestamp': DatetimeWithNanoseconds(2022, 11, 23, 23, 16, 36, 130000, tzinfo=datetime.timezone.utc)}, {'timestamp': DatetimeWithNanoseconds(2022, 11, 23, 23, 16, 36, 47000, tzinfo=datetime.timezone.utc), 'event_status': 'NOT_STARTED', 'event_id': 1018936282, 'event_start': '2022-11-24T00:00:00Z', 'event_name': 'Indiana Pacers - Minnesota Timberwolves', 'competition': 'NBA'}, {'event_name': 'Cleveland Cavaliers - Portland Trail Blazers', 'event_status': 'NOT_STARTED', 'event_id': 1018936296, 'event_start': '2022-11-24T00:00:00Z', 'competition': 'NBA', 'timestamp': DatetimeWithNanoseconds(2022, 11, 23, 23, 16, 35, 988000, tzinfo=datetime.timezone.utc)}, {'competition': 'NBA', 'event_id': 1018936309, 'timestamp': DatetimeWithNanoseconds(2022, 11, 23, 23, 16, 35, 921000, tzinfo=datetime.timezone.utc), 'event_name': 'Charlotte Hornets - Philadelphia 76ers', 'event_start': '2022-11-24T00:00:00Z', 'event_status': 'NOT_STARTED'}, {'timestamp': DatetimeWithNanoseconds(2022, 11, 23, 4, 42, 57, 664000, tzinfo=datetime.timezone.utc), 'event_status': 'STARTED', 'event_id': 1018936307, 'event_start': '2022-11-23T03:04:46Z', 'event_name': 'Phoenix Suns - Los Angeles Lakers', 'competition': 'NBA'}, {'event_start': '2022-11-23T02:11:59Z', 'event_name': 'Denver Nuggets - Detroit Pistons', 'competition': 'NBA', 'timestamp': DatetimeWithNanoseconds(2022, 11, 23, 3, 17, 19, 117000, tzinfo=datetime.timezone.utc), 'event_status': 'STARTED', 'event_id': 1018936291}, {'event_name': 'Memphis Grizzlies - Sacramento Kings', 'event_id': 1018936283, 'event_start': '2022-11-23T01:11:03Z', 'timestamp': DatetimeWithNanoseconds(2022, 11, 23, 3, 17, 19, 55000, tzinfo=datetime.timezone.utc), 'event_status': 'STARTED', 'competition': 'NBA'}, {'event_id': 1018936277, 'event_status': 'NOT_STARTED', 'event_start': '2022-11-23T00:30:00Z', 'competition': 'NBA', 'timestamp': DatetimeWithNanoseconds(2022, 11, 22, 22, 3, 18, 277000, tzinfo=datetime.timezone.utc), 'event_name': 'Philadelphia 76ers - Brooklyn Nets'}]
</code></pre>
<p><strong>HTML template</strong></p>
<pre><code>{% block content %}
<table class="table table-striped" style="padding: 15px; width: 1000px">
<thead>
<tr>
<th scope="col">Event ID</th>
<th scope="col">Competition</th>
<th scope="col">Event Name</th>
<th scope="col">Event Start</th>
<th scope="col">Event Status</th>
</tr>
</thead>
{% for xxx_nba in data %}
<tbody>
<tr>
<th>{{xxx_nba.event_id}}</th>
<td>{{xxx_nba.competition}}</td>
<td>{{xxx_nba.event_name}}</td>
<td>{{xxx_nba.event_start}}</td>
<td>{{xxx_nba.event_status}}</td>
</tr>
</tbody>
{% endfor %}
</table>
{% endblock %}
</code></pre>
<p><strong>HTML Output</strong></p>
<pre><code>1018936256 NBA Los Angeles Lakers - Portland Trail Blazers 2022-12-01T03:30:00Z NOT_STARTED
1018936251 NBA Sacramento Kings - Indiana Pacers 2022-12-01T03:00:00Z NOT_STARTED
1018936209 NBA Phoenix Suns - Chicago Bulls 2022-12-01T02:00:00Z NOT_STARTED
1018936229 NBA Utah Jazz - Los Angeles Clippers 2022-12-01T02:00:00Z NOT_STARTED
1018936241 NBA Denver Nuggets - Houston Rockets 2022-12-01T02:00:00Z NOT_STARTED
1018936233 NBA Oklahoma City Thunder - San Antonio Spurs 2022-12-01T01:00:00Z NOT_STARTED
1018936246 NBA Minnesota Timberwolves - Memphis Grizzlies 2022-12-01T01:00:00Z NOT_STARTED
1018936258 NBA New Orleans Pelicans - Toronto Raptors 2022-12-01T01:00:00Z NOT_STARTED
1018936245 NBA New York Knicks - Milwaukee Bucks 2022-12-01T00:41:56Z STARTED
1018936268 NBA Boston Celtics - Miami Heat 2022-12-01T00:40:58Z STARTED
1018936243 NBA Brooklyn Nets - Washington Wizards 2022-12-01T00:40:43Z STARTED
1018936226 NBA Cleveland Cavaliers - Philadelphia 76ers 2022-12-01T00:10:25Z STARTED
1018936242 NBA Orlando Magic - Atlanta Hawks 2022-12-01T00:10:19Z STARTED
1018936272 NBA Portland Trail Blazers - Los Angeles Clippers 2022-11-30T03:00:00Z NOT_STARTED
1018936236 NBA Dallas Mavericks - Golden State Warriors 2022-11-30T00:30:00Z NOT_STARTED
1018936230 NBA Detroit Pistons - New York Knicks 2022-11-30T00:00:00Z NOT_STARTED
1018936255 NBA Los Angeles Lakers - Indiana Pacers 2022-11-29T03:30:00Z NOT_STARTED
1018936259 NBA Sacramento Kings - Phoenix Suns 2022-11-29T03:00:00Z NOT_STARTED
1018936225 NBA Denver Nuggets - Houston Rockets 2022-11-29T02:00:00Z NOT_STARTED
1018936240 NBA Utah Jazz - Chicago Bulls 2022-11-29T02:00:00Z NOT_STARTED
1018936249 NBA New Orleans Pelicans - Oklahoma City Thunder 2022-11-29T01:00:00Z NOT_STARTED
1018936264 NBA Toronto Raptors - Cleveland Cavaliers 2022-11-29T00:30:00Z NOT_STARTED
1018936266 NBA Boston Celtics - Charlotte Hornets 2022-11-29T00:30:00Z NOT_STARTED
1018936275 NBA Brooklyn Nets - Orlando Magic 2022-11-29T00:30:00Z NOT_STARTED
1018936215 NBA Philadelphia 76ers - Atlanta Hawks 2022-11-29T00:00:00Z NOT_STARTED
1018936237 NBA Washington Wizards - Minnesota Timberwolves 2022-11-29T00:00:00Z NOT_STARTED
1018936297 NBA Milwaukee Bucks - Dallas Mavericks 2022-11-28T01:00:00Z NOT_STARTED
</code></pre>
<p>I need to filter by event_start which is formatted like</p>
<blockquote>
<p>2022-12-01T02:00:00Z</p>
</blockquote>
<p>I am trying to reformat that date so that I can use 2022-12-01 section of the date data to filter the games for the day.</p>
<p>I would like to send data to the HTML for only the games that are in the database with the start time (event_start) matching the days date (games_today).</p>
<p>Any help would be apreciated in filtering this data by date and publishing in the HTML document.</p>
|
[
{
"answer_id": 74636305,
"author": "Rob Napier",
"author_id": 97337,
"author_profile": "https://Stackoverflow.com/users/97337",
"pm_score": 2,
"selected": false,
"text": "interactor.getTodos() @MainActor didInit @MainActor MainActor.run {...}"
},
{
"answer_id": 74637330,
"author": "teja_D",
"author_id": 9109095,
"author_profile": "https://Stackoverflow.com/users/9109095",
"pm_score": 1,
"selected": false,
"text": "@MainActor\nfunc updateUI() async {\n // Code to update your UI\n}\n func didInit() {\n Task.detached { // or specify a priority with Task.detached(priority: .background)\n listOfTodo = interactor.getTodos()\n await self.updateUI()\n }\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19124338/"
] |
74,636,071
|
<p>I have a lot of cronjobs I need to set on Kubernetes.
I want a file to manage them all and set them to Kubernetes on deployment. I wish that if I remove a cron from that file it will be removed from Kubernetes too.
Basically, I want to handle the corns like I'm handling them today on the machine (from a cron file that I would deploy). Add, remove and change crons.</p>
<p>I couldn't find a way of doing so. Does someone have an idea?
Library or framework I can use like helm? Or any other solution.</p>
|
[
{
"answer_id": 74636305,
"author": "Rob Napier",
"author_id": 97337,
"author_profile": "https://Stackoverflow.com/users/97337",
"pm_score": 2,
"selected": false,
"text": "interactor.getTodos() @MainActor didInit @MainActor MainActor.run {...}"
},
{
"answer_id": 74637330,
"author": "teja_D",
"author_id": 9109095,
"author_profile": "https://Stackoverflow.com/users/9109095",
"pm_score": 1,
"selected": false,
"text": "@MainActor\nfunc updateUI() async {\n // Code to update your UI\n}\n func didInit() {\n Task.detached { // or specify a priority with Task.detached(priority: .background)\n listOfTodo = interactor.getTodos()\n await self.updateUI()\n }\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4752738/"
] |
74,636,075
|
<p>The second function will take the array as a parameter
How would you send the inner function as a parameter?</p>
<pre><code>const score = [98, 76, 94, 82, 70, 95, 45, 90]
const determinePass = function (threshold) {
return function (array) {
return array.map(function (value) {
return value > threshold ? "pass" : "fail";
})
}
}
</code></pre>
|
[
{
"answer_id": 74636116,
"author": "Leo Ward",
"author_id": 20421592,
"author_profile": "https://Stackoverflow.com/users/20421592",
"pm_score": 0,
"selected": false,
"text": "const score = [98, 76, 94, 82, 70, 95, 45, 90]\n \nfunction determinePass(threshold, array){\n return array.map(function (value) {\n return value > threshold ? \"pass\" : \"fail\";\n });\n}\n\nconsole.log(determinePass(50, score)); const score = [98, 76, 94, 82, 70, 95, 45, 90]\n \nfunction determinePass(threshold){\n return score.map(function (value) {\n return value > threshold ? \"pass\" : \"fail\";\n });\n}\n\nconsole.log(determinePass(50));\n"
},
{
"answer_id": 74636123,
"author": "Layhout",
"author_id": 17308201,
"author_profile": "https://Stackoverflow.com/users/17308201",
"pm_score": 1,
"selected": false,
"text": "determinePass(threshold)(array);\n\n// for example\n// determinePass(50)(score)\n const score = [98, 76, 94, 82, 70, 95, 45, 90]\nconst determinePass = function (threshold) {\n return function (array) {\n return array.map(function (value) {\n return value > threshold ? \"pass\" : \"fail\";\n })\n }\n}\n\nconsole.log(determinePass(50)(score));"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16069370/"
] |
74,636,118
|
<p>I have been searching the stackoverflow community on how to approach the situation below.
There is a table called APPOINTMENTS which two or more APPOINTMENTS may be LINKED to each other. For instance:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>START</th>
<th>END</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>10:00am</td>
<td>12:00pm</td>
</tr>
<tr>
<td>2</td>
<td>12:00pm</td>
<td>01:00pm</td>
</tr>
<tr>
<td>3</td>
<td>04:00pm</td>
<td>04:30pm</td>
</tr>
</tbody>
</table>
</div>
<p>AppointmentModel.kt</p>
<p>So, APOINTMENTS 1 and 2 may be linked to each other, meaning actually they are some sort of the same event divided into two APOINTMENTS (like work and lunch hours).</p>
<p>I have created an association table to keep those rows linked in a many to many relation:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>LINKED_ID</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
<p>AppointmentJoinRef.kt</p>
<p>I would use those associations in a way that the deletion of ID 1 should cascade to ID 2 (vice-versa).</p>
<p>My POJO looks like this right now:</p>
<pre><code>data class ApointmentsPOJO(
@Embedded var Appointment: AppointmentModel,
@Relation(
entity = AppointmentModel::class,
parentColumn = "ID",
entityColumn = "ID",
associateBy = Junction(AppointmentJoinRef::class)
var linkedAppointments: List<AppointmentModel>
</code></pre>
<p>From this code, all I can fetch from table is a list containing repetitions of the "parent" Appointment. I am not able to fetch the linked Appointment, and I am afraid it may be not possible from this approach.
I have also tried to mess it up changing parentColumn and entityColumn both in the Relation and in the Junction parameters.</p>
<p>My question is: What is the correct approach?</p>
|
[
{
"answer_id": 74636116,
"author": "Leo Ward",
"author_id": 20421592,
"author_profile": "https://Stackoverflow.com/users/20421592",
"pm_score": 0,
"selected": false,
"text": "const score = [98, 76, 94, 82, 70, 95, 45, 90]\n \nfunction determinePass(threshold, array){\n return array.map(function (value) {\n return value > threshold ? \"pass\" : \"fail\";\n });\n}\n\nconsole.log(determinePass(50, score)); const score = [98, 76, 94, 82, 70, 95, 45, 90]\n \nfunction determinePass(threshold){\n return score.map(function (value) {\n return value > threshold ? \"pass\" : \"fail\";\n });\n}\n\nconsole.log(determinePass(50));\n"
},
{
"answer_id": 74636123,
"author": "Layhout",
"author_id": 17308201,
"author_profile": "https://Stackoverflow.com/users/17308201",
"pm_score": 1,
"selected": false,
"text": "determinePass(threshold)(array);\n\n// for example\n// determinePass(50)(score)\n const score = [98, 76, 94, 82, 70, 95, 45, 90]\nconst determinePass = function (threshold) {\n return function (array) {\n return array.map(function (value) {\n return value > threshold ? \"pass\" : \"fail\";\n })\n }\n}\n\nconsole.log(determinePass(50)(score));"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6918661/"
] |
74,636,159
|
<p>I am trying to increment the ID value useing the useState hook,but its not incrementing .I have to call the fct two times for the id to be incremented.I was able to see that by console log the object before and after the usestate but i found the result the same</p>
<pre class="lang-js prettyprint-override"><code>function ToDoListApp() {
const [noteList, setNoteList]=useState([])
const [note,setNote]=useState({ noteId: 0 , txt: "", noteState: false })
function addToList(e) {
e.preventDefault();
if(noteList.length===0){
console.log(note)
setNote({noteId: 0 , txt: note.txt ,noteState: false })
setNoteList(noteList=>[...noteList,note])
}else{
console.log(note)
console.log(noteList[noteList.length-1].noteId + 1)
setNote({noteId:noteList[noteList.length-1].noteId + 1,txt:note.txt, noteState:false})
setNoteList(noteList=>[...noteList,note])
console.log(note)
}
}
function deleteItemFromList(e,id){
setNoteList(noteList.filter(note => note.noteId !== id ))
console.log(noteList.length)
}
function handleTheNoteTxt(e) {
e.preventDefault();
setNote({
...note,
txt:e.target.value
})
}
const notesDiplay =noteList.map((note)=>
<Stack key={note.noteId} direction="row" className="note-styling" justifyContent="center" alignItems="center" spacing={2}>
<p>{note.txt} </p>
<p>{note.noteId} </p>
<Button onClick={e => deleteItemFromList(e,note.noteId)} variant="outlined" size='small' >X</Button>
</Stack>
)
return (
<div>
<Stack direction="column" justifyContent="center" alignItems="center">
<Stack className='note-app-container bg1' direction="column" justifyContent="flex-start" alignItems="center" spacing={2} >
<div className='notes-input bg3'>
<TextField autoFocus label="Add your note" variant="standard" value={note.txt}
onChange={handleTheNoteTxt}/>
<Button variant="outlined" size='medium' onClick={addToList}>Add</Button>
</div>
<div className='notes-container bg3'>
{notesDiplay}
</div>
</Stack>
</Stack>
</div>
)
}
export default ToDoListApp`
</code></pre>
|
[
{
"answer_id": 74636316,
"author": "Paulo Fernando",
"author_id": 19223586,
"author_profile": "https://Stackoverflow.com/users/19223586",
"pm_score": 0,
"selected": false,
"text": "function addToList(e) {\n e.preventDefault();\n if (noteList.length === 0) {\n const newNote = { noteId: 0, txt: note.txt, noteState: false };\n setNote(newNote)\n setNoteList([...noteList, newNote])\n } else {\n const newNote = { noteId: noteList[noteList.length - 1].noteId + 1, txt: note.txt, noteState: false };\n setNote(newNote)\n setNoteList([...noteList, newNote])\n }\n }\n"
},
{
"answer_id": 74636370,
"author": "Aadmaa",
"author_id": 12598415,
"author_profile": "https://Stackoverflow.com/users/12598415",
"pm_score": 2,
"selected": true,
"text": "import { useState } from 'react';\nimport { Stack, Button, TextField } from '@mui/material'\n\nfunction ToDoListApp() {\n const [noteList, setNoteList] = useState([]);\n const [nextId, setNextId] = useState(1);\n const [value, setValue] = useState(\"\")\n\n\n function addToList(e) {\n e.preventDefault();\n noteList.push({\n noteId: nextId,\n txt: value,\n noteState: false\n })\n setNextId(val => val + 1);\n setValue(\"\");\n }\n\n\n function deleteItemFromList(e, id) {\n\n setNoteList(noteList.filter(note => note.noteId !== id))\n console.log(noteList.length)\n }\n\n\n const notesDiplay = noteList.map((note) =>\n <Stack key={note.noteId} direction=\"row\" className=\"note-styling\" justifyContent=\"center\" alignItems=\"center\" spacing={2}>\n <p>{note.txt} </p>\n <p>{note.noteId} </p>\n <Button onClick={e => deleteItemFromList(e, note.noteId)} variant=\"outlined\" size='small' >\n X\n </Button>\n </Stack>\n )\n\n return (\n <div>\n <Stack direction=\"column\" justifyContent=\"center\" alignItems=\"center\">\n <Stack className='note-app-container bg1' direction=\"column\" justifyContent=\"flex-start\" alignItems=\"center\" spacing={2} >\n <div className='notes-input bg3'>\n <TextField autoFocus label=\"Add your note\" variant=\"standard\"\n onChange={(e) => setValue(e.target.value) } />\n <Button variant=\"outlined\" size='medium' onClick={addToList}>Add</Button>\n </div>\n <div className='notes-container bg3'>\n {notesDiplay}\n </div>\n </Stack>\n </Stack>\n </div>\n )\n}\n\nexport default ToDoListApp\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20651196/"
] |
74,636,177
|
<p>If a table has a clustered index and a secondary index, the leaf nodes in secondary index contain the attribute value of the clustered index. But what if a table only has non-clustered index? How can a non-clustered index retrieve data without a clustered index?</p>
<pre class="lang-sql prettyprint-override"><code>create table table_without_primary_key(
name varchar(30) not null ,
date datetime not null
);
insert into table_without_primary_key
values ('jack',now());
insert into table_without_primary_key
values ('alice',now());
insert into table_without_primary_key
values ('ribbon',now());
create index time_index
on table_without_primary_key (date);
show index from table_without_primary_key;
</code></pre>
<p>Result:</p>
<pre class="lang-bash prettyprint-override"><code>+---------------------------+------------+------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Visible | Expression |
+---------------------------+------------+------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| table_without_primary_key | 1 | time_index | 1 | date | A | 2 | NULL | NULL | | BTREE | | | YES | NULL |
+---------------------------+------------+------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
1 row in set (0.02 sec)
</code></pre>
<p>Besides, I also heard from somewhere that if a table does not have primary key or unique index, it will use row id to create a clustered index.</p>
<p>But I doubt if it is true, since I found no automatic clustered index on row id from the table I described above.</p>
|
[
{
"answer_id": 74636316,
"author": "Paulo Fernando",
"author_id": 19223586,
"author_profile": "https://Stackoverflow.com/users/19223586",
"pm_score": 0,
"selected": false,
"text": "function addToList(e) {\n e.preventDefault();\n if (noteList.length === 0) {\n const newNote = { noteId: 0, txt: note.txt, noteState: false };\n setNote(newNote)\n setNoteList([...noteList, newNote])\n } else {\n const newNote = { noteId: noteList[noteList.length - 1].noteId + 1, txt: note.txt, noteState: false };\n setNote(newNote)\n setNoteList([...noteList, newNote])\n }\n }\n"
},
{
"answer_id": 74636370,
"author": "Aadmaa",
"author_id": 12598415,
"author_profile": "https://Stackoverflow.com/users/12598415",
"pm_score": 2,
"selected": true,
"text": "import { useState } from 'react';\nimport { Stack, Button, TextField } from '@mui/material'\n\nfunction ToDoListApp() {\n const [noteList, setNoteList] = useState([]);\n const [nextId, setNextId] = useState(1);\n const [value, setValue] = useState(\"\")\n\n\n function addToList(e) {\n e.preventDefault();\n noteList.push({\n noteId: nextId,\n txt: value,\n noteState: false\n })\n setNextId(val => val + 1);\n setValue(\"\");\n }\n\n\n function deleteItemFromList(e, id) {\n\n setNoteList(noteList.filter(note => note.noteId !== id))\n console.log(noteList.length)\n }\n\n\n const notesDiplay = noteList.map((note) =>\n <Stack key={note.noteId} direction=\"row\" className=\"note-styling\" justifyContent=\"center\" alignItems=\"center\" spacing={2}>\n <p>{note.txt} </p>\n <p>{note.noteId} </p>\n <Button onClick={e => deleteItemFromList(e, note.noteId)} variant=\"outlined\" size='small' >\n X\n </Button>\n </Stack>\n )\n\n return (\n <div>\n <Stack direction=\"column\" justifyContent=\"center\" alignItems=\"center\">\n <Stack className='note-app-container bg1' direction=\"column\" justifyContent=\"flex-start\" alignItems=\"center\" spacing={2} >\n <div className='notes-input bg3'>\n <TextField autoFocus label=\"Add your note\" variant=\"standard\"\n onChange={(e) => setValue(e.target.value) } />\n <Button variant=\"outlined\" size='medium' onClick={addToList}>Add</Button>\n </div>\n <div className='notes-container bg3'>\n {notesDiplay}\n </div>\n </Stack>\n </Stack>\n </div>\n )\n}\n\nexport default ToDoListApp\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12639005/"
] |
74,636,203
|
<p>I have a dataframe similar to this:</p>
<pre><code>import pandas as pd
id = [1001, 1002, 1003]
a = [156, 224, 67]
b = [131, 203, 61]
c = [97, 165, 54]
d = [68, 122, 50]
value = [71, 180, 66]
df = pd.DataFrame({'id':id, 'a':a, 'b':b, 'c':c, 'd':d, 'value':value})
</code></pre>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th><strong>a</strong></th>
<th><strong>b</strong></th>
<th><strong>c</strong></th>
<th><strong>d</strong></th>
<th><strong>value</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td>1001</td>
<td>156</td>
<td>131</td>
<td>97</td>
<td>68</td>
<td>71</td>
</tr>
<tr>
<td>1002</td>
<td>224</td>
<td>203</td>
<td>165</td>
<td>122</td>
<td>180</td>
</tr>
<tr>
<td>1003</td>
<td>67</td>
<td>61</td>
<td>54</td>
<td>50</td>
<td>66</td>
</tr>
</tbody>
</table>
</div>
<p>For each row, I would like to evaluate columns <strong>a-d</strong> and within them identify the next lowest and next highest values, as compared to <strong>value</strong>. So in this example, the expected result would look like:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>a</th>
<th>b</th>
<th>c</th>
<th>d</th>
<th>value</th>
<th>nxt_low</th>
<th>nxt_high</th>
</tr>
</thead>
<tbody>
<tr>
<td>1001</td>
<td>156</td>
<td>131</td>
<td>97</td>
<td>68</td>
<td>71</td>
<td>68</td>
<td>97</td>
</tr>
<tr>
<td>1002</td>
<td>224</td>
<td>203</td>
<td>165</td>
<td>122</td>
<td>180</td>
<td>165</td>
<td>203</td>
</tr>
<tr>
<td>1003</td>
<td>67</td>
<td>61</td>
<td>54</td>
<td>50</td>
<td>66</td>
<td>61</td>
<td>67</td>
</tr>
</tbody>
</table>
</div>
<p>I have tried creating a single column with a numpy array from <strong>a-d</strong> and trying to do some operations that way, but I'm not applying it correctly and have been unable to get the desired result. Any help is greatly appreciated.</p>
|
[
{
"answer_id": 74636293,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 3,
"selected": true,
"text": "df.apply(lambda x: x[x < x[-1]].max(), axis=1)\n 0 68\n1 165\n2 61\ndtype: int64\n df[['nxt_low', 'nxt_high']] = df.apply(lambda x: [x[x < x[-1]].max(), x[x > x[-1]].min()], axis=1, result_type='expand')\n df id a b c d value nxt_low nxt_high\n0 1001 156 131 97 68 71 68 97\n1 1002 224 203 165 122 180 165 203\n2 1003 67 61 54 50 66 61 67\n id df[['nxt_low', 'nxt_high']] = df.iloc[:, 1:].apply(lambda x: [x[x < x[-1]].max(), x[x > x[-1]].min()], axis=1, result_type='expand')\n"
},
{
"answer_id": 74636673,
"author": "rhug123",
"author_id": 13802115,
"author_profile": "https://Stackoverflow.com/users/13802115",
"pm_score": 1,
"selected": false,
"text": "cols = ['a','b','c','d']\ndf2 = df[cols].sub(df['value'],axis=0)\ndf = (df.assign(nxt_low = df.where(df2.lt(0)).max(axis=1),\nnxt_high = df.where(df2.gt(0)).min(axis=1)))\n id a b c d value nxt_low nxt_high\n0 1001 156 131 97 68 71 68.0 97.0\n1 1002 224 203 165 122 180 165.0 203.0\n2 1003 67 61 54 50 66 61.0 67.0\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10930703/"
] |
74,636,222
|
<pre><code>list = [4, 7, 11, 15]
</code></pre>
<p>I'm trying to create a function to loop through list items, and find the difference between list[1] and list[0], and then list[2] and list[1], and then list[3] and list[2]... and so on for the entirety of the list. I am thinking of using a for loop but there might be a better way. Thanks.</p>
<p>output would be:</p>
<pre><code>list_diff = [3, 4, 4]
</code></pre>
<pre><code>def difference(list):
for items in list():
or
def difference(list):
list_diff.append(list[1] - list[0])
list_diff.append(list[2] - list[1])
etc.
...
</code></pre>
|
[
{
"answer_id": 74636282,
"author": "Alex Rintt",
"author_id": 11793117,
"author_profile": "https://Stackoverflow.com/users/11793117",
"pm_score": 0,
"selected": false,
"text": "def diff(source):\n return [source[i] - source[i - 1] for i in range(1, len(source))]\n\nprint(diff([4, 7, 11, 15])) # [3, 4, 4]\n"
},
{
"answer_id": 74636284,
"author": "Daniel Hao",
"author_id": 10760768,
"author_profile": "https://Stackoverflow.com/users/10760768",
"pm_score": 2,
"selected": false,
"text": "pairwise \nfrom itertools import pairwise\n\n>>>[b-a for a, b in pairwise(lst)] # List Comprehension\n[3, 4, 4]\n\n# Or just zip()\ndiffs = [b-a for a, b in zip(lst, lst[1:]) ] # no import \n\n"
},
{
"answer_id": 74636319,
"author": "Leo Ward",
"author_id": 20421592,
"author_profile": "https://Stackoverflow.com/users/20421592",
"pm_score": 0,
"selected": false,
"text": "num_list = [4, 7, 11, 15]\n\ndef difference(numbers):\n diff_list = []\n\n for i in range(1, len(numbers)):\n diff_list.append(numbers[i] - numbers[i - 1])\n\n return diff_list\n\n\nprint(difference(num_list)) # [3, 4, 4]\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20649302/"
] |
74,636,232
|
<p>What is the greatest factorial we can calculate using an int in Java 19?</p>
<p>I have found the calculation is correct up to <em>Factorial(12)</em> using an int to stock the result.</p>
<p>Here is the recursive code I use:</p>
<pre><code>public static int Factorial(int n) {
if (n >= 13) {
System.out.println("Trop grand");
return -1;
}
if (n == 0) {
return 1;
} else {
return n * Factorial(n - 1);
}
}
</code></pre>
<p>Do you find the same result?</p>
<p>Subsidiary question: how would you implement the function with a long variable?</p>
<p>I tried everything, expected nothing and nothing special happened. (I have to fill this blank.)</p>
|
[
{
"answer_id": 74637997,
"author": "Spektre",
"author_id": 2521214,
"author_profile": "https://Stackoverflow.com/users/2521214",
"pm_score": 1,
"selected": false,
"text": "int 2^31 = 2147483648\n2^63 = 9223372036854775808\n [ 0.001 ms ] 1! = 1\n[ 0.000 ms ] 2! = 2\n[ 0.000 ms ] 3! = 6\n[ 0.000 ms ] 4! = 24\n[ 0.006 ms ] 5! = 120\n[ 0.006 ms ] 6! = 720\n[ 0.007 ms ] 7! = 5040\n[ 0.005 ms ] 8! = 40320\n[ 0.006 ms ] 9! = 362880\n[ 0.007 ms ] 10! = 3628800\n[ 0.008 ms ] 11! = 39916800\n[ 0.012 ms ] 12! = 479001600\n 2^31 = 2147483648 <-------------------------\n[ 0.013 ms ] 13! = 6227020800\n[ 0.014 ms ] 14! = 87178291200\n[ 0.016 ms ] 15! = 1307674368000\n[ 0.014 ms ] 16! = 20922789888000\n[ 0.015 ms ] 17! = 355687428096000\n[ 0.017 ms ] 18! = 6402373705728000\n[ 0.019 ms ] 19! = 121645100408832000\n[ 0.016 ms ] 20! = 2432902008176640000\n 2^63 = 9223372036854775808 <-------------------------\n[ 0.017 ms ] 21! = 51090942171709440000\n[ 0.019 ms ] 22! = 1124000727777607680000\n 20! unsigned int 21! void fact(int &man,int &exp,int n) // man * 10^exp = n!\n {\n man=1; exp=0;\n if (n<=1) return;\n int i,j;\n for (i=2;i<=n;i++)\n {\n j=i;\n while (j%10==0){j/=10; exp++; }\n man*=j;\n if (man<0){ man=0; exp=0; return; } // overflow\n while (man%10==0){ man/=10; exp++; }\n }\n }\n int i,m,e;\nAnsiString s;\nfor (i=0;i<40;i++)\n {\n fact(m,e,i);\n s=m; while (e){ s+=\"0\"; e--; } // just print m to s and add e times \"0\" at the end\n mm_log->Lines->Add(AnsiString().sprintf(\"%2i! = %s\",i,s)); // output to memo\n }\n 0! = 1\n 1! = 1\n 2! = 2\n 3! = 6\n 4! = 24\n 5! = 120\n 6! = 720\n 7! = 5040\n 8! = 40320\n 9! = 362880\n10! = 3628800\n11! = 39916800\n12! = 479001600\n13! = 6227020800\n14! = 87178291200\n15! = 19184179200 <- this one is overflowed too\n16! = 0\n17! = 0\n18! = 0\n19! = 0\n20! = 0\n21! = 0\n22! = 0\n23! = 0\n24! = 0\n25! = 0\n26! = 0\n27! = 0\n28! = 0\n29! = 0\n30! = 0\n31! = 0\n32! = 0\n33! = 0\n34! = 0\n35! = 0\n36! = 0\n37! = 0\n38! = 0\n39! = 0\n 14! 12!"
},
{
"answer_id": 74644708,
"author": "Old Dog Programmer",
"author_id": 5103317,
"author_profile": "https://Stackoverflow.com/users/5103317",
"pm_score": 1,
"selected": false,
"text": "int public static void factorialTest () {\n int i = 0, r = 1;\n \n while (r > 0) { \n r = factorial (i);\n System.out.println ((i++) + \"! = \" + r);\n }\n} \n\npublic static int factorial(int n) {\n if (n < 0) { return -1; }\n if (n == 0 || n == 1) { return 1; }\n int r = 1;\n try {\n for (int i = 1; i <= n; ++i) {\n r = Math.multiplyExact (r, i);\n }\n } catch (ArithmeticException ex) {\n return -2;\n }\n return r;\n}\n public static int factorial(int n) -1 -2 n int Math ~Exact ArithmeticException try ... catch try ... catch long int long unsigned toUnsignedString unsigned int unsigned long long 0! = 1\n1! = 1\n2! = 2\n3! = 6\n4! = 24\n5! = 120\n6! = 720\n7! = 5040\n8! = 40320\n9! = 362880\n10! = 3628800\n11! = 39916800\n12! = 479001600\n13! = 6227020800\n14! = 87178291200\n15! = 1307674368000\n16! = 20922789888000\n17! = 355687428096000\n18! = 6402373705728000\n19! = 121645100408832000\n20! = 2432902008176640000\n21! = -2\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16974223/"
] |
74,636,266
|
<p>The controller code is:</p>
<pre><code>public async Task<ActionResult<IEnumerable<OutputString>>> Getoutput(AccountByCustomer input)
{
string StoredProc = "exec dbo.Get_ACCOUNT_Data_To_API " +
"@CustomerNumber = '" + input.CustomerNumber + "'" + "," +
"@RequestClass = '" + input.RequestClass + "'" + "," +
"@EmailAddress = '" + input.EmailAddress + "'" + "," +
"@TransactionId = '" + input.TransactionId + "'";
return await _context.OutputString.FromSqlRaw(StoredProc).ToListAsync();
}
</code></pre>
<p>This returns:</p>
<p><a href="https://i.stack.imgur.com/OpoQP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OpoQP.png" alt="Sample Output" /></a></p>
<p>I am trying to return:</p>
<pre><code>{
"Account": [
{
"Token": "8026F271-34FB-47F9-A465-83E9B0EF99FD",
"CustomerNo": "...
(I need to keep this string short as it contains customer data...)
......
}
]
}
</code></pre>
<p>I have tried may ways, convert to string, deserialize, JsonResult -- absolutely NO success.</p>
<p>There are many examples in Stackoverflow, but I cannot make them work.</p>
<p>I assume that I need to convert "outMsg" which is a list to a string.</p>
<pre><code>var x = await _context.OutputString.FromSqlRaw(StoredProc).ToListAsync();
</code></pre>
<p>return Convert.ToString(x);</p>
<p>but that never worked.</p>
<pre><code>Json.Deserialize(x)
</code></pre>
<p>or any variations of it also failed.</p>
<p>I also tried to pass an output parameter to the procedure.</p>
<p>Using .net 7.0</p>
|
[
{
"answer_id": 74637997,
"author": "Spektre",
"author_id": 2521214,
"author_profile": "https://Stackoverflow.com/users/2521214",
"pm_score": 1,
"selected": false,
"text": "int 2^31 = 2147483648\n2^63 = 9223372036854775808\n [ 0.001 ms ] 1! = 1\n[ 0.000 ms ] 2! = 2\n[ 0.000 ms ] 3! = 6\n[ 0.000 ms ] 4! = 24\n[ 0.006 ms ] 5! = 120\n[ 0.006 ms ] 6! = 720\n[ 0.007 ms ] 7! = 5040\n[ 0.005 ms ] 8! = 40320\n[ 0.006 ms ] 9! = 362880\n[ 0.007 ms ] 10! = 3628800\n[ 0.008 ms ] 11! = 39916800\n[ 0.012 ms ] 12! = 479001600\n 2^31 = 2147483648 <-------------------------\n[ 0.013 ms ] 13! = 6227020800\n[ 0.014 ms ] 14! = 87178291200\n[ 0.016 ms ] 15! = 1307674368000\n[ 0.014 ms ] 16! = 20922789888000\n[ 0.015 ms ] 17! = 355687428096000\n[ 0.017 ms ] 18! = 6402373705728000\n[ 0.019 ms ] 19! = 121645100408832000\n[ 0.016 ms ] 20! = 2432902008176640000\n 2^63 = 9223372036854775808 <-------------------------\n[ 0.017 ms ] 21! = 51090942171709440000\n[ 0.019 ms ] 22! = 1124000727777607680000\n 20! unsigned int 21! void fact(int &man,int &exp,int n) // man * 10^exp = n!\n {\n man=1; exp=0;\n if (n<=1) return;\n int i,j;\n for (i=2;i<=n;i++)\n {\n j=i;\n while (j%10==0){j/=10; exp++; }\n man*=j;\n if (man<0){ man=0; exp=0; return; } // overflow\n while (man%10==0){ man/=10; exp++; }\n }\n }\n int i,m,e;\nAnsiString s;\nfor (i=0;i<40;i++)\n {\n fact(m,e,i);\n s=m; while (e){ s+=\"0\"; e--; } // just print m to s and add e times \"0\" at the end\n mm_log->Lines->Add(AnsiString().sprintf(\"%2i! = %s\",i,s)); // output to memo\n }\n 0! = 1\n 1! = 1\n 2! = 2\n 3! = 6\n 4! = 24\n 5! = 120\n 6! = 720\n 7! = 5040\n 8! = 40320\n 9! = 362880\n10! = 3628800\n11! = 39916800\n12! = 479001600\n13! = 6227020800\n14! = 87178291200\n15! = 19184179200 <- this one is overflowed too\n16! = 0\n17! = 0\n18! = 0\n19! = 0\n20! = 0\n21! = 0\n22! = 0\n23! = 0\n24! = 0\n25! = 0\n26! = 0\n27! = 0\n28! = 0\n29! = 0\n30! = 0\n31! = 0\n32! = 0\n33! = 0\n34! = 0\n35! = 0\n36! = 0\n37! = 0\n38! = 0\n39! = 0\n 14! 12!"
},
{
"answer_id": 74644708,
"author": "Old Dog Programmer",
"author_id": 5103317,
"author_profile": "https://Stackoverflow.com/users/5103317",
"pm_score": 1,
"selected": false,
"text": "int public static void factorialTest () {\n int i = 0, r = 1;\n \n while (r > 0) { \n r = factorial (i);\n System.out.println ((i++) + \"! = \" + r);\n }\n} \n\npublic static int factorial(int n) {\n if (n < 0) { return -1; }\n if (n == 0 || n == 1) { return 1; }\n int r = 1;\n try {\n for (int i = 1; i <= n; ++i) {\n r = Math.multiplyExact (r, i);\n }\n } catch (ArithmeticException ex) {\n return -2;\n }\n return r;\n}\n public static int factorial(int n) -1 -2 n int Math ~Exact ArithmeticException try ... catch try ... catch long int long unsigned toUnsignedString unsigned int unsigned long long 0! = 1\n1! = 1\n2! = 2\n3! = 6\n4! = 24\n5! = 120\n6! = 720\n7! = 5040\n8! = 40320\n9! = 362880\n10! = 3628800\n11! = 39916800\n12! = 479001600\n13! = 6227020800\n14! = 87178291200\n15! = 1307674368000\n16! = 20922789888000\n17! = 355687428096000\n18! = 6402373705728000\n19! = 121645100408832000\n20! = 2432902008176640000\n21! = -2\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2660603/"
] |
74,636,276
|
<p>I'm trying to post a request to this API. Here is my code:</p>
<pre><code>import requests
accesstoken = "74e41f9c-8ae6-4ebd-9568-f0c92e83bb54"
authnn = "4ef2db2b-70ea-11ed-9f86-063d0d6fdfb5"
def sender(number):
smstext = "hello test now#"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0','accessToken': accesstoken,'Authorization': authnn}
json_data = {
'content': smstext,
'contentType': 'TEXT',
'from': '+447860002234',
'to': number,
}
response = requests.post('https://api-sandbox.exmpl.io/v1/mms/', headers=headers, json=json_data)
resp =(response.text)
if '"acceptedTime":"' in resp:
print("SENT OK | {} | {}" .format(number,resp))
print(json_data)
time.sleep(10)
else:
print("ERROR => {}".format(resp))
print(json_data)
exit()
if __name__ == "__main__":
nums = input("NUMBERS LIST : ")
op = open(nums, "r")
for i in op:
for i in i.split():
sender(i)
</code></pre>
<p>I get error</p>
<pre><code>ERROR => {"code":"***","message":"Invalid parameter - : to"}
</code></pre>
<p>I printed the JSON to me I see no error :</p>
<pre><code>{'content': 'hello test now#', 'contentType': 'TEXT', 'from': '+447860002234', 'to': '+4113322422787'}
</code></pre>
<p>When I do a POST request like this with preloaded data it works fine.</p>
<pre><code>import requests
accesstoken = "74e41f9c-8ae6-4ebd-9568-f0c92e83bb54"
authnn = "4ef2db2b-70ea-11ed-9f86-063d0d6fdfb5"
def sender(number):
smstext = "hello bebe test hada wewe hehe dede nene tete Ref#"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0','accessToken': accesstoken,'Authorization': authnn}
json_data = {
'content': smstext,
'contentType': 'TEXT',
'from': '+4478623212234',
'to': '+4113322422787',
}
response = requests.post('https://api-sandbox.exmpl.io/v1/mms/', headers=headers, json=json_data)
resp =(response.text)
if '"acceptedTime":"' in resp:
print("SENT OK | {} | {}" .format(number,resp))
print(json_data)
time.sleep(10)
else:
print("ERROR => {}".format(resp))
print(json_data)
exit()
if __name__ == "__main__":
nums = input("NUMBERS LIST : ")
op = open(nums, "r")
for i in op:
for i in i.split():
sender(i)
</code></pre>
<p>I'm expecting to load value in JSON with a for loop.</p>
|
[
{
"answer_id": 74636327,
"author": "mzm",
"author_id": 20564950,
"author_profile": "https://Stackoverflow.com/users/20564950",
"pm_score": -1,
"selected": false,
"text": " json_data = {\n 'content': smstext,\n 'contentType': 'TEXT',\n 'from': '+447860002234',\n 'to': number \n }\n"
},
{
"answer_id": 74641039,
"author": "bigkeefer",
"author_id": 8344023,
"author_profile": "https://Stackoverflow.com/users/8344023",
"pm_score": 0,
"selected": false,
"text": "if __name__ == \"__main__\":\n nums = input(\"NUMBERS LIST : \")\n op = open(nums, \"r\")\n for i in op:\n for i in i.split():\n sender(i)\n sender sender with open('nums', 'r') as f:\n for line in f:\n line_elements = line.strip().split()\n print(line_elements)\n list with open('nums', 'r') as f:\n for line in f:\n line_elements = line.strip().split()\n sender(line_elements[0])\n with open('nums', 'r') as f:\n for number in f.readlines():\n sender(number.strip())\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20651480/"
] |
74,636,322
|
<p>I am trying to install pandas datareader, but I am hit with this error:</p>
<pre><code>Collecting pandas-datareader
Using cached pandas_datareader-0.10.0-py3-none-any.whl (109 kB)
Collecting lxml
Using cached lxml-4.9.1.tar.gz (3.4 MB)
Preparing metadata (setup.py) ... done
Requirement already satisfied: pandas>=0.23 in c:\users\marcu\appdata\local\programs\python\python311\lib\site-packages (from pandas-datareader) (1.5.2)
Requirement already satisfied: requests>=2.19.0 in c:\users\marcu\appdata\local\programs\python\python311\lib\site-packages (from pandas-datareader) (2.28.1)
Requirement already satisfied: python-dateutil>=2.8.1 in c:\users\marcu\appdata\local\programs\python\python311\lib\site-packages (from pandas>=0.23->pandas-datareader) (2.8.2)
Requirement already satisfied: pytz>=2020.1 in c:\users\marcu\appdata\local\programs\python\python311\lib\site-packages (from pandas>=0.23->pandas-datareader) (2022.6)
Requirement already satisfied: numpy>=1.21.0 in c:\users\marcu\appdata\local\programs\python\python311\lib\site-packages (from pandas>=0.23->pandas-datareader) (1.23.5)
Requirement already satisfied: charset-normalizer<3,>=2 in c:\users\marcu\appdata\local\programs\python\python311\lib\site-packages (from requests>=2.19.0->pandas-datareader) (2.1.1)
Requirement already satisfied: idna<4,>=2.5 in c:\users\marcu\appdata\local\programs\python\python311\lib\site-packages (from requests>=2.19.0->pandas-datareader) (3.4)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\users\marcu\appdata\local\programs\python\python311\lib\site-packages (from requests>=2.19.0->pandas-datareader) (1.26.13)
Requirement already satisfied: certifi>=2017.4.17 in c:\users\marcu\appdata\local\programs\python\python311\lib\site-packages (from requests>=2.19.0->pandas-datareader) (2022.9.24)
Requirement already satisfied: six>=1.5 in c:\users\marcu\appdata\local\programs\python\python311\lib\site-packages (from python-dateutil>=2.8.1->pandas>=0.23->pandas-datareader) (1.16.0)
Installing collected packages: lxml, pandas-datareader
DEPRECATION: lxml is being installed using the legacy 'setup.py install' method, because it does not have a 'pyproject.toml' and the 'wheel' package is not installed. pip 23.1 will enforce this behaviour change. A possible replacement is to enable the '--use-pep517' option. Discussion can be found at https://github.com/pypa/pip/issues/8559
Running setup.py install for lxml ... error
error: subprocess-exited-with-error
× Running setup.py install for lxml did not run successfully.
│ exit code: 1
╰─> [96 lines of output]
Building lxml version 4.9.1.
Building without Cython.
Building against pre-built libxml2 andl libxslt libraries
running install
C:\Users\marcu\AppData\Local\Programs\Python\Python311\Lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
warnings.warn(
running build
running build_py
creating build
creating build\lib.win-amd64-cpython-311
creating build\lib.win-amd64-cpython-311\lxml
copying src\lxml\builder.py -> build\lib.win-amd64-cpython-311\lxml
copying src\lxml\cssselect.py -> build\lib.win-amd64-cpython-311\lxml
copying src\lxml\doctestcompare.py -> build\lib.win-amd64-cpython-311\lxml
copying src\lxml\ElementInclude.py -> build\lib.win-amd64-cpython-311\lxml
copying src\lxml\pyclasslookup.py -> build\lib.win-amd64-cpython-311\lxml
copying src\lxml\sax.py -> build\lib.win-amd64-cpython-311\lxml
copying src\lxml\usedoctest.py -> build\lib.win-amd64-cpython-311\lxml
copying src\lxml\_elementpath.py -> build\lib.win-amd64-cpython-311\lxml
copying src\lxml\__init__.py -> build\lib.win-amd64-cpython-311\lxml
creating build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\__init__.py -> build\lib.win-amd64-cpython-311\lxml\includes
creating build\lib.win-amd64-cpython-311\lxml\html
copying src\lxml\html\builder.py -> build\lib.win-amd64-cpython-311\lxml\html
copying src\lxml\html\clean.py -> build\lib.win-amd64-cpython-311\lxml\html
copying src\lxml\html\defs.py -> build\lib.win-amd64-cpython-311\lxml\html
copying src\lxml\html\diff.py -> build\lib.win-amd64-cpython-311\lxml\html
copying src\lxml\html\ElementSoup.py -> build\lib.win-amd64-cpython-311\lxml\html
copying src\lxml\html\formfill.py -> build\lib.win-amd64-cpython-311\lxml\html
copying src\lxml\html\html5parser.py -> build\lib.win-amd64-cpython-311\lxml\html
copying src\lxml\html\soupparser.py -> build\lib.win-amd64-cpython-311\lxml\html
copying src\lxml\html\usedoctest.py -> build\lib.win-amd64-cpython-311\lxml\html
copying src\lxml\html\_diffcommand.py -> build\lib.win-amd64-cpython-311\lxml\html
copying src\lxml\html\_html5builder.py -> build\lib.win-amd64-cpython-311\lxml\html
copying src\lxml\html\_setmixin.py -> build\lib.win-amd64-cpython-311\lxml\html
copying src\lxml\html\__init__.py -> build\lib.win-amd64-cpython-311\lxml\html
creating build\lib.win-amd64-cpython-311\lxml\isoschematron
copying src\lxml\isoschematron\__init__.py -> build\lib.win-amd64-cpython-311\lxml\isoschematron
copying src\lxml\etree.h -> build\lib.win-amd64-cpython-311\lxml
copying src\lxml\etree_api.h -> build\lib.win-amd64-cpython-311\lxml
copying src\lxml\lxml.etree.h -> build\lib.win-amd64-cpython-311\lxml
copying src\lxml\lxml.etree_api.h -> build\lib.win-amd64-cpython-311\lxml
copying src\lxml\includes\c14n.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\config.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\dtdvalid.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\etreepublic.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\htmlparser.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\relaxng.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\schematron.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\tree.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\uri.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\xinclude.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\xmlerror.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\xmlparser.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\xmlschema.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\xpath.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\xslt.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\__init__.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\etree_defs.h -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\lxml-version.h -> build\lib.win-amd64-cpython-311\lxml\includes
creating build\lib.win-amd64-cpython-311\lxml\isoschematron\resources
creating build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\rng
copying src\lxml\isoschematron\resources\rng\iso-schematron.rng -> build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\rng
creating build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\xsl
copying src\lxml\isoschematron\resources\xsl\RNG2Schtrn.xsl -> build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\xsl
copying src\lxml\isoschematron\resources\xsl\XSD2Schtrn.xsl -> build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\xsl
creating build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
copying src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\iso_abstract_expand.xsl -> build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
copying src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\iso_dsdl_include.xsl -> build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
copying src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\iso_schematron_message.xsl -> build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
copying src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\iso_schematron_skeleton_for_xslt1.xsl -> build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
copying src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\iso_svrl_for_xslt1.xsl -> build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
copying src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\readme.txt -> build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
running build_ext
building 'lxml.etree' extension
creating build\temp.win-amd64-cpython-311
creating build\temp.win-amd64-cpython-311\Release
creating build\temp.win-amd64-cpython-311\Release\src
creating build\temp.win-amd64-cpython-311\Release\src\lxml
"C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.32.31326\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -DCYTHON_CLINE_IN_TRACEBACK=0 -Isrc -Isrc\lxml\includes -IC:\Users\marcu\AppData\Local\Programs\Python\Python311\include -IC:\Users\marcu\AppData\Local\Programs\Python\Python311\Include "-IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.32.31326\ATLMFC\include" "-IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.32.31326\include" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\include\um" /Tcsrc\lxml\etree.c /Fobuild\temp.win-amd64-cpython-311\Release\src\lxml\etree.obj -w
cl : Command line warning D9025 : overriding '/W3' with '/w'
etree.c
C:\Users\marcu\AppData\Local\Programs\Python\Python311\include\pyconfig.h(59): fatal error C1083: Cannot open include file: 'io.h': No such file or directory
Compile failed: command 'C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\VC\\Tools\\MSVC\\14.32.31326\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2
creating Users
creating Users\marcu
creating Users\marcu\AppData
creating Users\marcu\AppData\Local
creating Users\marcu\AppData\Local\Temp
"C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.32.31326\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -I/usr/include/libxml2 "-IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.32.31326\ATLMFC\include" "-IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.32.31326\include" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\include\um" /TcC:\Users\marcu\AppData\Local\Temp\xmlXPathInit65mzfy1g.c /FoUsers\marcu\AppData\Local\Temp\xmlXPathInit65mzfy1g.obj
xmlXPathInit65mzfy1g.c
C:\Users\marcu\AppData\Local\Temp\xmlXPathInit65mzfy1g.c(1): fatal error C1083: Cannot open include file: 'libxml/xpath.h': No such file or directory
error: command 'C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\VC\\Tools\\MSVC\\14.32.31326\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2
*********************************************************************************
Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?
*********************************************************************************
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
error: legacy-install-failure
× Encountered error while trying to install package.
╰─> lxml
note: This is an issue with the package mentioned above, not pip.
hint: See above for output from the failure.
</code></pre>
<p>I am using python 3.11.0, and the command I am using to install pandas datareader is "pip install pandas-datareader" Thanks for the help!</p>
<p>It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details.</p>
|
[
{
"answer_id": 74636327,
"author": "mzm",
"author_id": 20564950,
"author_profile": "https://Stackoverflow.com/users/20564950",
"pm_score": -1,
"selected": false,
"text": " json_data = {\n 'content': smstext,\n 'contentType': 'TEXT',\n 'from': '+447860002234',\n 'to': number \n }\n"
},
{
"answer_id": 74641039,
"author": "bigkeefer",
"author_id": 8344023,
"author_profile": "https://Stackoverflow.com/users/8344023",
"pm_score": 0,
"selected": false,
"text": "if __name__ == \"__main__\":\n nums = input(\"NUMBERS LIST : \")\n op = open(nums, \"r\")\n for i in op:\n for i in i.split():\n sender(i)\n sender sender with open('nums', 'r') as f:\n for line in f:\n line_elements = line.strip().split()\n print(line_elements)\n list with open('nums', 'r') as f:\n for line in f:\n line_elements = line.strip().split()\n sender(line_elements[0])\n with open('nums', 'r') as f:\n for number in f.readlines():\n sender(number.strip())\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16534139/"
] |
74,636,367
|
<p>I'm trying to calculate the average in this sample; This example <strong>is working</strong> (but only when I select a specific ID, rather than the avg for every ID limited to 20 entries) but I'm having a hard time remembering how to calculate this for every <strong>id</strong> within the database, rather than the developer specifying the ID explicitly (in this case as <strong>2958</strong>). I.E. It would be optimal to have the following rows (assuming this is grouped by each primary key with a limit of 20 values per avg):</p>
<ul>
<li><p>ID: 1 -> avg 5</p>
</li>
<li><p>ID: 2 -> avg 2</p>
</li>
<li><p>ID: 3 -> avg 7</p>
</li>
<li><p>etc....</p>
<pre><code>select avg(acc.amt)
from (
select acc.amt amt
from main_acc main_acc
join transactions trans on main_acc.id = trans.main_acc_id
where main_acc.id = 2958
order by main_acc.track_id, transactions.transaction_time desc
limit 20
) acc;
</code></pre>
</li>
</ul>
<p>Any help at all would be greatly appreciated. The only relevant columns are the ones shown above, I can add a schema definition if requested. Thank you!</p>
|
[
{
"answer_id": 74636327,
"author": "mzm",
"author_id": 20564950,
"author_profile": "https://Stackoverflow.com/users/20564950",
"pm_score": -1,
"selected": false,
"text": " json_data = {\n 'content': smstext,\n 'contentType': 'TEXT',\n 'from': '+447860002234',\n 'to': number \n }\n"
},
{
"answer_id": 74641039,
"author": "bigkeefer",
"author_id": 8344023,
"author_profile": "https://Stackoverflow.com/users/8344023",
"pm_score": 0,
"selected": false,
"text": "if __name__ == \"__main__\":\n nums = input(\"NUMBERS LIST : \")\n op = open(nums, \"r\")\n for i in op:\n for i in i.split():\n sender(i)\n sender sender with open('nums', 'r') as f:\n for line in f:\n line_elements = line.strip().split()\n print(line_elements)\n list with open('nums', 'r') as f:\n for line in f:\n line_elements = line.strip().split()\n sender(line_elements[0])\n with open('nums', 'r') as f:\n for number in f.readlines():\n sender(number.strip())\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3238707/"
] |
74,636,369
|
<p>I am working with sorting a table in r and i am running into issues.</p>
<p>I have data similar to this</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Sample.ID</th>
<th>SNP1</th>
<th>SNP2</th>
<th>SNP3</th>
<th>SNP4</th>
<th>SNP5</th>
</tr>
</thead>
<tbody>
<tr>
<td>39</td>
<td>GG</td>
<td>NA</td>
<td>CC</td>
<td>NA</td>
<td>GG</td>
</tr>
<tr>
<td>39</td>
<td>NA</td>
<td>CC</td>
<td>NA</td>
<td>NA</td>
<td>NA</td>
</tr>
<tr>
<td>39</td>
<td>NA</td>
<td>NA</td>
<td>NA</td>
<td>TT</td>
<td>NA</td>
</tr>
<tr>
<td>40</td>
<td>CC</td>
<td>NA</td>
<td>NA</td>
<td>CC</td>
<td>CG</td>
</tr>
<tr>
<td>40</td>
<td>NA</td>
<td>NA</td>
<td>TT</td>
<td>NA</td>
<td>NA</td>
</tr>
<tr>
<td>40</td>
<td>NA</td>
<td>GG</td>
<td>NA</td>
<td>NA</td>
<td>NA</td>
</tr>
</tbody>
</table>
</div>
<p>I am expecting something like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Sample.ID</th>
<th>SNP1</th>
<th>SNP2</th>
<th>SNP3</th>
<th>SNP4</th>
<th>SNP5</th>
</tr>
</thead>
<tbody>
<tr>
<td>39</td>
<td>GG</td>
<td>CC</td>
<td>CC</td>
<td>TT</td>
<td>GG</td>
</tr>
<tr>
<td>40</td>
<td>CC</td>
<td>GG</td>
<td>TT</td>
<td>CC</td>
<td>CG</td>
</tr>
</tbody>
</table>
</div>
<p>Any help is appreciated!!</p>
|
[
{
"answer_id": 74636417,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 2,
"selected": false,
"text": "NA NA NA aggregate(quux, quux[\"Sample.ID\"], FUN = function(z) unique(na.omit(z)[1]))\n# Group.1 Sample.ID SNP1 SNP2 SNP3 SNP4 SNP5\n# 1 39 39 GG CC CC TT GG\n# 2 40 40 CC GG TT CC CG\n library(dplyr)\nquux %>%\n group_by(Sample.ID) %>%\n summarize(across(everything(), ~ unique(na.omit(.))[1]))\n# # A tibble: 2 x 6\n# Sample.ID SNP1 SNP2 SNP3 SNP4 SNP5 \n# <int> <chr> <chr> <chr> <chr> <chr>\n# 1 39 GG CC CC TT GG \n# 2 40 CC GG TT CC CG \n library(data.table)\nas.data.table(quux)[, lapply(.SD, function(z) unique(na.omit(z)[1])), by = Sample.ID]\n# Sample.ID SNP1 SNP2 SNP3 SNP4 SNP5\n# <int> <char> <char> <char> <char> <char>\n# 1: 39 GG CC CC TT GG\n# 2: 40 CC GG TT CC CG\n quux <- structure(list(Sample.ID = c(39L, 39L, 39L, 40L, 40L, 40L), SNP1 = c(\"GG\", NA, NA, \"CC\", NA, NA), SNP2 = c(NA, \"CC\", NA, NA, NA, \"GG\"), SNP3 = c(\"CC\", NA, NA, NA, \"TT\", NA), SNP4 = c(NA, NA, \"TT\", \"CC\", NA, NA), SNP5 = c(\"GG\", NA, NA, \"CG\", NA, NA)), class = \"data.frame\", row.names = c(NA, -6L))\n"
},
{
"answer_id": 74636601,
"author": "jared_mamrot",
"author_id": 12957340,
"author_profile": "https://Stackoverflow.com/users/12957340",
"pm_score": 1,
"selected": false,
"text": "library(tidyverse)\n\ndf <- read.table(text = \"Sample.ID SNP1 SNP2 SNP3 SNP4 SNP5\n39 GG NA CC NA GG\n39 NA CC NA NA NA\n39 NA NA NA TT NA\n40 CC NA NA CC CG\n40 NA NA TT NA NA\n40 NA GG NA NA NA\", header = TRUE)\n\ndf %>%\n group_by(Sample.ID) %>%\n fill(everything(), .direction = 'downup') %>%\n distinct()\n#> # A tibble: 2 × 6\n#> # Groups: Sample.ID [2]\n#> Sample.ID SNP1 SNP2 SNP3 SNP4 SNP5 \n#> <int> <chr> <chr> <chr> <chr> <chr>\n#> 1 39 GG CC CC TT GG \n#> 2 40 CC GG TT CC CG\n library(tidyverse)\n\ndf <- read.table(text = \"Sample.ID SNP1 SNP2 SNP3 SNP4 SNP5\n39 GG NA CC NA GG\n39 NA CC NA NA CC\n39 NA NA NA TT NA\n40 CC NA NA CC CG\n40 NA NA TT NA NA\n40 NA GG NA NA NA\", header = TRUE)\n\ndf %>%\n group_by(Sample.ID) %>%\n fill(everything(), .direction = 'downup') %>%\n distinct()\n#> # A tibble: 3 × 6\n#> # Groups: Sample.ID [2]\n#> Sample.ID SNP1 SNP2 SNP3 SNP4 SNP5 \n#> <int> <chr> <chr> <chr> <chr> <chr>\n#> 1 39 GG CC CC TT GG \n#> 2 39 GG CC CC TT CC \n#> 3 40 CC GG TT CC CG\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19745098/"
] |
74,636,393
|
<p>On a call to fib(10), how many times is fib(4) computed?
I can't seem to figure this out, could anyone help?</p>
<pre><code>def fib ( n ):
if n < 3:
return 1
else:
return fib(n-1) + fib(n-2)
</code></pre>
<p>Trying to figure out how many times fib(4) is computed.</p>
|
[
{
"answer_id": 74636455,
"author": "Jason Lee",
"author_id": 15876496,
"author_profile": "https://Stackoverflow.com/users/15876496",
"pm_score": 1,
"selected": false,
"text": "T(n) = the times fib(n) call fib(4) T(4)=1, T(5)=1\n\nT(n) = T(n-1)+T(n-2)\n T(6) = T(5) + T(4) = 2\nT(7) = T(6) + T(5) = 3\nT(8) = T(7) + T(6) = 5\nT(9) = T(8) + T(7) = 8\nT(10) = T(9) + T(8) = 13\n a = 0\n\ndef fib ( n ):\n if(n==4):\n global a\n a=a+1\n print(a)\n\n if n < 3:\n return 1\n\n else:\n return fib(n-1) + fib(n-2)\n\nfib(10)\n"
},
{
"answer_id": 74636665,
"author": "DarrylG",
"author_id": 3066077,
"author_profile": "https://Stackoverflow.com/users/3066077",
"pm_score": 0,
"selected": false,
"text": "def fib (n, cntr = None):\n if cntr is None:\n cntr = {}\n cntr[n] = cntr.get(n, 0) + 1 # update count of current argumenet\n \n if n < 3:\n return 1\n else:\n return fib(n-1, cntr) + fib(n-2, cntr) # mutate cntr in recursive calls\n cntr = {} # Initialize counter\nprint(fib(10, cntr)) # Calculate fib(10)\n# Output: 55\n\nprint(cntr[4]) # get count of number of times fib(4) called\n# Output: 13\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17214961/"
] |
74,636,407
|
<p>I want to add <code>ɨ</code> on the right side of <code>tʂ</code>, <code>tʂ</code>, <code>ʂ</code>, <code>ʐ</code>, <code>ts</code>, <code>ts'</code>, and <code>s</code> when they appear in isolation (when they are not touching other IPA characters). Note that there's a number after each of them, and the lines are surrounded by <code>/</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>const input = `/ʊɔ3 yɛn2 tʂ2 tʂɑʊ3/
/ʊɔ3 mən5 tɕ'ʂ2 tʂɑʊ3/
/pu2 ʂ4 tʂə4 kə4/
/ʂ1/`
const output = input.replace(/(\/|[ ])(tʂ|tʂ\'|ʂ|ʐ|ts|ts\'|s)\d([ ]|\/)/g, '$&ɨ')
console.log(output)</code></pre>
</div>
</div>
</p>
<p>Right now, this is the output:</p>
<pre><code>/ʊɔ3 yɛn2 tʂ2 ɨtʂɑʊ3/
/ʊɔ3 mən5 tɕ'ʂ2 tʂɑʊ3/
/pu2 ʂ4 ɨtʂə4 kə4/
/ʂ1/ɨ
</code></pre>
<p>But what I want is this:</p>
<pre><code>/ʊɔ3 yɛn2 tʂɨ2 tʂɑʊ3/
/ʊɔ3 mən5 tɕ'ʂ2 tʂɑʊ3/
/pu2 ʂɨ4 tʂə4 kə4/
/ʂɨ1/
</code></pre>
|
[
{
"answer_id": 74636475,
"author": "dc-ddfe",
"author_id": 18709498,
"author_profile": "https://Stackoverflow.com/users/18709498",
"pm_score": 1,
"selected": false,
"text": "const input = `/ʊɔ3 yɛn2 tʂ2 tʂɑʊ3/\n/ʊɔ3 mən5 tɕ'ʂ2 tʂɑʊ3/\n/pu2 ʂ4 tʂə4 kə4/\n/ʂ1/`\n\nconst output = input.replace(/(\\/|[ ])(tʂ|tʂ\\'|ʂ|ʐ|ts|ts\\'|s)(\\d([ ]|\\/))/g, '$1$2ɨ$3')\nconsole.log(output)"
},
{
"answer_id": 74638554,
"author": "JvdV",
"author_id": 9758194,
"author_profile": "https://Stackoverflow.com/users/9758194",
"pm_score": 2,
"selected": false,
"text": "([/ ](?:t[ʂs]'?|[ʂʐs])(?=\\d+[ /]))\n $1ɨ ([/ ] (?:t[ʂs]'?|[ʂʐs]) (?=\\d+[ /]) ) const input = `/ʊɔ3 yɛn2 tʂ2 tʂɑʊ3/\n/ʊɔ3 mən5 tɕ'ʂ2 tʂɑʊ3/\n/pu2 ʂ4 tʂə4 kə4/\n/ʂ1/`\n\nconst output = input.replace(/([/ ](?:t[ʂs]'?|[ʂʐs])(?=\\d+[ /]))/g, '$1ɨ')\nconsole.log(output)"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122536/"
] |
74,636,410
|
<p>I would like to send a dm to a user just by using their user id that I copied from their profile.</p>
<p>This is the code that I made, but it didn't work.</p>
<pre><code>@client.command()
async def dm(userID, *, message):
user = client.get_user(userID)
await user.send(message)
</code></pre>
<p>This is the error that appeared:</p>
<p>discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'send'</p>
|
[
{
"answer_id": 74636475,
"author": "dc-ddfe",
"author_id": 18709498,
"author_profile": "https://Stackoverflow.com/users/18709498",
"pm_score": 1,
"selected": false,
"text": "const input = `/ʊɔ3 yɛn2 tʂ2 tʂɑʊ3/\n/ʊɔ3 mən5 tɕ'ʂ2 tʂɑʊ3/\n/pu2 ʂ4 tʂə4 kə4/\n/ʂ1/`\n\nconst output = input.replace(/(\\/|[ ])(tʂ|tʂ\\'|ʂ|ʐ|ts|ts\\'|s)(\\d([ ]|\\/))/g, '$1$2ɨ$3')\nconsole.log(output)"
},
{
"answer_id": 74638554,
"author": "JvdV",
"author_id": 9758194,
"author_profile": "https://Stackoverflow.com/users/9758194",
"pm_score": 2,
"selected": false,
"text": "([/ ](?:t[ʂs]'?|[ʂʐs])(?=\\d+[ /]))\n $1ɨ ([/ ] (?:t[ʂs]'?|[ʂʐs]) (?=\\d+[ /]) ) const input = `/ʊɔ3 yɛn2 tʂ2 tʂɑʊ3/\n/ʊɔ3 mən5 tɕ'ʂ2 tʂɑʊ3/\n/pu2 ʂ4 tʂə4 kə4/\n/ʂ1/`\n\nconst output = input.replace(/([/ ](?:t[ʂs]'?|[ʂʐs])(?=\\d+[ /]))/g, '$1ɨ')\nconsole.log(output)"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19282100/"
] |
74,636,413
|
<p>I'm trying to store all the <code>likedUserIds</code>s and <code>dislikedUserIds</code>s in local storage but for some reason, it's not even hitting the <code>if()</code> statement. The <code>likedPhotoUserId</code> function parameter indeed has a value, so why's it not hitting the first <code>if()</code>?</p>
<p>Any feedback would be appreciated!</p>
<pre><code>const handleLikesBasedOnUserId = (likedPhotoUserId) => {
console.log(likedPhotoUserId); // value is present
// dislike
if(likedPhotoUserId) {
// if the user id exists
if(localStorage.getItem('dislikedUserIds')) {
console.log("inside if");
// split the existing values into an array
let vals = localStorage.getItem('dislikedUserIds').split(',');
// if the value has not already been added
if (!vals.includes(likedPhotoUserId)) {
// add the value to the array
vals.push(likedPhotoUserId);
// sort the array
vals.sort();
// join the values into a delimeted string and store it
localStorage.setItem('dislikedUserIds', vals.join(','));
} else {
console.log("inside else");
// the key doesn't exist yet, add it and the new value
localStorage.setItem('dislikedUserIds', likedPhotoUserId);
}
}
} else {
// like
if(likedPhotoUserId) {
// if the user id exists
if(localStorage.getItem('likedUserIds')) {
console.log("inside if");
// split the existing values into an array
let vals = localStorage.getItem('likedUserIds').split(',');
// if the value has not already been added
if (!vals.includes(likedPhotoUserId)) {
// add the value to the array
vals.push(likedPhotoUserId);
// sort the array
vals.sort();
// join the values into a delimeted string and store it
localStorage.setItem('likedUserIds', vals.join(','));
} else {
console.log("inside else");
// the key doesn't exist yet, add it and the new value
localStorage.setItem('likedUserIds', likedPhotoUserId);
}
}
}
}
};
</code></pre>
|
[
{
"answer_id": 74636475,
"author": "dc-ddfe",
"author_id": 18709498,
"author_profile": "https://Stackoverflow.com/users/18709498",
"pm_score": 1,
"selected": false,
"text": "const input = `/ʊɔ3 yɛn2 tʂ2 tʂɑʊ3/\n/ʊɔ3 mən5 tɕ'ʂ2 tʂɑʊ3/\n/pu2 ʂ4 tʂə4 kə4/\n/ʂ1/`\n\nconst output = input.replace(/(\\/|[ ])(tʂ|tʂ\\'|ʂ|ʐ|ts|ts\\'|s)(\\d([ ]|\\/))/g, '$1$2ɨ$3')\nconsole.log(output)"
},
{
"answer_id": 74638554,
"author": "JvdV",
"author_id": 9758194,
"author_profile": "https://Stackoverflow.com/users/9758194",
"pm_score": 2,
"selected": false,
"text": "([/ ](?:t[ʂs]'?|[ʂʐs])(?=\\d+[ /]))\n $1ɨ ([/ ] (?:t[ʂs]'?|[ʂʐs]) (?=\\d+[ /]) ) const input = `/ʊɔ3 yɛn2 tʂ2 tʂɑʊ3/\n/ʊɔ3 mən5 tɕ'ʂ2 tʂɑʊ3/\n/pu2 ʂ4 tʂə4 kə4/\n/ʂ1/`\n\nconst output = input.replace(/([/ ](?:t[ʂs]'?|[ʂʐs])(?=\\d+[ /]))/g, '$1ɨ')\nconsole.log(output)"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9903235/"
] |
74,636,418
|
<p>I am learning Unity by building a simple card game.</p>
<p>I trying to display one card at the time using random function on the game object array.</p>
<p>I am using UI image component with sprite assets assigned to it while calling DealMyNewCard function on the button component.</p>
<p>I am expecting to see one card displayed at the time while still being able to repeat the process of randomly dealing the card.</p>
<pre><code>using UnityEngine;
public class DealCard : MonoBehaviour
{
public GameObject[] dealtCard;
public int cardGenerate;
public void DealMyNewCard(){
cardGenerate = Random.Range(2, 6);
dealtCard[cardGenerate].SetActive(!dealtCard[cardGenerate].activeSelf);
}
}
</code></pre>
<p>The issue arises when I reach the top or higher card of the array because it overrides the other hierarchy components of the object and prevents the display of previous cards.</p>
|
[
{
"answer_id": 74636511,
"author": "Willard Peng",
"author_id": 10259001,
"author_profile": "https://Stackoverflow.com/users/10259001",
"pm_score": 0,
"selected": false,
"text": "public void DealMyNewCard()\n{\n\n cardGenerate = Random.Range(2, 6);\n HideAllCards();\n dealtCard[cardGenerate].SetActive(true);\n}\n\nprivate void HideAllCards()\n{\n foreach (var card in dealtCard)\n {\n card.SetActive(false);\n }\n}\n SetActive()"
},
{
"answer_id": 74636797,
"author": "Willard Peng",
"author_id": 10259001,
"author_profile": "https://Stackoverflow.com/users/10259001",
"pm_score": 2,
"selected": true,
"text": "using UnityEngine;\n\npublic class DealCard : MonoBehaviour\n{\n public GameObject[] dealtCard;\n public int cardGenerate;\n\n[ContextMenu(\"Test DealMyNewCard()\")] //for inspector test use\npublic void DealMyNewCard()\n{\n cardGenerate = Random.Range(1, dealtCard.Length);\n HideAllCards();\n dealtCard[cardGenerate].SetActive(true);\n}\n\nprivate void HideAllCards()\n{\n foreach (var card in dealtCard)\n {\n card.SetActive(false);\n }\n}\n}\n"
},
{
"answer_id": 74639050,
"author": "derHugo",
"author_id": 7111561,
"author_profile": "https://Stackoverflow.com/users/7111561",
"pm_score": 1,
"selected": false,
"text": "public void DealMyNewCard()\n{\n // btw I would start at 0 if you want to ever get the first item as well\n cardGenerate = Random.Range(0, dealtCard.Length);\n\n // iterate through the card once\n for(var i = 0; i < dealtCard.Length; i++)\n {\n // set item active if it is the random index otherwise set inactive\n dealtCard[i].SetActive(i == cardGenerate);\n }\n}\n private GameObject currentCard;\n\nprivate void Awake()\n{\n // Initially deactivate all ONCE\n foreach (var card in dealtCard)\n {\n card.SetActive(false);\n }\n}\n\npublic void DealMyNewCard()\n{\n // if there is a current card\n if(currentCard)\n {\n // disable that one - no other card should be active anyway\n currentCard.SetActive(false);\n }\n\n cardGenerate = Random.Range(0, dealtCard.Length);\n \n // store the new card and enable it\n currentCard = dealtCard[cardGenerate];\n currentCard.SetActive(true);\n}\n using System.Linq;\n\n...\n\ncurrentCard = dealtCard.Where(c => c != currentCard).OrderBy(c => Random.value).First();\nurrentCard.SetActive(true);\n public GameObject[] dealtCard;\n\nprivate IEnumerator<GameObject> shuffledCards;\nprivate GameObject currentCard;\n\nprivate void Awake()\n{\n // Initially deactivate all ONCE\n foreach (var card in dealtCard)\n {\n card.SetActive(false);\n }\n\n // order cards randomly and store es enumerator\n shuffledCards = dealtCard.OrderBy(c => UnityEngine.Random.value).GetEnumerator();\n}\n\npublic void DealMyNewCard()\n{\n // if there is a current card\n if (currentCard)\n {\n // disable that one - no other card should be active anyway\n currentCard.SetActive(false);\n }\n\n // try to move to the next card\n // if this returns falls you reached the end of the deck\n if (!shuffledCards.MoveNext())\n {\n Debug.LogError(\"No more cards available!\");\n return;\n }\n\n // store the new card and enable it\n currentCard = shuffledCards.Current;\n currentCard.SetActive(true);\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6802953/"
] |
74,636,426
|
<p>I want to keep the first 2 elements in a Vec, and release unused memory, here is my code:</p>
<pre><code>let data: Vec<usize> = vec![1,2,3,4,5,6];//produced by another function
data.truncate(2);
data.shrink_to_fit();
</code></pre>
<p>I wonder is there an easier way to do this task?</p>
|
[
{
"answer_id": 74636447,
"author": "tymtam",
"author_id": 581076,
"author_profile": "https://Stackoverflow.com/users/581076",
"pm_score": 0,
"selected": false,
"text": "let v = vec![v[0], v[1]];\n vec![&v[0], &v[1]] push insert push insert len()==capacity() Vec"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1805497/"
] |
74,636,441
|
<p>I have implemented a Transformer encoder in keras using the template provided by Francois Chollet <a href="https://github.com/fchollet/deep-learning-with-python-notebooks/blob/master/chapter11_part03_transformer.ipynb" rel="nofollow noreferrer">here</a>. After I train the model I save it using <code>model.save</code>, but when I load it again for inference I find that the weights seem to be random again, and therefore my model loses all inference ability.</p>
<p>I have looked at similar issues on SO and Github, and applied the following suggestions, but still getting the same issue:</p>
<ol>
<li>Use the <code>@tf.keras.utils.register_keras_serializable()</code> decorator on the class.</li>
<li>Make sure <code>**kwargs</code> is in the init call</li>
<li>Make sure the custom layer has <code>get_config</code> and <code>from_config</code> methods.</li>
<li>Use <code>custom_object_scope</code> to load model.</li>
</ol>
<p>Below is a minimally reproducible example to replicate the issue. How do I change it so that the model weights save correctly?</p>
<pre><code>import numpy as np
from tensorflow import keras
import tensorflow as tf
from tensorflow.keras import layers
from keras.models import load_model
from keras.utils import custom_object_scope
@tf.keras.utils.register_keras_serializable()
class TransformerEncoder(layers.Layer):
def __init__(self, embed_dim, dense_dim, num_heads, **kwargs):
super().__init__(**kwargs)
self.embed_dim = embed_dim
self.dense_dim = dense_dim
self.num_heads = num_heads
self.attention = layers.MultiHeadAttention(
num_heads=num_heads, key_dim=embed_dim)
self.dense_proj = keras.Sequential(
[
layers.Dense(dense_dim, activation="relu"),
layers.Dense(embed_dim),
]
)
self.layernorm_1 = layers.LayerNormalization()
self.layernorm_2 = layers.LayerNormalization()
def call(self, inputs, mask=None):
if mask is not None:
mask = mask[:, tf.newaxis, :]
attention_output = self.attention(
inputs, inputs, attention_mask=mask)
proj_input = self.layernorm_1(inputs + attention_output)
proj_output = self.dense_proj(proj_input)
return self.layernorm_2(proj_input + proj_output)
def get_config(self):
config = super().get_config()
config.update({
"embed_dim": self.embed_dim,
"num_heads": self.num_heads,
"dense_dim": self.dense_dim,
})
return config
@classmethod
def from_config(cls, config):
return cls(**config)
# Create simple model:
encoder = TransformerEncoder(embed_dim=2, dense_dim=2, num_heads=1)
inputs = keras.Input(shape=(2, 2), batch_size=None, name="test_inputs")
x = encoder(inputs)
x = layers.Flatten()(x)
outputs = layers.Dense(1, activation="linear")(x)
model = keras.Model(inputs, outputs)
# Fit the model and save it:
np.random.seed(42)
X = np.random.rand(10, 2, 2)
y = np.ones(10)
model.compile(optimizer=keras.optimizers.Adam(), loss="mean_squared_error")
model.fit(X, y, epochs=2, batch_size=1)
model.save("./test_model")
# Load the saved model:
with custom_object_scope({
'TransformerEncoder': TransformerEncoder
}):
loaded_model = load_model("./test_model")
print(model.weights[0].numpy())
print(loaded_model.weights[0].numpy())
</code></pre>
|
[
{
"answer_id": 74637625,
"author": "Jirayu Kaewprateep",
"author_id": 7848579,
"author_profile": "https://Stackoverflow.com/users/7848579",
"pm_score": -1,
"selected": false,
"text": "import tensorflow as tf\n\nclass MyDenseLayer(tf.keras.layers.Layer):\n def __init__(self, num_outputs):\n super(MyDenseLayer, self).__init__()\n self.num_outputs = num_outputs\n \n def build(self, input_shape):\n \"\"\" initialize weights with randomize numbers \"\"\"\n min_size_init = tf.keras.initializers.RandomUniform(minval=1, maxval=5, seed=None)\n self.kernel = self.add_weight(shape=[int(input_shape[-1]), self.num_outputs],\n initializer = min_size_init, trainable=True)\n \n def call(self, inputs):\n return tf.matmul(inputs, self.kernel)\n\n\nstart = 3\nlimit = 33\ndelta = 3\n\n# Create DATA\nsample = tf.range(start, limit, delta)\nsample = tf.cast( sample, dtype=tf.float32 )\n\n# Initail, ( 10, 1 )\nsample = tf.constant( sample, shape=( 10, 1 ) )\nlayer = MyDenseLayer(10)\ndata = layer(sample)\n ### 1st round ###\n# [array([[-0.07862139, -0.45416605, -0.53606 , 0.18597281, 0.2919714 ,\n # -0.27334914, 0.60890776, -0.3856985 , 0.58052486, -0.5634572 ]], dtype=float32)]\n \n### 2nd round ###\n# [array([[ 0.5949032 , 0.05113244, -0.51997787, 0.26252705, -0.09235346,\n # -0.35243294, -0.0187515 , -0.12527376, 0.22348166, 0.37051445]], dtype=float32)]\n \n### 3rd round ###\n# [array([[-0.6654639 , -0.46027896, -0.48666477, -0.23095328, 0.30391783,\n # 0.21867174, -0.5405392 , -0.45399982, -0.22143698, 0.66893476]], dtype=float32)]\n layer.build([1]) \nprint( data )\nprint( layer.get_weights() )\n ### 1st round ###\n# [array([[ 0.73738164, 0.14095825, -0.5416008 , -0.35084447, -0.35209572,\n # -0.35504425, 0.1692887 , 0.2611189 , 0.43355125, -0.3325353 ]], dtype=float32)]\n \n### 2nd round ###\n# [array([[ 0.5949032 , 0.05113244, -0.51997787, 0.26252705, -0.09235346,\n # -0.35243294, -0.0187515 , -0.12527376, 0.22348166, 0.37051445]], dtype=float32)]\n \n### 3rd round ###\n# [array([[-0.6654639 , -0.46027896, -0.48666477, -0.23095328, 0.30391783,\n # 0.21867174, -0.5405392 , -0.45399982, -0.22143698, 0.66893476]], dtype=float32)]\n \"\"\" initialize weights with values ones \"\"\"\n min_size_init = tf.keras.initializers.Ones()\n ### 1st round ###\n# tf.Tensor(\n# [[ 3. 3. 3. 3. 3. 3. 3. 3. 3. 3.]\n # [ 6. 6. 6. 6. 6. 6. 6. 6. 6. 6.]\n # [ 9. 9. 9. 9. 9. 9. 9. 9. 9. 9.]\n # [12. 12. 12. 12. 12. 12. 12. 12. 12. 12.]\n # [15. 15. 15. 15. 15. 15. 15. 15. 15. 15.]\n # [18. 18. 18. 18. 18. 18. 18. 18. 18. 18.]\n # [21. 21. 21. 21. 21. 21. 21. 21. 21. 21.]\n # [24. 24. 24. 24. 24. 24. 24. 24. 24. 24.]\n # [27. 27. 27. 27. 27. 27. 27. 27. 27. 27.]\n # [30. 30. 30. 30. 30. 30. 30. 30. 30. 30.]], shape=(10, 10), dtype=float32)\n# [array([[1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]], dtype=float32)]\n\n### 2nd round ###\n# tf.Tensor(\n# [[ 3. 3. 3. 3. 3. 3. 3. 3. 3. 3.]\n # [ 6. 6. 6. 6. 6. 6. 6. 6. 6. 6.]\n # [ 9. 9. 9. 9. 9. 9. 9. 9. 9. 9.]\n # [12. 12. 12. 12. 12. 12. 12. 12. 12. 12.]\n # [15. 15. 15. 15. 15. 15. 15. 15. 15. 15.]\n # [18. 18. 18. 18. 18. 18. 18. 18. 18. 18.]\n # [21. 21. 21. 21. 21. 21. 21. 21. 21. 21.]\n # [24. 24. 24. 24. 24. 24. 24. 24. 24. 24.]\n # [27. 27. 27. 27. 27. 27. 27. 27. 27. 27.]\n # [30. 30. 30. 30. 30. 30. 30. 30. 30. 30.]], shape=(10, 10), dtype=float32)\n# [array([[1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]], dtype=float32)]\n temp = tf.random.normal([10], 1, 0.2, tf.float32)\ntemp = np.asarray(temp) * np.asarray([ coefficient_0, coefficient_1, coefficient_2, coefficient_3, coefficient_4, coefficient_5, coefficient_6, coefficient_7, coefficient_8, coefficient_9 ])\ntemp = tf.nn.softmax(temp)\naction = int(np.argmax(temp)) \n"
},
{
"answer_id": 74637921,
"author": "AndrzejO",
"author_id": 7246805,
"author_profile": "https://Stackoverflow.com/users/7246805",
"pm_score": 1,
"selected": false,
"text": "load_weights __init__ class TransformerEncoder(layers.Layer):\n def __init__(self, embed_dim, dense_dim, num_heads, attention_config=None, dense_proj_config=None, **kwargs):\n super().__init__(**kwargs)\n self.embed_dim = embed_dim\n self.dense_dim = dense_dim\n self.num_heads = num_heads\n self.attention = layers.MultiHeadAttention(\n num_heads=num_heads, key_dim=embed_dim) \\\n if attention_config is None else layers.MultiHeadAttention.from_config(attention_config)\n self.dense_proj = keras.Sequential(\n [\n layers.Dense(dense_dim, activation=\"relu\"),\n layers.Dense(embed_dim),\n ]\n ) if dense_proj_config is None else keras.Sequential.from_config(dense_proj_config)\n ...\n\n def call(self, inputs, mask=None):\n ...\n\n def get_config(self):\n config = super().get_config()\n config.update({\n \"embed_dim\": self.embed_dim,\n \"num_heads\": self.num_heads,\n \"dense_dim\": self.dense_dim,\n \"attention_config\": self.attention.get_config(),\n \"dense_proj_config\": self.dense_proj.get_config(),\n })\n return config\n [[[-0.810745 -0.14727005]]\n\n[[ 0.8542909 0.09689581]]]\n[[[-0.810745 -0.14727005]]\n\n[[ 0.8542909 0.09689581]]]\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6286540/"
] |
74,636,539
|
<p>My son is learning Python. He's only ten and just starting out and he's gotten stuck. He has a syntax error - can anyone help please? It's on line 18.</p>
<p>The error displayed is as follows:</p>
<p>File "main.py", line 23
elif player_choice == "2":
^
SyntaxError: invalid syntax
</p>
<p>Please see code below:</p>
<pre><code># choose a chest
import random
exitChoice = ("Nothing")
while exitChoice != "EXIT":
print("You find four dusty treasure chests in the attic.")
print("You have one rusted key which seems to be giving")
print("You the urge to open the chest but there is only one key")
print("and four chests, which chest will you open?")
player_choice = input("Choose 1, 2, 3, or 4...")
if player_choice == "1":
print("The chest contains billions of dollars but the money seems to")
print("be engulfed in a strange green light which happens to be")
print("radioactive!")
print("You start feeling light headed and then die!")
print("GAME OVER!")
elif player_choice == "2":
print("The chest contains a golden amulet emitting a powerful energy aswell as a metal glove with black particles surrounding it. you can only choose one, what will your choice be.")
box_choice = input ("Choose, amulet or glove")
if box_choice == "amulet":
print("The amulet contains incredible power but you coudn't handle this power so you went ballistic destroying hundreds of galaxys but you ended up destroying killing all human kind but the amulet would only work as long as earth was around so the amulet exploded destroying you and the universe ")
print("GAME OVER!")
elif box_choice =="glove":
print("When you put the glove on black ooze came up and out the glove covering your whole arm. You started wreaking havoc on the world. However you realised what you were doing and thought to yourself why am I doing this i had a great life. Happines took over and you spent the rest of your days with your family happier then ever")
print("Thanks for playing!")
else:
print("Error")
elif player_choice =="3":
print("You see a small black stone at the bottom of the chest so you pick it up. The stone turns into a black hole which destroys every thing in exsitence.")
print("GAME OVER!")
elif player_choice =="4":
print("A genie comes out the chest and says if you can guess the number im thinking of between 1 and 10 I will grant you eternal happienes.")
number = int(input("What number do you choose?" ))
if number =="random.randint(1,10)":
print("Well done now for your eternal happienes.")
print("'Thanks for playing!")
else:
print("Incorrect now I must make you suffer by enflicting you with eternal pain mwahahah!")
print("GAME OVER!")
else:
print("Sorry, you didn't enter 1, 2, 3 or 4.")
exitChoice = input("press return to play again, or type EXIT to leave.")
</code></pre>
<p>Not sure what other details I can add.</p>
|
[
{
"answer_id": 74636575,
"author": "John Gordon",
"author_id": 494134,
"author_profile": "https://Stackoverflow.com/users/494134",
"pm_score": 1,
"selected": false,
"text": "if player_choice == \"1\":\n print(\"The chest contains billions of dollars but the money seems to\")\nprint(\"be engulfed in a strange green light which happens to be\")\nprint(\"radioactive!\")\nprint(\"You start feeling light headed and then die!\")\nprint(\"GAME OVER!\")\n if print(\"The chest ..\") if if print(\"be engulfed...\") if elif if if"
},
{
"answer_id": 74637245,
"author": "ThatCSFresher",
"author_id": 19493334,
"author_profile": "https://Stackoverflow.com/users/19493334",
"pm_score": 0,
"selected": false,
"text": "if(a<b)\n{\n printf(\"a is less than b\");\n}\nelse{\nprintf(\"a is greater than b\");\n}\n {} \nif a>b:\n print(a)\nprint(b)\n if a>b:\n print(a)\n print(b)\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20651769/"
] |
74,636,557
|
<p>Given a 2D array I am looking for an elegant and performant way to divide up a 1D array of <code>words</code> given a start index and end index.</p>
<pre><code>// pass this in as an arg
var trim = [
[3, 4], // remove two words at index 3 and 4
[9, 10] // remove two words at index 9 and 10
]; // use this to reformat
var words = [
{ word: "hello", st: 0 },
{ word: "stack-overflow", st: 0.5 },
{ word: "lets", st: 1 },
{ word: "remove", st: 1.5 },
{ word: "some", st: 2 },
{ word: "words", st: 2.5 },
{ word: "efficiently", st: 3 },
{ word: "lets", st: 3.5 },
{ word: "do", st: 4 },
{ word: "it", st: 4.5 },
{ word: "yay", st: 5 }
];
// this is the result I am looking for
var result = [
[
{ word: "hello", st: 0 },
{ word: "stack-overflow", st: 0.5 },
{ word: "lets", st: 1 }
],
[
{ word: "words", st: 2.5 },
{ word: "efficiently", st: 3 },
{ word: "lets", st: 3.5 },
{ word: "do", st: 4 }
]
];
</code></pre>
<p>This is the best I could do, missing return as 2D array</p>
<pre><code>words.reduce((acc, curr, i) => {
const wordBetween = trim.some(t => {
return t[0] <= i && t[1] >= i
});
console.log({wordBetween, curr})
if (wordBetween) {
return acc;
}
return [...acc, curr]
}, [])
</code></pre>
|
[
{
"answer_id": 74636637,
"author": "danh",
"author_id": 294949,
"author_profile": "https://Stackoverflow.com/users/294949",
"pm_score": 0,
"selected": false,
"text": "const arrayWithoutIndexes = (array, indexes) => {\n return array.filter((el, i) => !indexes.includes(i));\n};\n\nvar words = [\n { word: \"hello\", st: 0 },\n { word: \"stack-overflow\", st: 0.5 },\n { word: \"lets\", st: 1 },\n { word: \"remove\", st: 1.5 },\n { word: \"some\", st: 2 },\n { word: \"words\", st: 2.5 },\n { word: \"efficiently\", st: 3 },\n { word: \"lets\", st: 3.5 },\n { word: \"do\", st: 4 },\n { word: \"it\", st: 4.5 },\n { word: \"yay\", st: 5 }\n];\n\nconsole.log(arrayWithoutIndexes(words, [1,4])); const arrayWithoutIndexes = (array, indexes) => {\n // the map here just copies the word, so the result has new word objects\n return array.filter((el, i) => !indexes.includes(i)).map(o => Object.assign({}, o));\n};\n\nvar words = [\n { word: \"hello\", st: 0 },\n { word: \"stack-overflow\", st: 0.5 },\n { word: \"lets\", st: 1 },\n { word: \"remove\", st: 1.5 },\n { word: \"some\", st: 2 },\n { word: \"words\", st: 2.5 },\n { word: \"efficiently\", st: 3 },\n { word: \"lets\", st: 3.5 },\n { word: \"do\", st: 4 },\n { word: \"it\", st: 4.5 },\n { word: \"yay\", st: 5 }\n];\n\nlet removeThese = [\n [2, 3],\n [4, 5]\n];\n\nlet result = removeThese.map(indexes => arrayWithoutIndexes(words, indexes));\nconsole.log(result)"
},
{
"answer_id": 74636731,
"author": "Layhout",
"author_id": 17308201,
"author_profile": "https://Stackoverflow.com/users/17308201",
"pm_score": 0,
"selected": false,
"text": "JSON.stringify const splitArrayBasedOnIndexes = (arr = [], indexToRemove = []) => {\n indexToRemove = indexToRemove.flat(Infinity);\n let result = JSON.stringify(arr.map((w, i) => {\n if (indexToRemove.includes(i)) return null;\n return w\n }))\n result = result.substring(1, result.lastIndexOf(\"]\")).split(\"null\").reduce((p, c) => {\n if (c.substring(c.indexOf(\"{\"), c.lastIndexOf(\"}\") + 1))\n p.push(JSON.parse(\"[\" + c.substring(c.indexOf(\"{\"), c.lastIndexOf(\"}\") + 1) + \"]\"))\n return p\n }, []);\n\n return result;\n}\n\nconst words = [\n { word: \"hello\", st: 0 },\n { word: \"stack-overflow\", st: 0.5 },\n { word: \"lets\", st: 1 },\n { word: \"remove\", st: 1.5 },\n { word: \"some\", st: 2 },\n { word: \"words\", st: 2.5 },\n { word: \"efficiently\", st: 3 },\n { word: \"lets\", st: 3.5 },\n { word: \"do\", st: 4 },\n { word: \"it\", st: 4.5 },\n { word: \"yay\", st: 5 }\n];\n\nconst trim = [\n [3, 4],\n [9, 10]\n];\n\nconsole.log(splitArrayBasedOnIndexes(words, trim));"
},
{
"answer_id": 74636757,
"author": "James",
"author_id": 535480,
"author_profile": "https://Stackoverflow.com/users/535480",
"pm_score": 2,
"selected": true,
"text": "let start = 0;\nlet result = [];\nfor (let [end, newStart] of trim) {\n result.push(words.slice(start, end));\n start = newStart + 1;\n}\nresult.push(words.slice(start, words.length));\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1971279/"
] |
74,636,571
|
<p>I am connecting to my backend login service using Angular. But I can't set the popup message when the username or password is wrong. In case of any mistake, I want to show the detail message from the API on my page in the login process, but it does not show anything.</p>
<p>login.component.ts</p>
<pre><code>import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators, ReactiveFormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthService } from '../auth.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
form = new FormGroup({
username: new FormControl(null, Validators.required),
password: new FormControl(null, Validators.required),
});
constructor(private authService: AuthService ,private router: Router) {}
loading = false;
loginText = "Giriş Yap";
testVar = undefined;
submitForm() {
if(this.form.invalid) {
return;
}
this.loginText = "Checking.."
this.loading = true;
let username = String(this.form.get('username')?.value)
let password = String(this.form.get('password')?.value)
this.authService
.login(username , password)
.subscribe((_response) => {
this.router.navigate(['/dashboard'])
})
}
ngOnInit(): void {
}
}
</code></pre>
<p>auth.service.ts</p>
<pre><code>import { NONE_TYPE } from '@angular/compiler';
import { Injectable } from '@angular/core';
import { BehaviorSubject, tap } from 'rxjs';
import { ChockService } from './chock.service';
import { UsersModel } from './models/users.model';
import { LoginDetailModel } from './models/logindetail.model';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private _isLoggedIn$ = new BehaviorSubject<boolean>(false);
private readonly TOKEN_NAME = 'access_token';
isLoggedIn$ = this._isLoggedIn$.asObservable();
user : UsersModel | null;
errorMsg = "";
get token() : any{
return localStorage.getItem(this.TOKEN_NAME);
}
constructor(private chockService : ChockService) {
this._isLoggedIn$.next(!!this.token);
this.user = this.getUser(this.token);
}
login(username: string, password: string) {
return this.chockService.login(username,password).pipe(
tap((response :any) => {
console.log(response)
this._isLoggedIn$.next(true);
localStorage.setItem(this.TOKEN_NAME, response.access_token);
})
)
}
private getUser(access_token: string): UsersModel | null{
if(!access_token){
return null;
}
console.log(JSON.parse(atob(access_token.split('.')[1])) as UsersModel);
return JSON.parse(atob(access_token.split('.')[1])) as UsersModel;
}
}
</code></pre>
<p>When the login process is successful, the response I get from the API is as follows, I can set it and use it. There is no problem.</p>
<pre><code>{
"access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFscCIsImlkIjoxLCJvd25lcm5hbWUiOiJiZXRveCIsInJvbGUiOiJhZG1pbiIsImV4cCI6MTY2OTg2NTcyNn0.3uEKgA8Iqv5OGk5lyAXtPBot3e7SAfEQfNYf-aMBToI",
"token_type":"bearer"
}
</code></pre>
<p>When the login process is unsuccessful, I cannot set and export the response I received from the API to HTML so that I can show it on the page. Response from API when it fails:</p>
<pre><code>{"detail":"Wrong password"}
</code></pre>
<p>I tried a code like this in the <code>login.component.ts</code> file, but the detail is never printed and set to the console. I put an if condition so that it doesn't redirect to the dashboard when login fails. What I want to do exactly is to be able to transfer the <code>"detail"</code> value from the response to the page if the login process is successful, if it is not successful, to redirect to the dashboard. Where do you think I might be going wrong?</p>
<pre><code>this.authService
.login(username , password)
.subscribe((_response) => {
if(_response.access_token in response) {
this.router.navigate(['/dashboard'])
}
else {
this.errMsg = _response.detail;
}
})
</code></pre>
|
[
{
"answer_id": 74636637,
"author": "danh",
"author_id": 294949,
"author_profile": "https://Stackoverflow.com/users/294949",
"pm_score": 0,
"selected": false,
"text": "const arrayWithoutIndexes = (array, indexes) => {\n return array.filter((el, i) => !indexes.includes(i));\n};\n\nvar words = [\n { word: \"hello\", st: 0 },\n { word: \"stack-overflow\", st: 0.5 },\n { word: \"lets\", st: 1 },\n { word: \"remove\", st: 1.5 },\n { word: \"some\", st: 2 },\n { word: \"words\", st: 2.5 },\n { word: \"efficiently\", st: 3 },\n { word: \"lets\", st: 3.5 },\n { word: \"do\", st: 4 },\n { word: \"it\", st: 4.5 },\n { word: \"yay\", st: 5 }\n];\n\nconsole.log(arrayWithoutIndexes(words, [1,4])); const arrayWithoutIndexes = (array, indexes) => {\n // the map here just copies the word, so the result has new word objects\n return array.filter((el, i) => !indexes.includes(i)).map(o => Object.assign({}, o));\n};\n\nvar words = [\n { word: \"hello\", st: 0 },\n { word: \"stack-overflow\", st: 0.5 },\n { word: \"lets\", st: 1 },\n { word: \"remove\", st: 1.5 },\n { word: \"some\", st: 2 },\n { word: \"words\", st: 2.5 },\n { word: \"efficiently\", st: 3 },\n { word: \"lets\", st: 3.5 },\n { word: \"do\", st: 4 },\n { word: \"it\", st: 4.5 },\n { word: \"yay\", st: 5 }\n];\n\nlet removeThese = [\n [2, 3],\n [4, 5]\n];\n\nlet result = removeThese.map(indexes => arrayWithoutIndexes(words, indexes));\nconsole.log(result)"
},
{
"answer_id": 74636731,
"author": "Layhout",
"author_id": 17308201,
"author_profile": "https://Stackoverflow.com/users/17308201",
"pm_score": 0,
"selected": false,
"text": "JSON.stringify const splitArrayBasedOnIndexes = (arr = [], indexToRemove = []) => {\n indexToRemove = indexToRemove.flat(Infinity);\n let result = JSON.stringify(arr.map((w, i) => {\n if (indexToRemove.includes(i)) return null;\n return w\n }))\n result = result.substring(1, result.lastIndexOf(\"]\")).split(\"null\").reduce((p, c) => {\n if (c.substring(c.indexOf(\"{\"), c.lastIndexOf(\"}\") + 1))\n p.push(JSON.parse(\"[\" + c.substring(c.indexOf(\"{\"), c.lastIndexOf(\"}\") + 1) + \"]\"))\n return p\n }, []);\n\n return result;\n}\n\nconst words = [\n { word: \"hello\", st: 0 },\n { word: \"stack-overflow\", st: 0.5 },\n { word: \"lets\", st: 1 },\n { word: \"remove\", st: 1.5 },\n { word: \"some\", st: 2 },\n { word: \"words\", st: 2.5 },\n { word: \"efficiently\", st: 3 },\n { word: \"lets\", st: 3.5 },\n { word: \"do\", st: 4 },\n { word: \"it\", st: 4.5 },\n { word: \"yay\", st: 5 }\n];\n\nconst trim = [\n [3, 4],\n [9, 10]\n];\n\nconsole.log(splitArrayBasedOnIndexes(words, trim));"
},
{
"answer_id": 74636757,
"author": "James",
"author_id": 535480,
"author_profile": "https://Stackoverflow.com/users/535480",
"pm_score": 2,
"selected": true,
"text": "let start = 0;\nlet result = [];\nfor (let [end, newStart] of trim) {\n result.push(words.slice(start, end));\n start = newStart + 1;\n}\nresult.push(words.slice(start, words.length));\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15015277/"
] |
74,636,590
|
<p>I am using matplotlib and cartopy to draw lines overlaid on maps in python. As of right now, I am just identifying the lat/lon of two points and plotting a line between them. Since I am taking cross sections across these lines, I would like to find a way to make the line the same length (say 300km long) no matter where I place it on the map. Is this possible without just using trial and error and setting the points until they are the desired length?</p>
<p>lat1, lat2, lon1, lon2 = [34.5, 36, -100, -97]
x, y = [lon1, lon2], [lat1, lat2]</p>
<p>ax1.plot(x, y, color="black", marker="o", zorder=3, transform = ccrs.PlateCarree(), linewidth = 2.5)</p>
<p>Here are the relevant parts of the code that I am using now. This works, but I am looking for a way to hold the line length constant rather than changing the values for the endpoints at "lat1, lat2, lon1, lon2." I envision setting a line length, a mid-point (lat/lon), and an angle that would pivot around that point. I don't know if that's even possible, but that's how I'd imagine it'd have to work!</p>
<p><a href="https://i.stack.imgur.com/g550T.png" rel="nofollow noreferrer">Example of a line that the cross section would be through</a></p>
|
[
{
"answer_id": 74637683,
"author": "Michael Delgado",
"author_id": 3888719,
"author_profile": "https://Stackoverflow.com/users/3888719",
"pm_score": 0,
"selected": false,
"text": "import cartopy.crs as ccrs\nimport geopandas as gpd\n\npoint = gpd.GeoDataFrame(\n geometry=gpd.points_from_xy([-100], [34.5], crs=\"epsg:4326\")\n)\n\ncrs = ccrs.AzimuthalEquidistant(-100, 34.5)\n\ncircle = point.to_crs(crs).buffer(300000).boundary.to_crs(\"epsg:4326\")\n In [17]: circle.iloc[0]\nOut[17]: <shapely.geometry.linestring.LineString at 0x18c3db7c0>\n\nIn [18]: circle.iloc[0].xy\nOut[18]:\n(array('d', [-96.73458302693649, -96.76051210175493, -96.81721890848735, -96.90389145413285, -97.0194601113924, -97.16261553916054, -97.33182721184983, -97.52536229026433, -97.74130463130324, -97.97757379088794, -98.23194392302969, -98.5020625175967, -98.78546895046141, -99.07961284313612, -99.38187224585855, -99.68957166961148, -100.0, -100.31042833038852, -100.61812775414145, -100.92038715686388, -101.21453104953859, -101.4979374824033, -101.76805607697031, -102.02242620911204, -102.25869536869676, -102.47463770973567, -102.66817278815017, -102.83738446083946, -102.98053988860761, -103.09610854586715, -103.18278109151265, -103.23948789824507, -103.26541697306351, -103.26003093177158, -103.22308261845816, -103.15462889147989, -103.05504203609833, -102.92501821713451, -102.7655823598689, -102.57808885099398, -102.3642174900262, -102.12596419991539, -101.86562612586265, -101.58578091250277, -101.28926014666801, -100.97911717692438, -100.65858975917035, -100.33105821410338, -100.0, -99.66894178589662, -99.34141024082963, -99.02088282307564, -98.710739853332, -98.41421908749726, -98.13437387413735, -97.87403580008461, -97.63578250997378, -97.42191114900605, -97.23441764013111, -97.07498178286552, -96.94495796390169, -96.84537110852011, -96.77691738154184, -96.73996906822842, -96.73458302693649]),\n array('d', [34.45635448578617, 34.191923718769814, 33.930839345631036, 33.67556892797355, 33.42850443127362, 33.191942126948454, 32.96806390193457, 32.75892001047773, 32.566413289704464, 32.39228485200862, 32.23810126231687, 32.105243205881486, 31.99489565146612, 31.90803951485474, 31.845444827911535, 31.80766541851577, 31.795035106337213, 31.80766541851577, 31.845444827911535, 31.90803951485474, 31.99489565146612, 32.105243205881486, 32.23810126231687, 32.392284852008615, 32.566413289704464, 32.75892001047773, 32.96806390193457, 33.191942126948454, 33.42850443127362, 33.67556892797355, 33.93083934563104, 34.191923718769814, 34.45635448578617, 34.72160994100843, 34.985136962504626, 35.244374905489536, 35.49678051263328, 35.739853647811024, 35.97116361010222, 36.18837573214065, 36.38927791396905, 36.57180669376817, 36.73407241410168, 36.874383010755274, 36.99126593481258, 37.08348772070849, 37.15007073604399, 37.19030669398129, 37.20376657546522, 37.19030669398129, 37.15007073604399, 37.08348772070849, 36.99126593481258, 36.87438301075528, 36.73407241410169, 36.57180669376818, 36.38927791396906, 36.18837573214065, 35.97116361010222, 35.739853647811024, 35.496780512633286, 35.244374905489536, 34.98513696250464, 34.72160994100843, 34.45635448578617]))\n"
},
{
"answer_id": 74638581,
"author": "Rutger Kassies",
"author_id": 1755432,
"author_profile": "https://Stackoverflow.com/users/1755432",
"pm_score": 2,
"selected": true,
"text": "Geod ccrs.Geodetic() import matplotlib.pyplot as plt\nimport cartopy.crs as ccrs\nfrom pyproj import Geod\nimport numpy as np\n\n# start with a random point\nnp.random.seed(0)\nlon = np.random.randint(-180,180)\nlat = np.random.randint(-90,90)\n\n# and a random direction and distance\nhalf_width = (1 + np.random.rand()) * 5000000 # meters\nazimuth = np.random.randint(0,360)\n\n# calculate the end points\ngeod = Geod(ellps=\"WGS84\")\nlon_end1, lat_end1, azi_rev1 = geod.fwd(lon, lat, azimuth, half_width)\nlon_end2, lat_end2, azi_rev2 = geod.fwd(lon, lat, azimuth-180, half_width)\n\n# visualize the result\nfig, ax = plt.subplots(\n figsize=(8,4), dpi=86, layout=\"compressed\", facecolor=\"w\", \n subplot_kw=dict(projection=ccrs.PlateCarree()),\n)\n\nax.set_title(f\"{lon=}, {lat=}, {azimuth=}, {half_width=:1.1f}m\")\nax.plot(\n [lon_end1, lon, lon_end2], \n [lat_end1, lat, lat_end2], \n \"ro-\",\n transform=ccrs.Geodetic(),\n)\nax.coastlines()\nax.set_global()\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17990324/"
] |
74,636,602
|
<p>Im new in cypress, trying to login to my practice web, but I got problem with this gtag. The actual testing with cypress is done (user success login) but there is one error that keeps make this testing failed, does anyone can help me?. this my pic and my cypress code and my config</p>
<p>This is my error pic</p>
<p><img src="https://i.stack.imgur.com/IMxiO.png" alt="1" /></p>
<pre><code>describe('Login user', () => {
beforeEach(() => {
cy.viewport(1392, 768)
cy.visit('thiswebcom')
})
it('Login as user', () => {
cy.get('a[href*="/login"]').first().click()
cy.get('#buttonLoginTrack').should('have.text', '\n Login\n ')
const userName = 'mymail@gmail.com'
const password = 'mypassword'
cy.get('#email').type(`${userName}`)
cy.get('#password').type(`${password}`).type('{enter}')
})
</code></pre>
<p>this is my cypress code for login in</p>
<pre><code>module.exports = {
e2e: {
setupNodeEvents(on, config) {
// implement node event listeners here
},
},
};
</code></pre>
<p>this is my cypress.config.js file</p>
<p>I tried with blockHosts but no idea how to put it in, thanks</p>
|
[
{
"answer_id": 74637093,
"author": "Kitty.Flanagan",
"author_id": 20652454,
"author_profile": "https://Stackoverflow.com/users/20652454",
"pm_score": 2,
"selected": true,
"text": "Cypress.on('uncaught:exception', (err, runnable) => {\n return false;\n})\n"
},
{
"answer_id": 74644380,
"author": "jjhelguero",
"author_id": 17917809,
"author_profile": "https://Stackoverflow.com/users/17917809",
"pm_score": 0,
"selected": false,
"text": "Cypress.on() cy.on() cy.on('uncaught:exception', (err, runnable) => {\n return !e.message.includes('ReferenceError: gtag is not defined in Cypress')\n})\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20651808/"
] |
74,636,623
|
<p>I am getting a table from database and creating it as an html table to send automated mail..the table has date modified section and another column which has only date and not t..but while it is getting converted to html table the date column shows date along with time.
My html table structure:
Other dynamic function:</p>
<pre><code>public string GetHtmlTable(string title, DataTable table)
{
try
{
string messageBody = "<font> "+title+" </font><br><br>";
if (table.Rows.Count == 0)
return messageBody;
string htmlTableStart = "<table style=\"border-collapse:collapse; text-align:center;\" >";
string htmlTableEnd = "</table>";
string htmlHeaderRowStart = "<tr style =\"background-color:#6FA1D2; color:#ffffff;\">";
string htmlHeaderRowEnd = "</tr>";
string htmlTrStart = "<tr style =\"color:#555555;\">";
string htmlTrEnd = "</tr>";
string htmlTdStart = "<td style=\" border-color:#5c87b2; border-style:solid; border-width:thin; padding: 5px;\">";
string htmlTdEnd = "</td>";
messageBody += htmlTableStart;
messageBody += htmlHeaderRowStart;
foreach(DataColumn column in table.Columns)
messageBody += htmlTdStart + column + htmlTdEnd;
messageBody += htmlHeaderRowEnd;
foreach (DataRow row in table.Rows)
{
messageBody += htmlTrStart;
foreach (string item in row.ItemArray)
{
messageBody += htmlTdStart;
messageBody += item;
messageBody += htmlTdEnd;
}
messageBody += htmlTrEnd;
}
messageBody += htmlTableEnd;
return messageBody;
}
catch (Exception e)
{
return null;
}
}
</code></pre>
<p>I'm sending the table genereated to this html query and generating it as html string and i'l mail it as message body..my requirement is I need to get date and not time...i don't have time in my SQL column from where I get the table.plz help.
<a href="https://i.stack.imgur.com/5iyzi.jpg" rel="nofollow noreferrer">What i get in date modified and other date column</a>
I need only date and not time</p>
|
[
{
"answer_id": 74642710,
"author": "Vic F",
"author_id": 4054386,
"author_profile": "https://Stackoverflow.com/users/4054386",
"pm_score": 2,
"selected": false,
"text": "DateTime ToString() var dateOnly = DateTime.Now.ToString(\"yyyy-MM-dd\"); DateOnly DateOnly dateOnly = DateOnly.FromDateTime(DateTime.Now);"
},
{
"answer_id": 74646005,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": true,
"text": "foreach (string item in row.ItemArray)\n{\n messageBody += htmlTdStart;\n messageBody += item;\n messageBody += htmlTdEnd;\n}\n row.ItemArray object?[] item object? messageBody += item; .ToString() item date DateOnly DateOnly DateTime DateTime DateTime.ToString() double decimal DataTableToHTML() NULL public string GetHtmlTable(string title, DataTable table, Func<string, DataRow> formatRowCells)\n{\n var tableResult = new StringBuilder($\"<div class=\\\"generatedTableTitle\\\">{title}</div>\");\n\n if (table.Rows.Count == 0) return tableResult.ToString();\n\n string htmlTableStart = \"<table class=\\\"generatedTable\\\">\";\n string htmlTableEnd = \"</table>\";\n string htmlHeaderRowStart = \"<tr class=\\\"generatedHeaderRow\\\">\";\n string htmlHeaderRowEnd = \"</tr>\";\n string htmlThStart = \"<th>\";\n string htmlThEnd = \"</th>\";\n string htmlTrStart = \"<tr>\";\n string htmlTrEnd = \"</tr>\";\n\n tableResult.AppendLine(htmlTableStart)\n .AppendLine(htmlHeaderRowStart);\n\n foreach(DataColumn column in table.Columns)\n tableResult.Append($\"{htmlTrStart}{column}{htmlThEnd}\");\n\n tableResult.AppendLine(htmlHeaderRowEnd);\n\n foreach (DataRow row in table.Rows)\n {\n tableResult.AppendLine(htmlTrStart)\n .AppendLine(formatRowCells(row))\n .AppendLine(htmlTrEnd);\n }\n\n tableResult.AppendLine(htmlTableEnd);\n return tableResult.ToString();\n}\n public string GetHtmlTable(string title, DataTable table)\n{\n return GetHtmlTable(title, table, row => string.Join(\"\", row.ItemArray.Select(td => $\"<td>{td}</td>\"))); \n}\n string MyTable = GetHtmlTable(title, table, row =>\n {\n var rowResult = new StringBuilder();\n\n int dateColumnIndex = 2; // put the date column index here\n for (int c = 0; c < row.ItemArray.Length; c++)\n {\n string cellValue = row[c];\n if (c == dateColumnIndex)\n cellValue = row[c].ToString(\"d\");\n rowResult.Append($\"<td>{cellValue}</td>\");\n }\n return rowResult.ToString();\n });\n switch string MyTable = GetHtmlTable(title, table, row =>\n {\n var rowResult = new StringBuilder();\n\n int dateColumnIndex = 2; // put the date column index here\n for (int c = 0; c < row.ItemArray.Length; c++)\n {\n string cellValue = switch c\n {\n dateColumnIndex => row[c].ToString(\"d\"),\n _ => row[c]\n };\n }\n return rowResult.ToString();\n }); \n generatedTable <style>\n div.generatedTableTitle {margin-bottom:2em;font-family:missing_from_question;}\n table.generatedTable {border-collapse:collapse; text-align:center;}\n table.generatedTable tr { color:#555555; }\n table.generatedTable td { border-color:#5c87b2; border-style:solid; border-width:thin; padding: 5px; }\n table.generatedTable tr.generatedHeaderRow {background-color:#6FA1D2; color:#ffffff;}\n table.generatedTable th { border-color:#5c87b2; border-style:solid; border-width:thin; padding: 5px; }\n</style>\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20152482/"
] |
74,636,630
|
<pre><code>library(data.table)
library(dplyr)
A <-data.frame(V1=c("Amy", 1:6), V2=c("Grade", 1:6), V3=c("level", LETTERS[1:6]))
B <-data.frame(V1=c("Mike", 1:6), V2=c("Grade", 1:6), V3=c("level", LETTERS[1:6]))
C <-data.frame(V1=c("Kevin", 1:6), V2=c("Grade", 1:6), V3=c("level", LETTERS[1:6]))
D <-data.frame(V1=c("Grace", 1:6), V2=c("Grade", 1:6), V3=c("level", LETTERS[1:6]))
df <- A %>% rbind(B, C, D) %>% setnames(c("V1", "V2", "V3"), c("ID", "Grade", "level"))
</code></pre>
<p>I have 4 dataframe need to merge, the code above will keep value what I want to remove.
I want ask about maybe have more effective way?</p>
<p>I want to replace Grade and level by NA or space.
<a href="https://i.stack.imgur.com/Bh2rd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Bh2rd.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74642710,
"author": "Vic F",
"author_id": 4054386,
"author_profile": "https://Stackoverflow.com/users/4054386",
"pm_score": 2,
"selected": false,
"text": "DateTime ToString() var dateOnly = DateTime.Now.ToString(\"yyyy-MM-dd\"); DateOnly DateOnly dateOnly = DateOnly.FromDateTime(DateTime.Now);"
},
{
"answer_id": 74646005,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": true,
"text": "foreach (string item in row.ItemArray)\n{\n messageBody += htmlTdStart;\n messageBody += item;\n messageBody += htmlTdEnd;\n}\n row.ItemArray object?[] item object? messageBody += item; .ToString() item date DateOnly DateOnly DateTime DateTime DateTime.ToString() double decimal DataTableToHTML() NULL public string GetHtmlTable(string title, DataTable table, Func<string, DataRow> formatRowCells)\n{\n var tableResult = new StringBuilder($\"<div class=\\\"generatedTableTitle\\\">{title}</div>\");\n\n if (table.Rows.Count == 0) return tableResult.ToString();\n\n string htmlTableStart = \"<table class=\\\"generatedTable\\\">\";\n string htmlTableEnd = \"</table>\";\n string htmlHeaderRowStart = \"<tr class=\\\"generatedHeaderRow\\\">\";\n string htmlHeaderRowEnd = \"</tr>\";\n string htmlThStart = \"<th>\";\n string htmlThEnd = \"</th>\";\n string htmlTrStart = \"<tr>\";\n string htmlTrEnd = \"</tr>\";\n\n tableResult.AppendLine(htmlTableStart)\n .AppendLine(htmlHeaderRowStart);\n\n foreach(DataColumn column in table.Columns)\n tableResult.Append($\"{htmlTrStart}{column}{htmlThEnd}\");\n\n tableResult.AppendLine(htmlHeaderRowEnd);\n\n foreach (DataRow row in table.Rows)\n {\n tableResult.AppendLine(htmlTrStart)\n .AppendLine(formatRowCells(row))\n .AppendLine(htmlTrEnd);\n }\n\n tableResult.AppendLine(htmlTableEnd);\n return tableResult.ToString();\n}\n public string GetHtmlTable(string title, DataTable table)\n{\n return GetHtmlTable(title, table, row => string.Join(\"\", row.ItemArray.Select(td => $\"<td>{td}</td>\"))); \n}\n string MyTable = GetHtmlTable(title, table, row =>\n {\n var rowResult = new StringBuilder();\n\n int dateColumnIndex = 2; // put the date column index here\n for (int c = 0; c < row.ItemArray.Length; c++)\n {\n string cellValue = row[c];\n if (c == dateColumnIndex)\n cellValue = row[c].ToString(\"d\");\n rowResult.Append($\"<td>{cellValue}</td>\");\n }\n return rowResult.ToString();\n });\n switch string MyTable = GetHtmlTable(title, table, row =>\n {\n var rowResult = new StringBuilder();\n\n int dateColumnIndex = 2; // put the date column index here\n for (int c = 0; c < row.ItemArray.Length; c++)\n {\n string cellValue = switch c\n {\n dateColumnIndex => row[c].ToString(\"d\"),\n _ => row[c]\n };\n }\n return rowResult.ToString();\n }); \n generatedTable <style>\n div.generatedTableTitle {margin-bottom:2em;font-family:missing_from_question;}\n table.generatedTable {border-collapse:collapse; text-align:center;}\n table.generatedTable tr { color:#555555; }\n table.generatedTable td { border-color:#5c87b2; border-style:solid; border-width:thin; padding: 5px; }\n table.generatedTable tr.generatedHeaderRow {background-color:#6FA1D2; color:#ffffff;}\n table.generatedTable th { border-color:#5c87b2; border-style:solid; border-width:thin; padding: 5px; }\n</style>\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20137369/"
] |
74,636,639
|
<p>I got strings like</p>
<p><code>String1=277473—-2627272———-273-3838383-/./--asdfg-----123:12:2---</code></p>
<p>I cant take length of function because I have multiple strings with different lenghts.</p>
<p>I wanted to use split function to take them as a variable but I need this format</p>
<p><code>String1=277473-2627272—273-3838383-/./-asdfg-123:12:2</code></p>
<p>Is there any way to do that easily?</p>
|
[
{
"answer_id": 74642710,
"author": "Vic F",
"author_id": 4054386,
"author_profile": "https://Stackoverflow.com/users/4054386",
"pm_score": 2,
"selected": false,
"text": "DateTime ToString() var dateOnly = DateTime.Now.ToString(\"yyyy-MM-dd\"); DateOnly DateOnly dateOnly = DateOnly.FromDateTime(DateTime.Now);"
},
{
"answer_id": 74646005,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": true,
"text": "foreach (string item in row.ItemArray)\n{\n messageBody += htmlTdStart;\n messageBody += item;\n messageBody += htmlTdEnd;\n}\n row.ItemArray object?[] item object? messageBody += item; .ToString() item date DateOnly DateOnly DateTime DateTime DateTime.ToString() double decimal DataTableToHTML() NULL public string GetHtmlTable(string title, DataTable table, Func<string, DataRow> formatRowCells)\n{\n var tableResult = new StringBuilder($\"<div class=\\\"generatedTableTitle\\\">{title}</div>\");\n\n if (table.Rows.Count == 0) return tableResult.ToString();\n\n string htmlTableStart = \"<table class=\\\"generatedTable\\\">\";\n string htmlTableEnd = \"</table>\";\n string htmlHeaderRowStart = \"<tr class=\\\"generatedHeaderRow\\\">\";\n string htmlHeaderRowEnd = \"</tr>\";\n string htmlThStart = \"<th>\";\n string htmlThEnd = \"</th>\";\n string htmlTrStart = \"<tr>\";\n string htmlTrEnd = \"</tr>\";\n\n tableResult.AppendLine(htmlTableStart)\n .AppendLine(htmlHeaderRowStart);\n\n foreach(DataColumn column in table.Columns)\n tableResult.Append($\"{htmlTrStart}{column}{htmlThEnd}\");\n\n tableResult.AppendLine(htmlHeaderRowEnd);\n\n foreach (DataRow row in table.Rows)\n {\n tableResult.AppendLine(htmlTrStart)\n .AppendLine(formatRowCells(row))\n .AppendLine(htmlTrEnd);\n }\n\n tableResult.AppendLine(htmlTableEnd);\n return tableResult.ToString();\n}\n public string GetHtmlTable(string title, DataTable table)\n{\n return GetHtmlTable(title, table, row => string.Join(\"\", row.ItemArray.Select(td => $\"<td>{td}</td>\"))); \n}\n string MyTable = GetHtmlTable(title, table, row =>\n {\n var rowResult = new StringBuilder();\n\n int dateColumnIndex = 2; // put the date column index here\n for (int c = 0; c < row.ItemArray.Length; c++)\n {\n string cellValue = row[c];\n if (c == dateColumnIndex)\n cellValue = row[c].ToString(\"d\");\n rowResult.Append($\"<td>{cellValue}</td>\");\n }\n return rowResult.ToString();\n });\n switch string MyTable = GetHtmlTable(title, table, row =>\n {\n var rowResult = new StringBuilder();\n\n int dateColumnIndex = 2; // put the date column index here\n for (int c = 0; c < row.ItemArray.Length; c++)\n {\n string cellValue = switch c\n {\n dateColumnIndex => row[c].ToString(\"d\"),\n _ => row[c]\n };\n }\n return rowResult.ToString();\n }); \n generatedTable <style>\n div.generatedTableTitle {margin-bottom:2em;font-family:missing_from_question;}\n table.generatedTable {border-collapse:collapse; text-align:center;}\n table.generatedTable tr { color:#555555; }\n table.generatedTable td { border-color:#5c87b2; border-style:solid; border-width:thin; padding: 5px; }\n table.generatedTable tr.generatedHeaderRow {background-color:#6FA1D2; color:#ffffff;}\n table.generatedTable th { border-color:#5c87b2; border-style:solid; border-width:thin; padding: 5px; }\n</style>\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17241290/"
] |
74,636,644
|
<p>I have these directories:</p>
<pre><code>└── MY_FOLDER
├── MY_PROJECT
│ └── settings.py
│
├── MY_APP
├── STATIC
│ └── style.css
├── MEDIA
└── manage.py
</code></pre>
<p>In the settings.py I've indicated:</p>
<pre><code>BASE_DIR = Path(__file__).resolve().parent.parent
STATIC_URL = 'static/'
STATICFILES_DIR = (os.path.join(BASE_DIR,'static'))
</code></pre>
<p>When I</p>
<pre><code>print(STATICFILES_DIR)
</code></pre>
<p>I get a path:
MY_FOLDER/STATIC - what is exactly I wanted.</p>
<p>But Django don't see any css there, in that folder.</p>
<p>I tried to put my css to MY_APP/STATIC and it started to work correctly. But I want to have it not in MY_APP but in BASE_DIR/STATIC. How to do it?</p>
<p>Or if it is impossible, how to make a correct path for STATICFILES_DIR to let it search my statics in all apps I'll add in the future. Not only in one app by doing this:</p>
<pre><code>STATICFILES_DIR = (os.path.join(BASE_DIR,'MY_APP','static'))
</code></pre>
<p>Thanks.</p>
|
[
{
"answer_id": 74642710,
"author": "Vic F",
"author_id": 4054386,
"author_profile": "https://Stackoverflow.com/users/4054386",
"pm_score": 2,
"selected": false,
"text": "DateTime ToString() var dateOnly = DateTime.Now.ToString(\"yyyy-MM-dd\"); DateOnly DateOnly dateOnly = DateOnly.FromDateTime(DateTime.Now);"
},
{
"answer_id": 74646005,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": true,
"text": "foreach (string item in row.ItemArray)\n{\n messageBody += htmlTdStart;\n messageBody += item;\n messageBody += htmlTdEnd;\n}\n row.ItemArray object?[] item object? messageBody += item; .ToString() item date DateOnly DateOnly DateTime DateTime DateTime.ToString() double decimal DataTableToHTML() NULL public string GetHtmlTable(string title, DataTable table, Func<string, DataRow> formatRowCells)\n{\n var tableResult = new StringBuilder($\"<div class=\\\"generatedTableTitle\\\">{title}</div>\");\n\n if (table.Rows.Count == 0) return tableResult.ToString();\n\n string htmlTableStart = \"<table class=\\\"generatedTable\\\">\";\n string htmlTableEnd = \"</table>\";\n string htmlHeaderRowStart = \"<tr class=\\\"generatedHeaderRow\\\">\";\n string htmlHeaderRowEnd = \"</tr>\";\n string htmlThStart = \"<th>\";\n string htmlThEnd = \"</th>\";\n string htmlTrStart = \"<tr>\";\n string htmlTrEnd = \"</tr>\";\n\n tableResult.AppendLine(htmlTableStart)\n .AppendLine(htmlHeaderRowStart);\n\n foreach(DataColumn column in table.Columns)\n tableResult.Append($\"{htmlTrStart}{column}{htmlThEnd}\");\n\n tableResult.AppendLine(htmlHeaderRowEnd);\n\n foreach (DataRow row in table.Rows)\n {\n tableResult.AppendLine(htmlTrStart)\n .AppendLine(formatRowCells(row))\n .AppendLine(htmlTrEnd);\n }\n\n tableResult.AppendLine(htmlTableEnd);\n return tableResult.ToString();\n}\n public string GetHtmlTable(string title, DataTable table)\n{\n return GetHtmlTable(title, table, row => string.Join(\"\", row.ItemArray.Select(td => $\"<td>{td}</td>\"))); \n}\n string MyTable = GetHtmlTable(title, table, row =>\n {\n var rowResult = new StringBuilder();\n\n int dateColumnIndex = 2; // put the date column index here\n for (int c = 0; c < row.ItemArray.Length; c++)\n {\n string cellValue = row[c];\n if (c == dateColumnIndex)\n cellValue = row[c].ToString(\"d\");\n rowResult.Append($\"<td>{cellValue}</td>\");\n }\n return rowResult.ToString();\n });\n switch string MyTable = GetHtmlTable(title, table, row =>\n {\n var rowResult = new StringBuilder();\n\n int dateColumnIndex = 2; // put the date column index here\n for (int c = 0; c < row.ItemArray.Length; c++)\n {\n string cellValue = switch c\n {\n dateColumnIndex => row[c].ToString(\"d\"),\n _ => row[c]\n };\n }\n return rowResult.ToString();\n }); \n generatedTable <style>\n div.generatedTableTitle {margin-bottom:2em;font-family:missing_from_question;}\n table.generatedTable {border-collapse:collapse; text-align:center;}\n table.generatedTable tr { color:#555555; }\n table.generatedTable td { border-color:#5c87b2; border-style:solid; border-width:thin; padding: 5px; }\n table.generatedTable tr.generatedHeaderRow {background-color:#6FA1D2; color:#ffffff;}\n table.generatedTable th { border-color:#5c87b2; border-style:solid; border-width:thin; padding: 5px; }\n</style>\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19317701/"
] |
74,636,649
|
<p>I am using the python webbrowser module to try and open a html file. I added a short thing to get code from a website to view, allowing me to store a web-page incase I ever need to view it without wifi, for instance a news article or something else.</p>
<p>The code itself is fairly short so far, so here it is:</p>
<pre><code>import requests as req
from bs4 import BeautifulSoup as bs
import webbrowser
import re
webcheck = re.compile('^(https?:\/\/)?(www.)?([a-z0-9]+\.[a-z]+)([\/a-zA-Z0-9#\-_]+\/?)*$')
#Valid URL Check
while True:
url = input('URL (MUST HAVE HTTP://): ')
check = webcheck.search(url)
groups = list(check.groups())
if check != None:
for group in groups:
if group == 'https://':
groups.remove(group)
elif group.count('/') > 0:
groups.append(group.replace('/', '--'))
groups.remove(group)
filename = ''.join(groups) + '.html'
break
#Getting Website Data
reply = req.get(url)
soup = bs(reply.text, 'html.parser')
#Writing Website
with open(filename, 'w') as file:
file.write(reply.text)
#Open Website
webbrowser.open(filename)
webbrowser.open('https://www.youtube.com')
</code></pre>
<p>I added <code>webbrowser.open('https://www.youtube.com')</code> so that I knew the module was working, which it was, as it did open up youtube.
However, <code>webbrowser.open(filename)</code> doesn't do anything, yet it returns <em><strong>True</strong></em> if I define it as a variable and print it.
The html file itself has a period in the name, but I don't think that should matter as I have made a file without it as the name and it wont run.</p>
<p>Does webbrowser need special permissions to work?
I'm not sure what to do as I've removed characters from the filename and even showed that the module is working by opening youtube.
What can I do to fix this?</p>
|
[
{
"answer_id": 74642710,
"author": "Vic F",
"author_id": 4054386,
"author_profile": "https://Stackoverflow.com/users/4054386",
"pm_score": 2,
"selected": false,
"text": "DateTime ToString() var dateOnly = DateTime.Now.ToString(\"yyyy-MM-dd\"); DateOnly DateOnly dateOnly = DateOnly.FromDateTime(DateTime.Now);"
},
{
"answer_id": 74646005,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": true,
"text": "foreach (string item in row.ItemArray)\n{\n messageBody += htmlTdStart;\n messageBody += item;\n messageBody += htmlTdEnd;\n}\n row.ItemArray object?[] item object? messageBody += item; .ToString() item date DateOnly DateOnly DateTime DateTime DateTime.ToString() double decimal DataTableToHTML() NULL public string GetHtmlTable(string title, DataTable table, Func<string, DataRow> formatRowCells)\n{\n var tableResult = new StringBuilder($\"<div class=\\\"generatedTableTitle\\\">{title}</div>\");\n\n if (table.Rows.Count == 0) return tableResult.ToString();\n\n string htmlTableStart = \"<table class=\\\"generatedTable\\\">\";\n string htmlTableEnd = \"</table>\";\n string htmlHeaderRowStart = \"<tr class=\\\"generatedHeaderRow\\\">\";\n string htmlHeaderRowEnd = \"</tr>\";\n string htmlThStart = \"<th>\";\n string htmlThEnd = \"</th>\";\n string htmlTrStart = \"<tr>\";\n string htmlTrEnd = \"</tr>\";\n\n tableResult.AppendLine(htmlTableStart)\n .AppendLine(htmlHeaderRowStart);\n\n foreach(DataColumn column in table.Columns)\n tableResult.Append($\"{htmlTrStart}{column}{htmlThEnd}\");\n\n tableResult.AppendLine(htmlHeaderRowEnd);\n\n foreach (DataRow row in table.Rows)\n {\n tableResult.AppendLine(htmlTrStart)\n .AppendLine(formatRowCells(row))\n .AppendLine(htmlTrEnd);\n }\n\n tableResult.AppendLine(htmlTableEnd);\n return tableResult.ToString();\n}\n public string GetHtmlTable(string title, DataTable table)\n{\n return GetHtmlTable(title, table, row => string.Join(\"\", row.ItemArray.Select(td => $\"<td>{td}</td>\"))); \n}\n string MyTable = GetHtmlTable(title, table, row =>\n {\n var rowResult = new StringBuilder();\n\n int dateColumnIndex = 2; // put the date column index here\n for (int c = 0; c < row.ItemArray.Length; c++)\n {\n string cellValue = row[c];\n if (c == dateColumnIndex)\n cellValue = row[c].ToString(\"d\");\n rowResult.Append($\"<td>{cellValue}</td>\");\n }\n return rowResult.ToString();\n });\n switch string MyTable = GetHtmlTable(title, table, row =>\n {\n var rowResult = new StringBuilder();\n\n int dateColumnIndex = 2; // put the date column index here\n for (int c = 0; c < row.ItemArray.Length; c++)\n {\n string cellValue = switch c\n {\n dateColumnIndex => row[c].ToString(\"d\"),\n _ => row[c]\n };\n }\n return rowResult.ToString();\n }); \n generatedTable <style>\n div.generatedTableTitle {margin-bottom:2em;font-family:missing_from_question;}\n table.generatedTable {border-collapse:collapse; text-align:center;}\n table.generatedTable tr { color:#555555; }\n table.generatedTable td { border-color:#5c87b2; border-style:solid; border-width:thin; padding: 5px; }\n table.generatedTable tr.generatedHeaderRow {background-color:#6FA1D2; color:#ffffff;}\n table.generatedTable th { border-color:#5c87b2; border-style:solid; border-width:thin; padding: 5px; }\n</style>\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19104306/"
] |
74,636,711
|
<pre><code>cm = int(input("Write height in Centimeters:"))
inches = 0.394*cm
feet = 0.0328*cm
print(("The length in inches",round(inches,2))).round(inches,2)
print(("The length in feet",round(feet,2))).round(feet,2)
</code></pre>
<p>this is the code</p>
<p>this code should convert cm in feet and inches but there is a error</p>
|
[
{
"answer_id": 74636738,
"author": "Sabir",
"author_id": 16954011,
"author_profile": "https://Stackoverflow.com/users/16954011",
"pm_score": 0,
"selected": false,
"text": "cm = int(input(\"Write height in Centimeters:\"))\ninches = 0.394*cm\nfeet = 0.0328*cm\nprint((\"The length in inches\",round(inches,2)))\nprint((\"The length in feet\",round(feet,2)))\n"
},
{
"answer_id": 74636748,
"author": "realhuman",
"author_id": 15690172,
"author_profile": "https://Stackoverflow.com/users/15690172",
"pm_score": 1,
"selected": false,
"text": "NoneType None .round() None None .round() print() None print((\"The length in inches\",round(inches,2))) # Removed extra .round()\nprint((\"The length in feet\",round(feet,2)))\n cm = int(input(\"Write height in Centimeters:\"))\ninches = 0.394*cm\nfeet = 0.0328*cm\nprint((\"The length in inches\",round(inches,2)))\nprint((\"The length in feet\",round(feet,2)))\n"
},
{
"answer_id": 74636751,
"author": "qbizzle68",
"author_id": 18984369,
"author_profile": "https://Stackoverflow.com/users/18984369",
"pm_score": 0,
"selected": false,
"text": "round() print None round() .round(inches, 2) .round(feet, 2)"
},
{
"answer_id": 74636769,
"author": "Henro Sutrisno Tanjung",
"author_id": 4785658,
"author_profile": "https://Stackoverflow.com/users/4785658",
"pm_score": 0,
"selected": false,
"text": "print((\"The length in inches\",round(inches,2)))\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20652006/"
] |
74,636,742
|
<p>I'm working on a small game. The point of the game is, you get random numbers, and you need to click those numbers in order from 1 through 25.</p>
<p>Basically i want to make sure that i can only click on no. 2 if not 1 was clicked and i can't click on another other box. Once no. 1 and 2 have been clicked, i can only click on no. 3 and no other boxes at that point. The idea of the game is for a little kid to be able to find numbers 1 - 25 in that order and if they happen to misclick, nothing will happen or an error will trigger to start over.</p>
<p>I can't seem to implement the logic. I don't know if I have a mistake in my code somewhere.</p>
<p>What I tried so far is basically, when I click a box with #1 in it, I push that value into a <code>clickedBoxes</code> array. Then I tried implement different checks, from index checking etc. but I can't seem to get it to work.</p>
<p>Any help would be appreciated.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const startBtn = document.querySelector('.start-btn')
const resetBtn = document.querySelector('.reset-btn')
const timer = document.querySelector('.time__countdown')
const squares = document.querySelectorAll('.grid .square');
const seperateSquare = document.querySelectorAll('.grid');
let gameStarted = false;
let counter = 60
let timeInterval;
let clickedSquares = []
startBtn.addEventListener('click', startGame)
function startGame() {
gameStarted = true;
randomNumber()
timeInterval = setInterval(function() {
counter--
if (counter >= 0) {
timer.innerHTML = `Time left: ${counter}`
}
}, 1000)
}
function getRandomColor() {
const letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function randomNumber() {
const numArray = []
for (let i = 1; i < 26; i++) {
numArray.push(i)
}
numArray.sort(() => 0.5 - Math.random())
for (let i = 0; i < squares.length; i++) {
const random = Math.floor(Math.random() * 25)
squares[i].textContent = numArray[i]
squares[i].style.fontSize = random + 15 + "px";
squares[i].style.color = getRandomColor()
squares[i].style.backgroundColor = '#000000'
squares[i].addEventListener('click', function() {
clickedSquares.push(numArray[i])
console.log(clickedSquares)
// clickedSquares.map((x,y) => {
// if (clickedSquares[0] === 1 && x === 1) {
// return squares[i].style.backgroundColor = 'green'
// } else if (clickedSquares[1] === 2 && x === 2 && clickedSquares[0] === 1 && x === 1) {
// } return squares[i].style.backgroundColor = 'green'
// console.log(x)
// console.log(clickedSquares[0])
// })
})
}
}
resetBtn.addEventListener('click', function() {
clearInterval(timeInterval)
counter = 60
timer.innerHTML = `Time left: 60`
gameStarted = false
squares.forEach((n) => {
n.textContent = "";
n.style.backgroundColor = "#000000";
})
})</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
margin: 0;
padding: 0;
}
body,
html {
min-width: 100%;
min-height: 100vh;
box-sizing: border-box;
font-size: 100%;
display: flex;
justify-content: center;
align-items: center;
background-color: black;
}
img {
max-width: 100%;
display: block;
}
main {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 24%;
background-color: #6688CC;
border-radius: 10px;
}
.grid {
border: 2px solid black;
width: 100%;
display: flex;
flex-wrap: wrap;
background-color: #ACBFE6;
justify-content: center;
align-items: center;
gap: 2px;
padding-top: 3px;
padding-bottom: 3px;
}
.square {
border: 2px solid black;
width: 70px;
height: 70px;
display: flex;
justify-content: center;
align-items: center;
background-color: #000000;
}
.time {
padding-bottom: 2em;
padding-top: 1em;
}
.btn {
margin: 1em;
padding: 1em;
border-radius: 10px;
font-family: Arial, Helvetica, sans-serif;
font-size: 1rem;
background-color: #6688CC;
border: 2px solid black;
}
.btn:hover {
background-color: #ACBFE6
}
.buttons {
display: flex;
}
.square-selected {
background-color: red;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
<div class="time">
<p class="time__countdown">Time left: 60</p>
</div>
<grid class="grid">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</grid>
<div class="buttons">
<button class="btn start-btn">Start Game</button>
<button class="btn reset-btn">Reset Game</button>
</div>
</main></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74636999,
"author": "NAZIR HUSSAIN",
"author_id": 20587701,
"author_profile": "https://Stackoverflow.com/users/20587701",
"pm_score": 0,
"selected": false,
"text": " squares[i].addEventListener('click', function() { \n console.log(clickedSquares)\n if(clickedSquares[clickedSquares.length - 1] === (numArray[i] - 1) ){\n clickedSquares.push(numArray[i]);\n }\n else {\n alert(\"wrong number selected\");\n }\n })\n"
},
{
"answer_id": 74637572,
"author": "NAZIR HUSSAIN",
"author_id": 20587701,
"author_profile": "https://Stackoverflow.com/users/20587701",
"pm_score": 3,
"selected": true,
"text": "const startBtn = document.querySelector('.start-btn')\nconst resetBtn = document.querySelector('.reset-btn')\nconst timer = document.querySelector('.time__countdown')\nconst squares = document.querySelectorAll('.grid .square');\nconst seperateSquare = document.querySelectorAll('.grid');\nlet gameStarted = false;\nlet counter = 60\nlet timeInterval;\n\nlet clickedSquares = []\n\nstartBtn.addEventListener('click', startGame)\n\nfunction startGame() {\n gameStarted = true;\n\n randomNumber()\n\n timeInterval = setInterval(function() {\n counter--\n if (counter >= 0) {\n timer.innerHTML = `Time left: ${counter}`\n }\n }, 1000)\n\n}\n\nfunction getRandomColor() {\n const letters = '0123456789ABCDEF';\n let color = '#';\n for (let i = 0; i < 6; i++) {\n color += letters[Math.floor(Math.random() * 16)];\n }\n return color;\n}\n\nfunction randomNumber() {\n const numArray = []\n\n for (let i = 1; i < 26; i++) {\n numArray.push(i)\n }\n\n numArray.sort(() => 0.5 - Math.random())\n\n for (let i = 0; i < squares.length; i++) {\n const random = Math.floor(Math.random() * 25)\n\n squares[i].textContent = numArray[i]\n squares[i].style.fontSize = random + 15 + \"px\";\n squares[i].style.color = getRandomColor()\n squares[i].style.backgroundColor = '#000000'\n squares[i].addEventListener('click', function() { \n\nif(\n (+clickedSquares[clickedSquares.length - 1] === +(numArray[i] - 1))\n || \n (+numArray[i] === 1 && clickedSquares.length === 0) \n ){\n clickedSquares.push(numArray[i]);\n console.log(clickedSquares)\n}\nelse {\n alert(\"wrong number selected\");\n}\n })\n\n\n\n}\n}\n\nresetBtn.addEventListener('click', function() {\n clearInterval(timeInterval)\n counter = 60\n timer.innerHTML = `Time left: 60`\n gameStarted = false\n squares.forEach((n) => {\n n.textContent = \"\";\n n.style.backgroundColor = \"#000000\";\n })\n\n\n\n}) * {\n margin: 0;\n padding: 0;\n}\n\nbody,\nhtml {\n min-width: 100%;\n min-height: 100vh;\n box-sizing: border-box;\n font-size: 100%;\n display: flex;\n justify-content: center;\n align-items: center;\n background-color: black;\n}\n\nimg {\n max-width: 100%;\n display: block;\n}\n\nmain {\n display: flex;\n flex-direction: column;\n justify-content: center;\n align-items: center;\n width: 24%;\n background-color: #6688CC;\n border-radius: 10px;\n}\n\n.grid {\n border: 2px solid black;\n width: 100%;\n display: flex;\n flex-wrap: wrap;\n background-color: #ACBFE6;\n justify-content: center;\n align-items: center;\n gap: 2px;\n padding-top: 3px;\n padding-bottom: 3px;\n}\n\n.square {\n border: 2px solid black;\n width: 70px;\n height: 70px;\n display: flex;\n justify-content: center;\n align-items: center;\n background-color: #000000;\n}\n\n.time {\n padding-bottom: 2em;\n padding-top: 1em;\n}\n\n.btn {\n margin: 1em;\n padding: 1em;\n border-radius: 10px;\n font-family: Arial, Helvetica, sans-serif;\n font-size: 1rem;\n background-color: #6688CC;\n border: 2px solid black;\n}\n\n.btn:hover {\n background-color: #ACBFE6\n}\n\n.buttons {\n display: flex;\n}\n\n.square-selected {\n background-color: red;\n} <main>\n <div class=\"time\">\n <p class=\"time__countdown\">Time left: 60</p>\n </div>\n <grid class=\"grid\">\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n </grid>\n <div class=\"buttons\">\n <button class=\"btn start-btn\">Start Game</button>\n <button class=\"btn reset-btn\">Reset Game</button>\n </div>\n</main>"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18992987/"
] |
74,636,744
|
<p>I am a very early beginner to coding. I downloaded VS Code so that I could, you know, have somewhere to code in Java. However, I keep getting these two errors telling me these two extensions that I already have installed on VS Code are not working <a href="https://i.stack.imgur.com/eotJ1.png" rel="nofollow noreferrer">here are the error messages</a>. I already searched through the odds and ends of StackOverflow and have tried everything, and nothing has worked. Any help would be appreciated.</p>
<p>I inputted some code into settings.json under a "java.configuration.runtimes" thing but nothing in it worked. I conformed it to my installation directories and current Java version</p>
|
[
{
"answer_id": 74636999,
"author": "NAZIR HUSSAIN",
"author_id": 20587701,
"author_profile": "https://Stackoverflow.com/users/20587701",
"pm_score": 0,
"selected": false,
"text": " squares[i].addEventListener('click', function() { \n console.log(clickedSquares)\n if(clickedSquares[clickedSquares.length - 1] === (numArray[i] - 1) ){\n clickedSquares.push(numArray[i]);\n }\n else {\n alert(\"wrong number selected\");\n }\n })\n"
},
{
"answer_id": 74637572,
"author": "NAZIR HUSSAIN",
"author_id": 20587701,
"author_profile": "https://Stackoverflow.com/users/20587701",
"pm_score": 3,
"selected": true,
"text": "const startBtn = document.querySelector('.start-btn')\nconst resetBtn = document.querySelector('.reset-btn')\nconst timer = document.querySelector('.time__countdown')\nconst squares = document.querySelectorAll('.grid .square');\nconst seperateSquare = document.querySelectorAll('.grid');\nlet gameStarted = false;\nlet counter = 60\nlet timeInterval;\n\nlet clickedSquares = []\n\nstartBtn.addEventListener('click', startGame)\n\nfunction startGame() {\n gameStarted = true;\n\n randomNumber()\n\n timeInterval = setInterval(function() {\n counter--\n if (counter >= 0) {\n timer.innerHTML = `Time left: ${counter}`\n }\n }, 1000)\n\n}\n\nfunction getRandomColor() {\n const letters = '0123456789ABCDEF';\n let color = '#';\n for (let i = 0; i < 6; i++) {\n color += letters[Math.floor(Math.random() * 16)];\n }\n return color;\n}\n\nfunction randomNumber() {\n const numArray = []\n\n for (let i = 1; i < 26; i++) {\n numArray.push(i)\n }\n\n numArray.sort(() => 0.5 - Math.random())\n\n for (let i = 0; i < squares.length; i++) {\n const random = Math.floor(Math.random() * 25)\n\n squares[i].textContent = numArray[i]\n squares[i].style.fontSize = random + 15 + \"px\";\n squares[i].style.color = getRandomColor()\n squares[i].style.backgroundColor = '#000000'\n squares[i].addEventListener('click', function() { \n\nif(\n (+clickedSquares[clickedSquares.length - 1] === +(numArray[i] - 1))\n || \n (+numArray[i] === 1 && clickedSquares.length === 0) \n ){\n clickedSquares.push(numArray[i]);\n console.log(clickedSquares)\n}\nelse {\n alert(\"wrong number selected\");\n}\n })\n\n\n\n}\n}\n\nresetBtn.addEventListener('click', function() {\n clearInterval(timeInterval)\n counter = 60\n timer.innerHTML = `Time left: 60`\n gameStarted = false\n squares.forEach((n) => {\n n.textContent = \"\";\n n.style.backgroundColor = \"#000000\";\n })\n\n\n\n}) * {\n margin: 0;\n padding: 0;\n}\n\nbody,\nhtml {\n min-width: 100%;\n min-height: 100vh;\n box-sizing: border-box;\n font-size: 100%;\n display: flex;\n justify-content: center;\n align-items: center;\n background-color: black;\n}\n\nimg {\n max-width: 100%;\n display: block;\n}\n\nmain {\n display: flex;\n flex-direction: column;\n justify-content: center;\n align-items: center;\n width: 24%;\n background-color: #6688CC;\n border-radius: 10px;\n}\n\n.grid {\n border: 2px solid black;\n width: 100%;\n display: flex;\n flex-wrap: wrap;\n background-color: #ACBFE6;\n justify-content: center;\n align-items: center;\n gap: 2px;\n padding-top: 3px;\n padding-bottom: 3px;\n}\n\n.square {\n border: 2px solid black;\n width: 70px;\n height: 70px;\n display: flex;\n justify-content: center;\n align-items: center;\n background-color: #000000;\n}\n\n.time {\n padding-bottom: 2em;\n padding-top: 1em;\n}\n\n.btn {\n margin: 1em;\n padding: 1em;\n border-radius: 10px;\n font-family: Arial, Helvetica, sans-serif;\n font-size: 1rem;\n background-color: #6688CC;\n border: 2px solid black;\n}\n\n.btn:hover {\n background-color: #ACBFE6\n}\n\n.buttons {\n display: flex;\n}\n\n.square-selected {\n background-color: red;\n} <main>\n <div class=\"time\">\n <p class=\"time__countdown\">Time left: 60</p>\n </div>\n <grid class=\"grid\">\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n <div class=\"square\"></div>\n </grid>\n <div class=\"buttons\">\n <button class=\"btn start-btn\">Start Game</button>\n <button class=\"btn reset-btn\">Reset Game</button>\n </div>\n</main>"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20652011/"
] |
74,636,829
|
<p>I'm looking for a way to replace all words not wrapped in a span tag to (space).
I've tried various ways, but so far not getting what I want.</p>
<p>The code that I wrote below is quite effective, but there are still many shortcomings.
For example if the lyrics are capitalized, they will not be converted to spaces.</p>
<p>So what's the best way to achieve this goal?</p>
<p>Here's the code I currently have:</p>
<p><strong>Update:</strong>
On the second line, the capital letters aren't converted to spaces, so it's pretty messed up.</p>
<p>I want the result to be: <code> Am Em C G C G </code></p>
<pre class="lang-html prettyprint-override"><code><div class="chord">
abcd ef<span>Am</span>ghi jklmn op<span>Em</span>
Yes<span>C</span>uvwxyz abcDE<span>G</span>Fghijk
qrst<span>C</span>uvwxyz abcde<span>G</span>fghijk
</div>
</code></pre>
<pre><code>$('.chord').each(function() {
var $this = $(this);
$this.html($this.text().replace(/a|c|d|e|f|g|h|i|j|k|l|n|o|p|q|r|s|t|u|v|w|x|y|z|<|>|\/|"|'|=|_|-|1|2|3|4|5|6|7|8|9|0/g, " ")
.replace(/ b| m/g, " ")
.replace(/\[ | \]|\( | \)|\[\(|\)\]| :|\nm|\nb|\n\n/g, "\n")
);
});
</code></pre>
|
[
{
"answer_id": 74636961,
"author": "DCodeMania",
"author_id": 8546303,
"author_profile": "https://Stackoverflow.com/users/8546303",
"pm_score": -1,
"selected": false,
"text": "const chord = document.querySelector('.chord');\nconst span = chord.querySelectorAll('span');\nconst spanText = [];\nspan.forEach((item) => {\n spanText.push(item.innerText);\n});\nconsole.log(spanText); <div class=\"chord\">\n\n abcd ef<span>Am</span>ghi jklmn op<span>Em</span>\n Yes<span>C</span>uvwxyz abcDE<span>G</span>Fghijk\n qrst<span>C</span>uvwxyz abcde<span>G</span>fghijk\n\n</div>"
},
{
"answer_id": 74637027,
"author": "Heretic Monkey",
"author_id": 215552,
"author_profile": "https://Stackoverflow.com/users/215552",
"pm_score": 2,
"selected": true,
"text": "<div class=\"chord\"> .chord span const container = document.querySelector('.chord');\nfor (const kid of container.childNodes) {\n if (kid.nodeType === Node.TEXT_NODE) {\n kid.nodeValue = \" \".repeat(kid.nodeValue.length);\n }\n} .chord { white-space: pre; font-family: monospace; } <div class=\"chord\">\n\nabcd ef<span>Am</span>ghi jklmn op<span>Em</span>\nYes<span>C</span>uvwxyz abcDE<span>G</span>Fghijk\nqrst<span>C</span>uvwxyz abcde<span>G</span>fghijk\n\n</div>"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20558795/"
] |
74,636,853
|
<p>I am not able to show the report to the management team in proper format. if you guys have any standared format or global format then please suggest me.</p>
|
[
{
"answer_id": 74636961,
"author": "DCodeMania",
"author_id": 8546303,
"author_profile": "https://Stackoverflow.com/users/8546303",
"pm_score": -1,
"selected": false,
"text": "const chord = document.querySelector('.chord');\nconst span = chord.querySelectorAll('span');\nconst spanText = [];\nspan.forEach((item) => {\n spanText.push(item.innerText);\n});\nconsole.log(spanText); <div class=\"chord\">\n\n abcd ef<span>Am</span>ghi jklmn op<span>Em</span>\n Yes<span>C</span>uvwxyz abcDE<span>G</span>Fghijk\n qrst<span>C</span>uvwxyz abcde<span>G</span>fghijk\n\n</div>"
},
{
"answer_id": 74637027,
"author": "Heretic Monkey",
"author_id": 215552,
"author_profile": "https://Stackoverflow.com/users/215552",
"pm_score": 2,
"selected": true,
"text": "<div class=\"chord\"> .chord span const container = document.querySelector('.chord');\nfor (const kid of container.childNodes) {\n if (kid.nodeType === Node.TEXT_NODE) {\n kid.nodeValue = \" \".repeat(kid.nodeValue.length);\n }\n} .chord { white-space: pre; font-family: monospace; } <div class=\"chord\">\n\nabcd ef<span>Am</span>ghi jklmn op<span>Em</span>\nYes<span>C</span>uvwxyz abcDE<span>G</span>Fghijk\nqrst<span>C</span>uvwxyz abcde<span>G</span>fghijk\n\n</div>"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20652161/"
] |
74,636,865
|
<p>I'm stumped as to why my solution for the Recursive Digit Sum question on HackerRank is being rejected.</p>
<h1>Background</h1>
<p><strong>The question:</strong></p>
<p>For an input of string n and integer k, the number h is created by concatenating n "k" times. Find the "super digit" of h by recursively summing the integers until one is left.</p>
<p><strong>For example:</strong></p>
<ul>
<li>n = '9875', k = 2, so h = 98759875</li>
<li>sum(98759875)= 58</li>
<li>sum(58)= 13</li>
<li>sum(13) = 4</li>
</ul>
<h1>Submissions</h1>
<h2>My Solution</h2>
<pre><code>def superDigit(n, k):
h=n*k
while len(h)>1:
h=str(sum([int(i) for i in h]))
return int(h)
</code></pre>
<h2>Solution I've Found</h2>
<pre><code>def superDigit(n, k):
return 1 + (k * sum(int(x) for x in n) - 1) % 9
</code></pre>
<h1>My Inquiry to the Community</h1>
<p>What am I missing in my solution? Yes it's not as simple as the supplied solution involving the digital root function (which I don't fully understand, I just found it online) but I don't see how my function is supplying incorrect answers. It passes most of the test cases but is rejecting for 1/3 of them.</p>
|
[
{
"answer_id": 74637139,
"author": "scr",
"author_id": 18781246,
"author_profile": "https://Stackoverflow.com/users/18781246",
"pm_score": 1,
"selected": false,
"text": "str int str >>> \"10\"*\"2\"\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: can't multiply sequence by non-int of type 'str'\n int h sum >>> str(sum([int(i) for i in 100]))\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: 'int' object is not iterable\n int str >>> 10 * \"2\"\n'2222222222'\n int str def superDigit(n: int, k:int) -> int:\n h=str(n*k)\n while len(h)>1:\n h=str(sum([int(i) for i in h]))\n return int(h)\n"
},
{
"answer_id": 74646220,
"author": "P-Sides",
"author_id": 10719083,
"author_profile": "https://Stackoverflow.com/users/10719083",
"pm_score": 1,
"selected": true,
"text": "h=str(sum([int(i) for i in n])*(k%9))"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10719083/"
] |
74,636,869
|
<p>I have the following list of dicts:</p>
<pre><code>lst = [{'a':1, 'b':2, 'c':3}, {'a':1, 'b':2, 'd':3}, {'a':1, 'c':2, 'k':3}, {'d':1, 'k':2, 'l':3}]
</code></pre>
<p>I want to filter the list of dicts (in my case it's a list of thousands or even more dicts, with different keys with some overlap) to be a list containing all the dicts that have keys: ["a", "b"]. I want to filter each dict only to these <code>a</code> and <code>b</code> keys, and if they don't exist, don't include the dictionary in the final list. I am using:</p>
<pre><code>[{"a": d.get("a"), "b": d.get("b")} for d in lst]
</code></pre>
<p>Please advise for an elegant way to solve it.</p>
|
[
{
"answer_id": 74636892,
"author": "wim",
"author_id": 674039,
"author_profile": "https://Stackoverflow.com/users/674039",
"pm_score": 2,
"selected": false,
"text": "<= >>> keys = set(\"ab\")\n>>> [{k: d[k] for k in keys} for d in lst if keys <= d.keys()]\n[{'a': 1, 'b': 2}, {'a': 1, 'b': 2}]\n"
},
{
"answer_id": 74661632,
"author": "SteveS",
"author_id": 1030099,
"author_profile": "https://Stackoverflow.com/users/1030099",
"pm_score": 1,
"selected": true,
"text": "lst = [{'a':1, 'b':2, 'c':3}, {'a':1, 'b':2, 'd':3}, {'a':1, 'c':2, 'k':3}, {'d':1, 'k':2, 'l':3}]\nkeys = set(\"ab\")\n[i for i in [{k: d.get(k) for k in keys if k in d} for d in lst] if i]\n [{'b': 2, 'a': 1}, {'b': 2, 'a': 1}, {'a': 1}]\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030099/"
] |
74,636,899
|
<p>Apologize for title. Having trouble explaining this.</p>
<p>I am running into an issue, and I am not sure what the best approach is here. Please see table picture. In this data set I need to find the date prd1 date in the prd2 column. If found, I need to then look at the dense_rnk column minus 1 and grab the value in the VAL column.</p>
<p>For example: 4/10 was found and the dense_rnk is 4 minus 1 is 3. The value needed in the output column is Z because it corresponds to dense_rnk 3. Should be driven by the dates on prd1.</p>
<p>Is there an excel offset comparable function that I can use in oracle? I added the window function thinking it would help, but it made everything more complicated.</p>
<p>Is this even possible? I appreciate any help here.</p>
<p><a href="https://i.stack.imgur.com/bzfDo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bzfDo.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74636892,
"author": "wim",
"author_id": 674039,
"author_profile": "https://Stackoverflow.com/users/674039",
"pm_score": 2,
"selected": false,
"text": "<= >>> keys = set(\"ab\")\n>>> [{k: d[k] for k in keys} for d in lst if keys <= d.keys()]\n[{'a': 1, 'b': 2}, {'a': 1, 'b': 2}]\n"
},
{
"answer_id": 74661632,
"author": "SteveS",
"author_id": 1030099,
"author_profile": "https://Stackoverflow.com/users/1030099",
"pm_score": 1,
"selected": true,
"text": "lst = [{'a':1, 'b':2, 'c':3}, {'a':1, 'b':2, 'd':3}, {'a':1, 'c':2, 'k':3}, {'d':1, 'k':2, 'l':3}]\nkeys = set(\"ab\")\n[i for i in [{k: d.get(k) for k in keys if k in d} for d in lst] if i]\n [{'b': 2, 'a': 1}, {'b': 2, 'a': 1}, {'a': 1}]\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16669577/"
] |
74,636,955
|
<p>I need a python program for converting an input sentence into Pig Latin which has 2 rules:</p>
<ol>
<li>If a word begins with a consonant all consonants before the first vowel are moved to the end of the word and the letters "ay" are then added to the end. e.g. "coin" becomes "oincay" and "flute" becomes "uteflay".</li>
<li>If a word begins with a vowel then "yay" is added to the end. e.g."egg" becomes "eggyay" and "oak" becomes "oakyay".</li>
</ol>
<p>I have written this program so far:</p>
<pre><code>string = input('String: ')
if string[0].upper() in 'BCDFGJKLMNPQSTVXZHRWY':
print(string.replace(string[0],'') + string[0]+'ay')
if string[0].upper() in 'AEIOUY':
print(string + 'yay')
#vowels = [each for each in
</code></pre>
<p>but this only works for one word(whereas i need the whole sentence), and the first part only replaces the first consonant, not all (whereas I need to replace all consonants before the first vowel)</p>
|
[
{
"answer_id": 74636892,
"author": "wim",
"author_id": 674039,
"author_profile": "https://Stackoverflow.com/users/674039",
"pm_score": 2,
"selected": false,
"text": "<= >>> keys = set(\"ab\")\n>>> [{k: d[k] for k in keys} for d in lst if keys <= d.keys()]\n[{'a': 1, 'b': 2}, {'a': 1, 'b': 2}]\n"
},
{
"answer_id": 74661632,
"author": "SteveS",
"author_id": 1030099,
"author_profile": "https://Stackoverflow.com/users/1030099",
"pm_score": 1,
"selected": true,
"text": "lst = [{'a':1, 'b':2, 'c':3}, {'a':1, 'b':2, 'd':3}, {'a':1, 'c':2, 'k':3}, {'d':1, 'k':2, 'l':3}]\nkeys = set(\"ab\")\n[i for i in [{k: d.get(k) for k in keys if k in d} for d in lst] if i]\n [{'b': 2, 'a': 1}, {'b': 2, 'a': 1}, {'a': 1}]\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20652287/"
] |
74,636,957
|
<p>Here is my function call using the std::thread library.</p>
<pre><code>threads.push_back(std::thread(&polynomial::multiply, this, std::cref(chunck[i]), std::cref(poly), std::ref(result_vector[i].poly)));
</code></pre>
<p>This is my function declarations:</p>
<pre><code>void polynomial::multiply(const std::unordered_map<power, coeff> &vector_current, const std::unordered_map<power, coeff> &other, std::unordered_map<power, coeff> &result)
</code></pre>
<p>I fail to understand why this is not compiling. Could anyone help me out.</p>
<pre><code> /usr/include/c++/11/bits/std_thread.h: In instantiation of
‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (polynomial::*)(const std::unordered_map<long unsigned int, int>&, const std::unordered_map<long unsigned int, int>&, std::unordered_map<long unsigned int, int>&); _Args = {const polynomial*, std::reference_wrapper<const std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > > >, std::reference_wrapper<const std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > > >, std::reference_wrapper<std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > > >}; <template-parameter-1-3> = void]’:
poly.cpp:88:142: required from here
/usr/include/c++/11/bits/std_thread.h:130:72: error: static assertion failed: std::thread arguments must be invocable after conversion to rvalues
130 | typename decay<_Args>::type...>::value,
| ^~~~~
/usr/include/c++/11/bits/std_thread.h:130:72: note: ‘std::integral_constant<bool, false>::value’ evaluates to false
/usr/include/c++/11/bits/std_thread.h: In instantiation of ‘struct std::thread::_Invoker<std::tuple<void (polynomial::*)(const std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > >&, const std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > >&, std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > >&), const polynomial*, std::reference_wrapper<const std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > > >, std::reference_wrapper<const std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > > >, std::reference_wrapper<std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > > > > >’:
/usr/include/c++/11/bits/std_thread.h:203:13: required from ‘struct std::thread::_State_impl<std::thread::_Invoker<std::tuple<void (polynomial::*)(const std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > >&, const std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > >&, std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > >&), const polynomial*, std::reference_wrapper<const std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > > >, std::reference_wrapper<const std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > > >, std::reference_wrapper<std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > > > > > >’
/usr/include/c++/11/bits/std_thread.h:143:29: required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (polynomial::*)(const std::unordered_map<long unsigned int, int>&, const std::unordered_map<long unsigned int, int>&, std::unordered_map<long unsigned int, int>&); _Args = {const polynomial*, std::reference_wrapper<const std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > > >, std::reference_wrapper<const std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > > >, std::reference_wrapper<std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > > >}; <template-parameter-1-3> = void]’
poly.cpp:88:142: required from here
/usr/include/c++/11/bits/std_thread.h:252:11: error: no type named ‘type’ in ‘struct std::thread::_Invoker<std::tuple<void (polynomial::*)(const std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > >&, const std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > >&, std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > >&), const polynomial*, std::reference_wrapper<const std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > > >, std::reference_wrapper<const std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > > >, std::reference_wrapper<std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > > > > >::__result<std::tuple<void (polynomial::*)(const std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > >&, const std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > >&, std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > >&), const polynomial*, std::reference_wrapper<const std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > > >, std::reference_wrapper<const std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > > >, std::reference_wrapper<std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > > > > >’
252 | _M_invoke(_Index_tuple<_Ind...>)
| ^~~~~~~~~
/usr/include/c++/11/bits/std_thread.h:256:9: error: no type named ‘type’ in ‘struct std::thread::_Invoker<std::tuple<void (polynomial::*)(const std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > >&, const std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > >&, std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > >&), const polynomial*, std::reference_wrapper<const std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > > >, std::reference_wrapper<const std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > > >, std::reference_wrapper<std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > > > > >::__result<std::tuple<void (polynomial::*)(const std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > >&, const std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > >&, std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > >&), const polynomial*, std::reference_wrapper<const std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > > >, std::reference_wrapper<const std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > > >, std::reference_wrapper<std::unordered_map<long unsigned int, int, std::hash<long unsigned int>, std::equal_to<long unsigned int>, std::allocator<std::pair<const long unsigned int, int> > > > > >’
256 | operator()()
</code></pre>
|
[
{
"answer_id": 74637001,
"author": "273K",
"author_id": 6752050,
"author_profile": "https://Stackoverflow.com/users/6752050",
"pm_score": 1,
"selected": false,
"text": "_Args = {const polynomial*, ...\n const void polynomial::multiply(const std::unordered_map<power, coeff> &vector_current, const std::unordered_map<power, coeff> &other, std::unordered_map<power, coeff> &result) const\n"
},
{
"answer_id": 74637034,
"author": "Pepijn Kramer",
"author_id": 16649550,
"author_profile": "https://Stackoverflow.com/users/16649550",
"pm_score": 0,
"selected": false,
"text": "#include <iostream>\n#include <future>\n#include <vector>\n\nclass SomeClass\n{\npublic:\n void some_function(int x)\n {\n std::cout << x << \"\\n\";\n }\n};\n\n\nint main()\n{\n SomeClass some_class;\n\n {\n std::vector<std::future<void>> futures;\n\n auto future1 = std::async(std::launch::async, [&] { some_class.some_function(1); });\n auto future2 = std::async(std::launch::async, [&] { some_class.some_function(2); });\n\n futures.emplace_back(std::move(future1));\n futures.emplace_back(std::move(future2));\n\n // now vector will go out of scope and synchronize with the futures in it \n // (wait for threads to complete)\n }\n\n return 0;\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19586504/"
] |
74,636,990
|
<p>I have a column in a dataframe holding subjects:</p>
<pre><code>sub <- c("A", "A", "B", "C", "C", "C", "D", "E", "F", "F")
subjects <- data.frame(sub)
</code></pre>
<p>I have another data frame containing columns of subjects (where subjects are only found in one column):</p>
<pre><code>one <- c("A", "C", "F")
two <- c("B", "D", NA)
three <- c("E", NA, NA)
newsubjects <- data.frame(one, two, three)
</code></pre>
<p>I'm wanting to rename the subjects in the first dataframe to the column name found in the second dataframe corresponding to that subject.</p>
<p>So for example, I want the A, C, and F subjects in the first dataframe to be renamed 'one'. Doing this manually would take a long time so I'm hoping theres a way to use the columns in the second data frame to do this.</p>
<p>I've tried a bunch of stuff with forcats::fct_recode and levels but nothing works because I'm not using these functions correctly. Eg IIRC one of my attempts looked something like this:</p>
<pre><code>subjects %>%
mutate(new_var = forcats::fct_recode(sub,
!!! setNames(as.character(subjects$sub), newsubjects$one)))
</code></pre>
<p>Which I know is completely wrong. Part of the problem is it's difficult fo me to articulate my problem in a way that returns relevant search results. Thank you for any help you can provide, I appreciate it.</p>
|
[
{
"answer_id": 74637064,
"author": "Jon Spring",
"author_id": 6851825,
"author_profile": "https://Stackoverflow.com/users/6851825",
"pm_score": 1,
"selected": false,
"text": "newsubjects library(tidyverse)\nsubjects %>%\n left_join(newsubjects %>% \n pivot_longer(everything(), names_to = \"new_sub\", values_to = \"sub\")) \n\nJoining, by = \"sub\"\n sub new_sub\n1 A one\n2 A one\n3 B two\n4 C one\n5 C one\n6 C one\n7 D two\n8 E three\n9 F one\n10 F one\n"
},
{
"answer_id": 74637073,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 3,
"selected": true,
"text": "purrr::map() newsubjects forcats::fct_collapse() subjects library(purrr)\nlibrary(forcats)\n\nnew_ids <- map(newsubjects, ~ .x[!is.na(.x)])\n\nsubjects$sub <- fct_collapse(subjects$sub, !!!new_ids)\n\nsubjects\n sub\n1 one\n2 one\n3 two\n4 one\n5 one\n6 one\n7 two\n8 three\n9 one\n10 one\n"
},
{
"answer_id": 74637136,
"author": "QHarr",
"author_id": 6241235,
"author_profile": "https://Stackoverflow.com/users/6241235",
"pm_score": 0,
"selected": false,
"text": "library(dplyr)\n\nsub <- c(\"A\", \"A\", \"B\", \"C\", \"C\", \"C\", \"D\", \"E\", \"F\", \"F\")\nsubjects <- data.frame(sub)\n\none <- c(\"A\", \"C\", \"F\")\ntwo <- c(\"B\", \"D\", NA)\nthree <- c(\"E\", NA, NA)\n\nadditions <- c(one, two, three)\n\nlookup <- data.frame(\n sub = additions %>% unlist(), \n value = rep(1:length(additions), each=length(additions[[1]])))\n\nsubjects %>% inner_join(lookup) %>% select(value)\n"
},
{
"answer_id": 74637641,
"author": "Just James",
"author_id": 19730031,
"author_profile": "https://Stackoverflow.com/users/19730031",
"pm_score": 0,
"selected": false,
"text": "gsub(\"\\\\d\", \"\", names(unlist(newsubjects))[match(subjects$sub, unlist(newsubjects))])\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74636990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7093643/"
] |
74,637,006
|
<p>I have two tables, user:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>full_name</th>
<th>is_admin</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>jane</td>
<td>0</td>
</tr>
<tr>
<td>2</td>
<td>Helio</td>
<td>0</td>
</tr>
<tr>
<td>3</td>
<td>fran</td>
<td>0</td>
</tr>
<tr>
<td>4</td>
<td>mila</td>
<td>0</td>
</tr>
<tr>
<td>5</td>
<td>admin</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
<p>approver :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>subordinate_id</th>
<th>approver_id</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
</tbody>
</table>
</div>
<p>and I would like to perform a query that brings up the user names that do not have the id in the subordinate_id column of the approvers table.</p>
<p>I tried it this way:</p>
<pre><code>SELECT
full_name
FROM user AS U
WHERE NOT EXISTS(
SELECT * FROM approver AS A
WHERE A.subordinate_id = U.id AND U.is_admin = 0);
</code></pre>
<p>but in this case the admin user is still coming, and I would like to not bring whoever has the is_admin column of the usuario table = 1. I want to bring only common users and not admin.</p>
<p>Can someone help me with this?</p>
|
[
{
"answer_id": 74637064,
"author": "Jon Spring",
"author_id": 6851825,
"author_profile": "https://Stackoverflow.com/users/6851825",
"pm_score": 1,
"selected": false,
"text": "newsubjects library(tidyverse)\nsubjects %>%\n left_join(newsubjects %>% \n pivot_longer(everything(), names_to = \"new_sub\", values_to = \"sub\")) \n\nJoining, by = \"sub\"\n sub new_sub\n1 A one\n2 A one\n3 B two\n4 C one\n5 C one\n6 C one\n7 D two\n8 E three\n9 F one\n10 F one\n"
},
{
"answer_id": 74637073,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 3,
"selected": true,
"text": "purrr::map() newsubjects forcats::fct_collapse() subjects library(purrr)\nlibrary(forcats)\n\nnew_ids <- map(newsubjects, ~ .x[!is.na(.x)])\n\nsubjects$sub <- fct_collapse(subjects$sub, !!!new_ids)\n\nsubjects\n sub\n1 one\n2 one\n3 two\n4 one\n5 one\n6 one\n7 two\n8 three\n9 one\n10 one\n"
},
{
"answer_id": 74637136,
"author": "QHarr",
"author_id": 6241235,
"author_profile": "https://Stackoverflow.com/users/6241235",
"pm_score": 0,
"selected": false,
"text": "library(dplyr)\n\nsub <- c(\"A\", \"A\", \"B\", \"C\", \"C\", \"C\", \"D\", \"E\", \"F\", \"F\")\nsubjects <- data.frame(sub)\n\none <- c(\"A\", \"C\", \"F\")\ntwo <- c(\"B\", \"D\", NA)\nthree <- c(\"E\", NA, NA)\n\nadditions <- c(one, two, three)\n\nlookup <- data.frame(\n sub = additions %>% unlist(), \n value = rep(1:length(additions), each=length(additions[[1]])))\n\nsubjects %>% inner_join(lookup) %>% select(value)\n"
},
{
"answer_id": 74637641,
"author": "Just James",
"author_id": 19730031,
"author_profile": "https://Stackoverflow.com/users/19730031",
"pm_score": 0,
"selected": false,
"text": "gsub(\"\\\\d\", \"\", names(unlist(newsubjects))[match(subjects$sub, unlist(newsubjects))])\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12321753/"
] |
74,637,025
|
<p>Student ID, Assignment, <strong>Score</strong><br />
123456, Zany Text, 100 <br />
123456, Magic 9 Ball, 60<br />
123456, Nim Grab, 80<br />
123456, Dungeon Crawl, 78<br />
123456, Ultimate TODO List, 90<br />
654321, Zany Text, 48</p>
<p>This is the content of the .txt file, I need to iterate through this text and get the average <strong>Score</strong> of all the students (and do some other stuff, but ill figure that out later).</p>
<p>Tried putting all the content in a 2d tuple, which worked but i couldnt reference any of the elements in the list inside the list - print(tup[1][1]) gave error list index out of range but print(tup[1]) did not.</p>
<p>my code-</p>
<pre><code>infile=open("scores.txt", "r")
total=0
i=0
tup=[]
for i in range (7):
tup.append([])
tup[0].append(infile.readline().split(","))
b=''
for i in range(1, len(tup)):
tup[i].append(infile.readline().split(","))
for i in range(0,len(tup)):
for j in range(len(tup[i])):
print(tup[i][j], end=' ')
print()
</code></pre>
|
[
{
"answer_id": 74637302,
"author": "Jack Reilly",
"author_id": 6741576,
"author_profile": "https://Stackoverflow.com/users/6741576",
"pm_score": 0,
"selected": false,
"text": "tup.append .readline() strip for item in list: \ninfile=open(\"scores.txt\", \"r\")\ntable = []\ntable.append(infile.readline().strip().split(\",\"))\nfor _ in range(16):\n table.append(infile.readline().strip().split(\",\"))\nfor row in table:\n for col in row:\n print(col, end=' ')\n print()\ntotal = sum(int(row[-1]) for row in table[1:] if row[-1])\nprint(total)\n"
},
{
"answer_id": 74637398,
"author": "louis joseph",
"author_id": 20652486,
"author_profile": "https://Stackoverflow.com/users/20652486",
"pm_score": 0,
"selected": false,
"text": "import csv\n\n# opening the CSV file\nwith open('score.csv', mode='r')as file:\n\n # reading the CSV file\n csvFile = csv.reader(file)\n # removing Headers from the file\n header = next(csvFile)\n # displaying the contents of the CSV file\n\n avg_score = 0\n total_score = 0\n total_row = 0\n\n for lines in csvFile:\n total_score += int(lines[2])\n total_row += 1\n\n avg_score = total_score/total_row\n print(avg_score)\n"
},
{
"answer_id": 74637410,
"author": "igrinis",
"author_id": 8505817,
"author_profile": "https://Stackoverflow.com/users/8505817",
"pm_score": 2,
"selected": true,
"text": "# read the file\ncontent = []\nwith open(\"scores.txt\", \"r\") as infile:\n for line in infile:\n if not line.isspace(): # skip empty lines\n content.append(line.strip().split(','))\n\n# print the content \nfor row in content:\n for element in row:\n print(el, end=' ')\n print()\n\nmean = sum([float(x[-1]) for x in content[1:]])/(len(content)-1)\nprint(mean)\n list comprehension"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20414189/"
] |
74,637,087
|
<p>I'm working with a subscription that has a few different deployed environments (dev, test, staging, etc.). Each environment has its own storage account, containing an associated Terraform state file. These environments get deployed via Azure DevOps Pipelines.</p>
<p>It's easy enough to get at the .tfstate files that have been created this way, through the portal, CLI, etc.</p>
<p>But is it possible to access these state files using the 'terraform state' commands, for example using Azure Cloud Shell? If so, how do you point them at the right location?</p>
<p>I've tried using the terraform state commands in a Cloud Shell, but it's not clear how to point them to the right location or if this is indeed possible.</p>
|
[
{
"answer_id": 74650505,
"author": "Bowman Zhu-MSFT",
"author_id": 6261890,
"author_profile": "https://Stackoverflow.com/users/6261890",
"pm_score": 0,
"selected": false,
"text": "AzurePowerShell - task: AzurePowerShell@5\n inputs:\n azureSubscription: 'testbowman_in_AAD' #This service connection related to service principal on Azure side.\n ScriptType: 'InlineScript'\n Inline: |\n # Put your logic here.\n # Put your logic here.\n azurePowerShellVersion: 'LatestVersion'\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20642679/"
] |
74,637,105
|
<p>i am a beginner in C++ and my question is:
why my vector in a class is empty when i try to access that vector elements in another class after i added elements to that vector?</p>
<p>i have a class for example <strong>class1</strong> and this class has a vector of type string and a member function which adds elements to the vector with push_back() and another member function which has an argument of type string and it returns true if the argument is in the vector or else it returns false. now if i write another class <strong>class2</strong> and it has a vector of type string named valid and a member function named check that it reads a string from input and we have a <strong>class1</strong> object that we can access the class1 member function to check if this input is in the vector from <strong>class1</strong> but looks like in <strong>class2</strong> the vector i had in <strong>class1</strong> with elements is empty. what am i doing wrong?</p>
<p>here is code:</p>
<pre><code>class abc{
private:
vector<string> words;
public:
void seta() {
string s;
cout << "word: ";
cin >> s;
words.push_back(s);
}
bool word_check(string a) {
for(string b : words) {
if(b == a) {
return true;
}
}
return false;
}
};
class b{
private:
vector<string> valid;
public:
void check() {
abc mlj;
string k;
cout << "Enter word to check: ";
cin >> k;
bool w = mlj.word_check(k);
while(w == false) {
cerr << "invalid input, try again: ";
cin.clear();
cin.ignore(INT_MAX, '\n');
cin >> k;
}
valid.push_back(k);
}
};
int main() {
abc vkk;
vkk.seta();
vkk.seta();
vkk.seta();
b pla;
pla.check();
}
</code></pre>
<p><a href="https://i.stack.imgur.com/bKaMB.png" rel="nofollow noreferrer">screenshot of the output</a></p>
<p>i was expecting that i can access vector elements in class from another class</p>
|
[
{
"answer_id": 74650505,
"author": "Bowman Zhu-MSFT",
"author_id": 6261890,
"author_profile": "https://Stackoverflow.com/users/6261890",
"pm_score": 0,
"selected": false,
"text": "AzurePowerShell - task: AzurePowerShell@5\n inputs:\n azureSubscription: 'testbowman_in_AAD' #This service connection related to service principal on Azure side.\n ScriptType: 'InlineScript'\n Inline: |\n # Put your logic here.\n # Put your logic here.\n azurePowerShellVersion: 'LatestVersion'\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20652291/"
] |
74,637,111
|
<p>I have two flatLists nested inside of a scrollView so I am able to scroll my entire page. However, I know that you are not supposed to nest flatLists in scrollViews for multiple reasons.</p>
<p><strong>How can I render two flatLists while still being able to scroll throughout the entire page?</strong> The GIF at the bottom of the post is the desired behavior I want.</p>
<p>I created a <a href="https://snack.expo.dev/@priedejm/f79de9" rel="nofollow noreferrer">snack post here</a> as well as provided some example code below.</p>
<pre><code>export default function App() {
return (
<View style={{ alignItems: 'center', marginTop: 100, flex: 1}}>
<FlatListB/>
<FlatListA/>
</View>
);
}
</code></pre>
<pre><code> return (
<FlatList
data={newData}
renderItem={renderItem}
onEndReached={fetchMoreBars}
onEndReachedThreshold={0.1}
/>
);
</code></pre>
<pre><code> return (
<FlatList
data={newData}
renderItem={renderItem}
onEndReached={fetchMoreBars}
onEndReachedThreshold={0.1}
horizontal={true}
/>
);
</code></pre>
<p><a href="https://giphy.com/gifs/7V07FvYyn8ZG3nwVVU" rel="nofollow noreferrer">https://giphy.com/gifs/7V07FvYyn8ZG3nwVVU</a> - This GIF was created by nesting FlatListB and FlatListA in a ScrollView</p>
|
[
{
"answer_id": 74637632,
"author": "Peter Tam",
"author_id": 20002061,
"author_profile": "https://Stackoverflow.com/users/20002061",
"pm_score": 2,
"selected": true,
"text": "ListHeaderComponent <FlatList\n data={newData}\n renderItem={renderItem}\n onEndReached={fetchMoreBars}\n onEndReachedThreshold={0.1}\n ListHeaderComponent={<FlatListB />}\n />\n export default function App() {\n return (\n <FlatListA/>\n );\n}\n"
},
{
"answer_id": 74637689,
"author": "Hardik prajapati",
"author_id": 18241250,
"author_profile": "https://Stackoverflow.com/users/18241250",
"pm_score": -1,
"selected": false,
"text": " const Data = [1,2,3,4,1,1,1,1,1,1,1,]\nconst Horizontal = () => {\n const Data = [1,2,3,4,1,1,1]\n return <FlatList\n horizontal\n data={Data} renderItem={() => {\n return <View style={{height:100,width:100,backgroundColor:'pink',margin:2}}>\n </View>\n }}/>\n}\nconst ListHeaderComponent = () => {\n return <Horizontal/>\n}\n<View >\n <FlatList\n ListHeaderComponent={ListHeaderComponent}\n data={Data} renderItem={() => {\n return <View style={{height:100,width:100,backgroundColor:'white',margin:2}}>\n </View>\n }}/>\n</View>\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12915212/"
] |
74,637,121
|
<p>Im currently having issues with my first bloc made from 0, it supposed to throw an error once a number reaches a certain number, but i noticed through testing that the event is not receiving any data at all, i have no idea what im doing wrong.</p>
<p>I can confirm that the event is being triggered, on changed the textfield fires the event.</p>
<p>I dont know if it matters yet but if try to int.parse it i recieve null.</p>
<p>Widget with the string that should be sent to the event.</p>
<pre><code>class Daytextfield extends StatelessWidget {
Daytextfield({
Key? key,
required this.digits,
required this.hint,
}) : super(key: key);
final int digits;
final String hint;
final String texto = '';
@override
Widget build(BuildContext context) {
final TextEditingController dias = TextEditingController(text: texto);
Color color = Colors.black;
return BlocConsumer<DaysBloc, DaysState>(
listener: (context, state) {
if(state is DaysIncorrectState){
color = Colors.red;
} else if (state is DaysCorrectState){
color = Colors.green;
}
},
builder: (context, state) {
return TextFormField(
onChanged: (value) {
BlocProvider.of<DaysBloc>(context).add(DaysChangedEvent(texto: texto));
print(state);
// var ree = int.tryParse(texto);
print(texto);
},
controller: dias,
keyboardType: TextInputType.number,
textInputAction: TextInputAction.next,
textAlign: TextAlign.center,
cursorColor: Color.fromARGB(148, 66, 63, 63),
style: Theme.of(context)
.textTheme
.headline1!
.copyWith(fontSize: 20, color: color),
</code></pre>
<p>Blocs</p>
<pre><code>
class DaysBloc extends Bloc<DaysEvent, DaysState> {
int max = 360;
DaysBloc() : super(DaysInitial()) {
on<DaysChangedEvent>((event, emit) {
if(event.texto == '123') {emit(DaysIncorrectState(texto: event.texto));}
else emit(DaysCorrectState(texto: event.texto));
});
}
}
</code></pre>
<pre><code>abstract class DaysEvent extends Equatable {
const DaysEvent();
@override
List<Object> get props => [];
}
class DaysChangedEvent extends DaysEvent {
String texto;
DaysChangedEvent({
required this.texto,
});
@override
List<Object> get props => [texto];
}
</code></pre>
<pre><code>class DaysInitial extends DaysState {}
class DaysCorrectState extends DaysState {
String texto;
DaysCorrectState({
required this.texto,
});
@override
List<Object> get props => [texto];
}
class DaysIncorrectState extends DaysState {
String texto;
DaysIncorrectState({
required this.texto,
});
@override
List<Object> get props => [texto];
}
</code></pre>
|
[
{
"answer_id": 74637632,
"author": "Peter Tam",
"author_id": 20002061,
"author_profile": "https://Stackoverflow.com/users/20002061",
"pm_score": 2,
"selected": true,
"text": "ListHeaderComponent <FlatList\n data={newData}\n renderItem={renderItem}\n onEndReached={fetchMoreBars}\n onEndReachedThreshold={0.1}\n ListHeaderComponent={<FlatListB />}\n />\n export default function App() {\n return (\n <FlatListA/>\n );\n}\n"
},
{
"answer_id": 74637689,
"author": "Hardik prajapati",
"author_id": 18241250,
"author_profile": "https://Stackoverflow.com/users/18241250",
"pm_score": -1,
"selected": false,
"text": " const Data = [1,2,3,4,1,1,1,1,1,1,1,]\nconst Horizontal = () => {\n const Data = [1,2,3,4,1,1,1]\n return <FlatList\n horizontal\n data={Data} renderItem={() => {\n return <View style={{height:100,width:100,backgroundColor:'pink',margin:2}}>\n </View>\n }}/>\n}\nconst ListHeaderComponent = () => {\n return <Horizontal/>\n}\n<View >\n <FlatList\n ListHeaderComponent={ListHeaderComponent}\n data={Data} renderItem={() => {\n return <View style={{height:100,width:100,backgroundColor:'white',margin:2}}>\n </View>\n }}/>\n</View>\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19702304/"
] |
74,637,131
|
<p>I can set dates, times, and type whatever ask I won't successfully and reminders. I do not have receive any error, but I don't have receive any notification, when the task is set. These are my code snippet below:</p>
<pre><code></code></pre>
<p>this is my set alarm class:</p>
<pre><code></code></pre>
<blockquote>
<p>private void setAlarm( String text, String date, String time){
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);</p>
<pre><code>//create an intent to show notification
</code></pre>
<p>Intent intent = new Intent(CreateTask.this, TaskNotificationAlarm.class);
intent.putExtra("event", text);
intent.putExtra("time", date);
intent.putExtra("date", time);</p>
<p>PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_IMMUTABLE);
String dateandtime = date + " " + timeTonotify;
DateFormat formatter = new SimpleDateFormat("d-M-yyyy hh:mm");
try {
Date date1 = formatter.parse(dateandtime);
alarmManager.set(AlarmManager.RTC_WAKEUP, date1.getTime(), pendingIntent);
Toast.makeText(getApplicationContext(), "Alarm", Toast.LENGTH_SHORT).show();
catch (ParseException e) {
e.printStackTrace();
}</p>
<p>Intent intentBack = new Intent(getApplicationContext(), TaskActivity.class);
intentBack.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intentBack);
}</p>
</blockquote>
<pre><code>
this is my notification class:
</code></pre>
<blockquote>
<p>public class TaskNotificationAlarm extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
String text = bundle.getString("event");
String description = bundle.getString("event description");
String date = bundle.getString("date") + "" + bundle.getString("time");</p>
<p>Intent intent1 = new Intent(context, AlertDetails.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent1.putExtra("message", text);</p>
<p>PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent1, PendingIntent.FLAG_ONE_SHOT);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "notify_001");</p>
<p>RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.activity_notification);
PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
contentView.setOnClickPendingIntent(R.id.flashButton, pendingSwitchIntent);
contentView.setTextViewText(R.id.message, text);
contentView.setTextViewText(R.id.date, date);
builder.setSmallIcon(R.drawable.ic_baseline_calendar);
builder.setAutoCancel(true);
builder.setOngoing(true);
builder.setAutoCancel(true);
builder.setPriority(Notification.PRIORITY_HIGH);
builder.setOnlyAlertOnce(true);
builder.build().flags = Notification.FLAG_NO_CLEAR | Notification.PRIORITY_HIGH;
builder.setContent(contentView);
builder.setContentIntent(pendingIntent);</p>
<p>if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
String channelId = "channel_id";
NotificationChannel channel = new NotificationChannel(channelId, "channel name", NotificationManager.IMPORTANCE_HIGH);
channel.enableVibration(true);
notificationManager.createNotificationChannel(channel);
builder.setChannelId(channelId);
}
Notification notification = builder.build();
notificationManager.notify(1, notification);
}
}</p>
</blockquote>
<pre><code></code></pre>
<pre><code></code></pre>
|
[
{
"answer_id": 74637320,
"author": "Sadegh.t",
"author_id": 6166210,
"author_profile": "https://Stackoverflow.com/users/6166210",
"pm_score": 0,
"selected": false,
"text": "alarmManager.set alarmManager.setAlarmClock()"
},
{
"answer_id": 74639099,
"author": "Vishal Shah",
"author_id": 17552167,
"author_profile": "https://Stackoverflow.com/users/17552167",
"pm_score": 4,
"selected": true,
"text": "onReceive() private void createNotificationChannel() {\n // Write your channel creation code here\n Log.d(\"TAG\",\"Notification Channel Running\")\n}\nprivate void createNotification() {\n// Write your notification builder code here\nLog.d(\"TAG\",\"Notification Builder Running\")\n}\n <receiver\n android:name=\".TaskNotificationAlarm\"\n android:enabled=\"true\"\n android:exported=\"false\" />\n <application></application> setAndAllowWhileIdle() private AlarmManager alarmManager;\nalarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);\nalarmManager.setAndAllowWhileIdle (int type, \n long triggerAtMillis, \n PendingIntent operation)\n alarmManager.cancel()"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20023087/"
] |
74,637,152
|
<p>I have 2 tables: dish and rating. Dish:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>pizza</td>
</tr>
<tr>
<td>2</td>
<td>wok</td>
</tr>
<tr>
<td>3</td>
<td>sushi</td>
</tr>
</tbody>
</table>
</div>
<p>Rating:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">dish</th>
<th style="text-align: center;">rate</th>
<th style="text-align: right;">user</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">1</td>
<td style="text-align: center;">10</td>
<td style="text-align: right;">1</td>
</tr>
<tr>
<td style="text-align: left;">1</td>
<td style="text-align: center;">4</td>
<td style="text-align: right;">2</td>
</tr>
<tr>
<td style="text-align: left;">2</td>
<td style="text-align: center;">2</td>
<td style="text-align: right;">1</td>
</tr>
</tbody>
</table>
</div>
<p><strong>In dish</strong>: id is primary.
<strong>In rating</strong>: dish is foreign key to dish.id table and user is foreign key also but don't worry about user.</p>
<p>So i need to count average rating of each dish.</p>
<p>It will look like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>dishID</th>
<th>aver. rate</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>7</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>0</td>
</tr>
</tbody>
</table>
</div>
<p>i dunno how to write such a hard SQL request
need help :3</p>
|
[
{
"answer_id": 74637320,
"author": "Sadegh.t",
"author_id": 6166210,
"author_profile": "https://Stackoverflow.com/users/6166210",
"pm_score": 0,
"selected": false,
"text": "alarmManager.set alarmManager.setAlarmClock()"
},
{
"answer_id": 74639099,
"author": "Vishal Shah",
"author_id": 17552167,
"author_profile": "https://Stackoverflow.com/users/17552167",
"pm_score": 4,
"selected": true,
"text": "onReceive() private void createNotificationChannel() {\n // Write your channel creation code here\n Log.d(\"TAG\",\"Notification Channel Running\")\n}\nprivate void createNotification() {\n// Write your notification builder code here\nLog.d(\"TAG\",\"Notification Builder Running\")\n}\n <receiver\n android:name=\".TaskNotificationAlarm\"\n android:enabled=\"true\"\n android:exported=\"false\" />\n <application></application> setAndAllowWhileIdle() private AlarmManager alarmManager;\nalarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);\nalarmManager.setAndAllowWhileIdle (int type, \n long triggerAtMillis, \n PendingIntent operation)\n alarmManager.cancel()"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20648314/"
] |
74,637,159
|
<p>I have a program that uses a large amount of stack. I use Linux, and so have already set the stack size limit via <code>ulimit -s 1048576</code>.</p>
<p>Running <code>cargo test -- --test-threads 1</code> works as expected, but when I use more than one thread, e.g. <code>cargo test -- --test-threads 2</code>, I get <code>fatal runtime error: stack overflow</code>. I believe this is because the Rust thread default stack size, used when running tests, is too small.</p>
<p>How do I increase this stack size when running <code>cargo test</code>?</p>
|
[
{
"answer_id": 74637444,
"author": "Ana",
"author_id": 1002430,
"author_profile": "https://Stackoverflow.com/users/1002430",
"pm_score": 2,
"selected": false,
"text": "RUST_MIN_STACK RUST_MIN_STACK=104857600 cargo test"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1002430/"
] |
74,637,179
|
<p>I have tried to use media queries and display: none in my CSS, but it does not hide the text on a smaller screen. Please help</p>
<p>HTML code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>@media all and (max-width: 600px) {
header h1 {
display: none;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><header class="word">
<h1> MY <span> WEBSITE </span> </h1>
</header></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74637307,
"author": "Kairav Thakar",
"author_id": 20447312,
"author_profile": "https://Stackoverflow.com/users/20447312",
"pm_score": 2,
"selected": false,
"text": "@media screen and (max-width: 600px) {\n header h1 {\n display: none;\n }\n} <header class=\"word\">\n <h1> MY <span> WEBSITE </span> </h1>\n</header> "
},
{
"answer_id": 74666331,
"author": "in2d",
"author_id": 6108371,
"author_profile": "https://Stackoverflow.com/users/6108371",
"pm_score": 1,
"selected": false,
"text": "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20555751/"
] |
74,637,192
|
<p>I am looking for an API that lists all the startup applications in Windows, and can return whether each application is enabled or disabled at startup and it's level of impact.</p>
<p>These settings and the startup apps referred to are found in Settings->Apps->Startup.</p>
<p>I have found PowerShell and command line commands to list some (but not all) of the start up apps. However I am looking for a way to do so programmatically in C# so I do not need to execute a script to list the startup apps. The commands also are limited to the name, command, and location. They do not show whether the startup app is enabled/disabled and the level of impact.</p>
<p>These are the commands I have used to list some of the start up apps.
Powershell: Get-CimInstance Win32_StartupCommand | Select-Object Name, command, Location, User | Format-List</p>
<p>Command Line: wmic startup get caption,command</p>
|
[
{
"answer_id": 74637586,
"author": "ufosnowcat",
"author_id": 1728208,
"author_profile": "https://Stackoverflow.com/users/1728208",
"pm_score": -1,
"selected": false,
"text": "using(PowerShell ps = PowerShell.Create())\n{\n ps.AddCommand(\"the command\")\n .AddParameter(\"parname\",\"value\");\n ps.Invoke();\n Collection<PSObject> result = ps.Invoke();\n foreach(var outputObject in result)\n {\n // outputObject contains the result of the powershell script\n }\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8436436/"
] |
74,637,231
|
<p>I'm trying to write a function that will take a set of arguments from the rows of a 2d array and use them in conjunction with all the elements of a longer 1d array:</p>
<pre><code>x = np.linspace(-10,10,100)
abc = np.array([[1,2,1],
[1,3,5],
[12.5,-6.4,-1.25],
[4,2,1]])
def quadratic(a, b, c, x):
return a*(x ** 2) + b*x + c
y = quadratic(abc[:,0], abc[:,1], abc[:,2], x)
</code></pre>
<p>But this returns:</p>
<pre><code>operands could not be broadcast together with shapes (4,) (100,)
</code></pre>
<p>When I manually enter the a, b and c values, I get a 100-element 1d array, so I would expect this to return a (4,100) array. What gives?</p>
|
[
{
"answer_id": 74637586,
"author": "ufosnowcat",
"author_id": 1728208,
"author_profile": "https://Stackoverflow.com/users/1728208",
"pm_score": -1,
"selected": false,
"text": "using(PowerShell ps = PowerShell.Create())\n{\n ps.AddCommand(\"the command\")\n .AddParameter(\"parname\",\"value\");\n ps.Invoke();\n Collection<PSObject> result = ps.Invoke();\n foreach(var outputObject in result)\n {\n // outputObject contains the result of the powershell script\n }\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20029037/"
] |
74,637,232
|
<p>I am creating a matchmaking function where 2 players with the same weight will be paired.</p>
<p>It is currently working now based on the same weight. Now, I added another condition where players have their own level. My first condition is based on the same weight. This is working. My 2nd condition is about "CLASS", if the players have the same class, they should not be matched/paired.</p>
<pre><code>const source = [
{
entryID: 1,
entryName: "player1",
weight: 1900,
class: ['a', 'b'],
},
{
entryID: 2,
entryName: "player2",
weight: 1900,
class: ['a', 'b'],
},
{
entryID: 3,
entryName: "player3",
weight: 1900,
class: ['c', 'd'],
},
{
entryID: 4,
entryName: "player4",
weight: 1900,
class: ['c', 'd'],
},
];
console.log(combine(source))
function combine(data = [], different = 0, maxGroupSize = 2) {
const groups = [], related = [], sortedData = [...data].sort((a, b) => a.weight - b.weight),
alreadyInRela = (setX, eName) => {
let list = [...setX, eName]
return related.some(rela => list.every(l => rela.has(l)))
};
sortedData.forEach((el, indx) => {
let place = groups.findIndex( // find a place in a group forEach element, use indx as track
g => g.names.size < maxGroupSize // is the group incomplete ?
&& !g.names.has(el.entryName) // is entryName not in the group list (names Set) ?
&& (el.weight - g.weight) <= different
&& !alreadyInRela(g.names, el.entryName) // is (entryName + group list) does not already used ?
)
if (place < 0) { // not found -> create new group
let names = new Set().add(el.entryName) // create new group
groups.push({ names, indxs: [indx], weight: el.weight }) // group constitutive info
related.push(names) // keep track of group list
} else { // find a place in a group
groups[place].names.add(el.entryName) // related list is also updated
groups[place].indxs.push(indx) // add indx to retreive element in sortedData
}
});
return groups.reduce((r, g, i) => { // build result
if (g.indxs.length > 1) {
let key = `${i}_` + g.indxs.map(x => sortedData[x].weight).join('_')
r[key] = []
g.indxs.forEach(x => r[key].push(sortedData[x]))
}
return r
}, {})
}
</code></pre>
<p>My current output:</p>
<pre><code>{
0_1900_1900: [
{
class: ["a", "b"],
entryID: 1,
entryName: "player1",
weight: 1900
},
{
class: ["a", "b"],
entryID: 2,
entryName: "player2",
weight: 1900
}
],
1_1900_1900: [
{
class: ["c", "d"],
entryID: 3,
entryName: "player3",
weight: 1900
},
{
class: ["c", "d"],
entryID: 4,
entryName: "player4",
weight: 1900
}
]
}
</code></pre>
<p>Target output (As we can see here, the players with the same CLASS are not joined/combined. This is what I need to aim for):</p>
<pre><code>{
0_1900_1900: [
{
class: ["a", "b"],
entryID: 1,
entryName: "player1",
weight: 1900
},
{
class: ["c", "d"],
entryID: 3,
entryName: "player3",
weight: 1900
}
],
1_1900_1900: [
{
class: ["a", "b"],
entryID: 2,
entryName: "player2",
weight: 1900
},
{
class: ["c", "d"],
entryID: 4,
entryName: "player4",
weight: 1900
}
]
}
</code></pre>
|
[
{
"answer_id": 74637586,
"author": "ufosnowcat",
"author_id": 1728208,
"author_profile": "https://Stackoverflow.com/users/1728208",
"pm_score": -1,
"selected": false,
"text": "using(PowerShell ps = PowerShell.Create())\n{\n ps.AddCommand(\"the command\")\n .AddParameter(\"parname\",\"value\");\n ps.Invoke();\n Collection<PSObject> result = ps.Invoke();\n foreach(var outputObject in result)\n {\n // outputObject contains the result of the powershell script\n }\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14793352/"
] |
74,637,241
|
<p>I'm trying to set up an elasticsearch index with an array of objects. I tried the following mapping:</p>
<pre><code>{
"mappings": {
"date_detection": false,
"properties": {
"resource": {
"type": "object",
"properties": {
"name": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"uid": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"id": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"source": {
"properties": {
"serviceType": {
"type": "text"
},
"serviceId": {
"type": "text"
},
"state": {
"type": "text"
},
"type": {
"type": "text"
},
"connectorName": {
"type": "text"
},
"displayName": {
"type": "text"
}
}
},
"_key": {
"type": "text"
}
}
},
// other, irrelevnt fields
}
}
}
</code></pre>
<p>And putting the following document:</p>
<pre><code>"resource": [
{
"source": {
"serviceType": "AWS",
"serviceId": "...",
"state": null,
"type": "Source",
"connectorName": "AWS",
"displayName": null
},
"name": "...",
"id": "...",
"_key": "...",
"uid": "..."
},
{
"source": {
"serviceType": "AWS",
"serviceId": "..",
"state": null,
"type": "Source",
"connectorName": "AWS",
"displayName": null
},
"name": "...",
"id": "...",
"_key": "...",
"uid": "..."
}
</code></pre>
<p>However it seems like the resource field is being parsed correctly: <a href="https://i.stack.imgur.com/q2VPz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/q2VPz.png" alt="enter image description here" /></a></p>
<p>I tried playing around with the fields but didn't manage to make it work. What am I missing?</p>
|
[
{
"answer_id": 74638540,
"author": "ESCoder",
"author_id": 10348758,
"author_profile": "https://Stackoverflow.com/users/10348758",
"pm_score": 2,
"selected": false,
"text": "properties {\n \"mappings\": {\n \"properties\": { // note this\n \"resource\": {\n \"type\": \"object\",\n \"properties\": {\n \"name\": {\n \"type\": \"text\",\n \"fields\": {\n \"keyword\": {\n \"type\": \"keyword\",\n \"ignore_above\": 256\n }\n }\n },\n \"uid\": {\n \"type\": \"text\",\n \"fields\": {\n \"keyword\": {\n \"type\": \"keyword\",\n \"ignore_above\": 256\n }\n }\n },\n \"id\": {\n \"type\": \"text\",\n \"fields\": {\n \"keyword\": {\n \"type\": \"keyword\",\n \"ignore_above\": 256\n }\n }\n },\n \"source\": {\n \"properties\": {\n \"serviceType\": {\n \"type\": \"text\"\n },\n \"serviceId\": {\n \"type\": \"text\"\n },\n \"state\": {\n \"type\": \"text\"\n },\n \"type\": {\n \"type\": \"text\"\n },\n \"connectorName\": {\n \"type\": \"text\"\n },\n \"displayName\": {\n \"type\": \"text\"\n }\n }\n },\n \"_key\": {\n \"type\": \"text\"\n }\n }\n }\n }\n }\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1330810/"
] |
74,637,254
|
<p>I have copy pasted data from an Excel file into Google Sheet.
One of the columns has date formatted as - 11-07-2022.
<a href="https://i.stack.imgur.com/FKlHv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FKlHv.png" alt="enter image description here" /></a></p>
<p>Google Sheets is reading it as 11th July, 2022 - whereas I want it to read as 7th Nov, 2022.
While I can just change the format manually in one of the cells, unfortunately I have more than 1000 rows with such date format.</p>
<p>Is there a better way to do it? I searched online and no matter how I changed the format, it only changed the way the date is displayed rather than reading the date as MM-DD-YYYY.</p>
<p>Please help!</p>
|
[
{
"answer_id": 74638952,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 3,
"selected": true,
"text": "=ARRAYFORMULA(IFERROR(REGEXREPLACE(TO_TEXT(A2:A), \n \"(\\d+)/(\\d+)/(\\d{2,4})\", \"$2/$1/$3\")*1, A2:A)*1)\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13170475/"
] |
74,637,278
|
<p>I am testing react functional component where i need to click a button before button click it is using some state which is false i want to make true so that my test case will pass.please help</p>
|
[
{
"answer_id": 74638952,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 3,
"selected": true,
"text": "=ARRAYFORMULA(IFERROR(REGEXREPLACE(TO_TEXT(A2:A), \n \"(\\d+)/(\\d+)/(\\d{2,4})\", \"$2/$1/$3\")*1, A2:A)*1)\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10524249/"
] |
74,637,284
|
<p>I had a dataset like with four columns</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">quarter</th>
<th style="text-align: left;">Year</th>
<th style="text-align: left;">Product</th>
<th style="text-align: left;">state</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">1</td>
<td style="text-align: left;">2022</td>
<td style="text-align: left;">Aspirin</td>
<td style="text-align: left;">VA</td>
</tr>
<tr>
<td style="text-align: left;">1</td>
<td style="text-align: left;">2022</td>
<td style="text-align: left;">Dolo</td>
<td style="text-align: left;">MD</td>
</tr>
<tr>
<td style="text-align: left;">1</td>
<td style="text-align: left;">2022</td>
<td style="text-align: left;">Aspirin</td>
<td style="text-align: left;">VA</td>
</tr>
<tr>
<td style="text-align: left;">1</td>
<td style="text-align: left;">2022</td>
<td style="text-align: left;">Aspirin</td>
<td style="text-align: left;">MD</td>
</tr>
<tr>
<td style="text-align: left;">2</td>
<td style="text-align: left;">2022</td>
<td style="text-align: left;">Aspirin</td>
<td style="text-align: left;">VA</td>
</tr>
<tr>
<td style="text-align: left;">2</td>
<td style="text-align: left;">2022</td>
<td style="text-align: left;">Dolo</td>
<td style="text-align: left;">MD</td>
</tr>
<tr>
<td style="text-align: left;">2</td>
<td style="text-align: left;">2022</td>
<td style="text-align: left;">Dolo</td>
<td style="text-align: left;">VA</td>
</tr>
</tbody>
</table>
</div>
<p>I am trying to get output like</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">quarter</th>
<th style="text-align: left;">Product</th>
<th style="text-align: left;">count</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">1</td>
<td style="text-align: left;">Aspirin</td>
<td style="text-align: left;">3</td>
</tr>
<tr>
<td style="text-align: left;">1</td>
<td style="text-align: left;">Dolo</td>
<td style="text-align: left;">1</td>
</tr>
</tbody>
</table>
</div>
<p>and also bar graph visualization with the product on the x-axis and count on the y-axis.</p>
<p>I've tried many ways by using count, summary also tried to insert the summary count into table to plot the graph.</p>
<pre><code>df_raw <- dmv %>% group_by(quarter, product) %>% summarize(count=n())
table(df_raw)
</code></pre>
<p>tried this also</p>
<pre><code>df1<- dmv[dmv$quarter == 1,] #creating a dataframe for quarter 1
str(df1$product)
df1$product <- as.factor(df1$product_name)
str(df1)
df_product_10 <- names(summary(df1$product)[1:10])
df_product_10_x <- unname(summary(df1$product)[1:10])
rows_id <- seq(1,10)
df2 <- as.data.frame(rows_id, df_product_10, df_product_10_x)
hist(df)
</code></pre>
|
[
{
"answer_id": 74638952,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 3,
"selected": true,
"text": "=ARRAYFORMULA(IFERROR(REGEXREPLACE(TO_TEXT(A2:A), \n \"(\\d+)/(\\d+)/(\\d{2,4})\", \"$2/$1/$3\")*1, A2:A)*1)\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8747361/"
] |
74,637,312
|
<p>Not sure if it something im doing wrong or a bug or a change in .net7 razor pages.</p>
<p>when navigation to a page with a route. the page loads fine and has the route values in the url but does not populate the variables with the values.</p>
<p>my page directive is
@page "/flights/{SourceIATA?}/{DestinationIATA?}"
and is located in Pages\Flights\Index.cshtml
and my varibles are declared.</p>
<pre><code> public class IndexModel : PageModel
{
public string? SourceIATA { get; set; }
public string? DestinationIATA { get; set; }
</code></pre>
<p>am using program.cs.</p>
<pre><code>var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
//builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")) , ServiceLifetime.Transient,
ServiceLifetime.Transient);
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.Configure<RequestLocalizationOptions>(ops =>
{
var cultures = new CultureInfo[] { new CultureInfo("en-US"), new CultureInfo("en-AU")
, new CultureInfo("en-GB")
, new CultureInfo("es-US")
};
ops.SupportedCultures = cultures;
ops.SupportedUICultures = cultures;
ops.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("en-US");
ops.RequestCultureProviders.Insert(0, new RouteSegmentRequestCultureProvider(cultures));
});
builder.Services.AddHttpClient<ITranslator, MyMemoryTranslateService>();
builder.Services.Configure<CookiePolicyOptions>(options =>
{
//gdpr
// This lambda determines whether user consent for non-essential
// cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
// requires using Microsoft.AspNetCore.Http;
options.MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.None;
// options.MinimumSameSitePolicy = SameSiteMode.None;
});
builder.Services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
builder.Services.AddAntiforgery(options =>
{
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
});
builder.Services.Configure<RouteOptions>(options =>
{
options.LowercaseUrls = true;
options.LowercaseQueryStrings = true;
// options.AppendTrailingSlash = true;
});
builder.Services.AddRazorPages()
.AddRazorPagesOptions(ops => { ops.Conventions.Insert(0, new RouteTemplateModelConventionRazorPages()); })
.AddXDbLocalizer<ApplicationDbContext, MyMemoryTranslateService>(ops =>
{
ops.AutoAddKeys = false;
ops.AutoTranslate = false;
ops.UseExpressMemoryCache = false;
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseRequestLocalization();
app.MapRazorPages();
app.Run();
</code></pre>
<p>Has anyone had anything similar with .net 7 or any advices to point me in the right direction would be greatly appreciated.
thanks in advance.</p>
|
[
{
"answer_id": 74638952,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 3,
"selected": true,
"text": "=ARRAYFORMULA(IFERROR(REGEXREPLACE(TO_TEXT(A2:A), \n \"(\\d+)/(\\d+)/(\\d{2,4})\", \"$2/$1/$3\")*1, A2:A)*1)\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9666854/"
] |
74,637,349
|
<p>Please help me how to stop the hover effect. I want a Javascript or Jquery code to stop hover after clicking the values and the list of value will stay. And for the "x" button(close), it will close list of value and reset back to hover.
Thanks in advance.</p>
<p>CSS:
<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>.dropbtn {
background-color: #04AA6D;
color: white;
padding: 16px;
font-size: 16px;
border: none;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content .close{
float:right;
cursor: pointer;
}
.dropdown-content a:hover {background-color: #ddd;}
.dropdown:hover .dropdown-content {display: block;}
.dropdown:hover .dropbtn {background-color: #3e8e41;}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="dropdown">
<button class="dropbtn">Dropdown</button>
<div class="dropdown-content">
<div class="close">x</div>
<a href="#">Value 1</a>
<a href="#">Value 2</a>
<a href="#">Value 3</a>
</div>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74638952,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 3,
"selected": true,
"text": "=ARRAYFORMULA(IFERROR(REGEXREPLACE(TO_TEXT(A2:A), \n \"(\\d+)/(\\d+)/(\\d{2,4})\", \"$2/$1/$3\")*1, A2:A)*1)\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19312269/"
] |
74,637,359
|
<p>here is the example image of i need</p>
<p><a href="https://i.stack.imgur.com/fRBe5.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fRBe5.jpg" alt="Example Image" /></a></p>
<p>and here is the code i tried</p>
<pre><code>Padding(
padding: const EdgeInsets.only(right: 30, left: 30, bottom: 20),
child: Container(
decoration: boxDecoration,
child: const ExpansionTile(
collapsedIconColor: Colors.white,
iconColor: Colors.white,
tilePadding: EdgeInsets.only(left: 5, right: 20, top: 5, bottom: 5),
leading: NotifyIcon(
size: 20,
),
title: Text('Title'),
subtitle: Text('09:15 AM'),
),
),
);
</code></pre>
<p>here is the output i get</p>
<p><a href="https://i.stack.imgur.com/aa1eKm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aa1eKm.jpg" alt="My Output" /></a></p>
<p>but there is no option to add a text above the title in expansion tile. like the example image i given. how do i achieve that?</p>
<p>trying to get accurate output from an example image, i tried to code and all those code and output given in this question</p>
|
[
{
"answer_id": 74637472,
"author": "Ravindra S. Patil",
"author_id": 13997210,
"author_profile": "https://Stackoverflow.com/users/13997210",
"pm_score": 3,
"selected": true,
"text": "Padding(\n padding: const EdgeInsets.only(right: 30, left: 30, bottom: 20),\n child: Container(\n decoration: BoxDecoration(\n borderRadius: BorderRadius.circular(20),\n border: Border.all(color: Colors.grey),\n ),\n child: ExpansionTile(\n collapsedIconColor: Colors.white,\n iconColor: Colors.white,\n tilePadding: EdgeInsets.only(left: 5, right: 20, top: 5, bottom: 5),\n leading: Icon(Icons.edit),\n title: Text(\n 'Quick Reminder',\n style: TextStyle(\n fontSize: 12,\n ),\n ),\n subtitle: Column(\n crossAxisAlignment: CrossAxisAlignment.start,\n children: [\n const SizedBox(\n height: 5,\n ),\n Text(\n 'Push The Code on Main Branch',\n style: TextStyle(\n fontWeight: FontWeight.bold,\n ),\n ),\n const SizedBox(\n height: 5,\n ),\n Text(\n '10/02/22',\n style: TextStyle(\n fontSize: 12,\n ),\n )\n ],\n ),\n ),\n ),\n),\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20652703/"
] |
74,637,367
|
<p>So, the method is supposed to go into the array, choose the positive numbers, and then store those even numbers in a different array.</p>
<p>I have tried debugging checks, tried switching values in the if statement, but nothing has worked. I am still new to dealing with arrays, so I apologize if this has a really simple solution that I am missing.</p>
<pre><code> public static void main(String[] args)
{
int [] arr = {2, 1, 4, 3, 6, 5, 8, 7};
int[] arr3 = {1, 2, 1, 2, 3, 4, 5, 1, 2, 3};
int[] arrEvens;
arrEvens = removeEvens(arr);
System.out.println("\nNew array of even values: ");
for (int i : arrEvens)
System.out.print(i + " ");
System.out.println();
arrEvens = removeEvens(arr3);
System.out.println("\nNew array of even values: ");
for (int i : arrEvens)
System.out.print(i + " ");
System.out.println();
```
public static int[] removeEvens(int[] arr)
{
int[] newArr = arr;
int count = 0;
for(int i = 0; i < arr.length; i++)
{
if (arr[i] % 2 == 0)
{
newArr[count] = arr[i];
count++;
}
}
return newArr;
}
</code></pre>
<p>It should only print out 2468 for arr and 2242 for arr3, but it actually prints 24686587 and 2242345123 respectively</p>
|
[
{
"answer_id": 74637472,
"author": "Ravindra S. Patil",
"author_id": 13997210,
"author_profile": "https://Stackoverflow.com/users/13997210",
"pm_score": 3,
"selected": true,
"text": "Padding(\n padding: const EdgeInsets.only(right: 30, left: 30, bottom: 20),\n child: Container(\n decoration: BoxDecoration(\n borderRadius: BorderRadius.circular(20),\n border: Border.all(color: Colors.grey),\n ),\n child: ExpansionTile(\n collapsedIconColor: Colors.white,\n iconColor: Colors.white,\n tilePadding: EdgeInsets.only(left: 5, right: 20, top: 5, bottom: 5),\n leading: Icon(Icons.edit),\n title: Text(\n 'Quick Reminder',\n style: TextStyle(\n fontSize: 12,\n ),\n ),\n subtitle: Column(\n crossAxisAlignment: CrossAxisAlignment.start,\n children: [\n const SizedBox(\n height: 5,\n ),\n Text(\n 'Push The Code on Main Branch',\n style: TextStyle(\n fontWeight: FontWeight.bold,\n ),\n ),\n const SizedBox(\n height: 5,\n ),\n Text(\n '10/02/22',\n style: TextStyle(\n fontSize: 12,\n ),\n )\n ],\n ),\n ),\n ),\n),\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20443194/"
] |
74,637,386
|
<p>I have a parent component and a child component, and I want to pass a src attribute to the child component via defineProps to make it display the image.</p>
<p>Below is my parent component code:</p>
<pre><code><script setup>
import item from "./item.vue";
const items=[
{
id:0,
img:'../assets/2.png',
name:'秘塔写作猫',
des:'码文章必备工具'
},
{
id:1,
img:'../assets/2.png',
name:'AdblockPlus广告拦截',
des:'最流行的广告拦截拓展程序'
},
{
id:2,
img:'../assets/3.png',
name:'Tampermonkey油猴脚本',
des:'码文章必备工具'
},
{
id:3,
img:'../assets/4.png',
name:'蔚蓝主页',
des:'个性化简洁风格浏览器主页'
},
{
id:4,
img:'../assets/5.png',
name:'ABCD PDF',
des:'完全免费在线PDF压缩转换工具'
},
{
id:5,
img:'../assets/6.png',
name:'ASO谷歌商店工具',
des:'洞悉竞品下载、评论等核心数据'
},
]
</script>
<template>
<div id="ain">
<div id="head">
<h4>站长推荐</h4>
<a>查看全部</a>
</div>
<div id="body">
<item v-for="item in items" :key="item.id" :img="item.img" :name="item.name" :des="item.des">
</item>
</div>
</div>
</template>
</code></pre>
<p>Below is my subcomponent code:</p>
<pre><code><script setup>
defineProps(['img','name','des'])
</script>
<template>
<div id="item">
<div>
<img src="img">
<p>{{name}}</p>
<p id="detail">{{des}}</p>
</div>
</div>
</template>
</code></pre>
<p>This error is displayed in the console:GET <a href="http://127.0.0.1:5173/assets/2.png" rel="nofollow noreferrer">http://127.0.0.1:5173/assets/2.png</a> 404 (Not Found)</p>
<p>I think it's a problem with passing parameters, but I don't know how to modify it, thank you all.</p>
|
[
{
"answer_id": 74637472,
"author": "Ravindra S. Patil",
"author_id": 13997210,
"author_profile": "https://Stackoverflow.com/users/13997210",
"pm_score": 3,
"selected": true,
"text": "Padding(\n padding: const EdgeInsets.only(right: 30, left: 30, bottom: 20),\n child: Container(\n decoration: BoxDecoration(\n borderRadius: BorderRadius.circular(20),\n border: Border.all(color: Colors.grey),\n ),\n child: ExpansionTile(\n collapsedIconColor: Colors.white,\n iconColor: Colors.white,\n tilePadding: EdgeInsets.only(left: 5, right: 20, top: 5, bottom: 5),\n leading: Icon(Icons.edit),\n title: Text(\n 'Quick Reminder',\n style: TextStyle(\n fontSize: 12,\n ),\n ),\n subtitle: Column(\n crossAxisAlignment: CrossAxisAlignment.start,\n children: [\n const SizedBox(\n height: 5,\n ),\n Text(\n 'Push The Code on Main Branch',\n style: TextStyle(\n fontWeight: FontWeight.bold,\n ),\n ),\n const SizedBox(\n height: 5,\n ),\n Text(\n '10/02/22',\n style: TextStyle(\n fontSize: 12,\n ),\n )\n ],\n ),\n ),\n ),\n),\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20485257/"
] |
74,637,393
|
<p>I have a Mailchimp sign-up form with an <code><input></code> element that has placeholder text. On Chrome, Firefox, and Microsoft Edge it displays fine but on Safari (desktop and mobile) the placeholder text does not show. It is blank. Code below:</p>
<pre><code><input type="email" placeholder="Enter your email" onfocus="this.placeholder='Enter your email'" name="EMAIL" id="mce-EMAIL" class="required email" required="" aria-required="true">
</code></pre>
<p>I used <a href="https://stackoverflow.com/questions/2781549/removing-input-background-colour-for-chrome-autocomplete">web-kit</a> fixes to remove the background color from the autocomplete, have white text, and add text styles.</p>
<pre><code>input:-webkit-autofill,
input:-webkit-autofill:active,
input:-webkit-autofill:focus,
input:-webkit-autofill:hover,
select:-webkit-autofill,
select:-webkit-autofill:active,
select:-webkit-autofill:focus,
select:-webkit-autofill:hover,
textarea:-webkit-autofill,
textarea:-webkit-autofill:active,
textarea:-webkit-autofill:focus,
textarea:-webkit-autofill:hover {
background-color: #ED3A38 !important;
transition: background-color 5000s ease-in-out 0s !important;
-webkit-text-fill-color: #FFFFFF !important;
font-size: 6vw !important;
}
</code></pre>
<p>As well as followed <a href="https://www.w3schools.com/howto/howto_css_placeholder.asp" rel="nofollow noreferrer">this</a> guide to change the placeholder text colour and size:</p>
<pre><code>input:-webkit-autofill::first-line,
input:-internal-autofill-previewed,
::-webkit-input-placeholder,
::-moz-placeholder,
:-ms-input-placeholder,
::-ms-input-placeholder,
:-moz-placeholder {
-webkit-text-fill-color: #FFFFFF !important;
font-size: 6vw !important;
letter-spacing: -0.057em;
}
::placeholder {
color: #FFFFFF !important;
opacity: 1 !important;
}
</code></pre>
<p>I'm stuck on why this isn't working. Is there something I am missing?</p>
<p>This is the live example in production: <a href="https://mucho.melbourne/" rel="nofollow noreferrer">link</a></p>
|
[
{
"answer_id": 74637472,
"author": "Ravindra S. Patil",
"author_id": 13997210,
"author_profile": "https://Stackoverflow.com/users/13997210",
"pm_score": 3,
"selected": true,
"text": "Padding(\n padding: const EdgeInsets.only(right: 30, left: 30, bottom: 20),\n child: Container(\n decoration: BoxDecoration(\n borderRadius: BorderRadius.circular(20),\n border: Border.all(color: Colors.grey),\n ),\n child: ExpansionTile(\n collapsedIconColor: Colors.white,\n iconColor: Colors.white,\n tilePadding: EdgeInsets.only(left: 5, right: 20, top: 5, bottom: 5),\n leading: Icon(Icons.edit),\n title: Text(\n 'Quick Reminder',\n style: TextStyle(\n fontSize: 12,\n ),\n ),\n subtitle: Column(\n crossAxisAlignment: CrossAxisAlignment.start,\n children: [\n const SizedBox(\n height: 5,\n ),\n Text(\n 'Push The Code on Main Branch',\n style: TextStyle(\n fontWeight: FontWeight.bold,\n ),\n ),\n const SizedBox(\n height: 5,\n ),\n Text(\n '10/02/22',\n style: TextStyle(\n fontSize: 12,\n ),\n )\n ],\n ),\n ),\n ),\n),\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13996581/"
] |
74,637,401
|
<p>I'm trying to figure out how I can trigger two functions within an onSubmit event handler inside a form element in React. I've been googling for answers, but they either have () after the functions (which returns an error), only one function works, or neither of two works.</p>
<p>Here are my functional components</p>
<pre><code>const [checkBox, setCheckBox] = useState(false)
const [formData, setFormData] = useState(initialStateForm)
//initialStateForm is an object of user inputs
</code></pre>
<p>Here is the form element</p>
<pre><code><form className="restaurant" onSubmit={(handleSubmit, handleSubmitVisit)}>
//I tried (handleSubmitVisit && handleSubmit) but only one fires
</code></pre>
<p>This one is a handleSubmit function with conditional statements</p>
<pre><code> } if (formData.rating === "") {
rate = 0
rateArray = []
countRate = 0
} else if (formData.rating !== "") {
rate = parseFloat(formData.rating)
rateArray = [parseInt(formData.rating)]
countRate = 1
}
return fetch('http://localhost:4000/restaurants', {
method: "POST",
headers: {
"Content-Type" : "application/json"
},
body: JSON.stringify({
...formData,
location: parseFloat(formData.location),
rating: rate,
ratingData: rateArray,
ratingcount: countRate,
comment: ""
})
})
</code></pre>
<p>And this one should execute when user clicks on a checkbox</p>
<pre><code> if (checkBox) {
fetch('http://localhost:4000/user', {
method: "POST",
headers: {
"Content-Type" : "application/json"
},
body: JSON.stringify({
...formData,
location: parseFloat(formData.location),
rating: parseInt(formData.rating),
ratingData: [parseInt(formData.rating)],
ratingcount: 1,
comment: "",
userrating: parseInt(formData.rating),
visitCounter: parseInt(1),
id: restaurant.length + 1
})
})
}
</code></pre>
<p>Appreciate the help!</p>
|
[
{
"answer_id": 74638152,
"author": "Azzy",
"author_id": 2122822,
"author_profile": "https://Stackoverflow.com/users/2122822",
"pm_score": 1,
"selected": false,
"text": "<form \n className=\"restaurant\" \n onSubmit={(values) => {\n handleSubmit(values)\n handleSubmitVisit(values)\n }\n <form \n className=\"restaurant\" \n onSubmit={async (values) => {\n await handleSubmit(values)\n await handleSubmitVisit(values)\n }\n"
},
{
"answer_id": 74638182,
"author": "Dr. Tenma",
"author_id": 3357677,
"author_profile": "https://Stackoverflow.com/users/3357677",
"pm_score": 2,
"selected": false,
"text": "const handleSubmit = () => {\n console.log('running handlesubmit function')\n};\n\nconst handleSubmitVisit = () => {\n console.log('running handlesubmitVisit function')\n};\n\nconst runBothFunctions = () => {\n handleSubmit();\n handleSubmitVisit();\n};\n\nrunBothFunctions(); const runBothFunctions = () => {\n if ( /*some condition*/ ) {\n //run handleSubmit function\n handleSubmit();\n } else if (checkbox) {\n //run handle handleSubmitVisit function\n handleSubmitVisit();\n } else {\n /*something else*/\n }\n};\n <form className=\"restaurant\" onSubmit={runBothFunctions}>\n"
},
{
"answer_id": 74639034,
"author": "Amirhossein",
"author_id": 11342834,
"author_profile": "https://Stackoverflow.com/users/11342834",
"pm_score": 1,
"selected": false,
"text": "<form className=\"restaurant\" onSubmit={() => [handleSubmit(), handleSubmitVisit()]}>\n const handleSubmit = () => {\n handleSubmitVisit();\n // Rest of the code\n}\n const runFunctions = () => {\n handleSubmit();\n handleSubmitVisit();\n};\n <form className=\"restaurant\" onSubmit={runFunctions}>\n <form className=\"restaurant\" onSubmit={() => {\n handleSubmit();\n handleSubmitVisit();\n}}>\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19583401/"
] |
74,637,403
|
<p><strong>dbo.table1</strong></p>
<pre><code>DataID MemberID
2 1001
3 1001
</code></pre>
<p><strong>dbo.table2</strong></p>
<pre><code>PointsID MemberID PartnerPoints
1 1001 100
2 1001 100
</code></pre>
<p><strong>dbo.table3</strong></p>
<pre><code>DataID table3ID PointsID PartnerPoints
2 1 1 100
3 2 2 100
</code></pre>
<p>I need to add a new column on each table that will make the sum of partnerPoints column in dbo.table3 to 0.</p>
<p>Expected output:</p>
<p><strong>dbo.table1</strong></p>
<pre><code>DataID MemberID
2 1001
3 1001
4 1001
</code></pre>
<p><strong>dbo.table2</strong></p>
<pre><code>PointsID MemberID PartnerPoints
1 1001 100
2 1001 100
3 1001 -200
</code></pre>
<p><strong>dbo.table3</strong></p>
<pre><code>DataID table3ID PointsID PartnerPoints
2 1 1 100
3 2 2 100
4 3 3 -200
</code></pre>
<p>I tried this</p>
<pre><code>INSERT INTO [dbo].[Table3]
(
DataID
PointsID
PartnerPoints,
)
SELECT
DataID
PointsID
-PartnerPoints,
FROM @tempTable t
INNER JOIN dbo.table2 e ON t.memberID = e.MemberID
WHERE e.PartnerPoints <> 0
</code></pre>
<p>instead of adding only one row in dbo.table3 it add 2 columns:</p>
<p><strong>dbo.table3</strong></p>
<pre><code>DataID table3ID PointsID PartnerPoints
2 1 1 100
3 2 2 100
4 3 3 -100
4 4 3 -100
</code></pre>
<p>What part in the code do I need to improve? Using group by does not give the expected output.</p>
|
[
{
"answer_id": 74638421,
"author": "ufosnowcat",
"author_id": 1728208,
"author_profile": "https://Stackoverflow.com/users/1728208",
"pm_score": 0,
"selected": false,
"text": "INSERT INTO [dbo].[Table3]\n(\n DataID\n PointsID\n PartnerPoints,\n)\nSELECT\n DataID\n PointsID\n SUM(-PartnerPoints),\nFROM @tempTable t\n INNER JOIN dbo.table2 e ON t.memberID = e.MemberID \nWHERE e.PartnerPoints <> 0\ngroup by DataID,PointsID\n"
},
{
"answer_id": 74641560,
"author": "Amelia",
"author_id": 17334611,
"author_profile": "https://Stackoverflow.com/users/17334611",
"pm_score": 1,
"selected": false,
"text": "INSERT INTO [dbo].[Table3]\n(\n DataID\n PointsID\n PartnerPoints,\n)\nSELECT\n MAX(DataID)\n MAX(PointsID)\n -SUM(PartnerPoints),\nFROM @tempTable t\n INNER JOIN dbo.table2 e ON t.memberID = e.MemberID \nWHERE e.PartnerPoints <> 0\n DataID table3ID PointsID PartnerPoints\n2 1 1 100\n3 2 2 100\n4 3 3 -200\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17334611/"
] |
74,637,414
|
<p>What Mistake do we do while coding a loop for printing float values in C/C++ language?
How can we print decimal values such as 1.0,1.2,1.3,1.4...(till where we need them) using a loop?
What if, I don't want to increment the value of a variable with 1 digit, rather I want incrementation in decimals.</p>
<p>I didn't get any ways to print my numbers by float datatype such as
1.0, 1.1, 1.2, 1.3...</p>
|
[
{
"answer_id": 74637588,
"author": "EPIC PJM",
"author_id": 20652697,
"author_profile": "https://Stackoverflow.com/users/20652697",
"pm_score": -1,
"selected": false,
"text": "#include <stdio.h>\n#include <conio.h>\nvoid main()\n{\n float i;\n clrscr();\n for(i=1.2;i<=3.5;i+=0.1){\n printf(\"%f\\n\",i);\n getch();\n}\n"
},
{
"answer_id": 74641019,
"author": "Zach Donnelly",
"author_id": 20655194,
"author_profile": "https://Stackoverflow.com/users/20655194",
"pm_score": 0,
"selected": false,
"text": "float i; //this is your starting point\nfloat n; //this is your ending point\n\nstd::cin >> n; //whatever \"Til where we need them\" ends up being\n\nfor ( i = 1.0; i <= n; i += 0.1 )\n{\n std::cout << i << endl;\n}\n 1.0\n1.1\n1.2\n1.3\n1.4\n1.5\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20652697/"
] |
74,637,434
|
<p>It's a simple college problem. I have to get the result using the BMI calc</p>
<p>My code below:</p>
<pre><code>(write-line "BMI CALC")
(defun calc nil
(prog (w h) ; define p e h as local variables init with nil
(print "Weight: ")
(setq w (read))
(print "Height: ")
(setq h (read))
(return (/ w (* h h)))
)
)
(format t "BMI: ~D~%" (calc))
(setq bmi calc)
(cond
((< bmi 18.5) (print "Under weight"))
((< bmi 24.9) (print "Normal weight"))
((< bmi 29.9) (print "Overweight"))
((< bmi 34.9) (print "Obesity 1"))
((< bmi 39.9) (print "Obesity 2"))
(t (print "Obesity 3"))
)
</code></pre>
<p>And I got this result below:</p>
<pre><code>BMI CALC
"Weight: " 78
"Height: " 1.7
BMI: 26.989618
*** - SETQ:variable CALC has no value
</code></pre>
<p>I really don't understand why this error.</p>
<p>I expected to print the BMI result, like "Under weight" or "Obesity 1".</p>
|
[
{
"answer_id": 74637827,
"author": "Martin Půda",
"author_id": 13590263,
"author_profile": "https://Stackoverflow.com/users/13590263",
"pm_score": 2,
"selected": false,
"text": "calc (setq bmi calc) let (my-bmi) (defun calc ()\n (prog (w h)\n (print \"Weight: \")\n (setq w (read *query-io*))\n (print \"Height: \")\n (setq h (read *query-io*))\n (return (/ w (* h h)))))\n\n(defun my-bmi ()\n (print \"BMI CALC\")\n (let ((bmi (calc)))\n (format t \"BMI: ~D~%\" bmi)\n (print \n (cond \n ((< bmi 18.5) \"Under weight\")\n ((< bmi 24.9) \"Normal weight\")\n ((< bmi 29.9) \"Overweight\")\n ((< bmi 34.9) \"Obesity 1\")\n ((< bmi 39.9) \"Obesity 2\")\n (t \"Obesity 3\")))))\n"
},
{
"answer_id": 74641001,
"author": "coredump",
"author_id": 124319,
"author_profile": "https://Stackoverflow.com/users/124319",
"pm_score": 1,
"selected": false,
"text": "(setq bmi ...) bmi let format force-output (defun bmi-formula (&key height weight)\n (/ weight (* height height)))\n CL-USER> (bmi-formula :height 1.80 :weight 60)\n18.51852\n (defun bmi-obesity-judgment (bmi)\n (cond\n ((< bmi 18.5) 'underweight)\n ;; etc.\n ))\n bmi (ecase judgment (underweight \"magro\") ...) (defun prompt (message type)\n (loop\n (clear-input *query-io*)\n (fresh-line *query-io*)\n (write-string message *query-io*)\n (let ((value (read *query-io*)))\n (when (typep value type)\n (return value))\n (warn \"~a is not of type ~a\" value type))))\n (defun input-bmi-parameters ()\n (list\n :weight (prompt \"Weight (kgs): \" '(integer 0 1000))\n :height (prompt \"Height (meters): \" '(real 0 5))))\n (defun bmi-program ()\n (format *query-io* \"~&BMI Calculator. Enter weight and height and be judged.~%\")\n (let ((parameters (input-bmi-parameters)))\n ...))\n let parameters prompt value *query-io* bmi-program bmi-program *query-io*"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17100588/"
] |
74,637,457
|
<p>Recently I stumbled upon the <code>Promise.then</code> example on MDN just before this article <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#nesting" rel="nofollow noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#nesting</a></p>
<p>The example uses this:</p>
<pre><code>.then((url) =>
fetch(url)
.then((res) => res.json())
.then((data) => {
listOfIngredients.push(data);
}), // Note this comma here
)
</code></pre>
<p>In simple terms this is equivalent to the following:</p>
<pre><code>.then(successFunc,);
</code></pre>
<p>To my surprise, this actually doesn't throw any error. Following works, but why?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const speakPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("success");
}, 500);
});
speakPromise.then(function (data) {
console.log(data, " End code");
}, ); // Note the trailing comma here</code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74637827,
"author": "Martin Půda",
"author_id": 13590263,
"author_profile": "https://Stackoverflow.com/users/13590263",
"pm_score": 2,
"selected": false,
"text": "calc (setq bmi calc) let (my-bmi) (defun calc ()\n (prog (w h)\n (print \"Weight: \")\n (setq w (read *query-io*))\n (print \"Height: \")\n (setq h (read *query-io*))\n (return (/ w (* h h)))))\n\n(defun my-bmi ()\n (print \"BMI CALC\")\n (let ((bmi (calc)))\n (format t \"BMI: ~D~%\" bmi)\n (print \n (cond \n ((< bmi 18.5) \"Under weight\")\n ((< bmi 24.9) \"Normal weight\")\n ((< bmi 29.9) \"Overweight\")\n ((< bmi 34.9) \"Obesity 1\")\n ((< bmi 39.9) \"Obesity 2\")\n (t \"Obesity 3\")))))\n"
},
{
"answer_id": 74641001,
"author": "coredump",
"author_id": 124319,
"author_profile": "https://Stackoverflow.com/users/124319",
"pm_score": 1,
"selected": false,
"text": "(setq bmi ...) bmi let format force-output (defun bmi-formula (&key height weight)\n (/ weight (* height height)))\n CL-USER> (bmi-formula :height 1.80 :weight 60)\n18.51852\n (defun bmi-obesity-judgment (bmi)\n (cond\n ((< bmi 18.5) 'underweight)\n ;; etc.\n ))\n bmi (ecase judgment (underweight \"magro\") ...) (defun prompt (message type)\n (loop\n (clear-input *query-io*)\n (fresh-line *query-io*)\n (write-string message *query-io*)\n (let ((value (read *query-io*)))\n (when (typep value type)\n (return value))\n (warn \"~a is not of type ~a\" value type))))\n (defun input-bmi-parameters ()\n (list\n :weight (prompt \"Weight (kgs): \" '(integer 0 1000))\n :height (prompt \"Height (meters): \" '(real 0 5))))\n (defun bmi-program ()\n (format *query-io* \"~&BMI Calculator. Enter weight and height and be judged.~%\")\n (let ((parameters (input-bmi-parameters)))\n ...))\n let parameters prompt value *query-io* bmi-program bmi-program *query-io*"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3429430/"
] |
74,637,464
|
<p>I am getting an object from parent component and setting to state. In child component I am updating the state, but the parent reference object values also changing instead of only state changes.</p>
<p><strong>Parent Component has a huge object,</strong></p>
<pre><code>obj = {
values: {
per1: { name: "rsk" },
per2: { name: "ssk" },
}
}
</code></pre>
<p><strong>Child Component:</strong></p>
<pre><code>const ChildComponent = ({obj}) => {
const [inp, setInp] = useState(obj.values);
const onChange = useCallback(({target}) => {
setInp((prev) => {
const nD = { ...prev };
//k1, k2 comes from some logic
nD[k1][k2] = target.value;
return nD;
})
}, []);
return (
Here the "inp" state is looped by objects and keys in text box to build a html form
)
}
</code></pre>
<p>Here the question is, why the core obj.values also changing on onChange setInp time. I dont want to disturb the obj.values untill i submit the form.
Because before submit the Form, I need to validate,</p>
<p><em><strong>obj.values are equal or not to inp state values</strong></em></p>
<p>Any idea on this.</p>
|
[
{
"answer_id": 74638012,
"author": "Tejashree Surve",
"author_id": 15197074,
"author_profile": "https://Stackoverflow.com/users/15197074",
"pm_score": 0,
"selected": false,
"text": " const [inp, setInp] = useState(Object.assign({}, obj.values));\n"
},
{
"answer_id": 74638462,
"author": "tomleb",
"author_id": 15169145,
"author_profile": "https://Stackoverflow.com/users/15169145",
"pm_score": 2,
"selected": true,
"text": "const ChildComponent = ({obj}) => {\n const [inp, setInp] = useState({...obj.values});\n ...\n}\n obj.values JSON const clone = JSON.parse(JSON.stringify(original));\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8889546/"
] |
74,637,478
|
<p>This should be simple but I can't get ride of this null pointer warning. What can you do?
<a href="https://i.stack.imgur.com/jg0yp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jg0yp.png" alt="enter image description here" /></a></p>
<pre><code>private static List<OrderHeader> orderHeaders = new List<OrderHeader>{...};
/*Delete order line item from the provided OrderHeader*/
private void DeleteOrderLine(int orderHeaderIndex, int orderLineIndex)
{
if (orderHeaders != null &&
orderHeaders[orderHeaderIndex] != null &&
orderHeaders[orderHeaderIndex].OrderLineItems != null &&
orderHeaders[orderHeaderIndex].OrderLineItems.Count > orderLineIndex
)
{
orderHeaders[orderHeaderIndex].OrderLineItems.RemoveAt(orderLineIndex);
} else
{
Console.WriteLine("Failed to delete the order line. Please try again");
}
}
</code></pre>
<p>Here is second attempt.. still not working.</p>
<pre><code>/*Delete order line item from the provided OrderHeader*/
private void DeleteOrderLine(int orderHeaderIndex, int orderLineIndex)
{
if (orderHeaders is not null &&
orderHeaders[orderHeaderIndex] is not null &&
orderHeaders[orderHeaderIndex].OrderLineItems is not null &&
orderHeaders[orderHeaderIndex].OrderLineItems.Count > orderLineIndex
)
{
orderHeaders[orderHeaderIndex].OrderLineItems.RemoveAt(orderLineIndex);
} else
{
Console.WriteLine("Failed to delete the order line. Please try again");
}
}
</code></pre>
<p>Here's the the order Header definition</p>
<p>public class OrderHeader
{</p>
<pre><code> public enum OrderTypes
{
Normal = 0,
Staff,
Mechanical,
Perishable
}
public enum OrderStatusTypes
{
New = 0,
Processing,
Complete
}
[Key]
public string OrderId { get; set; } = string.Empty;
public OrderTypes OrderType { get; set; }
public OrderStatusTypes OrderStatus { get; set; }
public DateTime CreateDate { get; set; } = DateTime.Now;
public string CustomerName { get; set; } = string.Empty;
public List<OrderLine>? OrderLineItems { get; set; }
}
</code></pre>
<p>Here is the orderLine definition</p>
<p>public class OrderLine
{
public int LineNumber { get; set; }</p>
<pre><code>public string ProductCode { get; set; } = string.Empty;
public ProductTypes ProductType { get; set; } = 0;
[Column(TypeName = "decimal(18,2)")]
public decimal CostPrice { get; set; }
[Column(TypeName = "decimal(18,2)")]
public decimal SalePrice { get; set; }
public int Quantity { get; set; }
</code></pre>
<p>}</p>
|
[
{
"answer_id": 74637590,
"author": "Nate1zn",
"author_id": 18154499,
"author_profile": "https://Stackoverflow.com/users/18154499",
"pm_score": 0,
"selected": false,
"text": "<Nullable>enable</Nullable>\n"
},
{
"answer_id": 74637672,
"author": "Carlos",
"author_id": 10413901,
"author_profile": "https://Stackoverflow.com/users/10413901",
"pm_score": 3,
"selected": true,
"text": "<Nullable>enable</Nullable> orderHeaders[orderHeaderIndex].OrderLineItems is not null ! private void DeleteOrderLine(int orderHeaderIndex, int orderLineIndex)\n{\n if (orderHeaders is not null && \n orderHeaders[orderHeaderIndex] is not null && \n orderHeaders[orderHeaderIndex].OrderLineItems is not null &&\n orderHeaders[orderHeaderIndex].OrderLineItems!.Count > orderLineIndex\n )\n {\n orderHeaders[orderHeaderIndex].OrderLineItems!.RemoveAt(orderLineIndex); \n } else\n {\n Console.WriteLine(\"Failed to delete the order line. Please try again\"); \n }\n}\n"
},
{
"answer_id": 74638036,
"author": "Damien_The_Unbeliever",
"author_id": 15498,
"author_profile": "https://Stackoverflow.com/users/15498",
"pm_score": 2,
"selected": false,
"text": "/*Delete order line item from the provided OrderHeader*/\nprivate bool DeleteOrderLine(int orderHeaderIndex, int orderLineIndex)\n{\n if(orderHeaders is null) return false;\n var header = orderHeaders[orderHeaderIndex];\n if(header is null) return false;\n var lineItems = header.OrderLineItems;\n if(lineItems is null || lineItems.Count <= orderLineIndex) return false;\n lineItems.RemoveAt(orderLineIndex);\n return true;\n}\n OrderLineItems orderHeaders orderHeaderIndex ArgumentXxxException bool"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1500778/"
] |
74,637,498
|
<p>I have the below JSON string with multiple JSON objects. I would like to extract just the id and name from each object and print it.</p>
<pre class="lang-json prettyprint-override"><code>{
"users": [
{
"id": "1",
"name": "John Wick",
"location": "USA"
},
{
"id": "2",
"name": "Walter White",
"location": "USA"
}
]
}
</code></pre>
<p>I am using the below code to extract the id and name using 'jq'</p>
<pre class="lang-bash prettyprint-override"><code>for key in $(jq -c '.users | .[]' sample.json); do
id=$(jq -r '.id' <<< "$key");
name=$(jq -r '.name' <<< "$key")
echo $id $name
done
</code></pre>
<p>But I am getting parsing errors like below. Can someone help me with this?</p>
<blockquote>
<pre><code>parse error: Unfinished string at EOF at line 2, column 0
</code></pre>
</blockquote>
<p>I tried replacing spaces with a combination of special chars and replace again special chars with spaces. It worked for me but I need a better solution than this.</p>
|
[
{
"answer_id": 74637890,
"author": "TheAnalogyGuy",
"author_id": 6317990,
"author_profile": "https://Stackoverflow.com/users/6317990",
"pm_score": 1,
"selected": false,
"text": "man jq\n jq -r '.users[] | [.id , .name] | @csv' sample.json\n $ jq -r '.users[] | [.id , .name] | @csv' sample.json\n\"1\",\"John Wick\"\n\"2\",\"Walter White\"\n $ jq -r '.users[] | [.id, .name] | \"\\(.[0]) \\(.[1])\"' sample.json\n1 John Wick\n2 Walter White\n"
},
{
"answer_id": 74641879,
"author": "0stone0",
"author_id": 5625547,
"author_profile": "https://Stackoverflow.com/users/5625547",
"pm_score": 0,
"selected": false,
"text": "read id name #!/bin/bash\njq -r -c '.users[] | .id, .name' /tmp/input3 | while read -r id && read -r name; do\n echo -e \"ID: ${id}\\t Name: ${name}\"\ndone\n ID: 1 Name: John Wick\nID: 2 Name: Walter White\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5955680/"
] |
74,637,501
|
<p>I am trying to Manipulate the Text with id 'varname' (Spartans) with the value inputted in the form saved as a variable 'input'</p>
<pre><code><div class="middle">
<h2 class="greet" id="demo">Welcome Back,&nbsp; <span id="varname">Spartan</span></h2>
<div class="form">
<form>
<label for="Name">Enter Your Name</label>
<input type="text" id="Name">
<input type="submit" value="Submit" onclick="myFunction()">
</form>
</div>
<script>
function myFunction(){
var input= document.getElementById("Name").value;
document.getElementById("varname").innerHTML = input;
}
</script>
</code></pre>
|
[
{
"answer_id": 74637564,
"author": "Natrium",
"author_id": 59119,
"author_profile": "https://Stackoverflow.com/users/59119",
"pm_score": 3,
"selected": true,
"text": "<input type=\"button\"> <input type=\"submit\">"
},
{
"answer_id": 74649070,
"author": "Nagonus Lrak",
"author_id": 20476491,
"author_profile": "https://Stackoverflow.com/users/20476491",
"pm_score": 0,
"selected": false,
"text": "<form id=\"manipulate\">\n <label for=\"Name\">Enter Your Name</label>\n <input type=\"text\" id=\"Name\">\n <input type=\"submit\" value=\"Submit\">\n</form>\n document.getElementById(\"manipulate\").addEventListener(\"submit\", e => {\n e.preventDefault()\n\n const formData = new FormData(e.target)\n\n document.getElementById('varname').innerHTML = formData.get(\"Name\")\n})\n e.preventDefault()"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18018970/"
] |
74,637,514
|
<p>I have 3 <code>Vec<T></code> structs that shared the same function:</p>
<pre><code>Vec<RawTransaction>
Vec<RawCashTransaction>
Vec<RawAdjustmentTransaction>
</code></pre>
<p>All three shared the same <code>VerifyableRaw</code> traits and the <code>verify()</code> function. I use the <code>verify()</code> function check the validity of the content of that array/vector.</p>
<p>Here's my implementation. As you can see, all of them shared the same basic fields, namely: <code>date</code>, <code>total</code>, <code>credit</code>, and <code>debit</code>.</p>
<p>My problem is: since I use the same fields that those structs shared, the <code>verify()</code> function is the same for all of them. In <code>verify</code> function, I need to access the <code>date</code>, <code>total</code>, <code>credit</code>, and <code>debit</code> fields so I just copy and paste the code from one implementation to another.</p>
<p>My question is: Can I refactor this trait implementation into a single function definition ?</p>
<p>I found out that I need to repeat myself each time I need to use <code>verify()</code> function and <code>VerifyableRaw</code> trait to another struct that needs it</p>
<pre><code>pub struct RawTransaction {
pub date: Option<NaiveDate>,
pub contact_name: String,
pub total: Option<Decimal>,
pub credit: String,
pub debit: String,
}
pub struct RawCashTransaction{
pub tr_type: String,
pub date: Option<NaiveDate>,
pub contact_name: String,
pub total: Option<Decimal>,
pub credit: String,
pub debit: String,
}
pub struct RawAdjustmentTransaction{
pub date: Option<NaiveDate>,
pub info: String,
pub total: Option<Decimal>,
pub credit: String,
pub debit: String,
}
</code></pre>
<p>Here's my trait implementation:</p>
<pre><code>#[async_trait]
pub trait VerifyableRaw {
async fn verify(&self, cid: String, db: Database) -> Result<bool, Err>;
}
#[async_trait]
impl VerifyableRaw for Vec<RawTransaction> {
async fn verify(&self, cid: String, db: Database) -> Result<bool, Err> {
/// .... this function is the same for all three
let data = &self; // access the vector
for (i, row) in data.iter().enumerate() {
// enumerate each item in this vector
let date = row.date.unwrap(); // check if the date is valid, etc
let de = row.debit.clone(); // check if this value is valid
let cr = row.credit.clone(); // check if this value is valid
// ... another process here ...
}
}
}
#[async_trait]
impl VerifyableRaw for Vec<RawCashTransaction> {
async fn verify(&self, cid: String, db: Database) -> Result<bool, Err> {
/// .... this function is exactly the same as RawTransaction above
}
}
#[async_trait]
impl VerifyableRaw for Vec<RawAdjustmentTransaction> {
async fn verify(&self, cid: String, db: Database) -> Result<bool, Err> {
/// .... this function is exactly the same as RawTransaction above
}
}
</code></pre>
|
[
{
"answer_id": 74637824,
"author": "Maxim Gritsenko",
"author_id": 4997879,
"author_profile": "https://Stackoverflow.com/users/4997879",
"pm_score": 1,
"selected": false,
"text": "pub trait VerifyableRaw {\n fn date(&self) -> Option<NativeDate>;\n fn credit(&self) -> &str;\n fn debit(&self) -> &str;\n}\n\npub trait VerifyableRaws {\n async fn verify(&self, cid: String, db: Database) -> Result<bool, Err>;\n}\n\nimpl VerifyableRaw for RawCashTransaction {\n fn date(&self) -> Option<NativeDate> { self.date }\n fn credit(&self) -> &str { &self.credit }\n fn debit(&self) -> &str { &self.debit }\n}\n\nimpl<T: VerifyableRaw> VerifyableRaws for Vec<T> {\n async fn verify(&self, cid: String, db: Database) -> Result<bool, Err> {\n // your implementation here, but replace field access with method calls\n }\n}\n\n// other types have the same implementation\n"
},
{
"answer_id": 74638333,
"author": "Jmb",
"author_id": 5397009,
"author_profile": "https://Stackoverflow.com/users/5397009",
"pm_score": 3,
"selected": true,
"text": "pub struct BaseTransaction {\n pub date: Option<NaiveDate>,\n pub total: Option<Decimal>,\n pub credit: String,\n pub debit: String,\n}\n\npub struct RawTransaction {\n pub base: BaseTransaction,\n pub contact_name: String,\n}\n\npub struct RawCashTransaction{\n pub base: BaseTransaction,\n pub tr_type: String,\n pub contact_name: String,\n}\n\npub struct RawAdjustmentTransaction{\n pub base: BaseTransaction,\n pub info: String,\n}\n impl AsRef<BaseTransaction> impl AsRef<BaseTransaction> for RawTransaction {\n fn as_ref (&self) -> &BaseTransaction {\n &self.base\n }\n}\nimpl AsRef<BaseTransaction> for RawCashTransaction {\n fn as_ref (&self) -> &BaseTransaction {\n &self.base\n }\n}\nimpl AsRef<BaseTransaction> for RawAdjustmentTransaction {\n fn as_ref (&self) -> &BaseTransaction {\n &self.base\n }\n}\n AsRef<BaseTransaction> impl<T: AsRef<BaseTransaction>> VerifyableRaw for Vec<T> {\n async fn verify(&self, cid: String, db: Database) -> Result<bool, Err> {\n let base: BaseTransaction = self.as_ref();\n unimplemented!()\n }\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1608979/"
] |
74,637,528
|
<p>There are many persons working on the same git repo. I'd like to list each person's last commit time. Like:</p>
<pre><code>Alice Nov 22
Bob Nov 21
Charlie Nov 29
</code></pre>
<p>...</p>
<p>I know that I can get a specific person's last commit using:</p>
<pre><code>git log --author="bob" -1
</code></pre>
<p>Is it possible to get everybody's last commit time?</p>
|
[
{
"answer_id": 74637591,
"author": "Zhubei Federer",
"author_id": 10769406,
"author_profile": "https://Stackoverflow.com/users/10769406",
"pm_score": 0,
"selected": false,
"text": "$ git log --format=\"%aN\" | sort | uniq\n $ git log --format=\"%aN %ad\" --date=short | grep \"^<USERNAME>\"\n $ git log --format=\"%aN %ad\" --date=short | grep \"^<USERNAME>\" | tail -n 1\n $ git log --format=\"%aN %ad\" --date=short | grep \"^john\" | tail -n 1\n #!/bin/\n"
},
{
"answer_id": 74638902,
"author": "Romain Valeri",
"author_id": 1057485,
"author_profile": "https://Stackoverflow.com/users/1057485",
"pm_score": 2,
"selected": true,
"text": "git log --all --pretty=format:\"%aN\" | sort -u\n .mailmap Joe Schmoe joeshmoe joe.schmoe.home while git log --all --pretty=format:\"%aN\" | sort -u | while read -r line ; do git log --all --pretty=\"%aN %ad\" --date=short -1 --author=\"$line\"; done\n # set the alias\ngit config --global alias.autlog '!git log --all --pretty=format:\"%aN\" | sort -u | while read -r line ; do git log --all --pretty=\"%aN %ad\" --date=short -1 --author=\"$line\"; done'\n\n# use it\ngit autlog\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2185472/"
] |
74,637,548
|
<p>I am trying to calculate a percentage of landmass occupied by a country from the total landmass.I am taking two arguments as string and float in a function and returning String along with the calculated percentage in it. For example the <strong>Input =area_of_country("Russia", 17098242)</strong> and <strong>Output = "Russia is 11.48% of the total world's landmass"</strong>. Below is my code</p>
<pre><code> class Solution(object):
def landmass(self, st, num):
percentage = 148940000 / num * 100
return st + "is" + percentage + "of total world mass!"
if __name__ == "__main__":
s = "Russia"
n = 17098242
print(Solution().landmass(s, n))
</code></pre>
<p>Error :-</p>
<pre><code> return st + "is" + percentage + "of total world mass!"
TypeError: can only concatenate str (not "float") to str
</code></pre>
|
[
{
"answer_id": 74637570,
"author": "ilyasbbu",
"author_id": 16475089,
"author_profile": "https://Stackoverflow.com/users/16475089",
"pm_score": 1,
"selected": false,
"text": "return str(st) + \"is\" + str(percentage) + \"of total world mass!\"\n"
},
{
"answer_id": 74637601,
"author": "coderman",
"author_id": 19456156,
"author_profile": "https://Stackoverflow.com/users/19456156",
"pm_score": 2,
"selected": false,
"text": "return str(st) + \"is\" + str(percentage) + \"of total world mass!\"\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20502753/"
] |
74,637,565
|
<p>I defined a tuples in a for loop like this (From <a href="https://leetcode.com/problems/determine-if-string-halves-are-alike/description/" rel="nofollow noreferrer">Leetcode 1704</a>)</p>
<pre><code>for (var tuple = (i : 0, j : s.Length / 2); tuple.i < s.Length / 2 && tuple.j < s.Length; tuple.i++, tuple.j++){...}
</code></pre>
<p>It worked properly.</p>
<p>Then I tried to explicitly define the variable type of the tuple.</p>
<p>This is the method I found on the Internet</p>
<pre><code>for (Tuple<int, int> tuple = new Tuple<int, int>(i : 0, j : s.Length / 2); tuple.i < s.Length / 2 && tuple.j < s.Length; tuple.i++, tuple.j++)
</code></pre>
<p>And I got some errors</p>
<pre><code>Line 7: Char 58: error CS1739: The best overload for 'Tuple' does not have a parameter named 'i' (in Solution.cs)
Line 7: Char 90: error CS1061: 'Tuple<int, int>' does not contain a definition for 'i' and no accessible extension method 'i' accepting a first argument of type 'Tuple<int, int>' could be found (are you missing a using directive or an assembly reference?) (in Solution.cs)
Line 7: Char 116: error CS1061: 'Tuple<int, int>' does not contain a definition for 'j' and no accessible extension method 'j' accepting a first argument of type 'Tuple<int, int>' could be found (are you missing a using directive or an assembly reference?) (in Solution.cs)
Line 7: Char 136: error CS1061: 'Tuple<int, int>' does not contain a definition for 'i' and no accessible extension method 'i' accepting a first argument of type 'Tuple<int, int>' could be found (are you missing a using directive or an assembly reference?) (in Solution.cs)
Line 7: Char 147: error CS1061: 'Tuple<int, int>' does not contain a definition for 'j' and no accessible extension method 'j' accepting a first argument of type 'Tuple<int, int>' could be found (are you missing a using directive or an assembly reference?) (in Solution.cs)
Line 9: Char 41: error CS1061: 'Tuple<int, int>' does not contain a definition for 'i' and no accessible extension method 'i' accepting a first argument of type 'Tuple<int, int>' could be found (are you missing a using directive or an assembly reference?) (in Solution.cs)
Line 10: Char 41: error CS1061: 'Tuple<int, int>' does not contain a definition for 'j' and no accessible extension method 'j' accepting a first argument of type 'Tuple<int, int>' could be found (are you missing a using directive or an assembly reference?) (in Solution.cs)
</code></pre>
<p>I want to know is it special to define a Tuple in a for loop? And how should I do it</p>
<p>(Of course it's clearer and easier to read with var... I just want to figure out how to do it without omitting.)</p>
|
[
{
"answer_id": 74637626,
"author": "SNBS",
"author_id": 20426120,
"author_profile": "https://Stackoverflow.com/users/20426120",
"pm_score": 0,
"selected": false,
"text": "string int Tuple<int, string> tuple = Tuple.Create<int, string>(0, \"a string\"); // Generic parameters are types of the elements\n\n// Accessing the elements\nint element1 = tuple.Item1;\n"
},
{
"answer_id": 74637687,
"author": "AceGambit",
"author_id": 920319,
"author_profile": "https://Stackoverflow.com/users/920319",
"pm_score": 1,
"selected": false,
"text": "System.Tuple<T1,T2> ValueTuple"
},
{
"answer_id": 74637986,
"author": "slfan",
"author_id": 599668,
"author_profile": "https://Stackoverflow.com/users/599668",
"pm_score": 3,
"selected": true,
"text": "for (Tuple<int, int> tuple = new Tuple<int, int>(0, s.Length / 2);\n tuple.Item1 < s.Length / 2 && tuple.Item2 < s.Length; tuple.Item1++, tuple.Item2++) { }\n for (ValueTuple<int, int> tuple = new ValueTuple<int, int>(0, s.Length / 2);\n tuple.Item1 < s.Length / 2 && tuple.Item2 < s.Length; tuple.Item1++, tuple.Item2++) { }\n for ((int i, int j) tuple = (i: 0, j: s.Length / 2); \n tuple.i < s.Length / 2 && tuple.j < s.Length; tuple.i++, tuple.j++) { }\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16571732/"
] |
74,637,635
|
<p>i am trying to create a video player ,So I am trying to add the videos to the list
Storage permission is required to fetch the videos, so I took the permission with the below code.
But playstore was reject My app for this <strong>MANAGE EXTERNAL STORAGE</strong> permission.
But without this permission, I can't get storage permission on Android 10+ device.
To change the name of the video, delete the video and download the video permission is required , so please help me , please tell me how to get storage permission (/storage/Media/Videos , /storage/Download/)</p>
<p><strong>My storage permission code :-</strong></p>
<pre><code><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="28" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
android:requestLegacyExternalStorage="true"
</code></pre>
<p><strong>Main activity code :-</strong></p>
<pre><code>private boolean checkPermission() {
if (SDK_INT >= Build.VERSION_CODES.R) {
return Environment.isExternalStorageManager();
} else {
int result = ContextCompat.checkSelfPermission(PermissionActivity.this, READ_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(PermissionActivity.this, WRITE_EXTERNAL_STORAGE);
return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED;
}
}
private void requestPermission() {
if (SDK_INT >= Build.VERSION_CODES.R) {
try {
Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
intent.addCategory("android.intent.category.DEFAULT");
intent.setData(Uri.parse(String.format("package:%s",getApplicationContext().getPackageName())));
startActivityForResult(intent, 2296);
} catch (Exception e) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
startActivityForResult(intent, 2296);
}
} else {
//below android 11
ActivityCompat.requestPermissions(PermissionActivity.this, new String[]{WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2296) {
if (SDK_INT >= Build.VERSION_CODES.R) {
if (Environment.isExternalStorageManager()) {
// perform action when allow permission success
} else {
Toast.makeText(this, "Allow permission for storage access!", Toast.LENGTH_SHORT).show();
}
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0) {
boolean READ_EXTERNAL_STORAGE = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean WRITE_EXTERNAL_STORAGE = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (READ_EXTERNAL_STORAGE && WRITE_EXTERNAL_STORAGE) {
// perform action when allow permission success
} else {
Toast.makeText(this, "Allow permission for storage access!", Toast.LENGTH_SHORT).show();
}
}
break;
}
}
</code></pre>
<p>So please tell me how to take storage permission in Android10+ Devices and also below Android 10 devices with out using MANAGE EXTERNAL STORAGE permission , Please Help Me</p>
|
[
{
"answer_id": 74637626,
"author": "SNBS",
"author_id": 20426120,
"author_profile": "https://Stackoverflow.com/users/20426120",
"pm_score": 0,
"selected": false,
"text": "string int Tuple<int, string> tuple = Tuple.Create<int, string>(0, \"a string\"); // Generic parameters are types of the elements\n\n// Accessing the elements\nint element1 = tuple.Item1;\n"
},
{
"answer_id": 74637687,
"author": "AceGambit",
"author_id": 920319,
"author_profile": "https://Stackoverflow.com/users/920319",
"pm_score": 1,
"selected": false,
"text": "System.Tuple<T1,T2> ValueTuple"
},
{
"answer_id": 74637986,
"author": "slfan",
"author_id": 599668,
"author_profile": "https://Stackoverflow.com/users/599668",
"pm_score": 3,
"selected": true,
"text": "for (Tuple<int, int> tuple = new Tuple<int, int>(0, s.Length / 2);\n tuple.Item1 < s.Length / 2 && tuple.Item2 < s.Length; tuple.Item1++, tuple.Item2++) { }\n for (ValueTuple<int, int> tuple = new ValueTuple<int, int>(0, s.Length / 2);\n tuple.Item1 < s.Length / 2 && tuple.Item2 < s.Length; tuple.Item1++, tuple.Item2++) { }\n for ((int i, int j) tuple = (i: 0, j: s.Length / 2); \n tuple.i < s.Length / 2 && tuple.j < s.Length; tuple.i++, tuple.j++) { }\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20317930/"
] |
74,637,639
|
<p>I have a spreadsheet with 100+ entries. One column consists of IDs. I need to combine these into a single string with each ID separated by a comma, eg:</p>
<h2>| ID |</h2>
<p>|123|
|567|
|890|</p>
<p>Becomes one cell with the value</p>
<pre><code>123,567,980
</code></pre>
<p>I know I can <code>concat</code> each cell, but there are hundreds.</p>
<p>Is there a way I can concat the entire column, but separate it by commas?</p>
<p>Closes I've gotten is:</p>
<pre><code>=CONCAT(A:A)
</code></pre>
<p>but I can't figure out how to add a separator so it just outputs:</p>
<pre><code>123567980
</code></pre>
|
[
{
"answer_id": 74637626,
"author": "SNBS",
"author_id": 20426120,
"author_profile": "https://Stackoverflow.com/users/20426120",
"pm_score": 0,
"selected": false,
"text": "string int Tuple<int, string> tuple = Tuple.Create<int, string>(0, \"a string\"); // Generic parameters are types of the elements\n\n// Accessing the elements\nint element1 = tuple.Item1;\n"
},
{
"answer_id": 74637687,
"author": "AceGambit",
"author_id": 920319,
"author_profile": "https://Stackoverflow.com/users/920319",
"pm_score": 1,
"selected": false,
"text": "System.Tuple<T1,T2> ValueTuple"
},
{
"answer_id": 74637986,
"author": "slfan",
"author_id": 599668,
"author_profile": "https://Stackoverflow.com/users/599668",
"pm_score": 3,
"selected": true,
"text": "for (Tuple<int, int> tuple = new Tuple<int, int>(0, s.Length / 2);\n tuple.Item1 < s.Length / 2 && tuple.Item2 < s.Length; tuple.Item1++, tuple.Item2++) { }\n for (ValueTuple<int, int> tuple = new ValueTuple<int, int>(0, s.Length / 2);\n tuple.Item1 < s.Length / 2 && tuple.Item2 < s.Length; tuple.Item1++, tuple.Item2++) { }\n for ((int i, int j) tuple = (i: 0, j: s.Length / 2); \n tuple.i < s.Length / 2 && tuple.j < s.Length; tuple.i++, tuple.j++) { }\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1433268/"
] |
74,637,645
|
<p>I'm working on a alumni portal where I need to display the committee member details. I need to print like 4 members in a line and next 4 in the next line. Any solution would be helpful.
<a href="https://i.stack.imgur.com/7jNiM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7jNiM.png" alt="enter image description here" /></a></p>
<pre><code><h2>Member Details</h2>
<div class="jumbotron container">
<div class="pull-right">
<a class="btn btn-primary" data-toggle="modal" id="mediumButton" data-target="#mediumModal" data-attr="{{ route('add_details')}}" title="Add Institute Details"> <i class="fas fa-plus-circle"></i>
</a>
</div>
<div class="container main" id="wrapper">
@foreach ($members as $member)
<div class="img-box">
<pre>
<img src="/uploads/image/{{ $member->image }}" width="100" height="100"/>
&nbsp; &nbsp; &nbsp; {{ $member->id }}<br/>
<a> &nbsp; {{ $member->name }}</a>
<!-- @if(($member->id) >=5 )
<span style="white-space: pre-line">
</span>
@endif
</pre> -->
</div>
@endforeach
</div>
</div>
</code></pre>
|
[
{
"answer_id": 74637740,
"author": "Danz",
"author_id": 19681705,
"author_profile": "https://Stackoverflow.com/users/19681705",
"pm_score": 1,
"selected": true,
"text": "<div class=\"row\">\n @foreach ($members as $member)\n <div class=\"col-md-3\">\n <div class=\"img-box\">\n <pre>\n <img src=\"/uploads/image/{{ $member->image }}\" width=\"100\" height=\"100\"/>\n {{ $member->id }}<br/>\n <a> {{ $member->name }}</a>\n </pre>\n </div>\n </div>\n @endforeach\n</div>\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19784195/"
] |
74,637,660
|
<p>I have 2 tables.</p>
<p>table1:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>item</th>
<th>end time</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2022-11-23 08:12:00</td>
</tr>
<tr>
<td>1</td>
<td>2022-11-23 09:12:00</td>
</tr>
<tr>
<td>2</td>
<td>2022-11-22 13:12:00</td>
</tr>
<tr>
<td>3</td>
<td>2022-11-22 14:12:00</td>
</tr>
</tbody>
</table>
</div>
<p>table2:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>item</th>
<th>value</th>
<th>last_dt</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>11</td>
<td>2022-11-23 09:12:00</td>
</tr>
<tr>
<td>1</td>
<td>12</td>
<td>2022-11-23 08:30:00</td>
</tr>
<tr>
<td>1</td>
<td>13</td>
<td>2022-11-24 08:30:00</td>
</tr>
<tr>
<td>2</td>
<td>21</td>
<td>2022-11-22 13:12:00</td>
</tr>
<tr>
<td>3</td>
<td>31</td>
<td>2022-11-22 14:12:00</td>
</tr>
<tr>
<td>3</td>
<td>32</td>
<td>2022-11-22 14:30:00</td>
</tr>
</tbody>
</table>
</div>
<p>i would like to left join table1 to table2 by comparing the table1's end_time with table2's last_dt.</p>
<p>below is the expected result.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>item</th>
<th>end time</th>
<th>value</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2022-11-23 08:12:00</td>
<td>12</td>
</tr>
<tr>
<td>1</td>
<td>2022-11-23 09:12:00</td>
<td>11</td>
</tr>
<tr>
<td>2</td>
<td>2022-11-22 13:12:00</td>
<td>21</td>
</tr>
<tr>
<td>3</td>
<td>2022-11-22 14:12:00</td>
<td>31</td>
</tr>
</tbody>
</table>
</div>
|
[
{
"answer_id": 74637740,
"author": "Danz",
"author_id": 19681705,
"author_profile": "https://Stackoverflow.com/users/19681705",
"pm_score": 1,
"selected": true,
"text": "<div class=\"row\">\n @foreach ($members as $member)\n <div class=\"col-md-3\">\n <div class=\"img-box\">\n <pre>\n <img src=\"/uploads/image/{{ $member->image }}\" width=\"100\" height=\"100\"/>\n {{ $member->id }}<br/>\n <a> {{ $member->name }}</a>\n </pre>\n </div>\n </div>\n @endforeach\n</div>\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20653002/"
] |
74,637,692
|
<p>Rahul was learning about numbers in list. He came across one word ground of a number.</p>
<p>A ground of a number is defined as the number which is just smaller or equal to the number given to you.Hence he started solving some assignments related to it. He got struck in some questions. Your task is to help him.</p>
<p>O(n) time complexity</p>
<p>O(n) Auxilary space</p>
<p>Input Description:
First line contains two numbers ‘n’ denoting number of integers and ‘k’ whose ground is to be check. Next line contains n space separated numbers.</p>
<p>Output Description:
Print the index of val.Print -1 if equal or near exqual number</p>
<p>Sample Input :
7 3
1 2 3 4 5 6 7
Sample Output :
2</p>
<p>`</p>
<pre><code>n,k = 7,3
a= [1,2,3,4,5,6,7]
b=[]
for i in range(n):
if k==a[i]:
print(i)
break
elif a[i]<k:
b.append(i)
print(max(b))
</code></pre>
<p>`</p>
|
[
{
"answer_id": 74637740,
"author": "Danz",
"author_id": 19681705,
"author_profile": "https://Stackoverflow.com/users/19681705",
"pm_score": 1,
"selected": true,
"text": "<div class=\"row\">\n @foreach ($members as $member)\n <div class=\"col-md-3\">\n <div class=\"img-box\">\n <pre>\n <img src=\"/uploads/image/{{ $member->image }}\" width=\"100\" height=\"100\"/>\n {{ $member->id }}<br/>\n <a> {{ $member->name }}</a>\n </pre>\n </div>\n </div>\n @endforeach\n</div>\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20214346/"
] |
74,637,704
|
<p><a href="https://i.stack.imgur.com/iLg0o.jpg" rel="nofollow noreferrer">Confusion matrix</a>
we know that the precision formula is tp/(tp+fp) and the recall formula is tp/(tp+fn) my doubt is how to get tp, fp, fn values from the confusion matrix and what is predicted on the y-axis side and what is true on x-axis side of the given confusion matrix.</p>
<p>from the confusion matrix. I want tp, tn, fp, fn, and what is true on the x-axis and predicated on the y-axis and what are background fp and background fn.
How to read tp, tn, fp, fn from the given confusion matrix above image.</p>
|
[
{
"answer_id": 74637740,
"author": "Danz",
"author_id": 19681705,
"author_profile": "https://Stackoverflow.com/users/19681705",
"pm_score": 1,
"selected": true,
"text": "<div class=\"row\">\n @foreach ($members as $member)\n <div class=\"col-md-3\">\n <div class=\"img-box\">\n <pre>\n <img src=\"/uploads/image/{{ $member->image }}\" width=\"100\" height=\"100\"/>\n {{ $member->id }}<br/>\n <a> {{ $member->name }}</a>\n </pre>\n </div>\n </div>\n @endforeach\n</div>\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20222824/"
] |
74,637,705
|
<p>I have a bit of a situation on the main branch in my repository.</p>
<p>A developer mistakingly pushed a PR from our develop branch directly into main and pushed to remote. We've applied policies so that this cannot happen again.</p>
<p>After this, we reversed this PR by utilising the 'Revert PR' feature in Azure DevOps, which created a branch, undid all the changes, and then merged it all back into main. So far so good.</p>
<p>In the meantime, we've also had to apply some hotfixes to the main branch. When attempting to roll these changes back up to develop, I've realised that the revert commit will also go back up, meaning we will lose changes in develop.</p>
<p>I've also now realised that when we do a PR from dev to main, these previously pushed changes will not be merged back down again.</p>
<p>How do I sort out the situation so that I do not lose the feature changes when merging hotfixes back into develop and also ensure that the feature comes back to main the next time we do a correct PR?</p>
<p>My assumption is that I need to revert the revert (git revert -m 1 ), but is there a better way?</p>
|
[
{
"answer_id": 74641957,
"author": "Jay",
"author_id": 4068476,
"author_profile": "https://Stackoverflow.com/users/4068476",
"pm_score": 0,
"selected": false,
"text": "dev main main main dev dev git revert <commit Y> -m 1 main dev dev dev main"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1248716/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.