qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,644,462
|
<p>I have this simple array:</p>
<pre><code>const arr = [
{
"id": 2,
"color": "red"
},
{
"id": 1,
"color": "blue"
},
{
"id": 2,
"color": "yellow"
},
];
</code></pre>
<p>I want to create a hash map where I want to add new colors on that key.</p>
<p>E.g I want to added <code>color: green</code> on <code>id: 3</code></p>
<p>Now here you can see there is no <code>id: 3</code></p>
<p>Now here I am expecting:</p>
<pre><code>{
2: [{color: "red"}]
1: [{color: "blue"}, {color: "yellow"}],
3: [{color: "green"}]
}
</code></pre>
<p>Now if I want to add <code>color: brown</code> on <code>id: 2</code></p>
<p>In that case I am expecting:</p>
<pre><code>{
2: [{color: "red"}, {color: "brown"}]
1: [{color: "blue"}, {color: "yellow"}],
3: [{color: "green"}]
}
</code></pre>
<p>I have created a Playground:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const arr = [
{
"id": 2,
"color": "red"
},
{
"id": 1,
"color": "blue"
},
{
"id": 2,
"color": "yellow"
},
];
function addItem(id: number, colors: any) {
let newArr = {[id]: colors};
arr.forEach(function (obj) {
newArr[obj.id].push({id: obj.color});
});
return newArr;
}
console.log(addItem(3, [{color: "green"}]))
console.log(addItem(1, [{color: "brown"}]))</code></pre>
</div>
</div>
</p>
<p>Here I also want to avoid duplicates</p>
|
[
{
"answer_id": 74644931,
"author": "ACTS 238",
"author_id": 18715651,
"author_profile": "https://Stackoverflow.com/users/18715651",
"pm_score": 0,
"selected": false,
"text": "function test(id, color) {\n for (var i = 0; i < arr.length; i++) {\n if (arr[i].id == id) {\n arr[i].color.push(color)\n }\n }\n }\n"
},
{
"answer_id": 74644932,
"author": "Sanay Varghese",
"author_id": 20193094,
"author_profile": "https://Stackoverflow.com/users/20193094",
"pm_score": 0,
"selected": false,
"text": "const hashMap = new Map([\n [1, [{ color: \"red\" }]],\n [2, [{ color: \"blue\" }]],\n [3, [{ color: \"yellow\" }]],\n]);\n\nfunction addItem(id, colors) {\n hashMap.set(\n id,\n hashMap.has(id) ? [...hashMap.get(id).concat(colors)] : colors\n );\n\n return hashMap;\n}\nconsole.log(hashMap);\nconsole.log(addItem(3, [{ color: \"green\" }]));\nconsole.log(addItem(4, [{ color: \"pink\" }]));"
},
{
"answer_id": 74644954,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 1,
"selected": false,
"text": "const arr = [{\n \"id\": 2,\n \"color\": \"red\"\n },\n {\n \"id\": 1,\n \"color\": \"blue\"\n },\n {\n \"id\": 2,\n \"color\": \"yellow\"\n },\n];\n\nconst grouped = arr.reduce((groups, current) => {\n if (!(current.id in groups)) {\n groups[current.id] = []\n }\n groups[current.id].push({\n color: current.color\n })\n return groups\n}, {})\n\naddItem(3, {\n color: \"green\"\n})\n\naddItem(1, {\n color: \"brown\"\n})\n\nconsole.log(grouped)\n\nfunction addItem(id, item) {\n if (!(id in grouped)) {\n grouped[id] = []\n }\n grouped[id].push(item)\n}"
},
{
"answer_id": 74645878,
"author": "dangarfield",
"author_id": 3265253,
"author_profile": "https://Stackoverflow.com/users/3265253",
"pm_score": 0,
"selected": false,
"text": "let arr = [{\n \"id\": 2,\n \"color\": \"red\"\n },\n {\n \"id\": 1,\n \"color\": \"blue\"\n },\n {\n \"id\": 2,\n \"color\": \"yellow\"\n },\n];\n\nconst groupBy = (xs, key) => {\n return xs.reduce(function(rv, x) {\n const y = {...x};\n delete y[key];\n (rv[x[key]] = rv[x[key]] || []).push(y);\n return rv\n }, {})\n}\n\n\nconst addItem = (id, colors) => {\n // const newArr = arr... etc if you don't want to modify the existing array\n arr = arr.concat(colors.map(c => {\n c.id = id;\n return c\n }))\n\n const grouped = groupBy(arr, 'id')\n return grouped\n}\n\nconsole.log(addItem(3, [{\n color: \"green\"\n}]))\nconsole.log(addItem(1, [{\n color: \"brown\"\n}]))"
},
{
"answer_id": 74648577,
"author": "Andy",
"author_id": 1377002,
"author_profile": "https://Stackoverflow.com/users/1377002",
"pm_score": 0,
"selected": false,
"text": "const arr=[{id:2,color:\"red\"},{id:1,color:\"blue\"},{id:2,color:\"yellow\"}];\n\nclass ColorMap {\n \n // `reduce` over the array to create a `colors` Map.\n // If the id doesn't exist on the map as a key,\n // create it, and assign an empty array to it.\n // Then push in the color to the array if\n // it doesn't already exist\n constructor(arr) {\n this.colors = arr.reduce((acc, obj) => {\n const { id, color } = obj;\n if (!acc.has(id)) acc.set(id, []);\n if (!this.colorExists(id, color)) {\n acc.get(id).push({ color });\n }\n return acc;\n }, new Map());\n }\n \n // Simple check to see if the color already\n // exists in the target array\n colorExists(id, color) {\n return this.colors?.get(id)?.find(obj => {\n return obj.color === color;\n });\n }\n\n // Similar to the `reduce` function, if the id doesn't have\n // a key on the map create one, and initialise an empty array,\n // and if the color doesn't already exist add it\n addColor(id, color) {\n if (!this.colors.has(id)) this.colors.set(id, []);\n if (!this.colorExists(id, color)) {\n this.colors.get(id).push({ color });\n }\n }\n\n // Return the colors map as a readable object\n showColors() {\n return Object.fromEntries(this.colors);\n }\n\n}\n\nconst colorMap = new ColorMap(arr);\n\ncolorMap.addColor(3, 'green');\ncolorMap.addColor(1, 'brown');\ncolorMap.addColor(1, 'brown');\n\nconsole.log(colorMap.showColors()); reduce"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74644462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3924832/"
] |
74,644,490
|
<p>I don't quite get the definition and use case of an abstract machine and how its actually related to a compiler or interpreter</p>
<p>I googled what abstract machines were but understood very little out of it.</p>
<pre><code>An abstract machine is a model of a computer system (considered either as hardware or software) constructed to allow a detailed and precise analysis of how the computer system works.
</code></pre>
<p>Here are some articles I read but understood not that much out of:</p>
<ul>
<li><a href="https://mortoray.com/abstract-machines-interpreters-and-compilers/" rel="nofollow noreferrer">Article 1</a></li>
<li><a href="https://en.wikipedia.org/wiki/Abstract_machine" rel="nofollow noreferrer">Wikipedia definition</a></li>
<li><a href="https://www.quora.com/What-is-abstract-machine-and-how-does-it-work" rel="nofollow noreferrer">Quora Question</a></li>
<li><a href="https://stackoverflow.com/questions/64092889/how-is-code-stored-and-executed-on-the-c-abstract-machine">Stackoverflow question</a></li>
</ul>
|
[
{
"answer_id": 74644931,
"author": "ACTS 238",
"author_id": 18715651,
"author_profile": "https://Stackoverflow.com/users/18715651",
"pm_score": 0,
"selected": false,
"text": "function test(id, color) {\n for (var i = 0; i < arr.length; i++) {\n if (arr[i].id == id) {\n arr[i].color.push(color)\n }\n }\n }\n"
},
{
"answer_id": 74644932,
"author": "Sanay Varghese",
"author_id": 20193094,
"author_profile": "https://Stackoverflow.com/users/20193094",
"pm_score": 0,
"selected": false,
"text": "const hashMap = new Map([\n [1, [{ color: \"red\" }]],\n [2, [{ color: \"blue\" }]],\n [3, [{ color: \"yellow\" }]],\n]);\n\nfunction addItem(id, colors) {\n hashMap.set(\n id,\n hashMap.has(id) ? [...hashMap.get(id).concat(colors)] : colors\n );\n\n return hashMap;\n}\nconsole.log(hashMap);\nconsole.log(addItem(3, [{ color: \"green\" }]));\nconsole.log(addItem(4, [{ color: \"pink\" }]));"
},
{
"answer_id": 74644954,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 1,
"selected": false,
"text": "const arr = [{\n \"id\": 2,\n \"color\": \"red\"\n },\n {\n \"id\": 1,\n \"color\": \"blue\"\n },\n {\n \"id\": 2,\n \"color\": \"yellow\"\n },\n];\n\nconst grouped = arr.reduce((groups, current) => {\n if (!(current.id in groups)) {\n groups[current.id] = []\n }\n groups[current.id].push({\n color: current.color\n })\n return groups\n}, {})\n\naddItem(3, {\n color: \"green\"\n})\n\naddItem(1, {\n color: \"brown\"\n})\n\nconsole.log(grouped)\n\nfunction addItem(id, item) {\n if (!(id in grouped)) {\n grouped[id] = []\n }\n grouped[id].push(item)\n}"
},
{
"answer_id": 74645878,
"author": "dangarfield",
"author_id": 3265253,
"author_profile": "https://Stackoverflow.com/users/3265253",
"pm_score": 0,
"selected": false,
"text": "let arr = [{\n \"id\": 2,\n \"color\": \"red\"\n },\n {\n \"id\": 1,\n \"color\": \"blue\"\n },\n {\n \"id\": 2,\n \"color\": \"yellow\"\n },\n];\n\nconst groupBy = (xs, key) => {\n return xs.reduce(function(rv, x) {\n const y = {...x};\n delete y[key];\n (rv[x[key]] = rv[x[key]] || []).push(y);\n return rv\n }, {})\n}\n\n\nconst addItem = (id, colors) => {\n // const newArr = arr... etc if you don't want to modify the existing array\n arr = arr.concat(colors.map(c => {\n c.id = id;\n return c\n }))\n\n const grouped = groupBy(arr, 'id')\n return grouped\n}\n\nconsole.log(addItem(3, [{\n color: \"green\"\n}]))\nconsole.log(addItem(1, [{\n color: \"brown\"\n}]))"
},
{
"answer_id": 74648577,
"author": "Andy",
"author_id": 1377002,
"author_profile": "https://Stackoverflow.com/users/1377002",
"pm_score": 0,
"selected": false,
"text": "const arr=[{id:2,color:\"red\"},{id:1,color:\"blue\"},{id:2,color:\"yellow\"}];\n\nclass ColorMap {\n \n // `reduce` over the array to create a `colors` Map.\n // If the id doesn't exist on the map as a key,\n // create it, and assign an empty array to it.\n // Then push in the color to the array if\n // it doesn't already exist\n constructor(arr) {\n this.colors = arr.reduce((acc, obj) => {\n const { id, color } = obj;\n if (!acc.has(id)) acc.set(id, []);\n if (!this.colorExists(id, color)) {\n acc.get(id).push({ color });\n }\n return acc;\n }, new Map());\n }\n \n // Simple check to see if the color already\n // exists in the target array\n colorExists(id, color) {\n return this.colors?.get(id)?.find(obj => {\n return obj.color === color;\n });\n }\n\n // Similar to the `reduce` function, if the id doesn't have\n // a key on the map create one, and initialise an empty array,\n // and if the color doesn't already exist add it\n addColor(id, color) {\n if (!this.colors.has(id)) this.colors.set(id, []);\n if (!this.colorExists(id, color)) {\n this.colors.get(id).push({ color });\n }\n }\n\n // Return the colors map as a readable object\n showColors() {\n return Object.fromEntries(this.colors);\n }\n\n}\n\nconst colorMap = new ColorMap(arr);\n\ncolorMap.addColor(3, 'green');\ncolorMap.addColor(1, 'brown');\ncolorMap.addColor(1, 'brown');\n\nconsole.log(colorMap.showColors()); reduce"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74644490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17544515/"
] |
74,644,492
|
<pre class="lang-py prettyprint-override"><code>ANIMALS = (('dog','dog'), ('cat','cat'))
class Owner(models.Model):
animal = models.Charfield(choices=ANIMALS, max_length=10)
</code></pre>
<p>My problem is how I can do if I have both ?</p>
|
[
{
"answer_id": 74644931,
"author": "ACTS 238",
"author_id": 18715651,
"author_profile": "https://Stackoverflow.com/users/18715651",
"pm_score": 0,
"selected": false,
"text": "function test(id, color) {\n for (var i = 0; i < arr.length; i++) {\n if (arr[i].id == id) {\n arr[i].color.push(color)\n }\n }\n }\n"
},
{
"answer_id": 74644932,
"author": "Sanay Varghese",
"author_id": 20193094,
"author_profile": "https://Stackoverflow.com/users/20193094",
"pm_score": 0,
"selected": false,
"text": "const hashMap = new Map([\n [1, [{ color: \"red\" }]],\n [2, [{ color: \"blue\" }]],\n [3, [{ color: \"yellow\" }]],\n]);\n\nfunction addItem(id, colors) {\n hashMap.set(\n id,\n hashMap.has(id) ? [...hashMap.get(id).concat(colors)] : colors\n );\n\n return hashMap;\n}\nconsole.log(hashMap);\nconsole.log(addItem(3, [{ color: \"green\" }]));\nconsole.log(addItem(4, [{ color: \"pink\" }]));"
},
{
"answer_id": 74644954,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 1,
"selected": false,
"text": "const arr = [{\n \"id\": 2,\n \"color\": \"red\"\n },\n {\n \"id\": 1,\n \"color\": \"blue\"\n },\n {\n \"id\": 2,\n \"color\": \"yellow\"\n },\n];\n\nconst grouped = arr.reduce((groups, current) => {\n if (!(current.id in groups)) {\n groups[current.id] = []\n }\n groups[current.id].push({\n color: current.color\n })\n return groups\n}, {})\n\naddItem(3, {\n color: \"green\"\n})\n\naddItem(1, {\n color: \"brown\"\n})\n\nconsole.log(grouped)\n\nfunction addItem(id, item) {\n if (!(id in grouped)) {\n grouped[id] = []\n }\n grouped[id].push(item)\n}"
},
{
"answer_id": 74645878,
"author": "dangarfield",
"author_id": 3265253,
"author_profile": "https://Stackoverflow.com/users/3265253",
"pm_score": 0,
"selected": false,
"text": "let arr = [{\n \"id\": 2,\n \"color\": \"red\"\n },\n {\n \"id\": 1,\n \"color\": \"blue\"\n },\n {\n \"id\": 2,\n \"color\": \"yellow\"\n },\n];\n\nconst groupBy = (xs, key) => {\n return xs.reduce(function(rv, x) {\n const y = {...x};\n delete y[key];\n (rv[x[key]] = rv[x[key]] || []).push(y);\n return rv\n }, {})\n}\n\n\nconst addItem = (id, colors) => {\n // const newArr = arr... etc if you don't want to modify the existing array\n arr = arr.concat(colors.map(c => {\n c.id = id;\n return c\n }))\n\n const grouped = groupBy(arr, 'id')\n return grouped\n}\n\nconsole.log(addItem(3, [{\n color: \"green\"\n}]))\nconsole.log(addItem(1, [{\n color: \"brown\"\n}]))"
},
{
"answer_id": 74648577,
"author": "Andy",
"author_id": 1377002,
"author_profile": "https://Stackoverflow.com/users/1377002",
"pm_score": 0,
"selected": false,
"text": "const arr=[{id:2,color:\"red\"},{id:1,color:\"blue\"},{id:2,color:\"yellow\"}];\n\nclass ColorMap {\n \n // `reduce` over the array to create a `colors` Map.\n // If the id doesn't exist on the map as a key,\n // create it, and assign an empty array to it.\n // Then push in the color to the array if\n // it doesn't already exist\n constructor(arr) {\n this.colors = arr.reduce((acc, obj) => {\n const { id, color } = obj;\n if (!acc.has(id)) acc.set(id, []);\n if (!this.colorExists(id, color)) {\n acc.get(id).push({ color });\n }\n return acc;\n }, new Map());\n }\n \n // Simple check to see if the color already\n // exists in the target array\n colorExists(id, color) {\n return this.colors?.get(id)?.find(obj => {\n return obj.color === color;\n });\n }\n\n // Similar to the `reduce` function, if the id doesn't have\n // a key on the map create one, and initialise an empty array,\n // and if the color doesn't already exist add it\n addColor(id, color) {\n if (!this.colors.has(id)) this.colors.set(id, []);\n if (!this.colorExists(id, color)) {\n this.colors.get(id).push({ color });\n }\n }\n\n // Return the colors map as a readable object\n showColors() {\n return Object.fromEntries(this.colors);\n }\n\n}\n\nconst colorMap = new ColorMap(arr);\n\ncolorMap.addColor(3, 'green');\ncolorMap.addColor(1, 'brown');\ncolorMap.addColor(1, 'brown');\n\nconsole.log(colorMap.showColors()); reduce"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74644492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9322470/"
] |
74,644,499
|
<p>I'm trying to initialize a tuple (using <code>std::make_tuple</code>), and I want to store an std::type_info in it as well, but I don't know why for some reason this simple looking piece of code doesn't compile.</p>
<p>I tried running the following code:-</p>
<pre><code>#include <iostream>
#include <string>
#include <tuple>
#include <typeinfo>
#include <any>
int main()
{
std::tuple<std::type_info, int, std::any> tpl = std::make_tuple(typeid(float), 1, "Hello");
const auto&[type, num, anyval] = tpl;
std::cout<<type.name()<<std::endl;
std::cout<<num<<std::endl;
std::cout<<std::any_cast<const char*>(anyval)<<std::endl;
return 0;
}
</code></pre>
<p>If I only omit storing the first value (ie. type info) and create only <code>std::tuple<int, std::any></code> there doesn't seem to be any problem, but this attempt fails. How to get around it, as I've to store the <code>std::type_info</code> object anyhow.</p>
|
[
{
"answer_id": 74645127,
"author": "Marek R",
"author_id": 1387438,
"author_profile": "https://Stackoverflow.com/users/1387438",
"pm_score": 2,
"selected": false,
"text": "std::type_info std::reference_wrapper int main()\n{\n std::tuple<std::reference_wrapper<const std::type_info>, int, std::any> tpl = std::make_tuple(std::cref(typeid(float)), 1, \"Hello\");\n\n const auto& [type, num, anyval] = tpl;\n std::cout << type.get().name() << std::endl;\n std::cout << num << std::endl;\n std::cout << std::any_cast<const char*>(anyval) << std::endl;\n return 0;\n}\n StoryTeller int main()\n{\n std::tuple<std::type_index, int, std::any> tpl = std::make_tuple(std::type_index(typeid(float)), 1, \"Hello\");\n\n const auto& [type, num, anyval] = tpl;\n std::cout << type.name() << std::endl;\n std::cout << num << std::endl;\n std::cout << std::any_cast<const char*>(anyval) << std::endl;\n return 0;\n}\n"
},
{
"answer_id": 74652748,
"author": "Aayush Anand",
"author_id": 13489126,
"author_profile": "https://Stackoverflow.com/users/13489126",
"pm_score": 0,
"selected": false,
"text": "std::type_info std::type_index std::any std::type_info"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74644499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13489126/"
] |
74,644,553
|
<p>I'm using external API to make an SQL query for a user. As a result i get matching Entity but as a set of fields, lookin like this:</p>
<pre><code>[
{ IsNull: false, Name: 'Key', Value: '897', Values: null },
{ IsNull: false, Name: 'FirstName', Value: 'User', Values: null },
{ IsNull: false, Name: 'LastName', Value: 'Portal', Values: null },
{
IsNull: false,
Name: 'Email',
Value: 'some@email.com',
Values: null
},
{ IsNull: true, Name: 'Salutation', Value: null, Values: null },
{ IsNull: false, Name: 'Type', Value: '2', Values: null },
{
IsNull: false,
Name: 'LastLoggedDate',
Value: '2022-12-01 15:24:03',
Values: null
}
]
</code></pre>
<p>How to transform this response to end with simple object { email: 'some@email', firstName: 'User' lastName: 'Portal' } ??</p>
<p>I ended up with solution like this (below) but i believe there's some easiest way to do that, especially with more fields</p>
<pre><code>let userRawEntity = queryResult.data.Entities[0].Fields;
const userEmail = userRawEntity.filter((obj) => { return obj.Name === 'Email' });
const userFirstName = userRawEntity.filter((obj) => { return obj.Name === 'FirstName' });
const userLastName = userRawEntity.filter((obj) => { return obj.Name === 'LastName' });
return { email: userEmail[0].Value, firstName: userFirstName[0].Value, lastName: userLastName[0].Value };
</code></pre>
<p>Edit:
final solution that works and looks nicer. thanks for help :)</p>
<pre><code> if (queryResult.data.TotalEntityCount > 0) {
let user: {[key: string]: string | null } = {}
let userRawEntity = queryResult.data.Entities[0].Fields;
userRawEntity.forEach(data => user[data.Name] = data.Value);
return { email: user.Email, currency: user.Currency } as JwtPayload;
}
</code></pre>
|
[
{
"answer_id": 74644877,
"author": "Sean Anglim",
"author_id": 17843144,
"author_profile": "https://Stackoverflow.com/users/17843144",
"pm_score": 2,
"selected": true,
"text": "let dataTransformed: {[key: string]: string | null} = {}\n\ndata.forEach(d => {\n dataTransformed[d.Name] = d.Value\n})\n {\n \"Key\": \"897\",\n \"FirstName\": \"User\",\n \"LastName\": \"Portal\",\n \"Email\": \"some@email.com\",\n \"Salutation\": null,\n \"Type\": \"2\",\n \"LastLoggedDate\": \"2022-12-01 15:24:03\"\n}\n"
},
{
"answer_id": 74646371,
"author": "saumya jain",
"author_id": 20590130,
"author_profile": "https://Stackoverflow.com/users/20590130",
"pm_score": 0,
"selected": false,
"text": "lodash _.mapValues(_.keyBy(data, \"Name\"), o => o.Value || o.Values);"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74644553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20657935/"
] |
74,644,586
|
<p>I'm seeing multi-second pauses in the event stream, even reading from the retention pool.</p>
<p>Here's the main nugget of EH setup:</p>
<pre><code>BlobContainerClient storageClient = new BlobContainerClient(blobcon, BLOB_NAME);
RTMTest.eventProcessor = new EventProcessorClient(storageClient, consumerGroup, ehubcon, EVENTHUB_NAME);
</code></pre>
<p>And then the do nothing processor:</p>
<pre><code> static async Task processEventHandler(ProcessEventArgs eventArgs)
{
RTMTest.eventsPerSecond++;
RTMTest.eventCount++;
if ((RTMTest.eventCount % 16) == 0)
{
await eventArgs.UpdateCheckpointAsync(eventArgs.CancellationToken);
}
}
</code></pre>
<p>And then a typical execution:</p>
<pre><code>15:02:23: no events
15:02:24: no events
15:02:25: reqs=643
15:02:26: reqs=656
15:02:27: reqs=1280
15:02:28: reqs=2221
15:02:29: no events
15:02:30: no events
15:02:31: no events
15:02:32: no events
15:02:33: no events
15:02:34: no events
15:02:35: no events
15:02:36: no events
15:02:37: no events
15:02:38: no events
15:02:39: no events
15:02:40: no events
15:02:41: no events
15:02:42: no events
15:02:43: no events
15:02:44: reqs=3027
15:02:45: reqs=3440
15:02:47: reqs=4320
15:02:48: reqs=9232
15:02:49: reqs=4064
15:02:50: reqs=395
15:02:51: no events
15:02:52: no events
15:02:53: no events
</code></pre>
<p>The event hub, blob storage and RTMTest webjob are all in US West 2. The event hub as 16 partitions. It's correctly calling my handler as evidenced by the bursts of data. The error handler is not called.</p>
<p>Here are two applications side by side, left using Redis, right using Event Hub. The events turn into the animations so you can visually watch the long stalls. Note: these are vaccines being reported around the US, either live or via batch reconciliations from the pharmacies.</p>
<p><a href="http://vaxbytes.com/dual.html" rel="nofollow noreferrer">vaccine reporting animations</a></p>
<p>Any idea why I see the multi-second stalls?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 74644877,
"author": "Sean Anglim",
"author_id": 17843144,
"author_profile": "https://Stackoverflow.com/users/17843144",
"pm_score": 2,
"selected": true,
"text": "let dataTransformed: {[key: string]: string | null} = {}\n\ndata.forEach(d => {\n dataTransformed[d.Name] = d.Value\n})\n {\n \"Key\": \"897\",\n \"FirstName\": \"User\",\n \"LastName\": \"Portal\",\n \"Email\": \"some@email.com\",\n \"Salutation\": null,\n \"Type\": \"2\",\n \"LastLoggedDate\": \"2022-12-01 15:24:03\"\n}\n"
},
{
"answer_id": 74646371,
"author": "saumya jain",
"author_id": 20590130,
"author_profile": "https://Stackoverflow.com/users/20590130",
"pm_score": 0,
"selected": false,
"text": "lodash _.mapValues(_.keyBy(data, \"Name\"), o => o.Value || o.Values);"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74644586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4884960/"
] |
74,644,592
|
<p>I am creating a tool to automate some tasks. These tasks generate two DataFrames, but when concatenating them the columns are messed up as follows:</p>
<pre><code> col2 col4 col3 col1
0 A 2 0 a
1 A 1 1 B
2 B 9 9 c
3 NaN 8 4 D
4 D 7 2 e
5 C 4 3 F
</code></pre>
<p>But I need to rearrange them so that they look like this:</p>
<pre><code> col1 col2 col3 col4
0 a A 0 2
1 B A 1 1
2 c B 9 9
3 D NaN 4 8
4 e D 2 7
5 F C 3 4
</code></pre>
<p>Can someone help me?</p>
<p>I tried with sort_values, but it didn't work, and I can't find anywhere another way to try to solve the problem.</p>
|
[
{
"answer_id": 74644625,
"author": "SomeDude",
"author_id": 1410303,
"author_profile": "https://Stackoverflow.com/users/1410303",
"pm_score": 0,
"selected": false,
"text": "df = df[sorted(df.columns.tolist())].copy()\n"
},
{
"answer_id": 74644636,
"author": "supersquires",
"author_id": 18182675,
"author_profile": "https://Stackoverflow.com/users/18182675",
"pm_score": 0,
"selected": false,
"text": "df = df[['col1', 'col2', 'col3', 'col4']]\n"
},
{
"answer_id": 74644655,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 2,
"selected": true,
"text": "df.sort_index(axis=1)\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74644592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17944590/"
] |
74,644,603
|
<p>I am trying to fetch the price of a stock using <code>fetch</code> in my pure React App.
When I try to fetch without options or configurations, using <code>fetch(url)</code>, this error comes:</p>
<pre><code>Access to fetch at 'https://query1.finance.yahoo.com/v8/finance/chart/RCF.BO' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
</code></pre>
<p>The API : <code>https://query1.finance.yahoo.com/v8/finance/chart/<SYMBOL>.BO</code> is open. I don't seem to have any issue fetching it from my browser directly. It's causing the same issue even when I am including this option to the fetch:</p>
<pre><code> var options = {
method: 'GET',
crossorigin: true,
headers: {
'Access-Control-Allow-Origin': '*',
}
}
</code></pre>
<p>The error I am getting as per my knowledge and research is common. But the solutions proposed, deals with changing the server configurations and allowing different origins, which are not applicable for me as the API I am using is open. I am not using any backend but just pure React.</p>
<p>Using <code>no-cors</code> also doesn't work as I need the data to be visible so that I can use it. I used some third party extensions while development phase, but now while hosting, it's not fetching the data from the API.</p>
<p>Can someone help with this issue?</p>
|
[
{
"answer_id": 74644625,
"author": "SomeDude",
"author_id": 1410303,
"author_profile": "https://Stackoverflow.com/users/1410303",
"pm_score": 0,
"selected": false,
"text": "df = df[sorted(df.columns.tolist())].copy()\n"
},
{
"answer_id": 74644636,
"author": "supersquires",
"author_id": 18182675,
"author_profile": "https://Stackoverflow.com/users/18182675",
"pm_score": 0,
"selected": false,
"text": "df = df[['col1', 'col2', 'col3', 'col4']]\n"
},
{
"answer_id": 74644655,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 2,
"selected": true,
"text": "df.sort_index(axis=1)\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74644603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13037132/"
] |
74,644,618
|
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncGenerator/return" rel="nofollow noreferrer">AsyncGenerator.prototype.return() - JavaScript | MDN</a> states:</p>
<blockquote>
<p>The <code>return()</code> method of an async generator acts as if a <code>return</code> statement is inserted in the generator's body at the current suspended position, which finishes the generator and allows the generator to perform any cleanup tasks when combined with a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch#the_finally-block" rel="nofollow noreferrer"><code>try...finally</code></a> block.</p>
</blockquote>
<p>Why then does the following code print <code>0</code>–<code>3</code> rather than only <code>0</code>–<code>2</code>?</p>
<pre class="lang-js prettyprint-override"><code>const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const values = (async function* delayedIntegers() {
let n = 0;
while (true) {
yield n++;
await delay(100);
}
})();
await Promise.all([
(async () => {
for await (const value of values) console.log(value);
})(),
(async () => {
await delay(250);
values.return();
})(),
]);
</code></pre>
<p>I tried adding log statements to better understand where the "current suspended position" is and from what I can tell when I call the <code>return()</code> method the <code>AsyncGenerator</code> instance isn't suspended (the body execution isn't at a <code>yield</code> statement) and instead of returning once reaching the <code>yield</code> statement the next value is <code>yielded</code> and then suspended at which point the "return" finally happens.</p>
<p>Is there any way to detect that the <code>return()</code> method has been invoked and not <code>yield</code> afterwards?</p>
<hr />
<p>I can implement the <code>AsyncIterator</code> interface myself but then I lose the <code>yield</code> syntax supported by async generators:</p>
<pre class="lang-js prettyprint-override"><code>const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const values = (() => {
let n = 0;
let done = false;
return {
[Symbol.asyncIterator]() {
return this;
},
async next() {
if (done) return { done, value: undefined };
if (n !== 0) {
await delay(100);
if (done) return { done, value: undefined };
}
return { done, value: n++ };
},
async return() {
done = true;
return { done, value: undefined };
},
};
})();
await Promise.all([
(async () => {
for await (const value of values) console.log(value);
})(),
(async () => {
await delay(250);
values.return();
})(),
]);
</code></pre>
|
[
{
"answer_id": 74670232,
"author": "armful",
"author_id": 20664163,
"author_profile": "https://Stackoverflow.com/users/20664163",
"pm_score": 2,
"selected": false,
"text": "values.return() yield return yield yield return yield AbortSignal const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n\nconst controller = new AbortController();\nconst { signal } = controller;\n\nconst values = (async function* delayedIntegers(signal) {\n let n = 0;\n while (true) {\n if (signal.aborted) break;\n yield n++;\n await delay(100);\n }\n})(signal);\n\nawait Promise.all([\n (async () => {\n for await (const value of values) console.log(value);\n })(),\n (async () => {\n await delay(250);\n controller.abort();\n })(),\n]);\n AbortSignal delayedIntegers aborted signal true break abort() AbortController AbortSignal"
},
{
"answer_id": 74670652,
"author": "Emre",
"author_id": 6468955,
"author_profile": "https://Stackoverflow.com/users/6468955",
"pm_score": 0,
"selected": false,
"text": "return() return yield yield return() values yield return() return() return() return() return() const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n\nconst values = (async function* delayedIntegers() {\n let n = 0;\n let shouldReturn = false;\n while (true) {\n if (shouldReturn) return;\n yield n++;\n await delay(100);\n }\n})();\n\n// Register a callback that sets the shouldReturn flag when the return() method is called\nvalues.return(() => { shouldReturn = true });\n\nawait Promise.all([\n (async () => {\n for await (const value of values) console.log(value);\n })(),\n (async () => {\n await delay(250);\n values.return();\n })(),\n]);\n try...finally return() const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n\nconst values = (async function* delayedIntegers() {\n let n = 0;\n try {\n while (true) {\n yield n++;\n await delay(100);\n }\n } finally {\n // Perform any necessary cleanup tasks here\n }\n})();\n\nawait Promise.all([\n (async () => {\n for await (const value of values) console.log(value);\n })(),\n (async () => {\n await delay(250);\n values.return();\n })(),\n]);\n next() return() throw() const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n\nconst values = (() => {\n let n = 0;\n let done = false;\n return {\n [Symbol.asyncIterator]() {\n return this;\n },\n async next() {\n if (done) return { done, value: undefined };\n if (n !== 0) {\n await delay(100);\n if (done) return { done, value: undefined };\n }\n return { done, value: n++ };\n },\n async return() {\n done = true;\n return { done, value: undefined };\n },\n };\n})();\n\nawait Promise.all([\n (async () => {\n for await (const value of values) console.log(value);\n })(),\n"
},
{
"answer_id": 74671237,
"author": "Bergi",
"author_id": 1048572,
"author_profile": "https://Stackoverflow.com/users/1048572",
"pm_score": 2,
"selected": false,
"text": "0–3 0–2 return() AsyncGenerator yield yield yield for await … of .next() .return() next const values = (async function*() {\n let i=0; while (true) {\n await new Promise(r => { setTimeout(r, 1000); });\n yield i++;\n }\n})();\nvalues.next().then(console.log, console.error);\nvalues.next().then(console.log, console.error);\nvalues.next().then(console.log, console.error);\nvalues.return('done').then(console.log, console.error);\nvalues.next().then(console.log, console.error); return() yield for await … of break const delay = (ms) => new Promise((resolve) => {\n setTimeout(resolve, ms);\n});\n\nasync function* delayedIntegers() {\n let n = 0;\n while (true) {\n yield n++;\n await delay(1000);\n }\n}\n\n(async function main() {\n const start = Date.now();\n const values = delayedIntegers();\n for await (const value of values) {\n if (Date.now() - start > 2500) {\n console.log('done:', value);\n break;\n }\n console.log(value);\n }\n})(); AbortSignal const delay = (ms, signal) => new Promise((resolve, reject) => {\n function done() {\n resolve();\n signal?.removeEventListener(\"abort\", stop);\n }\n function stop() {\n reject(this.reason);\n clearTimeout(handle);\n }\n signal?.throwIfAborted();\n const handle = setTimeout(done, ms);\n signal?.addEventListener(\"abort\", stop);\n});\n\nasync function* delayedIntegers(signal) {\n let n = 0;\n while (true) {\n yield n++;\n await delay(1000, signal);\n }\n}\n\n(async function main() {\n try {\n const values = delayedIntegers(AbortSignal.timeout(2500));\n for await (const value of values) {\n console.log(value);\n }\n } catch(e) {\n if (e.name != \"TimeoutError\") throw e;\n console.log(\"done\");\n }\n})();"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74644618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3255152/"
] |
74,644,650
|
<p>In my app I have multiple forms where the result JSON object may vary in its structure and has nested objects and arrays in different levels. These forms also allow the user to upload files and the object stores and array with url to download, name, etc.</p>
<p>What I do now is turn the file into base64 string, then before any request that has files, I upload them to my backend.</p>
<p>What I want to do is to make that API call of file upload, wait until it finish and once I get response, modify the user's body request, only then make the main post request with these modifications. But is not pausing, the queries are being executed in parallel, I know this because in the backend the file <em>is</em> uploaded but the user's object is not modified, and besides for some reason the query of file upload is being executed several times for no reason.</p>
<pre><code>export class FilesCheckerInterceptor implements HttpInterceptor {
constructor(private filesService: FilesService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const data = request.body;
if (data) {
const uploaded: File[] = [];
this.traverse(data, files => {
files.forEach(file => {
const base64 = file.data;
const result = this.filesService.toFile(base64, file.name);
uploaded.push(result);
});
});
console.log(request);
return this.filesService.uploadFile(uploaded).pipe(
mergeMap(response => {
this.traverse(data, files => {
for (let i = 0; i < response.length; i++) {
files[i] = response[i];
}
});
return next.handle(request.clone({ body: data }));
}),
);
}
else {
return next.handle(request);
}
}
traverse(obj: any, action: (value: InternalFile[]) => void) {
if (obj !== null && typeof obj === 'object') {
Object.entries(obj).forEach(([key, value]) => {
if (key === 'attachments' && Array.isArray(value)) {
// const files = value as InternalFile[];
action(value);
}
else {
this.traverse(value, action);
}
})
}
}
}
</code></pre>
|
[
{
"answer_id": 74670232,
"author": "armful",
"author_id": 20664163,
"author_profile": "https://Stackoverflow.com/users/20664163",
"pm_score": 2,
"selected": false,
"text": "values.return() yield return yield yield return yield AbortSignal const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n\nconst controller = new AbortController();\nconst { signal } = controller;\n\nconst values = (async function* delayedIntegers(signal) {\n let n = 0;\n while (true) {\n if (signal.aborted) break;\n yield n++;\n await delay(100);\n }\n})(signal);\n\nawait Promise.all([\n (async () => {\n for await (const value of values) console.log(value);\n })(),\n (async () => {\n await delay(250);\n controller.abort();\n })(),\n]);\n AbortSignal delayedIntegers aborted signal true break abort() AbortController AbortSignal"
},
{
"answer_id": 74670652,
"author": "Emre",
"author_id": 6468955,
"author_profile": "https://Stackoverflow.com/users/6468955",
"pm_score": 0,
"selected": false,
"text": "return() return yield yield return() values yield return() return() return() return() return() const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n\nconst values = (async function* delayedIntegers() {\n let n = 0;\n let shouldReturn = false;\n while (true) {\n if (shouldReturn) return;\n yield n++;\n await delay(100);\n }\n})();\n\n// Register a callback that sets the shouldReturn flag when the return() method is called\nvalues.return(() => { shouldReturn = true });\n\nawait Promise.all([\n (async () => {\n for await (const value of values) console.log(value);\n })(),\n (async () => {\n await delay(250);\n values.return();\n })(),\n]);\n try...finally return() const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n\nconst values = (async function* delayedIntegers() {\n let n = 0;\n try {\n while (true) {\n yield n++;\n await delay(100);\n }\n } finally {\n // Perform any necessary cleanup tasks here\n }\n})();\n\nawait Promise.all([\n (async () => {\n for await (const value of values) console.log(value);\n })(),\n (async () => {\n await delay(250);\n values.return();\n })(),\n]);\n next() return() throw() const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n\nconst values = (() => {\n let n = 0;\n let done = false;\n return {\n [Symbol.asyncIterator]() {\n return this;\n },\n async next() {\n if (done) return { done, value: undefined };\n if (n !== 0) {\n await delay(100);\n if (done) return { done, value: undefined };\n }\n return { done, value: n++ };\n },\n async return() {\n done = true;\n return { done, value: undefined };\n },\n };\n})();\n\nawait Promise.all([\n (async () => {\n for await (const value of values) console.log(value);\n })(),\n"
},
{
"answer_id": 74671237,
"author": "Bergi",
"author_id": 1048572,
"author_profile": "https://Stackoverflow.com/users/1048572",
"pm_score": 2,
"selected": false,
"text": "0–3 0–2 return() AsyncGenerator yield yield yield for await … of .next() .return() next const values = (async function*() {\n let i=0; while (true) {\n await new Promise(r => { setTimeout(r, 1000); });\n yield i++;\n }\n})();\nvalues.next().then(console.log, console.error);\nvalues.next().then(console.log, console.error);\nvalues.next().then(console.log, console.error);\nvalues.return('done').then(console.log, console.error);\nvalues.next().then(console.log, console.error); return() yield for await … of break const delay = (ms) => new Promise((resolve) => {\n setTimeout(resolve, ms);\n});\n\nasync function* delayedIntegers() {\n let n = 0;\n while (true) {\n yield n++;\n await delay(1000);\n }\n}\n\n(async function main() {\n const start = Date.now();\n const values = delayedIntegers();\n for await (const value of values) {\n if (Date.now() - start > 2500) {\n console.log('done:', value);\n break;\n }\n console.log(value);\n }\n})(); AbortSignal const delay = (ms, signal) => new Promise((resolve, reject) => {\n function done() {\n resolve();\n signal?.removeEventListener(\"abort\", stop);\n }\n function stop() {\n reject(this.reason);\n clearTimeout(handle);\n }\n signal?.throwIfAborted();\n const handle = setTimeout(done, ms);\n signal?.addEventListener(\"abort\", stop);\n});\n\nasync function* delayedIntegers(signal) {\n let n = 0;\n while (true) {\n yield n++;\n await delay(1000, signal);\n }\n}\n\n(async function main() {\n try {\n const values = delayedIntegers(AbortSignal.timeout(2500));\n for await (const value of values) {\n console.log(value);\n }\n } catch(e) {\n if (e.name != \"TimeoutError\") throw e;\n console.log(\"done\");\n }\n})();"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74644650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13749429/"
] |
74,644,651
|
<pre><code>df = pd.DataFrame({'c1':['Ax','Bx','Ay','By'], 'c2':[1,2,3,4]})
c1 c2
0 Ax 1
1 Bx 2
2 Ay 3
3 By 4
</code></pre>
<p>I'd like to group <code>x</code>s and <code>y</code>s in <code>c1</code> and sum their respective <code>c2</code> values.</p>
<p>Desired output:</p>
<pre><code> c1 c2
0 Cx 3
1 Cy 7
</code></pre>
|
[
{
"answer_id": 74644738,
"author": "SomeDude",
"author_id": 1410303,
"author_profile": "https://Stackoverflow.com/users/1410303",
"pm_score": 1,
"selected": false,
"text": "out = df.groupby(df.c1.str[-1]).sum().reset_index()\nout['c1'] = 'C' + out['c1']\n c1 c2\n0 Cx 3\n1 Cy 7\n"
},
{
"answer_id": 74644742,
"author": "Mustafa Aydın",
"author_id": 9332187,
"author_profile": "https://Stackoverflow.com/users/9332187",
"pm_score": 1,
"selected": false,
"text": ">>> (df.groupby(df.c1.str[-1])[\"c2\"]\n .sum().reset_index()\n .assign(c1=lambda fr: fr.c1.radd(\"C\")))\n\n c1 c2\n0 Cx 3\n1 Cy 7\n assign radd"
},
{
"answer_id": 74644747,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 3,
"selected": true,
"text": "df.groupby(df['c1'].str[-1]).sum()\n c2\nc1 \nx 3\ny 7\n df.groupby('C' + df['c1'].str[-1]).sum().reset_index()\n c1 c2\n0 Cx 3\n1 Cy 7\n"
},
{
"answer_id": 74644775,
"author": "abokey",
"author_id": 16120011,
"author_profile": "https://Stackoverflow.com/users/16120011",
"pm_score": 1,
"selected": false,
"text": "pandas.Series.replace GroupBy.sum out = (\n df\n .assign(c1= df[\"c1\"].str.replace(\"[A-Z]\", \"C\", regex=True))\n .groupby(\"c1\", as_index=False).sum(numeric_only=True)\n )\n \nprint(out)\n\n c1 c2\n0 Cx 3\n1 Cy 7\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74644651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2635863/"
] |
74,644,660
|
<p>I have created a pbix file and parametrized the data source.
Published the same to PowerBI Cloud and when I am trying to pass the datasource via a parameter concatenated to the URL, it does not seem to work.</p>
<p><a href="https://app.powerbi.com/groups/xxxxxxxxxxxxxx/reports/yyyyyyyyy/ReportSection9f88b1fd1e14a6e9LLLLabc?rp:Database=DatabaseA" rel="nofollow noreferrer">https://app.powerbi.com/groups/xxxxxxxxxxxxxx/reports/yyyyyyyyy/ReportSection9f88b1fd1e14a6e9LLLLabc?rp:Database=DatabaseA</a></p>
<p>I am adding from '? to A' t the published URL. This does not work, can you please provide insights.</p>
<p>Power BI Parameter working via URL</p>
|
[
{
"answer_id": 74644738,
"author": "SomeDude",
"author_id": 1410303,
"author_profile": "https://Stackoverflow.com/users/1410303",
"pm_score": 1,
"selected": false,
"text": "out = df.groupby(df.c1.str[-1]).sum().reset_index()\nout['c1'] = 'C' + out['c1']\n c1 c2\n0 Cx 3\n1 Cy 7\n"
},
{
"answer_id": 74644742,
"author": "Mustafa Aydın",
"author_id": 9332187,
"author_profile": "https://Stackoverflow.com/users/9332187",
"pm_score": 1,
"selected": false,
"text": ">>> (df.groupby(df.c1.str[-1])[\"c2\"]\n .sum().reset_index()\n .assign(c1=lambda fr: fr.c1.radd(\"C\")))\n\n c1 c2\n0 Cx 3\n1 Cy 7\n assign radd"
},
{
"answer_id": 74644747,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 3,
"selected": true,
"text": "df.groupby(df['c1'].str[-1]).sum()\n c2\nc1 \nx 3\ny 7\n df.groupby('C' + df['c1'].str[-1]).sum().reset_index()\n c1 c2\n0 Cx 3\n1 Cy 7\n"
},
{
"answer_id": 74644775,
"author": "abokey",
"author_id": 16120011,
"author_profile": "https://Stackoverflow.com/users/16120011",
"pm_score": 1,
"selected": false,
"text": "pandas.Series.replace GroupBy.sum out = (\n df\n .assign(c1= df[\"c1\"].str.replace(\"[A-Z]\", \"C\", regex=True))\n .groupby(\"c1\", as_index=False).sum(numeric_only=True)\n )\n \nprint(out)\n\n c1 c2\n0 Cx 3\n1 Cy 7\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74644660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20622964/"
] |
74,644,664
|
<p>I am new to stackOverflow and Reactjs,
i had tried many other problem like them but they didn't help</p>
<p>I aam trying to inert the form data from react to mongodb database using node and express.
and i am using FETCH API to send my form data. but there are two errors in chrome console.</p>
<p><strong>First error</strong></p>
<p><code>POST http://localhost:3000/register 404 (Not Found)</code></p>
<p>*For this error i had used *</p>
<p><code>"proxy": "http://localhost:4000"</code> in my pakage.json(reactjs) but still there is error*</p>
<p><strong>second error</strong></p>
<p><code>VM18761:1 Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON</code></p>
<p><em>I dont know what is this</em></p>
<p><strong>please guide me how to tackle all of these error</strong></p>
<p><strong>Reister.js(reactjs)</strong></p>
<pre><code>import React, { useState } from 'react'
import zerotwo from "../images/07.svg"
// import { Formik, useFormik } from 'formik'
// import { Signupschema } from '../Form-Validation/Schema'
const Signup = () => {
const [user, setUser] = useState({
username: "",
email: "",
mobile: "",
password: "",
cpassword: ""
})
let name, value
const handleInput = (e) => {
name = e.target.name
value = e.target.value
setUser({ ...user, [name]: value })
}
const PostData = async (e) => {
e.preventDefault()
const { username, email, mobile, password, cpassword } = user
const res = await fetch("/register", {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
username, email, mobile, password, cpassword
})
})
const data = await res.json()
if (data === 422 || !data) {
alert("not registered")
} else {
alert("Sucesssfuly")
}
}
return (
<div>
<div class=" container position-relative z-index-9">
<div class="row g-4 g-sm-5 justify-content-between">
<div class=" hero-rah mb-5 col-12 col-lg-6 d-md-flex align-items-center justify-content-center bg-opacity-10 vh-lg-100">
<div class="p-3 p-lg-5">
<div class="text-center">
<h2 class="fw-bold">Welcome to our largest community</h2>
<p class="mb-0 h6 fw-light">Let's learn something new today!</p>
</div>
<img src={zerotwo} class="mt-5" alt="" />
</div>
</div>
<div class="col-lg-6 position-relative">
<div class=" jk mt-5 bg-primary bg-opacity-10 rounded-3 p-4 p-sm-5">
<h2 class="mb-3">Register Here</h2>
<form method='POST' class="row g-4 g-sm-3 mt-2 mb-0">
<div class="col-12">
<label class="form-label">Name *</label>
<input type="text"
class="form-control"
aria-label="First name"
name='username'
value={user.username}
onChange={handleInput}
/>
{/* {errors.username && touched.username ? (<span class="badge badge-danger">{errors.username}</span>) : null} */}
</div>
<div class="col-12">
<label class="form-label">Email *</label>
<input type="email"
class="form-control"
name='email'
value={user.email}
onChange={handleInput}
/>
{/* {errors.email && touched.email ? (<span class="badge badge-danger">{errors.email}</span>) : null} */}
</div>
<div class="col-12">
<label class="form-label">Mobile number *</label>
<input type="text"
class="form-control"
aria-label="Mobile number"
name='mobile'
value={user.mobile}
onChange={handleInput}
/>
{/* {errors.mobile && touched.mobile ? (<span class="badge badge-danger">{errors.mobile}</span>) : null} */}
</div>
<div class="col-12">
<label class="form-label">Password *</label>
<input type="password"
class="form-control"
aria-label="password"
name='password'
value={user.password}
onChange={handleInput}
/>
{/* {errors.password && touched.password ? (<span class="badge badge-danger">{errors.password}</span>) : null} */}
</div>
<div class="col-12">
<label class="form-label">Confirm Password *</label>
<input type="password"
class="form-control"
aria-label="password"
name='cpassword'
value={user.cpassword}
onChange={handleInput}
/>
{/* {errors.cpassword && touched.cpassword ? (<span class="badge badge-danger">{errors.cpassword}</span>) : null} */}
</div>
<div class="col-12 d-grid">
<button onClick={PostData} type="submit" class="btn btn-lg btn-primary mb-0">Register</button>
</div>
</form>
</code></pre>
<p><strong>Auth.js</strong></p>
<pre><code>const express = require("express")
const router = express()
const bcrypt = require("bcryptjs")
const jwt = require("jsonwebtoken")
require("../conn")
const User = require("../models/SignupSchema")
router.get("/", (req, res) => {
res.send("hello i am home router js")
})
router.post("/register", (req, res) => {
const { username, email, mobile, password, cpassword } = req.body
if (!username || !email || !mobile || !password || !cpassword) {
return res.status(422).json({ error: "please fill all the data" })
}
User.findOne({ email: email }).then((userExit) => {
if (userExit) {
return res.status(422).json({ error: "User is already registered" })
}
const user = new User({ username, email, mobile, password, cpassword })
user.save().then(() => {
res.status(200).json({ message: "user is registered" })
}).catch(() => {
res.status(500).json({ error: "Error while registering the user" })
})
}).catch((err) => {
console.log(err);
})
})
router.post("/login", async (req, res) => {
let token
try {
const { email, password } = req.body
if (!email || !password) {
return res.status(400).json({ message: "fill the credentials" })
}
const UserLogin = await User.findOne({ email: email })
if (UserLogin) {
const passmatch = await bcrypt.compare(password, UserLogin.password)
token = await UserLogin.generateAuthToken()
console.log(token);
res.cookie("jwt",token,{
expires : new Date(Date.now()+25892000000),
httpOnly : true
})
if (!passmatch) {
res.status(400).json({ error: "Invalid credentials" })
}
else {
res.status(200).json({ message: "sign in successfully" })
}
} else {
res.status(400).json({ error: "Invalid credentials" })
}
} catch (err) {
console.log(err);
}
})
module. Exports = router
</code></pre>
<p><strong>App.js(backend)</strong></p>
<pre><code>const dotenv = require("dotenv")
const express = require("express")
const app = express()
dotenv.config({path:"./config.env"})
require("./conn")
app.use(express.json())
const PORT = process.env.PORT
app.use(require("./router/Auth"))
const middleware = (req,res,next)=>{
console.log("i am using middleware");
next();
}
app.get("/",(req,res)=>{
res.send("hello world from the server")
})
app.get("/about",middleware,(req,res)=>{
res.send("this is about page rahul")
})
app.listen(PORT,()=>{
console.log(`server is listening ${PORT}`);
})
</code></pre>
<p><strong>signup schema</strong></p>
<pre><code>const mongoose = require("mongoose")
const bcrypt = require("bcryptjs")
const jwt = require("jsonwebtoken")
const SignupSchema = new mongoose.Schema({
username: {
type: String,
required: true
},
email: {
type: String,
required: true
},
mobile: {
type: String,
required: true
},
password: {
type: String,
required: true
},
cpassword: {
type: String,
required: true
},
tokens:[
{
token:{
type:String,
required:true
}
}
]
})
SignupSchema.pre("save", async function (next) {
console.log("hi i am pre");
if (this.isModified("password")) {
console.log("hi i am pre password");
this.password = await bcrypt.hash(this.password, 12)
this.cpassword = await bcrypt.hash(this.cpassword, 12)
next()
}
})
SignupSchema.methods.generateAuthToken = async function () {
try {
let token = jwt.sign({ _id:this._id},process.env.SECRET_KEY)
this.tokens = this.tokens.concat({token:token})
await this.save()
return token
} catch (err) {
console.log(err);
}
}
const Signup = mongoose.model("SIGNUP", SignupSchema)
module. Exports = Signup
</code></pre>
<p>I had tried to insert my form data using fect api in reactjs abd i expecting to data to be inserted in my database</p>
|
[
{
"answer_id": 74644738,
"author": "SomeDude",
"author_id": 1410303,
"author_profile": "https://Stackoverflow.com/users/1410303",
"pm_score": 1,
"selected": false,
"text": "out = df.groupby(df.c1.str[-1]).sum().reset_index()\nout['c1'] = 'C' + out['c1']\n c1 c2\n0 Cx 3\n1 Cy 7\n"
},
{
"answer_id": 74644742,
"author": "Mustafa Aydın",
"author_id": 9332187,
"author_profile": "https://Stackoverflow.com/users/9332187",
"pm_score": 1,
"selected": false,
"text": ">>> (df.groupby(df.c1.str[-1])[\"c2\"]\n .sum().reset_index()\n .assign(c1=lambda fr: fr.c1.radd(\"C\")))\n\n c1 c2\n0 Cx 3\n1 Cy 7\n assign radd"
},
{
"answer_id": 74644747,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 3,
"selected": true,
"text": "df.groupby(df['c1'].str[-1]).sum()\n c2\nc1 \nx 3\ny 7\n df.groupby('C' + df['c1'].str[-1]).sum().reset_index()\n c1 c2\n0 Cx 3\n1 Cy 7\n"
},
{
"answer_id": 74644775,
"author": "abokey",
"author_id": 16120011,
"author_profile": "https://Stackoverflow.com/users/16120011",
"pm_score": 1,
"selected": false,
"text": "pandas.Series.replace GroupBy.sum out = (\n df\n .assign(c1= df[\"c1\"].str.replace(\"[A-Z]\", \"C\", regex=True))\n .groupby(\"c1\", as_index=False).sum(numeric_only=True)\n )\n \nprint(out)\n\n c1 c2\n0 Cx 3\n1 Cy 7\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74644664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20658000/"
] |
74,644,678
|
<p>There are tons of questions here on this topic and I've read through most of them but I cannot get my head around this problem. I am trying to add arrays containing URLs of files to the result of an SQL query. In NodeJS it works perfectly well but the response is sent too early, before any of the arrays of files have been added.</p>
<p>So far I've tried promises, async and synchronous fs.extra functions, npm async module, promisify. They were all very promising and likely to work but there is just something about this mysql query and first loop that I don't understand. This on especially where I tried both methods <a href="https://stackoverflow.com/a/70748789/12498040">https://stackoverflow.com/a/70748789/12498040</a> and which I kind of what I have at the moment. The one with promises would "fail" the <code>promises.all</code> instead of waiting for them all</p>
<p>Anyway, here is the code : how would you make sure that <code>res.json(result)</code> is executed last? Thank you in advance :)</p>
<pre><code>con.query(sql, function (err, result) {
if (err) throw err;
for (let i = 0; i < result.length; i++) {
//these test arrays are being sent to the client
result[i].test = ["aaa", "bbb", "ccc"]
fs.existsSync(fichiers_observations + result[i].id_observation, (exists) => {
if (exists) {
fs.readdirSync(fichiers_observations+result[i].id_observation, (err,files) => {
if (err) throw err;
result[i].files = [];
for (const file of files) {
//these URL are not being sent to the client
result[i].files.push('a URL/' + file)
}
});
}
})
}
res.json(result);
})
</code></pre>
|
[
{
"answer_id": 74644738,
"author": "SomeDude",
"author_id": 1410303,
"author_profile": "https://Stackoverflow.com/users/1410303",
"pm_score": 1,
"selected": false,
"text": "out = df.groupby(df.c1.str[-1]).sum().reset_index()\nout['c1'] = 'C' + out['c1']\n c1 c2\n0 Cx 3\n1 Cy 7\n"
},
{
"answer_id": 74644742,
"author": "Mustafa Aydın",
"author_id": 9332187,
"author_profile": "https://Stackoverflow.com/users/9332187",
"pm_score": 1,
"selected": false,
"text": ">>> (df.groupby(df.c1.str[-1])[\"c2\"]\n .sum().reset_index()\n .assign(c1=lambda fr: fr.c1.radd(\"C\")))\n\n c1 c2\n0 Cx 3\n1 Cy 7\n assign radd"
},
{
"answer_id": 74644747,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 3,
"selected": true,
"text": "df.groupby(df['c1'].str[-1]).sum()\n c2\nc1 \nx 3\ny 7\n df.groupby('C' + df['c1'].str[-1]).sum().reset_index()\n c1 c2\n0 Cx 3\n1 Cy 7\n"
},
{
"answer_id": 74644775,
"author": "abokey",
"author_id": 16120011,
"author_profile": "https://Stackoverflow.com/users/16120011",
"pm_score": 1,
"selected": false,
"text": "pandas.Series.replace GroupBy.sum out = (\n df\n .assign(c1= df[\"c1\"].str.replace(\"[A-Z]\", \"C\", regex=True))\n .groupby(\"c1\", as_index=False).sum(numeric_only=True)\n )\n \nprint(out)\n\n c1 c2\n0 Cx 3\n1 Cy 7\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74644678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12498040/"
] |
74,644,755
|
<p>First time encountering floating point arithmetic.</p>
<p>How can I add:</p>
<pre><code>0.4047617913405519 + 250459325658972.0
</code></pre>
<p>and choose my presicion?</p>
<p>I get</p>
<pre><code>250459325658972.4
</code></pre>
<p>But I want at least</p>
<pre><code>250459325658972.405
</code></pre>
<p>Why is python doing that. Any further resources?</p>
|
[
{
"answer_id": 74644891,
"author": "scr",
"author_id": 18781246,
"author_profile": "https://Stackoverflow.com/users/18781246",
"pm_score": 1,
"selected": false,
"text": ">>> from decimal import *\n>>> getcontext().prec = 6\n>>> Decimal(1) / Decimal(7)\nDecimal('0.142857')\n>>> getcontext().prec = 28\n>>> Decimal(1) / Decimal(7)\nDecimal('0.1428571428571428571428571429')\n Decimal"
},
{
"answer_id": 74645151,
"author": "rishabh11336",
"author_id": 15002598,
"author_profile": "https://Stackoverflow.com/users/15002598",
"pm_score": -1,
"selected": false,
"text": "print(\"{0:.4f}\".format(250459325658972.0 +0.4047617913405519))\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74644755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13817472/"
] |
74,644,762
|
<p>I'm trying to set methods of a class programmatically by calling <code>setattr</code> in a loop, but the reference I pass to the function that is called by this method defaults back to its last value, instead of what was passed at the time of the <code>setattr</code>call. Curiously, I'm also setting the <code>__doc__</code> attribute and this assignment actually works as expected:</p>
<pre><code>class Foo2:
def do_this(self, pass_this: str):
print(pass_this)
class Foo:
def __init__(self):
self.reference = "ti-hihi"
self.foo2 = Foo2()
for (method_name, pass_this) in [("bar", "passed-for-bar"), ("bar2", "passed-for-bar2")]:
my_doc = f"""my_custom_docstring: {pass_this}"""
def some_func():
self.foo2.do_this(pass_this=pass_this)
some_func.__doc__ = my_doc
setattr(self, method_name, some_func)
if __name__ == '__main__':
f = Foo()
f.bar() # prints "pass-for-bar2" instead of "pass-for-bar"
f.bar.__doc__ # prints "pass-for-bar" as expected
</code></pre>
<p>I already tried a few things but couldn't figure it out.</p>
<p>Things I tried:</p>
<p>lambda -- my best bet, tbh</p>
<pre><code>def some_func(reference):
self.foo2.do_this(pass_this=reference)
some_func.__doc__ = my_doc
setattr(self, method_name, lambda: some_func(pass_this))
</code></pre>
<p>deepcopy</p>
<pre><code>import copy
def some_func():
self.foo2.do_this(pass_this=copy.deepcopy(pass_this))
some_func.__doc__ = my_doc
setattr(self, method_name, some_func)
</code></pre>
<p>another deepcopy variant which feels dangerous if I think about the place I want to put this:</p>
<pre><code>import copy
def some_func():
self.foo2.do_this(pass_this=pass_this)
some_func.__doc__ = my_doc
setattr(self, method_name, copy.deepcopy(some_func))
</code></pre>
<p>... and a few combinations of those but I'm missing some crucial piece.</p>
|
[
{
"answer_id": 74644891,
"author": "scr",
"author_id": 18781246,
"author_profile": "https://Stackoverflow.com/users/18781246",
"pm_score": 1,
"selected": false,
"text": ">>> from decimal import *\n>>> getcontext().prec = 6\n>>> Decimal(1) / Decimal(7)\nDecimal('0.142857')\n>>> getcontext().prec = 28\n>>> Decimal(1) / Decimal(7)\nDecimal('0.1428571428571428571428571429')\n Decimal"
},
{
"answer_id": 74645151,
"author": "rishabh11336",
"author_id": 15002598,
"author_profile": "https://Stackoverflow.com/users/15002598",
"pm_score": -1,
"selected": false,
"text": "print(\"{0:.4f}\".format(250459325658972.0 +0.4047617913405519))\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74644762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9902863/"
] |
74,644,781
|
<p>In my main thread I create two additional threads that I want to use a value from. Basically what I want to do is this:</p>
<pre><code>Threads thread1 = new Threads();
Threads thread2 = new Threads();
Thread.currentThread.wait();
If (thread1 = complete){
var = thread1.getter
//delete thread2
}
If (thread2 == complete){
var = thread2.getter
//delete thread1
}
</code></pre>
<p>With thread1 and thread2 having a notify() at the end that wakes up the main thread and the thread that doesn't finish is deleted. But I realise that I don't properly understand wait() and multithreading so the way this is setup may not be correct. I know that Thread.currentThread.wait() is definitely not correct.</p>
<p>I think I may have to synchronize the methods but I have not been able to find any examples that show how to do this in this situation.</p>
<p>Edit: To give more info Thread1 takes input from a scanner and Thread2 takes input from a keylistener and I want to use the first input from 1 of them</p>
|
[
{
"answer_id": 74644891,
"author": "scr",
"author_id": 18781246,
"author_profile": "https://Stackoverflow.com/users/18781246",
"pm_score": 1,
"selected": false,
"text": ">>> from decimal import *\n>>> getcontext().prec = 6\n>>> Decimal(1) / Decimal(7)\nDecimal('0.142857')\n>>> getcontext().prec = 28\n>>> Decimal(1) / Decimal(7)\nDecimal('0.1428571428571428571428571429')\n Decimal"
},
{
"answer_id": 74645151,
"author": "rishabh11336",
"author_id": 15002598,
"author_profile": "https://Stackoverflow.com/users/15002598",
"pm_score": -1,
"selected": false,
"text": "print(\"{0:.4f}\".format(250459325658972.0 +0.4047617913405519))\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74644781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20657801/"
] |
74,644,786
|
<p>Is there any way to store terraform output values to s3 bucket file..</p>
<pre><code>output "certificate_body" {
description = "The acm certificate body"
value = venafi_certificate.this.certificate
}
</code></pre>
<p>how can we dump this output to a file which is in s3 bucket ?</p>
|
[
{
"answer_id": 74644891,
"author": "scr",
"author_id": 18781246,
"author_profile": "https://Stackoverflow.com/users/18781246",
"pm_score": 1,
"selected": false,
"text": ">>> from decimal import *\n>>> getcontext().prec = 6\n>>> Decimal(1) / Decimal(7)\nDecimal('0.142857')\n>>> getcontext().prec = 28\n>>> Decimal(1) / Decimal(7)\nDecimal('0.1428571428571428571428571429')\n Decimal"
},
{
"answer_id": 74645151,
"author": "rishabh11336",
"author_id": 15002598,
"author_profile": "https://Stackoverflow.com/users/15002598",
"pm_score": -1,
"selected": false,
"text": "print(\"{0:.4f}\".format(250459325658972.0 +0.4047617913405519))\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74644786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16250966/"
] |
74,644,798
|
<p>Hi my code works fine but is there any way to print how many times numbers 1-6 were said into a percentage</p>
<p>I haven't tried anything yet.</p>
<pre><code>import pandas as pd
import random
data = [random.randint(0,6) for _ in range(10)]
df = pd.DataFrame(data)
print(df)
df.to_excel(r'H:\Grade10\Cs\Mir Hussain 12.00.00 3.xlsx', index=False)
</code></pre>
|
[
{
"answer_id": 74644891,
"author": "scr",
"author_id": 18781246,
"author_profile": "https://Stackoverflow.com/users/18781246",
"pm_score": 1,
"selected": false,
"text": ">>> from decimal import *\n>>> getcontext().prec = 6\n>>> Decimal(1) / Decimal(7)\nDecimal('0.142857')\n>>> getcontext().prec = 28\n>>> Decimal(1) / Decimal(7)\nDecimal('0.1428571428571428571428571429')\n Decimal"
},
{
"answer_id": 74645151,
"author": "rishabh11336",
"author_id": 15002598,
"author_profile": "https://Stackoverflow.com/users/15002598",
"pm_score": -1,
"selected": false,
"text": "print(\"{0:.4f}\".format(250459325658972.0 +0.4047617913405519))\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74644798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20658118/"
] |
74,644,851
|
<pre><code>#include<stdio.h>
int main()
{
int value = 0 ;
if(value)
printf("0");
printf("1");
printf("2");
return 0;
}
</code></pre>
<p>The output of the above code is <code>12</code>
but when I tweak the code by adding curly brackets the output differs</p>
<pre><code>#include<stdio.h>
int main()
{
int value = 0 ;
if(value)
{
printf("0\n");
printf("1\n");
printf("2\n");
}
return 0;
}
</code></pre>
<p>After adding curly brackets I didn't get an output.</p>
<p>When I change the declared variable to <code>1</code> I expected the program to only output the line printf("2") because when the <code>value = 0 it gave 12</code> as the output excluding the first printf statment, So I expected changing the assigned variable <code>value = 1 </code>as the output would exclude both the first and second printf statments, but it didn't. This made me more confused.</p>
<p>Summary:
If there is no curly bracket{} in the code it gives a different output for the same code with curly brackets
When I declare value=1 or any other number program prints <code>012</code>(in both codes).
I would like to know why is this happening.</p>
<p>Thank you.</p>
|
[
{
"answer_id": 74644916,
"author": "SilicDev",
"author_id": 20614914,
"author_profile": "https://Stackoverflow.com/users/20614914",
"pm_score": 1,
"selected": false,
"text": "true 0 false if"
},
{
"answer_id": 74644989,
"author": "Steve Summit",
"author_id": 3923896,
"author_profile": "https://Stackoverflow.com/users/3923896",
"pm_score": 3,
"selected": true,
"text": "if ( condition )\n stuff\n condition stuff condition stuff condition 0 value i > 1 && i < 10 stuff { } if( condition ) { } if( condition ) if(value)\nprintf(\"0\");\nprintf(\"1\");\nprintf(\"2\");\n if value 0 value 0 2 3 if(value)\n printf(\"0\");\nprintf(\"1\");\nprintf(\"2\");\n if(value)\n {\n printf(\"0\\n\");\n printf(\"1\\n\");\n printf(\"2\\n\");\n }\n if value value"
},
{
"answer_id": 74658582,
"author": "John Bode",
"author_id": 134554,
"author_profile": "https://Stackoverflow.com/users/134554",
"pm_score": 0,
"selected": false,
"text": "if(value)\n\nprintf(\"0\");\nprintf(\"1\");\nprintf(\"2\");\n if(value)\n{\n printf(\"0\");\n}\n\nprintf(\"1\");\nprintf(\"2\");\n printf(\"0\"); value printf(\"1\"); printf(\"2\"); if(value)\n{\nprintf(\"0\\n\");\nprintf(\"1\\n\");\nprintf(\"2\\n\");\n}\n printf value"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74644851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20657846/"
] |
74,644,856
|
<p>I need to organize the arrays that are inside an array so that the first numbers in the array are even</p>
<p>For now I can only scroll through the arrays, I couldn't implement the logic <code> </code></p>
<pre><code>let matriz = [
[5, 1, 2, 4, 7, 9],
[2, 4, 3, 1, 7, 9],
[1, 2, 3, 4, 5, 6],
]
for (let i = 0; i < matriz.length; i++) {
let innerArrLength = matriz[i].length
for (let j = 0; j < innerArrLength; j++) {
if (matriz[i][j] % 2 === 0) {
// code
} else {
// code
}
}
}
</code></pre>
<p>`</p>
|
[
{
"answer_id": 74645025,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 2,
"selected": false,
"text": "true const\n move = (array, fn) => array.sort((a, b) => fn(b) - fn(a)),\n array = [5, 1, 2, 4, 7, 9];\n\nmove(array, v => v % 2 === 0);\n\nconsole.log(...array);"
},
{
"answer_id": 74645077,
"author": "malarres",
"author_id": 2729605,
"author_profile": "https://Stackoverflow.com/users/2729605",
"pm_score": 0,
"selected": false,
"text": "filter let matriz = [\n [5, 1, 2, 4, 7, 9],\n [2, 4, 3, 1, 7, 9],\n [1, 2, 3, 4, 5, 6],\n]\n\nfor (let i = 0; i < matriz.length; i++) {\n matriz[i] = matriz[i].filter(x => x%2 == 0)\n .concat(\n matriz[i].filter(x => x%2 != 0))\n}\n\nconsole.log(matriz)"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74644856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17736532/"
] |
74,644,870
|
<p>I have to retype most of this by hand since the system I'm testing on can't currently connect to the internet, forgive any obvious typos please.</p>
<p>We are programmatically scheduling deployments into a large sandbox with 19 nodes, 16 of which are workers. Usually we scan through available nodes to find the ones with the most available memory/cpu and select it for the new deployment, though given the affinity below I'm wondering if this particular deployment is being deployed through some other part of our code somehow since it has no nodeAffinity at all.</p>
<p>Either way usually deployment works, but occasionally a pod will fail to schedule</p>
<pre><code>0/19 nodes are available: 16 node(s) didn't match pod affinity rules, 16 node(s) didn't match pod affinity/anti-affinity, 3 node(s) had taint (node-role.kubernetes.io/controlplane: true), that the pod didn't tolerate
</code></pre>
<p>I've used kubectl to look up the pods affinities after they are created. We have multiple nearly identical pods, both the ones that can be scheduled and the one that can't appear to have identical affinities:</p>
<pre><code>"podAffinity": {
"requiredDuringSchedulingIgnoreDuringExecution": [
{
"labelSelector": {
"matchExpressions: " [
{
"key": "app.kubernetes.io/instance",
"operator": "In",
"values": [
<instance name>
]
},
{
"key": "host",
"operator": "In",
"values": [
"yes"
]
}
]
},
"topologyKey": "kubernetes.io/hostname"
}
]
}
</code></pre>
<p>I get this by looking at spec.affinity:</p>
<pre><code>kubectl get pods <pod_name> -o json | jq '.spec.affinity'
</code></pre>
<p>I thought I understood affinity, but clearly not because I can't find any 'host' label on the pod or the node. I also don't understand why the pod affinity would prevent the pod from being scheduled on a node.</p>
<p>More importantly I don't understand what a host of "yes" means. It's not literally looking for a label with a value of "yes" is it?</p>
<p>Since I don't understand how the affinity works when assigning a functional pod I really don't understand why the same affinity occasionally fails. I'd appreciate any help in understanding what the affinity is actually doing or why it may occasionally fail.</p>
|
[
{
"answer_id": 74645161,
"author": "user2311578",
"author_id": 2311578,
"author_profile": "https://Stackoverflow.com/users/2311578",
"pm_score": 2,
"selected": true,
"text": "requiredDuringSchedulingIgnoreDuringExecution \"topologyKey\": \"kubernetes.io/hostname\" apiVersion: v1\nkind: Pod\nmetadata:\n name: foo\n labels:\n \"app.kubernetes.io/instance\": <instance-name>\n host: yes\n"
},
{
"answer_id": 74646968,
"author": "Justin Pierce",
"author_id": 6431503,
"author_profile": "https://Stackoverflow.com/users/6431503",
"pm_score": 0,
"selected": false,
"text": "affinity:\n nodeAffinity:\n requiredDuringSchedulingIgnoredDuringExecution:\n nodeSelectorTerms:\n - matchExpressions:\n - key: kubernetes.io/hostname\n operator: In\n values:\n - \"<INSTANCE HOSTNAME>\"\n NodeResourcesFit LeastAllocated"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74644870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/897272/"
] |
74,644,919
|
<p>I’m working on an Azure Function App that will grab a .pgp file off of Blob Storage, decrypt it, and then upload that decrypted file back to Blob Storage.</p>
<p>I’ve done quite a bit of research and everything usually assumes you are downloading a file to a local drive, decrypt, then upload. However, in my case I’m trying to do everything in Azure.</p>
<p>This is the code I’ve come up with so far. This will connect to and download the file to a stream successfully but I’m not figuring out how to wire it up with the output stream.
The line for the <code>UploadAsync()</code> is the one I'm having issues with and it needs a value passed into the method but I’m assuming the targetBlobClient already has reference to the Blob Container and file name.</p>
<p>I’m lost here and can’t seem to find any kind of examples to help me figure out what to do. I’m sure this code could be reduced and I will look into that once I can get it to work.</p>
<pre><code>var outputStream = await targetBlobClient.UploadAsync();
</code></pre>
<p>Here is the code I've come up with so far:</p>
<pre><code>try
{
var privateKeyValue = GetKeyVaultSecretValue(m.KeyVaultURL, m.KeyVaultPrivateSecretName);
var privateKeyPassword = GetKeyVaultSecretValue(m.KeyVaultURL, m.KeyVaultPrivateSecretPassword);
var storageConnString = m.InputStorageConnection;
var containerName = m.InputStorageContainer;
var sourceFile = m.InputFileName;
var targetFile = m.OutputFileName;
var sourceFolder = Path.Combine(m.InputStorageContainer, m.InputStorageFolder);
var targetFolder = Path.Combine(m.OutputStorageContainer, m.OutputFolder);
Console.WriteLine(@"Source full path: " + sourceFolder + "\\" + sourceFile);
BlobServiceClient blobServiceClient = new BlobServiceClient(storageConnString);
BlobContainerClient sourceContainerClient = blobServiceClient.GetBlobContainerClient(sourceFolder);
BlobClient sourceBlobClient = sourceContainerClient.GetBlobClient(sourceFile);
BlobContainerClient targetContainerClient = blobServiceClient.GetBlobContainerClient(targetFolder);
BlobClient targetBlobClient = sourceContainerClient.GetBlobClient(targetFile);
if (await sourceBlobClient.ExistsAsync())
{
var inputStream = await sourceBlobClient.DownloadAsync();
var outputStream = await targetBlobClient.UploadAsync();
EncryptionKeys encryptionKeys = new EncryptionKeys(privateKeyValue, privateKeyPassword);
PGP pgp = new PGP(encryptionKeys);
await pgp.DecryptStreamAsync(inputStream, outputStream);
}
else
{
Console.WriteLine(@"Error finding file. " + sourceFolder + "\\" + sourceFile);
_log.LogError("Error find file {0}\\{1}.", sourceFolder, sourceFile);
}
}
catch (Exception ex)
{
_log.LogError("Error decrypting file. EventType: {0} | File: {1} | {2} | {3} | {4}", m.EventName, m.InputFileName, ex.Message, ex.StackTrace, ex.InnerException);
Console.WriteLine("Error: " + ex.Message);
}
</code></pre>
|
[
{
"answer_id": 74646912,
"author": "Joel Cochran",
"author_id": 75838,
"author_profile": "https://Stackoverflow.com/users/75838",
"pm_score": 1,
"selected": false,
"text": "// TMP file names\nvar temp_sourceFileName = IOHelper.BuildTempFileName(BlobHelper.StripPath(sourceBlobName));\nvar temp_targetFileName = IOHelper.BuildTempFileName(BlobHelper.StripPath(targetBlobName));\nvar temp_keyFileName = IOHelper.BuildTempFileName(BlobHelper.StripPath(keyBlobName));\n\n\n// download Blob to TMP\nusing (var sourceStream = new FileStream(temp_sourceFileName, FileMode.Create))\n{\n var sourceBlobClient = new BlobClient(blobAccountConnStr, sourceContainerName, sourceBlobName);\n await sourceBlobClient.DownloadToAsync(sourceStream);\n}\n\n// download key to TMP\nusing (var keyStream = new FileStream(temp_keyFileName, FileMode.Create))\n{\n var keyBlobClient = new BlobClient(blobAccountConnStr, sourceContainerName, keyBlobName);\n await keyBlobClient.DownloadToAsync(keyStream);\n}\n\n\n// Encrypt stream\nusing (var pgp = new PGP())\n{\n using (FileStream inputFileStream = new FileStream(temp_sourceFileName, FileMode.Open))\n {\n using (Stream outputFileStream = File.Create(temp_targetFileName))\n {\n using (Stream publicKeyStream = new FileStream(temp_keyFileName, FileMode.Open))\n {\n pgp.EncryptStream(inputFileStream, outputFileStream, publicKeyStream, true, true);\n }\n }\n }\n}\n\n// write to target blob\n// write to target blob\nusing (var encryptStream = new FileStream(temp_targetFileName, FileMode.Open))\n{\n var targetBlobClient = new BlobClient(blobAccountConnStr, targetContainerName, targetBlobName);\n await targetBlobClient.UploadAsync(encryptStream, true);\n\n return new OkObjectResult(targetBlobClient);\n}\n"
},
{
"answer_id": 74661677,
"author": "Caverman",
"author_id": 5216651,
"author_profile": "https://Stackoverflow.com/users/5216651",
"pm_score": 0,
"selected": false,
"text": "public async Task DecryptFileAsync(PGPmessage m)\n{\n _log.LogInformation(\"Start decryption process for Event: {0}\", m.EventName);\n\n\n //========= Get PGP Keys ================================================================\n var privateKeyValue = GetKeyVaultSecretValue(m.KeyVaultURL, m.KeyVaultPrivateSecretName);\n var privateKeyPassword = GetKeyVaultSecretValue(m.KeyVaultURL, m.KeyVaultPrivateSecretPassword);\n\n\n try\n {\n var storageConnString = m.InputStorageConnection;\n\n var sourceFolder = m.InputStorageContainer;\n var sourceFile = m.InputFileName;\n \n var targetFolder = m.OutputStorageContainer;\n var targetFile = m.OutputFileName;\n\n _log.LogInformation(@\"Looking for file {0}\\{1}.\", sourceFolder, sourceFile);\n Console.WriteLine(@\"Source full path: \" + sourceFolder + \"\\\\\" + sourceFile);\n\n\n // Create the connections to Blob Storage for both Source and Target files.\n BlobServiceClient blobServiceClient = new BlobServiceClient(storageConnString);\n\n BlobContainerClient sourceContainerClient = blobServiceClient.GetBlobContainerClient(sourceFolder); \n BlobClient sourceBlobClient = sourceContainerClient.GetBlobClient(sourceFile); \n\n BlobContainerClient targetContainerClient = blobServiceClient.GetBlobContainerClient(targetFolder);\n BlobClient targetBlobClient = sourceContainerClient.GetBlobClient(targetFile);\n\n if (await sourceBlobClient.ExistsAsync())\n {\n // Use a memory stream because a Stream type is not seekable, a memory stream is. \n var inputStream = new MemoryStream();\n var outputStream = new MemoryStream();\n\n // Download from blob storage. Copy to memory stream so that it can be seakable. \n // After copying to memory stream, reset the position to 0 so that it will be able to read from the begining.\n var blobDownloadStream = await sourceBlobClient.DownloadAsync();\n blobDownloadStream.Value.Content.CopyTo(inputStream);\n inputStream.Position = 0;\n\n // Create PGP Core object passing in the PGP Keys. \n EncryptionKeys encryptionKeys = new EncryptionKeys(privateKeyValue, privateKeyPassword);\n PGP pgp = new PGP(encryptionKeys);\n\n await pgp.DecryptStreamAsync(inputStream, outputStream);\n\n _log.LogInformation(@\"Uploading file to storage: {0}\\{1}\", targetFolder, targetFile);\n\n // Reset to the beginning of the stream since it will be at the end due to writing the decrypted value to the stream.\n outputStream.Position = 0; \n await targetBlobClient.UploadAsync(outputStream, true); //Set to overwrite=true\n\n _log.LogInformation(@\"Uploading to file to storage Complete. {0}\\{1}\", targetFolder, targetFile);\n Console.WriteLine(@\"Uploading to file to storage Complete. {0}\\{1}\", targetFolder, targetFile);\n }\n else\n {\n Console.WriteLine(@\"Error finding file: \" + sourceFolder + \"\\\\\" + sourceFile);\n _log.LogError(\"Error finding file: {0}\\\\{1}.\", sourceFolder, sourceFile);\n }\n }\n catch (Exception ex)\n {\n _log.LogError(\"Error decrypting file. EventType: {0} | File: {1} | {2} | {3} | {4}\", m.EventName, m.InputFileName, ex.Message, ex.StackTrace, ex.InnerException);\n\n Console.WriteLine(\"Error: \" + ex.Message);\n }\n}\n\nprivate string GetKeyVaultSecretValue(string keyVaultURL, string secretName)\n{\n var kvSecretValue = string.Empty;\n\n try\n {\n var secretsClient = new SecretClient(new Uri(keyVaultURL), new DefaultAzureCredential());\n kvSecretValue = secretsClient.GetSecret(secretName).Value.Value;\n\n //https://scottgeek.technology/the-azure-vault-pgp-and-other-matters-part-2/\n }\n catch (Exception ex)\n {\n _log.LogError(\"Error getting Key Vault secret. SecretName: {0} | {1} | {2} | {3}\", secretName, ex.Message, ex.StackTrace, ex.InnerException);\n }\n\n return kvSecretValue;\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74644919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5216651/"
] |
74,644,938
|
<pre><code>const productIds = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', ...]
const generateBearerToken = async () => {
await //api calling
} // will return bearerToken
const getSubmissions = async () => {
await // api calling
}
let sellerId = null
const getPublisherId = async (productId) => {
//generating bearer token using generateBearerToken()
await GenerateBearerToken()
//calling API here and setting the value of sellerId
const response = await axios.get(url, { header })
//From this response, I am setting the value of sellerId, then calling getSubmission()
sellerId = response.data.sellerId
await getSubmission()
}
productsIds.map((productId) => {
await getPublisherId(productId)
})
</code></pre>
<p>The <code>sellerId</code> which I am getting from <code>getPublisherId</code>, I am using that value in the header for calling <code>getSubmissions</code>. This value (<code>sellerId</code>) is different for different product Ids. But when I am calling this above map function, the <code>sellerId</code> of one is getting passed in other calling <code>getSubmissions</code>, that should be not the case. The <code>sellerId</code> should be passed to that particular <code>getSubmissions</code> only. How to avoid this collision?</p>
|
[
{
"answer_id": 74646912,
"author": "Joel Cochran",
"author_id": 75838,
"author_profile": "https://Stackoverflow.com/users/75838",
"pm_score": 1,
"selected": false,
"text": "// TMP file names\nvar temp_sourceFileName = IOHelper.BuildTempFileName(BlobHelper.StripPath(sourceBlobName));\nvar temp_targetFileName = IOHelper.BuildTempFileName(BlobHelper.StripPath(targetBlobName));\nvar temp_keyFileName = IOHelper.BuildTempFileName(BlobHelper.StripPath(keyBlobName));\n\n\n// download Blob to TMP\nusing (var sourceStream = new FileStream(temp_sourceFileName, FileMode.Create))\n{\n var sourceBlobClient = new BlobClient(blobAccountConnStr, sourceContainerName, sourceBlobName);\n await sourceBlobClient.DownloadToAsync(sourceStream);\n}\n\n// download key to TMP\nusing (var keyStream = new FileStream(temp_keyFileName, FileMode.Create))\n{\n var keyBlobClient = new BlobClient(blobAccountConnStr, sourceContainerName, keyBlobName);\n await keyBlobClient.DownloadToAsync(keyStream);\n}\n\n\n// Encrypt stream\nusing (var pgp = new PGP())\n{\n using (FileStream inputFileStream = new FileStream(temp_sourceFileName, FileMode.Open))\n {\n using (Stream outputFileStream = File.Create(temp_targetFileName))\n {\n using (Stream publicKeyStream = new FileStream(temp_keyFileName, FileMode.Open))\n {\n pgp.EncryptStream(inputFileStream, outputFileStream, publicKeyStream, true, true);\n }\n }\n }\n}\n\n// write to target blob\n// write to target blob\nusing (var encryptStream = new FileStream(temp_targetFileName, FileMode.Open))\n{\n var targetBlobClient = new BlobClient(blobAccountConnStr, targetContainerName, targetBlobName);\n await targetBlobClient.UploadAsync(encryptStream, true);\n\n return new OkObjectResult(targetBlobClient);\n}\n"
},
{
"answer_id": 74661677,
"author": "Caverman",
"author_id": 5216651,
"author_profile": "https://Stackoverflow.com/users/5216651",
"pm_score": 0,
"selected": false,
"text": "public async Task DecryptFileAsync(PGPmessage m)\n{\n _log.LogInformation(\"Start decryption process for Event: {0}\", m.EventName);\n\n\n //========= Get PGP Keys ================================================================\n var privateKeyValue = GetKeyVaultSecretValue(m.KeyVaultURL, m.KeyVaultPrivateSecretName);\n var privateKeyPassword = GetKeyVaultSecretValue(m.KeyVaultURL, m.KeyVaultPrivateSecretPassword);\n\n\n try\n {\n var storageConnString = m.InputStorageConnection;\n\n var sourceFolder = m.InputStorageContainer;\n var sourceFile = m.InputFileName;\n \n var targetFolder = m.OutputStorageContainer;\n var targetFile = m.OutputFileName;\n\n _log.LogInformation(@\"Looking for file {0}\\{1}.\", sourceFolder, sourceFile);\n Console.WriteLine(@\"Source full path: \" + sourceFolder + \"\\\\\" + sourceFile);\n\n\n // Create the connections to Blob Storage for both Source and Target files.\n BlobServiceClient blobServiceClient = new BlobServiceClient(storageConnString);\n\n BlobContainerClient sourceContainerClient = blobServiceClient.GetBlobContainerClient(sourceFolder); \n BlobClient sourceBlobClient = sourceContainerClient.GetBlobClient(sourceFile); \n\n BlobContainerClient targetContainerClient = blobServiceClient.GetBlobContainerClient(targetFolder);\n BlobClient targetBlobClient = sourceContainerClient.GetBlobClient(targetFile);\n\n if (await sourceBlobClient.ExistsAsync())\n {\n // Use a memory stream because a Stream type is not seekable, a memory stream is. \n var inputStream = new MemoryStream();\n var outputStream = new MemoryStream();\n\n // Download from blob storage. Copy to memory stream so that it can be seakable. \n // After copying to memory stream, reset the position to 0 so that it will be able to read from the begining.\n var blobDownloadStream = await sourceBlobClient.DownloadAsync();\n blobDownloadStream.Value.Content.CopyTo(inputStream);\n inputStream.Position = 0;\n\n // Create PGP Core object passing in the PGP Keys. \n EncryptionKeys encryptionKeys = new EncryptionKeys(privateKeyValue, privateKeyPassword);\n PGP pgp = new PGP(encryptionKeys);\n\n await pgp.DecryptStreamAsync(inputStream, outputStream);\n\n _log.LogInformation(@\"Uploading file to storage: {0}\\{1}\", targetFolder, targetFile);\n\n // Reset to the beginning of the stream since it will be at the end due to writing the decrypted value to the stream.\n outputStream.Position = 0; \n await targetBlobClient.UploadAsync(outputStream, true); //Set to overwrite=true\n\n _log.LogInformation(@\"Uploading to file to storage Complete. {0}\\{1}\", targetFolder, targetFile);\n Console.WriteLine(@\"Uploading to file to storage Complete. {0}\\{1}\", targetFolder, targetFile);\n }\n else\n {\n Console.WriteLine(@\"Error finding file: \" + sourceFolder + \"\\\\\" + sourceFile);\n _log.LogError(\"Error finding file: {0}\\\\{1}.\", sourceFolder, sourceFile);\n }\n }\n catch (Exception ex)\n {\n _log.LogError(\"Error decrypting file. EventType: {0} | File: {1} | {2} | {3} | {4}\", m.EventName, m.InputFileName, ex.Message, ex.StackTrace, ex.InnerException);\n\n Console.WriteLine(\"Error: \" + ex.Message);\n }\n}\n\nprivate string GetKeyVaultSecretValue(string keyVaultURL, string secretName)\n{\n var kvSecretValue = string.Empty;\n\n try\n {\n var secretsClient = new SecretClient(new Uri(keyVaultURL), new DefaultAzureCredential());\n kvSecretValue = secretsClient.GetSecret(secretName).Value.Value;\n\n //https://scottgeek.technology/the-azure-vault-pgp-and-other-matters-part-2/\n }\n catch (Exception ex)\n {\n _log.LogError(\"Error getting Key Vault secret. SecretName: {0} | {1} | {2} | {3}\", secretName, ex.Message, ex.StackTrace, ex.InnerException);\n }\n\n return kvSecretValue;\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74644938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15384724/"
] |
74,644,960
|
<p>I want to ensure the angle <code>h_ur</code> is between 0 to 360 degrees.</p>
<pre><code> h_ur <- atan2(b, a)*(180.0/pi)
</code></pre>
<p>but for the sake of the question, I have simplified <code>h_ur</code> as following:</p>
<pre><code>h_ur <- -5
if (h_ur > 360){
h <- h_ur - 360
} else if (h_ur < 0){
h <- 360 + h_ur
} else {
h <- h_ur
}
print(h)
</code></pre>
<p>However, this code would only work if the <code>h_ur</code> is between 720 and 360, and 0 and -360.</p>
<ul>
<li>How can I alter the code to ensure it would work even if <code>h_ur</code> is outside this range?</li>
<li>Is there a more elegant way to do this?</li>
</ul>
|
[
{
"answer_id": 74645073,
"author": "DashdotdotDashdotdot",
"author_id": 20548300,
"author_profile": "https://Stackoverflow.com/users/20548300",
"pm_score": 3,
"selected": true,
"text": "h_ur <- c(-180,-5,0,90,359.999, 360,720,865)\nh <- h_ur %% 360\nprint(h)\n > print(h)\n[1] 180.000 355.000 0.000 90.000 359.999 0.000 0.000 145.000\n"
},
{
"answer_id": 74645121,
"author": "duffymo",
"author_id": 37213,
"author_profile": "https://Stackoverflow.com/users/37213",
"pm_score": 0,
"selected": false,
"text": "atan2"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74644960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20427544/"
] |
74,644,966
|
<p>HP are supposed to reset to 0 when its 0 or under
But i guess my condition isnt good because it can go under 0.</p>
<p>And i dont understand why when i attack the opponent, it check the wrong opponent.
<a href="https://i.stack.imgur.com/gzWf0.png" rel="nofollow noreferrer">pic of error</a>
Here is the translate of the screenshot :</p>
<p>in the console it say :
Luffy is alive.</p>
<p>in the html it say :
Luffy attacked Naruto and remove him 8HP <- so this code is fine</p>
<p>Luffy HP : 100 <- this is fine because he didnt get attack
Naruto HP : -10 <- this is NOT fine because my instance method checkHealth is suppose to see that he reach 0hp and under.</p>
<p>So checkHealth check the wrong character, it check Luffy the attackers but i want it to check Naruto HP to see if HP are <= 0.</p>
<p>I tried this code and it works but it not very good to do like this bc its not very optimized :</p>
<pre><code> checkHealth (narutoCharacter){
if (narutoCharacter.health <=0){
narutoCharacter.health = 0;
popUp.style.display = 'inline';
popUp.innerText = narutoCharacter.name +' est mort.';
} else {
console.log (narutoCharacter.name + ' est en vie');
}
}
checkHealth (luffyCharacter){
if (luffyCharacter.health <=0){
luffyCharacter.health = 0;
popUp.style.display = 'inline';
popUp.innerText = luffyCharacter.name +' est mort.'
} else {
console.log (luffyCharacter.name + ' est en vie');
}
}
</code></pre>
<p>Here is my if statement in my instance method :</p>
<pre><code> checkHealth (){
if (this.health <=0){
this.health = 0;
popUp.style.display = 'inline';
popUp.innerText = this.name +' est mort.'
} else {
console.log (this.name + ' est en vie');
}
}
</code></pre>
<p>Here is the complete code of my javascript file :</p>
<pre><code>class Character {
constructor (name,type,health,attack,level){
this.name = name;
this.type = type;
this.health = health;
this.attack = attack;
this.level = level;
}
levelUp (){
this.level++;
popUp.style.display = 'inline';
popUp.innerText = this.name +' passe au niveau '+ this.level;
}
// checkHealth (){
// if (this.health <=0){
// this.health = 0;
// popUp.style.display = 'inline';
// popUp.innerText = this.name +' est mort.'
// } else {
// console.log (this.name + ' est en vie');
// }
// }
checkHealth (narutoCharacter){
if (narutoCharacter.health <=0){
narutoCharacter.health = 0;
popUp.style.display = 'inline';
popUp.innerText = narutoCharacter.name +' est mort.';
} else {
console.log (narutoCharacter.name + ' est en vie');
}
}
checkHealth (luffyCharacter){
if (luffyCharacter.health <=0){
luffyCharacter.health = 0;
popUp.style.display = 'inline';
popUp.innerText = luffyCharacter.name +' est mort.'
} else {
console.log (luffyCharacter.name + ' est en vie');
}
}
get informations (){
infoPopUp.innerText = this.name + ' ' + this.type + ' a ' + this.health + ' hp et est au niveau '+ this.level;
tempMessage.style.display = 'inline';
}
}
class Ninja extends Character {
constructor (name, type, health, attack, level){
super (name, type, health, attack, level)
}
attackEnemy (luffyCharacter){
luffyCharacter.health -= narutoCharacter.attack;
this.levelUp ();
popUp.style.display = 'inline';
popUp.innerText = narutoCharacter.name + ' attaque ' + luffyCharacter.name + ' et lui enlève ' + narutoCharacter.attack + ' PV';
this.checkHealth (luffyCharacter);
}
specialAttack (luffyCharacter){
(luffyCharacter.health -= narutoCharacter.attack * 3);
this.levelUp ();
popUp.style.display = 'inline';
popUp.innerText = narutoCharacter.name + ' utilise son Rasengan sur ' + luffyCharacter.name + ' et lui enlève ' + narutoCharacter.attack*3 + ' PV';
this.checkHealth (luffyCharacter);
}
heal (){
narutoCharacter.health += 9;
popUp.style.display = 'inline';
popUp.innerText = narutoCharacter.name + ' se soigne.';
}
}
class Pirate extends Character {
constructor (name, type, health, attack, level){
super (name, type, health, attack, level)
}
attackEnemy (narutoCharacter){
narutoCharacter.health -= luffyCharacter.attack;
this.levelUp ();
popUp.style.display = 'inline';
popUp.innerText = luffyCharacter.name + ' attaque ' + narutoCharacter.name + ' et lui enlève ' + luffyCharacter.attack + ' PV';
this.checkHealth (narutoCharacter);
}
specialAttack (narutoCharacter){
(narutoCharacter.health -= luffyCharacter.attack * 3);
this.levelUp ();
popUp.style.display = 'inline';
popUp.innerText = luffyCharacter.name + ' utilise Red Hawk sur ' + narutoCharacter.name + ' et lui enlève ' + luffyCharacter.attack*3 + ' PV';
this.checkHealth (narutoCharacter);
}
heal (){
this.health += 10;
popUp.style.display = 'inline';
popUp.innerText = luffyCharacter.name + ' se soigne.';
}
}
let luffyCharacter = new Ranger ("Luffy", "Ranger", 100, 8, 0);
let narutoCharacter = new Spy ("Naruto", "Spy", 110, 7, 0)
let attackSimpleNaruto = document.getElementById('attack-naruto-simple');
let attackSpecialNaruto = document.getElementById('attack-naruto-special');
let healNaruto = document.getElementById('naruto-heal');
let attackSimpleLuffy = document.getElementById('attack-luffy-simple');
let attackSpecialLuffy = document.getElementById('attack-luffy-special');
let healLuffy = document.getElementById('luffy-heal');
let luffyHp = document.getElementById ('luffy-hp');
let narutoHp = document.getElementById ('naruto-hp');
luffyHp.innerText = '100';
narutoHp.innerText = '110';
let luffyLevel = document.getElementById ('luffy-level');
let narutoLevel = document.getElementById ('naruto-level');
luffyLevel.innerText = '0';
narutoLevel.innerText = '0';
attackSimpleNaruto.addEventListener ('click', () => {
narutoCharacter.attackEnemy(luffyCharacter);
luffyHp.innerText = luffyCharacter.health;
narutoLevel.innerText = narutoCharacter.level;
luffyCharacter.informations;
})
attackSpecialNaruto.addEventListener ('click', () => {
narutoCharacter.specialAttack(luffyCharacter);
luffyHp.innerText = luffyCharacter.health;
narutoLevel.innerText = narutoCharacter.level;
luffyCharacter.informations;
})
healNaruto.addEventListener ('click', () => {
narutoCharacter.heal();
narutoCharacter.informations;
narutoLevel.innerText = narutoCharacter.level;
narutoHp.innerText = narutoCharacter.health;
})
attackSpecialLuffy.addEventListener ('click', () => {
luffyCharacter.specialAttack(narutoCharacter);
narutoHp.innerText = narutoCharacter.health;
luffyLevel.innerText = luffyCharacter.level;
narutoCharacter.informations;
})
healLuffy.addEventListener ('click', () => {
luffyCharacter.heal();
luffyHp.innerText = luffyCharacter.health;
luffyLevel.innerText = luffyCharacter.level;
luffyCharacter.informations;
})
attackSimpleLuffy.addEventListener ('click', () => {
luffyCharacter.attackEnemy(narutoCharacter);
narutoHp.innerText = narutoCharacter.health;
luffyLevel.innerText = luffyCharacter.level;
narutoCharacter.informations;
})
</code></pre>
<p>Thanks for trying to help me !</p>
|
[
{
"answer_id": 74645064,
"author": "birdspider",
"author_id": 2645347,
"author_profile": "https://Stackoverflow.com/users/2645347",
"pm_score": 0,
"selected": false,
"text": "luffyCharacter.attackEnemy(narutoCharacter);\n Ranger Ranger.attackEnemy"
},
{
"answer_id": 74645307,
"author": "Vit Lit",
"author_id": 12769919,
"author_profile": "https://Stackoverflow.com/users/12769919",
"pm_score": 0,
"selected": false,
"text": "class Character {\nconstructor (name,type,health,attack,level){\n this.name = name;\n this.type = type;\n this.health = health;\n this.attack = attack;\n this.level = level;\n}\nlevelUp (){\n this.level++;\n popUp.style.display = 'inline';\n popUp.innerText = this.name +' passe au niveau '+ this.level;\n}\ncheckHealth (){ \n if (this.health <=0){\n this.health = 0;\n popUp.style.display = 'inline';\n popUp.innerText = this.name +' est mort.'\n } else {\n console.log ('Toto');\n }\n}\nget informations (){\n infoPopUp.innerText = this.name + ' ' + this.type + ' a ' + this.health \n+ ' hp et est au niveau '+ this.level;\n tempMessage.style.display = 'inline';\n }\n}\n\nclass Game{\n attack(source, target){\n target.health -= source.attack; \n return target.checkHealth()\n }\n}\n\nvar game = new Game();\nvar luffy = new Character('Luffi','spy',100, 5, 3);\nvar naruto = new Character('Naruto','ranger',120, 2, 5);\n\ngame.attack(naruto, luffy);\n class Character {\n ....\n checkHealth (){ \n if (this.health <=0){\n this.health = 0;\n popUp.style.display = 'inline';\n popUp.innerText = this.name +' est mort.'\n } else {\n console.log ('Toto');\n }\n }\n .....\n\n Attacke(target){\n target.health -= this.attack; \n return target.checkHealth()\n }\n}\n\nluffi.Attack(naruto)\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74644966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20643763/"
] |
74,644,992
|
<p>I'm trying to delete from two tables using one function.</p>
<p>Controller code:</p>
<pre><code>public function userdelete()
{
$u_id = $this->uri->segment(3);
$lr_id = $this->uri->segment(3);
$returndata = $this->user_model->user_delete($u_id, $lr_id);
if($returndata) {
$this->session->set_flashdata('successmessage', 'user deleted successfully..');
redirect('users');
} else {
$this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
redirect('users');
}
}
</code></pre>
<p>Modle code:</p>
<pre><code>public function user_delete($lr_id, $u_id ) {
return $this->db->delete('login_roles',['lr_id'=>$lr_id]);
return $this->db->delete('login',['u_id'=>$u_id]);
}
</code></pre>
<p>I'm able to delete only from the first table but not the other one. this is working :</p>
<p><code>return $this->db->delete('login_roles',['lr_id'=>$lr_id]); but not return $this->db->delete('login',['u_id'=>$u_id]);.</code></p>
|
[
{
"answer_id": 74645064,
"author": "birdspider",
"author_id": 2645347,
"author_profile": "https://Stackoverflow.com/users/2645347",
"pm_score": 0,
"selected": false,
"text": "luffyCharacter.attackEnemy(narutoCharacter);\n Ranger Ranger.attackEnemy"
},
{
"answer_id": 74645307,
"author": "Vit Lit",
"author_id": 12769919,
"author_profile": "https://Stackoverflow.com/users/12769919",
"pm_score": 0,
"selected": false,
"text": "class Character {\nconstructor (name,type,health,attack,level){\n this.name = name;\n this.type = type;\n this.health = health;\n this.attack = attack;\n this.level = level;\n}\nlevelUp (){\n this.level++;\n popUp.style.display = 'inline';\n popUp.innerText = this.name +' passe au niveau '+ this.level;\n}\ncheckHealth (){ \n if (this.health <=0){\n this.health = 0;\n popUp.style.display = 'inline';\n popUp.innerText = this.name +' est mort.'\n } else {\n console.log ('Toto');\n }\n}\nget informations (){\n infoPopUp.innerText = this.name + ' ' + this.type + ' a ' + this.health \n+ ' hp et est au niveau '+ this.level;\n tempMessage.style.display = 'inline';\n }\n}\n\nclass Game{\n attack(source, target){\n target.health -= source.attack; \n return target.checkHealth()\n }\n}\n\nvar game = new Game();\nvar luffy = new Character('Luffi','spy',100, 5, 3);\nvar naruto = new Character('Naruto','ranger',120, 2, 5);\n\ngame.attack(naruto, luffy);\n class Character {\n ....\n checkHealth (){ \n if (this.health <=0){\n this.health = 0;\n popUp.style.display = 'inline';\n popUp.innerText = this.name +' est mort.'\n } else {\n console.log ('Toto');\n }\n }\n .....\n\n Attacke(target){\n target.health -= this.attack; \n return target.checkHealth()\n }\n}\n\nluffi.Attack(naruto)\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74644992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20658222/"
] |
74,645,031
|
<p>I am trying to fetch data from a table that returns a list of Row datetime.date objects. I would like to have them as a list of Varchar/String values.</p>
<pre><code>query = "select device_date from device where device is not null"
res = spark.sql(query).collect()
if len(res) != 0:
return res[:20]
</code></pre>
<p>The returned value seems to be of format</p>
<pre><code>[Row(device_date =datetime.date(2019, 9, 25)), Row(device_date =datetime.date(2019, 9, 17)), Row(device_date =datetime.date(2020, 1, 8))]
</code></pre>
<p>I would like to have the following output returned instead:</p>
<pre><code>['2019-09-25','2019-09-17','2020-01-08']
</code></pre>
<p>Please advise.</p>
|
[
{
"answer_id": 74645098,
"author": "scr",
"author_id": 18781246,
"author_profile": "https://Stackoverflow.com/users/18781246",
"pm_score": 1,
"selected": false,
"text": "date_format >>> from pyspark.sql.functions import date_format\n>>> df.select(date_format('device_date', 'YYYY-mm-dd').alias('date')).collect()\n[Row(date='2015-04-08')]\n \"device_date \""
},
{
"answer_id": 74645166,
"author": "Steven",
"author_id": 5013752,
"author_profile": "https://Stackoverflow.com/users/5013752",
"pm_score": 3,
"selected": true,
"text": "df = spark.sql(query) out = df.collect()\n\nlist(map(lambda x: datetime.datetime.strftime(x.device_date, \"%Y-%m-%d\"), out))\n\n['2019-09-25', '2019-09-17', '2020-01-08']\n\n# OR\n\nlist(map(str, (x.device_date for x in out)))\n['2019-09-25', '2019-09-17', '2020-01-08']\n from pyspark.sql import functions as F\n\ndf.select(F.date_format(\"device_date\", \"yyyy-MM-dd\").alias(\"device_date\")).collect()\n \n[Row(device_date='2019-09-25'),\n Row(device_date='2019-09-17'),\n Row(device_date='2020-01-08')]\n query = \"select date_format(device_date, 'yyyy-MM-dd') as date_format from device\"\n\nspark.sql(query).collect()\n\n[Row(date_format='2019-09-25'),\n Row(date_format='2019-09-17'),\n Row(date_format='2020-01-08')]\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11252662/"
] |
74,645,066
|
<p>Suppose I have a table like this:</p>
<p><strong>Example data:</strong></p>
<pre><code>x_id | type | user_id | other_id | date
----------------------------------------------
123 | AB | 999 | 001 | 10/12/12
124 | CD | 887 | 258 | 12/12/21
125 | CD | 651 | 702 | 03/04/11
126 | AB | 114 | 003 | 01/19/01
127 | EF | 573 | 777 | 02/08/17
128 | AB | 221 | 145 | 07/21/94
129 | CD | 999 | 001 | 10/12/12
130 | CD | 573 | 777 | 10/10/99
131 | EF | 114 | 003 | 03/02/97
132 | EF | 000 | 914 | 01/01/82
</code></pre>
<p>I want to select records with a <code>type</code> of <code>AB</code>, unless that type does not exist for a record. If that's the case, then I would want the oldest record, regardless of the <code>type</code>. For example, this is the result I'm looking for:</p>
<p><strong>Desired result:</strong></p>
<pre><code>x_id | type | user_id | other_id | date
----------------------------------------------
123 | AB | 999 | 001 | 10/12/12
124 | CD | 887 | 258 | 12/12/21
125 | CD | 651 | 702 | 03/04/11
126 | AB | 114 | 003 | 01/19/01
128 | AB | 221 | 145 | 07/21/94
130 | CD | 573 | 777 | 10/10/99
132 | EF | 000 | 914 | 01/01/82
</code></pre>
<p>I started out by seeing if I could simply return records where the <code>type</code> of <code>AB</code> does not exist via the query below:</p>
<pre><code>SELECT t1.x_id
,t1.type
,MAX(t1.user_id)
,t2.other_id
,MIN(t1.date)
FROM TBL_1 t1
LEFT JOIN TBL_2 t2 ON t1.y_id = t2.y_id
WHERE NOT EXISTS (
SELECT * FROM TBL_1 t1a
WHERE t1.user_id = t1a.user_id
AND t1.type LIKE '%AB%'
)
GROUP BY t1.x_id, t1.type, t2.other_id
</code></pre>
<p>However, this even returns records where a <code>type</code> equal to <code>AB</code> exists. For example, <code>user_id: 999</code> has a <code>type</code> of <code>AB</code> <em>and</em> <code>CD</code>. So I wouldn't want the query to return <code>user_id: 999</code> since they have a <code>type</code> of <code>AB</code>:</p>
<pre><code> x_id | type | user_id | other_id | date
----------------------------------------------
124 | CD | 887 | 258 | 12/12/21
125 | CD | 651 | 702 | 03/04/11
127 | EF | 573 | 777 | 02/08/17
129 | CD | 999 | 001 | 10/12/12
130 | CD | 573 | 777 | 10/10/99
131 | EF | 114 | 003 | 03/02/97
132 | EF | 000 | 914 | 01/01/82
</code></pre>
<p>What am I missing in this query to only return records that do not have a <code>type</code> of <code>AB</code>? And how can I further evolve this to select the oldest record regardless of type if <code>AB</code> does not exist? I'm not sure if I need to use a <code>CASE WHEN</code> or if there is a simpler way to do it. Any help is greatly appreciated.</p>
|
[
{
"answer_id": 74645098,
"author": "scr",
"author_id": 18781246,
"author_profile": "https://Stackoverflow.com/users/18781246",
"pm_score": 1,
"selected": false,
"text": "date_format >>> from pyspark.sql.functions import date_format\n>>> df.select(date_format('device_date', 'YYYY-mm-dd').alias('date')).collect()\n[Row(date='2015-04-08')]\n \"device_date \""
},
{
"answer_id": 74645166,
"author": "Steven",
"author_id": 5013752,
"author_profile": "https://Stackoverflow.com/users/5013752",
"pm_score": 3,
"selected": true,
"text": "df = spark.sql(query) out = df.collect()\n\nlist(map(lambda x: datetime.datetime.strftime(x.device_date, \"%Y-%m-%d\"), out))\n\n['2019-09-25', '2019-09-17', '2020-01-08']\n\n# OR\n\nlist(map(str, (x.device_date for x in out)))\n['2019-09-25', '2019-09-17', '2020-01-08']\n from pyspark.sql import functions as F\n\ndf.select(F.date_format(\"device_date\", \"yyyy-MM-dd\").alias(\"device_date\")).collect()\n \n[Row(device_date='2019-09-25'),\n Row(device_date='2019-09-17'),\n Row(device_date='2020-01-08')]\n query = \"select date_format(device_date, 'yyyy-MM-dd') as date_format from device\"\n\nspark.sql(query).collect()\n\n[Row(date_format='2019-09-25'),\n Row(date_format='2019-09-17'),\n Row(date_format='2020-01-08')]\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17245261/"
] |
74,645,122
|
<p>stuck with regular expressions. There is an example text:</p>
<blockquote>
<p>'[1 | Hi {name} | Hello {name} | Good morning {name}] other text {1
|{name}| 3| 4} OTHER {5 |{name}| 6| 7}'</p>
</blockquote>
<p>It is necessary to extract from it the constructions <strong>[1 | Hi {name} | hello {name} | Good morning {name}]</strong> and <strong>{1|{name}| 3| 4}</strong> and <strong>{5 |{name}| 6| 7}</strong></p>
<pre><code>re.findall(r'\s*(\{[^(/{name})].+\})\s*', message)
</code></pre>
<p>but I can't write a regular expression that matches the requirements
expression {name} must be ignored</p>
|
[
{
"answer_id": 74645715,
"author": "gog",
"author_id": 3494774,
"author_profile": "https://Stackoverflow.com/users/3494774",
"pm_score": 1,
"selected": false,
"text": "def top_level_parens(s):\n stack = []\n\n for n, c in enumerate(s):\n if c in '({[':\n stack.append(n)\n elif c in ')}]':\n m = stack.pop()\n if not stack:\n yield s[m:n+1]\n\n\nresult = list(top_level_parens(your_string))\n"
},
{
"answer_id": 74646461,
"author": "kirastel",
"author_id": 18760820,
"author_profile": "https://Stackoverflow.com/users/18760820",
"pm_score": 1,
"selected": true,
"text": "re.findall(r'(\\{[^n].*?[^e]\\})|(\\[.*?\\])', message)\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18760820/"
] |
74,645,137
|
<p>I have two functions that I want to run when user selects option. I have tried with a conditional. It looks something like this, but the h2 doesn't render.</p>
<pre><code> function a() {
// some logic
return <h2>{result of some logic}</h2>;
}
function b() {
// some logic
return <h2>{result of some logic}</h2>;
}
handleChange(e) {
if (e.target.value == "a") {
a()
}
else if (e.target.value == "b") {
b()
}
}
return (
<select onChange={handleChange()}>
<option value="a">a</option>
<option value="b">b</option>
</select>
)
</code></pre>
|
[
{
"answer_id": 74645437,
"author": "Emilien",
"author_id": 18143359,
"author_profile": "https://Stackoverflow.com/users/18143359",
"pm_score": 1,
"selected": false,
"text": "const [title, setTitle] = useState();\n\n handleChange(e) {\n setTitle(e.target.value)\n }\n\n return (\n<>\n <h2>{title}</h2>\n <select onChange={handleChange}>\n <option value=\"a\">a</option>\n <option value=\"b\">b</option>\n </select>\n</>\n )\n"
},
{
"answer_id": 74646429,
"author": "Saif",
"author_id": 4777670,
"author_profile": "https://Stackoverflow.com/users/4777670",
"pm_score": 0,
"selected": false,
"text": "function a() {\n return <h2>a</h2>;\n}\n\nfunction b() {\n return <h2>b</h2>;\n}\n\nfunction handleChange(e) {\n const selectedValue = e.target.value;\n const element = selectedValue === 'a' ? a() : b();\n \n // render the element somewhere in your component\n}\n\nreturn (\n <select onChange={handleChange}>\n <option value=\"a\">a</option>\n <option value=\"b\">b</option>\n </select>\n)\n\n handleChange"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19184437/"
] |
74,645,145
|
<p>I have an application which is registered in Azure (followed this <a href="https://learn.microsoft.com/en-us/azure/developer/python/sdk/authentication-on-premises-apps?source=recommendations&tabs=azure-portal" rel="nofollow noreferrer">guide</a>). I have the application-id for this application, and I would like to find its object-id by using Azure API (I am using python library). How can I retrieve the object-id?</p>
|
[
{
"answer_id": 74645437,
"author": "Emilien",
"author_id": 18143359,
"author_profile": "https://Stackoverflow.com/users/18143359",
"pm_score": 1,
"selected": false,
"text": "const [title, setTitle] = useState();\n\n handleChange(e) {\n setTitle(e.target.value)\n }\n\n return (\n<>\n <h2>{title}</h2>\n <select onChange={handleChange}>\n <option value=\"a\">a</option>\n <option value=\"b\">b</option>\n </select>\n</>\n )\n"
},
{
"answer_id": 74646429,
"author": "Saif",
"author_id": 4777670,
"author_profile": "https://Stackoverflow.com/users/4777670",
"pm_score": 0,
"selected": false,
"text": "function a() {\n return <h2>a</h2>;\n}\n\nfunction b() {\n return <h2>b</h2>;\n}\n\nfunction handleChange(e) {\n const selectedValue = e.target.value;\n const element = selectedValue === 'a' ? a() : b();\n \n // render the element somewhere in your component\n}\n\nreturn (\n <select onChange={handleChange}>\n <option value=\"a\">a</option>\n <option value=\"b\">b</option>\n </select>\n)\n\n handleChange"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1543532/"
] |
74,645,146
|
<p>I'm working with a bizarrely constructed XMl document, missing ID's and ambiguous names etc. Hopefully my example XML document paints a proper picture for you. The real document is huge and sometimes is nested 10 or more layers deep a real eye sore.</p>
<p>What I need to do is find a specific value in a node called Supplier/Name. But to find this I need to find a value in Var/Value first then look up. In my example I need to find Var/Value CLR-111.</p>
<p>I don't know if it's best to do this in LINQ or using XML docs?? The closet I found was XMLNode using previous node. But I'm not sure how to find the location first then jump up two.</p>
<p>The easy part is to locate the element but have no idea how to look up two elements . This is where I bomb.</p>
<p><strong>What I need to return is ACME.</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<Uni>
<Job ID="Job1">
<Manufacturing ID="MPG-1">
<Factory>
<SKUGroups ID="SKU-72">
<Supplier>
<Name>ACME</Name>
<Details address="123 Bobs Road" Zip="90210" />
</Supplier>
<Type>Paint</Type>
<Var>
<Name>ColorID</Name>
<Value>CLR-111</Value>
</Var>
<Supplier>
<Name>TomInc</Name>
<Details address="555 Jayne Lane" Zip="65986" />
</Supplier>
<Type>Tire</Type>
<Var>
<Name>ColorID</Name>
<Value>CLR-2222</Value>
</Var>
</SKUGroups>
</Factory>
</Manufacturing>
</Job>
</Uni>
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.Load(myPath);
XmlNode blaa = doc.SelectSingleNode("descendant::SKUGroups[Var/Value='CLR-111']/Var/Name");
</code></pre>
|
[
{
"answer_id": 74645437,
"author": "Emilien",
"author_id": 18143359,
"author_profile": "https://Stackoverflow.com/users/18143359",
"pm_score": 1,
"selected": false,
"text": "const [title, setTitle] = useState();\n\n handleChange(e) {\n setTitle(e.target.value)\n }\n\n return (\n<>\n <h2>{title}</h2>\n <select onChange={handleChange}>\n <option value=\"a\">a</option>\n <option value=\"b\">b</option>\n </select>\n</>\n )\n"
},
{
"answer_id": 74646429,
"author": "Saif",
"author_id": 4777670,
"author_profile": "https://Stackoverflow.com/users/4777670",
"pm_score": 0,
"selected": false,
"text": "function a() {\n return <h2>a</h2>;\n}\n\nfunction b() {\n return <h2>b</h2>;\n}\n\nfunction handleChange(e) {\n const selectedValue = e.target.value;\n const element = selectedValue === 'a' ? a() : b();\n \n // render the element somewhere in your component\n}\n\nreturn (\n <select onChange={handleChange}>\n <option value=\"a\">a</option>\n <option value=\"b\">b</option>\n </select>\n)\n\n handleChange"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20548788/"
] |
74,645,175
|
<p>I have an ArrayList of Objects called SprintResults, which contain the following attributes:</p>
<p>double time</p>
<p>Object Student(Which contains attributes such as String name).</p>
<p>I've sorted the ArrayList based on best times, with the intention of printing the top 5 students + their times. How do I go about preventing the same students from appearing multiple times in the top 5?</p>
|
[
{
"answer_id": 74645437,
"author": "Emilien",
"author_id": 18143359,
"author_profile": "https://Stackoverflow.com/users/18143359",
"pm_score": 1,
"selected": false,
"text": "const [title, setTitle] = useState();\n\n handleChange(e) {\n setTitle(e.target.value)\n }\n\n return (\n<>\n <h2>{title}</h2>\n <select onChange={handleChange}>\n <option value=\"a\">a</option>\n <option value=\"b\">b</option>\n </select>\n</>\n )\n"
},
{
"answer_id": 74646429,
"author": "Saif",
"author_id": 4777670,
"author_profile": "https://Stackoverflow.com/users/4777670",
"pm_score": 0,
"selected": false,
"text": "function a() {\n return <h2>a</h2>;\n}\n\nfunction b() {\n return <h2>b</h2>;\n}\n\nfunction handleChange(e) {\n const selectedValue = e.target.value;\n const element = selectedValue === 'a' ? a() : b();\n \n // render the element somewhere in your component\n}\n\nreturn (\n <select onChange={handleChange}>\n <option value=\"a\">a</option>\n <option value=\"b\">b</option>\n </select>\n)\n\n handleChange"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17117247/"
] |
74,645,189
|
<p>I need to contact a WebService:</p>
<p>this WS accepts only POST.</p>
<p>For authenticating I have to send some JSON in the BODY of request</p>
<p>while in the HEADER I have to send the WS method I want to call.</p>
<p>This is a valid request sent using CLI (WS answers correctly)</p>
<pre><code>curl -X POST -k -H 'Operation: TPLGetCardData' -H 'card_num: 123456789' -i 'https://example.com/ws.aspx' --data '{
"auth": [
{
"Timestamp": 1669910083,
"SenderIdentifier": "XXX-XXX-XXXX",
"ConnectionKey": "XXXX"
}
]
}'
</code></pre>
<p>This is the PHP code I've written, but I receive an error from the WS</p>
<pre><code>
$data = '{
"auth": [
{
"Timestamp": 1669910083,
"SenderIdentifier": "XXX-XXX-XXXX",
"ConnectionKey": "XXXX"
}
]
}';
$cURLConnection = curl_init();
curl_setopt($cURLConnection, CURLOPT_URL, 'https://example.com/ws.aspx');
curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cURLConnection, CURLOPT_POST, true);
curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, http_build_query($data));
//curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, $data);
curl_setopt($cURLConnection, CURLOPT_HTTPHEADER, array('Operation: TPLGetCardData', 'card_num: 123456789'));
//curl_setopt($cURLConnection, CURLOPT_VERBOSE , true);
$result = curl_exec($cURLConnection);
curl_close($cURLConnection);
$jsonArrayResponse - json_decode($result);
print_r('RESULT is <pre>'.$result.'</pre>');
</code></pre>
<p>If I send the request with</p>
<p><code>curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, $data)</code></p>
<p>the error is "no credentials"</p>
<p>if I send the request with</p>
<p><code>curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, http_build_query($data));</code></p>
<p>the error is "wrong credentials"</p>
<p>I don't understand which is the difference between what I send with curl CLI command and what I send with PHP.</p>
<p>If someone could help me, it will be really apreciated</p>
<p><strong>:::EDIT:::</strong>
Sorry, it came out that the problem was on the WS side, my request was OK...2 days lost in finding a non existing problem.</p>
|
[
{
"answer_id": 74645437,
"author": "Emilien",
"author_id": 18143359,
"author_profile": "https://Stackoverflow.com/users/18143359",
"pm_score": 1,
"selected": false,
"text": "const [title, setTitle] = useState();\n\n handleChange(e) {\n setTitle(e.target.value)\n }\n\n return (\n<>\n <h2>{title}</h2>\n <select onChange={handleChange}>\n <option value=\"a\">a</option>\n <option value=\"b\">b</option>\n </select>\n</>\n )\n"
},
{
"answer_id": 74646429,
"author": "Saif",
"author_id": 4777670,
"author_profile": "https://Stackoverflow.com/users/4777670",
"pm_score": 0,
"selected": false,
"text": "function a() {\n return <h2>a</h2>;\n}\n\nfunction b() {\n return <h2>b</h2>;\n}\n\nfunction handleChange(e) {\n const selectedValue = e.target.value;\n const element = selectedValue === 'a' ? a() : b();\n \n // render the element somewhere in your component\n}\n\nreturn (\n <select onChange={handleChange}>\n <option value=\"a\">a</option>\n <option value=\"b\">b</option>\n </select>\n)\n\n handleChange"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3202957/"
] |
74,645,253
|
<p>I am new using the <a href="https://docs.python.org/3/library/re.html" rel="nofollow noreferrer">re library</a> and I would like to know if somebody knows how to extract the following text:</p>
<p><strong>Initial</strong></p>
<pre><code>'[p]I am a test paragraph[/p]'
</code></pre>
<p><strong>Output</strong></p>
<pre><code>I am a test paragraph
</code></pre>
<p>I tried to use the following line :</p>
<pre><code>text = '[p]I am a test paragraph[/p]'
param = re.findall("[p](.*?)[/p]]", text)
</code></pre>
<p>but the output was :</p>
<pre><code>>>[']I am a test paragraph[/']
</code></pre>
<p>I tried to used the <a href="https://pypi.org/project/bbcode/" rel="nofollow noreferrer">BBCode library</a> but it doesn't work with this kind of text.</p>
|
[
{
"answer_id": 74645437,
"author": "Emilien",
"author_id": 18143359,
"author_profile": "https://Stackoverflow.com/users/18143359",
"pm_score": 1,
"selected": false,
"text": "const [title, setTitle] = useState();\n\n handleChange(e) {\n setTitle(e.target.value)\n }\n\n return (\n<>\n <h2>{title}</h2>\n <select onChange={handleChange}>\n <option value=\"a\">a</option>\n <option value=\"b\">b</option>\n </select>\n</>\n )\n"
},
{
"answer_id": 74646429,
"author": "Saif",
"author_id": 4777670,
"author_profile": "https://Stackoverflow.com/users/4777670",
"pm_score": 0,
"selected": false,
"text": "function a() {\n return <h2>a</h2>;\n}\n\nfunction b() {\n return <h2>b</h2>;\n}\n\nfunction handleChange(e) {\n const selectedValue = e.target.value;\n const element = selectedValue === 'a' ? a() : b();\n \n // render the element somewhere in your component\n}\n\nreturn (\n <select onChange={handleChange}>\n <option value=\"a\">a</option>\n <option value=\"b\">b</option>\n </select>\n)\n\n handleChange"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13931798/"
] |
74,645,305
|
<p>I have added to my phone authentication to my sign up process, in a send code activity - which sends the sms code to confirm the phone authentication process. Then, I have also added a "go-back"/"return" button which moves the user back to the main activity.</p>
<p>If I make the following request which sends the user a sms code to his phone:</p>
<pre><code>PhoneAuthProvider.verifyPhoneNumber(options);
</code></pre>
<p>I won't be able to make another request before the defined timeout duration ends. Therefore, I thought about the easy and not messy approach, that would be to cancel the ongoing request, but unfortunately couldn't find how to do so, if even possible nowadays. I have also saw the unanswered post here: <a href="https://stackoverflow.com/questions/70333570/android-firebase-otp-auth-is-there-a-way-to-cancel-otp-code-request-programatic">Android Firebase OTP auth: Is there a way to cancel OTP code request programatically before the actual timeout?</a></p>
<p>Couldn't work with this, even though it's what I am looking for, but it has no related answers.</p>
<ul>
<li>Note: I am programming my project with Java and not Kotlin.</li>
</ul>
<hr />
<p>I have also thought about the second approach, which is to save current activity's phone number and then extract it with onRestoreInstanceState and onSaveInstanceState, then resend a code sms again. But of course, it's much more complicated and messier.</p>
|
[
{
"answer_id": 74668889,
"author": "August Vilakia",
"author_id": 20314495,
"author_profile": "https://Stackoverflow.com/users/20314495",
"pm_score": 0,
"selected": false,
"text": "// Initiate the phone verification request\nPhoneAuthProvider.verifyPhoneNumber(\n phoneNumber,\n timeoutDuration,\n activity,\n new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {\n // Handle the verification state change events\n @Override\n public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken token) {\n // Save the verification ID and token\n this.verificationId = verificationId;\n this.token = token;\n }\n // ...\n }\n);\n\n// Cancel the ongoing phone verification request\nPhoneAuthProvider.verifyPhoneNumber(\n phoneNumber,\n timeoutDuration,\n activity,\n new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {\n // Handle the verification state change events\n @Override\n public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken token) {\n // Save the verification ID and token\n this.verificationId = verificationId;\n this.token = token;\n }\n // ...\n },\n token //\n"
},
{
"answer_id": 74671570,
"author": "diziaq",
"author_id": 2774914,
"author_profile": "https://Stackoverflow.com/users/2774914",
"pm_score": 1,
"selected": false,
"text": "verifyPhoneNumber forceResendingToken PhoneAuthProvider.getInstance() verifyPhoneNumber verifyPhoneNumber"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15213090/"
] |
74,645,339
|
<p>This is my first React project, so thank you in advance for bearing with me if this is a basic question. I have a two range inputs and I am trying to perform a calculation and update content when those range inputs are moved. Here's my file:</p>
<p>index.tsx</p>
<pre><code>import * as React from 'react'
export default function Index() {
let hours = React.useState(2)
const setHours = (newHours) => {
hours = newHours;
setPrice(hours, price);
}
let miles = React.useState(18)
const setMiles = (newMiles) => {
miles = newMiles;
setPrice(hours, price);
}
let price = React.useState(0)
const setPrice = (hours, miles) => {
price = hours * 6.00 + miles * 0.32
}
setPrice(hours, miles);
return (
<div>
<p className="font-medium">Estimated fee of ${price} for a {hours} hour, {miles} mile trip.</p>
<input onChange={(e) => setHours(e.target.value)} value={hours} type="range" min="1" max="24" />
<input onChange={(e) => setMiles(e.target.value)} value={miles} type="range" min="1" max="200" />
</div>
);
}
</code></pre>
<p>This unfortunately throws a warning "Functions are not valid as a React child."</p>
|
[
{
"answer_id": 74668889,
"author": "August Vilakia",
"author_id": 20314495,
"author_profile": "https://Stackoverflow.com/users/20314495",
"pm_score": 0,
"selected": false,
"text": "// Initiate the phone verification request\nPhoneAuthProvider.verifyPhoneNumber(\n phoneNumber,\n timeoutDuration,\n activity,\n new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {\n // Handle the verification state change events\n @Override\n public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken token) {\n // Save the verification ID and token\n this.verificationId = verificationId;\n this.token = token;\n }\n // ...\n }\n);\n\n// Cancel the ongoing phone verification request\nPhoneAuthProvider.verifyPhoneNumber(\n phoneNumber,\n timeoutDuration,\n activity,\n new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {\n // Handle the verification state change events\n @Override\n public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken token) {\n // Save the verification ID and token\n this.verificationId = verificationId;\n this.token = token;\n }\n // ...\n },\n token //\n"
},
{
"answer_id": 74671570,
"author": "diziaq",
"author_id": 2774914,
"author_profile": "https://Stackoverflow.com/users/2774914",
"pm_score": 1,
"selected": false,
"text": "verifyPhoneNumber forceResendingToken PhoneAuthProvider.getInstance() verifyPhoneNumber verifyPhoneNumber"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3713090/"
] |
74,645,352
|
<p>[I want to calculate the space of the circle
but after i enter the value of r the value of x become 0]</p>
<p>(<a href="https://i.stack.imgur.com/BjgpH.png" rel="nofollow noreferrer">https://i.stack.imgur.com/BjgpH.png</a>) (<a href="https://i.stack.imgur.com/LaRWI.png" rel="nofollow noreferrer">https://i.stack.imgur.com/LaRWI.png</a>)</p>
<p>I did not try anything since I am a beginner</p>
|
[
{
"answer_id": 74645452,
"author": "Bruno Peixoto",
"author_id": 4904472,
"author_profile": "https://Stackoverflow.com/users/4904472",
"pm_score": 2,
"selected": false,
"text": "namespace"
},
{
"answer_id": 74645620,
"author": "Masoom Raza",
"author_id": 8939178,
"author_profile": "https://Stackoverflow.com/users/8939178",
"pm_score": 2,
"selected": false,
"text": "// Creating namespaces\n#include <iostream>\nusing namespace std;\n\nnamespace mc {\nconst float b = 3.14;\nfloat value(int r) { \n return b*r*r; \n }\n}\n \nint main()\n{\n int r;\n cin>>r;\n cout << mc::value(2) << '\\n';\n return 0;\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20658347/"
] |
74,645,353
|
<p>I've a very basic Flask application:</p>
<pre><code>#main.py
from flask import Flask
app = Flask(__name__)
@app.route('/sth/')
def hi():
return 'HI\n'
</code></pre>
<p>and I try to test the existence of the url, however, to me it seems the routes are not registered:</p>
<pre><code>#tests/test_view.py
from flask import Flask
class TestSthView:
def test_sth_returns_ok(self):
app = Flask(__name__)
c = app.test_client()
resp = c.get('/sth/')
assert resp.request.path == '/sth/'
assert resp.status_code == 200
</code></pre>
<p>.</p>
<p>Could anybody point me out how can I test the existence of the /sth/ url? Why do I get 404 instead of 200 ?</p>
<p>I went through on many pages about testing, but I still unable to find the mistake.</p>
<pre><code>*
|
\---main.py
|
\---tests/
|
\--------test_view.py
</code></pre>
<p>Thanks.</p>
|
[
{
"answer_id": 74645441,
"author": "gerrel93",
"author_id": 14436548,
"author_profile": "https://Stackoverflow.com/users/14436548",
"pm_score": 1,
"selected": false,
"text": "#main.py\nfrom flask import Flask\n\napp = Flask(__name__)\n\n@app.route('/sth/')\ndef hi():\n return 'HI\\n'\n\nif __name__ == \"__main__\":\n app.run()\n import requests\n\nr = requests.get('http://127.0.0.1:5000/sth/')\n\nassert r.status_code == 200\n test_example.py @pytest.fixture()\ndef app():\n app = create_app()\n app.config.update({\n \"TESTING\": True,\n })\n\n # other setup can go here\n\n yield app\n\n # clean up / reset resources here\n\n\n@pytest.fixture()\ndef client(app):\n return app.test_client()\n\n\n\ndef yourtest(client):\n response = client.get(\"/sth/\")\n assert response.request.path == \"/index\"\n assert response.status_code == 200\n pytest test_example.py::yourtest"
},
{
"answer_id": 74645527,
"author": "barryodev",
"author_id": 15786191,
"author_profile": "https://Stackoverflow.com/users/15786191",
"pm_score": 0,
"selected": false,
"text": "app = Flask(__name__) from main import app\n\nclass TestSthView:\n def test_sth_returns_ok(self):\n c = app.test_client()\n resp = c.get('/sth/')\n\n assert resp.request.path == '/sth/'\n assert resp.status_code == 200\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2194805/"
] |
74,645,362
|
<pre><code>output [15:0] pin;
output [1:0] en;
input [6:0] dddr;
input [6:0] dbg;
</code></pre>
<p>replace this with ( I am counting the bus)</p>
<pre><code>16 : pin : output;
2 : en : output;
7 : dddr : input;
7 : dbg :input;
</code></pre>
<p>I tried this code after opening the file and stored it in var. but i am not able to filter it like above</p>
<pre><code>if ($var =~ /(\w+)\[(\d+)\:/) {
print "word=$1 number=$2\n";
}
</code></pre>
<p>//i am trying to add : in middle of the columns also</p>
|
[
{
"answer_id": 74645583,
"author": "simbabque",
"author_id": 1331451,
"author_profile": "https://Stackoverflow.com/users/1331451",
"pm_score": 3,
"selected": false,
"text": "(\\w+ ) \\[(\\d+):\n VVVVVVVV\noutput [15:0] pin; \n use strict;\nuse warnings;\nuse feature 'say';\n\nwhile (my $line = <DATA>) {\n if ($line =~ /(\\w+)\\s+\\[(\\d+)\\:/) {\n say \"word=$1 number=$2\";\n }\n}\n\n__DATA__\noutput [15:0] pin;\noutput [1:0] en;\ninput [6:0] dddr;\ninput [6:0] dbg;\n word=output number=15\nword=output number=1\nword=input number=6\nword=input number=6\n"
},
{
"answer_id": 74645648,
"author": "zdim",
"author_id": 4653379,
"author_profile": "https://Stackoverflow.com/users/4653379",
"pm_score": 2,
"selected": false,
"text": "use warnings;\nuse strict;\nuse feature 'say';\n\nwhile (<>) { \n if ( /(\\S+) \\s+ \\[ ([0-9]+):[0-9]+ \\] \\s+ (\\S+)/x ) {\n say $2+1, ' : ', $3, ' : ', $1, ';'; \n }\n}\n \\S+ .+? ; [^;]+ \\S [a-zA-Z0-9_] \\w+ [] : \\[\\s* \\s*\\] \\S+ .+? .+ ; + * .*"
},
{
"answer_id": 74645694,
"author": "pmqs",
"author_id": 2030808,
"author_profile": "https://Stackoverflow.com/users/2030808",
"pm_score": 3,
"selected": false,
"text": "(\\w+) (\\d+) while (<DATA>)\n{\n if ( /(\\w+)\\s+\\[(\\d+)\\:/) { \n print \"word=$1 number=$2\\n\";\n }\n}\n\n__DATA__\noutput [15:0] pin; \noutput [1:0] en; \ninput [6:0] dddr; \ninput [6:0] dbg;\n word=output number=15\nword=output number=1\nword=input number=6\nword=input number=6\n while (<DATA>)\n{\n if ( /(\\w+)\\s+\\[(\\d+)\\:\\d+\\]\\s+(.*);/) { \n print \"$2 : $3 : $1\\n\";\n }\n}\n\n__DATA__\noutput [15:0] pin; \noutput [1:0] en; \ninput [6:0] dddr; \ninput [6:0] dbg;\n 15 : pin : output\n1 : en : output\n6 : dddr : input\n6 : dbg : input\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14523938/"
] |
74,645,370
|
<pre><code>global mymul
mymul:
mov rax, rdi
mul rsi
ret
</code></pre>
<pre><code>#include <stdio.h>
typedef struct {
unsigned long long high;
unsigned long long low;
} resmul;
void mymul(unsigned long long, unsigned long long, resmul *res);
int main() {
resmul res;
mymul(3, 6, &res);
printf("mymul(3, 6); res.high=0x%llx, res.low=0x%llx\n", res.high, res.low);
//mymul(3, 6); res.high=0x0, res.low=0x12
return 0;
}
</code></pre>
<p>the goal is to multiply first arg with the second and send to result to the last arg
first arg = RDI / second arg = RSI
goal to send result high/low to typestruct</p>
<p>I dont understand why it gives 0 to both results
RAX and RDX should be returned but i doesnt</p>
|
[
{
"answer_id": 74645460,
"author": "Nate Eldredge",
"author_id": 634919,
"author_profile": "https://Stackoverflow.com/users/634919",
"pm_score": 2,
"selected": false,
"text": "mymul mul global mymul\nmymul:\n mov rcx, rdx ; save argument\n mov rax, rdi\n mul rsi\n mov [rcx], rdx\n mov [rcx+8], rax\n ret\n"
},
{
"answer_id": 74650103,
"author": "Peter Cordes",
"author_id": 224132,
"author_profile": "https://Stackoverflow.com/users/224132",
"pm_score": 0,
"selected": false,
"text": "void res unsigned __int128 #include <stdio.h>\n#include <stdint.h>\n\ntypedef struct {\n uint64_t low; // low first, the low half of RDX:RAX\n uint64_t high;\n} resmul; // x86-64 System V will return this in RDX:RAX, like __int128\n\nresmul mymul(uint64_t, uint64_t); // your function doesn't look for a pointer in RDX\n\nint main() {\n resmul res = mymul(3, 6);\n printf(\"mymul(3, 6); res.high=%#lx, res.low=%#lx\\n\", res.high, res.low);\n //mymul(3, 6); res.high=0x0, res.low=0x12\n return 0;\n}\n // compiles to the same asm\nresmul mymul(uint64_t a, uint64_t b){\n unsigned __int128 prod = a * (unsigned __int128)b;\n return (resmul){prod, prod>>64};\n}\n\nunsigned __int128 mulv2(uint64_t a, uint64_t b){\n return a * (unsigned __int128)b;\n}\n mymul(unsigned long, unsigned long):\n mov rax, rdi\n mul rsi\n ret\nmulv2(unsigned long, unsigned long):\n mov rax, rdi\n mul rsi\n ret\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20658440/"
] |
74,645,373
|
<p>I have this dataframe</p>
<pre><code>df = pd.DataFrame.from_dict(
{
'Name': ['Jane', 'Melissa', 'John', 'Matt'],
'Age': [23, 45, 35, 64],
'Birth City': ['London', 'Paris', 'Toronto', 'Atlanta'],
'Gender': ['F', 'F', 'M', 'M']
}
)
</code></pre>
<p>and I want to replace the <code>Gender</code> to <code>X</code>, when the name is <code>Melissa</code> or <code>John</code>. How would I do this?</p>
|
[
{
"answer_id": 74645409,
"author": "PaulS",
"author_id": 11564487,
"author_profile": "https://Stackoverflow.com/users/11564487",
"pm_score": 3,
"selected": true,
"text": "df['Gender'] = df['Gender'].mask(df['Name'].isin(['Melissa', 'John']), other='X')\n Name Age Birth City Gender\n0 Jane 23 London F\n1 Melissa 45 Paris X\n2 John 35 Toronto X\n3 Matt 64 Atlanta M\n"
},
{
"answer_id": 74645577,
"author": "swifferlifterupper",
"author_id": 20658567,
"author_profile": "https://Stackoverflow.com/users/20658567",
"pm_score": 2,
"selected": false,
"text": "df.loc[((df['Name'] == 'Melissa') | (df['Name'] == 'John')), 'Gender'] = 'X'\n Name Age Birth City Gender\n0 Jane 23 London F\n1 Melissa 45 Paris X\n2 John 35 Toronto X\n3 Matt 64 Atlanta M\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3935035/"
] |
74,645,464
|
<p>dob format is <code>2022-07</code></p>
<p>desired output is <code>0 Years 5 Months</code></p>
<p>Below is the code I tried but I am getting months in negative.</p>
<pre><code>export default function calculateAge(date) {
let month = new Date().getMonth() - Number(date.split("-")[1]);
let year = new Date().getFullYear() - Number(date.split("-")[0]);
console.log(`month is`, month);
if (month < 0 && year < 1) {
month = year * 12 + month;
year = 0;
}
console.log(`year`, year);
return `${year ? `${year} Year${year > 1 ? `s` : ""}` : ""} ${
month ? `${month} Month${month > 1 ? "s" : ""}` : ""
}`;
}
</code></pre>
|
[
{
"answer_id": 74645521,
"author": "Raz Luvaton",
"author_id": 5923666,
"author_profile": "https://Stackoverflow.com/users/5923666",
"pm_score": 1,
"selected": true,
"text": "function calculateAge(date) {\n // Split the date string into year and month\n const [year, month] = date.split(\"-\");\n\n // Get the current year and month\n const currentYear = new Date().getFullYear();\n const currentMonth = new Date().getMonth() + 1; // months are 0-indexed in JavaScript\n\n // Calculate the difference in years and months\n let ageYears = currentYear - Number(year);\n let ageMonths = currentMonth - Number(month);\n\n // If the age in months is negative, subtract 1 from the age in years and add 12 to the age in months\n if (ageMonths < 0) {\n ageYears -= 1;\n ageMonths += 12;\n }\n\n // Return the age in years and months as a string\n return `${ageYears ? `${ageYears} Year${ageYears > 1 ? `s` : \"\"}` : \"\"} ${\n ageMonths ? `${ageMonths} Month${ageMonths > 1 ? \"s\" : \"\"}` : \"\"\n }`;\n}\n"
},
{
"answer_id": 74648559,
"author": "Mister Jojo",
"author_id": 10669010,
"author_profile": "https://Stackoverflow.com/users/10669010",
"pm_score": -1,
"selected": false,
"text": "function calculateAge( start_date, end_Date ) // end_Date is optionnal\n {\n const\n [ yRef, mRef ] = start_date.split('-').map(Number)\n , today = new Date()\n , [ yEnd, mEnd ] = !!end_Date \n ? end_Date.split('-').map(Number)\n : [ today.getFullYear(), today.getMonth() +1 ]\n , delta_Months = ((yEnd - yRef) * 12) + mEnd -mRef \n , months = delta_Months % 12\n , years = (delta_Months - months) / 12\n ;\n return `${years} Year(s), ${months} Month(s)`\n }\n // actual date on code writing is 2022-12\n// PO test values . . . . . . . = 2022-07 \n// PO expected return . . . . . = 0 Years 5 Months\n \nconsole.log(calculateAge('2022-07')) // 0 Year(s), 5 Month(s)\n\nconsole.log(('--- -- - --- -- - --- -- - other tests'))\nconsole.log(calculateAge('2010-05')) // 12 Year(s), 7 Month(s)\nconsole.log(calculateAge('2010-10')) // 12 Year(s), 2 Month(s)\nconsole.log(calculateAge('2010-11'))\nconsole.log(calculateAge('2010-12')) // 12 Year(s), 0 Month(s)\nconsole.log(calculateAge('2011-01'))\nconsole.log(calculateAge('2011-02')) // 11 Year(s), 10 Month(s)\n\nconsole.log(('--- -- - --- -- - --- -- - test with specifics ending date '))\nconsole.log(calculateAge('2020-01','2022-06')) // 2 Year(s), 5 Month(s)\nconsole.log(calculateAge('2020-06','2022-06')) // 2 Year(s), 0 Month(s)\nconsole.log(calculateAge('2020-06','2022-01')) // 1 Year(s), 7 Month(s)\n\nfunction calculateAge( start_date, end_Date ) // end_Date is optionnal\n {\n const\n [ yRef, mRef ] = start_date.split('-').map(Number)\n , today = new Date()\n , [ yEnd, mEnd ] = !!end_Date \n ? end_Date.split('-').map(Number)\n : [ today.getFullYear(), today.getMonth() +1 ]\n , delta_Months = ((yEnd - yRef) * 12) + mEnd -mRef \n , months = delta_Months % 12\n , years = (delta_Months - months) / 12\n ;\n return `${years} Year(s), ${months} Month(s)`\n } .as-console-wrapper {max-height: 100% !important;top: 0;}\n.as-console-row::after {display: none !important;}"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14489691/"
] |
74,645,475
|
<p>I have a long list of random numbers between 1 and 100, and i would like to count how many of them are larger than 10,20,30 etc</p>
<pre><code>x <- c(sample(1:100, 500, replace = T))
y <- seq(0,100, by = 10)
</code></pre>
<p>I am looking for this to return an output such as;</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Total</th>
<th>10</th>
<th>20</th>
<th>30</th>
<th>40</th>
<th>50</th>
</tr>
</thead>
<tbody>
<tr>
<td>Count</td>
<td>7</td>
<td>13</td>
<td>17</td>
<td>28</td>
<td>42</td>
</tr>
</tbody>
</table>
</div>
<p>Where Count is the number of x Values that are larger than Total (each y value )</p>
<p>So far, I have tried</p>
<pre><code>Count = ifelse(x > y, 1, 0)
</code></pre>
<p>However this returns a list of Binary 1,0 returns for each of the 500 values of X</p>
<p>I'd appreciate any help</p>
|
[
{
"answer_id": 74645542,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 1,
"selected": false,
"text": "cut table table(cut(x, breaks = y))\n\n (0,10] (10,20] (20,30] (30,40] (40,50] (50,60] (60,70] (70,80] (80,90] (90,100] \n 51 66 36 44 54 49 55 46 58 41 \n findInterval table table(findInterval(x, y, left.open = TRUE))\n set.seed(505)\nx <- c(sample(1:100, 500, replace = T))\ny <- seq(0,100, by = 10)\n"
},
{
"answer_id": 74645582,
"author": "Vinícius Félix",
"author_id": 9696037,
"author_profile": "https://Stackoverflow.com/users/9696037",
"pm_score": 0,
"selected": false,
"text": "x <- c(sample(1:100, 500, replace = T))\ny <- seq(0,100, by = 10)\n\nis_bigger_than <- function(y){\n data.frame(y, n = sum(x > y,na.rm = TRUE))\n}\n \npurrr::map_df(y,is_bigger_than)\n\n y n\n1 0 500\n2 10 450\n3 20 403\n4 30 359\n5 40 305\n6 50 264\n7 60 201\n8 70 155\n9 80 100\n10 90 52\n11 100 0\n"
},
{
"answer_id": 74645599,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 0,
"selected": false,
"text": "rbind(Total = y, Count = rowSums(sapply(x, \">\", y)))\n [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]\nTotal 0 10 20 30 40 50 60 70 80 90 100\nCount 500 444 381 329 279 241 198 150 104 52 0\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20658455/"
] |
74,645,480
|
<p>I am very new to the nextjs and have come across the Image component issue. I also checked around and it seems that there are similar questions but none of them has the given scenario.</p>
<p>I am trying to load image from the remote source via Image component. The documentation saying that you should adjust your next.config.js file to allow remote images. Since I am using next 13.0.3 version I am using images.remotePatterns property. Despite this fact I am still getting an error of hostname not being configured.</p>
<p>Can you please suggest what I am doing wrong and how to overcome that problem?</p>
<p>Br,
Aleks.</p>
<p>next.config.js</p>
<pre><code>images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'swiperjs.com',
port: '',
pathname: '/demos/images/**',
}
],
},
Usage:
<Image
src="https://swiperjs.com/demos/images/nature-1.jpg"
className={styles.swiperslideimg}
alt="test" width={400} height={400}/>
</code></pre>
<p><strong>Error:</strong>
Invalid src prop (<a href="https://swiperjs.com/demos/images/nature-1.jpg" rel="nofollow noreferrer">https://swiperjs.com/demos/images/nature-1.jpg</a>) on <code>next/image</code>, hostname "swiperjs.com" is not configured under images in your <code>next.config.js</code>
See more info: <a href="https://nextjs.org/docs/messages/next-image-unconfigured-host" rel="nofollow noreferrer">https://nextjs.org/docs/messages/next-image-unconfigured-host</a></p>
|
[
{
"answer_id": 74645542,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 1,
"selected": false,
"text": "cut table table(cut(x, breaks = y))\n\n (0,10] (10,20] (20,30] (30,40] (40,50] (50,60] (60,70] (70,80] (80,90] (90,100] \n 51 66 36 44 54 49 55 46 58 41 \n findInterval table table(findInterval(x, y, left.open = TRUE))\n set.seed(505)\nx <- c(sample(1:100, 500, replace = T))\ny <- seq(0,100, by = 10)\n"
},
{
"answer_id": 74645582,
"author": "Vinícius Félix",
"author_id": 9696037,
"author_profile": "https://Stackoverflow.com/users/9696037",
"pm_score": 0,
"selected": false,
"text": "x <- c(sample(1:100, 500, replace = T))\ny <- seq(0,100, by = 10)\n\nis_bigger_than <- function(y){\n data.frame(y, n = sum(x > y,na.rm = TRUE))\n}\n \npurrr::map_df(y,is_bigger_than)\n\n y n\n1 0 500\n2 10 450\n3 20 403\n4 30 359\n5 40 305\n6 50 264\n7 60 201\n8 70 155\n9 80 100\n10 90 52\n11 100 0\n"
},
{
"answer_id": 74645599,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 0,
"selected": false,
"text": "rbind(Total = y, Count = rowSums(sapply(x, \">\", y)))\n [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]\nTotal 0 10 20 30 40 50 60 70 80 90 100\nCount 500 444 381 329 279 241 198 150 104 52 0\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9249683/"
] |
74,645,516
|
<p>I've the following PSObj with some properties stored in an $array :</p>
<pre><code>ComputerName : MyComputer
Time : 08/11/2022 13:57:53
DetectionFile : MyBadFile.exe
ThreatName : WS.Reputation.1
Action : 12
</code></pre>
<p>I'm trying to replace the action ID number by it's corresponding description. I've a hashtable with the possibles reasons behind the Action ID</p>
<pre><code>$ActionId = @{
0 = 'Unknown'
1 = 'Blocked'
2 = 'Allowed'
3 = 'No Action'
4 = 'Logged'
5 = 'Command Script Run'
6 = 'Corrected'
7 = 'Partially Corrected'
8 = 'Uncorrected'
10 = 'Delayed Requires reboot to finish the operation.'
11 = 'Deleted'
12 = 'Quarantined'
13 = 'Restored'
14 = 'Detected'
15 = 'Exonerated No longer suspicious (re-scored).'
16 = 'Tagged Marked with extended attributes.'
}
</code></pre>
<p>I'm trying to parse each item of this array, and each value of the reason ID to replace the ID by the reason string</p>
<pre><code> # parse array
foreach ($Item in $array) {
# parse possible values
foreach ($value in $ActionId) {
if ($value -eq $item.Action) {
$Item.Action = $ActionId[$value]
$Item.Action
}
}
</code></pre>
<p>From my understanding, I'm missing the correct syntax here</p>
<pre><code>$Item.Action = $ActionId[$value]
</code></pre>
<p>I do not get any errors, but from the debugger, I'm replacing the action property by $null with the above...</p>
|
[
{
"answer_id": 74645542,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 1,
"selected": false,
"text": "cut table table(cut(x, breaks = y))\n\n (0,10] (10,20] (20,30] (30,40] (40,50] (50,60] (60,70] (70,80] (80,90] (90,100] \n 51 66 36 44 54 49 55 46 58 41 \n findInterval table table(findInterval(x, y, left.open = TRUE))\n set.seed(505)\nx <- c(sample(1:100, 500, replace = T))\ny <- seq(0,100, by = 10)\n"
},
{
"answer_id": 74645582,
"author": "Vinícius Félix",
"author_id": 9696037,
"author_profile": "https://Stackoverflow.com/users/9696037",
"pm_score": 0,
"selected": false,
"text": "x <- c(sample(1:100, 500, replace = T))\ny <- seq(0,100, by = 10)\n\nis_bigger_than <- function(y){\n data.frame(y, n = sum(x > y,na.rm = TRUE))\n}\n \npurrr::map_df(y,is_bigger_than)\n\n y n\n1 0 500\n2 10 450\n3 20 403\n4 30 359\n5 40 305\n6 50 264\n7 60 201\n8 70 155\n9 80 100\n10 90 52\n11 100 0\n"
},
{
"answer_id": 74645599,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 0,
"selected": false,
"text": "rbind(Total = y, Count = rowSums(sapply(x, \">\", y)))\n [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]\nTotal 0 10 20 30 40 50 60 70 80 90 100\nCount 500 444 381 329 279 241 198 150 104 52 0\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2552996/"
] |
74,645,518
|
<p>Why I can't loop on 'data' ?</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>data = [{type: 'a', data: 'xyz'}, {type: 'a', data: 'xyz'}, {type: 'a', data: 'xyz'}];
for (i in data) {
console.log('one line');
}</code></pre>
</div>
</div>
</p>
<p>0 results, but data[0], data<a href="https://i.stack.imgur.com/TDJxb.png" rel="nofollow noreferrer">1</a>, data[2] has data...</p>
<p><a href="https://i.stack.imgur.com/TDJxb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TDJxb.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74645542,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 1,
"selected": false,
"text": "cut table table(cut(x, breaks = y))\n\n (0,10] (10,20] (20,30] (30,40] (40,50] (50,60] (60,70] (70,80] (80,90] (90,100] \n 51 66 36 44 54 49 55 46 58 41 \n findInterval table table(findInterval(x, y, left.open = TRUE))\n set.seed(505)\nx <- c(sample(1:100, 500, replace = T))\ny <- seq(0,100, by = 10)\n"
},
{
"answer_id": 74645582,
"author": "Vinícius Félix",
"author_id": 9696037,
"author_profile": "https://Stackoverflow.com/users/9696037",
"pm_score": 0,
"selected": false,
"text": "x <- c(sample(1:100, 500, replace = T))\ny <- seq(0,100, by = 10)\n\nis_bigger_than <- function(y){\n data.frame(y, n = sum(x > y,na.rm = TRUE))\n}\n \npurrr::map_df(y,is_bigger_than)\n\n y n\n1 0 500\n2 10 450\n3 20 403\n4 30 359\n5 40 305\n6 50 264\n7 60 201\n8 70 155\n9 80 100\n10 90 52\n11 100 0\n"
},
{
"answer_id": 74645599,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 0,
"selected": false,
"text": "rbind(Total = y, Count = rowSums(sapply(x, \">\", y)))\n [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]\nTotal 0 10 20 30 40 50 60 70 80 90 100\nCount 500 444 381 329 279 241 198 150 104 52 0\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1395691/"
] |
74,645,524
|
<p>There is a table that has an empty column, I need to fill up this column using row_number() and order it by value from other table.
My CTE works but I can't update the second table.</p>
<p>This is CTE (it works)</p>
<p><code>with testy(a, b, c) as (select t1.empno, t2.birthdate, ROW_NUMBER() OVER(ORDER BY t2.birthdate DESC) as order_by_id from test_tab as t1 join employee as t2 on t2.empno = t1.empno) </code></p>
<p>This request to update column but it doesn't work</p>
<pre><code>with testy(a, b, c) as (select
t1.empno
, t2.birthdate
, ROW_NUMBER() OVER(ORDER BY t2.birthdate DESC) as order_by_id
from test_tab as t1 join employee as t2 on t2.empno = t1.empno)
update test_tab
set test_tab.id = testy.b
where test_tab.empno = testy.a
</code></pre>
|
[
{
"answer_id": 74645542,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 1,
"selected": false,
"text": "cut table table(cut(x, breaks = y))\n\n (0,10] (10,20] (20,30] (30,40] (40,50] (50,60] (60,70] (70,80] (80,90] (90,100] \n 51 66 36 44 54 49 55 46 58 41 \n findInterval table table(findInterval(x, y, left.open = TRUE))\n set.seed(505)\nx <- c(sample(1:100, 500, replace = T))\ny <- seq(0,100, by = 10)\n"
},
{
"answer_id": 74645582,
"author": "Vinícius Félix",
"author_id": 9696037,
"author_profile": "https://Stackoverflow.com/users/9696037",
"pm_score": 0,
"selected": false,
"text": "x <- c(sample(1:100, 500, replace = T))\ny <- seq(0,100, by = 10)\n\nis_bigger_than <- function(y){\n data.frame(y, n = sum(x > y,na.rm = TRUE))\n}\n \npurrr::map_df(y,is_bigger_than)\n\n y n\n1 0 500\n2 10 450\n3 20 403\n4 30 359\n5 40 305\n6 50 264\n7 60 201\n8 70 155\n9 80 100\n10 90 52\n11 100 0\n"
},
{
"answer_id": 74645599,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 0,
"selected": false,
"text": "rbind(Total = y, Count = rowSums(sapply(x, \">\", y)))\n [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]\nTotal 0 10 20 30 40 50 60 70 80 90 100\nCount 500 444 381 329 279 241 198 150 104 52 0\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20503658/"
] |
74,645,543
|
<p>I have a NextJS application which conditionally renders a set of data tables using useState and useEffect:</p>
<pre><code>const [board,setBoard] = useState("AllTime");
const [AllTimeLeaderboardVisible, setAllTimeLeaderboardVisible] = useState(false);
const [TrendingCreatorLeaderboardVisible, setTrendingCreatorLeaderboardVisible] = useState(false);
const [TrendingVideoLeaderboardVisible, setTrendingVideoLeaderboardVisible ] = useState(false)
useEffect(() => {
board === "AllTime"
? setAllTimeLeaderboardVisible(true)
: setAllTimeLeaderboardVisible(false);
board === "TrendingVideo" ? setTrendingCreatorLeaderboardVisible(true) : setTrendingCreatorLeaderboardVisible(false);
board === "TrendingCreator" ? setTrendingVideoLeaderboardVisible(true) : setTrendingVideoLeaderboardVisible(false);
}, [board]);
const handleOnChange = (e: { target: { value: SetStateAction<string>; }; }) => {
setBoard(e.target.value);
};
</code></pre>
<p>The tables visibility is then controlled through a dropdown element:</p>
<pre><code> <select id ="dropdown" value={board} onChange={handleOnChange} className="mb-5 rounded-full bg-black px-6 py-3 duration-100 ease-in hover:bg-white hover:fill-black hover:text-black w-80 text-3xl tracking-tight font-work">
<option value="AllTime">All Time</option>
<option value="TrendingVideo">Trending Video</option>
<option value="TrendingCreator">Trending Creator</option>
</select>
{AllTimeLeaderboardVisible && <AllTimeLeaderboard />}
{TrendingVideoLeaderboardVisible && <TrendingVideoLeaderboard />}
{TrendingCreatorLeaderboardVisible && <TrendingVideoLeaderboard />}
</code></pre>
<p>While I have set „AllTime" as the first option Value, NextJS is giving me a</p>
<pre><code>TypeError: Cannot read properties of null (reading 'useState')
</code></pre>
<p>Error which is pointing to:</p>
<pre><code> const [board,setBoard] = useState('AllTime');
</code></pre>
<p><strong>How can this be a property of null?</strong></p>
|
[
{
"answer_id": 74645627,
"author": "Sean Anglim",
"author_id": 17843144,
"author_profile": "https://Stackoverflow.com/users/17843144",
"pm_score": 0,
"selected": false,
"text": "import { useState } from 'react';\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6491750/"
] |
74,645,555
|
<p>How to convert CommaDelimitedList Parameter to String for passing it as environment variable to Lamda Function ?</p>
<p>Below is sample CommaDelimitedList Parameter containing list of AWS regions which I need to pass it as Environment variable to AWS Lambda function in cloud formation template. The reason is when I try to pass it as it is <code>!Ref ExternalRegions</code> it gives error when create/update of the stack:</p>
<pre><code>Properties validation failed for resource LambdaFunction with message: #/Environment/Variables/EXTERNAL_REGIONS: expected type: String, found: JSONArray
Parameters:
ExternalRegions:
Description: CSV delimited account regions
Type: CommaDelimitedList
Resources:
LambdaFunction:
Type: AWS::Lambda::Function
Properties:
Environment:
Variables:
EXTERNAL_REGIONS: !Ref ExternalRegions
</code></pre>
<p>Parameter Template:</p>
<pre><code>[{
"ParameterKey": "ExternalRegions",
"ParameterValue": "us-east-1,us-west-2,ap-southeast-1"
}]
</code></pre>
<p>Could you please help, I am looking for a way to cast csv list into string so that I don't have to create another String variable with same values and always bother to keep them in sync during future changes.</p>
<p>Thanks in advace.</p>
<h2>Scrub</h2>
<p>Can't use comma in environment variable value in Lambda?</p>
<p><a href="https://stackoverflow.com/questions/41683730/comma-separator-in-lambda-function-environment-settings-using-the-serverless-fra">Comma separator in Lambda function environment settings using the Serverless Framework</a></p>
<p>If this is the case I would like to know a way where I could convert the comma delimited list parameter to string and replace comma with say alternative delimiter for ex. semi-colon (;) and pass it as lambda function variable. Is this possible?</p>
|
[
{
"answer_id": 74645627,
"author": "Sean Anglim",
"author_id": 17843144,
"author_profile": "https://Stackoverflow.com/users/17843144",
"pm_score": 0,
"selected": false,
"text": "import { useState } from 'react';\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2325916/"
] |
74,645,576
|
<p>I have the following bit of code</p>
<pre><code> const [inProgress, setInProgress] = useState(value);
useEffect(() => {
missionState.mission_summary.length > 0 ? setInProgress(true) : setInProgress(false);
console.log(missionState.mission_summary.length > 0) // false
console.log(inProgress) // true
});
</code></pre>
<p>In the last two lines, I logged the output. I would assume <code>inProgress</code> would be <code>false</code> since the condition that sets it is <code>false</code>. I am new-ish to React, so I am curious what is happening here.</p>
|
[
{
"answer_id": 74645602,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 2,
"selected": true,
"text": "useEffect useEffect(() => {\n missionState.mission_summary.length > 0 ? setInProgress(true) : setInProgress(false);\n console.log(missionState.mission_summary.length > 0) // false\n \n}, []);\n\n\nuseEffect(() => {\n console.log(inProgress) \n}, [inProgress])\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19389806/"
] |
74,645,674
|
<p>I am converting Pandas commands into Spark ones. I bumped into wanting to convert this line into Apache Spark code:</p>
<p>This line replaces every two spaces into one.</p>
<pre class="lang-py prettyprint-override"><code>df = df.columns.str.replace(' ', ' ')
</code></pre>
<p>Is it possible to replace a string from all columns using Spark?
I came into this, but it is not quite right.</p>
<pre class="lang-py prettyprint-override"><code>df = df.withColumnRenamed('--', '-')
</code></pre>
<p>To be clear I want this</p>
<pre><code>//+---+----------------------+-----+
//|id |address__test |state|
//+---+----------------------+-----+
</code></pre>
<p>to this</p>
<pre><code>//+---+----------------------+-----+
//|id |address_test |state|
//+---+----------------------+-----+
</code></pre>
|
[
{
"answer_id": 74645770,
"author": "scr",
"author_id": 18781246,
"author_profile": "https://Stackoverflow.com/users/18781246",
"pm_score": 0,
"selected": false,
"text": "columns_to_edit = [col for col in df.columns if \"__\" in col]\n for column in columns_to_edit:\n new_column = column.replace(\"__\", \"_\")\n df = df.withColumnRenamed(column, new_column)\n"
},
{
"answer_id": 74645782,
"author": "Bartosz Gajda",
"author_id": 6870955,
"author_profile": "https://Stackoverflow.com/users/6870955",
"pm_score": 3,
"selected": true,
"text": "replace df = spark.createDataFrame([(1, 2, 3)], \"id: int, address__test: int, state: int\")\ndf.show()\n+---+-------------+-----+\n| id|address__test|state|\n+---+-------------+-----+\n| 1| 2| 3|\n+---+-------------+-----+\n\nfrom pyspark.sql.functions import col\n\nnew_cols = [col(c).alias(c.replace(\"__\", \"_\")) for c in df.columns]\ndf.select(*new_cols).show()\n+---+------------+-----+\n| id|address_test|state|\n+---+------------+-----+\n| 1| 2| 3|\n+---+------------+-----+\n\n\n withColumnRenamed select select"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8284974/"
] |
74,645,681
|
<p>I just found AddDate() does not always works as expected.</p>
<p>ex:</p>
<pre><code>mayEndDate := time.Date(2021, 5, 31, 12, 00, 00, 00, time.UTC)
finalDate := endOfMay.AddDate(0, -1, 0)
</code></pre>
<p>here
output:</p>
<ul>
<li><strong>myEndDate</strong> = 2021-05-31 12:00:00 +0000 UTC</li>
<li><strong>finalDate</strong> = 2021-05-01 12:00:00 +0000 UTC</li>
</ul>
<p>I was expecting finalDate to be in <strong>April</strong>.
After reading the documentation, I found out the reason.</p>
<blockquote>
<p>AddDate normalizes its result in the same way that Date does, so, for example, adding one month to October 31 yields December 1, the normalized form for November 31.</p>
</blockquote>
<p><em><strong>My question:</strong></em> how to now correctly find out the last month's date from today's date?</p>
|
[
{
"answer_id": 74646000,
"author": "kimbo",
"author_id": 9638991,
"author_profile": "https://Stackoverflow.com/users/9638991",
"pm_score": 2,
"selected": false,
"text": "Month() currentMonth := mayEndDate.Month()\npreviousMonth := currentMonth - 1\nif currentMonth == time.January {\n previousMonth = time.December\n}\n"
},
{
"answer_id": 74646113,
"author": "rocka2q",
"author_id": 16465802,
"author_profile": "https://Stackoverflow.com/users/16465802",
"pm_score": 2,
"selected": false,
"text": "import (\n \"fmt\"\n \"time\"\n)\n\nfunc prevMonth(t time.Time) (int, time.Month) {\n y, m, _ := t.Date()\n y, m, _ = time.Date(y, m-1, 1, 0, 0, 0, 0, time.UTC).Date()\n return y, m\n}\n\nfunc main() {\n endOfMay := time.Date(2021, 5, 31, 12, 00, 00, 00, time.UTC)\n fmt.Println(endOfMay)\n fmt.Println(prevMonth(endOfMay))\n}\n 2021-05-31 12:00:00 +0000 UTC\n2021 April\n"
},
{
"answer_id": 74660818,
"author": "Manas Paldhe",
"author_id": 1683651,
"author_profile": "https://Stackoverflow.com/users/1683651",
"pm_score": -1,
"selected": false,
"text": "// Import the time package\nimport \"fmt\" // I added this, chatbot missed it.\nimport \"time\"\n\nfunc main() {\n // Get the current date and time\n now := time.Now()\n\n // Add -1 month to the current date and time\n lastMonth := now.AddDate(0, -1, 0)\n\n // Print the date of the last month\n fmt.Println(lastMonth)\n fmt.Println(lastMonth.Month()) // I added this, missed by chatbot\n}\n 2022-11-02 11:44:32.864467 -0700 PDT\n November\n // Import the time package\nimport \"fmt\" // I added this, missed by chatbot\nimport \"time\"\n\nfunc main() {\n // Get the current date and time\n now := time.Now()\n\n // Get the previous month from the current month\n lastMonth := now.Month() - 1\n\n // Set the month of the current date and time to the previous month\n lastMonthDate := time.Date(now.Year(), lastMonth, now.Day(), now.Hour(), now.Minute(), now.Second(), now.Nanosecond(), now.Location())\n\n // Print the date of the last month\n fmt.Println(lastMonthDate)\n fmt.Println(lastMonth) // I added this, missed by chatbot\n}\n 2022-11-02 11:43:36.508501 -0700 PDT\n November\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13898702/"
] |
74,645,684
|
<p>I have this filter and array for a message collector.</p>
<pre><code>const answers = ["Rock", "Paper", "Scissors"];
const filter = msg => answers.includes(msg.content());
</code></pre>
<p>That filter only detects a content that exactly matches what's in the array. So if a message say, "Scissors!!", it isn't detected because of the extra text (!!). The design is it should still be detected.</p>
<p>Is it correct that I should use a for loop with the filter? How do I exactly do it? Thanks in advance.</p>
|
[
{
"answer_id": 74645941,
"author": "Caladan",
"author_id": 17641423,
"author_profile": "https://Stackoverflow.com/users/17641423",
"pm_score": 2,
"selected": false,
"text": ".some() true false const string = \"test!!\";\nconst answers = [\"Rock\", \"Paper\", \"Scissors\"];\n\nconsole.log(answers.some((val) => string.includes(val.toLowerCase())));"
},
{
"answer_id": 74645997,
"author": "Saif",
"author_id": 4777670,
"author_profile": "https://Stackoverflow.com/users/4777670",
"pm_score": 2,
"selected": true,
"text": "const answers = [\"Rock\", \"Paper\", \"Scissors\"];\nconst filter = msg => {\n for (let answer of answers) {\n if (msg.content.includes(answer)) {\n return true;\n }\n }\n return false;\n}\n\n Array.some() const answers = [\"Rock\", \"Paper\", \"Scissors\"];\nconst filter = msg => answers.some(answer => msg.content.includes(answer));\n\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/874737/"
] |
74,645,690
|
<p>I'm trying to build a basic game-like program where I need to rearrange a given matrix but vertically. In this case, I only have 0s and 1s. 0 being lighter objects and 1 being heavier. When the function runs, all the 1s should fall down vertically and the zeros go up vertically as well. It needs to have the exact number of 0s and 1s as the original matrix. Example:
-If I give the following matrix:</p>
<pre><code>[1,0,1,1,0,1,0],
[0,0,0,1,0,0,0],
[1,0,1,1,1,1,1],
[0,1,1,0,1,1,0],
[1,1,0,1,0,0,1]
</code></pre>
<p>It should rearrange it to:</p>
<pre><code>[0,0,0,0,0,0,0],
[0,0,0,1,0,0,0],
[1,0,1,1,0,1,0],
[1,1,1,1,1,1,1],
[1,1,1,1,1,1,1]
</code></pre>
<p>Any help or suggestions will be highly appreciated.</p>
|
[
{
"answer_id": 74645743,
"author": "Priyatham",
"author_id": 2542516,
"author_profile": "https://Stackoverflow.com/users/2542516",
"pm_score": 2,
"selected": false,
"text": "np.sort np.sort(matrix, axis=0)\n"
},
{
"answer_id": 74645931,
"author": "Andrew Ryan",
"author_id": 7451892,
"author_profile": "https://Stackoverflow.com/users/7451892",
"pm_score": 1,
"selected": false,
"text": "from collections import Counter\n\ntest = [[1,0,1,1,0,1,0],\n[0,0,0,1,0,0,0],\n[1,0,1,1,1,1,1],\n[0,1,1,0,1,1,0],\n[1,1,0,1,0,0,1] ]\n\nnew_version = [[] for _ in test] # create an empty list to append data to\nfor count, item in enumerate(test[0]): # go through the length of one of the list of lists for their length # assuming that all lists are of equal length\n frequency = Counter([x[count] for x in test]) # get frequency count for the column\n for count_inside, item_inside in enumerate(test): \n # to add the values depending on their frequency distribution in the column\n value = 0 if 0 in frequency and count_inside < frequency[0] else 1\n new_version[count_inside].append(value)\n \nprint(new_version)\n \n"
},
{
"answer_id": 74645935,
"author": "John Coleman",
"author_id": 4996248,
"author_profile": "https://Stackoverflow.com/users/4996248",
"pm_score": 2,
"selected": true,
"text": "zip(*matrix) [row for row in zip(*[sorted(column) for column in zip(*matrix)])]\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15062354/"
] |
74,645,693
|
<p>I am currently having a similar need to the question in <a href="https://stackoverflow.com/questions/44978196/pandas-filling-missing-dates-and-values-within-group">this thread</a>, but it looks like it cannot fill in the <code>dates</code> if the <code>min</code> and <code>max</code> dates of the given <code>date</code> column does not fall into the first and last day of a given month and year. In particular, assume this dataframe</p>
<pre><code>df = pd.DataFrame({'user': ['a','a','b','b','c','c','c'], 'dt': ['2016-01-05','2016-01-08', '2016-01-10','2016-01-15','2016-01-16', '2016-01-22', '2016-01-19'], 'val': [1,33,2,1,5,5,6], 'price': [1,2,1,1,2,5.5,4.2]})
user dt val price
0 a 2016-01-05 1 1.0
1 a 2016-01-08 33 2.0
2 b 2016-01-10 2 1.0
3 b 2016-01-15 1 1.0
4 c 2016-01-16 5 2.0
5 c 2016-01-22 5 5.5
6 c 2016-01-19 6 4.2
</code></pre>
<p>Using the code in the first answer of the above thread, the resulting dataframe can only fill in <code>0</code> values for all <code>dates</code> between <code>2016-01-05</code> and <code>2016-01-22</code>. It could not do the same thing on dates between <code>2016-01-01</code> and <code>2016-01-04</code>, OR from <code>2016-01-23</code> to <code>2016-01-31.</code> I wonder if anyone could help address this point, as I currently have a need to accomplish the fill-in for every missing dates within a given month and year?</p>
<p><strong>Expected Output</strong></p>
<pre><code> user dt val price
0 a 2016-01-01 0 0.0
1 a 2016-01-02 0 0.0
2 a 2016-01-03 0 0.0
3 a 2016-01-04 0 0.0
4 a 2016-01-05 1 1.0
5 a 2016-01-06 0 0.0
6 a 2016-01-07 0 0.0
7 a 2016-01-08 33 2.0
8 a 2016-01-09 0 0.0
9 a 2016-01-10 0 0.0
10 a 2016-01-11 0 0.0
11 a 2016-01-12 0 0.0
12 a 2016-01-13 0 0.0
13 a 2016-01-14 0 0.0
14 a 2016-01-15 0 0.0
15 a 2016-01-16 0 0.0
16 a 2016-01-17 0 0.0
17 a 2016-01-18 0 0.0
18 a 2016-01-19 0 0.0
19 a 2016-01-20 0 0.0
20 a 2016-01-21 0 0.0
21 a 2016-01-22 0 0.0
22 a 2016-01-23 0 0.0
23 a 2016-01-24 0 0.0
24 a 2016-01-25 0 0.0
25 a 2016-01-26 0 0.0
26 a 2016-01-27 0 0.0
27 a 2016-01-28 0 0.0
28 a 2016-01-29 0 0.0
29 a 2016-01-30 0 0.0
30 a 2016-01-31 0 0.0
31 b 2016-01-01 0 0.0
32 b 2016-01-02 0 0.0
33 b 2016-01-03 0 0.0
34 b 2016-01-04 0 0.0
35 b 2016-01-05 0 0.0
36 b 2016-01-06 0 0.0
37 b 2016-01-07 0 0.0
38 b 2016-01-08 0 0.0
39 b 2016-01-09 0 0.0
40 b 2016-01-10 2 1.0
41 b 2016-01-11 0 0.0
42 b 2016-01-12 0 0.0
43 b 2016-01-13 0 0.0
44 b 2016-01-14 0 0.0
45 b 2016-01-15 1 1.0
46 b 2016-01-16 0 0.0
47 b 2016-01-17 0 0.0
48 b 2016-01-18 0 0.0
49 b 2016-01-19 0 0.0
50 b 2016-01-20 0 0.0
51 b 2016-01-21 0 0.0
52 b 2016-01-22 0 0.0
53 b 2016-01-23 0 0.0
54 b 2016-01-24 0 0.0
55 b 2016-01-25 0 0.0
56 b 2016-01-26 0 0.0
57 b 2016-01-27 0 0.0
58 b 2016-01-28 0 0.0
59 b 2016-01-29 0 0.0
60 b 2016-01-30 0 0.0
61 b 2016-01-31 0 0.0
62 c 2016-01-01 0 0.0
63 c 2016-01-02 0 0.0
64 c 2016-01-03 0 0.0
65 c 2016-01-04 0 0.0
66 c 2016-01-05 0 0.0
67 c 2016-01-06 0 0.0
68 c 2016-01-07 0 0.0
69 c 2016-01-08 0 0.0
70 c 2016-01-09 0 0.0
71 c 2016-01-10 2 1.0
72 c 2016-01-11 0 0.0
73 c 2016-01-12 0 0.0
74 c 2016-01-13 0 0.0
75 c 2016-01-14 0 0.0
76 c 2016-01-15 1 1.0
77 c 2016-01-16 5 2.0
78 c 2016-01-17 0 0.0
79 c 2016-01-18 0 0.0
80 c 2016-01-19 6 4.2
81 c 2016-01-20 0 0.0
82 c 2016-01-21 0 0.0
83 c 2016-01-22 5 5.5
84 c 2016-01-23 0 0.0
85 c 2016-01-24 0 0.0
86 c 2016-01-25 0 0.0
87 c 2016-01-26 0 0.0
88 c 2016-01-27 0 0.0
89 c 2016-01-28 0 0.0
90 c 2016-01-29 0 0.0
91 c 2016-01-30 0 0.0
92 c 2016-01-31 0 0.0
</code></pre>
|
[
{
"answer_id": 74645743,
"author": "Priyatham",
"author_id": 2542516,
"author_profile": "https://Stackoverflow.com/users/2542516",
"pm_score": 2,
"selected": false,
"text": "np.sort np.sort(matrix, axis=0)\n"
},
{
"answer_id": 74645931,
"author": "Andrew Ryan",
"author_id": 7451892,
"author_profile": "https://Stackoverflow.com/users/7451892",
"pm_score": 1,
"selected": false,
"text": "from collections import Counter\n\ntest = [[1,0,1,1,0,1,0],\n[0,0,0,1,0,0,0],\n[1,0,1,1,1,1,1],\n[0,1,1,0,1,1,0],\n[1,1,0,1,0,0,1] ]\n\nnew_version = [[] for _ in test] # create an empty list to append data to\nfor count, item in enumerate(test[0]): # go through the length of one of the list of lists for their length # assuming that all lists are of equal length\n frequency = Counter([x[count] for x in test]) # get frequency count for the column\n for count_inside, item_inside in enumerate(test): \n # to add the values depending on their frequency distribution in the column\n value = 0 if 0 in frequency and count_inside < frequency[0] else 1\n new_version[count_inside].append(value)\n \nprint(new_version)\n \n"
},
{
"answer_id": 74645935,
"author": "John Coleman",
"author_id": 4996248,
"author_profile": "https://Stackoverflow.com/users/4996248",
"pm_score": 2,
"selected": true,
"text": "zip(*matrix) [row for row in zip(*[sorted(column) for column in zip(*matrix)])]\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5508202/"
] |
74,645,753
|
<p>Consider a positive integer n. What will be the smallest number k such that if we concatenate the digits of n with those of k we get a perfect square?</p>
<p>For example, for n=1 the smallest k is 6 since 16 is a perfect square.</p>
<p>For n=4, k has to be 9 because 49 is a perfect square.</p>
<p>For n=35, k is 344, since 35344=1882 is the smallest perfect square starting with the digits 35.</p>
<p>Define the smallestSquare function that takes a positive integer n and returns the smallest integer k whose concatenation of the digits of n,k results in a perfect square.</p>
<p>For now all I have is this, which checks wether the given number is a perfect square or not.
I would like to solve this using recursion but I'm not even sure where to start.</p>
<pre><code>from math import sqrt
def isSquare(n):
return n == int(sqrt(n) + 0.5) ** 2
def smallestSquare(n):
</code></pre>
|
[
{
"answer_id": 74646256,
"author": "Vin",
"author_id": 7955271,
"author_profile": "https://Stackoverflow.com/users/7955271",
"pm_score": 0,
"selected": false,
"text": "import math\n\ndef find_smallest_perfect_square(start: int) -> int:\n while True:\n if int(math.sqrt(start)) != math.sqrt(start):\n start += 1\n else:\n return start\n \ndef find_concatenation(n: int) -> int:\n str_n = str(n)\n while True:\n val = find_smallest_perfect_square(n)\n if str(val).startswith(str_n):\n return val\n else:\n n = val + 1\n for i in range(10):\n print (f'The smallest perfect square that begins with {i} is {find_concatenation(i)}')\n\n# Result:\n # The smallest perfect square that begins with 0 is 0\n # The smallest perfect square that begins with 1 is 1\n # The smallest perfect square that begins with 2 is 25\n # The smallest perfect square that begins with 3 is 36\n # The smallest perfect square that begins with 4 is 4\n # The smallest perfect square that begins with 5 is 529\n # The smallest perfect square that begins with 6 is 64\n # The smallest perfect square that begins with 7 is 729\n # The smallest perfect square that begins with 8 is 81\n # The smallest perfect square that begins with 9 is 9\n"
},
{
"answer_id": 74646278,
"author": "user19077881",
"author_id": 19077881,
"author_profile": "https://Stackoverflow.com/users/19077881",
"pm_score": 1,
"selected": false,
"text": "def smallestSquare(n):\n x = 1\n while isSquare(int(str(n)+str(x))) == False:\n x += 1\n return int(str(n)+str(x))\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20400765/"
] |
74,645,769
|
<p>I have the following perl code in where I have a perl structure as follows:
`</p>
<pre><code>use Data::Dumper;
my %data = (
'status' => 200,
'message' => '',
'response' => {
'name' => 'John Smith',
'id' => '1abc579',
'ibge' => '3304557',
'uf' => 'XY',
'status' => bless( do{\(my $o = 1)}, 'JSON::PP::Boolean' )
}
);
my $resp = $data{'status'};
print "Response is $resp \n";
print Dumper(%data->{'response'});
</code></pre>
<p>Getting the status field works, however If I try something like this:
<code>my $resp = $data{'response'}</code></p>
<p>I get Response is HASH(0x8b6640)</p>
<p>So I'm wondering if there's a way I can extract <strong>all</strong> the data of the 'response' field on the same way I can do it for 'status' without getting that HASH...</p>
<p>I've tried all sort of combinations when accessing the data, however I'm still getting the HASH back when I try to get the content of 'response'</p>
|
[
{
"answer_id": 74645856,
"author": "Silvio Mayolo",
"author_id": 2288659,
"author_profile": "https://Stackoverflow.com/users/2288659",
"pm_score": 1,
"selected": false,
"text": "$data{'response'} %data HASH(0x8b6640) Dumper print Dumper($data{'response'});\n -> print $data{'response'}->{'name'}\n -> % $"
},
{
"answer_id": 74646036,
"author": "Mike",
"author_id": 20658697,
"author_profile": "https://Stackoverflow.com/users/20658697",
"pm_score": 0,
"selected": false,
"text": "use Data::Dumper;\n\nmy %data = (\n 'status' => 200,\n 'message' => '',\n 'response' => {\n 'name' => 'John Smith',\n 'id' => '1abc579',\n 'ibge' => '3304557',\n 'uf' => 'XY',\n 'status' => bless( do{\\(my $o = 1)}, 'JSON::PP::Boolean' )\n }\n\n);\n\nmy $resp = $data{'response'};\nprint Dumper($resp);\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20658697/"
] |
74,645,772
|
<p>I have the following image:</p>
<p><a href="https://i.stack.imgur.com/yACz0.png" rel="nofollow noreferrer">Initial Image</a></p>
<p>I am using the following code the rotate the image:</p>
<pre><code>from skimage.transform import rotate
image = cv2.imread('122.png')
rotated = rotate(image,34,cval=1,resize = True)
</code></pre>
<p>Once I execute this code, I receive the following image:</p>
<p><a href="https://i.stack.imgur.com/fDVYH.png" rel="nofollow noreferrer">Rotated Image</a></p>
<p>To eliminate the blur on the image, I use the following code to set a threshold. Anything that is not white is turned to black (so the gray spots turn black). The code for that is as follows:</p>
<pre><code>ret, thresh_hold = cv2.threshold(rotated, 0, 100, cv2.THRESH_BINARY)
plt.imshow(thresh_hold)
</code></pre>
<p>Instead of getting a nice clear picture, I receive the following:<a href="https://i.stack.imgur.com/8xXQ8.png" rel="nofollow noreferrer"><br />
Choppy Image</a></p>
<p>Does anyone know what I can do to improve the image quality, or adjust the threshold to create a clearer image?</p>
<p>I attempted to adjust the threshold to different values, but this changed the image to all black or all white.</p>
|
[
{
"answer_id": 74645856,
"author": "Silvio Mayolo",
"author_id": 2288659,
"author_profile": "https://Stackoverflow.com/users/2288659",
"pm_score": 1,
"selected": false,
"text": "$data{'response'} %data HASH(0x8b6640) Dumper print Dumper($data{'response'});\n -> print $data{'response'}->{'name'}\n -> % $"
},
{
"answer_id": 74646036,
"author": "Mike",
"author_id": 20658697,
"author_profile": "https://Stackoverflow.com/users/20658697",
"pm_score": 0,
"selected": false,
"text": "use Data::Dumper;\n\nmy %data = (\n 'status' => 200,\n 'message' => '',\n 'response' => {\n 'name' => 'John Smith',\n 'id' => '1abc579',\n 'ibge' => '3304557',\n 'uf' => 'XY',\n 'status' => bless( do{\\(my $o = 1)}, 'JSON::PP::Boolean' )\n }\n\n);\n\nmy $resp = $data{'response'};\nprint Dumper($resp);\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20658672/"
] |
74,645,787
|
<p>I want to make a bar containing mutual data of two users. I want it to be like this image:</p>
<p><img src="https://i.stack.imgur.com/P3MGM.png" alt="" /></p>
<p>I also used the <code>Rectangle()</code> shape here. But the bar starts to fill up after 0.5, it seems empty before that. What should I do here?</p>
<p>The code I wrote is as follows:</p>
<pre class="lang-swift prettyprint-override"><code> HStack{
ZStack(alignment: .leading){
Rectangle()
.trim(from:0.1, to:0.6)
.fill(Color.init( red: 0.965, green: 0.224, blue: 0.49))
.frame(width: 55, height: 11)
Text(String(nowduelList.user1StepCount))
.font(.system(size: 8))
.bold()
.foregroundColor(Color.white)
}
ZStack(alignment: .trailing){
Rectangle()
.trim(from:0, to: 0.8)
.fill(Color.init( red: 0.208, green: 0.231, blue: 0.314))
.frame(width: 55, height: 11)
Text(String(nowduelList.user2StepCount))
.font(.system(size: 8))
.bold()
.foregroundColor(Color.white)
}
}
</code></pre>
<p>And this is an image of my <code>View</code>:</p>
<p><img src="https://i.stack.imgur.com/I64Ks.png" alt="" /></p>
|
[
{
"answer_id": 74647106,
"author": "Kush Bhavsar",
"author_id": 15161794,
"author_profile": "https://Stackoverflow.com/users/15161794",
"pm_score": 0,
"selected": false,
"text": " HStack(spacing: -5) {\n ZStack(alignment: .leading){\n Rectangle()\n .trim(from:0, to:0.8) // << Same as second view\n .rotation(Angle(degrees: 180)) // << Rotation\n .fill(Color.init( red: 0.965, green: 0.224, blue: 0.49))\n .frame(width: 55, height: 11)\n \n Text(String(951))\n .font(.system(size: 8))\n .bold()\n .foregroundColor(Color.white)\n }\n \n ZStack(alignment: .trailing){\n Rectangle()\n .trim(from:0, to: 0.8)\n .fill(Color.init( red: 0.208, green: 0.231, blue: 0.314))\n .frame(width: 55, height: 11)\n Text(String(231))\n .font(.system(size: 8))\n .bold()\n .foregroundColor(Color.white)\n }\n }\n"
},
{
"answer_id": 74651674,
"author": "Jatin Bhuva",
"author_id": 19572222,
"author_profile": "https://Stackoverflow.com/users/19572222",
"pm_score": -1,
"selected": false,
"text": "struct Triangle: Shape {\n func path(in rect: CGRect) -> Path {\n var path = Path()\n path.move(to: CGPoint(x: 0, y: 0))\n path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))\n path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))\n path.addLine(to: CGPoint(x: rect.maxX/1.2, y: 0))\n return path\n }\n}\n\n\nstruct LeadingTriangle: Shape {\n func path(in rect: CGRect) -> Path {\n var path = Path()\n path.move(to: CGPoint(x: rect.maxX/1.2-rect.maxX, y: 0))\n path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))\n path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))\n path.addLine(to: CGPoint(x: rect.maxX, y: 0))\n return path\n }\n}\n\nvar body: some View {\n \n HStack{\n \n ZStack(alignment: .leading){\n Rectangle()\n .fill(Color.white)\n .frame(width: 150, height: 30)\n .overlay(\n Triangle()\n .fill(Color.red)\n )\n Text(String(23.32))\n .font(.system(size: 8))\n .bold()\n .foregroundColor(Color.white)\n }\n ZStack(alignment: .trailing){\n Rectangle()\n .fill(Color.white)\n .frame(width: 150, height: 30)\n .overlay(\n LeadingTriangle()\n .fill(Color.blue)\n )\n \n Text(String(23.32))\n .font(.system(size: 8))\n .bold()\n .foregroundColor(Color.white)\n }\n }\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20166709/"
] |
74,645,789
|
<p>I'd like to replace the + sign in my expression. When I did it with regular expression, it interprets this + as "at one or more", while in fact I'd like it to be interpreted as the literal +</p>
<p>The problem I have on hand is that I want to format the following string, which is not formatted nicely.
"model = y+ x1+ x2 +x3 +x4"
I want it to be:
"model = y + x1 + x2 + x3 + x4"</p>
<p>I have a lot of expressions like this needs to be re-written, I'd like to use regular expression rather than manually adjusting the format.
I was thinking something like:
<code>gsub('\s+\s',' + ', string)</code>, which doesn't work of course.</p>
<p>is there a way to get around this? what is the correct way of regular expression to achieve this? I've searched online but no results.</p>
|
[
{
"answer_id": 74647106,
"author": "Kush Bhavsar",
"author_id": 15161794,
"author_profile": "https://Stackoverflow.com/users/15161794",
"pm_score": 0,
"selected": false,
"text": " HStack(spacing: -5) {\n ZStack(alignment: .leading){\n Rectangle()\n .trim(from:0, to:0.8) // << Same as second view\n .rotation(Angle(degrees: 180)) // << Rotation\n .fill(Color.init( red: 0.965, green: 0.224, blue: 0.49))\n .frame(width: 55, height: 11)\n \n Text(String(951))\n .font(.system(size: 8))\n .bold()\n .foregroundColor(Color.white)\n }\n \n ZStack(alignment: .trailing){\n Rectangle()\n .trim(from:0, to: 0.8)\n .fill(Color.init( red: 0.208, green: 0.231, blue: 0.314))\n .frame(width: 55, height: 11)\n Text(String(231))\n .font(.system(size: 8))\n .bold()\n .foregroundColor(Color.white)\n }\n }\n"
},
{
"answer_id": 74651674,
"author": "Jatin Bhuva",
"author_id": 19572222,
"author_profile": "https://Stackoverflow.com/users/19572222",
"pm_score": -1,
"selected": false,
"text": "struct Triangle: Shape {\n func path(in rect: CGRect) -> Path {\n var path = Path()\n path.move(to: CGPoint(x: 0, y: 0))\n path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))\n path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))\n path.addLine(to: CGPoint(x: rect.maxX/1.2, y: 0))\n return path\n }\n}\n\n\nstruct LeadingTriangle: Shape {\n func path(in rect: CGRect) -> Path {\n var path = Path()\n path.move(to: CGPoint(x: rect.maxX/1.2-rect.maxX, y: 0))\n path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))\n path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))\n path.addLine(to: CGPoint(x: rect.maxX, y: 0))\n return path\n }\n}\n\nvar body: some View {\n \n HStack{\n \n ZStack(alignment: .leading){\n Rectangle()\n .fill(Color.white)\n .frame(width: 150, height: 30)\n .overlay(\n Triangle()\n .fill(Color.red)\n )\n Text(String(23.32))\n .font(.system(size: 8))\n .bold()\n .foregroundColor(Color.white)\n }\n ZStack(alignment: .trailing){\n Rectangle()\n .fill(Color.white)\n .frame(width: 150, height: 30)\n .overlay(\n LeadingTriangle()\n .fill(Color.blue)\n )\n \n Text(String(23.32))\n .font(.system(size: 8))\n .bold()\n .foregroundColor(Color.white)\n }\n }\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8149739/"
] |
74,645,799
|
<p>When the route is blank (i.e. <code>https://localhost:1234</code>) I want it to route to the search component.</p>
<p>I have routing set up in my <code>app.module.ts</code> like this:</p>
<pre><code>RouterModule.forRoot([
{ path: '', redirectTo: 'search', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{
path: '', component: BasicLayoutComponent,
children: [
{ path: 'search', component: SearchComponent },
{ path: 'settings', component: SettingsComponent },
{ path: 'profile', component: ProfileComponent }
]
},
{ path: '**', redirectTo: 'search' }
]),
</code></pre>
<p>This isn't working however, when I go to an empty route it is loading the <code>BasicLayoutComponent</code> without loading any of the child paths/components.</p>
<p>I have also tried putting the redirect route in the children like so:</p>
<pre><code>RouterModule.forRoot([
{ path: 'login', component: LoginComponent },
{
path: '', component: BasicLayoutComponent,
children: [
{ path: '', redirectTo: 'search', pathMatch: 'full' },
{ path: 'search', component: SearchComponent },
{ path: 'settings', component: SettingsComponent },
{ path: 'profile', component: ProfileComponent }
]
},
{ path: '**', redirectTo: 'search' }
]),
</code></pre>
<p>This also doesn't work and has the same problem (routes to empty BasicLayoutComponent). I've even tried having it in both places with no luck.</p>
<p>The wildcard redirect works correctly, navigating to <code>/test</code> for example redirects to <code>/search</code>.</p>
<p>What am I doing wrong?</p>
<p>This is with angular packages <code>^14.0.3</code>.</p>
|
[
{
"answer_id": 74646031,
"author": "Flo",
"author_id": 4472932,
"author_profile": "https://Stackoverflow.com/users/4472932",
"pm_score": -1,
"selected": false,
"text": "const routes: Routes = [\n {path: '', redirectTo: '/auth/sign-in', pathMatch: 'full'}\n];\n const routes: Routes = [\n {\n path: 'auth',\n component: AuthComponent,\n children: [\n {path: 'sign-in', component: SignInComponent}\n ]\n },\n\n];\n"
},
{
"answer_id": 74646342,
"author": "QTom",
"author_id": 4690605,
"author_profile": "https://Stackoverflow.com/users/4690605",
"pm_score": 0,
"selected": false,
"text": "{ path: '', redirectTo: 'search', pathMatch: 'full' }, RouterModule.forRoot([\n {\n path: '', component: BasicLayoutComponent, children: [\n { path: 'users', component: UsersIndexComponent }\n ]\n }\n ])\n RouterModule.forRoot([\n {\n path: 'users', component: BasicLayoutComponent, children: [\n { path: '', component: UsersIndexComponent }\n ]\n }\n ])\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4690605/"
] |
74,645,800
|
<p>I have this div that shows a <strong>top red bar</strong>. I've been trying to move this bar to the left side and make it look like a border left, but not having any luck. Does anyone know how to make it look like a <strong>border lef</strong>t using this code? Thanks in advance!</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>.container {
position: relative;
width: 100%;
padding: 18px;
margin-bottom: 16px;
border-radius: 8px;
border: solid 2px #e1e4e8;
overflow: hidden;
}
.container::after {
content: '';
position: absolute;
display: block;
height: 6px;
width: 100%;
top: 0;
left: 0;
background-color: red;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class = "container">this is a text</div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74645926,
"author": "John Li",
"author_id": 20436957,
"author_profile": "https://Stackoverflow.com/users/20436957",
"pm_score": 3,
"selected": true,
"text": "::after .container {\n position: relative;\n width: 100%;\n padding: 18px;\n margin-bottom: 16px;\n border-radius: 8px;\n border: solid 2px #e1e4e8;\n overflow: hidden;\n}\n\n.container::after {\n content: '';\n position: absolute;\n display: block;\n width: 6px;\n inset: 0;\n background-color: red;\n } <div class = \"container\">this is a text</div>"
},
{
"answer_id": 74645992,
"author": "Dr. Tenma",
"author_id": 3357677,
"author_profile": "https://Stackoverflow.com/users/3357677",
"pm_score": 0,
"selected": false,
"text": "border-left: 6px solid red; background-color: red; .container::after border-top: 2px solid #e1e4e8;\n border-bottom: 2px solid #e1e4e8;\n border-right: 2px solid #e1e4e8;\n .container {\n position: absolute;\n display: block;\n width: 100%;\n padding: 18px;\n margin-bottom: 16px;\n border-radius: 8px;\n border-left: 6px solid red;\n border-top: 2px solid #e1e4e8;\n border-bottom: 2px solid #e1e4e8;\n border-right: 2px solid #e1e4e8;\n overflow: hidden;\n}\n\n.container::after {\n content: '';\n position: absolute;\n display: block;\n height: 6px;\n width: 100%;\n top: 0;\n left: 0;\n } <div class = \"container\">this is a text</div>"
},
{
"answer_id": 74646027,
"author": "Mark Schultheiss",
"author_id": 125981,
"author_profile": "https://Stackoverflow.com/users/125981",
"pm_score": 0,
"selected": false,
"text": ".container {\n position: relative;\n width: 100%;\n padding: 18px;\n margin-bottom: 16px;\n border-radius: 8px;\n border: solid 2px #e1e4e8;\n border-left: solid 8px red;\n overflow: hidden;\n} <div class = \"container\">this is a text</div>"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5245070/"
] |
74,645,801
|
<p>I am trying to label the series of concentric circles below with the labels from <code>C</code> in the data frame</p>
<p>I am aware that I could use something like <code>geom_text_repel</code> but I cannot seem to get it to work.</p>
<p>In addition, I cannot seem to get rid of the tick marks on the upper left.</p>
<p><a href="https://i.stack.imgur.com/uiiTf.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uiiTf.jpg" alt="enter image description here" /></a></p>
<pre><code>df <- data.frame(C=c(rep("The macro-environment",4),rep("The industry",4),rep("Competitors",4),rep("The organisation",4)))
ggplot(df, aes(factor(1), fill = C)) +
geom_bar(width = 1, colour = NA, show.legend = FALSE, alpha = .8) +
coord_polar() +
labs(
x = "",
y = ""
) +
scale_fill_manual(values = c("#289045", "#beddc7", "#d4dfe9", "#286291")) +
theme(axis.ticks.x = element_blank(),
axis.ticks.y = element_blank()) +
theme_minimal()
</code></pre>
|
[
{
"answer_id": 74645907,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 2,
"selected": false,
"text": "ggplot(df, aes(factor(1), fill = C)) +\n geom_bar(width = 1, colour = NA, show.legend = FALSE, alpha = .8) + \n geom_text(stat = 'count', aes(label = C), size = 6,\n position = position_stack(vjust = 0.5),\n vjust = c(0.5, 0.5, 0.5, 2)) +\n coord_polar(start = pi) +\n labs(x = NULL, y = NULL ) +\n scale_fill_manual(values = c(\"#289045\", \"#beddc7\", \"#d4dfe9\", \"#286291\")) +\n theme_void()\n"
},
{
"answer_id": 74646132,
"author": "stefan",
"author_id": 12993861,
"author_profile": "https://Stackoverflow.com/users/12993861",
"pm_score": 3,
"selected": true,
"text": "geomtextpath library(ggplot2)\nlibrary(geomtextpath)\n\nggplot(df, aes(factor(1), fill = C)) +\n geom_bar(width = 1, colour = NA, show.legend = FALSE, alpha = .8) +\n geom_textpath(aes(x = .5, label = C, group = C),\n stat = \"count\", position = position_stack(vjust = .5),\n vjust = 1\n ) +\n coord_polar() +\n labs(\n x = \"\",\n y = \"\"\n ) +\n scale_fill_manual(values = c(\"#289045\", \"#beddc7\", \"#d4dfe9\", \"#286291\")) +\n theme_void()\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7389241/"
] |
74,645,811
|
<p>I have frames of a video taken from a microscope. I need to crop them to a square inscribed to the circle but the issue is that the circle isn't whole (like in the following image). How can I do it?
<a href="https://i.stack.imgur.com/TUP74.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TUP74.jpg" alt="input image from microscope" /></a></p>
<p>My idea was to use contour finding to get the center of the circle and then find the distance from each point over the whole array of coordinates to the center, take the maximum distance as the radius and find the corners of the square analytically but there must be a better way to do it (also I don't really have a formula to find the corners).</p>
|
[
{
"answer_id": 74647126,
"author": "fmw42",
"author_id": 7355741,
"author_profile": "https://Stackoverflow.com/users/7355741",
"pm_score": 3,
"selected": false,
"text": "import cv2\nimport numpy as np\n\n# read image\nimg = cv2.imread('img.jpg')\nh, w = img.shape[:2]\n\n# threshold so border is black and rest is white (invert as needed). \n# Here I needed to specify the upper threshold at 20 as your black is not pure black.\n\nlower = (0,0,0)\nupper = (20,20,20)\nmask = cv2.inRange(img, lower, upper)\nmask = 255 - mask\n\n# define top and left starting coordinates and starting width and height\ntop = 0\nleft = 0\nbottom = h\nright = w\n\n# compute the mean of each side of the image and its stop test\nmean_top = np.mean( mask[top:top+1, left:right] )\nmean_left = np.mean( mask[top:bottom, left:left+1] )\nmean_bottom = np.mean( mask[bottom-1:bottom, left:right] )\nmean_right = np.mean( mask[top:bottom, right-1:right] )\n\nmean_minimum = min(mean_top, mean_left, mean_bottom, mean_right)\n\ntop_test = \"stop\" if (mean_top == 255) else \"go\"\nleft_test = \"stop\" if (mean_left == 255) else \"go\"\nbottom_test = \"stop\" if (mean_bottom == 255) else \"go\"\nright_test = \"stop\" if (mean_right == 255) else \"go\"\n\n# iterate to compute new side coordinates if mean of given side is not 255 (all white) and it is the current darkest side\nwhile top_test == \"go\" or left_test == \"go\" or right_test == \"go\" or bottom_test == \"go\":\n\n # top processing\n if top_test == \"go\":\n if mean_top != 255:\n if mean_top == mean_minimum:\n top += 1\n mean_top = np.mean( mask[top:top+1, left:right] )\n mean_left = np.mean( mask[top:bottom, left:left+1] )\n mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )\n mean_right = np.mean( mask[top:bottom, right-1:right] )\n mean_minimum = min(mean_top, mean_left, mean_right, mean_bottom)\n #print(\"top\",mean_top)\n continue\n else:\n top_test = \"stop\" \n\n # left processing\n if left_test == \"go\":\n if mean_left != 255:\n if mean_left == mean_minimum:\n left += 1\n mean_top = np.mean( mask[top:top+1, left:right] )\n mean_left = np.mean( mask[top:bottom, left:left+1] )\n mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )\n mean_right = np.mean( mask[top:bottom, right-1:right] )\n mean_minimum = min(mean_top, mean_left, mean_right, mean_bottom)\n #print(\"left\",mean_left)\n continue\n else:\n left_test = \"stop\" \n\n # bottom processing\n if bottom_test == \"go\":\n if mean_bottom != 255:\n if mean_bottom == mean_minimum:\n bottom -= 1\n mean_top = np.mean( mask[top:top+1, left:right] )\n mean_left = np.mean( mask[top:bottom, left:left+1] )\n mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )\n mean_right = np.mean( mask[top:bottom, right-1:right] )\n mean_minimum = min(mean_top, mean_left, mean_right, mean_bottom)\n #print(\"bottom\",mean_bottom)\n continue\n else:\n bottom_test = \"stop\" \n\n # right processing\n if right_test == \"go\":\n if mean_right != 255:\n if mean_right == mean_minimum:\n right -= 1\n mean_top = np.mean( mask[top:top+1, left:right] )\n mean_left = np.mean( mask[top:bottom, left:left+1] )\n mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )\n mean_right = np.mean( mask[top:bottom, right-1:right] )\n mean_minimum = min(mean_top, mean_left, mean_right, mean_bottom)\n #print(\"right\",mean_right)\n continue\n else:\n right_test = \"stop\" \n\n\n# crop input\nresult = img[top:bottom, left:right]\n\n# print crop values \nprint(\"top: \",top)\nprint(\"bottom: \",bottom)\nprint(\"left: \",left)\nprint(\"right: \",right)\nprint(\"height:\",result.shape[0])\nprint(\"width:\",result.shape[1])\n\n# save cropped image\n#cv2.imwrite('border_image1_cropped.png',result)\ncv2.imwrite('img_cropped.png',result)\ncv2.imwrite('img_mask.png',mask)\n\n# show the images\ncv2.imshow(\"mask\", mask)\ncv2.imshow(\"cropped\", result)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n"
},
{
"answer_id": 74648346,
"author": "Dan Mašek",
"author_id": 3962537,
"author_profile": "https://Stackoverflow.com/users/3962537",
"pm_score": 3,
"selected": true,
"text": "img = cv2.imread('TUP74.jpg', cv2.IMREAD_COLOR)\nheight, width = img.shape[:2]\n 31 img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n_, thresh = cv2.threshold(img_gray, 31, 255, cv2.THRESH_BINARY)\n first_yd last_yd cv2.reduce cv2.findNonZero reduced = cv2.reduce(thresh, 1, cv2.REDUCE_MAX)\nrow_info = cv2.findNonZero(reduced)\nfirst_yd, last_yd = row_info[0][0][1], row_info[-1][0][1]\n d r r = d/2 center_y diameter = last_yd - first_yd\nradius = int(diameter / 2)\ncenter_y = first_yd + radius\n center_x c first_yc last_yc cv2.findNonZero row_info = cv2.findNonZero(thresh[:,0])\nfirst_yc, last_yc = row_info[0][0][1], row_info[-1][0][1]\n\nc = last_yc - first_yc\n c o r center_x = int(math.sqrt(radius**2 - (c/2)**2))\n r s s = int(math.sqrt(2) * radius)\n s/2 half_s = int(s/2)\ntl = (center_x - half_s, center_y - half_s)\nbr = (center_x + half_s, center_y + half_s)\n Circle diameter = 1167 pixels\nCircle radius = 583 pixels\nCircle center = (404,1089)\nInscribed square side = 824 pixels\nInscribed square top-left = (-8,677)\nInscribed square bottom-right = (816,1501)\n crop_left = max(tl[0], 0)\ncrop_top = max(tl[1], 0) # Kinda redundant, but why not\ncrop_right = min(br[0], width)\ncrop_bottom = min(br[1], height) # ditto\n\ncropped = img[crop_top:crop_bottom, crop_left:crop_right]\n import cv2\nimport numpy as np\nimport math\n\nimg = cv2.imread('TUP74.jpg', cv2.IMREAD_COLOR)\nheight, width = img.shape[:2]\n\nimg_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n_, thresh = cv2.threshold(img_gray, 31, 255, cv2.THRESH_BINARY)\n\n# Find top/bottom of the circle, to determine radius and center\nreduced = cv2.reduce(thresh, 1, cv2.REDUCE_MAX)\nrow_info = cv2.findNonZero(reduced)\nfirst_yd, last_yd = row_info[0][0][1], row_info[-1][0][1]\n\ndiameter = last_yd - first_yd\nradius = int(diameter / 2)\ncenter_y = first_yd + radius\n\n# Repeat again, just on first column, to find length of a chord of the circle\nrow_info = cv2.findNonZero(thresh[:,0])\nfirst_yc, last_yc = row_info[0][0][1], row_info[-1][0][1]\n\nc = last_yc - first_yc\n\n# Apply Pythagoras theorem to find the X offset of the center from the chord\n# Since the chord is in row 0, this is also the X coordinate\ncenter_x = int(math.sqrt(radius**2 - (c/2)**2))\n\n# Find length of the side of the inscribed square (Pythagoras again)\ns = int(math.sqrt(2) * radius)\n\n# Now find the top-left and bottom-right corners of the square\nhalf_s = int(s/2)\ntl = (center_x - half_s, center_y - half_s)\nbr = (center_x + half_s, center_y + half_s)\n\n# Let's print out what we found\nprint(\"Circle diameter = %d pixels\" % diameter)\nprint(\"Circle radius = %d pixels\" % radius)\nprint(\"Circle center = (%d,%d)\" % (center_x, center_y))\nprint(\"Inscribed square side = %d pixels\" % s)\nprint(\"Inscribed square top-left = (%d,%d)\" % tl)\nprint(\"Inscribed square bottom-right = (%d,%d)\" % br)\n\n# And visualize it...\nvis = img.copy()\ncv2.line(vis, (center_x-5,center_y), (center_x+5,center_y), (0,255,0), 3)\ncv2.line(vis, (center_x,center_y-5), (center_x,center_y+5), (0,255,0), 3)\ncv2.circle(vis, (center_x,center_y), radius, (0,0,255), 3)\ncv2.rectangle(vis, tl, br, (255,0,0), 3)\n\n# Write some illustration images\ncv2.imwrite('circ_thresh.png', thresh)\ncv2.imwrite('circ_vis.png', vis)\n\n# Time to do some cropping, but we need to make sure the coordinates are inside the bounds of the image\ncrop_left = max(tl[0], 0)\ncrop_top = max(tl[1], 0) # Kinda redundant, but why not\ncrop_right = min(br[0], width)\ncrop_bottom = min(br[1], height) # ditto\n\ncropped = img[crop_top:crop_bottom, crop_left:crop_right]\ncv2.imwrite('circ_cropped.png', cropped)\n"
},
{
"answer_id": 74650065,
"author": "fana",
"author_id": 18362054,
"author_profile": "https://Stackoverflow.com/users/18362054",
"pm_score": 0,
"selected": false,
"text": "minEnclosingCircle()"
},
{
"answer_id": 74670136,
"author": "fmw42",
"author_id": 7355741,
"author_profile": "https://Stackoverflow.com/users/7355741",
"pm_score": 1,
"selected": false,
"text": "import cv2\nimport numpy as np\nimport math\n\nimg = cv2.imread('img_circle.jpg')\nheight, width = img.shape[:2]\n\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\nthresh = cv2.threshold(gray, 31, 255, cv2.THRESH_BINARY)[1]\n\n# Find top/bottom of the circle, to determine radius and y coordinate center\nreduced = cv2.reduce(thresh, 1, cv2.REDUCE_MAX)\nrow_info = cv2.findNonZero(reduced)\nfirst_yd, last_yd = row_info[0][0][1], row_info[-1][0][1]\n\ndiameter = last_yd - first_yd\nradius = int(diameter / 2)\ncenter_y = first_yd + radius\n\n# count non-zero pixels in columns to find the column with the largest count\n# that will give us the x coordinate center\ncol_counts = np.count_nonzero(thresh, axis=0)\nmax_counts = np.amax(col_counts)\n\n# find index (x-coordinate) where col_counts=max_counts\nmax_coords = np.argwhere(col_counts==max_counts)\n\n# get number of max values in case more than one\nnum_max = len(max_coords)\n\n# compute center_y\ncenter_x = max_coords[0][0] + num_max//2\n\nprint(\"radius:\", radius, \"center_x:\", center_x, \"center_y:\", center_y)\nprint('')\n radius: 583 center_x: 388 center_y: 1089\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18992886/"
] |
74,645,817
|
<p>I am trying to assert vallue's in a requestbody which I have intercepted with cypress.</p>
<p>The values I need to assert are <strong>"name": "NewName",</strong> and "<strong>title": "STUB1-Draft"</strong> you can see in the requestbody example that I have attached.</p>
<p>My testscript in Cypress:</p>
<pre class="lang-js prettyprint-override"><code> it.only('Check the requestbody', function () {
cy.intercept('PUT', '**/api/assessmenttest/**', req => {
req.reply({ statusCode: 200 });
}).as('NewSectionAndItem');
cy.wait('@NewSectionAndItem')
.its('request.body.test')
.its('testParts')
.its('testSections')
.its('name')
.should('include', 'NewName');
//cy.wait('@NewSectionAndItem').its('request.body.testParts').expect(arr_obj[1].name).to.equal('NewName')
</code></pre>
<p>The request body look like the following:</p>
<pre><code>{
"structureStatistics": {
"testPartCount": 1,
"testSectionCount": 6,
"itemCount": 23
},
"name": "BIMMA",
"title": "OTAP",
"correctionInstructionsUrl": "C:Stub/FakePath/For/Cypress",
"correctionInstructionAppendices": [],
"testParts": [
{
"testSections": [
{
"order": 1,
"name": "Tekst 1 Looking for the one? ",
"itemReferences": [
{
"itemId": "55eb5a28-24d8-4705-b465-8e1454f73ac8",
"weight": 11,
"neutralisationType": "NoNeutralisation",
"itemSummary": {
"id": "55eb5a28-24d8-4705-b465-8e1454f73ac8",
"title": "H-E-T1-1"
}
}
],
"id": "5c3eef2d-1094-4b9e-84c1-f184956f87fa"
},
{
"id": "ffaebc93-0bf6-4f75-944a-f61345a7be90",
"name": "NewName",
"itemReferences": [
{
"itemId": "58a29037-c92c-48f6-a7c3-a2f94e288992",
"weight": 0,
"neutralisationType": "NoNeutralisation",
"itemSummary": {
"id": "58a29037-c92c-48f6-a7c3-a2f94e288992",
"title": "STUB1-Draft",
"state": "Draft"
}
}
]
},
{
"order": 2,
"name": "Tekst 2 The fruit Iron Ox bears",
"itemReferences": [
{
"itemId": "abfc0811-26c7-4d9d-b3cc-0c920e5af259",
"weight": 2,
"neutralisationType": "NoNeutralisation",
"itemSummary": {
"id": "abfc0811-26c7-4d9d-b3cc-0c920e5af259",
"title": "H-E-T2-2"
}
},
{
"itemId": "3cfda5e0-0d64-44ef-8a4d-21f37484c024",
"weight": 12,
"neutralisationType": "NoNeutralisation",
"itemSummary": {
"id": "3cfda5e0-0d64-44ef-8a4d-21f37484c024",
"title": "H-E-T2-3"
}
},
{
"itemId": "19ba8a53-9755-4beb-8f69-edd107b80230",
"weight": 1,
"neutralisationType": "NoNeutralisation",
"itemSummary": {
"id": "19ba8a53-9755-4beb-8f69-edd107b80230",
"title": "H-E-T2-4"
}
},
{
"itemId": "3f5b7b81-df1f-4f01-8165-cb2226d9044d",
"weight": 1,
"neutralisationType": "NoNeutralisation",
"itemSummary": {
"id": "3f5b7b81-df1f-4f01-8165-cb2226d9044d",
"title": "H-E-T2-5"
}
}
],
"id": "00f7455e-6d7d-4311-80cd-eff45c83ef2c"
},
{
"order": 3,
"name": "Tekst 3 How to live like a tramp",
"itemReferences": [
{
"itemId": "7e2d568c-4cde-4500-9c6b-c09f246155e4",
"weight": 1,
"neutralisationType": "NoNeutralisation",
"itemSummary": {
"id": "7e2d568c-4cde-4500-9c6b-c09f246155e4",
"title": "H-E-T3-6"
}
},
{
"itemId": "87a5bf1c-451a-40b8-802a-53ee842cafcd",
"weight": 1,
"neutralisationType": "NoNeutralisation",
"itemSummary": {
"id": "87a5bf1c-451a-40b8-802a-53ee842cafcd",
"title": "H-E-T3-7"
}
}
],
"id": "390ecc2e-6715-4898-aaea-158e790525a2"
}
],
"navigationMode": "Linear",
"submissionMode": "Individual",
"id": "a546a67c-ac39-4e81-bf03-beb482c920a0"
}
],
"metadataToBePublished": [
"be63002c-dcf8-449f-a0ae-6ba50d4e2712",
"4d70239e-7a6e-47c3-b157-462d6c8c5edc"
],
"created": "2022-07-08T09:00:00+00:00",
"modified": "2022-09-21T23:55:58.6532451+02:00",
"createdBy": {
"id": "a45ea6db-bf04-427d-9354-7081b7592a3d",
"fullName": "Manual Construction"
},
"lastModifiedBy": {
"id": "129a584c-a677-4d9f-b289-019d1815064f",
"fullName": "OZKAN"
},
"id": "300eea01-ee10-4bd9-9356-8aaa933e949c"
}
</code></pre>
<p>I could not figure out how I can assert nested arrays and value's, without using deep.equal for the complete request. Thank you indeed!</p>
|
[
{
"answer_id": 74646217,
"author": "jjhelguero",
"author_id": 17917809,
"author_profile": "https://Stackoverflow.com/users/17917809",
"pm_score": 0,
"selected": false,
"text": "const spok = require('cy-spok')\n// later in your test\ncy.wait('@NewSectionAndItem')\n .its('request.body')\n .should(spok({\n test: {\n testParts: {\n testSections: {\n name: 'NewName',\n title: 'STUB1-Draft'\n }\n }\n }\n });\n"
},
{
"answer_id": 74646787,
"author": "Paolo",
"author_id": 16791505,
"author_profile": "https://Stackoverflow.com/users/16791505",
"pm_score": 3,
"selected": true,
"text": "test testParts testSections cy.wait('@NewSectionAndItem')\n .its('request.body')\n .its('testParts.0')\n .its('testSections.1')\n .its('name')\n .should('include', 'NewName');\n testParts 0 testSection .json"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19285414/"
] |
74,645,823
|
<p>This is a continuation of the previous question. When I continued to work on the site and when I wanted to test the site through "python manage.py runserver" in the C:\mysite\site\miniproject directory, the following error pops up:</p>
<pre><code>C:\Program Files\Python36\lib\site-packages\django\db\models\base.py:321: RuntimeWarning: Model 'blog.post' was already registered. Reloading models is not advised as it can lead to inconsistencies, most notably with related models.
new_class._meta.apps.register_model(new_class._meta.app_label, new_class)
C:\Program Files\Python36\lib\site-packages\django\db\models\base.py:321: RuntimeWarning: Model 'blog.post' was already registered. Reloading models is not advised as it can lead to inconsistencies, most notably with related models.
new_class._meta.apps.register_model(new_class._meta.app_label, new_class)
Watching for file changes with StatReloader
Performing system checks...
Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Program Files\Python36\lib\site-packages\django\urls\conf.py", line 17, in include
urlconf_module, app_name = arg
ValueError: too many values to unpack (expected 2)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "C:\Program Files\Python36\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "C:\Program Files\Python36\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "C:\Program Files\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run
self.check(display_num_errors=True)
File "C:\Program Files\Python36\lib\site-packages\django\core\management\base.py", line 423, in check
databases=databases,
File "C:\Program Files\Python36\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "C:\Program Files\Python36\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "C:\Program Files\Python36\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "C:\Program Files\Python36\lib\site-packages\django\urls\resolvers.py", line 416, in check
for pattern in self.url_patterns:
File "C:\Program Files\Python36\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Program Files\Python36\lib\site-packages\django\urls\resolvers.py", line 602, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Program Files\Python36\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Program Files\Python36\lib\site-packages\django\urls\resolvers.py", line 595, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Program Files\Python36\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 978, in _gcd_import
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File "C:\mysite\site\miniproject\miniproject\urls.py", line 20, in <module>
url(r'^admin/', include(admin.site.urls)),
File "C:\Program Files\Python36\lib\site-packages\django\urls\conf.py", line 27, in include
'provide the namespace argument to include() instead.' % len(arg)
django.core.exceptions.ImproperlyConfigured: Passing a 3-tuple to include() is not supported. Pass a 2-tuple containing the list of patterns and app_name, and provide the namespace argument to include() instead.
</code></pre>
<p>Here is a link to the chapter where I worked: <a href="https://pocoz.gitbooks.io/django-v-primerah/content/sozdanie-shablonov-dlia-view.html" rel="nofollow noreferrer">https://pocoz.gitbooks.io/django-v-primerah/content/sozdanie-shablonov-dlia-view.html</a> , Most likely I made a mistake somewhere. Next, I will show you the contents of the files:</p>
<pre><code>base.html:
{% load static files %}
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link href="{% static "css/blog.css" %}" rel="stylesheet">
</head>
<body>
<div id="content">
{% block content %}
{%endblock%}
</div>
<div id="sidebar">
<h2>My blog</h2>
<p>This is my blog.</p>
</div>
</body>
</html>
list.html:
{% extends "blog/base.html" %}
{% block title %}My Blog{% endblock %}
{% block content %}
<h1>My Blog</h1>
{% for post in posts %}
<h2>
<a href="{{ post.get_absolute_url }}">{{ post.title }}</a>
</h2>
<p class="date">
Published {{ post.publish }} by {{ post.author }}
</p>
{{ post.body|truncatewords:30|linebreaks }}
{% endfor %}
{%endblock%}
detail.html:
{% extends "blog/base.html" %}
{% block title %}{{ post. title }}{% endblock %}
{% block content %}
<h1>{{post.title}}</h1>
<p class="date">
Published {{ post.publish }} by {{ post.author }}
</p>
{{ post.body|linebreaks}}
{%endblock%}
C:\mysite\site\miniproject\blog\views.py:
from django.shortcuts import render, get_object_or_404
from .models import Post
def post_list(request):
posts = Post.published.all()
return render(request, 'blog/post/list.html', {'posts': posts})
def post_detail(request, year, month, day, post):
post = get_object_or_404(Post, slug=post,
status='published',
publish_year=year,
publish__month=month,
publish_day=day)
return render(request,'blog/post/detail.html', {'post': post})
# Create your views here.
C:\mysite\site\miniproject\blog\urls.py:
from django.conf.urls import url
from. import views
urlpatterns = [
# post views
url(r'^$', views.post_list, name='post_list'),
url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/'\
r'(?P<post>[-\w]+)/$',
views.post_detail,
name='post_detail'),
]
C:\mysite\site\miniproject\miniproject\urls.py:
"""miniproject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^blog/', include('blog.urls',
namespace='blog',
app_name='blog')),
]
C:\mysite\site\miniproject\blog\models.py:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.shortcuts import reverse
class Post(models.Model):
def get_absolute_url(self):
return reverse('blog:post_detail',
args=[self.publish.year,
self.publish.strftime('%m'),
self.publish.strftime('%d'),
self.slug])
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique_for_date='publish')
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
# Create your models here.
</code></pre>
<p>I updated the Python libraries and carefully checked everything, read the Django documentation and nothing helped, maybe I inserted the Python code incorrectly</p>
|
[
{
"answer_id": 74654386,
"author": "Bairam",
"author_id": 16885688,
"author_profile": "https://Stackoverflow.com/users/16885688",
"pm_score": 0,
"selected": false,
"text": "from django.shortcuts import reverse"
},
{
"answer_id": 74660846,
"author": "kalkidan Teklu",
"author_id": 14680923,
"author_profile": "https://Stackoverflow.com/users/14680923",
"pm_score": 1,
"selected": false,
"text": "app_name url(r'^blog/', include('blog.urls',\n namespace='blog',\n app_name='blog')), \n url(r'^blog/', include('blog.urls', \"blog\", namespace='blog'),\n def include(arg, namespace=None):\n app_name = None\n if isinstance(arg, tuple):\n # Callable returning a namespace hint.\n try:\n urlconf_module, app_name = arg\n except ValueError:\n if namespace:\n raise ImproperlyConfigured(\n \"Cannot override the namespace for a dynamic module that \"\n \"provides a namespace.\"\n )\n raise ImproperlyConfigured(\n \"Passing a %d-tuple to include() is not supported. Pass a \"\n \"2-tuple containing the list of patterns and app_name, and \"\n \"provide the namespace argument to include() instead.\" % len(arg)\n )\n else:\n # No namespace hint - use manually provided namespace.\n urlconf_module = arg\n ...\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19350769/"
] |
74,645,839
|
<p>How would one go about creating a script for creating 25 empty files in succession? (I.e 1-25, 26-51, 52-77)</p>
<p>I can create files 1-25 but I’m having trouble figuring out how to create a script that continues that process from where it left off, every time I run the script.</p>
|
[
{
"answer_id": 74654386,
"author": "Bairam",
"author_id": 16885688,
"author_profile": "https://Stackoverflow.com/users/16885688",
"pm_score": 0,
"selected": false,
"text": "from django.shortcuts import reverse"
},
{
"answer_id": 74660846,
"author": "kalkidan Teklu",
"author_id": 14680923,
"author_profile": "https://Stackoverflow.com/users/14680923",
"pm_score": 1,
"selected": false,
"text": "app_name url(r'^blog/', include('blog.urls',\n namespace='blog',\n app_name='blog')), \n url(r'^blog/', include('blog.urls', \"blog\", namespace='blog'),\n def include(arg, namespace=None):\n app_name = None\n if isinstance(arg, tuple):\n # Callable returning a namespace hint.\n try:\n urlconf_module, app_name = arg\n except ValueError:\n if namespace:\n raise ImproperlyConfigured(\n \"Cannot override the namespace for a dynamic module that \"\n \"provides a namespace.\"\n )\n raise ImproperlyConfigured(\n \"Passing a %d-tuple to include() is not supported. Pass a \"\n \"2-tuple containing the list of patterns and app_name, and \"\n \"provide the namespace argument to include() instead.\" % len(arg)\n )\n else:\n # No namespace hint - use manually provided namespace.\n urlconf_module = arg\n ...\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20658725/"
] |
74,645,840
|
<p>I have this data</p>
<pre><code>dw <- structure(list(ccssid = c(1000023L, 1000043L), base.age = c("22",
"27"), fu1.age = c("30", "35"), fu2.age = c("33", "37"), fu3.age = c("35",
"40"), fu7.age = c("38", "42"), fu5.age = c("44", "49"), fu6.age = c("48",
"52"), base.bmi = c("25.1421", "21.6333"), fu2.bmi = c("25.7959",
"23.5078"), fu7.bmi = c("25.105", "24.961"), fu5.bmi = c("24.366",
"24.961"), fu2.MET = c("150", "0"), fu2.CDC = c("Yes", "No"),
fu5.MET = c("360", "120"), fu5.CDC = c("Yes", "No"), fu6.MET = c(NA_character_,
NA_character_), fu6.CDC = c(NA_character_, NA_character_),
base.smk = c(NA, "1"), fu2.smk = c("2", "1"), fu7.smk = c("2",
"1"), fu5.smk = c("2", "1"), base.riskydrk = c(NA, "No"),
fu7.riskydrk = c("Yes", "Yes"), fu5.riskydrk = c("No", "No"
), base.MET = c(NA, NA), base.CDC = c(NA, NA), fu1.bmi = c(NA,
NA), fu1.MET = c(NA, NA), fu1.CDC = c(NA, NA), fu1.smk = c(NA,
NA), fu1.riskydrk = c(NA, NA), fu2.riskydrk = c(NA, NA),
fu3.bmi = c(NA, NA), fu3.MET = c(NA, NA), fu3.CDC = c(NA,
NA), fu3.smk = c(NA, NA), fu3.riskydrk = c(NA, NA), fu7.MET = c(NA,
NA), fu7.CDC = c(NA, NA), fu6.bmi = c(NA, NA), fu6.smk = c(NA,
NA), fu6.riskydrk = c(NA, NA)), row.names = 1:2, class = "data.frame")
</code></pre>
<p>I tried this code below to transform this data, but I am not sure why the values of <code>riskydrk</code> column are switched with <code>smk</code> column in the output. The <code>smk</code> column should have values 1,2, but somehow, it is switched with the values of <code>riskydrk</code> column. Can someone please help me figure out the issue? Thanks!</p>
<pre><code>reshape(dw, direction='long',
varying=c('base.age', 'base.bmi', "base.MET", 'base.CDC', "base.smk", "base.riskydrk",
'fu1.age', 'fu1.bmi', "fu1.MET", 'fu1.CDC', "fu1.smk", "fu1.riskydrk",
'fu2.age', 'fu2.bmi', "fu2.MET", 'fu2.CDC', "fu2.smk", "fu2.riskydrk",
'fu3.age', 'fu3.bmi', "fu3.MET", 'fu3.CDC', "fu3.smk", "fu3.riskydrk",
'fu7.age', 'fu7.bmi', "fu7.MET", 'fu7.CDC', "fu7.smk", "fu7.riskydrk",
'fu5.age', 'fu5.bmi', "fu5.MET", 'fu5.CDC', "fu5.smk", "fu5.riskydrk",
'fu6.age', 'fu6.bmi', "fu6.MET", 'fu6.CDC', "fu6.smk", "fu6.riskydrk"),
timevar='var',
times=c('base', 'fu1', 'fu2', 'fu3', 'fu7', 'fu5', 'fu6'),
v.names=c('age', 'bmi', 'MET', 'CDC', 'smk', 'riskydrk'),
idvar='ccssid')
</code></pre>
<p>The desired output should be like this:</p>
<p><a href="https://i.stack.imgur.com/XKS8x.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XKS8x.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74646211,
"author": "jay.sf",
"author_id": 6574038,
"author_profile": "https://Stackoverflow.com/users/6574038",
"pm_score": 3,
"selected": true,
"text": "reshape ## make prefixes to suffixes\nnames(dw) <- strsplit(names(dw), '\\\\.') |> lapply(rev) |> sapply(paste, collapse='.')\n\nreshape(dw, direction='l', idvar='ccssid', varying=sort(names(dw)[-1]))\n# ccssid time age bmi CDC MET riskydrk smk\n# 1000023.base 1000023 base 22 25.1421 <NA> <NA> <NA> <NA>\n# 1000043.base 1000043 base 27 21.6333 <NA> <NA> No 1\n# 1000023.fu1 1000023 fu1 30 <NA> <NA> <NA> <NA> <NA>\n# 1000043.fu1 1000043 fu1 35 <NA> <NA> <NA> <NA> <NA>\n# 1000023.fu2 1000023 fu2 33 25.7959 Yes 150 <NA> 2\n# 1000043.fu2 1000043 fu2 37 23.5078 No 0 <NA> 1\n# 1000023.fu3 1000023 fu3 35 <NA> <NA> <NA> <NA> <NA>\n# 1000043.fu3 1000043 fu3 40 <NA> <NA> <NA> <NA> <NA>\n# 1000023.fu5 1000023 fu5 44 24.366 Yes 360 No 2\n# 1000043.fu5 1000043 fu5 49 24.961 No 120 No 1\n# 1000023.fu6 1000023 fu6 48 <NA> <NA> <NA> <NA> <NA>\n# 1000043.fu6 1000043 fu6 52 <NA> <NA> <NA> <NA> <NA>\n# 1000023.fu7 1000023 fu7 38 25.105 <NA> <NA> Yes 2\n# 1000043.fu7 1000043 fu7 42 24.961 <NA> <NA> Yes 1\n"
},
{
"answer_id": 74646264,
"author": "Rui Barradas",
"author_id": 8245406,
"author_profile": "https://Stackoverflow.com/users/8245406",
"pm_score": 2,
"selected": false,
"text": "dplyr tidyr tidyr suppressPackageStartupMessages({\n library(tidyr)\n})\n\ndw |>\n pivot_longer(\n cols = -ccssid,\n names_to = c(\"var\", \".value\"),\n names_pattern = \"(.*)\\\\.(.*)\"\n )\n#> # A tibble: 14 × 8\n#> ccssid var age bmi MET CDC smk riskydrk\n#> <int> <chr> <chr> <chr> <chr> <chr> <chr> <chr> \n#> 1 1000023 base 22 25.1421 <NA> <NA> <NA> <NA> \n#> 2 1000023 fu1 30 <NA> <NA> <NA> <NA> <NA> \n#> 3 1000023 fu2 33 25.7959 150 Yes 2 <NA> \n#> 4 1000023 fu3 35 <NA> <NA> <NA> <NA> <NA> \n#> 5 1000023 fu7 38 25.105 <NA> <NA> 2 Yes \n#> 6 1000023 fu5 44 24.366 360 Yes 2 No \n#> 7 1000023 fu6 48 <NA> <NA> <NA> <NA> <NA> \n#> 8 1000043 base 27 21.6333 <NA> <NA> 1 No \n#> 9 1000043 fu1 35 <NA> <NA> <NA> <NA> <NA> \n#> 10 1000043 fu2 37 23.5078 0 No 1 <NA> \n#> 11 1000043 fu3 40 <NA> <NA> <NA> <NA> <NA> \n#> 12 1000043 fu7 42 24.961 <NA> <NA> 1 Yes \n#> 13 1000043 fu5 49 24.961 120 No 1 No \n#> 14 1000043 fu6 52 <NA> <NA> <NA> <NA> <NA>\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4701887/"
] |
74,645,846
|
<p>In Pandas I can do the following:</p>
<pre><code>data = pd.DataFrame(
{
"era": ["01", "01", "02", "02", "03", "10"],
"pred1": [1, 2, 3, 4, 5,6],
"pred2": [2,4,5,6,7,8],
"pred3": [3,5,6,8,9,1],
"something_else": [5,4,3,67,5,4],
})
pred_cols = ["pred1", "pred2", "pred3"]
ERA_COL = "era"
DOWNSAMPLE_CROSS_VAL = 10
test_split = ['01', '02', '10']
test_split_index = data[ERA_COL].isin(test_split)
downsampled_train_split_index = train_split_index[test_split_index].index[::DOWNSAMPLE_CROSS_VAL]
data.loc[test_split_index, "pred1"] = somefunction()["another_column"]
</code></pre>
<p>How can I achieve the same in Polars? I tried to do some <code>data.filter(****) = somefunction()["another_column"]</code>, but the <code>filter</code> output is not assignable with Polars.</p>
|
[
{
"answer_id": 74646211,
"author": "jay.sf",
"author_id": 6574038,
"author_profile": "https://Stackoverflow.com/users/6574038",
"pm_score": 3,
"selected": true,
"text": "reshape ## make prefixes to suffixes\nnames(dw) <- strsplit(names(dw), '\\\\.') |> lapply(rev) |> sapply(paste, collapse='.')\n\nreshape(dw, direction='l', idvar='ccssid', varying=sort(names(dw)[-1]))\n# ccssid time age bmi CDC MET riskydrk smk\n# 1000023.base 1000023 base 22 25.1421 <NA> <NA> <NA> <NA>\n# 1000043.base 1000043 base 27 21.6333 <NA> <NA> No 1\n# 1000023.fu1 1000023 fu1 30 <NA> <NA> <NA> <NA> <NA>\n# 1000043.fu1 1000043 fu1 35 <NA> <NA> <NA> <NA> <NA>\n# 1000023.fu2 1000023 fu2 33 25.7959 Yes 150 <NA> 2\n# 1000043.fu2 1000043 fu2 37 23.5078 No 0 <NA> 1\n# 1000023.fu3 1000023 fu3 35 <NA> <NA> <NA> <NA> <NA>\n# 1000043.fu3 1000043 fu3 40 <NA> <NA> <NA> <NA> <NA>\n# 1000023.fu5 1000023 fu5 44 24.366 Yes 360 No 2\n# 1000043.fu5 1000043 fu5 49 24.961 No 120 No 1\n# 1000023.fu6 1000023 fu6 48 <NA> <NA> <NA> <NA> <NA>\n# 1000043.fu6 1000043 fu6 52 <NA> <NA> <NA> <NA> <NA>\n# 1000023.fu7 1000023 fu7 38 25.105 <NA> <NA> Yes 2\n# 1000043.fu7 1000043 fu7 42 24.961 <NA> <NA> Yes 1\n"
},
{
"answer_id": 74646264,
"author": "Rui Barradas",
"author_id": 8245406,
"author_profile": "https://Stackoverflow.com/users/8245406",
"pm_score": 2,
"selected": false,
"text": "dplyr tidyr tidyr suppressPackageStartupMessages({\n library(tidyr)\n})\n\ndw |>\n pivot_longer(\n cols = -ccssid,\n names_to = c(\"var\", \".value\"),\n names_pattern = \"(.*)\\\\.(.*)\"\n )\n#> # A tibble: 14 × 8\n#> ccssid var age bmi MET CDC smk riskydrk\n#> <int> <chr> <chr> <chr> <chr> <chr> <chr> <chr> \n#> 1 1000023 base 22 25.1421 <NA> <NA> <NA> <NA> \n#> 2 1000023 fu1 30 <NA> <NA> <NA> <NA> <NA> \n#> 3 1000023 fu2 33 25.7959 150 Yes 2 <NA> \n#> 4 1000023 fu3 35 <NA> <NA> <NA> <NA> <NA> \n#> 5 1000023 fu7 38 25.105 <NA> <NA> 2 Yes \n#> 6 1000023 fu5 44 24.366 360 Yes 2 No \n#> 7 1000023 fu6 48 <NA> <NA> <NA> <NA> <NA> \n#> 8 1000043 base 27 21.6333 <NA> <NA> 1 No \n#> 9 1000043 fu1 35 <NA> <NA> <NA> <NA> <NA> \n#> 10 1000043 fu2 37 23.5078 0 No 1 <NA> \n#> 11 1000043 fu3 40 <NA> <NA> <NA> <NA> <NA> \n#> 12 1000043 fu7 42 24.961 <NA> <NA> 1 Yes \n#> 13 1000043 fu5 49 24.961 120 No 1 No \n#> 14 1000043 fu6 52 <NA> <NA> <NA> <NA> <NA>\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/865662/"
] |
74,645,899
|
<p>I am tring to learn python and want to know if i can do this, and how. I am trying to make binary looking code come up digit by digit, with delay.
In maybe there is 15 numbers, and each repeat i would like to make it do a set of 5, with a space after.</p>
<pre><code>if answer == 'MAYBE':
deleteall()
print("GIVE ME AN ANSWER!!!")
time.sleep(1)
deletelastline()
for x in maybe:
print(random.choice("1" "0"))
time.sleep(0.1)
print(random.choice("1" "0"))
time.sleep(0.1)
print(random.choice("1" "0"))
time.sleep(0.1)
print(random.choice("1" "0"))
time.sleep(0.1)
print(random.choice("1" "0"))
time.sleep(0.1)
print(" ")
</code></pre>
<p>However, it outputs this:</p>
<pre><code>0
1
1
0
0
1
0
0
0
1
1
</code></pre>
<p>ext.</p>
<p>How do i get them on one line?!?
Thx</p>
|
[
{
"answer_id": 74646211,
"author": "jay.sf",
"author_id": 6574038,
"author_profile": "https://Stackoverflow.com/users/6574038",
"pm_score": 3,
"selected": true,
"text": "reshape ## make prefixes to suffixes\nnames(dw) <- strsplit(names(dw), '\\\\.') |> lapply(rev) |> sapply(paste, collapse='.')\n\nreshape(dw, direction='l', idvar='ccssid', varying=sort(names(dw)[-1]))\n# ccssid time age bmi CDC MET riskydrk smk\n# 1000023.base 1000023 base 22 25.1421 <NA> <NA> <NA> <NA>\n# 1000043.base 1000043 base 27 21.6333 <NA> <NA> No 1\n# 1000023.fu1 1000023 fu1 30 <NA> <NA> <NA> <NA> <NA>\n# 1000043.fu1 1000043 fu1 35 <NA> <NA> <NA> <NA> <NA>\n# 1000023.fu2 1000023 fu2 33 25.7959 Yes 150 <NA> 2\n# 1000043.fu2 1000043 fu2 37 23.5078 No 0 <NA> 1\n# 1000023.fu3 1000023 fu3 35 <NA> <NA> <NA> <NA> <NA>\n# 1000043.fu3 1000043 fu3 40 <NA> <NA> <NA> <NA> <NA>\n# 1000023.fu5 1000023 fu5 44 24.366 Yes 360 No 2\n# 1000043.fu5 1000043 fu5 49 24.961 No 120 No 1\n# 1000023.fu6 1000023 fu6 48 <NA> <NA> <NA> <NA> <NA>\n# 1000043.fu6 1000043 fu6 52 <NA> <NA> <NA> <NA> <NA>\n# 1000023.fu7 1000023 fu7 38 25.105 <NA> <NA> Yes 2\n# 1000043.fu7 1000043 fu7 42 24.961 <NA> <NA> Yes 1\n"
},
{
"answer_id": 74646264,
"author": "Rui Barradas",
"author_id": 8245406,
"author_profile": "https://Stackoverflow.com/users/8245406",
"pm_score": 2,
"selected": false,
"text": "dplyr tidyr tidyr suppressPackageStartupMessages({\n library(tidyr)\n})\n\ndw |>\n pivot_longer(\n cols = -ccssid,\n names_to = c(\"var\", \".value\"),\n names_pattern = \"(.*)\\\\.(.*)\"\n )\n#> # A tibble: 14 × 8\n#> ccssid var age bmi MET CDC smk riskydrk\n#> <int> <chr> <chr> <chr> <chr> <chr> <chr> <chr> \n#> 1 1000023 base 22 25.1421 <NA> <NA> <NA> <NA> \n#> 2 1000023 fu1 30 <NA> <NA> <NA> <NA> <NA> \n#> 3 1000023 fu2 33 25.7959 150 Yes 2 <NA> \n#> 4 1000023 fu3 35 <NA> <NA> <NA> <NA> <NA> \n#> 5 1000023 fu7 38 25.105 <NA> <NA> 2 Yes \n#> 6 1000023 fu5 44 24.366 360 Yes 2 No \n#> 7 1000023 fu6 48 <NA> <NA> <NA> <NA> <NA> \n#> 8 1000043 base 27 21.6333 <NA> <NA> 1 No \n#> 9 1000043 fu1 35 <NA> <NA> <NA> <NA> <NA> \n#> 10 1000043 fu2 37 23.5078 0 No 1 <NA> \n#> 11 1000043 fu3 40 <NA> <NA> <NA> <NA> <NA> \n#> 12 1000043 fu7 42 24.961 <NA> <NA> 1 Yes \n#> 13 1000043 fu5 49 24.961 120 No 1 No \n#> 14 1000043 fu6 52 <NA> <NA> <NA> <NA> <NA>\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20658624/"
] |
74,645,900
|
<p>I have example data as follows:</p>
<pre><code>library(data.table)
dat <- fread("Survey Variable_codes_2022
D D1
A A1
B B1
B B3
B B2
E E1
B NA
E NA")
</code></pre>
<p>For the two rows that have <code>Variable_codes_2022==NA</code>, I would like to increment the variable code so that it becomes:</p>
<pre><code>dat <- fread("Survey Variable_codes_2022
D D1
A A1
B B1
B B3
B B2
E E1
B B4
E E2"
</code></pre>
<p>Because the column <code>Variable_codes_2022</code> is a string variable, the numbers are not in numerical order.</p>
<p>I have no idea where to start and I was wondering if someone could help me on the right track.</p>
|
[
{
"answer_id": 74646032,
"author": "Vinícius Félix",
"author_id": 9696037,
"author_profile": "https://Stackoverflow.com/users/9696037",
"pm_score": 1,
"selected": false,
"text": "dat <- \nstructure(list(survey = c(\"D\", \"A\", \"B\", \"B\", \"B\", \"E\", \"B\", \n\"E\", \"B\"), var_code = c(\"D1\", \"A1\", \"B1\", \"B3\", \"B2\", \"E1\", NA, \nNA, NA)), row.names = c(NA, -9L), class = c(\"data.table\", \"data.frame\"\n), .internal.selfref = <pointer: 0x0000026db10f1ef0>)\n\nlibrary(dplyr)\nlibrary(stringr)\n\ndat %>% \n group_by(survey) %>% \n mutate(\n aux1 = as.numeric(stringr::str_remove(var_code,survey)),\n aux2 = cumsum(is.na(var_code)),\n var_code = paste0(survey,max(aux1,na.rm = TRUE)+aux2)\n ) %>% \n ungroup() %>% \n select(-aux1,-aux2)\n\n# A tibble: 9 x 2\n survey var_code\n <chr> <chr> \n1 D D1 \n2 A A1 \n3 B B3 \n4 B B3 \n5 B B3 \n6 E E1 \n7 B B4 \n8 E E2 \n9 B B5 \n"
},
{
"answer_id": 74646154,
"author": "Ric Villalba",
"author_id": 6912817,
"author_profile": "https://Stackoverflow.com/users/6912817",
"pm_score": 1,
"selected": false,
"text": "rowid library(data.table)\n#> Warning: package 'data.table' was built under R version 4.2.2\ndat <- fread(\"Survey Variable_codes_2022\n D D1\n A A1\n B B1\n B B3\n B B2\n E E1\n B NA\n E NA\n E NA\")\n\ndat[, n := as.numeric(substr(\n Variable_codes_2022, nchar(Survey)+1, nchar(Variable_codes_2022)))]\n\ndat[is.na(n),\n Variable_codes_2022 := paste0(Survey, rowid(Survey) + \n dat[.SD[,.(Survey)], .(m=max(n, na.rm=T)), on = \"Survey\", by=.EACHI ][,m])]\n\ndat \n#> Survey Variable_codes_2022 n\n#> 1: D D1 1\n#> 2: A A1 1\n#> 3: B B1 1\n#> 4: B B3 3\n#> 5: B B2 2\n#> 6: E E1 1\n#> 7: B B4 NA\n#> 8: E E2 NA\n#> 9: E E3 NA\n"
},
{
"answer_id": 74646183,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 2,
"selected": false,
"text": "mutate library(dplyr)\n\ndat %>% \n group_by(Survey) %>% \n arrange(.by_group = TRUE) %>% \n mutate(Variable_codes_2022 = paste0(Survey, row_number()))\n Survey Variable_codes_2022\n <chr> <chr> \n1 A A1 \n2 B B1 \n3 B B2 \n4 B B3 \n5 B B4 \n6 D D1 \n7 E E1 \n8 E E2 \n"
},
{
"answer_id": 74646945,
"author": "Quinten",
"author_id": 14282714,
"author_profile": "https://Stackoverflow.com/users/14282714",
"pm_score": 2,
"selected": false,
"text": "data.table rleid library(data.table)\ndat[, Variable_codes_2022 := paste0(Survey, rleid(Variable_codes_2022)), by = Survey]\ndat\n#> Survey Variable_codes_2022\n#> 1: D D1\n#> 2: A A1\n#> 3: B B1\n#> 4: B B2\n#> 5: B B3\n#> 6: E E1\n#> 7: B B4\n#> 8: E E2\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8071608/"
] |
74,645,909
|
<p>I can get the current date using</p>
<pre><code> Instant.now()
</code></pre>
<p>I am looking to get <code>18-<current month>-<current year></code></p>
|
[
{
"answer_id": 74646048,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 2,
"selected": false,
"text": "YearMonth // Represents a year and month only, no day of month. \n.now( \n ZoneId.of( \"America/Edmonton\" ) // Returns a `ZoneId` object. \n)\n.atDay( 18 ) // Returns a `LocalDate` object. \n.format(\n DateTimeFormatter\n .ofPattern( \"dd-MM-uuuu\" )\n) // Returns a `String` object. \n Instant LocalDate YearMonth ZoneId z = ZoneId.of( \"Pacific/Auckland\" ) ;\nYearMonth ym = YearMonth.now( z ) ;\n ZoneOffset.UTC YearMonth ym = YearMonth.now( ZoneOffset.UTC ) ;\n LocalDate ld = ym.atDay( 18 ) ;\n String output = ld.toString() ;\n DateTimeFormatter f = DateTimeFormatter.ofPattern( \"dd-MM-uuuu\" ) ;\nString output = ld.format( f ) ;\n"
},
{
"answer_id": 74646130,
"author": "Saif",
"author_id": 4777670,
"author_profile": "https://Stackoverflow.com/users/4777670",
"pm_score": -1,
"selected": false,
"text": "Instant instant = Instant.now().with(TemporalAdjusters.dayOfMonth(18));\n with TemporalAdjuster Instant Instant with Instant instant = Instant.now()\n .with(TemporalAdjusters.dayOfMonth(18))\n .with(ChronoField.HOUR_OF_DAY, 0);\n Instant"
},
{
"answer_id": 74647180,
"author": "Arvind Kumar Avinash",
"author_id": 10819573,
"author_profile": "https://Stackoverflow.com/users/10819573",
"pm_score": 2,
"selected": false,
"text": "Instant OffsetDateTime public class Main {\n public static void main(String[] args) {\n Instant thisInstantOn18th = OffsetDateTime.now(ZoneOffset.UTC)\n .with(ChronoField.DAY_OF_MONTH, 18)\n .toInstant();\n System.out.println(thisInstantOn18th);\n }\n}\n 2022-12-18T19:19:20.128313Z\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5481621/"
] |
74,645,913
|
<p>I have a go service which receives data from an external service.</p>
<p>The data looks as follows (json)-</p>
<pre class="lang-json prettyprint-override"><code>{
"firstName": "XYZ",
"lastName": "ABC",
"createdAtTimestamp": "Mon Nov 21 2022 17:01:59 GMT+0530 (India Standard Time)"
}
</code></pre>
<p>Note that <code>createdAtTimestamp</code> is the output in format of nodeJS <code>new Date().toString()</code> which does not have any particular RFC format specified.</p>
<p>How do I parse <code>createdAtTimestamp</code> to <code>time</code> in go ?</p>
<p>I tried this but it is failing-</p>
<pre class="lang-golang prettyprint-override"><code>data, _ := time.Parse(time.RFC1123, "Mon Nov 21 2022 17:01:59 GMT+0530 (India Standard Time)")
fmt.Println(data.Format(time.RFC3339))
</code></pre>
|
[
{
"answer_id": 74646048,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 2,
"selected": false,
"text": "YearMonth // Represents a year and month only, no day of month. \n.now( \n ZoneId.of( \"America/Edmonton\" ) // Returns a `ZoneId` object. \n)\n.atDay( 18 ) // Returns a `LocalDate` object. \n.format(\n DateTimeFormatter\n .ofPattern( \"dd-MM-uuuu\" )\n) // Returns a `String` object. \n Instant LocalDate YearMonth ZoneId z = ZoneId.of( \"Pacific/Auckland\" ) ;\nYearMonth ym = YearMonth.now( z ) ;\n ZoneOffset.UTC YearMonth ym = YearMonth.now( ZoneOffset.UTC ) ;\n LocalDate ld = ym.atDay( 18 ) ;\n String output = ld.toString() ;\n DateTimeFormatter f = DateTimeFormatter.ofPattern( \"dd-MM-uuuu\" ) ;\nString output = ld.format( f ) ;\n"
},
{
"answer_id": 74646130,
"author": "Saif",
"author_id": 4777670,
"author_profile": "https://Stackoverflow.com/users/4777670",
"pm_score": -1,
"selected": false,
"text": "Instant instant = Instant.now().with(TemporalAdjusters.dayOfMonth(18));\n with TemporalAdjuster Instant Instant with Instant instant = Instant.now()\n .with(TemporalAdjusters.dayOfMonth(18))\n .with(ChronoField.HOUR_OF_DAY, 0);\n Instant"
},
{
"answer_id": 74647180,
"author": "Arvind Kumar Avinash",
"author_id": 10819573,
"author_profile": "https://Stackoverflow.com/users/10819573",
"pm_score": 2,
"selected": false,
"text": "Instant OffsetDateTime public class Main {\n public static void main(String[] args) {\n Instant thisInstantOn18th = OffsetDateTime.now(ZoneOffset.UTC)\n .with(ChronoField.DAY_OF_MONTH, 18)\n .toInstant();\n System.out.println(thisInstantOn18th);\n }\n}\n 2022-12-18T19:19:20.128313Z\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6451802/"
] |
74,645,915
|
<p>just starting testcontainers. I love the idea. thanks for investing in this project.</p>
<p>I am trying to create a simple postgres 14.5 container (and susceeded) and now I am trying to populate it using the .withInitScript() method.</p>
<p>the file I am feeding into the init method is a dump I created with pg_dumpall.</p>
<p>testcontainers fails for many parsing/validation reasons. each time I delete a portion and another reason pops up.</p>
<p>should I be able to succesfully use the withInitScript with pg_dump files?</p>
<p>BTW, using pg_dump for my main DB also has many similar issues.</p>
<p>thanks!</p>
|
[
{
"answer_id": 74650961,
"author": "Eddú Meléndez",
"author_id": 2203890,
"author_profile": "https://Stackoverflow.com/users/2203890",
"pm_score": 2,
"selected": true,
"text": "BTW, using pg_dump for my main DB also has many similar issues. new PostgreSQLContainer(\"postgres:14.5\")\n .withCopyFileToContainer(\n MountableFile.forClasspathResource(\"init.sql\"), \n \"/docker-entrypoint-initdb.d/init.sql\"\n );\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74645915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1061835/"
] |
74,646,034
|
<p>we had some issues with jenkins docker stages, where they needed to be run with root permissions (args root:root). At this time, I'm not 100% recalling why they made this decision, but I couldn't get around it a few months ago.</p>
<p>The issue we mainly ran into with root:root was that jenkins couldn't clean up after itself, as the docker filesystem was owned by root user.</p>
<p>So, I created created some mascarade commands in my global groovy library</p>
<pre><code>def container_init (myUserId) {
sh( returnStdout: true, script: """/usr/sbin/useradd -u ${myUserId} dummy;""").trim()
}
def command (input) {
sh( returnStdout: true, script: """su dummy -c '${input}';""").trim()
}
</code></pre>
<p>The problem now is that some of these docker_mask.command() are not passing exit code from failed e2e tests or even failed terraform deployments. Some are passing and positively exciting, but it's inconsistent.</p>
<p>Anything I can do to get positive exits?</p>
|
[
{
"answer_id": 74646098,
"author": "Saif",
"author_id": 4777670,
"author_profile": "https://Stackoverflow.com/users/4777670",
"pm_score": -1,
"selected": false,
"text": "root:root root:root root:root jenkins docker.withRegistry"
},
{
"answer_id": 74656784,
"author": "deric4",
"author_id": 4526019,
"author_profile": "https://Stackoverflow.com/users/4526019",
"pm_score": 2,
"selected": false,
"text": "su 0 dummy su dummy -c '${input}; exit $?'\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74646034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1255642/"
] |
74,646,040
|
<p>I'm writing a program that creates instances of EC2 on AWS. The names of the instances are "Manager" and "Worker", and for some unknown reason, in some of the runs, an instance with the name "-" is created (just a dash). Has anyone experienced something similar?</p>
<p><img src="https://i.stack.imgur.com/EpFFN.jpg" alt="The instances that were created" /></p>
|
[
{
"answer_id": 74646098,
"author": "Saif",
"author_id": 4777670,
"author_profile": "https://Stackoverflow.com/users/4777670",
"pm_score": -1,
"selected": false,
"text": "root:root root:root root:root jenkins docker.withRegistry"
},
{
"answer_id": 74656784,
"author": "deric4",
"author_id": 4526019,
"author_profile": "https://Stackoverflow.com/users/4526019",
"pm_score": 2,
"selected": false,
"text": "su 0 dummy su dummy -c '${input}; exit $?'\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74646040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20658759/"
] |
74,646,052
|
<p>Given the following table with purchase data.</p>
<pre><code>CREATE TABLE myTable (
id INT NOT NULL AUTO_INCREMENT,
date DATETIME NOT NULL,
subNo SMALLINT NOT NULL,
poNo INT NOT NULL,
PRIMARY KEY (id))
INSERT INTO myTable VALUES (0, '2022-11-01 12:43', 1, 800), (0, '2022-11-02 13:00', 1, 800), (0, '2022-11-03 12:43', 2, 800), (0, '2022-11-03 14:00', 1, 923), (0, '2022-11-03 15:00', 2, 800), (0, '2022-11-04 12:43', 1, 800)
</code></pre>
<pre>
Id | Date | SubNo | PO# |
----|------------------|-------|-----|
100 | 2022-11-01 12:43 | 1 | 800 |
101 | 2022-11-02 13:00 | 1 | 800 |
102 | 2022-11-03 12:43 | 2 | 800 |
103 | 2022-11-03 14:00 | 1 | 923 |
104 | 2022-11-03 15:00 | 2 | 800 |
105 | 2022-11-04 12:43 | 1 | 800 |
</pre>
<p>SubNo is the ordinal number of a subset or partial quantity of the purchase (PO#). There can be more than 30 subsets to a purchase.</p>
<p>I am looking for a query supplying for a given purchase for each of its subsets the latest date.<br>
For PO 800 it would look like this:</p>
<pre>
Id | Date | SubNo | PO# |
----|------------------|-------|-----|
105 | 2022-11-04 12:43 | 1 | 800 |
104 | 2022-11-03 15:00 | 2 | 800 |
</pre>
<p>I haven't found a way to filter the latest dates.
A rough approach is</p>
<pre><code>SELECT id, date, subNo
FROM myTable
WHERE poNo=800
GROUP BY subNo
ORDER BY subNo, date DESC
</code></pre>
<p>but DISTINCT and GROUP BY do not guarantee to return the latest date.</p>
<p>Then I tried to create a VIEW first, to be used in a later query.</p>
<pre><code>CREATE VIEW myView AS
SELECT subNo s, (SELECT MAX(date) FROM myTable WHERE poNo=800 AND subNo=s) AS dd
FROM myTable
WHERE poNo=800
GROUP BY s
</code></pre>
<p>But although the query is ok, the result differs when used for a VIEW, probably due to VIEW restrictions.</p>
<p>Finally I tried a joined table</p>
<pre><code>SELECT id, datum, subNo s
FROM myTable my JOIN (SELECT MAX(date) AS d FROM myTable WHERE poNo=800 AND subNo=s) tmp ON my.date=tmp.d
WHERE poNo=800
</code></pre>
<p>but getting the error "Unknown column 's' in where clause.</p>
<p>My MySql version is 8.0.22</p>
|
[
{
"answer_id": 74646458,
"author": "DannySlor",
"author_id": 19174570,
"author_profile": "https://Stackoverflow.com/users/19174570",
"pm_score": 1,
"selected": false,
"text": "row_number() SubNo PO Date select Id \n ,Date\n ,SubNo \n ,PO\nfrom\n(\nselect *\n ,row_number() over(partition by SubNo, PO order by Date desc) as rn\nfrom t\n) t\nwhere rn = 1\n"
},
{
"answer_id": 74647241,
"author": "Zachary Dionne",
"author_id": 17311738,
"author_profile": "https://Stackoverflow.com/users/17311738",
"pm_score": 1,
"selected": true,
"text": "SELECT id, date, subno\nFROM mytable\nWHERE pono = 800 AND (date, subno) IN (\n SELECT MAX(date), subno\n FROM mytable\n WHERE pono = 800\n GROUP BY subno\n)\nGROUP BY subno;\n +----+---------------------+-------+\n| id | date | subno |\n+----+---------------------+-------+\n| 6 | 2022-11-04 12:43:00 | 1 |\n| 5 | 2022-11-03 15:00:00 | 2 |\n+----+---------------------+-------+\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74646052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8368531/"
] |
74,646,076
|
<p>Im working on a project with MVC and i'd like to know if there's a way to store the id of an input, which is a value received from one of my model items, into one of my JS variables</p>
<p>here's how the id of the input is being adressed</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>@foreach (var item in Model) {
<input type="hidden" value="@item.id" id="@item.id">
<input type="hidden" value="@item.nome" id="@item.nome">
<input type="hidden" value="@item.preco" id="@item.preco">
}</code></pre>
</div>
</div>
</p>
<p>and here's what i been trying to do in my .JS file</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var id = document.getElementById('@item.id').value;
var nome = document.getElementById('@item.nome').value;
var preco = document.getElementById('@item.price').value;</code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74646458,
"author": "DannySlor",
"author_id": 19174570,
"author_profile": "https://Stackoverflow.com/users/19174570",
"pm_score": 1,
"selected": false,
"text": "row_number() SubNo PO Date select Id \n ,Date\n ,SubNo \n ,PO\nfrom\n(\nselect *\n ,row_number() over(partition by SubNo, PO order by Date desc) as rn\nfrom t\n) t\nwhere rn = 1\n"
},
{
"answer_id": 74647241,
"author": "Zachary Dionne",
"author_id": 17311738,
"author_profile": "https://Stackoverflow.com/users/17311738",
"pm_score": 1,
"selected": true,
"text": "SELECT id, date, subno\nFROM mytable\nWHERE pono = 800 AND (date, subno) IN (\n SELECT MAX(date), subno\n FROM mytable\n WHERE pono = 800\n GROUP BY subno\n)\nGROUP BY subno;\n +----+---------------------+-------+\n| id | date | subno |\n+----+---------------------+-------+\n| 6 | 2022-11-04 12:43:00 | 1 |\n| 5 | 2022-11-03 15:00:00 | 2 |\n+----+---------------------+-------+\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74646076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19075720/"
] |
74,646,092
|
<p>I have an array that stores a key tree from a dictionary. For example</p>
<pre class="lang-py prettyprint-override"><code>person_dict = [{"person": {"first_name": "John", "age_of_children": [1, 8, 13]}}, ...]
</code></pre>
<p>Becomes</p>
<pre><code>key_tree = [0, "person", "first_name"]
</code></pre>
<p>OR</p>
<pre><code>key_tree = [0, "person", "age_of_children"]
</code></pre>
<p>This array count contain one item or many items.</p>
<p>I'd like to get the value from the <code>person_dict</code>, <code>"John"</code> in this case, by using the <code>key_tree</code> array dynamically. I would then like to set a different value for it.</p>
|
[
{
"answer_id": 74646140,
"author": "S.B",
"author_id": 13944524,
"author_profile": "https://Stackoverflow.com/users/13944524",
"pm_score": 2,
"selected": true,
"text": "def get_value(d, key_list):\n for key in key_list:\n d = d[key]\n return d\n\n\ndef set_value(d, key_list, value):\n res = d\n *keys, last_key = key_list\n\n for key in keys:\n d = d[key]\n\n d[last_key] = value\n return res\n\n\nperson_dict = [{\"person\": {\"first_name\": \"John\", \"age_of_children\": [1, 8, 13]}}]\nkey_tree = [0, \"person\", \"first_name\"]\n\nprint(get_value(person_dict, key_tree))\nprint(set_value(person_dict, key_tree, \"John2\"))\n John\n[{'person': {'first_name': 'John2', 'age_of_children': [1, 8, 13]}}]\n get_value set_value d last_key value res = d"
},
{
"answer_id": 74646189,
"author": "ksha",
"author_id": 3125008,
"author_profile": "https://Stackoverflow.com/users/3125008",
"pm_score": 0,
"selected": false,
"text": "person_dict['person'].update({'first_name':'Ahmad'})\n person_dict[key_tree[0]].update({key_tree[1]: 'Ahmad'})\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74646092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1600895/"
] |
74,646,122
|
<p>If I want to default a date to the next working day I am using the following:</p>
<pre><code><?php
echo(date('d/m/Y',strtotime('+1 Weekdays')));
?>
</code></pre>
<p>For example: If a user is adding an item on a Friday it is given a default of the following Monday - the next working day.</p>
<p>I have to create a schedule of events with a start and end date. The end date needs to 1 year in the future on the preceding working day.</p>
<p>For example: If a user adds a schedule that has a start day of Wednesday and the same date in a years time happens to be a Sunday, then the end date needs to default to the previous Friday - the preceding working day.</p>
|
[
{
"answer_id": 74646140,
"author": "S.B",
"author_id": 13944524,
"author_profile": "https://Stackoverflow.com/users/13944524",
"pm_score": 2,
"selected": true,
"text": "def get_value(d, key_list):\n for key in key_list:\n d = d[key]\n return d\n\n\ndef set_value(d, key_list, value):\n res = d\n *keys, last_key = key_list\n\n for key in keys:\n d = d[key]\n\n d[last_key] = value\n return res\n\n\nperson_dict = [{\"person\": {\"first_name\": \"John\", \"age_of_children\": [1, 8, 13]}}]\nkey_tree = [0, \"person\", \"first_name\"]\n\nprint(get_value(person_dict, key_tree))\nprint(set_value(person_dict, key_tree, \"John2\"))\n John\n[{'person': {'first_name': 'John2', 'age_of_children': [1, 8, 13]}}]\n get_value set_value d last_key value res = d"
},
{
"answer_id": 74646189,
"author": "ksha",
"author_id": 3125008,
"author_profile": "https://Stackoverflow.com/users/3125008",
"pm_score": 0,
"selected": false,
"text": "person_dict['person'].update({'first_name':'Ahmad'})\n person_dict[key_tree[0]].update({key_tree[1]: 'Ahmad'})\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74646122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18745848/"
] |
74,646,129
|
<p>I have requirement where I want to select multiple categories and subcategories and send their ids as a query string using Axios. Let's suppose if user has selected 2 categories having ids 1 and 2 and from these two categories he has selected subcategories having ids 31 and 65, I want request URL to be like this :</p>
<p><a href="https://example.com/api/data?categories=1,2&subCategories=31,65" rel="nofollow noreferrer">https://example.com/api/data?categories=1,2&subCategories=31,65</a></p>
<p>How can I achieve this desired format of URL?</p>
|
[
{
"answer_id": 74646140,
"author": "S.B",
"author_id": 13944524,
"author_profile": "https://Stackoverflow.com/users/13944524",
"pm_score": 2,
"selected": true,
"text": "def get_value(d, key_list):\n for key in key_list:\n d = d[key]\n return d\n\n\ndef set_value(d, key_list, value):\n res = d\n *keys, last_key = key_list\n\n for key in keys:\n d = d[key]\n\n d[last_key] = value\n return res\n\n\nperson_dict = [{\"person\": {\"first_name\": \"John\", \"age_of_children\": [1, 8, 13]}}]\nkey_tree = [0, \"person\", \"first_name\"]\n\nprint(get_value(person_dict, key_tree))\nprint(set_value(person_dict, key_tree, \"John2\"))\n John\n[{'person': {'first_name': 'John2', 'age_of_children': [1, 8, 13]}}]\n get_value set_value d last_key value res = d"
},
{
"answer_id": 74646189,
"author": "ksha",
"author_id": 3125008,
"author_profile": "https://Stackoverflow.com/users/3125008",
"pm_score": 0,
"selected": false,
"text": "person_dict['person'].update({'first_name':'Ahmad'})\n person_dict[key_tree[0]].update({key_tree[1]: 'Ahmad'})\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74646129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7780102/"
] |
74,646,176
|
<p>This is my first time dealing with regex. I need to have a string array as apart of a regex pattern. Specifically I’m trying to match a date so the two formats I’m dealing with are <code>DDTTTTMMM</code> and <code>MMMDDTTTT</code> the month is a <em>three letter abbreviation</em> (ex:<code>DEC</code>) I can’t control where the month is placed in my input.</p>
<p>Date example for today is <code>011150DEC</code> or <code>DEC011150</code></p>
<pre><code>String[] months = {“JAN”, “FEB”, …, “DEC”}
String pattern1 = [0-9][0-9][0-9][0-9][0-9][0-9][months];
String pattern2 = [months][0-9][0-9][0-9][0-9][0-9][0-9];
</code></pre>
|
[
{
"answer_id": 74646140,
"author": "S.B",
"author_id": 13944524,
"author_profile": "https://Stackoverflow.com/users/13944524",
"pm_score": 2,
"selected": true,
"text": "def get_value(d, key_list):\n for key in key_list:\n d = d[key]\n return d\n\n\ndef set_value(d, key_list, value):\n res = d\n *keys, last_key = key_list\n\n for key in keys:\n d = d[key]\n\n d[last_key] = value\n return res\n\n\nperson_dict = [{\"person\": {\"first_name\": \"John\", \"age_of_children\": [1, 8, 13]}}]\nkey_tree = [0, \"person\", \"first_name\"]\n\nprint(get_value(person_dict, key_tree))\nprint(set_value(person_dict, key_tree, \"John2\"))\n John\n[{'person': {'first_name': 'John2', 'age_of_children': [1, 8, 13]}}]\n get_value set_value d last_key value res = d"
},
{
"answer_id": 74646189,
"author": "ksha",
"author_id": 3125008,
"author_profile": "https://Stackoverflow.com/users/3125008",
"pm_score": 0,
"selected": false,
"text": "person_dict['person'].update({'first_name':'Ahmad'})\n person_dict[key_tree[0]].update({key_tree[1]: 'Ahmad'})\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74646176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20658899/"
] |
74,646,182
|
<p>I am attempting to reserve memory for a med_array vector as seen below</p>
<pre><code>vector <int> med_array = {};
med_array.reserve(50000);
MedianFinder();
void addNum(int num);
double findMedian();
vector<int> get_array();
void print_array();
</code></pre>
<p>However, I get an error stating:</p>
<pre class="lang-none prettyprint-override"><code>medianfinderheader.h:10:4: error: 'med_array' does not name a type
10 | med_array.reserve(50000);
</code></pre>
<p>I have no idea why this is happening.</p>
|
[
{
"answer_id": 74646140,
"author": "S.B",
"author_id": 13944524,
"author_profile": "https://Stackoverflow.com/users/13944524",
"pm_score": 2,
"selected": true,
"text": "def get_value(d, key_list):\n for key in key_list:\n d = d[key]\n return d\n\n\ndef set_value(d, key_list, value):\n res = d\n *keys, last_key = key_list\n\n for key in keys:\n d = d[key]\n\n d[last_key] = value\n return res\n\n\nperson_dict = [{\"person\": {\"first_name\": \"John\", \"age_of_children\": [1, 8, 13]}}]\nkey_tree = [0, \"person\", \"first_name\"]\n\nprint(get_value(person_dict, key_tree))\nprint(set_value(person_dict, key_tree, \"John2\"))\n John\n[{'person': {'first_name': 'John2', 'age_of_children': [1, 8, 13]}}]\n get_value set_value d last_key value res = d"
},
{
"answer_id": 74646189,
"author": "ksha",
"author_id": 3125008,
"author_profile": "https://Stackoverflow.com/users/3125008",
"pm_score": 0,
"selected": false,
"text": "person_dict['person'].update({'first_name':'Ahmad'})\n person_dict[key_tree[0]].update({key_tree[1]: 'Ahmad'})\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74646182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20489120/"
] |
74,646,196
|
<p>I have a dataframe with duplicate columns (number not known a priori) like this example:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: right;"></th>
<th style="text-align: right;">a</th>
<th style="text-align: right;">a</th>
<th style="text-align: right;">a</th>
<th style="text-align: right;">b</th>
<th style="text-align: right;">b</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: right;">0</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">1</td>
</tr>
<tr>
<td style="text-align: right;">1</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">1</td>
</tr>
</tbody>
</table>
</div>
<p>I need to be able to aggregate the columns by summing their values (by rows) and returning NaN if at least one value, in one of the columns among the duplicates, is NaN.</p>
<p>I have tried this code:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import pandas as pd
df = pd.DataFrame([[1,1,1,1,1], [1,np.nan,1,1,1]], columns=['a','a','a','b','b'])
df = df.groupby(axis=1, level=0).sum()
</code></pre>
<p>The result i get is as follows, but it does not return NaN in the second row of column 'a'.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: right;"></th>
<th style="text-align: right;">a</th>
<th style="text-align: right;">b</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: right;">0</td>
<td style="text-align: right;">3</td>
<td style="text-align: right;">2</td>
</tr>
<tr>
<td style="text-align: right;">1</td>
<td style="text-align: right;">2</td>
<td style="text-align: right;">2</td>
</tr>
</tbody>
</table>
</div><hr />
<p>In the documentation of <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sum.html" rel="nofollow noreferrer">pandas.DataFrame.sum</a>, there is the <code>skipna</code> parameter which might suit my case. But I am using the function <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.sum.html" rel="nofollow noreferrer">pandas.core.groupby.GroupBy.sum</a> which does not have this parameter, but the <code>min_count</code> which does what i want but the number is not known in advance and would be different for each duplicate column.</p>
<p><em>For example, a min_count=3 solves the problem for column 'a', but obviously returns NaN on the whole of column 'b'.</em></p>
<hr />
<p>The result I want to achieve is:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: right;"></th>
<th style="text-align: right;">a</th>
<th style="text-align: right;">b</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: right;">0</td>
<td style="text-align: right;">3</td>
<td style="text-align: right;">2</td>
</tr>
<tr>
<td style="text-align: right;">1</td>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">2</td>
</tr>
</tbody>
</table>
</div>
|
[
{
"answer_id": 74646619,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "apply DataFrame.sum df.groupby(level=0, axis=1).apply(lambda x: x.sum(axis=1, skipna=False))\n a b\n0 3.0 2.0\n1 NaN 2.0\n"
},
{
"answer_id": 74648170,
"author": "PaulS",
"author_id": 11564487,
"author_profile": "https://Stackoverflow.com/users/11564487",
"pm_score": 0,
"selected": false,
"text": "cols, ldf = df.columns.unique(), len(df)\n\npd.DataFrame(\n np.reshape([sum(df.loc[i, x]) for i in range(ldf) for x in cols],\n (len(cols), ldf)), \n columns=cols)\n a b\n0 3.0 2.0\n1 NaN 2.0\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74646196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20249888/"
] |
74,646,236
|
<p>i would like to get an numpy array , shape 1000 row and 2 column.</p>
<ol>
<li>1st column will contain - Gaussian distributed variables with standard deviation 2 and mean 1.</li>
<li>2nd column will contain Gaussian distributed variables with mean -1 and standard deviation 0.5.</li>
</ol>
<p>How to create the array using define value of mean and std?</p>
|
[
{
"answer_id": 74646357,
"author": "Vini",
"author_id": 6927944,
"author_profile": "https://Stackoverflow.com/users/6927944",
"pm_score": 1,
"selected": false,
"text": "import numpy as np\n\n# as per kwinkunks suggestion\nrng = np.random.default_rng()\n\narr1 = rng.normal(1, 2, 1000).reshape(1000, 1)\narr2 = rng.normal(-1, 0.5, 1000).reshape(1000, 1)\n\narr1[:5]\n\narray([[-2.8428678 ],\n [ 2.52213097],\n [-0.98329961],\n [-0.87854616],\n [ 0.65674208]])\n\narr2[:5]\n\narray([[-0.85321735],\n [-1.59748405],\n [-1.77794019],\n [-1.02239036],\n [-0.57849622]])\n np.concatenate([arr1, arr2], axis = 1)\n\n# output\narray([[-2.8428678 , -0.85321735],\n [ 2.52213097, -1.59748405],\n [-0.98329961, -1.77794019],\n ...,\n [ 0.84249042, -0.26451526],\n [ 0.6950764 , -0.86348222],\n [ 3.53885426, -0.95546126]])\n"
},
{
"answer_id": 74646368,
"author": "Chrispresso",
"author_id": 2599709,
"author_profile": "https://Stackoverflow.com/users/2599709",
"pm_score": 0,
"selected": false,
"text": "normal np.hstack((np.random.normal(1, 2, size=(1000,1)), np.random.normal(-1, 0.5, size=(1000,1))))\n"
},
{
"answer_id": 74649170,
"author": "AGN Gazer",
"author_id": 8033585,
"author_profile": "https://Stackoverflow.com/users/8033585",
"pm_score": 1,
"selected": false,
"text": "np.random.normal import numpy as np\nnp.random.normal([1, -1], [2, 0.5], (1000, 2))\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74646236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20658907/"
] |
74,646,244
|
<p>I want to identify the port of a device that is connected to my PC, it's a PINPAD, however the only way I could do it was by running the following command in CMD:
<code>reg query HKLM\HARDWARE\DEVICEMAP\SERIALCOMM</code>
After running this command in CMD "PROMPT COMMAND", it returns the following information:
`</p>
<pre><code>HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM
\Device\gertec_usbcdc_AcmSerial0 REG_SZ COM4
</code></pre>
<p>`
As you can see, it returns me to COM4 at the end, my question is how to run this command within my application, which library to use and how to assemble this query to obtain the same return within the C# code.
Attached is an image of the query performed in CMD<a href="https://i.stack.imgur.com/UIyDN.png" rel="nofollow noreferrer">image prompt command, in reg query</a></p>
<p>I saw some answers here in the forum, and I tried to apply it in my code, but in none I was successful, below are some of the things I tried.</p>
<pre><code>
</code></pre>
<pre><code> try
{
using (var key = Registry.CurrentUser.OpenSubKey(@"reg query HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM", false)) // False is important!
{
var s = key?.GetValue("Version") as string;
if (!string.IsNullOrWhiteSpace(s))
{
var version = new Version(s);
}
}
}
catch (Exception ex) //just for demonstration...it's always best to handle specific exceptions
{
//react appropriately
}
</code></pre>
<pre><code>
</code></pre>
<p>I also tried</p>
<pre><code>RegistryKey key = Registry.CurrentUser.OpenSubKey(@"HKLM\HARDWARE\DEVICEMAP\SERIALCOMM");
</code></pre>
<p>Nesse caso ele sempre retorna a key como null.</p>
|
[
{
"answer_id": 74646357,
"author": "Vini",
"author_id": 6927944,
"author_profile": "https://Stackoverflow.com/users/6927944",
"pm_score": 1,
"selected": false,
"text": "import numpy as np\n\n# as per kwinkunks suggestion\nrng = np.random.default_rng()\n\narr1 = rng.normal(1, 2, 1000).reshape(1000, 1)\narr2 = rng.normal(-1, 0.5, 1000).reshape(1000, 1)\n\narr1[:5]\n\narray([[-2.8428678 ],\n [ 2.52213097],\n [-0.98329961],\n [-0.87854616],\n [ 0.65674208]])\n\narr2[:5]\n\narray([[-0.85321735],\n [-1.59748405],\n [-1.77794019],\n [-1.02239036],\n [-0.57849622]])\n np.concatenate([arr1, arr2], axis = 1)\n\n# output\narray([[-2.8428678 , -0.85321735],\n [ 2.52213097, -1.59748405],\n [-0.98329961, -1.77794019],\n ...,\n [ 0.84249042, -0.26451526],\n [ 0.6950764 , -0.86348222],\n [ 3.53885426, -0.95546126]])\n"
},
{
"answer_id": 74646368,
"author": "Chrispresso",
"author_id": 2599709,
"author_profile": "https://Stackoverflow.com/users/2599709",
"pm_score": 0,
"selected": false,
"text": "normal np.hstack((np.random.normal(1, 2, size=(1000,1)), np.random.normal(-1, 0.5, size=(1000,1))))\n"
},
{
"answer_id": 74649170,
"author": "AGN Gazer",
"author_id": 8033585,
"author_profile": "https://Stackoverflow.com/users/8033585",
"pm_score": 1,
"selected": false,
"text": "np.random.normal import numpy as np\nnp.random.normal([1, -1], [2, 0.5], (1000, 2))\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74646244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055108/"
] |
74,646,298
|
<p>I am trying to mess around with matrices in python, and wanted to use multiprocessing to processes each row separately for a math operation, I have posted a minimal reproducible sample below, but keep in mind that for my actual code I do in-fact need the entire matrix passed to the helper function. This sample takes literally forever to process a 10,000 by 10,000 matrix. Almost 2 hours with 9 processes. Looking in task manage it seems only 4-5 of the threads will run at any given time on my cpu, and the application never uses more than 25%. I've done my absolute best to avoid branches in my real code, though the sample provided is branchless. It still takes roughly 25 seconds to process a 1000 by 1000 matrix on my machine, which is ludacris to me as a mainly c++ developer. I wrote serial code in C that executes the entire 10,000 by 10,000 in constant time in less than a second. I think the main bottleneck is the multiprocessing code, but I am required to do this with multiprocessing. Any ideas for how I could go about improving this? Each row can be processed entirely separately but they need to be joined together back into a matrix for my actual code.</p>
<pre><code>import random
from multiprocessing import Pool
import time
def addMatrixRow(matrixData):
matrix = matrixData[0]
rowNum = matrixData[1]
del (matrixData)
rowSum = 0
for colNum in range(len(matrix[rowNum])):
rowSum += matrix[rowNum][colNum]
return rowSum
def genMatrix(row, col):
matrix = list()
for i in range(row):
matrix.append(list())
for j in range(col):
matrix[i].append(random.randint(0, 1))
return matrix
def main():
matrix = genMatrix(1000, 1000)
print("generated matrix")
MAX_PROCESSES = 4
finalSum = 0
processPool = Pool(processes=MAX_PROCESSES)
poolData = list()
start = time.time()
for i in range(100):
for rowNum in range(len(matrix)):
matrixData = [matrix, rowNum]
poolData.append(matrixData)
finalData = processPool.map(addMatrixRow, poolData)
poolData = list()
finalSum += sum(finalData)
end = time.time()
print(end-start)
print(f'final sum {finalSum}')
if __name__ == '__main__':
main()
</code></pre>
|
[
{
"answer_id": 74646437,
"author": "Ahmed AEK",
"author_id": 15649230,
"author_profile": "https://Stackoverflow.com/users/15649230",
"pm_score": 1,
"selected": false,
"text": "sum import random\nfrom multiprocessing import Pool\nimport time\n\n\ndef addMatrixRow(row_data):\n rowSum = sum(row_data)\n return rowSum\n\n\ndef genMatrix(row, col):\n matrix = list()\n for i in range(row):\n matrix.append(list())\n for j in range(col):\n matrix[i].append(random.randint(0, 1))\n return matrix\n\ndef main():\n matrix = genMatrix(1000, 1000)\n print(\"generated matrix\")\n MAX_PROCESSES = 4\n finalSum = 0\n\n processPool = Pool(processes=MAX_PROCESSES)\n poolData = list()\n\n start = time.time()\n for i in range(100):\n for rowNum in range(len(matrix)):\n matrixData = matrix[rowNum]\n poolData.append(matrixData)\n\n finalData = processPool.map(addMatrixRow, poolData)\n poolData = list()\n finalSum += sum(finalData)\n end = time.time()\n print(end-start)\n print(f'final sum {finalSum}')\n\n\nif __name__ == '__main__':\n main()\n generated matrix\n3.5028157234191895\nfinal sum 49963400\n process pool list(map(sum,poolData)) generated matrix\n1.2143816947937012\nfinal sum 50020800\n"
},
{
"answer_id": 74658622,
"author": "Booboo",
"author_id": 2823719,
"author_profile": "https://Stackoverflow.com/users/2823719",
"pm_score": 3,
"selected": true,
"text": "matrix addMatrixRow poolArgs map imap_unordered imap imap_unordered multiprocessing.pool.Pool imap imap_unordered for sum import random\nfrom multiprocessing import Pool\nimport time\n\n\ndef init_pool_processes(m):\n global matrix\n matrix = m \n\ndef addMatrixRow(rowNum):\n return sum(matrix[rowNum])\n\ndef genMatrix(row, col):\n return [[random.randint(0, 1) for _ in range(col)] for _ in range(row)]\n \ndef compute_chunksize(pool_size, iterable_size):\n chunksize, remainder = divmod(iterable_size, 4 * pool_size)\n if remainder:\n chunksize += 1\n return chunksize\n\ndef main():\n matrix = genMatrix(1000, 1000)\n print(\"generated matrix\")\n MAX_PROCESSES = 4\n\n processPool = Pool(processes=MAX_PROCESSES, initializer=init_pool_processes, initargs=(matrix,))\n start = time.time()\n # Use a generator function:\n poolData = (rowNum for _ in range(100) for rowNum in range(len(matrix)))\n # Compute efficient chunksize\n chunksize = compute_chunksize(MAX_PROCESSES, len(matrix) * 100)\n finalSum = sum(processPool.imap_unordered(addMatrixRow, poolData, chunksize=chunksize))\n end = time.time()\n print(end-start)\n print(f'final sum {finalSum}')\n processPool.close()\n processPool.join()\n\n\nif __name__ == '__main__':\n main()\n generated matrix\n0.35799622535705566\nfinal sum 49945400\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74646298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12847370/"
] |
74,646,312
|
<p>Output on ':hover' is always</p>
<p>"1IPSUM"</p>
<p>And if i decide to add a ':before' element with 'content:"1"' it just adds a 1 making the output before hover "11"</p>
<p>The output i am looking for is:</p>
<p>on 'hover' "IPSUM"</p>
<p>Fiddle: <a href="https://jsfiddle.net/Zxdfvv/u9xgoks3/" rel="nofollow noreferrer">https://jsfiddle.net/Zxdfvv/u9xgoks3/</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.btn:hover:after {
padding-bottom: 200px;
content:"IPSUM";
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='btn'>1</div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74646437,
"author": "Ahmed AEK",
"author_id": 15649230,
"author_profile": "https://Stackoverflow.com/users/15649230",
"pm_score": 1,
"selected": false,
"text": "sum import random\nfrom multiprocessing import Pool\nimport time\n\n\ndef addMatrixRow(row_data):\n rowSum = sum(row_data)\n return rowSum\n\n\ndef genMatrix(row, col):\n matrix = list()\n for i in range(row):\n matrix.append(list())\n for j in range(col):\n matrix[i].append(random.randint(0, 1))\n return matrix\n\ndef main():\n matrix = genMatrix(1000, 1000)\n print(\"generated matrix\")\n MAX_PROCESSES = 4\n finalSum = 0\n\n processPool = Pool(processes=MAX_PROCESSES)\n poolData = list()\n\n start = time.time()\n for i in range(100):\n for rowNum in range(len(matrix)):\n matrixData = matrix[rowNum]\n poolData.append(matrixData)\n\n finalData = processPool.map(addMatrixRow, poolData)\n poolData = list()\n finalSum += sum(finalData)\n end = time.time()\n print(end-start)\n print(f'final sum {finalSum}')\n\n\nif __name__ == '__main__':\n main()\n generated matrix\n3.5028157234191895\nfinal sum 49963400\n process pool list(map(sum,poolData)) generated matrix\n1.2143816947937012\nfinal sum 50020800\n"
},
{
"answer_id": 74658622,
"author": "Booboo",
"author_id": 2823719,
"author_profile": "https://Stackoverflow.com/users/2823719",
"pm_score": 3,
"selected": true,
"text": "matrix addMatrixRow poolArgs map imap_unordered imap imap_unordered multiprocessing.pool.Pool imap imap_unordered for sum import random\nfrom multiprocessing import Pool\nimport time\n\n\ndef init_pool_processes(m):\n global matrix\n matrix = m \n\ndef addMatrixRow(rowNum):\n return sum(matrix[rowNum])\n\ndef genMatrix(row, col):\n return [[random.randint(0, 1) for _ in range(col)] for _ in range(row)]\n \ndef compute_chunksize(pool_size, iterable_size):\n chunksize, remainder = divmod(iterable_size, 4 * pool_size)\n if remainder:\n chunksize += 1\n return chunksize\n\ndef main():\n matrix = genMatrix(1000, 1000)\n print(\"generated matrix\")\n MAX_PROCESSES = 4\n\n processPool = Pool(processes=MAX_PROCESSES, initializer=init_pool_processes, initargs=(matrix,))\n start = time.time()\n # Use a generator function:\n poolData = (rowNum for _ in range(100) for rowNum in range(len(matrix)))\n # Compute efficient chunksize\n chunksize = compute_chunksize(MAX_PROCESSES, len(matrix) * 100)\n finalSum = sum(processPool.imap_unordered(addMatrixRow, poolData, chunksize=chunksize))\n end = time.time()\n print(end-start)\n print(f'final sum {finalSum}')\n processPool.close()\n processPool.join()\n\n\nif __name__ == '__main__':\n main()\n generated matrix\n0.35799622535705566\nfinal sum 49945400\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74646312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15377919/"
] |
74,646,324
|
<p>I want to solve an optimization problem in Julia.
I am trying to define a binary variable x_{r,i}
Thereby, the length of the sets of both indices is not the same.</p>
<p>Let's say there is r_a and r_b, but for r_a there are i_1 and i_2 whereas for r_b there are i_1, i_2 and i_3 so in the end I want to get X_a_1, X_a_2 and X_b_1, X_b_2, X_b_3</p>
<p>The set of indices i varies for different indices r.</p>
<p>Is there any way to define variable x with these indices in Julia?</p>
<p>This is what I tried:</p>
<pre><code>R=["a","b"]
I=Dict("a" => [1,2],"b"=>[1,2,3])
m = Model(CPLEX.Optimizer)
@variables m begin
X[R,[I]], Bin
end
</code></pre>
|
[
{
"answer_id": 74647064,
"author": "Przemyslaw Szufel",
"author_id": 9957710,
"author_profile": "https://Stackoverflow.com/users/9957710",
"pm_score": 0,
"selected": false,
"text": "julia> indices = [Symbol.(:a, 1:2);Symbol.(:b, 1:3)];\n\njulia> @variable(m, x[indices], Bin)\n1-dimensional DenseAxisArray{VariableRef,1,...} with index sets:\n Dimension 1, [:a1, :a2, :b1, :b2, :b3]\nAnd data, a 5-element Vector{VariableRef}:\n x[a1]\n x[a2]\n x[b1]\n x[b2]\n x[b3]\n\n"
},
{
"answer_id": 74650438,
"author": "Oscar Dowson",
"author_id": 13591160,
"author_profile": "https://Stackoverflow.com/users/13591160",
"pm_score": 4,
"selected": true,
"text": "SparseAxisArray julia> R = [\"a\", \"b\"]\n2-element Vector{String}:\n \"a\"\n \"b\"\n\njulia> I = Dict(\"a\" => [1, 2], \"b\" => [1, 2, 3])\nDict{String, Vector{Int64}} with 2 entries:\n \"b\" => [1, 2, 3]\n \"a\" => [1, 2]\n\njulia> model = Model();\n\njulia> @variable(model, x[r in R, i in I[r]])\nJuMP.Containers.SparseAxisArray{VariableRef, 2, Tuple{String, Int64}} with 5 entries:\n [a, 1] = x[a,1]\n [a, 2] = x[a,2]\n [b, 1] = x[b,1]\n [b, 2] = x[b,2]\n [b, 3] = x[b,3]\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74646324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20592131/"
] |
74,646,363
|
<p>I have the following undirected graph (picture) that contains a cycle or a Hamiltonian path of length |V|= 8. The cycle (path) with no repeated edges and vertices is the red line. The adjacency matrix is :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;"></th>
<th style="text-align: center;">A</th>
<th style="text-align: right;">B</th>
<th style="text-align: left;">C</th>
<th style="text-align: left;">D</th>
<th style="text-align: right;">E</th>
<th style="text-align: left;">F</th>
<th style="text-align: left;">G</th>
<th style="text-align: right;">H</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">A</td>
<td style="text-align: center;">0</td>
<td style="text-align: right;">1</td>
<td style="text-align: left;">0</td>
<td style="text-align: left;">1</td>
<td style="text-align: right;">1</td>
<td style="text-align: left;">0</td>
<td style="text-align: left;">0</td>
<td style="text-align: right;">0</td>
</tr>
<tr>
<td style="text-align: left;">B</td>
<td style="text-align: center;">1</td>
<td style="text-align: right;">0</td>
<td style="text-align: left;">1</td>
<td style="text-align: left;">0</td>
<td style="text-align: right;">0</td>
<td style="text-align: left;">1</td>
<td style="text-align: left;">0</td>
<td style="text-align: right;">0</td>
</tr>
<tr>
<td style="text-align: left;">C</td>
<td style="text-align: center;">0</td>
<td style="text-align: right;">1</td>
<td style="text-align: left;">0</td>
<td style="text-align: left;">1</td>
<td style="text-align: right;">0</td>
<td style="text-align: left;">0</td>
<td style="text-align: left;">0</td>
<td style="text-align: right;">1</td>
</tr>
<tr>
<td style="text-align: left;">D</td>
<td style="text-align: center;">1</td>
<td style="text-align: right;">0</td>
<td style="text-align: left;">1</td>
<td style="text-align: left;">0</td>
<td style="text-align: right;">0</td>
<td style="text-align: left;">0</td>
<td style="text-align: left;">1</td>
<td style="text-align: right;">0</td>
</tr>
<tr>
<td style="text-align: left;">E</td>
<td style="text-align: center;">1</td>
<td style="text-align: right;">0</td>
<td style="text-align: left;">0</td>
<td style="text-align: left;">0</td>
<td style="text-align: right;">0</td>
<td style="text-align: left;">1</td>
<td style="text-align: left;">1</td>
<td style="text-align: right;">0</td>
</tr>
<tr>
<td style="text-align: left;">F</td>
<td style="text-align: center;">0</td>
<td style="text-align: right;">1</td>
<td style="text-align: left;">0</td>
<td style="text-align: left;">0</td>
<td style="text-align: right;">1</td>
<td style="text-align: left;">0</td>
<td style="text-align: left;">0</td>
<td style="text-align: right;">1</td>
</tr>
<tr>
<td style="text-align: left;">G</td>
<td style="text-align: center;">0</td>
<td style="text-align: right;">0</td>
<td style="text-align: left;">0</td>
<td style="text-align: left;">1</td>
<td style="text-align: right;">1</td>
<td style="text-align: left;">0</td>
<td style="text-align: left;">0</td>
<td style="text-align: right;">1</td>
</tr>
<tr>
<td style="text-align: left;">H</td>
<td style="text-align: center;">0</td>
<td style="text-align: right;">0</td>
<td style="text-align: left;">1</td>
<td style="text-align: left;">0</td>
<td style="text-align: right;">0</td>
<td style="text-align: left;">1</td>
<td style="text-align: left;">1</td>
<td style="text-align: right;">0</td>
</tr>
</tbody>
</table>
</div>
<p>How can I plot this graph in R ?</p>
<pre><code>Ham = matrix(c(0,1,0,1,1,0,0,0,
1,0,1,0,0,1,0,0,
0,1,0,1,0,0,0,1,
1,0,1,0,0,0,1,0,
1,0,0,0,0,1,1,0,
0,1,0,0,1,0,0,1,
0,0,0,1,1,0,0,1,
0,0,1,0,0,1,1,0),8,8)
Ham
</code></pre>
<p><a href="https://i.stack.imgur.com/IFdju.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IFdju.jpg" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74647534,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 3,
"selected": true,
"text": "graph.subisomorphic.lad g <- graph_from_adjacency_matrix(Ham, \"undirected\")\nes <- graph.subisomorphic.lad(make_ring(vcount(g)), g)$map\ng %>%\n set_edge_attr(\"color\", value = \"black\") %>%\n set_edge_attr(\"color\",\n get.edge.ids(g, c(rbind(es, c(es[-1], es[1])))),\n value = \"red\"\n ) %>%\n plot()\n subgraph_isomorphisms g <- graph_from_adjacency_matrix(Ham, \"undirected\")\nlst <- lapply(\n subgraph_isomorphisms(make_ring(vcount(g)), g),\n function(es) {\n g %>%\n set_edge_attr(\"color\", value = \"black\") %>%\n set_edge_attr(\"color\",\n get.edge.ids(g, c(rbind(es, c(es[-1], es[1])))),\n value = \"red\"\n )\n }\n)\n lst plot(lst[[1]] plot(lst[[2]]"
},
{
"answer_id": 74657536,
"author": "clp",
"author_id": 3604103,
"author_profile": "https://Stackoverflow.com/users/3604103",
"pm_score": 1,
"selected": false,
"text": "## Make edge lists to prevent igraph from rearranging the edges.\nelh <- as_edgelist(make_graph( ~ A-B-F-E-G-H-C-D) )\nelr <- as_edgelist(make_graph( ~ D-A, A-E, B-C, F-H, G-D) )\ng1 <- graph_from_edgelist(rbind(elh, elr), directed=FALSE )\n E(g1)$label <- paste(\"a\", seq(ecount(g1)), sep = \"\")\nE(g1)[ (1:8)]$color <- \"red\" \nE(g1)[-(1:8)]$color <- \"black\"\n layout_as_homer <- matrix( c( -4,4, 4,4, 4,-4, -4,-4 # A:D.\n , -2,2, 2,2, -2,-2, 2,-2 # E:H.\n )\n , ncol=2, byrow=TRUE\n )\n g2 <- permute(g1, match(V(g1)$name, LETTERS[1:8]))\nplot(g2, layout=layout_as_homer, edge.width=3, edge.label.cex = 1.5)\ng2[] # adjacency matrix\n 8 x 8 sparse Matrix of class \"dgCMatrix\"\n A B C D E F G H\nA . 1 . 1 1 . . .\nB 1 . 1 . . 1 . .\nC . 1 . 1 . . . 1\nD 1 . 1 . . . 1 .\nE 1 . . . . 1 1 .\nF . 1 . . 1 . . 1\nG . . . 1 1 . . 1\nH . . 1 . . 1 1 .\n"
},
{
"answer_id": 74661881,
"author": "clp",
"author_id": 3604103,
"author_profile": "https://Stackoverflow.com/users/3604103",
"pm_score": 1,
"selected": false,
"text": "igraphs q3 <- make_graph(~ A-B-C-D-A\n , a-b-c-d-a\n , A-a, B-b, C-c, D-d\n )\nq3$main = \"Planar layout of hyper graph Q3\"\nE(q3)$label <- paste(\"a\", seq(ecount(q3)), sep = \"\")\n\nhp <- c( \"A\",\"B\", \"B\",\"b\", \"b\",\"a\", \"a\",\"d\"\n , \"d\",\"c\", \"c\",\"C\", \"C\",\"D\", \"D\",\"A\"\n )\n\nE(q3)[ get.edge.ids(q3, hp)]$color <- \"red\"\nE(q3)[-get.edge.ids(q3, hp)]$color <- \"black\"\n\nlayout_as_homer <- matrix( c( -4,4, 4,4, 4,-4, -4,-4 # A:D\n , -2,2, 2,2, 2,-2, -2,-2 # a:d\n )\n , ncol=2, byrow=TRUE\n ) \nplot(q3, layout=layout_as_homer, edge.width=3, edge.label.cex = 1.5)\nq3[]\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74646363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16346449/"
] |
74,646,379
|
<p>if anyone can tell me how to draw this shape</p>
<p><a href="https://i.stack.imgur.com/aAzc7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aAzc7.png" alt="enter image description here" /></a></p>
<p>with an inside text, id greatly appreciate it.
Is there a way to do it in regular xml or any android api</p>
<p>i dont know how to do it</p>
|
[
{
"answer_id": 74646452,
"author": "Thracian",
"author_id": 5457853,
"author_profile": "https://Stackoverflow.com/users/5457853",
"pm_score": 0,
"selected": false,
"text": "fun getBubbleShape(\n density: Density,\n cornerRadius: Dp,\n arrowWidth: Dp,\n arrowHeight: Dp,\n arrowOffset: Dp\n): GenericShape {\n\n val cornerRadiusPx: Float\n val arrowWidthPx: Float\n val arrowHeightPx: Float\n val arrowOffsetPx: Float\n\n with(density) {\n cornerRadiusPx = cornerRadius.toPx()\n arrowWidthPx = arrowWidth.toPx()\n arrowHeightPx = arrowHeight.toPx()\n arrowOffsetPx = arrowOffset.toPx()\n }\n\n return GenericShape { size: Size, layoutDirection: LayoutDirection ->\n\n this.addRoundRect(\n RoundRect(\n rect = Rect(\n offset = Offset(0f, arrowHeightPx),\n size = Size(size.width, size.height - arrowHeightPx)\n ),\n cornerRadius = CornerRadius(cornerRadiusPx, cornerRadiusPx)\n )\n )\n\n moveTo(arrowOffsetPx, arrowHeightPx)\n lineTo(arrowOffsetPx + arrowWidthPx / 2, 0f)\n lineTo(arrowOffsetPx + arrowWidthPx, arrowHeightPx)\n\n }\n}\n @Composable\nprivate fun BubbleShapeSample() {\n val density = LocalDensity.current\n val arrowHeight = 16.dp\n\n val bubbleShape = remember {\n getBubbleShape(\n density = density,\n cornerRadius = 12.dp,\n arrowWidth = 20.dp,\n arrowHeight = arrowHeight,\n arrowOffset = 30.dp\n )\n }\n\n Column(\n modifier = Modifier\n .shadow(5.dp, bubbleShape)\n .background(Color.White)\n .padding(8.dp)\n ) {\n\n\n Spacer(modifier = Modifier.height(arrowHeight))\n\n Row(modifier = Modifier.padding(12.dp)) {\n\n Icon(\n modifier = Modifier.size(60.dp),\n imageVector = Icons.Default.NotificationsActive,\n contentDescription = \"\",\n tint = Color(0xffFFC107)\n )\n\n Spacer(modifier = Modifier.width(20.dp))\n Text(\n \"Get updates\\n\" +\n \"on questions\\n\" +\n \"and answers\",\n\n fontSize = 20.sp\n )\n\n Spacer(modifier = Modifier.width(20.dp))\n\n Icon(\n imageVector = Icons.Default.Close,\n contentDescription = \"\"\n )\n\n }\n\n }\n}\n"
},
{
"answer_id": 74650436,
"author": "Bullionist",
"author_id": 4192614,
"author_profile": "https://Stackoverflow.com/users/4192614",
"pm_score": 2,
"selected": false,
"text": "Box {\n Canvas(\n modifier = Modifier\n .size(200.dp)\n .padding(40.dp)\n ) {\n val trianglePath = Path().let {\n it.moveTo(this.size.width * .40f, 0f)\n it.lineTo(this.size.width * .50f, -30f)\n it.lineTo(this.size.width * .60f, 0f)\n it.close()\n it\n }\n drawRoundRect(\n Color.LightGray,\n size = Size(this.size.width, this.size.height * 0.95f),\n cornerRadius = CornerRadius(60f)\n )\n drawPath(\n path = trianglePath,\n Color.LightGray,\n )\n }\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74646379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20659102/"
] |
74,646,404
|
<p>I have a .txt file where the word 'picture:' is found multiple times in the file. How can I extract all words after the 'pictures:' word and save in a text file</p>
<p>I tried the follow code,but doesn't work:</p>
<pre><code>cat users_sl.txt |awk -F: '/^login:"/{print $2}' cookies.txt
</code></pre>
<p><code>user_sl.txt</code>:</p>
<p><code>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quis picture lobortis scelerisque fermentum dui faucibus in ornare quam. Est ullamcorper eget nulla facilisi etiam dignissim diam quis. Quis viverra nibh cras pulvinar mattis nunc sed. Turpis massa sed elementum picture tempus egestas. Condimentum vitae sapien pellentesque habitant. Et molestie ac feugiat sed lectus vestibulum mattis ullamcorper. Tincidunt lobortis feugiat vivamus at augue eget arcu picture dictum varius. Donec massa sapien faucibus et molestie ac feugiat sed. Tincidunt eget nullam non nisi est. Ornare arcu dui vivamus arcu. Mattis enim ut tellus elementum sagittis vitae et leo duis</code></p>
<p>picturelist.txt:</p>
<pre><code>lobortis
dictum
tempus
</code></pre>
|
[
{
"answer_id": 74646576,
"author": "Saif",
"author_id": 4777670,
"author_profile": "https://Stackoverflow.com/users/4777670",
"pm_score": 0,
"selected": false,
"text": "awk '/picture:/{getline; print}' users_sl.txt > output.txt\n"
},
{
"answer_id": 74646705,
"author": "Gilles Quenot",
"author_id": 465183,
"author_profile": "https://Stackoverflow.com/users/465183",
"pm_score": 0,
"selected": false,
"text": "$ perl -nE 'say for /\\bpicture\\b\\s+(\\w+)\\b/g' user_sl.txt | tee picturelist.txt\nlobortis\ntempus\ndictum\n"
},
{
"answer_id": 74646765,
"author": "Gilles Quenot",
"author_id": 465183,
"author_profile": "https://Stackoverflow.com/users/465183",
"pm_score": 0,
"selected": false,
"text": "$ awk '{\n for (i=1; i<=NF; i++) {\n if ($i == \"picture\") print $(i+1)\n }\n}' user_sl.txt | tee picturelist.txt\n $ printf '%s\\n' $(< users_sl.txt) |\n awk '/picture/{p=1;next} {if (p==1) {print;p=0}}' > picturelist.txt\n lobortis\ntempus\ndictum\n"
},
{
"answer_id": 74646779,
"author": "Jack",
"author_id": 2584475,
"author_profile": "https://Stackoverflow.com/users/2584475",
"pm_score": 1,
"selected": false,
"text": "picture **picture:** $ cat sl.txt \nLorem ipsum dolor sit amet, consectetur adipiscing elit,\nsed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\nQuis picture lobortis scelerisque fermentum dui faucibus in ornare quam.\nEst ullamcorper eget nulla facilisi etiam dignissim diam quis.\nQuis viverra nibh cras pulvinar mattis nunc sed.\nTurpis massa sed elementum picture tempus egestas.\nCondimentum vitae sapien pellentesque habitant.\nEt molestie ac feugiat sed lectus vestibulum mattis ullamcorper.\nTincidunt lobortis feugiat vivamus at augue eget arcu picture\ndictum varius. Donec massa sapien faucibus et molestie ac feugiat sed.\nTincidunt eget nullam non nisi est.\nOrnare arcu dui vivamus arcu.\nMattis enim ut tellus elementum sagittis vitae et leo duis\n\n$ cat sl.txt | tr '\\n' ' ' | grep -o 'picture [^ ]*' | cut -d' ' -f2\nlobortis\ntempus\ndictum\n tr '\\n' ' ' -o grep picture [^ ]* cut -d ' ' -f 2"
},
{
"answer_id": 74646931,
"author": "Gilles Quenot",
"author_id": 465183,
"author_profile": "https://Stackoverflow.com/users/465183",
"pm_score": 0,
"selected": false,
"text": "#!/bin/bash\n\narr=( $(<user_sl.txt) )\nfor ((i=0; i<${#arr[@]}; i++)); do\n if [[ ${arr[i]} == picture ]]; then\n printf '%s\\n' \"${arr[i+1]}\"\n fi\ndone | tee picturelist.txt\n lobortis\ntempus\ndictum\n"
},
{
"answer_id": 74646937,
"author": "john-jones",
"author_id": 322537,
"author_profile": "https://Stackoverflow.com/users/322537",
"pm_score": -1,
"selected": false,
"text": "cat textfile | \\\n grep -o 'picture:\\*\\*[^ ]*' | \\\n sed 's/.*\\*\\(.*\\)/\\1/g';\n"
},
{
"answer_id": 74647066,
"author": "Tobias Lins",
"author_id": 2160595,
"author_profile": "https://Stackoverflow.com/users/2160595",
"pm_score": -1,
"selected": false,
"text": "cat users_sl.txt | awk -F \"picture:\" '{print $2}' > picturelist.txt\n cat users_sl.txt awk -F \"picture:\" '{print $2}' awk $2 > picturelist.txt awk"
},
{
"answer_id": 74662054,
"author": "John",
"author_id": 3833426,
"author_profile": "https://Stackoverflow.com/users/3833426",
"pm_score": 1,
"selected": false,
"text": "#!/usr/bin/env bash\n\nIFS=\" \" read -r -a WORDS <<< \"$(tr '\\n' ' ' < users_sl.txt)\"\n\necho processing ${#WORDS[@]} words\n\nfor (( i=0; i < ${#WORDS[@]}; i++ ))\ndo\n if [ \"${WORDS[$i]}\" = \"picture\" ]; then\n echo \"${WORDS[i+1]}\"\n fi\ndone | tee picturelist.txt\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74646404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10256749/"
] |
74,646,408
|
<p>What I want is to send encypted data from my app to PostgreSQL database via formatted string (query) by using Npgsql. Problem is that after sha256.ComputeHash() I get byte array which I'm trying to send by inserting it into my string query. It works fine but then in my dbms column I see System.Byte[] instead of byte array. How can I fix that?</p>
<p>My string query is something like that:</p>
<pre><code>private readonly SHA256 sha256 = SHA256.Create();
string sql = $"""
INSERT INT table(encrypted_column) VALUES (
'{sha256.ComputeHash(data)}');
""";
```[What in db after Query][1]
[1]: https://i.stack.imgur.com/9Ch7t.png
</code></pre>
|
[
{
"answer_id": 74646576,
"author": "Saif",
"author_id": 4777670,
"author_profile": "https://Stackoverflow.com/users/4777670",
"pm_score": 0,
"selected": false,
"text": "awk '/picture:/{getline; print}' users_sl.txt > output.txt\n"
},
{
"answer_id": 74646705,
"author": "Gilles Quenot",
"author_id": 465183,
"author_profile": "https://Stackoverflow.com/users/465183",
"pm_score": 0,
"selected": false,
"text": "$ perl -nE 'say for /\\bpicture\\b\\s+(\\w+)\\b/g' user_sl.txt | tee picturelist.txt\nlobortis\ntempus\ndictum\n"
},
{
"answer_id": 74646765,
"author": "Gilles Quenot",
"author_id": 465183,
"author_profile": "https://Stackoverflow.com/users/465183",
"pm_score": 0,
"selected": false,
"text": "$ awk '{\n for (i=1; i<=NF; i++) {\n if ($i == \"picture\") print $(i+1)\n }\n}' user_sl.txt | tee picturelist.txt\n $ printf '%s\\n' $(< users_sl.txt) |\n awk '/picture/{p=1;next} {if (p==1) {print;p=0}}' > picturelist.txt\n lobortis\ntempus\ndictum\n"
},
{
"answer_id": 74646779,
"author": "Jack",
"author_id": 2584475,
"author_profile": "https://Stackoverflow.com/users/2584475",
"pm_score": 1,
"selected": false,
"text": "picture **picture:** $ cat sl.txt \nLorem ipsum dolor sit amet, consectetur adipiscing elit,\nsed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\nQuis picture lobortis scelerisque fermentum dui faucibus in ornare quam.\nEst ullamcorper eget nulla facilisi etiam dignissim diam quis.\nQuis viverra nibh cras pulvinar mattis nunc sed.\nTurpis massa sed elementum picture tempus egestas.\nCondimentum vitae sapien pellentesque habitant.\nEt molestie ac feugiat sed lectus vestibulum mattis ullamcorper.\nTincidunt lobortis feugiat vivamus at augue eget arcu picture\ndictum varius. Donec massa sapien faucibus et molestie ac feugiat sed.\nTincidunt eget nullam non nisi est.\nOrnare arcu dui vivamus arcu.\nMattis enim ut tellus elementum sagittis vitae et leo duis\n\n$ cat sl.txt | tr '\\n' ' ' | grep -o 'picture [^ ]*' | cut -d' ' -f2\nlobortis\ntempus\ndictum\n tr '\\n' ' ' -o grep picture [^ ]* cut -d ' ' -f 2"
},
{
"answer_id": 74646931,
"author": "Gilles Quenot",
"author_id": 465183,
"author_profile": "https://Stackoverflow.com/users/465183",
"pm_score": 0,
"selected": false,
"text": "#!/bin/bash\n\narr=( $(<user_sl.txt) )\nfor ((i=0; i<${#arr[@]}; i++)); do\n if [[ ${arr[i]} == picture ]]; then\n printf '%s\\n' \"${arr[i+1]}\"\n fi\ndone | tee picturelist.txt\n lobortis\ntempus\ndictum\n"
},
{
"answer_id": 74646937,
"author": "john-jones",
"author_id": 322537,
"author_profile": "https://Stackoverflow.com/users/322537",
"pm_score": -1,
"selected": false,
"text": "cat textfile | \\\n grep -o 'picture:\\*\\*[^ ]*' | \\\n sed 's/.*\\*\\(.*\\)/\\1/g';\n"
},
{
"answer_id": 74647066,
"author": "Tobias Lins",
"author_id": 2160595,
"author_profile": "https://Stackoverflow.com/users/2160595",
"pm_score": -1,
"selected": false,
"text": "cat users_sl.txt | awk -F \"picture:\" '{print $2}' > picturelist.txt\n cat users_sl.txt awk -F \"picture:\" '{print $2}' awk $2 > picturelist.txt awk"
},
{
"answer_id": 74662054,
"author": "John",
"author_id": 3833426,
"author_profile": "https://Stackoverflow.com/users/3833426",
"pm_score": 1,
"selected": false,
"text": "#!/usr/bin/env bash\n\nIFS=\" \" read -r -a WORDS <<< \"$(tr '\\n' ' ' < users_sl.txt)\"\n\necho processing ${#WORDS[@]} words\n\nfor (( i=0; i < ${#WORDS[@]}; i++ ))\ndo\n if [ \"${WORDS[$i]}\" = \"picture\" ]; then\n echo \"${WORDS[i+1]}\"\n fi\ndone | tee picturelist.txt\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74646408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16632154/"
] |
74,646,435
|
<p>If a have a dataframe from which I get the total ocurrence of a value per year-month period, is there a way to change the month's start and end date?</p>
<p>For example, let's take this:</p>
<pre><code>import pandas as pd
data= {
'date':
[
'2022-01-10', '2022-01-24', '2022-02-08', '2022-02-23', '2022-03-10',
'2022-03-24', '2022-04-08', '2022-04-23', '2022-05-08', '2022-05-23',
'2022-06-06', '2022-06-21', '2022-07-06', '2022-07-21', '2022-08-05',
'2022-08-19', '2022-09-03', '2022-09-18', '2022-10-03', '2022-10-18',
'2022-11-01', '2022-11-16', '2022-12-01', '2022-12-16', '2022-12-31'
],
'status':
[
'no', 'yes', 'no', 'yes', 'no', 'yes', 'no', 'no', 'no', 'no',
'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no', 'no',
'no', 'yes', 'yes', 'yes', 'yes'
]
}
df= pd.DataFrame(data=data)
df.date = pd.to_datetime(df.date)
</code></pre>
<p>What I have now is this:</p>
<pre><code>df['period'] = df.date.dt.strftime('%Y-%m') # <-- this creates the 'period' column
check_yes = df['status'] == 'yes'
total_yes_period = df.loc[check_yes]['period'].value_counts().sort_index() # <-- obtain total 'yes' count per period
</code></pre>
<p>However, this works when a month is taken as 'June', 'November' (i.e. first to last day). My question is, is there a way to change this to a different period? (e.g. a 'month' starts on the 10th and ends on the 9th of the next).</p>
|
[
{
"answer_id": 74646576,
"author": "Saif",
"author_id": 4777670,
"author_profile": "https://Stackoverflow.com/users/4777670",
"pm_score": 0,
"selected": false,
"text": "awk '/picture:/{getline; print}' users_sl.txt > output.txt\n"
},
{
"answer_id": 74646705,
"author": "Gilles Quenot",
"author_id": 465183,
"author_profile": "https://Stackoverflow.com/users/465183",
"pm_score": 0,
"selected": false,
"text": "$ perl -nE 'say for /\\bpicture\\b\\s+(\\w+)\\b/g' user_sl.txt | tee picturelist.txt\nlobortis\ntempus\ndictum\n"
},
{
"answer_id": 74646765,
"author": "Gilles Quenot",
"author_id": 465183,
"author_profile": "https://Stackoverflow.com/users/465183",
"pm_score": 0,
"selected": false,
"text": "$ awk '{\n for (i=1; i<=NF; i++) {\n if ($i == \"picture\") print $(i+1)\n }\n}' user_sl.txt | tee picturelist.txt\n $ printf '%s\\n' $(< users_sl.txt) |\n awk '/picture/{p=1;next} {if (p==1) {print;p=0}}' > picturelist.txt\n lobortis\ntempus\ndictum\n"
},
{
"answer_id": 74646779,
"author": "Jack",
"author_id": 2584475,
"author_profile": "https://Stackoverflow.com/users/2584475",
"pm_score": 1,
"selected": false,
"text": "picture **picture:** $ cat sl.txt \nLorem ipsum dolor sit amet, consectetur adipiscing elit,\nsed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\nQuis picture lobortis scelerisque fermentum dui faucibus in ornare quam.\nEst ullamcorper eget nulla facilisi etiam dignissim diam quis.\nQuis viverra nibh cras pulvinar mattis nunc sed.\nTurpis massa sed elementum picture tempus egestas.\nCondimentum vitae sapien pellentesque habitant.\nEt molestie ac feugiat sed lectus vestibulum mattis ullamcorper.\nTincidunt lobortis feugiat vivamus at augue eget arcu picture\ndictum varius. Donec massa sapien faucibus et molestie ac feugiat sed.\nTincidunt eget nullam non nisi est.\nOrnare arcu dui vivamus arcu.\nMattis enim ut tellus elementum sagittis vitae et leo duis\n\n$ cat sl.txt | tr '\\n' ' ' | grep -o 'picture [^ ]*' | cut -d' ' -f2\nlobortis\ntempus\ndictum\n tr '\\n' ' ' -o grep picture [^ ]* cut -d ' ' -f 2"
},
{
"answer_id": 74646931,
"author": "Gilles Quenot",
"author_id": 465183,
"author_profile": "https://Stackoverflow.com/users/465183",
"pm_score": 0,
"selected": false,
"text": "#!/bin/bash\n\narr=( $(<user_sl.txt) )\nfor ((i=0; i<${#arr[@]}; i++)); do\n if [[ ${arr[i]} == picture ]]; then\n printf '%s\\n' \"${arr[i+1]}\"\n fi\ndone | tee picturelist.txt\n lobortis\ntempus\ndictum\n"
},
{
"answer_id": 74646937,
"author": "john-jones",
"author_id": 322537,
"author_profile": "https://Stackoverflow.com/users/322537",
"pm_score": -1,
"selected": false,
"text": "cat textfile | \\\n grep -o 'picture:\\*\\*[^ ]*' | \\\n sed 's/.*\\*\\(.*\\)/\\1/g';\n"
},
{
"answer_id": 74647066,
"author": "Tobias Lins",
"author_id": 2160595,
"author_profile": "https://Stackoverflow.com/users/2160595",
"pm_score": -1,
"selected": false,
"text": "cat users_sl.txt | awk -F \"picture:\" '{print $2}' > picturelist.txt\n cat users_sl.txt awk -F \"picture:\" '{print $2}' awk $2 > picturelist.txt awk"
},
{
"answer_id": 74662054,
"author": "John",
"author_id": 3833426,
"author_profile": "https://Stackoverflow.com/users/3833426",
"pm_score": 1,
"selected": false,
"text": "#!/usr/bin/env bash\n\nIFS=\" \" read -r -a WORDS <<< \"$(tr '\\n' ' ' < users_sl.txt)\"\n\necho processing ${#WORDS[@]} words\n\nfor (( i=0; i < ${#WORDS[@]}; i++ ))\ndo\n if [ \"${WORDS[$i]}\" = \"picture\" ]; then\n echo \"${WORDS[i+1]}\"\n fi\ndone | tee picturelist.txt\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74646435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20446652/"
] |
74,646,457
|
<p>I am tasked with looking for files in a network location with many many sub directories. My current implementation is based on answers I found on stackoverflow:</p>
<pre><code>private void PollFolder(string sourceDir)
{
try
{
// var start = DateTime.Now.AddHours(-_filesToGetTimeRangeFromNowInDays);
var start = DateTime.Now.AddMonths(-5);
var end = DateTime.Now;
var filesFromToolDir = Directory.GetFiles(sourceDir, "*.gz", SearchOption.AllDirectories)
.Where(f => new FileInfo(f).CreationTime >= start
&& new FileInfo(f).CreationTime <= end)
.ToArray();
}
catch (Exception ex)
{
}
}
</code></pre>
<p>I am supposed to filter files by creation date in a certain time range given by the user. Here I am using an example of 5 months. The issue with this function is that for some directories, it can take up to 5 hours to find files within a specified time range.</p>
<p><strong>My question</strong>: is there any way for me to optimize and make this file search across a network folder with many sub directories faster? Is there a better way to look for files?</p>
|
[
{
"answer_id": 74646905,
"author": "Gabriel Luci",
"author_id": 1202807,
"author_profile": "https://Stackoverflow.com/users/1202807",
"pm_score": 2,
"selected": false,
"text": "Directory.GetFiles() new FileInfo(f).CreationTime FileInfo DirectoryInfo.EnumerateFiles() FileInfo var start = DateTime.Now.AddMonths(-5);\nvar end = DateTime.Now;\n\nvar dir = new DirectoryInfo(sourceDir);\nvar filesFromToolDir = dir.EnumerateFiles(\"*.gz\", SearchOption.AllDirectories)\n .Where(f => f.CreationTime >= start \n && f.CreationTime <= end)\n .ToArray();\n EnumerateFiles Directory DirectoryInfo NtQueryDirectoryFile null FileName *.gz"
},
{
"answer_id": 74653764,
"author": "Max",
"author_id": 13523921,
"author_profile": "https://Stackoverflow.com/users/13523921",
"pm_score": 1,
"selected": false,
"text": "FileSearchOptions options = new FileSearchOptions(\n new string[] { \"*.*\" },\n DateTime.Now.AddMonths(-5),\n DateTime.Now\n);\nstring[] dirs = DirectoryUtil.GetDirectories(root, true);\nstring[] files = DirectoryUtil.LoadFiles(options, dirs);\n using System;\n\nnamespace Your.Namespace\n{\n /// <summary>\n /// Contains options for a file search.\n /// </summary>\n public struct FileSearchOptions\n {\n /// <summary>\n /// Array of file type filters.\n /// <para>Text file example: *.txt</para>\n /// </summary>\n public string[] FileTypes;\n /// <summary>\n /// The minimum creation timestamp of the file.\n /// </summary>\n public Nullable<DateTime> CreationTimeMin;\n /// <summary>\n /// The maximum creation timestamp of the file.\n /// </summary>\n public Nullable<DateTime> CreationTimeMax;\n /// <summary>\n /// The minimum last write timestamp of the file.\n /// </summary>\n public Nullable<DateTime> LastWriteTimeMin;\n /// <summary>\n /// The maximum last write timestamp of the file.\n /// </summary>\n public Nullable<DateTime> LastWriteTimeMax;\n\n\n public FileSearchOptions(\n string[] fileTypes,\n DateTime? createdMin = null,\n DateTime? createdMax = null,\n DateTime? lastWriteMin = null,\n DateTime? lastWriteMax = null)\n {\n FileTypes = fileTypes;\n CreationTimeMin = createdMin;\n CreationTimeMax = createdMax;\n LastWriteTimeMin = lastWriteMin;\n LastWriteTimeMax = lastWriteMax;\n }\n }\n}\n\n using System;\nusing System.Runtime.InteropServices;\n\n\nnamespace Your.Namespace\n{\n [StructLayout(LayoutKind.Sequential, Pack = 2)]\n internal struct SystemTime\n {\n public ushort Year;\n public ushort Month;\n public ushort DayOfWeek;\n public ushort Day;\n public ushort Hour;\n public ushort Minute;\n public ushort Second;\n public ushort Milliseconds;\n\n public SystemTime(DateTime dt)\n {\n dt = dt.ToUniversalTime();\n Year = Convert.ToUInt16(dt.Year);\n Month = Convert.ToUInt16(dt.Month);\n DayOfWeek = Convert.ToUInt16(dt.DayOfWeek);\n Day = Convert.ToUInt16(dt.Day);\n Hour = Convert.ToUInt16(dt.Hour);\n Minute = Convert.ToUInt16(dt.Minute);\n Second = Convert.ToUInt16(dt.Second);\n Milliseconds = Convert.ToUInt16(dt.Millisecond);\n }\n\n public SystemTime(ushort year, ushort month, ushort day, ushort hour = 0, ushort minute = 0, ushort second = 0, ushort millisecond = 0)\n {\n Year = year;\n Month = month;\n Day = day;\n Hour = hour;\n Minute = minute;\n Second = second;\n Milliseconds = millisecond;\n DayOfWeek = 0;\n }\n\n public static implicit operator DateTime(SystemTime st)\n {\n if (st.Year == 0 || st == MinValue)\n return DateTime.MinValue;\n if (st == MaxValue)\n return DateTime.MaxValue;\n\n //DateTime dt = new DateTime(st.Year, st.Month, st.Day, st.Hour, st.Minute, st.Second, st.Milliseconds, DateTimeKind.Utc);\n return new DateTime(st.Year, st.Month, st.Day, st.Hour, st.Minute, st.Second, st.Milliseconds, DateTimeKind.Utc);\n }\n\n public static bool operator ==(SystemTime s1, SystemTime s2)\n {\n return (s1.Year == s2.Year \n && s1.Month == s2.Month \n && s1.Day == s2.Day \n && s1.Hour == s2.Hour \n && s1.Minute == s2.Minute \n && s1.Second == s2.Second \n && s1.Milliseconds == s2.Milliseconds);\n }\n\n public static bool operator !=(SystemTime s1, SystemTime s2)\n {\n return !(s1 == s2);\n }\n\n public static readonly SystemTime MinValue, MaxValue;\n\n static SystemTime()\n {\n MinValue = new SystemTime(1601, 1, 1);\n MaxValue = new SystemTime(30827, 12, 31, 23, 59, 59, 999);\n }\n\n public override bool Equals(object obj)\n {\n if (obj is SystemTime)\n return ((SystemTime)obj) == this;\n return base.Equals(obj);\n }\n\n public override int GetHashCode()\n {\n return base.GetHashCode();\n }\n }\n}\n\n using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing ComTypes = System.Runtime.InteropServices.ComTypes;\nusing System.IO;\nusing System.Runtime.ConstrainedExecution;\nusing System.Security;\n\nnamespace Your.Namespace\n{\n internal static class DirectoryUtil\n {\n //\n // Searches a directory for a file or subdirectory \n // with a name and attributes that match specified.\n //\n [DllImport(\"kernel32.dll\", SetLastError = true, CharSet = CharSet.Unicode)]\n private static extern IntPtr FindFirstFileExW(\n string lpFileName, // The directory or path, and the file name.\n FINDEX_INFO_LEVELS fInfoLevelId, // The information level of the returned data.\n out WIN32_FIND_DATA lpFindFileData, // A pointer to the buffer that receives the file data.\n FINDEX_SEARCH_OPS fSearchOp, // The type of filtering to perform\n // that is different from wildcard matching.\n IntPtr lpSearchFilter, // A pointer to the search criteria if the specified fSearchOp \n // needs structured search information.\n int dwAdditionalFlags // Specifies additional flags that control the search.\n );\n\n\n //\n // Continues a file search from a previous call to the \n // FindFirstFileExW function.\n //\n [DllImport(\"kernel32.dll\", SetLastError = true, CharSet = CharSet.Auto)]\n private static extern bool FindNextFile(\n IntPtr hFindFile, // The search handle returned by a previous call\n // to the FindFirstFileExW function.\n out WIN32_FIND_DATA lpFindFileData // A pointer to the WIN32_FIND_DATA structure\n // that receives information about the found file or subdirectory.\n );\n\n\n //\n // Converts a file time to system time format.\n // System time is based on UTC.\n //\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n private static extern bool FileTimeToSystemTime(\n [In] ref ComTypes.FILETIME lpFileTIme, // A pointer to a FILETIME structure containing \n // the file time to be converted to system UTC.\n out SystemTime lpSystemTime // A pointer to a SYSTEMTIME structure to\n // receive the converted file time.\n );\n\n\n //\n // Contains information about the file that is found by\n // the FindFirstFileExW function.\n //\n [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]\n internal struct WIN32_FIND_DATA\n {\n [MarshalAs(UnmanagedType.U4)]\n public FileAttributes dwFileAttributes; // The file attributes of a file.\n public ComTypes.FILETIME ftCreationTime; // A FILETIME structure taht specifies\n // when a file or directory was created.\n public ComTypes.FILETIME ftLastAccessTime; // A FILETIME structure that specifies \n // when the file was last read from, written to, or run (.exe).\n public ComTypes.FILETIME ftLastWriteTime; // A FILETIME structure that specifies\n // when the files was last written to, trucated, or overwritten.\n public uint nFileSizeHigh; // The high-order DWORD value of the file size, in bytes.\n public uint nFileSizeLow; // The low-order DWORD value of the file size, in bytes.\n public uint dwReserved0; // If the dwFileAttributes member includes the FILE_ATTRIBUTE_REPARSE_POINT\n // attribute, this member specifies the reparse point tag.\n public uint dwReserved1; // Reserved for future use.\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]\n public string cFileName; // The name of the file.\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]\n public string cAlternateFileName; // An alternative name for the file.\n public uint dwFileType; // Obsolete. Do not use.\n public uint dwCreatorType; // Obsolete. Do not use.\n public uint wFinderFlags; // Obsolete. Do not use.\n }\n\n\n // \n // Defines values that are used with the FindFirstFileEx\n // function to specify the information level of the returned data.\n //\n internal enum FINDEX_INFO_LEVELS\n {\n // The FindFirstFileEx function retrieves a\n // standard set of attribute information. The data is returned in a\n FindExInfoStandard = 0,\n // The FindFirstFileEx function does not query the short file name,\n // improving overall enumeration speed. The data is returned in a\n // WIN32_FIND_DATA structure, and the cAlternateFileName\n // member is always a NULL string.\n // This value is not supported until Windows Server 2008 R2 and Windows 7.\n FindExInfoBasic = 1\n }\n\n\n //\n // Defines values that are used with the FindFirstFileEx\n // function to specify the type of filtering to perform.\n //\n internal enum FINDEX_SEARCH_OPS\n {\n // The search for a file that matches a specified file name.\n FindExSearchNameMatch = 0,\n // This is an advisory flag.\n // If the file system supports directory filtering, the function\n // searches for a file that matches the specified name and is also a directory.\n // If the file system does not support directory filtering,\n // this flag is silently ignored.\n FindExSearchLimitToDirectories = 1,\n // This filtering type is not available.\n FindExSearchLimitToDevices = 2\n }\n\n\n // Searches are case-sensitive. \n private const int FIND_FIRST_EX_CASE_SENSITIVE = 1;\n // Uses a larger buffer for directory queries,\n // which can increase performance of the find operation. \n // This value is not supported until Windows Server 2008 R2 and Windows 7.\n private const int FIND_FRIST_EX_LARGE_FETCH = 2;\n // Limits the results to files that are physically on disk.\n // This flag is only relevant when a file virtualization filter is present. \n private const int FIND_FIRST_EX_ON_DISK_ENTRIES_ONLY = 4;\n\n // Invalid pointer value.\n private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);\n\n\n // Caught Win32 errors.\n private static List<string> _errors = new List<string>();\n public static string LastError\n {\n get {\n return _errors[_errors.Count - 1];\n }\n }\n public static string[] Errors\n {\n get {\n return _errors.ToArray();\n }\n }\n\n\n //\n // Formats a file path to match the search format \n // of the FindFirstFileExW function.\n //\n private static readonly Func<string, string, string> FormatFilePath = (s, f) =>\n {\n if (s.EndsWith(\".\") || s.EndsWith(\"..\")) {\n return string.Empty;\n }\n\n if (s.EndsWith(\"\\\\\")) {\n s += f;\n }\n\n if (!(s.EndsWith(\"\\\\\" + f))) {\n s += \"\\\\\" + f;\n }\n\n if (s == \".\\\\*\" || s == \"..\\\\*\") {\n return string.Empty;\n }\n return s;\n };\n\n\n //\n // Formats a directory path to match the search format \n // of the FindFirstFileExW function.\n //\n private static readonly Func<string, string> FormatPath = (s) =>\n {\n if (s.EndsWith(\".\") || s.EndsWith(\"..\")) {\n return string.Empty;\n }\n\n if (s.EndsWith(\"\\\\\")) {\n s += \"*\";\n }\n\n if (!(s.EndsWith(\"\\\\*\"))) {\n s += \"\\\\*\";\n }\n\n if (s == \".\\\\*\" || s == \"..\\\\*\") {\n return string.Empty;\n }\n return s;\n };\n\n\n //\n // Gets all files in the specified directory\n // and adds them to the referenced list object.\n //\n private static void LoadFilesInternal(\n string dir, \n string fileType, \n FileSearchOptions options, \n ref List<string> files)\n {\n // Get standard set of information.\n FINDEX_INFO_LEVELS findLevel = FINDEX_INFO_LEVELS.FindExInfoStandard;\n // File name search.\n FINDEX_SEARCH_OPS findOps = FINDEX_SEARCH_OPS.FindExSearchNameMatch;\n\n int additionalFlags = 0;\n // Check if OS version is later supported\n // OS beginning from WinSvr 2008 R2 and Win 7\n if (Environment.OSVersion.Version.Major >= 6) {\n // Ingore short file name to improve performance.\n findLevel = FINDEX_INFO_LEVELS.FindExInfoBasic;\n // Use larger buffer.\n additionalFlags = FIND_FRIST_EX_LARGE_FETCH;\n }\n\n // Format path to match FindFirstFileExW pattern.\n string search = FormatFilePath(dir, fileType);\n if (string.IsNullOrEmpty(search)) {\n return;\n }\n\n WIN32_FIND_DATA ffd;\n // Try to get handle to first file system object.\n IntPtr hFind = FindFirstFileExW(\n search, findLevel,\n out ffd, findOps,\n IntPtr.Zero, additionalFlags\n );\n\n // FindFirstFileExW failed...\n if (INVALID_HANDLE_VALUE == hFind) {\n int err = Marshal.GetLastWin32Error();\n _errors.Add(\"FindFirstFileExW returned Win32 error: \" + err);\n return;\n }\n\n // Stores the end of the path without search pattern.\n // Used to create new file name.\n string end = string.Empty;\n // Stores the new concatinated file name.\n string newDir = string.Empty;\n // SystemTime used to convert WinAPI FILETIME to DateTime.\n SystemTime st;\n // Stores the file creation time.\n DateTime ct;\n // Stores the file last write time.\n DateTime lw;\n // Check if options has a creation time timespan.\n bool hasCreationTime = options.CreationTimeMin.HasValue && options.CreationTimeMax.HasValue;\n // Check if options has a last write time timespan.\n bool hasWriteTime = options.LastWriteTimeMin.HasValue && options.LastWriteTimeMax.HasValue;\n\n do\n {\n // Ignore if handle points to directory.\n if ((ffd.dwFileAttributes & FileAttributes.Directory) \n == FileAttributes.Directory) \n {\n continue;\n }\n\n // Ignore if handle points to current directory \n // or top-level directory.\n if (ffd.cFileName == \"..\" || ffd.cFileName == \".\") {\n continue;\n }\n\n // Convert FILETIME to SystemTime and \n // SystemTime to .Net DateTime.\n FileTimeToSystemTime(ref ffd.ftCreationTime, out st); \n ct = (DateTime)st;\n FileTimeToSystemTime(ref ffd.ftLastWriteTime, out st);\n lw = (DateTime)st;\n \n // No creation time or write is specified.\n if (!(hasCreationTime) && !(hasWriteTime)) {\n end = search.Replace(\"\\\\\" + fileType, string.Empty);\n newDir = end + Path.DirectorySeparatorChar + ffd.cFileName;\n files.Add(newDir);\n }\n // Creation time is specified and write time is not.\n else if ((hasCreationTime && !(hasWriteTime)) &&\n (ct <= options.CreationTimeMax \n && ct >= options.CreationTimeMin)) \n {\n end = search.Replace(\"\\\\\" + fileType, string.Empty);\n newDir = end + Path.DirectorySeparatorChar + ffd.cFileName;\n files.Add(newDir);\n }\n // Creation time is not specified and write time is.\n else if ((!(hasCreationTime) && hasWriteTime) &&\n lw <= options.LastWriteTimeMax \n && lw >= options.LastWriteTimeMin) \n {\n end = search.Replace(\"\\\\\" + fileType, string.Empty);\n newDir = end + Path.DirectorySeparatorChar + ffd.cFileName;\n files.Add(newDir);\n }\n // Creation time and write time is specified.\n else if (hasCreationTime && hasWriteTime &&\n (ct <= options.CreationTimeMax\n && ct >= options.CreationTimeMin) &&\n lw <= options.LastWriteTimeMax\n && lw >= options.LastWriteTimeMin)\n {\n end = search.Replace(\"\\\\\" + fileType, string.Empty);\n newDir = end + Path.DirectorySeparatorChar + ffd.cFileName;\n files.Add(newDir);\n }\n } \n while (FindNextFile(hFind, out ffd));\n }\n\n\n /// <summary>\n /// Loads all files in the referenced directories.\n /// </summary>\n /// <param name=\"options\">Options for the file search.</param>\n public static string[] LoadFiles(FileSearchOptions options, ICollection<string> directories)\n {\n if (options.FileTypes == null) {\n options.FileTypes = new string[] { \"*.*\" };\n }\n\n if (options.FileTypes.Length == 0) {\n options.FileTypes = new string[] { \"*.*\" };\n }\n\n // Iterate through directories and add all filtered files.\n List<string> files = new List<string>();\n foreach (string filter in options.FileTypes) {\n foreach (string dir in directories) {\n LoadFilesInternal(dir, filter, options, ref files);\n }\n }\n return files.ToArray();\n }\n\n\n\n /// <summary>\n /// Adds all directories within the root directory \n /// to an existing array of directories.\n /// </summary>\n /// <param name=\"root\">The root directory.</param>\n /// <param name=\"directories\">The array to add the new directories.</param>\n /// <param name=\"recursive\">TRUE to get all sub-directories recursivly.</param>\n public static void AddDirectory(string root, ref string[] directories, bool recursive = false)\n { \n if (!(directories.Contains(root)) && !(recursive)) {\n string[] dirNew = new string[directories.Length + 1];\n Buffer.BlockCopy(directories, 0, dirNew, 0, directories.Length);\n dirNew[dirNew.Length - 1] = root;\n directories = dirNew;\n dirNew = new string[0];\n dirNew = null;\n }\n else if (!(directories.Contains(root)) && recursive) {\n List<string> dirTemp = new List<string>();\n dirTemp.AddRange(directories);\n GetDirectoriesRecursInternal(root, ref dirTemp);\n directories = dirTemp.ToArray();\n }\n }\n\n\n //\n // Gets all the directories and sub-directories \n // in the specified root directory.\n //\n private static void GetDirectoriesRecursInternal(string dir, ref List<string> directories)\n {\n // Get standard set of information.\n FINDEX_INFO_LEVELS findLevel = FINDEX_INFO_LEVELS.FindExInfoStandard;\n // File name search.\n FINDEX_SEARCH_OPS findOps = FINDEX_SEARCH_OPS.FindExSearchNameMatch;\n\n int additionalFlags = 0;\n // Check if OS version is later supported\n // OS beginning from WinSvr 2008 R2 and Win 7.\n if (Environment.OSVersion.Version.Major >= 6) {\n // Ignore short file name to improve performance.\n findLevel = FINDEX_INFO_LEVELS.FindExInfoBasic;\n // Use larger buffer.\n additionalFlags = FIND_FRIST_EX_LARGE_FETCH;\n }\n\n // Format path to match FindFirstFileExW pattern.\n dir = FormatPath(dir);\n if (string.IsNullOrEmpty(dir)) {\n return;\n }\n\n WIN32_FIND_DATA ffd;\n // Try to get handle to first file system object.\n IntPtr hFind = FindFirstFileExW(\n dir, findLevel,\n out ffd, findOps,\n IntPtr.Zero, additionalFlags\n );\n\n // FindFirstFileExW failed...\n if (INVALID_HANDLE_VALUE == hFind) {\n int err = Marshal.GetLastWin32Error();\n _errors.Add(\"FindFirstFileExW returned Win32 error: \" + err);\n return;\n }\n\n // Stores end of directory name without search pattern.\n // Used to create new directory name.\n string end = string.Empty;\n // Stores the new concatinated directory name.\n string newDir = string.Empty;\n\n do\n {\n // Check if handle points to directory.\n if ((ffd.dwFileAttributes & FileAttributes.Directory) \n == FileAttributes.Directory)\n {\n // Ignore if handle points to current directory\n // or top-level directory.\n if (ffd.cFileName != \"..\" && ffd.cFileName != \".\") {\n // Remove wildcard from current directory.\n end = dir.Replace(\"\\\\*\", string.Empty);\n // Create new directory name.\n newDir = end + Path.DirectorySeparatorChar + ffd.cFileName;\n directories.Add(newDir);\n GetDirectoriesRecursInternal(newDir, ref directories);\n }\n }\n } while (FindNextFile(hFind, out ffd));\n }\n\n\n //\n // Gets all the directories in the specified root directory.\n //\n private static void GetDirectoriesInternal(string root, ref List<string> directories)\n {\n // Get standard set of information.\n FINDEX_INFO_LEVELS findLevel = FINDEX_INFO_LEVELS.FindExInfoStandard;\n // File name search.\n FINDEX_SEARCH_OPS findOps = FINDEX_SEARCH_OPS.FindExSearchNameMatch;\n\n int additionalFlags = 0;\n // Check if OS version is later supported\n // OS beginning from WinSvr 2008 R2 and Win 7.\n if (Environment.OSVersion.Version.Major >= 6) {\n // Ignore short file name to improve performance.\n findLevel = FINDEX_INFO_LEVELS.FindExInfoBasic;\n // Use larger buffer.\n additionalFlags = FIND_FRIST_EX_LARGE_FETCH;\n }\n\n // Format path to match FindFirstFileExW pattern.\n root = FormatPath(root);\n if (string.IsNullOrEmpty(root)) {\n return;\n }\n\n WIN32_FIND_DATA ffd;\n // Try to get handle to first file system object.\n IntPtr hFind = FindFirstFileExW(\n root, findLevel,\n out ffd, findOps,\n IntPtr.Zero, additionalFlags\n );\n\n // FindFirstFileExW failed... \n if (INVALID_HANDLE_VALUE == hFind) {\n int err = Marshal.GetLastWin32Error();\n _errors.Add(\"FindFirstFileExW returned Win32 error: \" + err);\n return;\n }\n\n // Stores end of directory name without search pattern.\n // Used to create new directory name.\n string end = string.Empty;\n // Stores the new concatinated directory name.\n string newDir = string.Empty;\n\n do\n {\n // Check if handle points to a directory.\n if ((ffd.dwFileAttributes & FileAttributes.Directory) \n == FileAttributes.Directory)\n {\n // Ingore if handle points to current directory\n // or top-level directory.\n if (ffd.cFileName != \"..\" && ffd.cFileName != \".\") {\n // Remove wildcard from current directory.\n end = root.Replace(\"\\\\*\", string.Empty);\n // Create new directory name.\n newDir = end + Path.DirectorySeparatorChar + ffd.cFileName;\n directories.Add(newDir);\n }\n }\n } while (FindNextFile(hFind, out ffd));\n }\n\n\n /// <summary>\n /// Gets all directories from the root directory.\n /// </summary>\n /// <param name=\"root\">The root directory.</param>\n /// <param name=\"recurse\">TRUE to get all sub-directories recursivly.</param>\n /// <returns></returns>\n public static string[] GetDirectories(string root, bool recurse = true)\n {\n List<string> list = new List<string>();\n if (recurse) {\n // Get all sub-directories.\n GetDirectoriesRecursInternal(root, ref list);\n }\n else {\n // Top-level directories only.\n GetDirectoriesInternal(root, ref list);\n }\n return list.ToArray();\n }\n }\n}\n\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74646457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17784579/"
] |
74,646,486
|
<p>I want to try out Python 3.11 to find out how much faster this version is than what I'm currently using (3.7.3). I am using Anaconda and Spyder, but Anaconda does not yet support Python 3.11 and additionally I regularly have problems with updating in Anaconda.</p>
<p>Importantly, I want to maintain my Anaconda and Spyder environments as it is and use Python 3.11 independently from this. Therefore, I was wondering if simply downloading Python 3.11 from their website will mess up my environment, as then there will be two versions of Python insalled on my PC. Also I would like to know if I have to use a different IDE for this (or even without IDE).</p>
<p>Even though my question might be a bit vague, thanks in advance.</p>
|
[
{
"answer_id": 74646605,
"author": "Saif",
"author_id": 4777670,
"author_profile": "https://Stackoverflow.com/users/4777670",
"pm_score": -1,
"selected": false,
"text": "conda create -n py311 python=3.11\n conda activate py311\n conda deactivate\n conda install numpy scipy pandas\n"
},
{
"answer_id": 74650018,
"author": "Alex Granovsky",
"author_id": 1351877,
"author_profile": "https://Stackoverflow.com/users/1351877",
"pm_score": 0,
"selected": false,
"text": "<your.version> <any.over.version>"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74646486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20387372/"
] |
74,646,588
|
<p>I have a dataframe with 3 columns, x-points, y-points and the heat. Like this:</p>
<pre><code>X, Y, Z
-2, 0, 1
-2, 1, 2
-2, 2, 5
-1, 0, 3
-1, 1, 5
-1, 2, 8
.., .., ..
2, 1, 4
2, 2, 1
</code></pre>
<p>I want to plot a heatmap of this data with X and Y being the coords, and Z being the heat.</p>
<p>I have tried lots of ways to do this and constantly run into different errors.</p>
|
[
{
"answer_id": 74646649,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": true,
"text": "pivot seaborn.heatmap import seaborn as sns\n\nsns.heatmap(df.pivot(index='Y', columns='X', values='Z'))\n df2 = (df\n .pivot(index='Y', columns='X', values='Z')\n .pipe(lambda d: d.reindex(index=range(d.index.min(), d.index.max()+1),\n columns=range(d.columns.min(), d.columns.max()+1),\n )\n )\n)\n\nsns.heatmap(df2)\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74646588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17824108/"
] |
74,646,592
|
<p>Im making a turtle race game, its a game where there are a few turtles who are assigned random speeds and then one turtle wins. However, just for fun im trying to add a few things to the game. For example, a button to exit the game and a button to restart the race. I have made only the exit button for now, and gave the command to exit the game. The button works, however not in the right time.</p>
<p>The problem is is that i have a piece of code that makes the canvas (background), Which is just the turtle drawing. I have another piece of code that places the buttons and tells them what to do when being clicked. And then I have a piece of code that assigns random speeds to the turtles.</p>
<p>This is the buttons code.(The try again button command is not finished yet.)</p>
<pre><code>screen = Screen()
screen.setup(width=600, height=400)
def exit_game():
exit()
canvas = screen.getcanvas()
button = Button(canvas.master, text="Exit Game", command=exit_game, width=10, height=4, fg="white", bg="dodgerblue")
button.pack()
button.place(x=150, y=530)
canvas2 = screen.getcanvas()
button2 = Button(canvas2.master, text="Try Again", command=exit_game, width=10, height=4, fg="white", bg="dodgerblue" )
button2.pack()
button2.place(x=50, y=530)
</code></pre>
<p>And here is the code for assigning random numbers to the turtles.</p>
<pre><code>for movement in range (230):
red.forward(randint(1,8))
blue.forward(randint(1,8))
purple.forward(randint(1,8))
orange.forward(randint(1,8))
</code></pre>
<p>The problem is, is that when for example the turtles are moving, i can press the button, but it does not do the command. After the movement loop goes through 230 times, only then it exits the game. So basically my code is just reading the speed to the turtles and forgot about the button commands.</p>
<p>Is there a way to override this somehow and make my button exit the game when being clicked at all times?<br />
Also i did try to put the button into an infinite loop, but it did not work(maybe I did it wrong).</p>
<pre><code>import turtle
import time
from random import randint
from tkinter import *
from turtle import Screen, Turtle
import tkinter
import tkinter as tk
# Window Customization
Window = turtle.Screen()
Window.title('Turtle Race Game')
#Complete back canvas for the game
def back_canvas():
# Main drawing turtle
pen = turtle.Turtle()
pen.speed(0)
# far left -640; far right 633
#top 330; bottom -320
# Landscape making
#Making the ground
pen.hideturtle()
pen.color("sienna")
pen.penup()
pen.left(90)
pen.setpos(-640, -320)
pen.pendown()
pen.begin_fill()
pen.color("sienna")
for i in range(2):
pen.forward(162.5)
pen.right(90)
pen.forward(1272)
pen.right(90)
pen.end_fill()
#Making Racing Area
for i in range(2):
pen.forward(162.5)
pen.color("lime")
pen.begin_fill()
for i in range(2):
pen.forward(162.5)
pen.right(90)
pen.forward(1272)
pen.right(90)
pen.end_fill()
#Making Top Area
pen.color("dodgerblue")
pen.begin_fill()
pen.forward(162.5)
for i in range(2):
pen.forward(162.5)
pen.right(90)
pen.forward(1272)
pen.right(90)
pen.end_fill()
pen.penup()
# Writing "Turtle Race Game"
pen.color('lime')
pen.setpos(-170,250)
pen.color("black")
pen.write("Turtle Race Game",pen, font=("Arial", 27, 'normal'))
# Making the first finishline
pen.setpos(500,143)
pen.right(180)
for i in range(7):
pen.color('black')
pen.begin_fill()
pen.left(90)
pen.forward(20)
pen.right(90)
pen.forward(20)
pen.right(90)
pen.forward(20)
pen.right(90)
pen.forward(20)
pen.right(180)
pen.forward(20)
pen.end_fill()
pen.color('white')
pen.begin_fill()
pen.left(90)
pen.forward(20)
pen.right(90)
pen.forward(20)
pen.right(90)
pen.forward(20)
pen.right(90)
pen.forward(20)
pen.right(180)
pen.forward(20)
pen.end_fill()
# Making the second finishline
pen.setpos(520,143)
for i in range(7):
pen.color('white')
pen.begin_fill()
pen.left(90)
pen.forward(20)
pen.right(90)
pen.forward(20)
pen.right(90)
pen.forward(20)
pen.right(90)
pen.forward(20)
pen.right(180)
pen.forward(20)
pen.end_fill()
pen.color('black')
pen.begin_fill()
pen.left(90)
pen.forward(20)
pen.right(90)
pen.forward(20)
pen.right(90)
pen.forward(20)
pen.right(90)
pen.forward(20)
pen.right(180)
pen.forward(20)
pen.end_fill()
# placing main pen to right place to say who won
pen.setpos(520,180)
# Making all the turtles
def race():
# Making the turtles, turtle 1
red = turtle.Turtle()
red.speed(0)
red.shape("turtle")
red.penup()
red.color("red")
red.setpos(-550, 90)
red.pendown()
# Making the turtles, turtle 2
blue = turtle.Turtle()
blue.shape("turtle")
blue.speed(0)
blue.penup()
blue.color("blue")
blue.setpos(-550,30)
blue.pendown()
# Making the turtles, turtle 3
purple = turtle.Turtle()
purple.speed(0)
purple.shape("turtle")
purple.penup()
purple.color("purple")
purple.setpos(-550,-30)
purple.pendown()
# Making the turtles, turtle 4
orange = turtle.Turtle()
orange.speed(0)
orange.shape("turtle")
orange.penup()
orange.color("orange")
orange.setpos(-550,-90)
orange.pendown()
race_step_count = 230
if race_step_count:
red.forward(randint(1,8))
blue.forward(randint(1,8))
purple.forward(randint(1,8))
orange.forward(randint(1,8))
race_step_count -= 1
next_step = Window.after(100, race) # call this function again after 100mS
else: # no more steps - the race is over!
Window.after_cancel(next_step) # stop calling the race function
def main_game():
run = True
screen = Screen()
screen.setup(width=600, height=400)
def exit_game():
exit()
canvas = screen.getcanvas()
button = Button(canvas.master, text="Exit Game",command = exit_game ,width= 10, height = 4, fg = "white", bg = "dodgerblue")
button.place(x=150, y=530)
canvas2 = screen.getcanvas()
button2 = Button(canvas2.master, text="Try Again",command = exit_game, width= 10, height = 4,fg = "white", bg = "dodgerblue" )
button2.place(x=50, y=530)
#Complete back canvas for the game
back_canvas()
# Making all the turtles
race()
main_game()
# Making my button do something when being clicked
# Making the turtles stop when hitting the finish line
time.sleep(1)
#Writing who won
def who_won():
for i in range(1):
if blue.xcor() > red.xcor() and blue.xcor() > purple.xcor() and blue.xcor() > orange.xcor():
time.sleep(1)
pen.write('Blue won!', align = "center", font =("Arial", 25, "bold"))
elif red.xcor() > blue.xcor() and red.xcor() > purple.xcor() and red.xcor() > orange.xcor():
time.sleep(1)
pen.write('Red won!', align = "center", font =("Arial", 25, "bold"))
elif purple.xcor() > blue.xcor() and purple.xcor() > red.xcor() and purple.xcor() > orange.xcor():
time.sleep(1)
pen.write('Purple won!', align = "center", font =("Arial", 25, "bold"))
elif orange.xcor() > blue.xcor() and orange.xcor() > red.xcor() and orange.xcor() > purple.xcor():
time.sleep(1)
pen.write('Orange won!', align = "center", font =("Arial", 25, "bold"))
else:
continue
# Window doesnt close on its own
Window.mainloop()
</code></pre>
|
[
{
"answer_id": 74646897,
"author": "JRiggles",
"author_id": 8512262,
"author_profile": "https://Stackoverflow.com/users/8512262",
"pm_score": 1,
"selected": false,
"text": "tkinter.after() after # I don't know what your imports look like, so this is a boilerplate example\nimport tkinter as tk\n\nroot = tk.Tk() # this is whatever you're calling 'mainloop()' on right now\nrace_step_count = 230 # define how 'long' the race is\n\n\ndef race():\n global race_step_count\n if race_step_count:\n red.forward(randint(1,8))\n blue.forward(randint(1,8))\n purple.forward(randint(1,8))\n orange.forward(randint(1,8))\n race_step_count -= 1\n next_step = root.after(100, race) # call this function again after 100mS\n else: # no more steps - the race is over!\n root.after_cancel(next_step) # stop calling the race function\n race()"
},
{
"answer_id": 74660701,
"author": "cdlane",
"author_id": 5771269,
"author_profile": "https://Stackoverflow.com/users/5771269",
"pm_score": 1,
"selected": true,
"text": "AttributeError: '_Screen' object has no attribute 'after'\n \"Exit Game\" from random import randint\nfrom turtle import TurtleScreen, RawTurtle\nimport tkinter as tk\nimport sys\n\ndef back_canvas():\n # Landscape making\n # Making the ground\n\n pen.color('sienna')\n\n pen.penup()\n pen.setpos(-640, -162.5)\n pen.pendown()\n\n pen.begin_fill()\n\n for _ in range(2):\n pen.forward(1280)\n pen.right(90)\n pen.forward(162.5)\n pen.right(90)\n\n pen.end_fill()\n\n # Making Racing Area\n\n pen.color('lime')\n pen.begin_fill()\n\n for _ in range(2):\n pen.forward(1280)\n pen.left(90)\n pen.forward(325)\n pen.left(90)\n\n pen.end_fill()\n\n # Making Top Area\n\n pen.color('dodgerblue')\n pen.begin_fill()\n pen.left(90)\n pen.forward(325)\n\n for _ in range(2):\n pen.forward(162.5)\n pen.right(90)\n pen.forward(1280)\n pen.right(90)\n\n pen.end_fill()\n pen.penup()\n\n # Writing \"Turtle Race Game\"\n pen.color('lime')\n pen.setpos(0, 250)\n pen.color('black')\n pen.write(\"Turtle Race Game\", align='center', font=('Arial', 27, 'normal'))\n\n # Making the first finish line\n pen.right(90)\n pen.setpos(500, 143)\n\n def flag():\n pen.color('black')\n pen.begin_fill()\n\n for _ in range(4):\n pen.forward(20)\n pen.right(90)\n\n pen.end_fill()\n pen.forward(20)\n\n pen.color('white')\n pen.begin_fill()\n\n for _ in range(4):\n pen.forward(20)\n pen.right(90)\n\n pen.end_fill()\n pen.forward(20)\n\n for _ in range(7):\n flag()\n\n pen.right(90)\n pen.forward(40)\n pen.right(90)\n\n flag()\n\n pen.right(180)\n\n # placing main pen to right place to say who won\n pen.setpos(520, 180)\n\nrace_step_count = 230\n\ndef race():\n global race_step_count\n\n if race_step_count > 0:\n red.forward(randint(1, 8))\n blue.forward(randint(1, 8))\n purple.forward(randint(1, 8))\n orange.forward(randint(1, 8))\n\n race_step_count -= 1\n screen.ontimer(race, 100) # call this function again after 100mS\n else:\n who_won()\n\ndef who_won():\n if blue.xcor() > red.xcor() and blue.xcor() > purple.xcor() and blue.xcor() > orange.xcor():\n pen.write(\"Blue won!\", align='center', font=('Arial', 25, 'bold'))\n elif red.xcor() > blue.xcor() and red.xcor() > purple.xcor() and red.xcor() > orange.xcor():\n pen.write(\"Red won!\", align='center', font=('Arial', 25, 'bold'))\n elif purple.xcor() > blue.xcor() and purple.xcor() > red.xcor() and purple.xcor() > orange.xcor():\n pen.write(\"Purple won!\", align='center', font=('Arial', 25, 'bold'))\n elif orange.xcor() > blue.xcor() and orange.xcor() > red.xcor() and orange.xcor() > purple.xcor():\n pen.write(\"Orange won!\", align='center', font=('Arial', 25, 'bold'))\n\nmaster = tk.Tk()\nmaster.title(\"Turtle Race Game\")\n\ncanvas = tk.Canvas(master, width=1280, height=650)\ncanvas.pack()\n\nscreen = TurtleScreen(canvas)\n\ntk.Button(master, text=\"Exit Game\", command=sys.exit, width=0, height=4, fg='gold', bg='dodgerblue').pack()\n\n# Main drawing turtle\npen = RawTurtle(screen)\npen.hideturtle()\npen.speed('fastest')\n\nback_canvas()\n\nred = RawTurtle(screen)\nred.speed('fastest')\nred.shape('turtle')\nred.penup()\n\nred.color('red')\nred.setpos(-550, 90)\n\nblue = red.clone()\nblue.color('blue')\nblue.setpos(-550, 30)\n\npurple = red.clone()\npurple.color('purple')\npurple.setpos(-550, -30)\n\norange = red.clone()\norange.color('orange')\norange.setpos(-550, -90)\n\nrace()\n\nscreen.mainloop()\n import import"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74646592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19874383/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.