qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,640,085
|
<p>Regarding best practice in creating routes in Node.Js Express.Js. For example, if I have 4 roles, namely headmaster, student and teacher, then I have a route called <code>/sliders</code>, which in the application these sliders can be seen by both teacher, student, and administrator only.</p>
<p>When creating routes and middleware for checking roles, what are the best practices?</p>
<p>I.
Should I create 1 endpoints and 1 middleware that can be access by student and teacher only?</p>
<p>For example:</p>
<pre><code>v1.get('/sliders', isUserOrTeacher, controller.findAll)
</code></pre>
<p>and my middleware code:</p>
<pre><code>const isUserOrTeacher = (req, res, next) => {
User.findById(req.payload.aud).exec((err, user) => {
if (err) {
res.status(500).send({ message: err })
return
}
Role.find(
{
_id: { $in: user.roles }
},
(err, roles) => {
if (err) {
res.status(500).send({ message: err })
return
}
for (let i = 0; i < roles.length; i++) {
if (roles[i].name === 'student' || roles[i].name === 'teacher' || roles[i].name === 'admin') {
next()
return
}
}
logger.error(req.method, req.originalUrl, '. Error isUserOrTeacher: ' + req.payload)
return sendUnauthorized(res)
}
)
})
}
</code></pre>
<p>II.
or i should make 2 different endpoint and 2 middleware</p>
<p>for example:</p>
<pre><code>v1.get('/user/sliders', isUser, controller.findAll)
v1.get('/teacher/sliders', isTeacher, controller.findAll)
</code></pre>
<p>III.
or can i make route like this?? And how the coding? for middleware:</p>
<pre><code>v1.get('/sliders', isUser, isTeacher, isAdmin, controller.findAll)
</code></pre>
<p>Which one is the best practice?</p>
|
[
{
"answer_id": 74648879,
"author": "Valentin Marguerie",
"author_id": 15522586,
"author_profile": "https://Stackoverflow.com/users/15522586",
"pm_score": 0,
"selected": false,
"text": "canGet<Controller name> switch(userRole): \n case 'teacher':\n next();\n break;\n case 'user':\n next();\n break;\n default:\n res.statut(403);\n"
},
{
"answer_id": 74649899,
"author": "Titan XP",
"author_id": 19262395,
"author_profile": "https://Stackoverflow.com/users/19262395",
"pm_score": 0,
"selected": false,
"text": " const express = require(\"express\");\n const router = express.Router();\n const role = require(\"../authentication/authRole\");\n const auth = require(\"../authentication/authentication\");\n\n router.get('/sliders', auth.isAuthenticated, role.isUserOrTeacher(\"admin\", \"teacher\", \"student\"), controller.findAll)\n\n // You can add more routes and define which role is allowed to access\n\n module.exports = router;\n const isUserOrTeacher = (roleOne, roleTwo, roleThree) => {\n return (req, res, next) => {\n // codes\n for (let i = 0; i < roles.length; i++) {\n if (roles[i].name === roleOne || roles[i].name === roleTwo || roles[i].name === roleThree) {\n // codes\n }\n // codes\n }\n }\n"
},
{
"answer_id": 74649961,
"author": "Bergi",
"author_id": 1048572,
"author_profile": "https://Stackoverflow.com/users/1048572",
"pm_score": 3,
"selected": true,
"text": "v1.get('/sliders', isAuthenticated, hasRole(['teacher', 'admin']), controller.findAll)\n isAuthenticated hasRole"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8402887/"
] |
74,640,086
|
<p>I'm doing my thing in my normal view blade file, but when i edit my code and save it, it doesn't update. I found out that the view cache stored in /storage/framework/views keeps interrupting. Whatever i change in my normal blade file doesn't change the output. It only reacts to my cache, which doesn't update. I've already cleared my cache, but it doesn't work, it keeps coming back. Is there any way i can ignore or delete the view cache?</p>
|
[
{
"answer_id": 74642807,
"author": "keepyourmouthshut",
"author_id": 10408643,
"author_profile": "https://Stackoverflow.com/users/10408643",
"pm_score": -1,
"selected": false,
"text": "php artisan cache:clear\n"
},
{
"answer_id": 74648272,
"author": "Ed McDarwin",
"author_id": 19543917,
"author_profile": "https://Stackoverflow.com/users/19543917",
"pm_score": 0,
"selected": false,
"text": " php artisan clear\n php artisan route:clear\n php artisan cache:clear\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20357346/"
] |
74,640,107
|
<p>Hi I want to get underline for only 2 letters but getting for full text how to get underline only for first 2 letters, Below is the code i have used to get underline for text.</p>
<pre><code><Text
style={{
textDecorationLine: "underline",
textDecorationColor: "#F88022",
textDecorationStyle: "solid",
marginTop: SCREENHEIGHT * 0.08,
fontFamily: "Outfit-Regular",
fontSize: SCREENHEIGHT * 0.023,
color: "#0C0C0C",
}}
>
Contract Details
</Text>
</code></pre>
|
[
{
"answer_id": 74641173,
"author": "Ragnar",
"author_id": 9608873,
"author_profile": "https://Stackoverflow.com/users/9608873",
"pm_score": 3,
"selected": true,
"text": "<Text>\nyour rest of the text\n <Text\n style={{\n textDecorationLine: \"underline\",\n textDecorationColor: \"#F88022\",\n textDecorationStyle: \"solid\",\n marginTop: SCREENHEIGHT * 0.08,\n fontFamily: \"Outfit-Regular\",\n fontSize: SCREENHEIGHT * 0.023,\n color: \"#0C0C0C\",\n }}>\n your underline text\n </Text>\n\n</Text>\n"
},
{
"answer_id": 74650927,
"author": "John Ocean",
"author_id": 16241616,
"author_profile": "https://Stackoverflow.com/users/16241616",
"pm_score": 1,
"selected": false,
"text": "<View style={{flexDirection: 'row'}}>\n <Text>The Other Text </Text>\n <Text\n style={{\n textDecorationLine: \"underline\",\n textDecorationColor: \"#F88022\",\n textDecorationStyle: \"solid\",\n marginTop: SCREENHEIGHT * 0.08,\n fontFamily: \"Outfit-Regular\",\n fontSize: SCREENHEIGHT * 0.023,\n color: \"#0C0C0C\",\n }}\n >\n Contract Details\n </Text>\n <Text>The Other Text </Text>\n</View>\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19614803/"
] |
74,640,111
|
<p>I am using Angular material, this is the html code:</p>
<pre><code><mat-card>
<mat-card-header *ngFor="let club of result[0]">
<mat-card-title>{{club.clubName}}</mat-card-title>
<mat-card-subtitle>Club</mat-card-subtitle>
</mat-card-header>
</mat-card>
</code></pre>
<p>I want to this:</p>
<p><a href="https://i.stack.imgur.com/twLVJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/twLVJ.png" alt="Line" /></a></p>
|
[
{
"answer_id": 74641173,
"author": "Ragnar",
"author_id": 9608873,
"author_profile": "https://Stackoverflow.com/users/9608873",
"pm_score": 3,
"selected": true,
"text": "<Text>\nyour rest of the text\n <Text\n style={{\n textDecorationLine: \"underline\",\n textDecorationColor: \"#F88022\",\n textDecorationStyle: \"solid\",\n marginTop: SCREENHEIGHT * 0.08,\n fontFamily: \"Outfit-Regular\",\n fontSize: SCREENHEIGHT * 0.023,\n color: \"#0C0C0C\",\n }}>\n your underline text\n </Text>\n\n</Text>\n"
},
{
"answer_id": 74650927,
"author": "John Ocean",
"author_id": 16241616,
"author_profile": "https://Stackoverflow.com/users/16241616",
"pm_score": 1,
"selected": false,
"text": "<View style={{flexDirection: 'row'}}>\n <Text>The Other Text </Text>\n <Text\n style={{\n textDecorationLine: \"underline\",\n textDecorationColor: \"#F88022\",\n textDecorationStyle: \"solid\",\n marginTop: SCREENHEIGHT * 0.08,\n fontFamily: \"Outfit-Regular\",\n fontSize: SCREENHEIGHT * 0.023,\n color: \"#0C0C0C\",\n }}\n >\n Contract Details\n </Text>\n <Text>The Other Text </Text>\n</View>\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17384995/"
] |
74,640,121
|
<p>I have a HTML page with a table on it (attached to this)</p>
<p>I am trying to hide one of the columns at runtime. I know the JS is firing as I am outputting some text to the page and thats working (see div id <code>poo</code>)</p>
<p><a href="https://pastebin.com/iqMnYGgu" rel="nofollow noreferrer">https://pastebin.com/iqMnYGgu</a> <-- html here</p>
<p>If I open the page in a browser, the JS works as expected, but for some reason the wkhtmltopdf binary doesn't seem to like it</p>
<p>Wonder if its a problem with qt but how do I test that?</p>
<p>The <code>wkhtmtopdf</code> command line I am using is:</p>
<pre><code># wkhtmltopdf-amd64 \
--encoding UTF-8 \
--margin-top 10 \
--margin-right 10 \
--margin-bottom 25 \
--margin-left 10 \
--page-size A4 \
--orientation portrait \
--dpi 300 \
--zoom 0.9 \
--header-spacing 30 \
--no-outline \
--no-stop-slow-scripts \
--disable-smart-shrinking \
--javascript-delay 5000 \
--debug-javascript /tmp_wkhtmlto_pdf_XlMAtk.html \
output.pdf
</code></pre>
<p>Any advise on how to debug this?</p>
<p>I've stayed away from jquery and have gone for vanilla JS which I thought would be better for all concerned.</p>
<p>Here is a visual description of the issue:</p>
<p><a href="https://i.stack.imgur.com/OPXGW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OPXGW.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74640600,
"author": "yunzen",
"author_id": 476951,
"author_profile": "https://Stackoverflow.com/users/476951",
"pm_score": 0,
"selected": false,
"text": "targetElement if (targetElements) {\n // ...\n}\n function sortOutTotals() {\n document.getElementById(\"poo\").textContent = \"something here\";\n var masterElement = document.getElementsByClassName(\n \"ceta_row_quote_section_detail\"\n );\n\n for (var i = 0; i < masterElement.length; i++) {\n var subElement = masterElement[i];\n var targetElement = subElement.querySelector(\"td[data-col='quotedtotal']\");\n console.log(targetElement.textContent);\n if (targetElement) {\n targetElement.remove();\n targetElement.textContent = \"poo\";\n }\n }\n\n var masterElement = document.getElementsByClassName(\n \"ceta_row_quote_section_detail\"\n );\n for (var i = 0; i < masterElement.length; i++) {\n var subElement = masterElement[i];\n var targetElement = subElement.querySelector(\"td[data-col='description']\");\n if (targetElement) {\n targetElement.colSpan = 2;\n }\n }\n\n var masterElement = document.getElementsByClassName(\n \"ceta_row_quote_column_headings\"\n );\n for (var i = 0; i < masterElement.length; i++) {\n var subElement = masterElement[i];\n var targetElement = subElement.querySelector(\"th[data-col='quotedtotal']\");\n if (targetElement) {\n targetElement.remove();\n }\n }\n\n var masterElement = document.getElementsByClassName(\n \"ceta_row_quote_column_headings\"\n );\n for (var i = 0; i < masterElement.length; i++) {\n var subElement = masterElement[i];\n var targetElement = subElement.querySelector(\"th[data-col='description']\");\n if (targetElement) {\n targetElement.colSpan = 2;\n }\n }\n}\n\nwindow.onload = function (e) {\n setTimeout(function () {\n sortOutTotals();\n }, 10000);\n};\n\n data-col <th class='ceta_cell_heading ceta_data_type_text'' data-col=' description'>Description</th> <th class='ceta_cell_heading ceta_data_type_text' data-col='description'>Description</th> ------------------------------------------------^----------^ data-col \"th[data-col='quotedtotal']\" \"th[data-col*='quotedtotal']\" *"
},
{
"answer_id": 74643380,
"author": "yunzen",
"author_id": 476951,
"author_profile": "https://Stackoverflow.com/users/476951",
"pm_score": 2,
"selected": true,
"text": "wkhtmltopdf Element.remove() Element.remove() wkhtmltopdf targetElement.outerHTML = ''`` instead of targetElement.parentElement.removeChild(targetElement) targetElement.remove() targetElement.remove() (function (arr) {\n arr.forEach(function (item) {\n if (item.hasOwnProperty('remove')) {\n return;\n }\n Object.defineProperty(item, 'remove', {\n configurable: true,\n enumerable: true,\n writable: true,\n value: function remove() {\n this.parentNode && this.parentNode.removeChild(this);\n }\n });\n });\n})([Element.prototype, CharacterData.prototype, DocumentType.prototype].filter(Boolean));\n\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/405764/"
] |
74,640,141
|
<p>I'm using the Mustache template engine in a project, and I've run in to an issue where I have the same attribute name in different contexts, and I'm wondering if there is a way to specify only the attribute from the local context, without changing the name of the attribute.</p>
<p><strong>Consider having this data:</strong></p>
<pre><code>{
title: 'Hello World',
href: 'http://example.com',
socials: [
{
label: 'Twitter',
href: 'http://twitter.com'
},
{
label: 'Facebook',
}
]
}
</code></pre>
<p>The issue here is that the href attribute is available in two different contexts which will cause problems if you try to use this conditionally, <strong>like this</strong>:</p>
<pre><code><div>
<h1>{{title}}</h1>
<a href="{{href}}">{{href}}</a>
<ul>
{{#socials}}
<li>
{{#href}}
<!--- In here http://twitter.com will be used for the first Social,
but for Facebook it will use http://example.com.
For Facebook, this value should be empty. --->
<a href="{{href}}">{{label}}</a>
{{/href}}
{{^href}}
<!--- This will never be rendered --->
{{label}}
{{/href}}
</li>
{{/socials}}
</ul>
</div>
</code></pre>
<p>Hopefully this demonstrates my issue. What I want is to check ONLY the current context for the variable, not check the parent context as well.</p>
<p>I know I can use <code>{{.}}</code> to access the current context, but is there a way to access a specific variable in the current context? For example, <code>{{.href}}</code> (which I have tried, but does not work...)</p>
|
[
{
"answer_id": 74640600,
"author": "yunzen",
"author_id": 476951,
"author_profile": "https://Stackoverflow.com/users/476951",
"pm_score": 0,
"selected": false,
"text": "targetElement if (targetElements) {\n // ...\n}\n function sortOutTotals() {\n document.getElementById(\"poo\").textContent = \"something here\";\n var masterElement = document.getElementsByClassName(\n \"ceta_row_quote_section_detail\"\n );\n\n for (var i = 0; i < masterElement.length; i++) {\n var subElement = masterElement[i];\n var targetElement = subElement.querySelector(\"td[data-col='quotedtotal']\");\n console.log(targetElement.textContent);\n if (targetElement) {\n targetElement.remove();\n targetElement.textContent = \"poo\";\n }\n }\n\n var masterElement = document.getElementsByClassName(\n \"ceta_row_quote_section_detail\"\n );\n for (var i = 0; i < masterElement.length; i++) {\n var subElement = masterElement[i];\n var targetElement = subElement.querySelector(\"td[data-col='description']\");\n if (targetElement) {\n targetElement.colSpan = 2;\n }\n }\n\n var masterElement = document.getElementsByClassName(\n \"ceta_row_quote_column_headings\"\n );\n for (var i = 0; i < masterElement.length; i++) {\n var subElement = masterElement[i];\n var targetElement = subElement.querySelector(\"th[data-col='quotedtotal']\");\n if (targetElement) {\n targetElement.remove();\n }\n }\n\n var masterElement = document.getElementsByClassName(\n \"ceta_row_quote_column_headings\"\n );\n for (var i = 0; i < masterElement.length; i++) {\n var subElement = masterElement[i];\n var targetElement = subElement.querySelector(\"th[data-col='description']\");\n if (targetElement) {\n targetElement.colSpan = 2;\n }\n }\n}\n\nwindow.onload = function (e) {\n setTimeout(function () {\n sortOutTotals();\n }, 10000);\n};\n\n data-col <th class='ceta_cell_heading ceta_data_type_text'' data-col=' description'>Description</th> <th class='ceta_cell_heading ceta_data_type_text' data-col='description'>Description</th> ------------------------------------------------^----------^ data-col \"th[data-col='quotedtotal']\" \"th[data-col*='quotedtotal']\" *"
},
{
"answer_id": 74643380,
"author": "yunzen",
"author_id": 476951,
"author_profile": "https://Stackoverflow.com/users/476951",
"pm_score": 2,
"selected": true,
"text": "wkhtmltopdf Element.remove() Element.remove() wkhtmltopdf targetElement.outerHTML = ''`` instead of targetElement.parentElement.removeChild(targetElement) targetElement.remove() targetElement.remove() (function (arr) {\n arr.forEach(function (item) {\n if (item.hasOwnProperty('remove')) {\n return;\n }\n Object.defineProperty(item, 'remove', {\n configurable: true,\n enumerable: true,\n writable: true,\n value: function remove() {\n this.parentNode && this.parentNode.removeChild(this);\n }\n });\n });\n})([Element.prototype, CharacterData.prototype, DocumentType.prototype].filter(Boolean));\n\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9242634/"
] |
74,640,187
|
<p>I want to read <a href="https://github.com/shrikant-temburwar/Wine-Quality-Dataset/blob/master/winequality-white.csv" rel="nofollow noreferrer"><code>winequality-white.csv</code></a> data using <code>pandas.read_html()</code> function.</p>
<p>Here is my code:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
wine = pd.DataFrame(
pd.read_html(
"https://github.com/shrikant-temburwar/Wine-Quality-Dataset/blob/master/winequality-white.csv",
thousands=";",
header=0,
)[0]
)
</code></pre>
<p>... but the result is:</p>
<pre class="lang-py prettyprint-override"><code>Unnamed: 0 "fixed acidity";"volatile acidity";"citric acid";"residual sugar";"chlorides";"free sulfur dioxide";"total sulfur dioxide";"density";"pH";"sulphates";"alcohol";"quality"
0 NaN 7;0.27;0.36;20.7;0.045;45;170;1.001;3;0.45;8.8;6
1 NaN 6.3;0.3;0.34;1.6;0.049;14;132;0.994;3.3;0.49;9...
2 NaN 8.1;0.28;0.4;6.9;0.05;30;97;0.9951;3.26;0.44;1...
3 NaN 7.2;0.23;0.32;8.5;0.058;47;186;0.9956;3.19;0.4...
4 NaN 7.2;0.23;0.32;8.5;0.058;47;186;0.9956;3.19;0.4...
</code></pre>
<p>Of course I can choose <code>raw</code> and then use <code>read_csv</code>, but in case of <code>html</code> reading, how can I fix it?</p>
|
[
{
"answer_id": 74642647,
"author": "amirhm",
"author_id": 4529589,
"author_profile": "https://Stackoverflow.com/users/4529589",
"pm_score": -1,
"selected": false,
"text": "import pandas as pd\nimport requests\nimport io\nurl = \"https://raw.githubusercontent.com/shrikant-temburwar/Wine-Quality-Dataset/master/winequality-white.csv\"\nr = requests.get(url)\nobj = io.BytesIO(r.content)\nwine = pd.read_csv(obj, delimiter=\";\")\nwine.head()\n"
},
{
"answer_id": 74643037,
"author": "accdias",
"author_id": 6789321,
"author_profile": "https://Stackoverflow.com/users/6789321",
"pm_score": 0,
"selected": false,
"text": "pd.read_html import pandas as pd\n\nwine = pd.read_html(\n \"https://github.com/shrikant-temburwar/Wine-Quality-Dataset/blob/master/winequality-white.csv\",\n header=0\n)[0]\n\nwine.drop('Unnamed: 0', axis=1, inplace=True)\nheaders = wine.columns[0].replace('\"', '').split(';')\nwine.columns = ['data']\nwine[headers] = wine.data.str.split(';', expand=True)\nwine.drop('data', axis=1, inplace=True)\nwine.head()\n >>> wine.head()\n fixed acidity volatile acidity citric acid residual sugar chlorides free sulfur dioxide total sulfur dioxide density pH sulphates alcohol quality\n0 7 0.27 0.36 20.7 0.045 45 170 1.001 3 0.45 8.8 6\n1 6.3 0.3 0.34 1.6 0.049 14 132 0.994 3.3 0.49 9.5 6\n2 8.1 0.28 0.4 6.9 0.05 30 97 0.9951 3.26 0.44 10.1 6\n3 7.2 0.23 0.32 8.5 0.058 47 186 0.9956 3.19 0.4 9.9 6\n4 7.2 0.23 0.32 8.5 0.058 47 186 0.9956 3.19 0.4 9.9 6\n>>> \n import pandas as pd\n\nwine = pd.read_csv(\n 'https://raw.githubusercontent.com/shrikant-temburwar/Wine-Quality-Dataset/master/winequality-white.csv',\n header=0,\n sep=';'\n)\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20263244/"
] |
74,640,198
|
<p>I thought you had to use fetch to get the latest version of a branch from the remote repository. If you do this as the person who wrote the article, don't you create a new feature branch from the "develop" branch that you had stored locally, in other words from a possibly outdated branch?</p>
<p>I have the same question for when he merges his local feature branch to the "develop" branch and pushes it back. He uses checkout here, why not fetch?</p>
<p>link to the article: <a href="https://nvie.com/posts/a-successful-git-branching-model/" rel="nofollow noreferrer">https://nvie.com/posts/a-successful-git-branching-model/</a></p>
<p><a href="https://i.stack.imgur.com/9LAkJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9LAkJ.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74640880,
"author": "kosist",
"author_id": 6917446,
"author_profile": "https://Stackoverflow.com/users/6917446",
"pm_score": 2,
"selected": true,
"text": "git-fetch git-pull"
},
{
"answer_id": 74647734,
"author": "torek",
"author_id": 1256452,
"author_profile": "https://Stackoverflow.com/users/1256452",
"pm_score": 0,
"selected": false,
"text": "git pull git fetch git merge git rebase git pull --ff-only git pull git switch git checkout git switch checkout git restore"
},
{
"answer_id": 74651885,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 0,
"selected": false,
"text": "dev main dev main git pull git config --global pull.rebase true\ngit config --global rebase.autoStash true\n dev git switch dev git pull origin/dev git switch feature\ngit rebase dev\n# resolve conflicts, test\n# assuming I am the only one working on feature:\ngit push --force\n dev dev git switch dev\ngit merge feature\ngit push\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9038154/"
] |
74,640,209
|
<p>Is there a shortcut in replacing characters in a string?
My string is like this:</p>
<pre><code>string x = "[\r\n \"TEST\",\r\n \"GREAT\"\r\n]";
</code></pre>
<p>I want to have an output of only</p>
<pre><code>TEST,GREAT
</code></pre>
<p>Right now I'm formatting it like:
x..Replace("\r\n", "").Replace("[", "") and until I put all the characters.</p>
<p>My question is there a shortcut to do that instead of many "Replace"?
It does not matter if it will be a string or put in a List of string. As long as I have the result TEST,GREAT.</p>
|
[
{
"answer_id": 74640426,
"author": "Palle Due",
"author_id": 5516339,
"author_profile": "https://Stackoverflow.com/users/5516339",
"pm_score": 0,
"selected": false,
"text": "public static class RemoveExtensions\n{\n public static string RemoveMultiple(this string str, params string[] removes)\n {\n foreach (string s in removes)\n {\n str = str.Replace(s, \"\");\n }\n return str;\n }\n}\n string x = \"[\\r\\n \\\"TEST\\\",\\r\\n \\\"GREAT\\\"\\r\\n]\";\nstring result = x.RemoveMultiple(\"\\r\\n\", \"[\", \"]\");\n"
},
{
"answer_id": 74640496,
"author": "Krzysztof Skowronek",
"author_id": 3512524,
"author_profile": "https://Stackoverflow.com/users/3512524",
"pm_score": 0,
"selected": false,
"text": "public static string ExtractLetters(this string text) // it's an extension method\n{\n return text.Replace(\"\\r\\n\", \"\").Replace(\"[\", \"\")....;\n}\n var extracted = \"[\\r\\n \\\"TEST\\\",\\r\\n \\\"GREAT\\\"\\r\\n]\".ExtractLetters() using System.Text.RegularExpressions;\n\npublic static string ExtractLetters(this string text)\n{\n var regex = new Regex(\"[a-zA-Z]+\"); // define regex, look for regex compilation and instance caching for optimizations here\n string[] matches = regex.Matches(text).Select(x => x.Value).ToArray(); // extract matches\n \n return string.Join(\",\", matches); // join them if you want\n}\n"
},
{
"answer_id": 74640709,
"author": "phuzi",
"author_id": 592958,
"author_profile": "https://Stackoverflow.com/users/592958",
"pm_score": 3,
"selected": true,
"text": " string x = \"[\\r\\n \\\"TEST\\\",\\r\\n \\\"GREAT\\\"\\r\\n]\";\n\n // Parse JSON to a list (could be anything implementing IEnumerable<>) of strings\n var words= System.Text.Json.JsonSerializer.Deserialize<List<string>>(x);\n\n // And join the values back together with a comma\n var result = string.Join(',', words);\n\n Console.WriteLine(result);\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2353329/"
] |
74,640,246
|
<p>What command do I run to get the container ID of an image?</p>
<p>I would think docker ps -a something...</p>
<pre><code>CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
17ef697da46d local_django "/entrypoint /start" 56 minutes ago Up 56 minutes 0.0.0.0:8000->8000/tcp django-1
</code></pre>
<p>I only want the container ID returned from an image search</p>
|
[
{
"answer_id": 74640426,
"author": "Palle Due",
"author_id": 5516339,
"author_profile": "https://Stackoverflow.com/users/5516339",
"pm_score": 0,
"selected": false,
"text": "public static class RemoveExtensions\n{\n public static string RemoveMultiple(this string str, params string[] removes)\n {\n foreach (string s in removes)\n {\n str = str.Replace(s, \"\");\n }\n return str;\n }\n}\n string x = \"[\\r\\n \\\"TEST\\\",\\r\\n \\\"GREAT\\\"\\r\\n]\";\nstring result = x.RemoveMultiple(\"\\r\\n\", \"[\", \"]\");\n"
},
{
"answer_id": 74640496,
"author": "Krzysztof Skowronek",
"author_id": 3512524,
"author_profile": "https://Stackoverflow.com/users/3512524",
"pm_score": 0,
"selected": false,
"text": "public static string ExtractLetters(this string text) // it's an extension method\n{\n return text.Replace(\"\\r\\n\", \"\").Replace(\"[\", \"\")....;\n}\n var extracted = \"[\\r\\n \\\"TEST\\\",\\r\\n \\\"GREAT\\\"\\r\\n]\".ExtractLetters() using System.Text.RegularExpressions;\n\npublic static string ExtractLetters(this string text)\n{\n var regex = new Regex(\"[a-zA-Z]+\"); // define regex, look for regex compilation and instance caching for optimizations here\n string[] matches = regex.Matches(text).Select(x => x.Value).ToArray(); // extract matches\n \n return string.Join(\",\", matches); // join them if you want\n}\n"
},
{
"answer_id": 74640709,
"author": "phuzi",
"author_id": 592958,
"author_profile": "https://Stackoverflow.com/users/592958",
"pm_score": 3,
"selected": true,
"text": " string x = \"[\\r\\n \\\"TEST\\\",\\r\\n \\\"GREAT\\\"\\r\\n]\";\n\n // Parse JSON to a list (could be anything implementing IEnumerable<>) of strings\n var words= System.Text.Json.JsonSerializer.Deserialize<List<string>>(x);\n\n // And join the values back together with a comma\n var result = string.Join(',', words);\n\n Console.WriteLine(result);\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20593303/"
] |
74,640,259
|
<p>For days I am trying to archive my ios app, i set up provisioning and everything right, but when I run this command:</p>
<p>sudo dotnet publish -f:net6.0-ios -c:Release -r ios-arm64 --self-contained</p>
<p>I get three errors:</p>
<p>1)</p>
<pre><code> error NETSDK1032: The RuntimeIdentifier platform 'ios-arm64' and the PlatformTarget 'x64' must be compatible. [/Users/juliustolksdorf/Projects/Skillbased/app/skillbased_prod/Skillbased/Skillbased.csproj::TargetFramework=net6.0-ios]
</code></pre>
<ol start="2">
<li><p>/project.assets.json' doesn't have a target for 'net6.0-ios'. Ensure that restore has run and that you have included 'net6.0-ios' in the TargetFrameworks for your project.</p>
</li>
<li></li>
</ol>
<pre><code>A bundle identifier is required. Either add an 'ApplicationId' property in the project file, or add a 'CFBundleIdentifier' entry in the project's Info.plist file.
</code></pre>
<p>Error 1 I can ommit by editing the csproj.user file</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<IsFirstTimeProjectOpen>False</IsFirstTimeProjectOpen>
<ActiveDebugFramework>net6.0-ios</ActiveDebugFramework>
<ActiveDebugProfile>iPhone 14 Pro Max iOS 16.1</ActiveDebugProfile>
<SelectedPlatformGroup>Simulator</SelectedPlatformGroup>
<DefaultDevice>iPhone 14 Pro Max iOS 16.1</DefaultDevice>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetPlatformIdentifier)'=='iOS'">
<RuntimeIdentifier>iossimulator-x64</RuntimeIdentifier>
<PlatformTarget>x64</PlatformTarget>
</PropertyGroup>
</Project>
</code></pre>
<p>and taking out <code>x64</code>. Then the error does no longer appear on archive, but I cannot build my app on emulator anymore when I do this. Great success.</p>
<p>Error number 2 I was neber able to omit, what is especially wired is that it is talking about a sub project (middleware.data) and not the main project. What am I supposed to do with that information?</p>
<p>And error number 3 is just stupid; ofc I have set a bundle ID in my csproj file</p>
<pre><code><!-- App Identifier -->
<ApplicationId>com.skillbased.skillbasedapp</ApplicationId>
<ApplicationIdGuid>2041a417-5399-434b-95f8-83e997177fb7</ApplicationIdGuid>
</code></pre>
<p>Why does it hate me so much?</p>
<p>I am running this on visual studio mac</p>
<p>I really need your help!</p>
|
[
{
"answer_id": 74653051,
"author": "Alexandar May - MSFT",
"author_id": 9644964,
"author_profile": "https://Stackoverflow.com/users/9644964",
"pm_score": 1,
"selected": false,
"text": ".NET command line interface .ipa dotnet publish -f:net6.0-ios -c:Release /p:ArchiveOnBuild=true /p:_DotNetRootRemoteDirectory=/Users/{macOS username}/Library/Caches/Xamarin/XMA/SDKs/dotnet/\n <PropertyGroup Condition=\"'$(IsPublishing)' == 'true' And '$(TargetFramework)' == 'net6.0-ios'\">\n <RuntimeIdentifier>ios-arm64</RuntimeIdentifier>\n <CodesignKey>iPhone Distribution: John Smith (AY2GDE9QM7)</CodesignKey>\n <CodesignProvision>MyMauiApp</CodesignProvision>\n <ArchiveOnBuild>true</ArchiveOnBuild>\n</PropertyGroup>\n Info.plist <key>CFBundleIdentifier</key>\n<string>com.skillbased.skillbasedapp</string>\n\n"
},
{
"answer_id": 74653704,
"author": "inno",
"author_id": 14569809,
"author_profile": "https://Stackoverflow.com/users/14569809",
"pm_score": 0,
"selected": false,
"text": "<TargetFrameworks>net6.0-ios</TargetFrameworks> \n dotnet publish -f:net6.0-ios -c:Release -r ios-arm64 --self-contained\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14569809/"
] |
74,640,272
|
<p>I am at the verge of loosing my mind over trying to fix an Email Regex i built:</p>
<p>It is almost perfect for what i need. It works in 99.9% of all cases.</p>
<p>But there is one case which causes a catastrophic backtracking error and i cannot fix my regex for it.</p>
<p>The "Email" causing a catastrophic backtrack error:</p>
<p><code>jasmin.martinez@tester.co.rolisa-brown.king@tester.co.ro</code></p>
<p>Yes, such emails do occur in the application i need this Regex for.</p>
<p>People enter multiple Emails in one field for some reason. I have no answer for why this occurs.</p>
<p>I need the Help of Wizards of Stack Overflow.</p>
<p>My Email Regex might block or not block some officially valid Emails but that is not the point here.</p>
<p>All i want is to fix the catastrophic backtracking Problem of my Regex. I do not want to change what it blocks or not. It works for what i need it to do.</p>
<p>Here is my Email Regex:</p>
<p><code>^[^\W_]+\w*(?:[.-]\w*)*[^\W_]+@[^\W_]+(?:[.-]?\w*[^\W_]+)*(?:\.[^\W_]{2,})$</code></p>
<p>How can i make this Regex fail quickly so it doesn't cause a catastrophic backtracking error.</p>
<p>Thank You very much.</p>
|
[
{
"answer_id": 74640332,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 2,
"selected": true,
"text": "^(?!_)\\w+(?:[.-]\\w+)*(?<!_)@[^\\W_]+(?>[.-]?\\w*[^\\W_])*\\.[^\\W_]{2,}$\n (?>[.-]?\\w*[^\\W_])* @ (?!_)\\w+(?:[.-]\\w+)*(?<!_) _ . - _ + ^[^\\W_]+ \\w* + [^\\W_]@ ^(?!_)[A-Za-z0-9_]+(?:[.-][A-Za-z0-9_]+)*(?<!_)@[A-Za-z0-9]+(?>[.-]?[A-Za-z0-9_]*[A-Za-z0-9])*\\.[A-Za-z0-9]{2,}$\n"
},
{
"answer_id": 74640812,
"author": "horcrux",
"author_id": 4607733,
"author_profile": "https://Stackoverflow.com/users/4607733",
"pm_score": 2,
"selected": false,
"text": "^[^\\W_](?:[\\w.-]*[^\\W_])?@[^\\W_](?:\\w*[^\\W_])?(?:[.-]\\w*[^\\W_])*\\.[^\\W_]{2,}$\n before: ^[^\\W_]+ \\w*(?:[.-]\\w*)*[^\\W_]+ @[^\\W_]+ (?:[.-]?\\w*[^\\W_]+)*(?:\\.[^\\W_]{2,})$\nafter: ^[^\\W_] (?:[\\w.-]* [^\\W_] )? @[^\\W_] (?:\\w*[^\\W_])?(?:[.-] \\w*[^\\W_] )* \\.[^\\W_]{2,} $\n ^ ^ ^ ^ ^ ^ ^ ^ ^\n ^ ^ ^ ^ ^ ^ ^ ^ No reason to use a group\n ^ ^ ^ ^ ^ ^ ^ This quantifier was useless\n ^ ^ ^ ^ ^ ^ If you want to match only letters before the possible [.-]\n ^ ^ ^ ^ ^ Now, when you match [.-] there is no reason to make it optional\n ^ ^ ^ ^ If you want to match only letters before the possible [.-]\n ^ ^ ^ Now the + quantifier is useless\n ^ ^ The + quantifier was useless\n ^ \\w*(?:[.-]\\w*)* seems to be equivalent to [\\w.-]*\n The + quantifier was useless\n \\w ^[A-Za-z0-9](?:[A-Za-z0-9_.-]*[A-Za-z0-9])?@[A-Za-z0-9](?:[A-Za-z0-9_]*[A-Za-z0-9])?(?:[.-][A-Za-z0-9_]*[A-Za-z0-9])*\\.[A-Za-z0-9]{2,}$\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3564869/"
] |
74,640,301
|
<p>I am developing a paid application in Python. I do not want the users to see the source code or decompile it. How can I accomplish this task of hiding the source code from the user, but running the code perfectly with the same performance?</p>
|
[
{
"answer_id": 74640385,
"author": "DiMithras",
"author_id": 8489602,
"author_profile": "https://Stackoverflow.com/users/8489602",
"pm_score": 1,
"selected": false,
"text": ".pyc .py"
},
{
"answer_id": 74640409,
"author": "noah",
"author_id": 19745277,
"author_profile": "https://Stackoverflow.com/users/19745277",
"pm_score": 0,
"selected": false,
"text": "pip3 install pyinstaller pyinstaller main.py"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12976945/"
] |
74,640,366
|
<p>Implemented the example from the camera package here:</p>
<p><a href="https://pub.dev/packages/camera/example" rel="nofollow noreferrer">https://pub.dev/packages/camera/example</a></p>
<p>While testing on the physical device (running iOS 16), the app builds and runs fine, however the phone does not ask for any permissions to access the camera or microphone.</p>
<p>The following code has been added to <code>ios/Runner/Info.plist</code></p>
<pre><code><key>NSCameraUsageDescription</key>
<string>Testing the Camera integration.</string>
<key>NSMicrophoneUsageDescription</key>
<string>To add sounds to the videos you record.</string>
</code></pre>
<p>The <code>iOS Deployment Target</code> has been set to <em>iOS 11.0</em></p>
<p>Note:
I can assure you that the app has not been granted these permissions already because:</p>
<ol>
<li>It is not showing up in the app settings</li>
<li>The app is not listed in Settings>Privacy & Security>Camera</li>
</ol>
<p>Am I missing something?</p>
<p>Update:</p>
<p>Created a clean projects to test out this example code, Implemented the <a href="https://pub.dev/packages/permission_handler" rel="nofollow noreferrer">permission_handler</a> to force the permissions (based on recommendation from @cenk-yagmur).</p>
<p>The permissions window now comes up, however the example code still doesn't work.</p>
<p>This leads me to believe it is either:</p>
<ol>
<li>The camera package doesn't work on iOS16</li>
<li>The example code is wrong.</li>
</ol>
<p>I'm more inclined towards 2. Will be doing a custom integration and test if that fixes the issue.</p>
|
[
{
"answer_id": 74640601,
"author": "Cenk YAGMUR",
"author_id": 4659987,
"author_profile": "https://Stackoverflow.com/users/4659987",
"pm_score": 0,
"selected": false,
"text": "Map<Permission, PermissionStatus> statuses = await [\n Permission.camera,\n Permission.microphone,\n].request();\n"
},
{
"answer_id": 74641034,
"author": "rasityilmaz",
"author_id": 15812214,
"author_profile": "https://Stackoverflow.com/users/15812214",
"pm_score": 0,
"selected": false,
"text": " post_install do |installer|\n installer.pods_project.targets.each do |target|\n flutter_additional_ios_build_settings(target)\n target.build_configurations.each do |config|\n config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [\n '$(inherited)',\n \n ## dart: PermissionGroup.calendar\n ##'PERMISSION_EVENTS=1',\n \n ## dart: PermissionGroup.reminders\n #'PERMISSION_REMINDERS=0',\n \n ## dart: PermissionGroup.contacts\n # 'PERMISSION_CONTACTS=0',\n \n ## dart: PermissionGroup.camera\n 'PERMISSION_CAMERA=1',\n \n ## dart: PermissionGroup.microphone\n 'PERMISSION_MICROPHONE=1',\n \n ## dart: PermissionGroup.speech\n #'PERMISSION_SPEECH_RECOGNIZER=0'\n \n ## dart: PermissionGroup.photos\n 'PERMISSION_PHOTOS=1',\n \n ## dart: [PermissionGroup.location, PermissionGroup.locationAlways, PermissionGroup.locationWhenInUse]\n 'PERMISSION_LOCATION=1',\n \n ## dart: PermissionGroup.notification\n 'PERMISSION_NOTIFICATIONS=1',\n \n ## dart: PermissionGroup.appTrackingTransparency\n ##'PERMISSION_APP_TRACKING_TRANSPARENCY=1',\n \n ## dart: PermissionGroup.mediaLibrary\n ##'PERMISSION_MEDIA_LIBRARY=1'\n \n ## dart: PermissionGroup.sensors\n #'PERMISSION_SENSORS=0'\n ]\n end\n end\n end\n Future<bool?> _checkPermission(BuildContext context) async {\n if (Platform.isAndroid) {\n Map<Permission, PermissionStatus> statues = await [Permission.camera, Permission.photos].request();\n PermissionStatus? statusCamera = statues[Permission.camera];\n\n PermissionStatus? statusPhotos = statues[Permission.photos];\n bool isGranted = statusCamera == PermissionStatus.granted && statusPhotos == PermissionStatus.granted;\n if (isGranted) {\n return true;\n }\n bool isPermanentlyDenied = statusCamera == PermissionStatus.permanentlyDenied || statusPhotos == PermissionStatus.permanentlyDenied;\n if (isPermanentlyDenied) {\n return false;\n }\n } else {\n Map<Permission, PermissionStatus> statues = await [Permission.camera, Permission.storage, Permission.photos].request();\n PermissionStatus? statusCamera = statues[Permission.camera];\n PermissionStatus? statusStorage = statues[Permission.storage];\n PermissionStatus? statusPhotos = statues[Permission.photos];\n bool isGranted = statusCamera == PermissionStatus.granted && statusStorage == PermissionStatus.granted && statusPhotos == PermissionStatus.granted;\n if (isGranted) {\n return true;\n }\n bool isPermanentlyDenied = statusCamera == PermissionStatus.permanentlyDenied || statusStorage == PermissionStatus.permanentlyDenied || statusPhotos == PermissionStatus.permanentlyDenied;\n if (isPermanentlyDenied) {\n return false;\n }\n }\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1423089/"
] |
74,640,372
|
<p>I am working in one inventory project I use bootsrap modal for inserting and updating records the problem that I am facing is that when I am editing the record the jquery validation only applied on first row not on any other row can any one help me in this matter.</p>
<p><strong>index page is like below</strong></p>
<pre><code><tbody>
@foreach ($suppliers as $key => $supplier)
<tr class="odd">
<td class="sorting_1 dtr-control">{{ $key + 1 }}</td>
<td>{{ $supplier->name }}</td>
<td>{{ $supplier->mobile_no }}</td>
<td>{{ $supplier->email }}</td>
<td>{{ $supplier->address }}</td>
<td>
<a href="#edit{{ $supplier->id }}" data-bs-toggle="modal" class="fas fa-edit" title="Edit Data" style=" margin-right:20px">
</a>
@include('backend.supplier.editSupplier')
</td>
</tr>
@endforeach
</tbody>
</code></pre>
<p><strong>Modal is like below</strong></p>
<pre><code><div class="modal fade editModal" id="edit{{ $supplier->id }}" tabindex="-1" role="dialog"
aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Edit Supplier</h5>
<button type="button" class=" btn btn-danger btn btn-sm close" data-bs-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<form id="editForm" method="POST" action="{{ route('supplier.update', $supplier->id) }}"
class="needs-validation" novalidate>
@csrf
@method('PUT')
<div class="modal-body">
<!-- name -->
<div class="col-md-12 ">
<div class="mb-3 position-relative form-group">
<input class="form-control" type="text" autocomplete="name" placeholder="Supplier Name"
id="name" name="name1" value="{{ $supplier->name }}">
</div>
</div>
<!-- mobile number -->
<div class="col-md-12 ">
<div class="mb-3 position-relative form-group">
<input class="form-control " type="text" autocomplete="mobile_no"
placeholder="Mobile Number" id="mobile_no" name="mobile_no1"
value="{{ $supplier->mobile_no }}">
</div>
</div>
<!-- email -->
<div class="col-md-12 ">
<div class="mb-3 position-relative form-group">
<input class="form-control " type="email_address" placeholder="Email" id="email_address"
name="email_address1" value="{{ $supplier->email }}">
</div>
</div>
<div class="col-md-12 ">
<div class="mb-3 position-relative form-group">
<input class="form-control" type="text" autocomplete="address" placeholder="Address"
id="address" name="address1" value="{{ $supplier->address }}">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal"
onclick="resetForm()">No</button>
<button type="submit" class="btn btn-primary">Add Supplier</button>
</div>
</form>
</div>
</div>
</div>
</code></pre>
<p><strong>Jquery code is like below</strong></p>
<pre><code><script type="text/javascript">
$(document).ready(function() {
$('#editForm').validate({
rules: {
name1: {
required: true,
},
mobile_no1: {
required: true,
},
address1: {
required: true,
},
email_address1: {
required: true,
},
},
messages: {
name1: {
required: 'Please Enter Supplier Name',
},
mobile_no1: {
required: 'Please Enter Supplier mobile number',
},
address1: {
required: 'Please Enter Supplier address',
},
email_address1: {
required: 'Please Enter Supplier email',
},
},
errorElement: 'span',
errorPlacement: function(error, element) {
error.addClass('invalid-feedback');
element.closest('.form-group').append(error);
},
highlight: function(element, errorClass, validClass) {
$(element).addClass('is-invalid');
},
unhighlight: function(element, errorClass, validClass) {
$(element).removeClass('is-invalid');
},
});
});
function resetForm() {
$("#editForm").trigger("reset");
var validator = $("#editForm").validate();
validator.resetForm();
}
</script>
</code></pre>
|
[
{
"answer_id": 74646206,
"author": "Nur'Azim Zahurin",
"author_id": 11482131,
"author_profile": "https://Stackoverflow.com/users/11482131",
"pm_score": 0,
"selected": false,
"text": "name=\"mobile_no1<?php $supplier-id ?>\""
},
{
"answer_id": 74648043,
"author": "Mark Schultheiss",
"author_id": 125981,
"author_profile": "https://Stackoverflow.com/users/125981",
"pm_score": 2,
"selected": true,
"text": "$(function() {\n $('#editForm').validate({\n rules: {\n name1: {\n required: true,\n },\n mobile_no1: {\n required: true,\n },\n address1: {\n required: true,\n },\n email_address1: {\n required: true,\n }\n },\n messages: {\n name1: {\n required: 'Please Enter Supplier Name',\n },\n mobile_no1: {\n required: 'Please Enter Supplier mobile number',\n },\n address1: {\n required: 'Please Enter Supplier address',\n },\n email_address1: {\n required: 'Please Enter Supplier email',\n }\n },\n errorElement: 'span',\n errorPlacement: function(error, element) {\n error.addClass('invalid-feedback');\n element.closest('.form-group').append(error);\n },\n highlight: function(element, errorClass, validClass) {\n $(element).addClass('is-invalid');\n },\n unhighlight: function(element, errorClass, validClass) {\n $(element).removeClass('is-invalid');\n }\n });\n\n $('#my-great-suppliers').on('click', '.edit-link', function(event) {\n //event.preventDefault().preventPropagation();\n console.log('set up edit');\n const trow = $(this).closest('.supplier-row');\n console.log(\"Row:\", trow.index(), trow.length);\n const modal = $('#edit-modal-container').find('.edit-modal-child');\n const modalForm = modal.find('#editForm');\n const rowEdits = trow.find('.edit-me');\n let supplierid = $(this).data(\"supplierid\");\n let name = rowEdits.filter('[data-suppliername]').data(\"suppliername\");\n let email = rowEdits.filter('[data-email]').data(\"email\");\n let mobile = rowEdits.filter('[data-mobile]').data(\"mobile\");\n let address = rowEdits.filter('[data-address]').data(\"address\");\n console.log(supplierid, name, trow.length);\n modalForm.find('#name').val(name);\n modalForm.find('#email_address').val(email);\n modalForm.find('#address').val(address);\n modalForm.find('#mobile_no').val(mobile);\n let actionV = modalForm.attr(\"action\");\n console.log(actionV);\n // update the form action with the id\n modalForm.attr(\"action\", actionV + supplierid);\n // modal.show();\n });\n $('.submit-button').on('click', function(event) {\n event.preventDefault();\n const modalForm = $('#editForm');\n console.log(\"trying to save\");\n // now do what you need to validate\n if (modalForm.valid()) {\n // add your extra logic here to execute only when element is valid\n console.log('It is valid');\n let savedata = {\n name: modalForm.find('#name').val(),\n email: modalForm.find('#email_address').val(),\n address: modalForm.find('#address').val(),\n mobile: modalForm.find('#mobile_no').val()\n };\n console.log(\"Saving:\", savedata, 'To:', modalForm.attr(\"action\"));\n //now do what you want to save the form\n // since we updated the action when edit started we have the id in there\n // modalForm.submit()\n }\n });\n});\n\nfunction resetForm() {\n $(\"#editForm\").trigger(\"reset\");\n let validator = $(\"#editForm\").validate();\n validator.resetForm();\n} .edit-link {\n margin-right: 20px;\n}\n\n.edit-modal-container {}\n\n.cheers {\n border: solid 1px green;\n} <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65\" crossorigin=\"anonymous\">\n\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css\" integrity=\"sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w==\" crossorigin=\"anonymous\" referrerpolicy=\"no-referrer\"\n/>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<script src=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js\" integrity=\"sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4\" crossorigin=\"anonymous\"></script>\n\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.min.js\" integrity=\"sha512-rstIgDs0xPgmG6RX1Aba4KV5cWJbAMcvRCVmglpam9SoHZiUCyQVDdH2LPlxoHtrv17XWblE/V/PP+Tr04hbtA==\" crossorigin=\"anonymous\" referrerpolicy=\"no-referrer\"></script>\n\n<table id=\"my-great-suppliers\" class=\"my-great-suppliers-container\">\n <tbody>\n <tr class=\"supplier-row odd\">\n <td class=\"sorting_1 dtr-control\">$key1</td>\n <td class='edit-me' data-suppliername=\"Dirt supplier\">Dirt supplier</td>\n <td class=\"edit-me\" data-mobile=\"123-123-1234\">123-123-1234</td>\n <td class=\"edit-me\" data-email=\"happydays@example.com\">happydays@example.com</td>\n <td class=\"edit-me\" data-address=\"1234 Main St\">1234 Main St</td>\n <td>\n <a href=\"#\" data-supplierid=\"supplier-1\" data-bs-toggle=\"modal\" class=\"edit-link fas fa-edit\" title=\"Edit Data\" data-bs-target=\"#supplier-modal\">\n </a>\n </td>\n </tr>\n <tr class=\"supplier-row odd\">\n <td class=\"sorting_1 dtr-control\">$key2</td>\n <td class='edit-me' data-suppliername=\"Rock supplier\">Rock supplier</td>\n <td class='edit-me' data-mobile=\"321-123-4321\">321-123-4321</td>\n <td class='edit-me' data-email=\"biggerrocks@example.com\">biggerrocks@example.com</td>\n <td class='edit-me' data-address=\"12 Granite Lane\">12 Granite Lane</td>\n <td>\n <a href=\"#\" data-supplierid=\"supplier-2\" data-bs-toggle=\"modal\" class=\"edit-link fas fa-edit\" data-bs-target=\"#supplier-modal\" title=\"Edit Data\">\n </a>\n </td>\n </tr>\n </tbody>\n</table>\n<div id=\"edit-modal-container\" class=\"edit-modal-container\">\n <div id='supplier-modal' class=\"edit-modal-child modal fade editModal\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"exampleModalLabel\" aria-hidden=\"true\">\n <div class=\"modal-dialog\" role=\"document\">\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <h5 class=\"modal-title\">Edit Supplier</h5>\n <button type=\"button\" class=\"btn btn-danger btn btn-sm close\" data-bs-dismiss=\"modal\" aria-label=\"Close\">\n <span aria-hidden=\"true\">×</span>\n </button>\n </div>\n <form id=\"editForm\" method=\"POST\" action=\"/route/supplierupdate/\" class=\"needs-validation\" novalidate>\n <div class=\"modal-body\">\n <div class=\"col-md-12 \">\n <div class=\"mb-3 position-relative form-group\">\n <input class=\"form-control\" type=\"text\" autocomplete=\"name\" placeholder=\"Supplier Name\" id=\"name\" name=\"name1\" value=\"\">\n </div>\n </div>\n <div class=\"col-md-12 \">\n <div class=\"mb-3 position-relative form-group\">\n <input class=\"form-control \" type=\"text\" autocomplete=\"mobile_no\" placeholder=\"Mobile Number\" id=\"mobile_no\" name=\"mobile_no1\" value=\"\">\n </div>\n </div>\n <div class=\"col-md-12 \">\n <div class=\"mb-3 position-relative form-group\">\n <input class=\"form-control \" type=\"email_address\" placeholder=\"Email\" id=\"email_address\" name=\"email_address1\" value=\"\">\n </div>\n </div>\n <div class=\"col-md-12 \">\n <div class=\"mb-3 position-relative form-group\">\n <input class=\"form-control\" type=\"text\" autocomplete=\"address\" placeholder=\"Address\" id=\"address\" name=\"address1\" value=\"\">\n </div>\n </div>\n </div>\n <div class=\"modal-footer\">\n <button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\" onclick=\"resetForm()\">No</button>\n <button type=\"submit\" class=\"submit-button btn btn-primary\">Add Supplier</button>\n </div>\n </form>\n </div>\n </div>\n </div>\n</div>"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8701694/"
] |
74,640,391
|
<p>compare array of object with array of keys, filter array of object with array keys.</p>
<p>Input:</p>
<pre><code>let a = ['aa'];
let b = [{ aa: 1, bb: 2, c: 30 },{ aa: 2, bb: 3, c: 40}];
</code></pre>
<p>output:</p>
<pre><code>b = [{bb: 2, c: 30 },{bb: 3, c: 40}];
original array should be mutate.
</code></pre>
|
[
{
"answer_id": 74640455,
"author": "Disco",
"author_id": 11196441,
"author_profile": "https://Stackoverflow.com/users/11196441",
"pm_score": 0,
"selected": false,
"text": "let keysToRemove = ['aa'];\nlet array = [{ aa: 1, bb: 2, c: 30 },{ aa: 2, bb: 3, c: 40}];\nlet result = array.map((item) => {\n let filtered = Object.keys(item)\n .filter((key) => !keysToRemove.includes(key))\n .reduce((obj, key) => {\n obj[key] = item[key];\n return obj;\n }, {});\n return filtered;\n});\nconsole.log(result);"
},
{
"answer_id": 74640466,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 0,
"selected": false,
"text": "map delete let a = ['aa'];\nlet b = [{ aa: 1, bb: 2, c: 30 },{ aa: 2, bb: 3, c: 40}];\n\n\nconst result = b.map(item => {\n\n Object.keys(item).forEach(key => {\n if(a.includes(key)){\n delete item[key]\n }\n })\n \n return item\n \n})\n\nconsole.log(result)"
},
{
"answer_id": 74640498,
"author": "David",
"author_id": 9870107,
"author_profile": "https://Stackoverflow.com/users/9870107",
"pm_score": 1,
"selected": false,
"text": "b let a = ['aa'];\nlet b = [{ aa: 1, bb: 2, c: 30 },{ aa: 2, bb: 3, c: 40}];\n\nfunction removeKey(obj, key) {\n let clone = Object.assign({}, obj); // <-- shallow clone\n if (key in clone) {\n delete clone[key];\n }\n return clone;\n}\n\nfunction removeKeys(keys, objs) {\n return objs.map(o => keys.reduce(removeKey, o));\n}\n\nconsole.log(removeKeys(a, b));"
},
{
"answer_id": 74640593,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 1,
"selected": false,
"text": "const\n unwanted = ['aa'],\n data = [{ aa: 1, bb: 2, c: 30 }, { aa: 2, bb: 3, c: 40 }],\n result = data.map(o => unwanted.reduce((q, k) => {\n const { [k]: _, ...r } = q;\n return r;\n }, o));\n\nconsole.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }"
},
{
"answer_id": 74643467,
"author": "Rohìt Jíndal",
"author_id": 4116300,
"author_profile": "https://Stackoverflow.com/users/4116300",
"pm_score": 1,
"selected": true,
"text": "Array.forEach() let a = ['aa'];\nlet b = [{ aa: 1, bb: 2, c: 30 },{ aa: 2, bb: 3, c: 40}];\n\nb.forEach(obj => {\n Object.keys(obj).forEach(key => {\n a.forEach(item => delete obj[item])\n });\n});\n\nconsole.log(b);"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16108399/"
] |
74,640,404
|
<p>I want to create an extended component with some additional functions added.</p>
<p>Let's say I have an ExtendedButton component which has a button that is forwardRef:ed, but which also has a doubleClick method. I know this is a silly example, but something like this:</p>
<pre class="lang-js prettyprint-override"><code>const ExtendedButton = forwardRef<HTMLButtonElement, React.HTMLAttributes<HTMLButtonElement>>((props, ref) => {
const btnRef = useRef<HTMLButtonElement>(null);
useImperativeHandle(ref, () => btnRef?.current as HTMLButtonElement);
const doubleClick = () => {
btnRef.current?.click();
btnRef.current?.click();
};
return <button {...props} ref={btnRef}></button>;
});
</code></pre>
<p>I want to be able to get the doubleClick method, <em>as well</em> as all the methods on the button, from a consumer component like this:</p>
<pre><code>export const Consumer = () => {
const ref = useRef<HTMLButtonElement>(null);
ref.current.doubleClick();
ref.current.click();
return <ExtendedButton ref={ref}></ExtendedButton>;
};
</code></pre>
<p>I feel I should probably remove the forwardRef so the ref is pointing to ExtendedButton instead of button, but how can I get the button methods then?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 74640560,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 1,
"selected": true,
"text": "useImperativeHandle const ExtendedButton = forwardRef<HTMLButtonElement, React.HTMLAttributes<HTMLButtonElement>>((props, ref) => {\n const btnRef = useRef<HTMLButtonElement>( );\n \n \n useImperativeHandle(ref, () => ({\n\n ...btnRef.current,\n doubleClick: () => {\n btnRef.current?.click();\n btnRef.current?.click();\n };\n }));\n \n return <button {...props} ref={btnRef}></button>;\n });\n"
},
{
"answer_id": 74640647,
"author": "thedude",
"author_id": 270592,
"author_profile": "https://Stackoverflow.com/users/270592",
"pm_score": 1,
"selected": false,
"text": "useImperativeHandle type ExtendedButtonType = HTMLButtonElement & { doubleClick: () => void }\nconst ExtendedButton = forwardRef<ExtendedButtonType, React.HTMLAttributes<HTMLButtonElement>>(\n (props, ref) => {\n const btnRef = useRef<HTMLButtonElement>(null)\n const doubleClick = (): void => {\n btnRef.current?.click()\n btnRef.current?.click()\n }\n useImperativeHandle(\n ref,\n () =>\n ({\n ...btnRef.current,\n doubleClick,\n } as ExtendedButtonType),\n )\n\n return <button {...props} ref={btnRef} />\n },\n)\n\nexport const Consumer: FC = () => {\n const ref = useRef<ExtendedButtonType>(null)\n\n ref.current?.doubleClick()\n ref.current?.click()\n\n return <ExtendedButton ref={ref} />\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1644471/"
] |
74,640,410
|
<p>I am looking for a function or gem that gives me the cyclomatic complexity of a function.</p>
<p>For example, using rubocop, If I write</p>
<pre class="lang-rb prettyprint-override"><code>def my_func(foo)
foo.details['errors'].each do |attr, message|
case attr
when 1 then foo.errors.add(:err1, :format)
when 2 then foo.errors.add(:err3, :format)
when 3 then foo.errors.add(:err5, :format)
when 4 then foo.errors.add(:err7, :format)
when 5 then foo.errors.add(:err9, :format)
when 6 then foo.errors.add(:err11, :format)
when 7 then foo.errors.add(:err13, :format)
else foo.errors.add(:base, message)
end
end
return foo
end
</code></pre>
<p>When I run <code>rubocop</code>, then I got the error:</p>
<pre><code>Metrics/CyclomaticComplexity: Cyclomatic complexity for my_func is too high. [9/7]
def my_func(foo) ..."
</code></pre>
<p>And I know my cylcomatic complexity is <code>[9/7]</code>.</p>
<p>If I change my function and no error is raised by rubocop, how to get the function cyclomatic complexity ? A code snippet with an example would be great ! (I am not looking for a manual computation).</p>
<p>Bonus: Provide a solution for JavaScript functions also.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 74640560,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 1,
"selected": true,
"text": "useImperativeHandle const ExtendedButton = forwardRef<HTMLButtonElement, React.HTMLAttributes<HTMLButtonElement>>((props, ref) => {\n const btnRef = useRef<HTMLButtonElement>( );\n \n \n useImperativeHandle(ref, () => ({\n\n ...btnRef.current,\n doubleClick: () => {\n btnRef.current?.click();\n btnRef.current?.click();\n };\n }));\n \n return <button {...props} ref={btnRef}></button>;\n });\n"
},
{
"answer_id": 74640647,
"author": "thedude",
"author_id": 270592,
"author_profile": "https://Stackoverflow.com/users/270592",
"pm_score": 1,
"selected": false,
"text": "useImperativeHandle type ExtendedButtonType = HTMLButtonElement & { doubleClick: () => void }\nconst ExtendedButton = forwardRef<ExtendedButtonType, React.HTMLAttributes<HTMLButtonElement>>(\n (props, ref) => {\n const btnRef = useRef<HTMLButtonElement>(null)\n const doubleClick = (): void => {\n btnRef.current?.click()\n btnRef.current?.click()\n }\n useImperativeHandle(\n ref,\n () =>\n ({\n ...btnRef.current,\n doubleClick,\n } as ExtendedButtonType),\n )\n\n return <button {...props} ref={btnRef} />\n },\n)\n\nexport const Consumer: FC = () => {\n const ref = useRef<ExtendedButtonType>(null)\n\n ref.current?.doubleClick()\n ref.current?.click()\n\n return <ExtendedButton ref={ref} />\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9428538/"
] |
74,640,414
|
<p>What is the best practice to return null for:</p>
<blockquote>
<p>Unhandled exception: RangeError (index): Invalid value: Not in inclusive range 0..2</p>
</blockquote>
<p>My code:</p>
<pre><code>late final int? element;
try {
element = l[index];
} catch(e) {
element = null;
}
</code></pre>
<p>Looking for a shorter, one-liner solution.</p>
<p>Something like:</p>
<pre><code>final element = l[index] ?? null;
</code></pre>
|
[
{
"answer_id": 74641414,
"author": "HIMANI KANETKAR",
"author_id": 20069049,
"author_profile": "https://Stackoverflow.com/users/20069049",
"pm_score": 0,
"selected": false,
"text": "final int? element = (index == null || index.clamp(0,l.length - 1) != index) ? null : l[index];\n"
},
{
"answer_id": 74643265,
"author": "Sayyid J",
"author_id": 15366030,
"author_profile": "https://Stackoverflow.com/users/15366030",
"pm_score": 0,
"selected": false,
"text": " extension NullableList<T> on List<T> {\n T? nullable(int index){\n T? element;\n try {\n element = this[index];\n } catch(_) {\n }\n return element;\n }\n }\n List<int> l = [1];\n int? result = l.nullable(3);\n print(result); //--> null\n print(l.nullable(0)); //--> 1\n"
},
{
"answer_id": 74644491,
"author": "lrn",
"author_id": 2156621,
"author_profile": "https://Stackoverflow.com/users/2156621",
"pm_score": 2,
"selected": true,
"text": "final T? element = (index >= 0 && index < l.length) ? l[index] : null;\n late"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12695188/"
] |
74,640,477
|
<p>I am trying to create a search bar for a blog, which is working fine if i am logged in, but not when i am not logged out. As logged out user, it returns a empty array with succesed code 200. i shall really appreciated if someone can help me</p>
<p>here is my PHP file</p>
<p>`</p>
<pre><code>function get_ajax_posts() {
$posts_d =array();
// Query Arguments
$args = array(
'post_type' => 'custom_posts',
'post_status' => 'publish',
'posts_per_page' => -1,
'order' => 'DESC',
'orderby' => 'date',
);
// The Query
$ajaxposts = new WP_Query($args); // changed to get_posts from wp_query, because `get_posts` returns an array
if($ajaxposts->have_posts( )){
while($ajaxposts->have_posts( )){
$ajaxposts->the_post();
array_push($posts_d, array(
'title' => get_the_title(),
'url' => get_permalink()
));
}
}
echo json_encode( $posts_d );
exit; // exit ajax call(or it will return useless information to the response)
}
// Fire AJAX action for both logged in and non-logged in users
// add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');
wp_localize_script( 'hello-elementor-child-js', 'script',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
</code></pre>
<p>`</p>
<p>Here is my javascript code</p>
<p>`</p>
<pre><code>jQuery('#s').on('keyup',function(){
$ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>"
jQuery.ajax({
type: 'POST',
dataType: "json", // add data type
// url: script.ajax_url,
url: $ajaxurl,
data: { action : 'get_ajax_posts' },
success: function( response ) {
var jobs = '';
var count = 0;
var text = jQuery('#s').val().toLowerCase();
if (!arr || arr.length === 0){
var arr = jQuery(response.filter(function(value){
text = text || null;
return value.title.toLowerCase().includes(text);
}))
};
jQuery.each( arr, function( key, value ) {
if (count == 5){
return false;
} else {
jobs += '<a href="' + value.url + '"><p>' + value.title + '</p></a>';
count++;
}
} );
jQuery('#livesearch').html(jobs);
}
});
});
</code></pre>
<p>`</p>
|
[
{
"answer_id": 74641414,
"author": "HIMANI KANETKAR",
"author_id": 20069049,
"author_profile": "https://Stackoverflow.com/users/20069049",
"pm_score": 0,
"selected": false,
"text": "final int? element = (index == null || index.clamp(0,l.length - 1) != index) ? null : l[index];\n"
},
{
"answer_id": 74643265,
"author": "Sayyid J",
"author_id": 15366030,
"author_profile": "https://Stackoverflow.com/users/15366030",
"pm_score": 0,
"selected": false,
"text": " extension NullableList<T> on List<T> {\n T? nullable(int index){\n T? element;\n try {\n element = this[index];\n } catch(_) {\n }\n return element;\n }\n }\n List<int> l = [1];\n int? result = l.nullable(3);\n print(result); //--> null\n print(l.nullable(0)); //--> 1\n"
},
{
"answer_id": 74644491,
"author": "lrn",
"author_id": 2156621,
"author_profile": "https://Stackoverflow.com/users/2156621",
"pm_score": 2,
"selected": true,
"text": "final T? element = (index >= 0 && index < l.length) ? l[index] : null;\n late"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20465797/"
] |
74,640,483
|
<p>I'm getting all active countries via the service id <code>country.repository</code></p>
<pre><code>public function getCountries(Context $context): EntityCollection
{
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('active', true));
return $this->countryRepository->search($criteria, $context)->getEntities();
}
</code></pre>
<p>This gives me this CountryCollection:
<a href="https://i.stack.imgur.com/DAzKd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DAzKd.png" alt="CountryCollection" /></a></p>
<p>How can I access each element to get the <code>id</code> and the <code>name</code>?</p>
<p>I tried to loop over</p>
<pre><code>public function test($context): array
{
$countryIds = $this->getCountries($context);
$ids = [];
foreach ($countryIds as $countryId) {
$ids[] = $countryId['id'];
}
return $ids;
}
</code></pre>
<p>Obviously this doesn't work. It gives this error:</p>
<blockquote>
<p>Cannot use object of type Shopware\Core\System\Country\CountryEntity
as array</p>
</blockquote>
|
[
{
"answer_id": 74640606,
"author": "Stone Vo",
"author_id": 780427,
"author_profile": "https://Stackoverflow.com/users/780427",
"pm_score": -1,
"selected": false,
"text": "public function test($context): array\n{\n $countries = $this->getCountries($context);\n $ids = [];\n foreach ($countries as $country) {\n $ids[] = $country->getId();//or $country->getName()\n }\n return $ids;\n}\n"
},
{
"answer_id": 74640679,
"author": "j_elfering",
"author_id": 10064036,
"author_profile": "https://Stackoverflow.com/users/10064036",
"pm_score": 2,
"selected": false,
"text": "$criteria = new Criteria();\n$criteria->addFilter(new EqualsFilter('active', true));\n\n$ids = $this->countryRepository->searchIds($criteria, $context)->getIds();\n searchIds() searchIds() search()"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7952913/"
] |
74,640,495
|
<p>I have a dataset with 100,000 rows and 300 columns</p>
<p>Here is the sample dataset:</p>
<pre><code> EVENT_DTL
0 8. Background : no job / living with marriage_virgin 9. Social status : doing pretty well with his family
1 8. Background : Engineer / living with his mom marriage_married
</code></pre>
<p>How can I remove the white blank between ‘with’ and ‘marriage_virgin’ but leave only one white blank?</p>
<p>Desired outout would be:</p>
<pre><code> EVENT_DTL
0 8. Background : no job / living with marriage_virgin 9. Social status : doing pretty well with his family
1 8. Background : Engineer / living with his mom marriage_married
</code></pre>
|
[
{
"answer_id": 74640718,
"author": "abokey",
"author_id": 16120011,
"author_profile": "https://Stackoverflow.com/users/16120011",
"pm_score": 3,
"selected": true,
"text": "pandas.Series.str \"\\s+\" df[\"EVENT_DTL\"]= df[\"EVENT_DTL\"].str.replace(\"\\s+\", \" \", regex=True)\n print(df)\n EVENT_DTL\n0 8. Background : no job / living with marriage_virgin 9. Social status : doing pretty well with his family\n1 8. Background : Engineer / living with his mom marriage_married\n pandas.DataFrame.replace df.astype(str).replace(\"\\s+\", \" \", regex=True, inplace=True)\n"
},
{
"answer_id": 74640722,
"author": "Tzane",
"author_id": 14536215,
"author_profile": "https://Stackoverflow.com/users/14536215",
"pm_score": 1,
"selected": false,
"text": "df[\"EVENT_DTL\"].str.strip()\n .strip() import re\nimport pandas as pd\n\nd = {\"EVENT_DTL\": [\n \"8. Background : no job / living with marriage_virgin 9. Social status : doing pretty well with his family\",\n \"8. Background : Engineer / living with his mom marriage_married\"\n]}\ndf = pd.DataFrame(d)\npattern = re.compile(\" +\")\ndf[\"EVENT_DTL\"] = df[\"EVENT_DTL\"].apply(lambda x: pattern.sub(\" \", x))\nprint(df[\"EVENT_DTL\"][0])\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20376341/"
] |
74,640,591
|
<p>I want to <code>echo</code> files that does not contain a substring "cds" or "rna" in their filenames.</p>
<p>I use the following code:</p>
<pre><code>for genome in *
do
if [ ! "$genome" == *"cds"* ] || [ ! "$genome" == *"rna"* ]
then
echo $genome
fi
done
</code></pre>
<p>The code does not return any error but it keeps printing files that have the substrings indicated in the file name. How can I correct this? Thank you!</p>
|
[
{
"answer_id": 74640718,
"author": "abokey",
"author_id": 16120011,
"author_profile": "https://Stackoverflow.com/users/16120011",
"pm_score": 3,
"selected": true,
"text": "pandas.Series.str \"\\s+\" df[\"EVENT_DTL\"]= df[\"EVENT_DTL\"].str.replace(\"\\s+\", \" \", regex=True)\n print(df)\n EVENT_DTL\n0 8. Background : no job / living with marriage_virgin 9. Social status : doing pretty well with his family\n1 8. Background : Engineer / living with his mom marriage_married\n pandas.DataFrame.replace df.astype(str).replace(\"\\s+\", \" \", regex=True, inplace=True)\n"
},
{
"answer_id": 74640722,
"author": "Tzane",
"author_id": 14536215,
"author_profile": "https://Stackoverflow.com/users/14536215",
"pm_score": 1,
"selected": false,
"text": "df[\"EVENT_DTL\"].str.strip()\n .strip() import re\nimport pandas as pd\n\nd = {\"EVENT_DTL\": [\n \"8. Background : no job / living with marriage_virgin 9. Social status : doing pretty well with his family\",\n \"8. Background : Engineer / living with his mom marriage_married\"\n]}\ndf = pd.DataFrame(d)\npattern = re.compile(\" +\")\ndf[\"EVENT_DTL\"] = df[\"EVENT_DTL\"].apply(lambda x: pattern.sub(\" \", x))\nprint(df[\"EVENT_DTL\"][0])\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1945881/"
] |
74,640,623
|
<p>I am trying to get time entries through ClickUp API using the google apps scripts.</p>
<pre><code>function getTime()
{
const query = new URLSearchParams({
start_date: '0',
end_date: '0',
assignee: '0',
include_task_tags: 'true',
include_location_names: 'true',
space_id: '0',
folder_id: '0',
list_id: '0',
task_id: '0',
custom_task_ids: 'true',
team_id: '123'
}).toString();
const teamId = '123';
const resp = fetch(
`https://api.clickup.com/api/v2/team/${teamId}/time_entries?${query}`,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: 'tk_49237802_NCN'
}
}
);
const data = resp.text();
console.log(data);
}
</code></pre>
<p>However it keeps on showing following error:</p>
<p><strong>ReferenceError: URLSearchParams is not defined</strong></p>
<p>Any reference or help will be highly appreciated</p>
|
[
{
"answer_id": 74640718,
"author": "abokey",
"author_id": 16120011,
"author_profile": "https://Stackoverflow.com/users/16120011",
"pm_score": 3,
"selected": true,
"text": "pandas.Series.str \"\\s+\" df[\"EVENT_DTL\"]= df[\"EVENT_DTL\"].str.replace(\"\\s+\", \" \", regex=True)\n print(df)\n EVENT_DTL\n0 8. Background : no job / living with marriage_virgin 9. Social status : doing pretty well with his family\n1 8. Background : Engineer / living with his mom marriage_married\n pandas.DataFrame.replace df.astype(str).replace(\"\\s+\", \" \", regex=True, inplace=True)\n"
},
{
"answer_id": 74640722,
"author": "Tzane",
"author_id": 14536215,
"author_profile": "https://Stackoverflow.com/users/14536215",
"pm_score": 1,
"selected": false,
"text": "df[\"EVENT_DTL\"].str.strip()\n .strip() import re\nimport pandas as pd\n\nd = {\"EVENT_DTL\": [\n \"8. Background : no job / living with marriage_virgin 9. Social status : doing pretty well with his family\",\n \"8. Background : Engineer / living with his mom marriage_married\"\n]}\ndf = pd.DataFrame(d)\npattern = re.compile(\" +\")\ndf[\"EVENT_DTL\"] = df[\"EVENT_DTL\"].apply(lambda x: pattern.sub(\" \", x))\nprint(df[\"EVENT_DTL\"][0])\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20338118/"
] |
74,640,632
|
<p>i am making a chess game i have a div as a block and in that div there is a button and a pawn-div, i have given each button an onclick to move my pawn, now to kill a pawn i want to give another onclick to the button but for some reason i can't do please help</p>
<p>my code</p>
<pre><code>function hlblp(a) {
let pawn = document.getElementsByClassName("blp")[a]
let parent = Number.parseInt(pawn.parentElement.id)
hightlitght(parent)
for (let i=0; i<64; i++) {
let block = document.getElementsByClassName("Btns")[i]
block.onclick = function() {movepawn(block, pawn)};
}}
function removepawn(b) {console.log(b[0])}
function hightlitght(a) {
if (var1==true) {
var1 = false
let var2 = a-10
var2 = var2+"b"
if (occupied[var2]==true) {
let b1 = a-20
b11 = "r"+b1
let occ1 = b1+"b"
b11 = document.getElementsByClassName(b11)[0]
// this is where i want to give an second onclick
b11.onclick = function() {removepawn(b11)};
if ( occupied[occ1] == false ) {
if (
b1 < 89 && b1 > 80 ||
b1 < 79 && b1 > 70 ||
b1 < 69 && b1 > 60 ||
b1 < 59 && b1 > 50 ||
b1 < 49 && b1 > 40 ||
b1 < 39 && b1 > 30 ||
b1 < 29 && b1 > 20 ||
b1 < 19 && b1 > 10) {b11.style.display = "block";
}}
}}
</code></pre>
|
[
{
"answer_id": 74640718,
"author": "abokey",
"author_id": 16120011,
"author_profile": "https://Stackoverflow.com/users/16120011",
"pm_score": 3,
"selected": true,
"text": "pandas.Series.str \"\\s+\" df[\"EVENT_DTL\"]= df[\"EVENT_DTL\"].str.replace(\"\\s+\", \" \", regex=True)\n print(df)\n EVENT_DTL\n0 8. Background : no job / living with marriage_virgin 9. Social status : doing pretty well with his family\n1 8. Background : Engineer / living with his mom marriage_married\n pandas.DataFrame.replace df.astype(str).replace(\"\\s+\", \" \", regex=True, inplace=True)\n"
},
{
"answer_id": 74640722,
"author": "Tzane",
"author_id": 14536215,
"author_profile": "https://Stackoverflow.com/users/14536215",
"pm_score": 1,
"selected": false,
"text": "df[\"EVENT_DTL\"].str.strip()\n .strip() import re\nimport pandas as pd\n\nd = {\"EVENT_DTL\": [\n \"8. Background : no job / living with marriage_virgin 9. Social status : doing pretty well with his family\",\n \"8. Background : Engineer / living with his mom marriage_married\"\n]}\ndf = pd.DataFrame(d)\npattern = re.compile(\" +\")\ndf[\"EVENT_DTL\"] = df[\"EVENT_DTL\"].apply(lambda x: pattern.sub(\" \", x))\nprint(df[\"EVENT_DTL\"][0])\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20545624/"
] |
74,640,651
|
<p>I have the following code:</p>
<pre class="lang-py prettyprint-override"><code>from typing import List, NewType
MultiList = NewType("MultiList", List[List[int]])
def myfunc():
multi: MultiList = []
# More stuff here
</code></pre>
<p>The code works fine, it's just my IDE (PyCharm) doesn't like the instantiation of <code>multi</code> to an empty list, I get this error:</p>
<pre>
"Expected type 'MultiList', got 'list[list[int]]' instead"
</pre>
<p>I mean, a <code>MultiList</code> <em>is</em> a <code>list[list[int]]</code>, so I really don't know why it's complaining. Unless it's because the list is empty, but that doesn't make a lot of sense to me either.</p>
<p>It's not the end of the world, the code works just fine, I'd just like to know why it's marked as wrong.</p>
|
[
{
"answer_id": 74640693,
"author": "user2357112",
"author_id": 2357112,
"author_profile": "https://Stackoverflow.com/users/2357112",
"pm_score": 1,
"selected": false,
"text": "MultiList = List[List[int]]\n MultiList = NewType(\"MultiList\", List[List[int]])\nmulti: MultiList = MultiList([])\n"
},
{
"answer_id": 74640702,
"author": "Daniil Fajnberg",
"author_id": 19770795,
"author_profile": "https://Stackoverflow.com/users/19770795",
"pm_score": 3,
"selected": true,
"text": "typing.NewType MultiList list list MultiList def myfunc():\n multi: MultiList = MultiList([])\n NewType TypeAlias from typing import TypeAlias\n\nMultiList: TypeAlias = list[list[int]]\n\ndef myfunc():\n multi: MultiList = []\n list typing.List"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5734324/"
] |
74,640,655
|
<p>I spent hours trying to figure this out.
I have four binary values that I want to combine into a single number.
I got it working with two numbers but I need to get it working with four.</p>
<pre><code>int Index = ((Bitplane0_ROW[p] & (1 << N)) >> N) | (((Bitplane1_ROW[p] & (1 << N)) >> N) << 1); // Works
</code></pre>
<p>I am stumped.
Thanks in advance.</p>
<p>Edit.. Here is the complete program.</p>
<pre><code>int main()
{
int Bitplane0_ROW[] = { 0b01100110 , 0b11111111, 0b01011010, 0b01111110, 0b00000000, 0b10000001, 0b11111111, 0b01111110 }; // Array to to store numbers Last Row is first.
int Bitplane1_ROW[] = { 0b01111110, 0b11111111, 0b11111111, 0b11011011, 0b11111111, 0b01111110, 0b00000000, 0b00000000 };
int Bitplane2_ROW[] = { 0b00000000, 0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000};
int Bitplane3_ROW[] = { 0b00000000, 0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000 };
int N = 7; //to store bit
int c = 0;
BYTE* buf = new BYTE[8 * 5];
unsigned char White[] = {255, 255, 255};
unsigned char Green[] = {53, 189,104 };
unsigned char Brown[] = {59,85,142 };
unsigned char Tan[] = {154,194,237 };
for (int p = 0; p < 8; p++)
{
for (int j = 0; j < 8; j++) // Row 6
{
int Index = ((Bitplane0_ROW[p] & (1 << N)) >> N) | (((Bitplane1_ROW[p] & (1 << N)) >> N) << 1); // Works
if(Index == 0)
{
// Index 0 (White)
// Index = 0;
buf[c + 0] = White[Index];
buf[c + 1] = White[Index+1];
buf[c + 2] = White[Index+2];
}
else if (Index == 1)
{
// Index 1 (Green)
//Index = 0;
buf[c + 0] = Green[Index];
buf[c + 1] = Green[Index+1];
buf[c + 2] = Green[Index+2];
}
else if (Index == 2)
{
// Index 2 (Brown)
//Index = 0;
buf[c + 0] = Brown[Index];
buf[c + 1] = Brown[Index+1];
buf[c + 2] = Brown[Index+2];
}
else if (Index == 3)
{
// Index 3 (Tan)
Index = 0;
buf[c + 0] = Tan[Index];
buf[c + 1] = Tan[Index+1];
buf[c + 2] = Tan[Index+2];
}
else if (Index == 15)
{
// Index 1 (Green)
Index = 0;
buf[c + 0] = Green[Index];
buf[c + 1] = Green[Index+1];
buf[c + 2] = Green[Index+2];
}
c += 3;
N--;
}
N = 7;
}
SaveBitmapToFile((BYTE*)buf, 8, 8, 24, 0, "C:\\Users\\Chris\\Desktop\\Link_Sprite.bmp");
delete[] buf;
</code></pre>
<p>return 0;</p>
|
[
{
"answer_id": 74640824,
"author": "bitmask",
"author_id": 430766,
"author_profile": "https://Stackoverflow.com/users/430766",
"pm_score": 3,
"selected": true,
"text": "std::bitset #include <bitset>\n\n// ...\nstd::bitset<4> bs;\nbs.set(0, (Bitplane0_ROW[p] >> N) & 1);\nbs.set(1, (Bitplane1_ROW[p] >> N) & 1);\nbs.set(2, (Bitplane2_ROW[p] >> N) & 1);\nbs.set(3, (Bitplane3_ROW[p] >> N) & 1);\nunsigned long index = bs.to_ulong();\n"
},
{
"answer_id": 74642614,
"author": "axd",
"author_id": 20383376,
"author_profile": "https://Stackoverflow.com/users/20383376",
"pm_score": 0,
"selected": false,
"text": " N = 1;\n for (int j = 7; j >=0; j--) // I reversed you loop\n {\n \n N = 1<<j;\n Index = ((Bitplane0_ROW[p] & N ? 1 :0)<<3) \n + ((Bitplane1_ROW[p] & N ? 1 :0)<<2)\n + ((Bitplane2_ROW[p] & N ? 1 :0)<<1)\n + (Bitplane3_ROW[p] & N ? 1 :0);\n \n\n std::cout << \" Index = \" << std::bitset<4>(Index) << std::endl;\n #include <iostream>\n#include <bitset>\n\nusing namespace std;\n\nint main()\n{\n\nint Bitplane0_ROW[] = { 0b01100110 , 0b11111111, 0b01011010, 0b01111110, 0b00000000, 0b10000001, 0b11111111, 0b01111110 }; // Array to to store numbers Last Row is first.\nint Bitplane1_ROW[] = { 0b01111110, 0b11111111, 0b11111111, 0b11011011, 0b11111111, 0b01111110, 0b00000000, 0b00000000 };\nint Bitplane2_ROW[] = { 0b00000000, 0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000};\nint Bitplane3_ROW[] = { 0b00000000, 0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000 };\n\n\nint N = 7; //to store bit\nint c = 0;\n\nunsigned char* buf = new unsigned char[8 * 5];\n\nunsigned char White[] = {255, 255, 255};\nunsigned char Green[] = {53, 189,104 };\nunsigned char Brown[] = {59,85,142 };\nunsigned char Tan[] = {154,194,237 };\n\n\nint Index = 0;\n\n\nfor (int p = 0; p < 8; p++)\n{\n N = 1;\n for (int j = 7; j >=0; j--) // I reversed you loop\n {\n \n N = 1<<j;\n Index = ((Bitplane0_ROW[p] & N ? 1 :0)<<3) \n + ((Bitplane1_ROW[p] & N ? 1 :0)<<2)\n + ((Bitplane2_ROW[p] & N ? 1 :0)<<1)\n + (Bitplane3_ROW[p] & N ? 1 :0);\n \n\n std::cout << \" Index = \" << std::bitset<4>(Index) << std::endl;\n\n \n //int Index = ((Bitplane0_ROW[p] & (1 << N)) >> N) | (((Bitplane1_ROW[p] & (1 << N)) >> N) << 1); // Works\n if(Index == 0)\n {\n\n // Index 0 (White)\n // Index = 0;\n buf[c + 0] = White[Index];\n buf[c + 1] = White[Index+1];\n buf[c + 2] = White[Index+2];\n\n }\n\n else if (Index == 1)\n {\n // Index 1 (Green)\n //Index = 0;\n buf[c + 0] = Green[Index];\n buf[c + 1] = Green[Index+1];\n buf[c + 2] = Green[Index+2];\n\n }\n else if (Index == 2)\n {\n\n // Index 2 (Brown)\n //Index = 0;\n buf[c + 0] = Brown[Index];\n buf[c + 1] = Brown[Index+1];\n buf[c + 2] = Brown[Index+2];\n }\n else if (Index == 3)\n {\n\n // Index 3 (Tan)\n Index = 0;\n buf[c + 0] = Tan[Index];\n buf[c + 1] = Tan[Index+1];\n buf[c + 2] = Tan[Index+2];\n }\n else if (Index == 15)\n {\n // Index 1 (Green)\n Index = 0;\n buf[c + 0] = Green[Index];\n buf[c + 1] = Green[Index+1];\n buf[c + 2] = Green[Index+2];\n\n }\n c += 3;\n N--;\n }\n N = 7;\n}\n\n// SaveBitmapToFile((BYTE*)buf, 8, 8, 24, 0, \"C:\\\\Users\\\\Chris\\\\Desktop\\\\Link_Sprite.bmp\");\ndelete[] buf;\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13144883/"
] |
74,640,676
|
<p>Below is my sample data</p>
<p><a href="https://i.stack.imgur.com/3YMyB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3YMyB.png" alt="enter image description here" /></a></p>
<p>Here is the output i want using an sql query. The concatenated string should hold unique values in the order of their occurrence. Please help.</p>
<p><a href="https://i.stack.imgur.com/vyN3E.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vyN3E.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74641236,
"author": "ufosnowcat",
"author_id": 1728208,
"author_profile": "https://Stackoverflow.com/users/1728208",
"pm_score": 1,
"selected": false,
"text": "select sub.issue, STRING_AGG(sub.type, ', ') within group (order by sub.orderField) [Types]\n, count(sub.[type]) TypeCount\nfrom (\n select issue, MIN(c.time) orderField, c.[type] ,count(c.[type]) amt\n from concentrate c\n group by c.issue, c.[type]) sub\ngroup by sub.issue\n"
},
{
"answer_id": 74642060,
"author": "Olanike",
"author_id": 20655335,
"author_profile": "https://Stackoverflow.com/users/20655335",
"pm_score": 0,
"selected": false,
"text": " DECLARE @TEMP TABLE(ISSUE VARCHAR(50), [TYPE] VARCHAR(10))\n\n INSERT INTO @TEMP\n VALUES ('A', 'Apple'),\n ('A', 'Apple'),\n ('A', 'Apple'),\n ('A', 'Orange'),\n ('A', 'Banana')\n\n ;with cte as (\n select ISSUE , STUFF((SELECT DISTINCT ',' + [TYPE] from @TEMP T WHERE T.ISSUE = TP.ISSUE FOR XML PATH('')), 1,1,'') [TYPE], \n COUNT(DISTINCT [TYPE]) AS Total from @TEMP TP\n GROUP BY [TYPE], ISSUE\n )\n SELECT ISSUE, [TYPE], SUM(Total) Total FROM CTE\n GROUP BY ISSUE, [TYPE]\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9478438/"
] |
74,640,683
|
<p>I'm running two instances of <code>CompletableFuture</code>, which wait 1 second and print something to the console. The first one I interrupt after 0.5 seconds. So I expect only the second one to print, but in fact both do. What's going on here?</p>
<p>Here's the code:</p>
<pre><code>CompletableFuture<Void> c1 = CompletableFuture.runAsync(() -> {
System.out.println("Start CF 1");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(1);
});
CompletableFuture<Void> c2 = CompletableFuture.runAsync(() -> {
System.out.println("Start CF 2");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(2);
});
long start = System.currentTimeMillis();
try {
c1.get(500, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
System.out.println("CF interrupted after " + (System.currentTimeMillis() - start) + "ms");
}
c2.get();
</code></pre>
<p>And it prints:</p>
<pre><code>Start CF 1
Start CF 2
CF interrupted after 510ms
2
1
</code></pre>
|
[
{
"answer_id": 74641236,
"author": "ufosnowcat",
"author_id": 1728208,
"author_profile": "https://Stackoverflow.com/users/1728208",
"pm_score": 1,
"selected": false,
"text": "select sub.issue, STRING_AGG(sub.type, ', ') within group (order by sub.orderField) [Types]\n, count(sub.[type]) TypeCount\nfrom (\n select issue, MIN(c.time) orderField, c.[type] ,count(c.[type]) amt\n from concentrate c\n group by c.issue, c.[type]) sub\ngroup by sub.issue\n"
},
{
"answer_id": 74642060,
"author": "Olanike",
"author_id": 20655335,
"author_profile": "https://Stackoverflow.com/users/20655335",
"pm_score": 0,
"selected": false,
"text": " DECLARE @TEMP TABLE(ISSUE VARCHAR(50), [TYPE] VARCHAR(10))\n\n INSERT INTO @TEMP\n VALUES ('A', 'Apple'),\n ('A', 'Apple'),\n ('A', 'Apple'),\n ('A', 'Orange'),\n ('A', 'Banana')\n\n ;with cte as (\n select ISSUE , STUFF((SELECT DISTINCT ',' + [TYPE] from @TEMP T WHERE T.ISSUE = TP.ISSUE FOR XML PATH('')), 1,1,'') [TYPE], \n COUNT(DISTINCT [TYPE]) AS Total from @TEMP TP\n GROUP BY [TYPE], ISSUE\n )\n SELECT ISSUE, [TYPE], SUM(Total) Total FROM CTE\n GROUP BY ISSUE, [TYPE]\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/259288/"
] |
74,640,687
|
<p>I am working on a flutter project where I want a function that returns the Document ID. The only thing availabe is document field that is email or name.</p>
<p><a href="https://i.stack.imgur.com/MG9iq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MG9iq.png" alt="Firestore Database." /></a></p>
<p>What I want is:</p>
<pre><code>if (email == email) {
return documentID;
}
</code></pre>
|
[
{
"answer_id": 74641236,
"author": "ufosnowcat",
"author_id": 1728208,
"author_profile": "https://Stackoverflow.com/users/1728208",
"pm_score": 1,
"selected": false,
"text": "select sub.issue, STRING_AGG(sub.type, ', ') within group (order by sub.orderField) [Types]\n, count(sub.[type]) TypeCount\nfrom (\n select issue, MIN(c.time) orderField, c.[type] ,count(c.[type]) amt\n from concentrate c\n group by c.issue, c.[type]) sub\ngroup by sub.issue\n"
},
{
"answer_id": 74642060,
"author": "Olanike",
"author_id": 20655335,
"author_profile": "https://Stackoverflow.com/users/20655335",
"pm_score": 0,
"selected": false,
"text": " DECLARE @TEMP TABLE(ISSUE VARCHAR(50), [TYPE] VARCHAR(10))\n\n INSERT INTO @TEMP\n VALUES ('A', 'Apple'),\n ('A', 'Apple'),\n ('A', 'Apple'),\n ('A', 'Orange'),\n ('A', 'Banana')\n\n ;with cte as (\n select ISSUE , STUFF((SELECT DISTINCT ',' + [TYPE] from @TEMP T WHERE T.ISSUE = TP.ISSUE FOR XML PATH('')), 1,1,'') [TYPE], \n COUNT(DISTINCT [TYPE]) AS Total from @TEMP TP\n GROUP BY [TYPE], ISSUE\n )\n SELECT ISSUE, [TYPE], SUM(Total) Total FROM CTE\n GROUP BY ISSUE, [TYPE]\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10535413/"
] |
74,640,726
|
<p>I have two random lists of strings. The length of two lists won't be necessarily equal all the time. There is no repetition of the elements within a list.</p>
<pre><code>list1=['A', 'A-B', 'B', 'C']
list2=['A', 'A-B', 'B', 'D']
</code></pre>
<p>I want to compare the two lists, and the final output should be two lists with all common elements.</p>
<p>Expected output:</p>
<pre><code>list1_final=['A', 'A-B', 'B', 'C','D']
list2_final=['A', 'A-B', 'B','C', 'D']
</code></pre>
<p>How can I achieve this with a minimum number of lines of code?</p>
|
[
{
"answer_id": 74640778,
"author": "Will",
"author_id": 12829151,
"author_profile": "https://Stackoverflow.com/users/12829151",
"pm_score": 1,
"selected": false,
"text": "set1.intersection(set2) set1.union(set2)"
},
{
"answer_id": 74640830,
"author": "Luke Delves",
"author_id": 15059399,
"author_profile": "https://Stackoverflow.com/users/15059399",
"pm_score": -1,
"selected": false,
"text": "list1=['A', 'A-B', 'B', 'C']\nlist2=['A', 'A-B', 'B', 'D']\n\nlist1_final=[]\nlist2_final=[]\n\nfor item in list1:\n if item in list2:\n list1_final.append(item)\n list2_final.append(item)\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11021252/"
] |
74,640,733
|
<p>Im new in android and i do not know many things. I have a problem making a function inside two ore more buttons and place it in the <strong>onCreate</strong> method. For example:</p>
<pre><code>public class gameActivity extends AppCompatActivity {
private int num = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
//the two buttons from layout
Button tl = findViewById(R.id.buttonTL);
Button tm = findViewById(R.id.buttonTM);
//the void function that the buttons may use
void printChar(){
//do domething
}
//click listeners to above Buttons
tl.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
tl.setClickable(false);
num++;
//function i want to call
printChar();
}
});
tm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
tm.setClickable(false);
num++;\
//function i want to call
printChar();
}
});
}
}
</code></pre>
<p>All i want to do is to make the printChar(); function inside the onCreate(), to make all the buttons use this, and not write the same code inside each button again and again..</p>
|
[
{
"answer_id": 74640856,
"author": "z.y",
"author_id": 19023745,
"author_profile": "https://Stackoverflow.com/users/19023745",
"pm_score": 1,
"selected": false,
"text": "onCreate public class gameActivity extends AppCompatActivity {\n\n private int num = 0;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_game);\n\n //the two buttons from layout\n Button tl = findViewById(R.id.buttonTL);\n Button tm = findViewById(R.id.buttonTM);\n\n\n\n //click listeners to above Buttons\n tl.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n tl.setClickable(false);\n num++;\n //function i want to call\n printChar(num);\n }\n });\n\n tm.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n tm.setClickable(false);\n num++;\n //function i want to call\n printChar(num);\n }\n });\n }\n\n //the void function that the buttons may use\n void printChar(int num){\n Log.d(\"PrintNum\", \"Num: \" + num);\n }\n}\n"
},
{
"answer_id": 74642583,
"author": "Mouaad Abdelghafour AITALI",
"author_id": 7954210,
"author_profile": "https://Stackoverflow.com/users/7954210",
"pm_score": 1,
"selected": true,
"text": "public class gameActivity extends AppCompatActivity {\n\n private int num = 0;\n private Button tl, tm;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_game);\n\n //the two buttons from layout\n tl = findViewById(R.id.buttonTL);\n tm = findViewById(R.id.buttonTM);\n\n\n //click listeners to above Buttons\n tl.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n tl.setClickable(false);\n num++;\n //function i want to call\n printChar();\n }\n });\n\n tm.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n tm.setClickable(false);\n num++;\\\n //function i want to call\n printChar();\n }\n }); \n }\n\n\n void printChar(){\n //do domething\n String textTl = tl.getText().ToString();\n String textTm = tm.getText().ToString();\n\n } \n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15427573/"
] |
74,640,743
|
<p>I just cant figure out a solution for my problem.
I have CSS file and HTML, I had to create ChatBot where all the styling is located in CSS.</p>
<p>I am trying to make the Scrollbar go down when all screen is filled with messages and show the newest one. Messages are starting from top and then filling down til bottom.</p>
<p>This is my html main body code a.k.a chat screen body. In textFields are the messages witch is placed there with Jquery from user input. And bot output.</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>.chatBox {
height: 80%;
padding: 25px;
overflow-y: auto;
}
.textFields {
--rad: 20px;
--rad-sm: 3px;
font: 16px/1.5 sans-serif;
max-width: 100%;
min-height: 90%;
padding: 20px;
display: flex;
flex-direction: column;
margin-bottom: 20px;
}
#msgBubble {
border-radius: var(--rad) var(--rad-sm) var(--rad-sm) var(--rad);
background: #42a5f5;
color: #fff;
margin-left: auto;
max-width: 250px;
max-height: 250px;
padding: 10px 10px;
word-break: break-word;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="chatBox">
<div class="textFields">
</div>
</div></code></pre>
</div>
</div>
</p>
<p>I already tried on <code>.chatBox</code> to add <code>display: flex, flex-direction: column-reverse</code> but it didnt work.
At <code>.textFields</code> I tried to add <code>column-reverse</code> and that is working, but only up side down, as it just reverses the elements. I thought I could prepend elements to <code><div></code> so it would work from top. But still adding <code>column-reverse</code> and prepend does the same as now in code.</p>
|
[
{
"answer_id": 74640856,
"author": "z.y",
"author_id": 19023745,
"author_profile": "https://Stackoverflow.com/users/19023745",
"pm_score": 1,
"selected": false,
"text": "onCreate public class gameActivity extends AppCompatActivity {\n\n private int num = 0;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_game);\n\n //the two buttons from layout\n Button tl = findViewById(R.id.buttonTL);\n Button tm = findViewById(R.id.buttonTM);\n\n\n\n //click listeners to above Buttons\n tl.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n tl.setClickable(false);\n num++;\n //function i want to call\n printChar(num);\n }\n });\n\n tm.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n tm.setClickable(false);\n num++;\n //function i want to call\n printChar(num);\n }\n });\n }\n\n //the void function that the buttons may use\n void printChar(int num){\n Log.d(\"PrintNum\", \"Num: \" + num);\n }\n}\n"
},
{
"answer_id": 74642583,
"author": "Mouaad Abdelghafour AITALI",
"author_id": 7954210,
"author_profile": "https://Stackoverflow.com/users/7954210",
"pm_score": 1,
"selected": true,
"text": "public class gameActivity extends AppCompatActivity {\n\n private int num = 0;\n private Button tl, tm;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_game);\n\n //the two buttons from layout\n tl = findViewById(R.id.buttonTL);\n tm = findViewById(R.id.buttonTM);\n\n\n //click listeners to above Buttons\n tl.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n tl.setClickable(false);\n num++;\n //function i want to call\n printChar();\n }\n });\n\n tm.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n tm.setClickable(false);\n num++;\\\n //function i want to call\n printChar();\n }\n }); \n }\n\n\n void printChar(){\n //do domething\n String textTl = tl.getText().ToString();\n String textTm = tm.getText().ToString();\n\n } \n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20655285/"
] |
74,640,785
|
<p>I cannot understand the problem in my code. The book where I got my algorithm is: <strong>Introduction to Algorithms, Third Edition</strong></p>
<p>I understand how the algorithm works but while coding it, my program
only sorts the first 4 numbers.</p>
<h3>Code</h3>
<pre><code>#include <stdio.h>
void sortArr(int *nums, int arrSize) {
// nums[start...end]
// nums[start...mid] n1
// nums[mid+1...end] n2
int start, mid, end;
start = 0;
end = arrSize-1;
mid = (end + start) / 2;
int n1, n2;
n1 = mid - start + 1;
n2 = end - mid;
int l[n1], r[n2];
for (int i = 0; i < n1; i++) {
l[i] = nums[start + i];
}
for (int i = 0; i < n2; i++) {
r[i] = nums[mid + 1 + i];
}
int i, j;
i = 0;
j = 0;
for (int k = start; k < arrSize; k++) {
if (l[i] <= r[j]) {
nums[k] = l[i];
i++;
} else {
nums[k] = r[j];
j++;
}
}
}
int main() {
int arr[] = {3, 41, 52, 26, 38, 57, 9, 49};
int arrsize = sizeof(arr) / sizeof(arr[0]);
printf("before sorting: \n");
for (int i = 0; i < arrsize; i++) {
printf("%d ", arr[i]);
}
sortArr(arr, arrsize);
printf("\n after sorting: \n");
for (int i = 0; i < arrsize; i++) {
printf("%d ", arr[i]);
}
return 0;
}
</code></pre>
|
[
{
"answer_id": 74641003,
"author": "VLL",
"author_id": 2527795,
"author_profile": "https://Stackoverflow.com/users/2527795",
"pm_score": 0,
"selected": false,
"text": "printf(\"%d %d %d\\n\", k, i, j); n1 = n2 = 4 i"
},
{
"answer_id": 74641635,
"author": "Paul Hankin",
"author_id": 1400793,
"author_profile": "https://Stackoverflow.com/users/1400793",
"pm_score": 2,
"selected": true,
"text": "INT_MAX malloc size_t if li ri malloc ok failed rand #include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <assert.h>\n\nvoid MERGE(int *nums, int *buffer, size_t start, size_t mid, size_t end) {\n size_t n1 = mid - start + 1;\n size_t n2 = end - mid;\n assert(n1 > 0);\n assert(n2 > 0);\n memcpy(buffer, nums + start, (end - start + 1) * sizeof(int));\n int *L = buffer;\n int *R = buffer + n1;\n size_t li = 0, ri = 0;\n for (size_t i = start; i <= end; i++ ){\n if (li < n1 && (ri == n2 || L[li] <= R[ri])) {\n assert(li < n1);\n nums[i] = L[li++];\n } else {\n assert(ri < n2);\n nums[i] = R[ri++];\n }\n }\n}\n\nvoid MERGESORT0(int *nums, int *buffer, size_t start, size_t end) {\n if (end == start) return;\n size_t mid = start + (end - start) / 2;\n MERGESORT0(nums, buffer, start, mid);\n MERGESORT0(nums, buffer, mid+1, end);\n MERGE(nums, buffer, start, mid, end);\n}\n\nint MERGESORT(int *nums, size_t size) {\n if (size == 0) {\n return 1;\n }\n int *buffer = malloc(sizeof(int) * size);\n if (!buffer) return 0;\n MERGESORT0(nums, buffer, 0, size-1);\n free(buffer);\n return 1;\n}\n\n#define N 1234\nint main(){\n int arr[N];\n for (size_t i = 0; i < N; i++) {\n arr[i] = rand();\n }\n size_t arrsize = sizeof(arr)/sizeof(arr[0]);\n printf(\"before sorting: \\n\");\n for(size_t i=0; i<arrsize; i++){\n printf(\"%d \", arr[i]);\n }\n printf(\"\\n\");\n if (!MERGESORT(arr, arrsize)) {\n printf(\"failed\\n\");\n exit(1);\n }\n printf(\"after sorting: \\n\");\n int failed = 0;\n for(size_t i=0; i<arrsize; i++){\n if (i > 0 && arr[i] < arr[i-1]) failed = 1;\n printf(\"%d \", arr[i]);\n }\n printf(\"\\n\");\n printf(\"%s\\n\", failed ? \"failed\" : \"ok\");\n return 0;\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19655633/"
] |
74,640,822
|
<p>I have a problem while I was trying to use the $user variable, I'm pretty new to laravel but from what I can gather my controller file isn't able to pass the variable $user to my blade file. I have tried many solutions but I'm still not able to solve this problem. These are the files that I use:</p>
<p>Blade file:</p>
<pre><code><body>
<div class="justify-center flex text-center shadow-sm max-w-xs m-auto">
<img src="{{$user->image}}" id="imageName" class="object-cover w-24 h-24 float-left mr-5">
</div>
</div>
</div>
<form action="{{ route ('update_profile', $user->id) }}" method="POST" enctype="multipart/form-data">
@csrf
<input type="file" name="picture" id="my-file">
<input type="submit" name="Upload">
</form>
<br>
<div class="space-x-8 flex justify-between mt-32 md:mt-0 md:justify-center text-center">
<button class="text-black py-2 px-4 uppercase rounded bg-blue-400 hover:bg-blue-500 shadow hover:shadow-lg font-medium transition transform hover:-translate-y-0.5">
Connect
</button>
<button class="text-black py-2 px-4 uppercase rounded bg-gray-700 hover:bg-gray-800 shadow hover:shadow-lg font-medium transition transform hover:-translate-y-0.5">
Message
</button>
</div>
</div>
<br>
<div class="mt-20 text-center border-b pb-12">
<h1 class="text-4xl font-medium text-gray-700">Jessica Jones</h1>
<p class="font-light text-gray-600 mt-3">123 Address</p>
<p class="mt-8 text-gray-500">Rentee</p>
</div>
<div class="mt-12 flex flex-col justify-center">
<p class="text-gray-600 text-center font-light lg:px-16">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
<div class="justify-center flex text-center">
<button class="text-indigo-500 py-2 px-4 font-medium mt-4 ">
Show more
</button>
</div>
</div>
</div>
</div>
</body>
<script>
document.getElementById("my-file").onchange = function() {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
// e.target.result is a base64-encoded url that contains the image data
document.getElementById('imageName').setAttribute('src', e.target.result);
};
reader.readAsDataURL(this.files[0]);
}
}
</script>
</html>
<?php
</code></pre>
<p>Controller file:</p>
<pre><code><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Profile;
class ProfileController extends Controller
{
public function update_profile(Request $request,$id) {
$rquest->validate([
'picture'=>'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
$user = User::where('id', $id)->first();
unlink($user->image);
$image_name = $request->image->extension();
$request->image->move(public_path('public/images/profile/'),$image_name);
$path = 'images/profile/'.$image_name;
$user->image = $path;
$user->save();
return view('profile', compact ('user'));
}
}
</code></pre>
<p>Model file:</p>
<pre><code><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
use HasFactory;
protected $fillable = [
'name',
'size',
];
}
</code></pre>
<p>This is the error that I encountered</p>
<p><a href="https://i.stack.imgur.com/l4A2n.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l4A2n.png" alt="enter image description here" /></a></p>
<p>I have tried adding compact('user') to the return view line in the controller, tried using ['user' => $user] at the same return line and also clearing the route cache but they all resulted in the same error.</p>
|
[
{
"answer_id": 74641028,
"author": "scorpions78",
"author_id": 15328662,
"author_profile": "https://Stackoverflow.com/users/15328662",
"pm_score": -1,
"selected": false,
"text": "compact($user) with('user', $user) return view('profile')->with('user', $user);\n $user->update([\n 'name' => $request->name,\n 'email' => $request->email,\n 'updated_at' => now()\n ]);\n\n return $this->success('profile','Profile updated successfully!');\n $user = User::find($id);\n $user->name = $request->get('name');\n $user->email = $request->get('email');\n $user->password = \\Hash::make($request->get('password'));\n \n $user->update(); \n\n if($user){\n return redirect()->back()->with('message', 'User updated!');\n }else{\n return redirect()->back()->with('error', ' Error!');\n }\n"
},
{
"answer_id": 74641694,
"author": "Md.Tahmid Farzan",
"author_id": 20655686,
"author_profile": "https://Stackoverflow.com/users/20655686",
"pm_score": 0,
"selected": false,
"text": "$user = User::where(\"id\",$id)->firstOrFail();\n$user->name = $request->name;\n$user->mobile_no = $request->mobile_no;\n$user->user_role = $request->user_role;\n$user->updated_at = Carbon::now();\n$updateUser = $user->update();\nreturn view('profile',compact(\"user\"));\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12845523/"
] |
74,640,843
|
<p>I have a nested object and an array of objects (<a href="http://jsfiddle.net/9phkbgqe/" rel="nofollow noreferrer">http://jsfiddle.net/9phkbgqe/</a>):</p>
<pre><code>let data1 =
{
"fields": {
"Main": {
"Personal Details": {
"Surname": "Smith",
"Forename1": "John",
"Nickname": "Johny",
"Gender": "Male",
"Date_of_Birth": "05/04/1979",
"Marital_Status": "Divorced"
},
"More Details": {
"Injury": "Hand",
}
}
}
}
let data2 = [
{
"name": "Surname",
"displayName": "Surname",
"value": "Bush",
"dataType": "STRING",
"displayLevel1": "Main",
"displayLevel2": "Personal Details",
"displayLevel3": ""
},
{
"name": "Injury",
"displayName": "Injury",
"value": "Arm",
"dataType": "STRING",
"displayLevel1": "Main",
"displayLevel2": "More Details",
"displayLevel3": ""
}
]
</code></pre>
<p><strong>data2</strong> is the original data source in this scenario.</p>
<p>So, in <strong>data2</strong> I want to use the key <code>name</code> use its value, in this example its "Surname". Then in <strong>data1</strong> find the value of "Injury", in this example that's "smith". I then want to use "smith" as the new value for the <code>value</code> key back in <strong>data2</strong> - which replaces "Bush" in this example.</p>
<p><strong>Another example added</strong>
So, in <strong>data2</strong> I want to use the key <code>name</code> use its value, in this example its "Injury". Then in <strong>data1</strong> find the value of "Injury", in this example that's "Hand". I then want to use "Hand" as the new value for the <code>value</code> key back in <strong>data2</strong> - which replaces "Arm" in this example.</p>
<p>End result being:</p>
<pre><code>let data2 = [
{
"name": "Surname",
"displayName": "Surname",
"value": "Smith",
"dataType": "STRING",
"displayLevel1": "Main",
"displayLevel2": "Personal Details",
"displayLevel3": ""
},
{
"name": "Injury",
"displayName": "Injury",
"value": "Hand",
"dataType": "STRING",
"displayLevel1": "Main",
"displayLevel2": "More Details",
"displayLevel3": ""
}
]
</code></pre>
<p>Any help would be appreciated here! thanks</p>
|
[
{
"answer_id": 74641065,
"author": "analayze",
"author_id": 16986336,
"author_profile": "https://Stackoverflow.com/users/16986336",
"pm_score": 0,
"selected": false,
"text": "// get the value of key \"Name\" in data 2\nconst nameVal = data2[0]['name'] \n\n// once you have the value you can get the surname from data 1 obj \nconst simplifiedObj = data1['fields']['Main']['Personal Details']\nconst surname = simplifiedObj[nameVal]\n\n//finally you can assign your data2 (which is an array of objects, and not an object itself) the new value\ndata2[0]['value'] = surname\n"
},
{
"answer_id": 74641212,
"author": "RKataria",
"author_id": 19533962,
"author_profile": "https://Stackoverflow.com/users/19533962",
"pm_score": 2,
"selected": true,
"text": "const newData = data2.map((data) => {\n const val = ''\n if (data.displayLevel3) {\n return {\n ...data,\n value: data1.fields[data.displayLevel1][data.displayLevel2][data.displayLevel3][data.name]\n }\n }\n if (data.displayLevel2) {\n return {\n ...data,\n value: data1.fields[data.displayLevel1][data.displayLevel2][data.name]\n }\n }\n if (data.displayLevel1) {\n return {\n ...data,\n value: data1.fields[data.displayLevel1][data.name]\n }\n }\n return {\n ...data,\n value: data1.fields[data.name]\n }\n})\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2402389/"
] |
74,640,889
|
<p>I am given some school task, I am using React js and tailwindcss tools, I want to make a table that shows data.</p>
<p>I am using some sources I found on youtube, but not all the data was inserted into the table.</p>
<p>App.js code:</p>
<pre><code>import React, {useState} from "react";
import "./App.css";
import data from "./dataset.json";
const App = () => {
const [contacts, setContacts] = useState(data);
return (
<div className="app-container">
<table>
<thead>
<tr>
<th>NAMA</th>
<th>UMUR</th>
<th>TINGGI</th>
<th>BERAT BADAN</th>
<th>JENIS KELAMIN</th>
<th>TEKANAN SISTOLE</th>
<th>TEKANAN DIASTOLE</th>
<th>TINGKAT KOLESTEROL</th>
<th>TINGKAT GLUKOSA</th>
<th>PEROKOK AKTIF/TIDAK</th>
<th>ALKOHOLIK/TIDAK</th>
<th>AKTIVITAS FISIK</th>
<th>RIWAYAT PENYAKIT CARDIOVASCULAR</th>
</tr>
</thead>
<tbody>
{contacts.map((contacts)=> (
<tr>
<td>{contacts.name}</td>
<td>{contacts.age}</td>
<td>{contacts.height}</td>
<td>{contacts.weight}</td>
<td>{contacts.gender}</td>
<td>{contacts.ap_hi}</td>
<td>{contacts.ap_lo}</td>
<td>{contacts.cholestrol}</td>
<td>{contacts.gluc}</td>
<td>{contacts.smoke}</td>
<td>{contacts.alco}</td>
<td>{contacts.active}</td>
<td>{contacts.cardio}</td>
</tr>
)
)}
</tbody>
</table>
</div>
);
};
export default App;
</code></pre>
<p>This App.css :</p>
<pre class="lang-css prettyprint-override"><code>.app-container {
display: flex;
flex-direction: column;
gap: 10px;
padding: 2rem;
}
table {
border-collapse: collapse;
width: 250%;
}
th,
td {
border: 1px solid #ffffff;
text-align: center;
padding: 10px;
font-size: 25px;
}
th {
background-color: rgb(117, 201, 250);
}
td {
background-color: rgb(205, 235, 253);
}
form {
display: flex;
gap: 10px;
}
form td:last-child {
display: flex;
justify-content: space-evenly;
}
form * {
font-size: 25px;
}
</code></pre>
<p>and this my dataset.json :</p>
<pre class="lang-json prettyprint-override"><code>[
{
"_id": "633664fd355fcafc3b1282cc",
"name": "yazid",
"age": 18,
"height": 165,
"weight": 55,
"gender": true,
"ap_hi": 130,
"ap_lo": 85,
"cholestrol": 1,
"gluc": 1,
"smoke": true,
"alco": false,
"active": true,
"cardio": false,
"__v": 0
},
{
"_id": "63369d1d355fcafc3b1282da",
"name": "ryan",
"age": 18,
"height": 165,
"weight": 55,
"gender": true,
"ap_hi": 130,
"ap_lo": 85,
"cholestrol": 1,
"gluc": 1,
"smoke": true,
"alco": false,
"active": true,
"cardio": false,
"__v": 0
}
]
</code></pre>
<p>and here are few images of the UI</p>
<p><a href="https://i.stack.imgur.com/DNC3B.png" rel="nofollow noreferrer">Table1</a> <a href="https://i.stack.imgur.com/nwS31.png" rel="nofollow noreferrer">Table 2</a> <a href="https://i.stack.imgur.com/vvxff.png" rel="nofollow noreferrer">Table 3</a></p>
<p>I don't know why, but the data in "gender", "smoke", "alco", "active" and "cardio" won't show on the table but the data on"name" which is a string its showing up</p>
<p>so I made changes to the data as follows</p>
<pre><code>"smoke": "true",
"alco": "false",
"active": "true",
"cardio": "false",
</code></pre>
<p>but it still won't show any change.</p>
<p>if I set "smoke" to true I want it to show as "true"</p>
<p>and I also want to make a change for gender if it is true it should show as "man" and if it is false it should show as "woman" which I was not able to do</p>
|
[
{
"answer_id": 74641065,
"author": "analayze",
"author_id": 16986336,
"author_profile": "https://Stackoverflow.com/users/16986336",
"pm_score": 0,
"selected": false,
"text": "// get the value of key \"Name\" in data 2\nconst nameVal = data2[0]['name'] \n\n// once you have the value you can get the surname from data 1 obj \nconst simplifiedObj = data1['fields']['Main']['Personal Details']\nconst surname = simplifiedObj[nameVal]\n\n//finally you can assign your data2 (which is an array of objects, and not an object itself) the new value\ndata2[0]['value'] = surname\n"
},
{
"answer_id": 74641212,
"author": "RKataria",
"author_id": 19533962,
"author_profile": "https://Stackoverflow.com/users/19533962",
"pm_score": 2,
"selected": true,
"text": "const newData = data2.map((data) => {\n const val = ''\n if (data.displayLevel3) {\n return {\n ...data,\n value: data1.fields[data.displayLevel1][data.displayLevel2][data.displayLevel3][data.name]\n }\n }\n if (data.displayLevel2) {\n return {\n ...data,\n value: data1.fields[data.displayLevel1][data.displayLevel2][data.name]\n }\n }\n if (data.displayLevel1) {\n return {\n ...data,\n value: data1.fields[data.displayLevel1][data.name]\n }\n }\n return {\n ...data,\n value: data1.fields[data.name]\n }\n})\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20563760/"
] |
74,640,892
|
<p>I have the array as below;</p>
<p><a href="https://i.stack.imgur.com/bjTT7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bjTT7.png" alt="enter image description here" /></a></p>
<p>I'd like to insert each <code>name</code> keys into <code>tableName</code> and get the inserted id.
For the <code>steps</code>, each of them will be inserted into another table <code>tableSteps</code> including the last inserted id of the <code>name</code>.</p>
<p>Like as below screenshot.</p>
<p><a href="https://i.stack.imgur.com/u9fVk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u9fVk.png" alt="enter image description here" /></a></p>
<p>In my controller,</p>
<p>Here's what I've done so far.</p>
<pre><code> $instructionsArrays = $request->instructions;
$max = count($instructionsArrays);
for ($x = 1; $x <= $max; $x++) {
foreach($instructionsArrays as $instructionsArray){
Instruction::updateOrCreate(
['recipe_id' => session()->get('recipeArr.id'), 'sequence' => $x],
['name' => $instructionsArray['name']],
);
}
}
</code></pre>
<p>I was able to save sequence numbers but for names it saves only the last <code>name</code> key.
And... I'm really lost..</p>
|
[
{
"answer_id": 74641171,
"author": "Tghosh",
"author_id": 10321719,
"author_profile": "https://Stackoverflow.com/users/10321719",
"pm_score": 2,
"selected": false,
"text": "foreach($request->instructions as $key => $val){\n$id = Instruction::insertGetId(\n ['recipe_id' => session()->get('recipeArr.id'), 'sequence' => $key + 1],\n ['name' => $val['name']],\n);\n$data = []; //bulk insertion\n$created_at = now();\nforeach($val[\"steps\"] as $step){\n array_push($data, [\"header_id\" => $id, \"name\" => $step, \"sequence\" => $key+1, \"created_at\" => $created_at]); //why insert sequence when you can obtain it from the relationship?\n }\n Steps::insert($data);\n }\n"
},
{
"answer_id": 74642147,
"author": "Borgy",
"author_id": 12390764,
"author_profile": "https://Stackoverflow.com/users/12390764",
"pm_score": 1,
"selected": false,
"text": " foreach ($request->instructions as $key => $val) {\n $instruction = Instruction::updateOrCreate(\n ['recipe_id' => session()->get('recipeArr.id'), 'sequence' => $key + 1],\n ['instructions_name' => $val['name']],\n );\n $id = $instruction->id;\n $data = []; //bulk insertion\n $i = 1;\n foreach ($val[\"steps\"] as $step) {\n if(!is_null($step)){\n array_push($data, [\"instruction_id\" => $id, \"steps_name\" => $step, \"sequence\" => $i]);\n $i++;\n }\n }\n Steps::insert($data);\n }\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12390764/"
] |
74,640,911
|
<p><img src="https://i.stack.imgur.com/BjfN7.png" alt="example" /></p>
<p>How can i insert multiple values into one row?</p>
<p>My query</p>
<pre class="lang-sql prettyprint-override"><code>insert into table_RekamMedis values ('RM001', '1999-05-01', 'D01', 'Dr Zurmaini', 'S11', 'Tropicana', 'B01', 'Sulfa', '3dd1');
</code></pre>
<p>i cant insert two values into one row. is there another way to do it?</p>
|
[
{
"answer_id": 74641171,
"author": "Tghosh",
"author_id": 10321719,
"author_profile": "https://Stackoverflow.com/users/10321719",
"pm_score": 2,
"selected": false,
"text": "foreach($request->instructions as $key => $val){\n$id = Instruction::insertGetId(\n ['recipe_id' => session()->get('recipeArr.id'), 'sequence' => $key + 1],\n ['name' => $val['name']],\n);\n$data = []; //bulk insertion\n$created_at = now();\nforeach($val[\"steps\"] as $step){\n array_push($data, [\"header_id\" => $id, \"name\" => $step, \"sequence\" => $key+1, \"created_at\" => $created_at]); //why insert sequence when you can obtain it from the relationship?\n }\n Steps::insert($data);\n }\n"
},
{
"answer_id": 74642147,
"author": "Borgy",
"author_id": 12390764,
"author_profile": "https://Stackoverflow.com/users/12390764",
"pm_score": 1,
"selected": false,
"text": " foreach ($request->instructions as $key => $val) {\n $instruction = Instruction::updateOrCreate(\n ['recipe_id' => session()->get('recipeArr.id'), 'sequence' => $key + 1],\n ['instructions_name' => $val['name']],\n );\n $id = $instruction->id;\n $data = []; //bulk insertion\n $i = 1;\n foreach ($val[\"steps\"] as $step) {\n if(!is_null($step)){\n array_push($data, [\"instruction_id\" => $id, \"steps_name\" => $step, \"sequence\" => $i]);\n $i++;\n }\n }\n Steps::insert($data);\n }\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20655447/"
] |
74,640,926
|
<p>How to start executing a block of code after changing the value of MutableLiveData when using .observeAsState()?</p>
<p>Example: MutableLiveData changes and after need to call Toast.</p>
<p>This code returns error «Composable calls are not allowed inside the calculation parameter of inline fun remember(calculation: () -> TypeVariable(T)): TypeVariable(T)»</p>
<pre><code>@Composable
fun TextInfo() {
val isSuccess by remember { viewModel.isSuccess.observeAsState() }//var isSuccess = MutableLiveData<Boolean>() — in ViewModel
LaunchedEffect(isSuccess) {
Log.d("IS SUCCESS", "trues")
}
}
</code></pre>
|
[
{
"answer_id": 74641007,
"author": "Thracian",
"author_id": 5457853,
"author_profile": "https://Stackoverflow.com/users/5457853",
"pm_score": 0,
"selected": false,
"text": "LocalContext.current requires @Composable\nfun TextInfo() {\n val isSuccess by remember { viewModel.isSuccess.observeAsState() }//var isSuccess = MutableLiveData<Boolean>() — in ViewModel\n val context = LocalContext.current\n\n LaunchedEffect(isSuccess) {\n if(isSuccess){\n Toast.makeText(context, \"IS SUCCESS\", \"trues\", Toast.LENGTH_SHORT).show()\n }\n }\n}\n"
},
{
"answer_id": 74641022,
"author": "z.y",
"author_id": 19023745,
"author_profile": "https://Stackoverflow.com/users/19023745",
"pm_score": 3,
"selected": true,
"text": "remember{…} @Composable remember{…} ViewModel val isSuccess by viewModel.isSuccess.observeAsState()\n\nLaunchedEffect(isSuccess) {\n if (isSuccess) {\n Log.d(\"IS SUCCESS\", \"trues\")\n } \n}\n val isSuccess by viewModel.isSuccess.observeAsState()\n\nButton(onClick = { viewModel.updateSuccess() }) {}\n \nLaunchedEffect(isSuccess) {\n if (isSuccess) {\n Log.e(\"IS_SUCCESS\", \"IS_SUCCESS? $isSuccess\")\n }\n \n}\n ViewModel fun updateSuccess() {\n isSuccess.value = isSuccess.value?.not()\n}\n 29568-29568 E/IS_SUCCESS: IS_SUCCESS? true\n29568-29568 E/IS_SUCCESS: IS_SUCCESS? true\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17766330/"
] |
74,640,941
|
<p><a href="https://i.stack.imgur.com/4R2UT.png" rel="nofollow noreferrer">enter image description here</a>
I'm making a registration code, and it keeps saying error. What should I change?</p>
<p>I tried substituting it with every combination possible. I even took the space out, and yes there's a if code above.
<a href="https://i.stack.imgur.com/7Fi75.png" rel="nofollow noreferrer">enter image description here</a></p>
|
[
{
"answer_id": 74641007,
"author": "Thracian",
"author_id": 5457853,
"author_profile": "https://Stackoverflow.com/users/5457853",
"pm_score": 0,
"selected": false,
"text": "LocalContext.current requires @Composable\nfun TextInfo() {\n val isSuccess by remember { viewModel.isSuccess.observeAsState() }//var isSuccess = MutableLiveData<Boolean>() — in ViewModel\n val context = LocalContext.current\n\n LaunchedEffect(isSuccess) {\n if(isSuccess){\n Toast.makeText(context, \"IS SUCCESS\", \"trues\", Toast.LENGTH_SHORT).show()\n }\n }\n}\n"
},
{
"answer_id": 74641022,
"author": "z.y",
"author_id": 19023745,
"author_profile": "https://Stackoverflow.com/users/19023745",
"pm_score": 3,
"selected": true,
"text": "remember{…} @Composable remember{…} ViewModel val isSuccess by viewModel.isSuccess.observeAsState()\n\nLaunchedEffect(isSuccess) {\n if (isSuccess) {\n Log.d(\"IS SUCCESS\", \"trues\")\n } \n}\n val isSuccess by viewModel.isSuccess.observeAsState()\n\nButton(onClick = { viewModel.updateSuccess() }) {}\n \nLaunchedEffect(isSuccess) {\n if (isSuccess) {\n Log.e(\"IS_SUCCESS\", \"IS_SUCCESS? $isSuccess\")\n }\n \n}\n ViewModel fun updateSuccess() {\n isSuccess.value = isSuccess.value?.not()\n}\n 29568-29568 E/IS_SUCCESS: IS_SUCCESS? true\n29568-29568 E/IS_SUCCESS: IS_SUCCESS? true\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20655442/"
] |
74,640,956
|
<p>I try bring the snackbar to the foremost ui.</p>
<p>My case is</p>
<ol>
<li>Open internet_connectiviity popup(modal) with Settings.panel.ACTION_INTERNET_CONNECTIVITY</li>
<li>When user enable wifi, my app shows an alert to close this modal.</li>
<li><strong>However, snackbar shows, or appears behind system ui(internet connectivity modal).</strong></li>
</ol>
<p>Since Android 12, customization with Toast is pretty much limited, so that's why I decide to use snackbar as a primary option.</p>
<p>I realize that the Toast is controlled by the system, so maybe that is why it is always the foremost ui to the user, even if the system ui(such as internet connectivity panel) presents and I want snackbar to follow that exact behavior.</p>
<p><strong>How should i make snackbar the foremost ui??</strong></p>
<p>I feel like when using snackbar, we use <strong>view as a parameter to pass</strong>, so manupulating this view would make something different, but i couldn't figure it out.</p>
|
[
{
"answer_id": 74642747,
"author": "Shyam Sunder",
"author_id": 18542740,
"author_profile": "https://Stackoverflow.com/users/18542740",
"pm_score": 0,
"selected": false,
"text": "View view onCreate() function(View view) SnackBar view"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8281218/"
] |
74,641,009
|
<p>I'm trying to copy certain columns from a sheet to another (around 15).</p>
<p>My current method is less than ideal (I think).</p>
<pre><code>Sheets(2).Range("A:A").Value = Sheets(1).Range("C:C").Value
Sheets(2).Range("C:C").Value = Sheets(1).Range("G:G").Value
Sheets(2).Range("D:D").Value = Sheets(1).Range("T:T").Value
</code></pre>
<p>It looks repetitive and more importantly it copies the entire column, which slows down the process by loading the empty rows until the end of the sheet as well.</p>
<p>I'm trying to figure out the best possible way to copy the columns <em>just</em> up to the last used column.</p>
<p>This is my current idea, but the empty cells in the second sheet are filled with the <em>not available</em> error value, which defeats the purpose.</p>
<pre><code>lastRow = Sheets(1).Range("C" & Sheets(1).Rows.Count).End(xlUp).Row
Sheets(2).Range("A:A").Value = Sheets(1).Range("C1:C" & lastRow).Value
</code></pre>
<p>Any function that I'm probably not aware of? Thank you!</p>
<p>(And yes, this must be done in VBA. Ask my boss .)</p>
|
[
{
"answer_id": 74642747,
"author": "Shyam Sunder",
"author_id": 18542740,
"author_profile": "https://Stackoverflow.com/users/18542740",
"pm_score": 0,
"selected": false,
"text": "View view onCreate() function(View view) SnackBar view"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20197062/"
] |
74,641,021
|
<p>I have read that with TDD we should approach the entity (function, class etc.) under test from the perspective of the user/caller of the entity. The gist being focusing on the public "interface". This in turn would drive the design and help reason about the design earlier.<br />
But when we need to introduce mocks and stubs into our tests, isn't that an implementation detail?<br />
Why would/should the "user" care about the other entities that are supposed to be there?<br />
E.g.<br />
How to start writing a test for the <code>PlaceOrder</code> service which should check with the credit card service if the user has enough money? Putting a mock for the credit card service whilst writing a test from the perspective of the <code>PlaceOrder</code> client looks out of place now - because it is an implementation detail; our <code>PlaceOrder</code> may call the credit card for each user or it can simply have a cache with scores provided at the creation time.</p>
|
[
{
"answer_id": 74642747,
"author": "Shyam Sunder",
"author_id": 18542740,
"author_profile": "https://Stackoverflow.com/users/18542740",
"pm_score": 0,
"selected": false,
"text": "View view onCreate() function(View view) SnackBar view"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2566775/"
] |
74,641,023
|
<p>I'm trying to write some code that will deserialize JSON into <em>somebody elses class</em>. That is, I don't own the target class so I can't annotate it.</p>
<p>In particular, this class has some helper methods that are complicating the deserialization process. Something like this:</p>
<pre class="lang-java prettyprint-override"><code>class Result {
private List<String> ids;
public List<String> getIds() {
return ids;
}
public void setIds(List<String> ids) {
this.ids = ids;
}
// Helpers
public String getId() {
return this.ids.isEmpty() ? null : this.ids.get(0);
}
public void setId(String id) {
this.ids = List.of(id);
}
}
</code></pre>
<p>When serialized, we get both <code>ids</code> and <code>id</code> come through as fields:</p>
<pre class="lang-json prettyprint-override"><code>{
"ids": ["1", "2", "3"],
"id": "1"
}
</code></pre>
<p>And then when deserializing this JSON, Jackson is calling both setters - reasonably enough - and thus the object is wrong. The end result is that the <code>ids</code> field is set to <code>["1"]</code> and <em>not</em> <code>["1", "2", "3"]</code> as it should be.</p>
<p>So what I want to be able to do is fix this. And I'm thinking that the easiest/safest/best way is to be able to modify the JSON AST somewhere in the deserializing process. Specifically by just removing the "id" field from the JSON so that it doesn't get seen by the standard deserializer. (I know this works by doing it manually with string manipulation, but that's awful)</p>
<p>I could write a full deserializer for all the fields, but then I'm beholden to maintaining it if any new fields are added in the future, when all I actually want to do is ignore one single field and have everything else processed as normal. The real class actually has about a dozen fields at present, and I can't guarantee that it won't change in the future.</p>
<p>What I can't work out is how to do this. I was really hoping there was just some standard <code>JsonDeserializer</code> subclass that would let me do this, but I can't find one. The best I've been able to work out is a normal <code>StdDeserializer</code> that then uses <code>parser.getCodec().treeToValue()</code> - courtesty of <a href="https://stackoverflow.com/a/53053393/59724">this answer</a> - except that this results in an infinite loop as it calls back into the exact same deserializer every time!</p>
<p>Frustratingly, most answers to this problem are "Just annotate the class" - and that's not an option here!</p>
<p>Is there a standard way to achieve this?</p>
<p>Cheers</p>
|
[
{
"answer_id": 74641366,
"author": "Nikos Paraskevopoulos",
"author_id": 2764255,
"author_profile": "https://Stackoverflow.com/users/2764255",
"pm_score": 2,
"selected": true,
"text": "@JsonIgnoreProperties({ \"id\" })\npublic class ResultMixin {\n // nothing else required!\n}\n ObjectMapper ObjectMapper om = ...\nom.addMixIn(Result.class, ResultMixin.class);\n ObjectMapper Result id"
},
{
"answer_id": 74641467,
"author": "Graham",
"author_id": 59724,
"author_profile": "https://Stackoverflow.com/users/59724",
"pm_score": 0,
"selected": false,
"text": "BeanDeserializerModifier public class MyDeserializerModifier extends BeanDeserializerModifier {\n @Override\n public List<BeanPropertyDefinition> updateProperties(final DeserializationConfig config,\n final BeanDescription beanDesc, final List<BeanPropertyDefinition> propDefs) {\n if (beanDesc.getBeanClass().equals(Result.class)) {\n propDefs.removeIf(prop -> prop.getName().equals(\"id\"));\n }\n\n return super.updateProperties(config, beanDesc, propDefs);\n }\n\n @Override\n public BeanDeserializerBuilder updateBuilder(final DeserializationConfig config, final BeanDescription beanDesc,\n final BeanDeserializerBuilder builder) {\n if (beanDesc.getBeanClass().equals(Result.class)) {\n builder.addIgnorable(\"id\");\n }\n\n return super.updateBuilder(config, beanDesc, builder);\n }\n}\n\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/59724/"
] |
74,641,044
|
<p>Using playwright C# I've been trying to work with multiple elements that use the same locator.</p>
<p>Is there any functionality in playwright which is equivalent to the FindElements method from selenium? This method allows us to store multiple elements of the same locator in a collection which can then be used to access individual elements.
I actually need to perform actions of each of the elements so having them in a collection where I can access them by index works well for me.</p>
<p>It seems that due to playwrights locator strictness that there is nothing suitable to achieve the same result as Selenium Findelements.
I temporarily tried using ElementHandles but this is not recommended and still proves problematic when trying to access elements.</p>
<p>Playwright have First, Last and Nth() locator options which allow us to pick a specific element but I prefer having access to all of the elements in list, accessible by index which I find to be more useful when working with multiple elect's in the same or similar areas.</p>
<p>I ended up writing my own code to store the elements in a list but I wondered what others are using as a substitute for FindElements?</p>
<pre><code>IList<ILocator> elements = new List<ILocator>();
int listSize = await Page.Locator("div #internalSearch span.e-list-text").CountAsync();
for (int j = 0; j < listSize; j++)
{ ILocator locator = Page.Locator("div #internalSearch span.e-list-text").Nth(j);
elements.Add(locator);
}
Assert.True(elements.Count == listSize);
</code></pre>
|
[
{
"answer_id": 74641576,
"author": "AJG",
"author_id": 12347635,
"author_profile": "https://Stackoverflow.com/users/12347635",
"pm_score": 1,
"selected": false,
"text": "var rows = page.GetByRole(AriaRole.Listitem);\nvar count = await rows.CountAsync();\nfor (int i = 0; i < count; ++i)\n Console.WriteLine(await rows.Nth(i).TextContentAsync());\n IList < IWebElement > elements = driver.FindElements(By.TagName(\"p\"));\nforeach(IWebElement e in elements) {\n System.Console.WriteLine(e.Text);\n}\n"
},
{
"answer_id": 74648740,
"author": "Vishal Aggarwal",
"author_id": 1831456,
"author_profile": "https://Stackoverflow.com/users/1831456",
"pm_score": 0,
"selected": false,
"text": "const elements = page.locator('div');\nconst divCounts = await elements.evaluateAll((divs, min) => divs.length >= min, 10);\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5611422/"
] |
74,641,057
|
<p>As a part of my journey of creating own realization of drag&drop I faced with the problem of autoscrolling while dragging item.
For now I just try to realize primitive autoscrolling: when mouse enters the bottom-trigger area the page should start scrolling slowly, but it's scrolled by 10px and stopped, while I leave trigger area. What's the couse of these problem, does scrollBy rewrites each other till the end of recursion? If yes, how can I avoid it?</p>
<p>Code example(High order component AutoScroll):</p>
<pre><code>export interface IAutoScrollProps {
children: ReactNode;
}
const AutoScroll = ({ children }: IAutoScrollProps) => {
const bottomTriggerClass = `${styles['bottom-trigger']} ${styles['trigger']}
${styles['horizontal']}`;
const overBottomTrigger = useRef(false);
const scrollBottom: () => void | NodeJS.Timeout = useCallback(() => {
window.scrollBy(0, 10);
if (!overBottomTrigger.current) return;
if (document.body.scrollHeight - window.innerHeight - window.scrollY < 20) return;
return setTimeout(scrollBottom, 0);
}, []);
const onBottomTriggerMouseEnter: (e: React.MouseEvent) => void = useCallback(
(e) => {
console.log('enter');
overBottomTrigger.current = true;
scrollBottom();
},[scrollBottom]);
const onBottomTriggerMouseLeave: (e: React.MouseEvent) => void = useCallback((e) => {
console.log('leave');
overBottomTrigger.current = false;
}, []);
return (
<div>
<section className="autoScroll-container p-relative">
{children}
</section>
<span
className={bottomTriggerClass}
onMouseEnter={onBottomTriggerMouseEnter}
onMouseLeave={onBottomTriggerMouseLeave}
></span>
</div>
);
};
export default AutoScroll;
</code></pre>
<p><a href="https://i.stack.imgur.com/CdoFx.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CdoFx.gif" alt="Example of an program behaviour" /></a></p>
|
[
{
"answer_id": 74641576,
"author": "AJG",
"author_id": 12347635,
"author_profile": "https://Stackoverflow.com/users/12347635",
"pm_score": 1,
"selected": false,
"text": "var rows = page.GetByRole(AriaRole.Listitem);\nvar count = await rows.CountAsync();\nfor (int i = 0; i < count; ++i)\n Console.WriteLine(await rows.Nth(i).TextContentAsync());\n IList < IWebElement > elements = driver.FindElements(By.TagName(\"p\"));\nforeach(IWebElement e in elements) {\n System.Console.WriteLine(e.Text);\n}\n"
},
{
"answer_id": 74648740,
"author": "Vishal Aggarwal",
"author_id": 1831456,
"author_profile": "https://Stackoverflow.com/users/1831456",
"pm_score": 0,
"selected": false,
"text": "const elements = page.locator('div');\nconst divCounts = await elements.evaluateAll((divs, min) => divs.length >= min, 10);\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17351021/"
] |
74,641,071
|
<p>I have three <code>CSV</code> files:</p>
<p><code>doctors.csv</code></p>
<pre><code>1,John,Smith,Internal Med
2,Jone,Smith,Pediatrics
3,Jone,Carlos,Cardiology
</code></pre>
<p><code>patients.csv</code></p>
<pre><code>1,Sara,Smith,20,07012345678,B1234
2,Mike,Jones,37,07555551234,L22AB
3,Daivd,Smith,15,07123456789,C1ABC
</code></pre>
<p>... and <code>linked.csv</code>, which I need to populate based on <code>doctors.csv</code> and <code>patients.csv</code>.</p>
<p>I'm taking two inputs from the user that correspond with the <code>doctor ID</code> and <code>patient ID</code>, and checking if they are present, and then writing them to the <code>linked.csv</code> file.</p>
<p>I'd like the <code>linked.csv</code> file to contain for each column:</p>
<pre><code>[patientID,patientfirstname,patientsurname,doctorID,doctorfirstname,doctorlastname]
</code></pre>
<p>Unfortunately, I can't figure out how to read a specific row using the <code>csv</code> module and then extract the specific data I need from both files.</p>
<p>Here is the code I have so far:</p>
<pre class="lang-py prettyprint-override"><code>#asking for input
print('Please select both a Patient ID and Doctor ID to link together')
patient_index = input('Please enter the patient ID: ')
doctorlink = input('Please select a doctor ID: ')
doctorpresent = False
patientpresent = False
# precence check for both values
with open('patiens.csv', 'r') as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
if patient_index == row[0]:
print('Patient is present')
patientpresent = True
with open('doctors.csv', 'r') as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
if patient_index == row[0]:
print('Doctor is present')
doctorpresent = True
if patientpresent == True and doctorpresent == True:
</code></pre>
<p>Here, I need to add the code necessary for extracting the rows.</p>
|
[
{
"answer_id": 74641576,
"author": "AJG",
"author_id": 12347635,
"author_profile": "https://Stackoverflow.com/users/12347635",
"pm_score": 1,
"selected": false,
"text": "var rows = page.GetByRole(AriaRole.Listitem);\nvar count = await rows.CountAsync();\nfor (int i = 0; i < count; ++i)\n Console.WriteLine(await rows.Nth(i).TextContentAsync());\n IList < IWebElement > elements = driver.FindElements(By.TagName(\"p\"));\nforeach(IWebElement e in elements) {\n System.Console.WriteLine(e.Text);\n}\n"
},
{
"answer_id": 74648740,
"author": "Vishal Aggarwal",
"author_id": 1831456,
"author_profile": "https://Stackoverflow.com/users/1831456",
"pm_score": 0,
"selected": false,
"text": "const elements = page.locator('div');\nconst divCounts = await elements.evaluateAll((divs, min) => divs.length >= min, 10);\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20357735/"
] |
74,641,135
|
<p>im trying to make the background of a parent div change when hovering over a li in its child.. i did that but now i want to display a different img when hovering over a different li inside the same child div... i cant seem to do that and cant find anyone else having the same problem.. and if it needs JavaScript also i dont mind</p>
<p>i tried to specify the li but it doesnt work</p>
<p>heres the css code</p>
<pre><code>#mainpage{
pointer-events: none;
}
#listman {
pointer-events: auto;
}
#mainpage:hover {
background: url("bg1.jpg");
background-repeat: no-repeat;
height: 500x;
background-position: top;
background-size: 100%;
}
</code></pre>
<p>and heres the html part</p>
<pre><code>div id="mainpage">
<div id="listman">
<ul class="bigger">
<li id="listman1" href="#"> <a> 1 </a> </li>
<li id="listman2" href="#"> <a> 2 </a> </li>
<li id="listman3" href="#"> <a> 3 </a> </li>
<li id="listman4" href="#"> <a> 4 </a> </li>
<li id="listman5" href="#"> <a> 5 </a> </li>
<li id="listman6" href="#"> <a> 6 </a> </li>
<li id="listman7" href="#"> <a> 7 </a> </li>
<li id="listman8" href="#"> <a> 8 </a> </li>
</ul>
</div>
</div>
</div>
</code></pre>
<p>i want to make a different img to appear when hovering over (listman2) can anyone help me?</p>
|
[
{
"answer_id": 74641576,
"author": "AJG",
"author_id": 12347635,
"author_profile": "https://Stackoverflow.com/users/12347635",
"pm_score": 1,
"selected": false,
"text": "var rows = page.GetByRole(AriaRole.Listitem);\nvar count = await rows.CountAsync();\nfor (int i = 0; i < count; ++i)\n Console.WriteLine(await rows.Nth(i).TextContentAsync());\n IList < IWebElement > elements = driver.FindElements(By.TagName(\"p\"));\nforeach(IWebElement e in elements) {\n System.Console.WriteLine(e.Text);\n}\n"
},
{
"answer_id": 74648740,
"author": "Vishal Aggarwal",
"author_id": 1831456,
"author_profile": "https://Stackoverflow.com/users/1831456",
"pm_score": 0,
"selected": false,
"text": "const elements = page.locator('div');\nconst divCounts = await elements.evaluateAll((divs, min) => divs.length >= min, 10);\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20655479/"
] |
74,641,137
|
<p>I've published 5 versions of my repository so far without any issues. With version 1.0.5 I'm getting an error:</p>
<blockquote>
<p><code>Execution failed for task ':publishMavenJavaPublicationToOSSRHRepository'.</code></p>
<blockquote>
<p><code>> Failed to publish publication 'mavenJava' to repository 'OSSRH'</code></p>
<blockquote>
<p><code>> No cached resource 'https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/io/github/jspinak/brobot/1.0.5-SNAPSHOT/maven-metadata.xml' available for offline mode.</code></p>
</blockquote>
</blockquote>
</blockquote>
<p>The only help I've found online is to toggle the offline mode in Gradle
(<a href="https://stackoverflow.com/questions/60481987/no-cached-version-gradle-plugin-available-for-offline-mode">No Cached Version Gradle Plugin Available for offline mode</a>),
which then produces the following error when publishing:</p>
<blockquote>
<p><code>Could not GET 'https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/io/github/jspinak/brobot/1.0.5-SNAPSHOT/maven-metadata.xml'.</code></p>
<blockquote>
<p><code> Received status code 400 from server: Bad Request Disable Gradle 'offline mode' and sync project</code></p>
</blockquote>
</blockquote>
<p>I'm not sure if this is something I've done wrong, a Sonatype issue, a Gradle issue, an Intellij issue, or something else. I've also posted on the Sonatype message boards just in case.</p>
<p>In the Gradle Toolbar, there is an option <em>generateMetadataFileForMavenJavaPublication</em>. Running this doesn't seem to change anything.</p>
<p>This is an open source repository and you can see the build.gradle file at
<a href="https://github.com/jspinak/brobot/blob/main/library/build.gradle" rel="nofollow noreferrer">https://github.com/jspinak/brobot/blob/main/library/build.gradle</a>.</p>
|
[
{
"answer_id": 74641576,
"author": "AJG",
"author_id": 12347635,
"author_profile": "https://Stackoverflow.com/users/12347635",
"pm_score": 1,
"selected": false,
"text": "var rows = page.GetByRole(AriaRole.Listitem);\nvar count = await rows.CountAsync();\nfor (int i = 0; i < count; ++i)\n Console.WriteLine(await rows.Nth(i).TextContentAsync());\n IList < IWebElement > elements = driver.FindElements(By.TagName(\"p\"));\nforeach(IWebElement e in elements) {\n System.Console.WriteLine(e.Text);\n}\n"
},
{
"answer_id": 74648740,
"author": "Vishal Aggarwal",
"author_id": 1831456,
"author_profile": "https://Stackoverflow.com/users/1831456",
"pm_score": 0,
"selected": false,
"text": "const elements = page.locator('div');\nconst divCounts = await elements.evaluateAll((divs, min) => divs.length >= min, 10);\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13361997/"
] |
74,641,148
|
<p>So this is WPF + MVVM + .NET 4.8 + WCT.</p>
<p>I have an <code>AsyncRelayCommand</code> in my VM class defined like this:</p>
<pre><code>private AsyncRelayCommand _StartSyncCommand;
public AsyncRelayCommand StartSyncCommand
{
get
{
_StartSyncCommand ??= new AsyncRelayCommand(Pump, () => !_StartSyncCommand.IsRunning);
return _StartSyncCommand;
}
}
</code></pre>
<p>The actual task method contains an async iterator and looks like this:</p>
<pre><code>private async Task Pump(CancellationToken token)
{
OnPropertyChanged(nameof(IsBusy));
try
{
await foreach (var item in applicationService.FetchItems())
{
token.ThrowIfCancellationRequested();
...
}
}
catch(Exception ee)
{
...
}
finally
{
...
}
}
</code></pre>
<p>This method raises property change notification on <code>IsBusy</code> property (to show wait cursor in the UI). However when I check the status of <code>StartSyncCommand</code> in the property, it tells me that it is not running.</p>
<pre><code>public bool IsBusy => StartSyncCommand.IsRunning;
</code></pre>
<p>I can't see why this should be the case. The method is actually running when the property change notification occurs. I can see the method in the call stack.</p>
<p>What am I missing here?</p>
<h2>Update</h2>
<p>This is getting weirder. <code>StartSyncCommand.ExecutionTask</code> itself is <code>null</code> while I'm inside the task method:</p>
<p><a href="https://i.stack.imgur.com/lQRAp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lQRAp.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74650902,
"author": "Stephen Cleary",
"author_id": 263693,
"author_profile": "https://Stackoverflow.com/users/263693",
"pm_score": 2,
"selected": true,
"text": "async ExecutionTask = execute();\nIsRunning = true;\n execute Pump Pump await ExecutionTask await Task.Yield(); Pump OnPropertyChanged Pump IsRunning"
},
{
"answer_id": 74667530,
"author": "dotNET",
"author_id": 1137199,
"author_profile": "https://Stackoverflow.com/users/1137199",
"pm_score": 0,
"selected": false,
"text": "private AsyncRelayCommand _StartSyncCommand;\npublic AsyncRelayCommand StartSyncCommand\n{\n get\n {\n _StartSyncCommand ??= new AsyncRelayCommand(token =>\n {\n return Task.Run(async () =>\n {\n OnPropertyChanged(nameof(IsBusy));\n await Pump(token);\n });\n }, \n () => !_StartSyncCommand.IsRunning);\n return _StartSyncCommand;\n }\n}\n AsyncRelayCommand await IsRunning ExecutionTask await Task.Run()"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1137199/"
] |
74,641,237
|
<p>I want to print specific row and column from a csv file.
csv file look like,</p>
<p>R,IMSI,DATE FIRST EVENT,TIME FIRST EVENT,DATE LAST EVENT,TIME LAST EVENT,DC(HHMMSS),NC,VOLUME,SDR
R
C,634012007277489,20221122,150025,20221122,150025,711,1,0,294
C,634012031576061,20221122,150859,20221122,151738,905,3,0,1597
C,634012045006518,20221122,144022,20221122,144022,902,1,0,368
R
R
R,END OF REPORT
T,18</p>
<p>Output should be look like,</p>
<p>C,634012007277489,20221122,150025,20221122,150025,711,1,0,294 C,634012031576061,20221122,150859,20221122,151738,905,3,0,1597 C,634012045006518,20221122,144022,20221122,144022,902,1,0,368</p>
|
[
{
"answer_id": 74641273,
"author": "Triceratops",
"author_id": 13440165,
"author_profile": "https://Stackoverflow.com/users/13440165",
"pm_score": 1,
"selected": false,
"text": "pandas pip install pandas import pandas as pd\n\ndf = pd.read_csv(fullpath.csv)\nx = df[column_name].iloc[row_number]\n"
},
{
"answer_id": 74641302,
"author": "Orfeas Bourchas",
"author_id": 16781682,
"author_profile": "https://Stackoverflow.com/users/16781682",
"pm_score": 1,
"selected": false,
"text": "pandas.read_csv() import pandas as pd\ndf = pd.read_csv('filename.csv', skipfooter=1, header=1)\ndf.iloc[row_number,column_number]\n"
},
{
"answer_id": 74641416,
"author": "Dhruvin Vadgama",
"author_id": 20499874,
"author_profile": "https://Stackoverflow.com/users/20499874",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\n\ndf = pd.read_csv(\"example.csv\", delimiter =\",\")\n\nfor row in range(len(df)):\n for column in range(len(df.columns)):\n print(df.iat[row, column])\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20346620/"
] |
74,641,272
|
<pre><code>
def is_Data_Valid():
emp_df.withColumn(
"ValidationErrors",
f.when(
f.col("Name").rlike("^[a-zA-Z]+$") & f.col("Age").cast("int").isNotNull() & f.col(
"Experience").cast("int").isNotNull() & f.col("Year").cast("int").isNotNull() & f.col(
"Dept").rlike("^[a-zA-Z]+$"),
f.lit("0")
).otherwise(f.lit("Invalid data"))
)
</code></pre>
<p>I have this above function for validation, but here in this I can only validate the data of one dataframe "emp<em>df" but there is another dataframe "emp1</em>f_df".</p>
<p>So to avoid repeatation can I pass data frame to function and call function twice?</p>
|
[
{
"answer_id": 74641273,
"author": "Triceratops",
"author_id": 13440165,
"author_profile": "https://Stackoverflow.com/users/13440165",
"pm_score": 1,
"selected": false,
"text": "pandas pip install pandas import pandas as pd\n\ndf = pd.read_csv(fullpath.csv)\nx = df[column_name].iloc[row_number]\n"
},
{
"answer_id": 74641302,
"author": "Orfeas Bourchas",
"author_id": 16781682,
"author_profile": "https://Stackoverflow.com/users/16781682",
"pm_score": 1,
"selected": false,
"text": "pandas.read_csv() import pandas as pd\ndf = pd.read_csv('filename.csv', skipfooter=1, header=1)\ndf.iloc[row_number,column_number]\n"
},
{
"answer_id": 74641416,
"author": "Dhruvin Vadgama",
"author_id": 20499874,
"author_profile": "https://Stackoverflow.com/users/20499874",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\n\ndf = pd.read_csv(\"example.csv\", delimiter =\",\")\n\nfor row in range(len(df)):\n for column in range(len(df.columns)):\n print(df.iat[row, column])\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20642042/"
] |
74,641,295
|
<p>Given a number i.e (<code>0xD5B8</code>), what is the <strong>most</strong> efficient way in Python to subset across the bits over a sliding window using only native libraries?</p>
<p>A method might look like the following:</p>
<pre><code>def window_bits(n,w, s):
'''
n: the number
w: the window size
s: step size
'''
# code
window_bits(0xD5B8, 4, 4) # returns [[0b1101],[0b0101],[0b1011],[0b1000]]
window_bits(0xD5B8, 2, 2) # returns [[0b11],[0b01],[0b01],[0b01],[0b10],[0b11],[0b10],[0b00]]
</code></pre>
<p>Some things to consider:</p>
<ol>
<li>should strive to use minimal possible memory footprint</li>
<li>can only use inbuilt libraries</li>
<li>as fast as possible.</li>
<li>if <code>len(bin(n)) % w != 0</code>, then the last window should exist, with a size less than <code>w</code></li>
</ol>
<p>Some of the suggestions are like <a href="https://stackoverflow.com/questions/434287/how-to-iterate-over-a-list-in-chunks">How to iterate over a list in chunks</a>, which is convert the int using <code>bin</code> and iterate over as a slice. However, these questions do not prove the optimality. I would think that there are other possible bitwise operations that could be done that are more optimal than running over the bin as a slice (a generic data structure), either from a memory or speed perspective. This question is about the MOST optimal, not about what gets the job done, and it can be considered from memory, speed, or both. Ideally, an answer gives good reasons why their representation is the most optimal.</p>
<p>So, if it is provably the most optimal to convert to <code>bin(x)</code> and then just manage the bits as a slice, then that's the optimal methodology. But this is NOT about an easy way to move a window around bits. Every op and bit counts in this question.</p>
|
[
{
"answer_id": 74642768,
"author": "Tomerikoo",
"author_id": 6045800,
"author_profile": "https://Stackoverflow.com/users/6045800",
"pm_score": 1,
"selected": false,
"text": "bin(n)[2:] def window_bits(n, w, step_size):\n offset = n.bit_length() - w # the initial shift to get the MSB window\n mask = 2**w-1 # To get the actual window we need\n while offset >= 0:\n print(f\"{(n >> offset)&mask:x}\")\n offset -= step_size # advance the window\n window_bits(0xD5B8, 4, 4)"
},
{
"answer_id": 74667411,
"author": "andor kesselman",
"author_id": 2155614,
"author_profile": "https://Stackoverflow.com/users/2155614",
"pm_score": 0,
"selected": false,
"text": "def window_bits(n, w, s):\n offset = n.bit_length() - w \n mask = 2**w-1 \n ret = []\n while offset >= 0:\n ret.append((n >> offset) & mask)\n offset -= s # advance the window\n if offset < 0: # close the end\n mask = 2**(-offset)-1\n ret.append((n >> mask) & mask)\n return ret\n def chunker(n, size, s=None):\n seq = bin(n)\n return (seq[pos:pos + size] for pos in range(0, len(seq), size))\n numbers = [2**n for n in range(10)]\nwindow_size = [4, 8, 12]\nstep_size = window_size\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2155614/"
] |
74,641,296
|
<p>Let's say I have a line looking like this:</p>
<pre><code>/Users/random/354765478/Tests/StoreTests/Base64Tests.swift
</code></pre>
<p>In this example, I would like to get the result:</p>
<pre><code>Tests/StoreTests/Base64Tests.swift
</code></pre>
<p>How can I do if I want to get everything before the first pattern match (either <code>Sources</code> or <code>Tests</code>) using <strong>sed</strong> or <strong>awk</strong>?</p>
<p>I am using <code>sed 's/^.*\(Tests.*\).*$/\1/'</code> right now but it's falling:</p>
<pre><code>echo '/Users/random/354765478/Tests/StoreTests/Base64Tests.swift' | sed 's/^.*\(Tests\)/\1/'
Tests.swift
</code></pre>
<p>Here's another example using <strong>Sources</strong> (which seems to work):</p>
<pre><code>echo '/Users/random/741672469/Sources/Store/StoreDataSource.swift' | sed 's/^.*\(Sources\)/\1/'
Sources/Store/StoreDataSource.swift
</code></pre>
<p>I would like to get everything before the first, and not the last <strong>Sources</strong> or <strong>Tests</strong> pattern match.</p>
<p>Any help would be appreciated!</p>
|
[
{
"answer_id": 74641358,
"author": "RavinderSingh13",
"author_id": 5866580,
"author_profile": "https://Stackoverflow.com/users/5866580",
"pm_score": 2,
"selected": false,
"text": "grep /Sources /Tests grep -oP '^.*?\\/\\K(Sources|Tests)\\/.*' Input_file\n"
},
{
"answer_id": 74641387,
"author": "anubhava",
"author_id": 548225,
"author_profile": "https://Stackoverflow.com/users/548225",
"pm_score": 3,
"selected": true,
"text": "Sources Tests grep -o grep -Eo '(Sources|Tests)/.*' file\n\nTests/StoreTests/Base64Tests.swift\nSources/Store/StoreDataSource.swift\n\n# where input file is\ncat file\n\n/Users/random/354765478/Tests/StoreTests/Base64Tests.swift\n/Users/random/741672469/Sources/Store/StoreDataSource.swift\n (Sources|Tests)/.* Sources/ Tests/ -E -o awk awk 'match($0, /(Sources|Tests)\\/.*/) {\n print substr($0, RSTART)\n}' file\n\nTests/StoreTests/Base64Tests.swift\nSources/Store/StoreDataSource.swift\n sed sed -E 's~.*/((Sources|Tests)/.*)~\\1~' file\n\nTests/StoreTests/Base64Tests.swift\nSources/Store/StoreDataSource.swift\n"
},
{
"answer_id": 74642151,
"author": "HatLess",
"author_id": 16372109,
"author_profile": "https://Stackoverflow.com/users/16372109",
"pm_score": 2,
"selected": false,
"text": "sed $ sed -E 's~([^/]*/)+((Tests|Sources).*)~\\2~' input_file\nTests/StoreTests/Base64Tests.swift\n"
},
{
"answer_id": 74654561,
"author": "Daweo",
"author_id": 10785975,
"author_profile": "https://Stackoverflow.com/users/10785975",
"pm_score": 1,
"selected": false,
"text": "sed 's/^.*\\(Tests.*\\).*$/\\1/'\n * Tests Tests sed perl file.txt /Users/random/354765478/Tests/StoreTests/Base64Tests.swift\n perl -p -e 's/^.*?(Tests.*)$/\\1/' file.txt\n Tests/StoreTests/Base64Tests.swift\n -p -e .* .*? .*"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/408193/"
] |
74,641,301
|
<p>I was inspired by an intro logo and want to try implementing it in the website UI. However the more i tried, the more i realized i was just a beginner in website.</p>
<p><a href="https://i.stack.imgur.com/DNM8W.png" rel="nofollow noreferrer">This is the image</a></p>
<pre><code>function getCursorPosition(event) {
let x = event.clientX;
let y = event.clientY;
document.body[x:y].style.filter = blur("0px");
}
</code></pre>
<p><a href="https://jsfiddle.net/m6dbrv7p/" rel="nofollow noreferrer">This is my code</a>. Can I change the style of specific areas of body html with javascript based on mouse movement?</p>
<p>My expectation is that the body of the website page has filter = blur(5px). So that the specific area reached by the cursor will change its style to filter = blur(0px). Is that possible?</p>
|
[
{
"answer_id": 74641374,
"author": "RenokK",
"author_id": 2377357,
"author_profile": "https://Stackoverflow.com/users/2377357",
"pm_score": 0,
"selected": false,
"text": "document.elementFromPoint(x, y);\n"
},
{
"answer_id": 74641712,
"author": "o1dskoo1",
"author_id": 4722001,
"author_profile": "https://Stackoverflow.com/users/4722001",
"pm_score": 0,
"selected": false,
"text": "div clip-path div clip-path <body onmousemove=\"getCursorPosition(event)\">\n <div id=\"blur\" class=\"blur\"></div>\n <div id=\"kocak\">\n <span>My Website</span>\n <div class=\"cursor-position\">The X cursor position is: <span id=\"cursor-position-x\"></span>.</div>\n <div class=\"cursor-position\">The Y cursor position is: <span id=\"cursor-position-y\"></span>.</div>\n </div>\n</body>\n function getCursorPosition(event) {\n document.getElementById(\"cursor-position-x\").textContent = event.clientX;\n document.getElementById(\"cursor-position-y\").textContent = event.clientY;\n document.getElementById(\"blur\").style.left = event.clientX;\n document.getElementById(\"blur\").style.top = event.clientY;\n}\n .body {\n width: 100%;\n height: 100vh;\n overflow: hidden;\n}\n\n.blur {\n position: absolute;\n top: 50%;\n left: 50%;\n width: 200%;\n height: 200%;\n background: rgba(255, 255, 255, 0.5);\n backdrop-filter: blur(3px);\n clip-path: polygon(0% 0%, 0% 100%, 45% 100%, 45% 45%, 55% 45%, 55% 55%, 45% 55%, 45% 100%, 100% 100%, 100% 0%);\n transform: translate(-50%, -50%);\n}\n"
},
{
"answer_id": 74642475,
"author": "Vadim",
"author_id": 1580941,
"author_profile": "https://Stackoverflow.com/users/1580941",
"pm_score": 2,
"selected": false,
"text": "mousemove requestAnimationFrame() window.addEventListener('DOMContentLoaded', () => {\n const blurEl = document.querySelector('.blur');\n let curX, curY, isRenderScheduled = false;\n blurEl.addEventListener('mousemove', ({x,y}) => {\n curX = x;\n curY = y;\n if(!isRenderScheduled) {\n isRenderScheduled = true;\n requestAnimationFrame(() => {\n blurEl.setAttribute('style', `--x:${curX}px;--y:${curY}px`);\n isRenderScheduled = false;\n });\n }\n });\n}); .content {\n position: absolute;\n top: 0;\n left: 0;\n bottom: 0;\n right: 0;\n display: grid;\n place-content: center;\n}\n.blur {\n position: absolute;\n top: 0;\n left: 0;\n bottom: 0;\n right: 0;\n display: flex;\n flex-direction: row;\n align-items: stretch;\n justify-content: stretch;\n}\n.blur > div {\n display: flex;\n flex-direction: column;\n}\n.blur:before,\n.blur:after,\n.blur > div:before,\n.blur > div:after {\n content: '';\n backdrop-filter:blur(5px);\n flex-grow: 1;\n flex-shrink: 1;\n}\n.blur:before {\n min-width: var(--x, auto);\n max-width: var(--x, auto);\n}\n.blur > div:before {\n min-height: var(--y, auto);\n max-height: var(--y, auto);\n}\n.transparent {\n flex-grow: 0;\n flex-shrink: 0;\n width: 50px;\n height: 50px;\n border: 1px solid silver;\n} <div class=\"content\"> \n <h1>This is the content</h1>\n <div class=\"blur\" style=\"--x:auto;--y:auto;\">\n <div>\n <div class=\"transparent\"></div>\n </div>\n </div>\n</div> .blur :before :after"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20655181/"
] |
74,641,326
|
<p>Take this mockup dataframe for example:</p>
<pre><code>CustomerID Number of Purchases
ABC 5
DEF 24
GHI 85
JKL 2
MNO 100
</code></pre>
<p>Assume this dataframe is first sorted by <strong>Number of Purchases</strong> (descending).
How do I add a new column to it called <strong>Score</strong>, and have values assigned to it as follows:</p>
<ul>
<li>Out of the top 60% customers (meaning the first 3 rows after sorting), 3 should be assigned to <strong>Score</strong>.</li>
<li>Out of the next top 20% customers (row 4 after sorting), 2 should be assigned to <strong>Score</strong>.</li>
<li>Out of the next and last top 20% customers (row 5 after sorting), 1 should be assigned to <strong>Score</strong>.</li>
</ul>
<p>How do I do this in a large dataframe?</p>
|
[
{
"answer_id": 74641374,
"author": "RenokK",
"author_id": 2377357,
"author_profile": "https://Stackoverflow.com/users/2377357",
"pm_score": 0,
"selected": false,
"text": "document.elementFromPoint(x, y);\n"
},
{
"answer_id": 74641712,
"author": "o1dskoo1",
"author_id": 4722001,
"author_profile": "https://Stackoverflow.com/users/4722001",
"pm_score": 0,
"selected": false,
"text": "div clip-path div clip-path <body onmousemove=\"getCursorPosition(event)\">\n <div id=\"blur\" class=\"blur\"></div>\n <div id=\"kocak\">\n <span>My Website</span>\n <div class=\"cursor-position\">The X cursor position is: <span id=\"cursor-position-x\"></span>.</div>\n <div class=\"cursor-position\">The Y cursor position is: <span id=\"cursor-position-y\"></span>.</div>\n </div>\n</body>\n function getCursorPosition(event) {\n document.getElementById(\"cursor-position-x\").textContent = event.clientX;\n document.getElementById(\"cursor-position-y\").textContent = event.clientY;\n document.getElementById(\"blur\").style.left = event.clientX;\n document.getElementById(\"blur\").style.top = event.clientY;\n}\n .body {\n width: 100%;\n height: 100vh;\n overflow: hidden;\n}\n\n.blur {\n position: absolute;\n top: 50%;\n left: 50%;\n width: 200%;\n height: 200%;\n background: rgba(255, 255, 255, 0.5);\n backdrop-filter: blur(3px);\n clip-path: polygon(0% 0%, 0% 100%, 45% 100%, 45% 45%, 55% 45%, 55% 55%, 45% 55%, 45% 100%, 100% 100%, 100% 0%);\n transform: translate(-50%, -50%);\n}\n"
},
{
"answer_id": 74642475,
"author": "Vadim",
"author_id": 1580941,
"author_profile": "https://Stackoverflow.com/users/1580941",
"pm_score": 2,
"selected": false,
"text": "mousemove requestAnimationFrame() window.addEventListener('DOMContentLoaded', () => {\n const blurEl = document.querySelector('.blur');\n let curX, curY, isRenderScheduled = false;\n blurEl.addEventListener('mousemove', ({x,y}) => {\n curX = x;\n curY = y;\n if(!isRenderScheduled) {\n isRenderScheduled = true;\n requestAnimationFrame(() => {\n blurEl.setAttribute('style', `--x:${curX}px;--y:${curY}px`);\n isRenderScheduled = false;\n });\n }\n });\n}); .content {\n position: absolute;\n top: 0;\n left: 0;\n bottom: 0;\n right: 0;\n display: grid;\n place-content: center;\n}\n.blur {\n position: absolute;\n top: 0;\n left: 0;\n bottom: 0;\n right: 0;\n display: flex;\n flex-direction: row;\n align-items: stretch;\n justify-content: stretch;\n}\n.blur > div {\n display: flex;\n flex-direction: column;\n}\n.blur:before,\n.blur:after,\n.blur > div:before,\n.blur > div:after {\n content: '';\n backdrop-filter:blur(5px);\n flex-grow: 1;\n flex-shrink: 1;\n}\n.blur:before {\n min-width: var(--x, auto);\n max-width: var(--x, auto);\n}\n.blur > div:before {\n min-height: var(--y, auto);\n max-height: var(--y, auto);\n}\n.transparent {\n flex-grow: 0;\n flex-shrink: 0;\n width: 50px;\n height: 50px;\n border: 1px solid silver;\n} <div class=\"content\"> \n <h1>This is the content</h1>\n <div class=\"blur\" style=\"--x:auto;--y:auto;\">\n <div>\n <div class=\"transparent\"></div>\n </div>\n </div>\n</div> .blur :before :after"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14661648/"
] |
74,641,344
|
<p>I have a dataframe where the <strong>rows have been shifted horizontally</strong> by an unknown amount. <strong>Each and every row has shifted by a different amount</strong> as shown below:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Heading 1</th>
<th>Heading 2</th>
<th>Unnamed: 1</th>
<th>Unnamed: 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>NaN</td>
<td>34</td>
<td>24</td>
<td>NaN</td>
</tr>
<tr>
<td>5</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
</tr>
<tr>
<td>NaN</td>
<td>NaN</td>
<td>13</td>
<td>77</td>
</tr>
<tr>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
<td>18</td>
</tr>
</tbody>
</table>
</div>
<p>In the above dataframe, there are only <strong>2 original columns</strong> (<strong>Heading 1</strong> and <strong>Heading 2</strong>) but due to row shift (in rows <strong>1</strong> and <strong>3</strong>), <strong>extra columns</strong> (<strong>Unnamed: 1 and Unnamed: 2</strong>) have been created with the default name <strong>Unnamed: 1</strong> and <strong>Unnamed: 2</strong>.</p>
<p>Now <strong>for each row</strong>, I want to <strong>calculate</strong>:</p>
<p>1.) The <strong>spill over</strong>. Spill over is basically the amount of NaN values in extra columns(<strong>Unnamed</strong> columns). For example in <strong>row 1</strong> there is <strong>one non NaN</strong> value in extra columns (Unnamed: 1) and hence the <strong>spill over is 1</strong>. In <strong>row 2</strong> there are <strong>no non NaN</strong> values in extra columns so the <strong>spill over is 0</strong>. In <strong>row 3</strong> there are <strong>2 non NaN</strong> values in extra columns(Unnamed: 1 and Unnamed: 2) hence the <strong>spill over is 2</strong> and in <strong>row 4</strong> there are <strong>1 non NaN</strong> values in extra columns so the <strong>spill over is 1</strong>.</p>
<p>2.) The <strong>amount of NaN values in the original columns</strong>(<strong>Heading 1</strong> and <strong>Heading 2</strong>). For example in <strong>row 1</strong> amount of <strong>Nan values in original columns are 1</strong>, in <strong>row 2</strong> amount of <strong>NaN values in original columns is 0</strong>, in <strong>row 3</strong> amount of <strong>NaN values in original columns is 2</strong> and in <strong>row 4</strong> amount of <strong>NaN values in original columns is 2</strong>.</p>
<p>So basically for each row, I have to <strong>calculate the amount of Nan values in <strong>original</strong> columns(<strong>Heading 1</strong> and <strong>Heading 2</strong>) and the amount of non NaN values in <strong>extra</strong> columns(Unnamed: 1 and Unnamed: 2).</strong></p>
<p>I can get the amount of extra columns (Unnamed:1 and so on) present in a dataframe by:</p>
<pre><code>len(df.filter(regex=("Unnamed:.*")).columns.to_list())
</code></pre>
<p><strong>Thank you!</strong></p>
|
[
{
"answer_id": 74641438,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 0,
"selected": false,
"text": "isna cummin sum clip df.isna().cummin(axis=1).sum(axis=1).clip(upper=2)\n 0 1\n1 0\n2 2\n3 2\ndtype: int64\n df.isna()\n\n Heading 1 Heading 2 Unnamed: 1 Unnamed: 2\n0 True False False True\n1 False False True True\n2 True True False False\n3 True True True False\n\ndf.isna().cummin(axis=1)\n\n Heading 1 Heading 2 Unnamed: 1 Unnamed: 2\n0 True False False False\n1 False False False False\n2 True True False False\n3 True True True False\n\ndf.isna().cummin(axis=1).sum(axis=1)\n\n0 1\n1 0\n2 2\n3 3\ndtype: int64\n"
},
{
"answer_id": 74643978,
"author": "spectre",
"author_id": 15320579,
"author_profile": "https://Stackoverflow.com/users/15320579",
"pm_score": 2,
"selected": true,
"text": "#read the excel file\ndf = pd.read_excel('df.xlsx')\n\n#subset the df into original and extra df's\nextra = df.filter(regex=(\"Unnamed:.*\"))\noriginal = df.drop(extra, axis = 1)\n\n#ori contains a list of count of NaN values in original columns as asked \nori = original.isnull().sum(axis=1).tolist() #or to_dict() if you want a dict\next = len(extra.columns) - extra.isnull().sum(axis=1)\n#ext1 contains a list of count of non NaN values in the extra columns as asked\next1 = ext.tolist() # or to_dict() if you want a dict\n extra = df.filter(regex=(\"Unnamed:.*\"))\ny = extra.isna().cummin(axis=1).sum(axis=1).clip(upper=2).tolist()\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18567298/"
] |
74,641,350
|
<p>i've created an azure video indexer that is related to a media service account.
Add to it i've created a storage account to media service. I've uploaded the video in it but when i go on azure video indexer portal the video is not exist. How they share the storage (video indexer and media services)?</p>
<p>Thanks for collaborating</p>
<p>I don't find anything about that....</p>
|
[
{
"answer_id": 74641438,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 0,
"selected": false,
"text": "isna cummin sum clip df.isna().cummin(axis=1).sum(axis=1).clip(upper=2)\n 0 1\n1 0\n2 2\n3 2\ndtype: int64\n df.isna()\n\n Heading 1 Heading 2 Unnamed: 1 Unnamed: 2\n0 True False False True\n1 False False True True\n2 True True False False\n3 True True True False\n\ndf.isna().cummin(axis=1)\n\n Heading 1 Heading 2 Unnamed: 1 Unnamed: 2\n0 True False False False\n1 False False False False\n2 True True False False\n3 True True True False\n\ndf.isna().cummin(axis=1).sum(axis=1)\n\n0 1\n1 0\n2 2\n3 3\ndtype: int64\n"
},
{
"answer_id": 74643978,
"author": "spectre",
"author_id": 15320579,
"author_profile": "https://Stackoverflow.com/users/15320579",
"pm_score": 2,
"selected": true,
"text": "#read the excel file\ndf = pd.read_excel('df.xlsx')\n\n#subset the df into original and extra df's\nextra = df.filter(regex=(\"Unnamed:.*\"))\noriginal = df.drop(extra, axis = 1)\n\n#ori contains a list of count of NaN values in original columns as asked \nori = original.isnull().sum(axis=1).tolist() #or to_dict() if you want a dict\next = len(extra.columns) - extra.isnull().sum(axis=1)\n#ext1 contains a list of count of non NaN values in the extra columns as asked\next1 = ext.tolist() # or to_dict() if you want a dict\n extra = df.filter(regex=(\"Unnamed:.*\"))\ny = extra.isna().cummin(axis=1).sum(axis=1).clip(upper=2).tolist()\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13606315/"
] |
74,641,351
|
<p>I want to perform a column-wise operation in R on column pairs. <strong>The function I actually want to use is not the one shown here, because it would complicate this example.</strong></p>
<p>I have a dataframe:</p>
<pre><code>df <- data.frame(p1 = c(-5, -4, 2, 0, -2, 1, 3, 4, 2, 7)
,p2 = c(0, 1, 2, 0, -2, 1, 3, 3, 2, 0))
</code></pre>
<p>and a vector of the same length as the <code>df</code>:</p>
<pre><code>tocompare <- c(0, 0, 2, 0, 2, 4, 16, 12, 6, 9)
</code></pre>
<p>I want to run a function that compares each column of <code>df</code> to the <code>tocompare</code> object. The steps I need to take is:</p>
<ol>
<li>Make a two-element list. First element is a two-column dataframe <code>x</code>, in which the first column comes from the <code>df</code> and the second column is the <code>tocompare</code> object. Second element is a number. (this is needed for my actual function to work, I appreciate that it is not needed in this example). This number is constant for all iterations of this process (it's a number of rows in <code>df</code> / length of <code>tocompare</code>) in this example, it's <code>10</code>.</li>
</ol>
<pre><code>data1 <- list(x = cbind(df %>% select(1), tocompare), N = length(tocompare))
# select(1) is used rather than df[,1] ensures the column header is kept
</code></pre>
<ol start="2">
<li>Compare the two columns of the first element (called <code>x</code>) of the <code>data1</code> list. The function that I use in real life is not <code>cor</code>; this simplified example captures the problem. I wrote <code>my_function</code> in such a way that it needs the <code>data1</code> object created above.</li>
</ol>
<pre><code>my_function <- function(data1){
x <- data1[[1]]
cr <- cor(x[,1], x[,2])
header <- colnames(x)[1]
print(c(header, cr))
}
cr_df1 <- my_function(data1)
</code></pre>
<p>I can do the same for the second <code>df</code> column:</p>
<pre><code>data2 <- list(x = cbind(df %>% select(2), tocompare), N = length(tocompare))
cr_df2 <- my_function(data2)
</code></pre>
<p>And make a dataframe of final results:</p>
<pre><code>final_df <- rbind(cr_df1, cr_df2) %>%
`rownames<-`(NULL) %>%
`colnames<-`(c("p", "R")) %>%
as.data.frame()
</code></pre>
<p>the output will look like this:</p>
<pre><code>> final_df
p R
1 p1 0.7261224
2 p2 0.6233169
</code></pre>
<p>I would like to do this on a dataframe with thousands of columns. The bit I don't know is <em>how to split the single dataframe into multiple two-column dataframes and then run <code>my_function</code> on these many small dataframes to return a single output</em>. I think I would be able to do it with a <code>loop</code> and with transposing the <code>df</code>, but maybe there is a better way (I feel I should try to use <code>map</code> here)?</p>
|
[
{
"answer_id": 74641438,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 0,
"selected": false,
"text": "isna cummin sum clip df.isna().cummin(axis=1).sum(axis=1).clip(upper=2)\n 0 1\n1 0\n2 2\n3 2\ndtype: int64\n df.isna()\n\n Heading 1 Heading 2 Unnamed: 1 Unnamed: 2\n0 True False False True\n1 False False True True\n2 True True False False\n3 True True True False\n\ndf.isna().cummin(axis=1)\n\n Heading 1 Heading 2 Unnamed: 1 Unnamed: 2\n0 True False False False\n1 False False False False\n2 True True False False\n3 True True True False\n\ndf.isna().cummin(axis=1).sum(axis=1)\n\n0 1\n1 0\n2 2\n3 3\ndtype: int64\n"
},
{
"answer_id": 74643978,
"author": "spectre",
"author_id": 15320579,
"author_profile": "https://Stackoverflow.com/users/15320579",
"pm_score": 2,
"selected": true,
"text": "#read the excel file\ndf = pd.read_excel('df.xlsx')\n\n#subset the df into original and extra df's\nextra = df.filter(regex=(\"Unnamed:.*\"))\noriginal = df.drop(extra, axis = 1)\n\n#ori contains a list of count of NaN values in original columns as asked \nori = original.isnull().sum(axis=1).tolist() #or to_dict() if you want a dict\next = len(extra.columns) - extra.isnull().sum(axis=1)\n#ext1 contains a list of count of non NaN values in the extra columns as asked\next1 = ext.tolist() # or to_dict() if you want a dict\n extra = df.filter(regex=(\"Unnamed:.*\"))\ny = extra.isna().cummin(axis=1).sum(axis=1).clip(upper=2).tolist()\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9283607/"
] |
74,641,390
|
<p>I am wondering here by the parameter passing in the <strong>new</strong> Laravel Mail class. My IDE
(VSCode) also underlines the parameter and throws the following error: <code>syntax error, unexpected ':', expecting ')'</code></p>
<pre><code>public function envelope()
{
return new Envelope(
subject: 'Subject', // <-- the key subject
from: 'test@test.fr', // <-- the key from
);
}
</code></pre>
<p>Nevertheless, it works. It's probably a new PHP specification that I don't know
yet. What is it called and does it work? And how can I teach my IDE that it is
not an error?</p>
|
[
{
"answer_id": 74641438,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 0,
"selected": false,
"text": "isna cummin sum clip df.isna().cummin(axis=1).sum(axis=1).clip(upper=2)\n 0 1\n1 0\n2 2\n3 2\ndtype: int64\n df.isna()\n\n Heading 1 Heading 2 Unnamed: 1 Unnamed: 2\n0 True False False True\n1 False False True True\n2 True True False False\n3 True True True False\n\ndf.isna().cummin(axis=1)\n\n Heading 1 Heading 2 Unnamed: 1 Unnamed: 2\n0 True False False False\n1 False False False False\n2 True True False False\n3 True True True False\n\ndf.isna().cummin(axis=1).sum(axis=1)\n\n0 1\n1 0\n2 2\n3 3\ndtype: int64\n"
},
{
"answer_id": 74643978,
"author": "spectre",
"author_id": 15320579,
"author_profile": "https://Stackoverflow.com/users/15320579",
"pm_score": 2,
"selected": true,
"text": "#read the excel file\ndf = pd.read_excel('df.xlsx')\n\n#subset the df into original and extra df's\nextra = df.filter(regex=(\"Unnamed:.*\"))\noriginal = df.drop(extra, axis = 1)\n\n#ori contains a list of count of NaN values in original columns as asked \nori = original.isnull().sum(axis=1).tolist() #or to_dict() if you want a dict\next = len(extra.columns) - extra.isnull().sum(axis=1)\n#ext1 contains a list of count of non NaN values in the extra columns as asked\next1 = ext.tolist() # or to_dict() if you want a dict\n extra = df.filter(regex=(\"Unnamed:.*\"))\ny = extra.isna().cummin(axis=1).sum(axis=1).clip(upper=2).tolist()\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14807111/"
] |
74,641,450
|
<p>I have an AngularForm which binds the formControlName to an input field that is of type <code>number</code>.</p>
<p>I would like to accept numbers and dots only. Unfortunately the HTML attribute tag <code>number</code> also accepts dashes. This is something that I would like to prevent. Is there another attribute that could work within the HTML, or is there a suitable regEx expression that would only allow numbers and dots?</p>
<p><strong>HTML</strong></p>
<pre><code><input name="myNumber" step="any" type="number" formControlName="myNumber">
</code></pre>
<p><strong>Angular Form / TS</strong></p>
<pre><code>myForm = this.fb.group({
question_number: null,
});
</code></pre>
|
[
{
"answer_id": 74641438,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 0,
"selected": false,
"text": "isna cummin sum clip df.isna().cummin(axis=1).sum(axis=1).clip(upper=2)\n 0 1\n1 0\n2 2\n3 2\ndtype: int64\n df.isna()\n\n Heading 1 Heading 2 Unnamed: 1 Unnamed: 2\n0 True False False True\n1 False False True True\n2 True True False False\n3 True True True False\n\ndf.isna().cummin(axis=1)\n\n Heading 1 Heading 2 Unnamed: 1 Unnamed: 2\n0 True False False False\n1 False False False False\n2 True True False False\n3 True True True False\n\ndf.isna().cummin(axis=1).sum(axis=1)\n\n0 1\n1 0\n2 2\n3 3\ndtype: int64\n"
},
{
"answer_id": 74643978,
"author": "spectre",
"author_id": 15320579,
"author_profile": "https://Stackoverflow.com/users/15320579",
"pm_score": 2,
"selected": true,
"text": "#read the excel file\ndf = pd.read_excel('df.xlsx')\n\n#subset the df into original and extra df's\nextra = df.filter(regex=(\"Unnamed:.*\"))\noriginal = df.drop(extra, axis = 1)\n\n#ori contains a list of count of NaN values in original columns as asked \nori = original.isnull().sum(axis=1).tolist() #or to_dict() if you want a dict\next = len(extra.columns) - extra.isnull().sum(axis=1)\n#ext1 contains a list of count of non NaN values in the extra columns as asked\next1 = ext.tolist() # or to_dict() if you want a dict\n extra = df.filter(regex=(\"Unnamed:.*\"))\ny = extra.isna().cummin(axis=1).sum(axis=1).clip(upper=2).tolist()\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8836786/"
] |
74,641,457
|
<p>When I fetch data from my PostgreSQL database, it comes in the following format: <code>2022-11-30T21:00:00.000Z</code> and it's not a string; it's in the form of a date object.</p>
<p>The library that I'm using to work with dates is <code>dayjs</code>. So here is the issue.</p>
<p>When I call the format method, I get a bad date. like one day off.</p>
<p>dayjs('2022-11-30T21:00:00.000Z') and it gives me <code>2022-12-01T00:00:00+03:00</code>.So the real date that was stored was 30th November, but it gives me 1st December.</p>
<p>I saw this post <a href="https://stackoverflow.com/questions/58491212/dayjs-returns-wrong-date-with-format">dayjs returns wrong date with format</a> in Stack overflow but the accepted solution is wired because it assumes that I manually remove the <code>Z</code> at the end.</p>
<p>And even when i try to convert it in a <code>YYYY-MM-DD</code> by using <code>dayjs('2022-11-30T21:00:00.000Z').format('YYYY-MM-DD')</code> it's returning <code>2020-12-01</code>.</p>
<p>I really stuck.</p>
|
[
{
"answer_id": 74641438,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 0,
"selected": false,
"text": "isna cummin sum clip df.isna().cummin(axis=1).sum(axis=1).clip(upper=2)\n 0 1\n1 0\n2 2\n3 2\ndtype: int64\n df.isna()\n\n Heading 1 Heading 2 Unnamed: 1 Unnamed: 2\n0 True False False True\n1 False False True True\n2 True True False False\n3 True True True False\n\ndf.isna().cummin(axis=1)\n\n Heading 1 Heading 2 Unnamed: 1 Unnamed: 2\n0 True False False False\n1 False False False False\n2 True True False False\n3 True True True False\n\ndf.isna().cummin(axis=1).sum(axis=1)\n\n0 1\n1 0\n2 2\n3 3\ndtype: int64\n"
},
{
"answer_id": 74643978,
"author": "spectre",
"author_id": 15320579,
"author_profile": "https://Stackoverflow.com/users/15320579",
"pm_score": 2,
"selected": true,
"text": "#read the excel file\ndf = pd.read_excel('df.xlsx')\n\n#subset the df into original and extra df's\nextra = df.filter(regex=(\"Unnamed:.*\"))\noriginal = df.drop(extra, axis = 1)\n\n#ori contains a list of count of NaN values in original columns as asked \nori = original.isnull().sum(axis=1).tolist() #or to_dict() if you want a dict\next = len(extra.columns) - extra.isnull().sum(axis=1)\n#ext1 contains a list of count of non NaN values in the extra columns as asked\next1 = ext.tolist() # or to_dict() if you want a dict\n extra = df.filter(regex=(\"Unnamed:.*\"))\ny = extra.isna().cummin(axis=1).sum(axis=1).clip(upper=2).tolist()\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6137017/"
] |
74,641,461
|
<p>i'm trying to merge two array of object based on key. two array of object like this,</p>
<pre><code> let array1 = [
{
name: "Deepak",
age: 20
},
{
name: "John",
age: 30
}
]
</code></pre>
<pre><code> let array2 = [
{
name: "Deepak",
favGame: "Cricket"
},
{
name: "John",
favGame: "Football"
},
{
name: "Kailash",
favGame: "Basketball"
}
]
</code></pre>
<p>I found difficulties to merge as expected format. I expecting format like this</p>
<pre><code> let finalArray = [
{
name: "Deepak",
age: 20,
favGame: "Cricket"
},
{
name: "John",
age: 30,
favGame: "Football"
},
{
name: "Kailash",
favGame: "Basketball"
}
]
</code></pre>
|
[
{
"answer_id": 74641500,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 2,
"selected": true,
"text": "Array.map() Array.find() let array1 = [\n {\n name: \"Deepak\",\n age: 20\n },\n {\n name: \"John\",\n age: 30\n }\n ]\n\nlet array2 = [\n {\n name: \"Deepak\",\n favGame: \"Cricket\"\n },\n {\n name: \"John\",\n favGame: \"Football\"\n },\n {\n name: \"Kailash\",\n favGame: \"Basketball\"\n }\n ]\n \nlet result = array2.map(a => {\n let obj = array1.find(i => i.name === a.name)\n if(obj){\n a.age = obj.age\n }\n return a\n})\nconsole.log(result)"
},
{
"answer_id": 74641800,
"author": "Andrew Parks",
"author_id": 5898421,
"author_profile": "https://Stackoverflow.com/users/5898421",
"pm_score": 2,
"selected": false,
"text": "let a1 = [ { name: 'Deepak', age: 20 }, { name: 'John', age: 30 } ]\nlet a2 = [\n { name: 'Deepak', favGame: 'Cricket' },\n { name: 'John', favGame: 'Football' },\n { name: 'Kailash', favGame: 'Basketball' }\n]\n\nconsole.log(Object.values([...a1, ...a2]\n .reduce((a,{name, ...p})=>(a[name]={...a[name]??{},name,...p},a), {})))"
},
{
"answer_id": 74641843,
"author": "Amirhossein",
"author_id": 11342834,
"author_profile": "https://Stackoverflow.com/users/11342834",
"pm_score": 0,
"selected": false,
"text": "const array1 = [\n {\n name: \"Deepak\",\n age: 20\n },\n {\n name: \"John\",\n age: 30\n }\n];\n\nconst array2 = [\n {\n name: \"Deepak\",\n favGame: \"Cricket\"\n },\n {\n name: \"John\",\n favGame: \"Football\"\n },\n {\n name: \"Kailash\",\n favGame: \"Basketball\"\n }\n];\n\nconst mergedArray = [...array1, ...array2];\nconst newArray = [];\nmergedArray.forEach((item) => {\n const key = item.name;\n let index = -1;\n newArray.forEach((newArrayItem, _index) => {\n if(newArrayItem.name === key)\n index = _index;\n });\n if(index === -1){\n newArray.push({});\n index = newArray.length - 1;\n }\n newArray[index][\"name\"] = item.name;\n if(item.age) {\n newArray[index][\"age\"] = item.age;\n }\n if(item.favGame) {\n newArray[index][\"favGame\"] = item.favGame;\n }\n});\nconsole.log(newArray);"
},
{
"answer_id": 74642012,
"author": "Terry Lennox",
"author_id": 7237224,
"author_profile": "https://Stackoverflow.com/users/7237224",
"pm_score": 0,
"selected": false,
"text": "Array.reduce() name name Object.values() let array1 = [ { name: \"Deepak\", age: 20 }, { name: \"John\", age: 30 } ]\nlet array2 = [ { name: \"Deepak\", favGame: \"Cricket\" }, { name: \"John\", favGame: \"Football\" }, { name: \"Kailash\", favGame: \"Basketball\" } ]\n \nconst result = Object.values([...array1, ...array2].reduce((acc, { name, ...obj }) => { \n acc[name] = { ...(acc[name] || {}), name, ...obj };\n return acc;\n}, {}));\n\nconsole.log('Result:', result) .as-console-wrapper { max-height: 100% !important; }"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20647233/"
] |
74,641,464
|
<p>Please help me to write a Select :)</p>
<p>I need to return data from two tables: values from table X, but only these which also have value from table Y.
For example in table X values are:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Column A</th>
<th>Column B</th>
<th>----</th>
</tr>
</thead>
<tbody>
<tr>
<td>Great</td>
<td>Orange</td>
<td><- has attached photo which is located in table Y</td>
</tr>
<tr>
<td>Poor</td>
<td>Orange</td>
<td></td>
</tr>
<tr>
<td>Poor</td>
<td>Apple</td>
<td><- has attached photo which is located in table Y</td>
</tr>
<tr>
<td>Awesome</td>
<td>Orange</td>
<td><- has attached photo which is located in table Y</td>
</tr>
</tbody>
</table>
</div>
<p>I need to return values column A from table X, where value in column B is 'Orange' and only those which has attached photo in table Y.</p>
<p>Table X is in connection with table Y: <strong>referencing constrains</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Name</th>
<th>Table</th>
<th>Table owner</th>
<th>Unique</th>
<th>Columns</th>
</tr>
</thead>
<tbody>
<tr>
<td>Table_X</td>
<td>Table_Y</td>
<td>DBA</td>
<td>No</td>
<td>Table_X_id</td>
</tr>
</tbody>
</table>
</div>
<p>I tried this select, but it does not work properly, because it returns value 1 in every line where value is orange:</p>
<p>SELECT * FROM Table_X WHERE Table_X.Column_B='Orange' AND (EXISTS (select 1 from Table_Y att, Table_X orng where orng.Table_X_id=att.Table_X_id and att.Table_X_id is not null))</p>
<p>I hope it's clear.. help me :)</p>
|
[
{
"answer_id": 74641500,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 2,
"selected": true,
"text": "Array.map() Array.find() let array1 = [\n {\n name: \"Deepak\",\n age: 20\n },\n {\n name: \"John\",\n age: 30\n }\n ]\n\nlet array2 = [\n {\n name: \"Deepak\",\n favGame: \"Cricket\"\n },\n {\n name: \"John\",\n favGame: \"Football\"\n },\n {\n name: \"Kailash\",\n favGame: \"Basketball\"\n }\n ]\n \nlet result = array2.map(a => {\n let obj = array1.find(i => i.name === a.name)\n if(obj){\n a.age = obj.age\n }\n return a\n})\nconsole.log(result)"
},
{
"answer_id": 74641800,
"author": "Andrew Parks",
"author_id": 5898421,
"author_profile": "https://Stackoverflow.com/users/5898421",
"pm_score": 2,
"selected": false,
"text": "let a1 = [ { name: 'Deepak', age: 20 }, { name: 'John', age: 30 } ]\nlet a2 = [\n { name: 'Deepak', favGame: 'Cricket' },\n { name: 'John', favGame: 'Football' },\n { name: 'Kailash', favGame: 'Basketball' }\n]\n\nconsole.log(Object.values([...a1, ...a2]\n .reduce((a,{name, ...p})=>(a[name]={...a[name]??{},name,...p},a), {})))"
},
{
"answer_id": 74641843,
"author": "Amirhossein",
"author_id": 11342834,
"author_profile": "https://Stackoverflow.com/users/11342834",
"pm_score": 0,
"selected": false,
"text": "const array1 = [\n {\n name: \"Deepak\",\n age: 20\n },\n {\n name: \"John\",\n age: 30\n }\n];\n\nconst array2 = [\n {\n name: \"Deepak\",\n favGame: \"Cricket\"\n },\n {\n name: \"John\",\n favGame: \"Football\"\n },\n {\n name: \"Kailash\",\n favGame: \"Basketball\"\n }\n];\n\nconst mergedArray = [...array1, ...array2];\nconst newArray = [];\nmergedArray.forEach((item) => {\n const key = item.name;\n let index = -1;\n newArray.forEach((newArrayItem, _index) => {\n if(newArrayItem.name === key)\n index = _index;\n });\n if(index === -1){\n newArray.push({});\n index = newArray.length - 1;\n }\n newArray[index][\"name\"] = item.name;\n if(item.age) {\n newArray[index][\"age\"] = item.age;\n }\n if(item.favGame) {\n newArray[index][\"favGame\"] = item.favGame;\n }\n});\nconsole.log(newArray);"
},
{
"answer_id": 74642012,
"author": "Terry Lennox",
"author_id": 7237224,
"author_profile": "https://Stackoverflow.com/users/7237224",
"pm_score": 0,
"selected": false,
"text": "Array.reduce() name name Object.values() let array1 = [ { name: \"Deepak\", age: 20 }, { name: \"John\", age: 30 } ]\nlet array2 = [ { name: \"Deepak\", favGame: \"Cricket\" }, { name: \"John\", favGame: \"Football\" }, { name: \"Kailash\", favGame: \"Basketball\" } ]\n \nconst result = Object.values([...array1, ...array2].reduce((acc, { name, ...obj }) => { \n acc[name] = { ...(acc[name] || {}), name, ...obj };\n return acc;\n}, {}));\n\nconsole.log('Result:', result) .as-console-wrapper { max-height: 100% !important; }"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20655652/"
] |
74,641,473
|
<p>I have this .ejs page which contains a table. In that table, there are 4 columns which contain numbers. I want to display an average of each of these columns on the same page.</p>
<p>I have managed to get the averages, but it is very inefficient and is taking up a lot of space in the .ejs file.</p>
<p>This is what the page looks like.</p>
<p><img src="https://i.stack.imgur.com/XpCKo.jpg" alt="1" /></p>
<p>Here is my code for the .ejs file (including my poorly coded average "calculator"):</p>
<blockquote>
</blockquote>
<pre><code><!DOCTYPE html>
<html lang="en">
<html>
<head>
<title>MTU Phone Usage Monitor</title>
<link rel="stylesheet" href="/stylesheets/styleTable.css"></link>
</head>
<body>
<div class="banner">
<div class="navbar">
<img src="\images\logo.png" class="logo">
<ul>
<li><a href="/">Home</a></li>
<li><a href="/phone/create">New Entry</a></li>
<li><a href="/table">View Data</a></li>
<li><a href="/help">Help</a></li>
</ul>
</div>
<form action="/phone/find" method="post"></form>
<div class="table-wrapper">
<table class="tableData" id="table">
<caption>
<%= title %>
</caption>
<thead>
<tr>
<th>Name</th>
<th>Education Usage</th>
<th>Shopping Usage</th>
<th>Searching/Browsing usage</th>
<th>Social Media usage</th>
<th>Date and Time</th>
<th></th>
</tr>
</thead>
<tbody>
<% for(var i=0; i < phonelist.length; i++) { %>
<tr>
<td>
<%= phonelist[i].name %>
</td>
<td>
<%= phonelist[i].timeEducation %>
</td>
<td>
<%= phonelist[i].timeShopping %>
</td>
<td>
<%= phonelist[i].timeBrowsing %>
</td>
<td>
<%= phonelist[i].timeSocial %>
</td>
<td>
<%= phonelist[i].createdAt %>
</td>
<td>
<div class="secret">
<form action="/phone/delete" method="post"> <input type="String" value="<%= phonelist[i].id%>" name="id" readonly><button type="Submit">Delete</button></form>
<form action="/phone/update" method="post"> <input type="String" value="<%=phonelist[i].id%>" name="id" readonly><button type="Submit">Update</button></form>
</div>
</td>
</tr>
<% } %>
</div>
<span id="education"></span><br>
<span id="shopping"></span><br>
<span id="browsing"></span><br>
<span id="social"></span>
<script>
var table = document.getElementById("table"),
avgVal, sumVal = 0,
rowCount = table.rows.length - 1; // minus the header
//calculate average education usage
for (var i = 1; i < table.rows.length; i++) {
sumVal = sumVal + parseInt(table.rows[i].cells[1].innerHTML);
}
document.getElementById("education").innerHTML = "Average Education = " + parseFloat(sumVal / rowCount);
avgVal, sumVal = 0;
//calculate average shopping usage
for (var i = 1; i < table.rows.length; i++) {
sumVal = sumVal + parseInt(table.rows[i].cells[2].innerHTML);
}
document.getElementById("shopping").innerHTML = "Average Shopping = " + parseFloat(sumVal / rowCount);
avgVal, sumVal = 0;
//calculate average browsing usage
for (var i = 1; i < table.rows.length; i++) {
sumVal = sumVal + parseInt(table.rows[i].cells[3].innerHTML);
}
document.getElementById("browsing").innerHTML = "Average Shopping = " + parseFloat(sumVal / rowCount);
avgVal, sumVal = 0;
//calculate average browsing usage
for (var i = 1; i < table.rows.length; i++) {
sumVal = sumVal + parseInt(table.rows[i].cells[3].innerHTML);
}
document.getElementById("browsing").innerHTML = "Average Shopping = " + parseFloat(sumVal / rowCount);
avgVal, sumVal = 0;
//calculate average social usage
for (var i = 1; i < table.rows.length; i++) {
sumVal = sumVal + parseInt(table.rows[i].cells[4].innerHTML);
}
document.getElementById("social").innerHTML = "Average Shopping = " + parseFloat(sumVal / rowCount);
</script>
</body>
</html>
</code></pre>
<p>Here is the code for where the data comes from:</p>
<pre><code>
phoneRouter.route('/find')
.post((req, res, next) => {
phones.find({ name: req.body.name })
.then((phonetaken) => {
phones.find(req.body)
.then((phonefound) => {
res.render('oneFound.ejs', { 'phonelist': phonefound, title: 'All data recieved from user: ' + req.body.name }); //can use datadisplay
}, (err) => next(err));
})
})
</code></pre>
<p>I believe it is the <code>aggregate</code> method that would be used to calculate the averages here. How do I implement it?
How do I shorten that code, make it more presentable and more readable.
I think I could put a for loop inside of a for loop, but I'm not sure how to implement it and get all 4 averages displaying.</p>
<p>With this, I also want to generate a bar graph of the averages at the bottom of the page.</p>
<p><strong>How would I shorten my code/make it more efficient?
How would I generate a bar graph of the averages?</strong></p>
|
[
{
"answer_id": 74641500,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 2,
"selected": true,
"text": "Array.map() Array.find() let array1 = [\n {\n name: \"Deepak\",\n age: 20\n },\n {\n name: \"John\",\n age: 30\n }\n ]\n\nlet array2 = [\n {\n name: \"Deepak\",\n favGame: \"Cricket\"\n },\n {\n name: \"John\",\n favGame: \"Football\"\n },\n {\n name: \"Kailash\",\n favGame: \"Basketball\"\n }\n ]\n \nlet result = array2.map(a => {\n let obj = array1.find(i => i.name === a.name)\n if(obj){\n a.age = obj.age\n }\n return a\n})\nconsole.log(result)"
},
{
"answer_id": 74641800,
"author": "Andrew Parks",
"author_id": 5898421,
"author_profile": "https://Stackoverflow.com/users/5898421",
"pm_score": 2,
"selected": false,
"text": "let a1 = [ { name: 'Deepak', age: 20 }, { name: 'John', age: 30 } ]\nlet a2 = [\n { name: 'Deepak', favGame: 'Cricket' },\n { name: 'John', favGame: 'Football' },\n { name: 'Kailash', favGame: 'Basketball' }\n]\n\nconsole.log(Object.values([...a1, ...a2]\n .reduce((a,{name, ...p})=>(a[name]={...a[name]??{},name,...p},a), {})))"
},
{
"answer_id": 74641843,
"author": "Amirhossein",
"author_id": 11342834,
"author_profile": "https://Stackoverflow.com/users/11342834",
"pm_score": 0,
"selected": false,
"text": "const array1 = [\n {\n name: \"Deepak\",\n age: 20\n },\n {\n name: \"John\",\n age: 30\n }\n];\n\nconst array2 = [\n {\n name: \"Deepak\",\n favGame: \"Cricket\"\n },\n {\n name: \"John\",\n favGame: \"Football\"\n },\n {\n name: \"Kailash\",\n favGame: \"Basketball\"\n }\n];\n\nconst mergedArray = [...array1, ...array2];\nconst newArray = [];\nmergedArray.forEach((item) => {\n const key = item.name;\n let index = -1;\n newArray.forEach((newArrayItem, _index) => {\n if(newArrayItem.name === key)\n index = _index;\n });\n if(index === -1){\n newArray.push({});\n index = newArray.length - 1;\n }\n newArray[index][\"name\"] = item.name;\n if(item.age) {\n newArray[index][\"age\"] = item.age;\n }\n if(item.favGame) {\n newArray[index][\"favGame\"] = item.favGame;\n }\n});\nconsole.log(newArray);"
},
{
"answer_id": 74642012,
"author": "Terry Lennox",
"author_id": 7237224,
"author_profile": "https://Stackoverflow.com/users/7237224",
"pm_score": 0,
"selected": false,
"text": "Array.reduce() name name Object.values() let array1 = [ { name: \"Deepak\", age: 20 }, { name: \"John\", age: 30 } ]\nlet array2 = [ { name: \"Deepak\", favGame: \"Cricket\" }, { name: \"John\", favGame: \"Football\" }, { name: \"Kailash\", favGame: \"Basketball\" } ]\n \nconst result = Object.values([...array1, ...array2].reduce((acc, { name, ...obj }) => { \n acc[name] = { ...(acc[name] || {}), name, ...obj };\n return acc;\n}, {}));\n\nconsole.log('Result:', result) .as-console-wrapper { max-height: 100% !important; }"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20572636/"
] |
74,641,498
|
<p>I want to remove entire rows if all columns except the one is empty. So, imagine that my DataFrame is</p>
<pre><code>df = pd.DataFrame({"col1": ["s1", "s2", "s3", "s4", "s5", "s6"],
"col2": [41, np.nan, np.nan, np.nan, np.nan, 61],
"col3": [24, 51, np.nan, np.nan, np.nan, 84],
"col4": [53, 64, 81, np.nan, np.nan, np.nan],
"col5": [43, 83, 47, 12, np.nan, 19]})
</code></pre>
<p>which looks like this</p>
<pre><code> col1 col2 col3 col4 col5
0 s1 41 24 53 43
1 s2 NaN 51 64 83
2 s3 NaN NaN 81 47
3 s4 NaN NaN NaN 12
4 s5 NaN NaN NaN NaN
5 s6 61 84 NaN 19
</code></pre>
<p>In this example, the desired result is</p>
<pre><code> col1 col2 col3 col4 col5
0 s1 41 24 53 43
1 s2 NaN 51 64 83
2 s3 NaN NaN 81 47
3 s4 NaN NaN NaN 12
4 s6 61 84 NaN 19
</code></pre>
<p>which means that I want to remove the last row. I initially tried with <code>df.dropna(how="all")</code> but it does not work since the last row is not entirely empty (<code>s5</code> in the <code>col1</code>).</p>
<p>How can I solve this?</p>
|
[
{
"answer_id": 74641535,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": true,
"text": "thresh N = 1\ndf.dropna(thresh=N+1)\n N N = 1\nout = df[df.isna().sum(axis=1).ne(df.shape[1]-N)]\n col1 col2 col3 col4 col5\n0 s1 41.0 24.0 53.0 43.0\n1 s2 NaN 51.0 64.0 83.0\n2 s3 NaN NaN 81.0 47.0\n3 s4 NaN NaN NaN 12.0\n"
},
{
"answer_id": 74641537,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 1,
"selected": false,
"text": "df[df.iloc[:, 1:].notnull().any(axis=1)]\n"
},
{
"answer_id": 74641606,
"author": "Triceratops",
"author_id": 13440165,
"author_profile": "https://Stackoverflow.com/users/13440165",
"pm_score": 0,
"selected": false,
"text": "import numpy as np\nimport pandas as pd \n\ndf = pd.DataFrame({\"x1\": [np.nan, np.nan], \"x2\": [1, np.nan]})\nprint(df.head())\n\nfor idx, row in df.iterrows():\n if np.isnan(row).all():\n df = df.drop(idx)\n\nprint(df.head())\n\n import numpy as np\nimport pandas as pd \n\ndf = pd.DataFrame({\"name\": [\"keep\", \"remove\"], \"x1\": [np.nan, np.nan], \"x2\": [1, np.nan]})\nprint(\"ORG\")\nprint(df.head())\n\nfor idx, row in df.iterrows():\n if np.isnan(row[1:].astype(float)).all():\n df = df.drop(idx)\n\nprint(\"OUT\")\nprint(df.head())\n"
},
{
"answer_id": 74641613,
"author": "Muhammad Rizwan",
"author_id": 11867299,
"author_profile": "https://Stackoverflow.com/users/11867299",
"pm_score": 0,
"selected": false,
"text": "df = df.dropna(axis=0, thresh=2)\n"
},
{
"answer_id": 74641644,
"author": "Dhruvin Vadgama",
"author_id": 20499874,
"author_profile": "https://Stackoverflow.com/users/20499874",
"pm_score": 0,
"selected": false,
"text": "NaN np.isnan()"
},
{
"answer_id": 74641659,
"author": "DiMithras",
"author_id": 8489602,
"author_profile": "https://Stackoverflow.com/users/8489602",
"pm_score": 0,
"selected": false,
"text": ".dropna() col1 df = df.set_index(\"col1\")\n df.dropna(how='all') df['col1'] = df.index df.reset_index(drop=True) col1 col5 cols = df.columns.tolist()\ncols = cols[-1:] + cols[:-1]\ndf[cols]\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20655582/"
] |
74,641,510
|
<p>Maybe someone has already asked, but I didn't find the right answer. I need group arrays by <code>mpn</code> and <code>product_id</code> key values and count it's quantities.
my array:</p>
<pre><code> [0] => Array
(
[product] => Product HTC
[mpn] =>
[quantity] => 3
[product_id] => 28
)
[1] => Array
(
[product] => Product HTC
[mpn] => ggg
[quantity] => 5
[product_id] => 28
)
[2] => Array
(
[product] => Product HTC
[mpn] => ggg
[quantity] => 1
[product_id] => 28
)
[3] => Array
(
[product] => Product HTC
[mpn] => ggg
[quantity] => 1
[product_id] => 28
)
[4] => Array
(
[product] => Product HTC
[mpn] => fff
[quantity] => 1
[product_id] => 28
)
</code></pre>
<p>the desired result:</p>
<pre><code>[0] => Array
(
[product] => Product HTC
[mpn] =>
[quantity] => 3
[product_id] => 28
)
[1] => Array
(
[product] => Product HTC
[mpn] => ggg
[quantity] => 7
[product_id] => 28
)
[2] => Array
(
[product] => Product HTC
[mpn] => fff
[quantity] => 1
[product_id] => 28
)
</code></pre>
<p>I have tried this suggestion <a href="https://stackoverflow.com/questions/14113256/group-array-values-based-on-key-in-php">Group array values based on key in php?</a> but no success.</p>
|
[
{
"answer_id": 74641838,
"author": "Juan",
"author_id": 6510866,
"author_profile": "https://Stackoverflow.com/users/6510866",
"pm_score": 3,
"selected": true,
"text": "// For Each Element\nforeach ($myList as $myKey => $myValue)\n{\n // Define New Key\n $newKey = $myValue[\"mpn\"];\n\n // You can Define New Key with Concatenation of Multiple Element\n // Ex : $newKey = $myValue[\"mpn\"].\"_\".$myValue[\"product_id\"];\n\n // If Never Memorised OR Already Memorised\n if(!array_key_exists($newKey,$newList)) $newList[\"$newKey\"] = $myValue;\n else $newList[\"$newKey\"][\"quantity\"] = bcadd($newList[\"$newKey\"][\"quantity\"],$myValue[\"quantity\"],0);\n}\n// End - For Each Element\n\n// Display Result\necho \"<pre>\"; print_r($newList); echo \"</pre>\";\n"
},
{
"answer_id": 74641851,
"author": "Moudi",
"author_id": 16402009,
"author_profile": "https://Stackoverflow.com/users/16402009",
"pm_score": 1,
"selected": false,
"text": "<?php\nfunction group_by_mpn($array){\n $mpn = array();\n $result = array();\n foreach($array as $key => $value){\n if(!in_array($value['mpn'], $mpn)){\n $mpn[] = $value['mpn'];\n $result[] = $value;\n }else{\n $index = array_search($value['mpn'], $mpn);\n $result[$index]['quantity'] = $result[$index]['quantity'] + $value['quantity'];\n }\n }\n return $result;\n}\n$array = array(\n array('product' => 'Product HTC', 'mpn' => '', 'quantity' => 3, 'product_id' => 28),\n array('product' => 'Product HTC', 'mpn' => 'ggg', 'quantity' => 5, 'product_id' => 28),\n array('product' => 'Product HTC', 'mpn' => 'ggg', 'quantity' => 1, 'product_id' => 28),\n array('product' => 'Product HTC', 'mpn' => 'ggg', 'quantity' => 1, 'product_id' => 28),\n array('product' => 'Product HTC', 'mpn' => 'fff', 'quantity' => 1, 'product_id' => 28),\n);\n\n$result = group_by_mpn($array);\necho json_encode($result);\n\n?>\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2675139/"
] |
74,641,521
|
<p>How to split a single variable into multiple arguments?</p>
<p>In fish shell, one can use</p>
<pre><code>set my_var (echo 'line1
line2
line3' | string split '\n')
./my_command $my_var
</code></pre>
<p>this is equivalent to</p>
<pre><code>./my_command line1 line2 line3
</code></pre>
<p>so a single variable acting as multiple parameters, how to do that in bash shell?</p>
|
[
{
"answer_id": 74641838,
"author": "Juan",
"author_id": 6510866,
"author_profile": "https://Stackoverflow.com/users/6510866",
"pm_score": 3,
"selected": true,
"text": "// For Each Element\nforeach ($myList as $myKey => $myValue)\n{\n // Define New Key\n $newKey = $myValue[\"mpn\"];\n\n // You can Define New Key with Concatenation of Multiple Element\n // Ex : $newKey = $myValue[\"mpn\"].\"_\".$myValue[\"product_id\"];\n\n // If Never Memorised OR Already Memorised\n if(!array_key_exists($newKey,$newList)) $newList[\"$newKey\"] = $myValue;\n else $newList[\"$newKey\"][\"quantity\"] = bcadd($newList[\"$newKey\"][\"quantity\"],$myValue[\"quantity\"],0);\n}\n// End - For Each Element\n\n// Display Result\necho \"<pre>\"; print_r($newList); echo \"</pre>\";\n"
},
{
"answer_id": 74641851,
"author": "Moudi",
"author_id": 16402009,
"author_profile": "https://Stackoverflow.com/users/16402009",
"pm_score": 1,
"selected": false,
"text": "<?php\nfunction group_by_mpn($array){\n $mpn = array();\n $result = array();\n foreach($array as $key => $value){\n if(!in_array($value['mpn'], $mpn)){\n $mpn[] = $value['mpn'];\n $result[] = $value;\n }else{\n $index = array_search($value['mpn'], $mpn);\n $result[$index]['quantity'] = $result[$index]['quantity'] + $value['quantity'];\n }\n }\n return $result;\n}\n$array = array(\n array('product' => 'Product HTC', 'mpn' => '', 'quantity' => 3, 'product_id' => 28),\n array('product' => 'Product HTC', 'mpn' => 'ggg', 'quantity' => 5, 'product_id' => 28),\n array('product' => 'Product HTC', 'mpn' => 'ggg', 'quantity' => 1, 'product_id' => 28),\n array('product' => 'Product HTC', 'mpn' => 'ggg', 'quantity' => 1, 'product_id' => 28),\n array('product' => 'Product HTC', 'mpn' => 'fff', 'quantity' => 1, 'product_id' => 28),\n);\n\n$result = group_by_mpn($array);\necho json_encode($result);\n\n?>\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10347663/"
] |
74,641,523
|
<p>I want to do a margin style for <code>mat-slide-toggle-bar</code> which is in a specific parent element <code>mat-slide-toggle</code> with class name <code>parent-element</code>.</p>
<p>Here my Html:</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><mat-slide-toggle _ngcontent-ng-cli-universal-c397=""
class="parent-element mat-slide-toggle parent-element mat-accent mat-checked mat-disabled ng-untouched ng-pristine"
ng-reflect-form="[object Object]" id="mat-slide-toggle-1"><label class="mat-slide-toggle-label"
for="mat-slide-toggle-1-input">
<span class="mat-slide-toggle-bar">
<input type="checkbox" role="switch" class="mat-slide-toggle-input cdk-visually-hidden"
id="mat-slide-toggle-1-input" tabindex="-1" disabled="" aria-checked="true">
<span class="mat-slide-toggle-thumb-container">
<span class="mat-slide-toggle-thumb"></span>
<span mat-ripple="" class="mat-ripple mat-slide-toggle-ripple mat-focus-indicator"
ng-reflect-trigger="[object HTMLLabelElement]" ng-reflect-disabled="true" ng-reflect-centered="true"
ng-reflect-radius="20" ng-reflect-animation="[object Object]">
<span class="mat-ripple-element mat-slide-toggle-persistent-ripple"></span>
</span>
</span>
</span>
<span class="mat-slide-toggle-content"><span style="display: none;">&nbsp;</span> text</span></label>
</mat-slide-toggle></code></pre>
</div>
</div>
</p>
<p>What I did in style file but dosn't work :</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>.parent-element .mat-slide-toggle-bar {
margin-left: 80px;
}}}</code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74641838,
"author": "Juan",
"author_id": 6510866,
"author_profile": "https://Stackoverflow.com/users/6510866",
"pm_score": 3,
"selected": true,
"text": "// For Each Element\nforeach ($myList as $myKey => $myValue)\n{\n // Define New Key\n $newKey = $myValue[\"mpn\"];\n\n // You can Define New Key with Concatenation of Multiple Element\n // Ex : $newKey = $myValue[\"mpn\"].\"_\".$myValue[\"product_id\"];\n\n // If Never Memorised OR Already Memorised\n if(!array_key_exists($newKey,$newList)) $newList[\"$newKey\"] = $myValue;\n else $newList[\"$newKey\"][\"quantity\"] = bcadd($newList[\"$newKey\"][\"quantity\"],$myValue[\"quantity\"],0);\n}\n// End - For Each Element\n\n// Display Result\necho \"<pre>\"; print_r($newList); echo \"</pre>\";\n"
},
{
"answer_id": 74641851,
"author": "Moudi",
"author_id": 16402009,
"author_profile": "https://Stackoverflow.com/users/16402009",
"pm_score": 1,
"selected": false,
"text": "<?php\nfunction group_by_mpn($array){\n $mpn = array();\n $result = array();\n foreach($array as $key => $value){\n if(!in_array($value['mpn'], $mpn)){\n $mpn[] = $value['mpn'];\n $result[] = $value;\n }else{\n $index = array_search($value['mpn'], $mpn);\n $result[$index]['quantity'] = $result[$index]['quantity'] + $value['quantity'];\n }\n }\n return $result;\n}\n$array = array(\n array('product' => 'Product HTC', 'mpn' => '', 'quantity' => 3, 'product_id' => 28),\n array('product' => 'Product HTC', 'mpn' => 'ggg', 'quantity' => 5, 'product_id' => 28),\n array('product' => 'Product HTC', 'mpn' => 'ggg', 'quantity' => 1, 'product_id' => 28),\n array('product' => 'Product HTC', 'mpn' => 'ggg', 'quantity' => 1, 'product_id' => 28),\n array('product' => 'Product HTC', 'mpn' => 'fff', 'quantity' => 1, 'product_id' => 28),\n);\n\n$result = group_by_mpn($array);\necho json_encode($result);\n\n?>\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10238495/"
] |
74,641,528
|
<p>I would like to replace the captured group from my regex with <code>XXX</code> (captured group), but it is only replacing it with XXX and deleting the word captured by the regex.</p>
<pre class="lang-r prettyprint-override"><code>search <- "[a-z]{5,}"
gsub(search, "xxx\\1", texts$text)
</code></pre>
<p>If the word: "wonderful" is matched by the regex, I would have wanted to replace it with "XXXwonderful", but I only got <code>XXX</code></p>
|
[
{
"answer_id": 74641630,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 1,
"selected": false,
"text": "text <- \"wonderful\"\n\nsearch <- \"\\\\b([a-z]{5,})\\\\b\"\ngsub(search, \"XXX\\\\1\", text, perl=TRUE)\n# => [1] \"XXXwonderful\"\n search <- \"\\\\b(\\\\p{L}{5,})\\\\b\"\ngsub(search, \"XXX\\\\1\", text, perl=TRUE)\n# => [1] \"XXXwonderful\"\n \\b ([a-z]{5,}) \\p{L}{5,} \\p{Ll}{5,} \\b"
},
{
"answer_id": 74642523,
"author": "ludovicpeyter",
"author_id": 18277469,
"author_profile": "https://Stackoverflow.com/users/18277469",
"pm_score": 1,
"selected": true,
"text": "search <- \"([a-z]{5,})\"\ngsub(search, \"XXX\\\\1\", text)\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20647358/"
] |
74,641,579
|
<p>I am not the Powershell pro so I need some help.</p>
<p>What I have now is for example:</p>
<p><strong>somelongname_08-01-01_someotherlongname.pdf</strong></p>
<p>and I want a rename to</p>
<p><strong>somelongname_2008-01-01_someotherlongname.pdf</strong></p>
<p>In short changing two digit year format to four digit year format within the name of multiple files.</p>
<p>At the moment I use the following script to rename all files in a specific folder:</p>
<p><code>get-childitem *.* | foreach { rename-item $_ $_.Name.Replace("_08-", "_2008-") }</code></p>
<p>I do not want to achieve it by copying the above formula to:<br />
...<br />
<code>get-childitem *.* | foreach { rename-item $_ $_.Name.Replace("_08-", "_2008-") }</code><br />
<code>get-childitem *.* | foreach { rename-item $_ $_.Name.Replace("_09-", "_2009-") }</code><br />
<code>get-childitem *.* | foreach { rename-item $_ $_.Name.Replace("_10-", "_2010-") }</code><br />
...</p>
<p>So is there a more elegant and fast way, because the years may vary from +- 1925-2023</p>
<p>The basic search and replace pattern is always the same and its's unique in each filename and begins with <code>_</code> contains two numbers for the year and ends with <code>-</code>.</p>
<p>So I have two cases<br />
-) years from 25 to 99 need at the beginning an "19"<br />
-) years from 00 to 23 need at the beginning an "20"</p>
<p><br />
<br />
Thanks in advance</p>
|
[
{
"answer_id": 74641630,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 1,
"selected": false,
"text": "text <- \"wonderful\"\n\nsearch <- \"\\\\b([a-z]{5,})\\\\b\"\ngsub(search, \"XXX\\\\1\", text, perl=TRUE)\n# => [1] \"XXXwonderful\"\n search <- \"\\\\b(\\\\p{L}{5,})\\\\b\"\ngsub(search, \"XXX\\\\1\", text, perl=TRUE)\n# => [1] \"XXXwonderful\"\n \\b ([a-z]{5,}) \\p{L}{5,} \\p{Ll}{5,} \\b"
},
{
"answer_id": 74642523,
"author": "ludovicpeyter",
"author_id": 18277469,
"author_profile": "https://Stackoverflow.com/users/18277469",
"pm_score": 1,
"selected": true,
"text": "search <- \"([a-z]{5,})\"\ngsub(search, \"XXX\\\\1\", text)\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20655598/"
] |
74,641,588
|
<p>What method can I use for reach this:</p>
<p>If my String is: <strong>mailSPA</strong>: I want <strong>mail_spa</strong></p>
<p>If my String is: <strong>mailSPAOther</strong> -> <strong>mail_spaother</strong></p>
<p>I tried this method:</p>
<pre><code>public static String camelToUnderscore(String input) {
if (input == null) {
return "";
}
String regex = "([A-Z])";
String replacement = "_$1";
String result = input.replaceAll(regex, replacement).toLowerCase();
if (result.startsWith("_"))
return result.substring(1);
return result;
}
</code></pre>
<p>but it transform my string <strong>mailSPA</strong> to <strong>mail_s_p_a</strong></p>
|
[
{
"answer_id": 74641703,
"author": "evren",
"author_id": 16635445,
"author_profile": "https://Stackoverflow.com/users/16635445",
"pm_score": 2,
"selected": true,
"text": "public static String camelToUnderscore(String input) {\n if (input == null) {\n return \"\";\n }\n String regex = \"([a-z])([A-Z])\";\n String replacement = \"$1_$2\";\n String result = input.replaceAll(regex, replacement).toLowerCase();\n if (result.startsWith(\"_\"))\n return result.substring(1);\n return result;\n}\n"
},
{
"answer_id": 74641737,
"author": "OH GOD SPIDERS",
"author_id": 6073886,
"author_profile": "https://Stackoverflow.com/users/6073886",
"pm_score": 0,
"selected": false,
"text": "public static String camelToUnderscore(final String input) {\n if (input == null) {\n return \"\";\n }\n final StringBuilder sb = new StringBuilder();\n final char[] charArray = input.toCharArray();\n for (int i = 0; i < charArray.length; i++) {\n final char currentChar = charArray[i];\n if (i > 1 && Character.isUpperCase(currentChar) && Character.isLowerCase(charArray[i-1])) {\n sb.append(\"_\"+Character.toLowerCase(currentChar));\n } else {\n sb.append(Character.toLowerCase(currentChar));\n }\n }\n return sb.toString();\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18772237/"
] |
74,641,624
|
<p>My client app uses socket as http connections, meaing one-time send,receive, and close, i considered using a single persistent connection, instead of separate connection, each time, but problem was, sometimes the server received 2 packets of 32 kiB, while a single packet of 64kiB, the other times, and somtimes even smaller size, so to compensate for the latency introduced by 3 way handshake, i wanted to enable <code>TCP_FASTOPEN</code>, and <code>TCP_NODELAY</code>,</p>
<p>I use <code>setsockopt</code> with both options to the client-side(<code>connect</code>ing) socket, but im confused that:</p>
<ul>
<li>At the <strong>server side</strong>, which socket to <code>setsockopt</code>, the one created with <code>socket</code> function, or the <code>accept</code>ed one, or both, for both options,</li>
<li>Also, is there any solution, to the problem, of un-intentional partitioning of data packets, like 2x32k, or 4x16k, instead of 1x64k</li>
</ul>
<p>thanking you</p>
<p>I read the documentation available in linux man pages, but found it confusing</p>
|
[
{
"answer_id": 74641703,
"author": "evren",
"author_id": 16635445,
"author_profile": "https://Stackoverflow.com/users/16635445",
"pm_score": 2,
"selected": true,
"text": "public static String camelToUnderscore(String input) {\n if (input == null) {\n return \"\";\n }\n String regex = \"([a-z])([A-Z])\";\n String replacement = \"$1_$2\";\n String result = input.replaceAll(regex, replacement).toLowerCase();\n if (result.startsWith(\"_\"))\n return result.substring(1);\n return result;\n}\n"
},
{
"answer_id": 74641737,
"author": "OH GOD SPIDERS",
"author_id": 6073886,
"author_profile": "https://Stackoverflow.com/users/6073886",
"pm_score": 0,
"selected": false,
"text": "public static String camelToUnderscore(final String input) {\n if (input == null) {\n return \"\";\n }\n final StringBuilder sb = new StringBuilder();\n final char[] charArray = input.toCharArray();\n for (int i = 0; i < charArray.length; i++) {\n final char currentChar = charArray[i];\n if (i > 1 && Character.isUpperCase(currentChar) && Character.isLowerCase(charArray[i-1])) {\n sb.append(\"_\"+Character.toLowerCase(currentChar));\n } else {\n sb.append(Character.toLowerCase(currentChar));\n }\n }\n return sb.toString();\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17965276/"
] |
74,641,647
|
<p>Let's assume my <code>DataFrame</code> <code>df</code> has a column called <code>col</code> of type <code>string</code>. What is wrong with the following code line?</p>
<pre><code>df['col'].filter(str.isnumeric)
</code></pre>
|
[
{
"answer_id": 74641703,
"author": "evren",
"author_id": 16635445,
"author_profile": "https://Stackoverflow.com/users/16635445",
"pm_score": 2,
"selected": true,
"text": "public static String camelToUnderscore(String input) {\n if (input == null) {\n return \"\";\n }\n String regex = \"([a-z])([A-Z])\";\n String replacement = \"$1_$2\";\n String result = input.replaceAll(regex, replacement).toLowerCase();\n if (result.startsWith(\"_\"))\n return result.substring(1);\n return result;\n}\n"
},
{
"answer_id": 74641737,
"author": "OH GOD SPIDERS",
"author_id": 6073886,
"author_profile": "https://Stackoverflow.com/users/6073886",
"pm_score": 0,
"selected": false,
"text": "public static String camelToUnderscore(final String input) {\n if (input == null) {\n return \"\";\n }\n final StringBuilder sb = new StringBuilder();\n final char[] charArray = input.toCharArray();\n for (int i = 0; i < charArray.length; i++) {\n final char currentChar = charArray[i];\n if (i > 1 && Character.isUpperCase(currentChar) && Character.isLowerCase(charArray[i-1])) {\n sb.append(\"_\"+Character.toLowerCase(currentChar));\n } else {\n sb.append(Character.toLowerCase(currentChar));\n }\n }\n return sb.toString();\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2706344/"
] |
74,641,651
|
<p>I'm still learning MongoDB and I'm having a difficulty on my current problem.
How can I get the most used category in collection, so in this <code>JSON</code>, my most used category is <code>CIES</code>. so what I want to do is it to the front end.</p>
<pre><code>[
{
"_id": "63888d85674a07e0d7d2eccc",,
"products": [
{
"productId": {
"_id": "63888c6c674a07e0d7d2e6ee",
"category": "CEIS",
"productCategory": "Others"
},
}
],
},
{
"_id": "63888d92674a07e0d7d2ecf5",
"products": [
{
"productId": {
"_id": "63888c17674a07e0d7d2e68a",
"category": "CEIS",
"productCategory": "CEIS Merchandise"
},
}
],
},
{
"_id": "63888db6674a07e0d7d2ed93",
"products": [
{
"productId": {
"_id": "63888c8c674a07e0d7d2e725",
"category": "CAHS",
"productCategory": "Clinical Equipments"
},
}
],
}
]
</code></pre>
<p>How do i get the most use category</p>
<pre><code>[
{
"category": "CEIS",
"total" : 2
}
]
</code></pre>
|
[
{
"answer_id": 74642006,
"author": "Hugo Dias",
"author_id": 20656032,
"author_profile": "https://Stackoverflow.com/users/20656032",
"pm_score": 0,
"selected": false,
"text": "router.get('/top', async (req, res) => {\n \n try {\n const order = await Order.aggregate([\n {\n $group: {\n _id: \"$products.productId.category\",\n total: {$sum: 1}\n }\n },\n {\n $sort: {\n total: -1\n }\n },\n {\n $limit: 1\n }\n ])\n\n res.status(200).json(order); \n\n } catch (error) {\n res.status(500).json({error: error.message})\n }\n })\n"
},
{
"answer_id": 74642749,
"author": "dangarfield",
"author_id": 3265253,
"author_profile": "https://Stackoverflow.com/users/3265253",
"pm_score": 2,
"selected": true,
"text": "unwind db.collection.aggregate([\n {\n $unwind: \"$products\"\n },\n {\n $group: {\n _id: \"$products.productId.category\",\n total: {\n $sum: 1\n }\n }\n },\n {\n $sort: {\n total: -1\n }\n },\n {\n $project: {\n _id: 0,\n category: \"$_id\",\n total: 1\n }\n },\n {\n $limit: 1\n }\n])\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18478430/"
] |
74,641,687
|
<p>CustomerController.java</p>
<pre><code>@RequestMapping(value="/customer/delete",method = {RequestMethod.DELETE,RequestMethod.GET})
public String deleteCustomer(Long id) {
customerService.deleteCustomer(id);
return "redirect:/customer";
}
</code></pre>
<p>CustomerService.java</p>
<pre><code>public void deleteCustomer(Long id) {
customerRepository.deleteById(id);
}
</code></pre>
<p>customer.html delete modal</p>
<pre><code><!--Delete Modal -->
<a th:href="@{/customer/delete/(id=${customer.id})}"
type="button" class="btn btn-danger" id="deleteButton"
data-toggle="modal"
data-target="#deleteModal">
<span class="material-icons">delete_outline</span></a>
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Confirm Delete</h5>
</div>
<div class="modal-body">
Are you sure want to delete this customer record?
</div>
<div class="modal-footer">
<a type="button" id="confirmDeleteButton" href="" class="btn btn-danger">Yes, Delete</a>
<button type="button" class="btn btn-dark" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
</code></pre>
<p>js script</p>
<pre><code>$('#deleteButton').on('click',function(event){
var href = $(this).attr('href');
$('#confirmDeleteButton').attr('href',href);
$('#deleteModal').submit();
})
</code></pre>
<p>I am getting an error on clicking on delete confirmation button on modal</p>
<p><strong>Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
There was an unexpected error (type=Not Found, status=404).
No message available</strong></p>
|
[
{
"answer_id": 74642006,
"author": "Hugo Dias",
"author_id": 20656032,
"author_profile": "https://Stackoverflow.com/users/20656032",
"pm_score": 0,
"selected": false,
"text": "router.get('/top', async (req, res) => {\n \n try {\n const order = await Order.aggregate([\n {\n $group: {\n _id: \"$products.productId.category\",\n total: {$sum: 1}\n }\n },\n {\n $sort: {\n total: -1\n }\n },\n {\n $limit: 1\n }\n ])\n\n res.status(200).json(order); \n\n } catch (error) {\n res.status(500).json({error: error.message})\n }\n })\n"
},
{
"answer_id": 74642749,
"author": "dangarfield",
"author_id": 3265253,
"author_profile": "https://Stackoverflow.com/users/3265253",
"pm_score": 2,
"selected": true,
"text": "unwind db.collection.aggregate([\n {\n $unwind: \"$products\"\n },\n {\n $group: {\n _id: \"$products.productId.category\",\n total: {\n $sum: 1\n }\n }\n },\n {\n $sort: {\n total: -1\n }\n },\n {\n $project: {\n _id: 0,\n category: \"$_id\",\n total: 1\n }\n },\n {\n $limit: 1\n }\n])\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20572638/"
] |
74,641,705
|
<p>I am very new to python. I have a folder which contains many .png files (which are scatter plots I previously made in python). I want to write a script that turns these files into a movie.</p>
<p>My files are named 0.png 1.png 2.png .... 49.png</p>
<p>I tried the following</p>
<pre><code> frames = []
for i in range(0,M):
frames.append(f'{i}.png')
gif.save(frames, "mymovie.gif",duration=15, unit="s",between="startend")
</code></pre>
<p>Where this gif function saves the list of frames as a movie. But I have no idea what to be calling in the frames.append(), at the moment I just get a list of strings.</p>
|
[
{
"answer_id": 74642006,
"author": "Hugo Dias",
"author_id": 20656032,
"author_profile": "https://Stackoverflow.com/users/20656032",
"pm_score": 0,
"selected": false,
"text": "router.get('/top', async (req, res) => {\n \n try {\n const order = await Order.aggregate([\n {\n $group: {\n _id: \"$products.productId.category\",\n total: {$sum: 1}\n }\n },\n {\n $sort: {\n total: -1\n }\n },\n {\n $limit: 1\n }\n ])\n\n res.status(200).json(order); \n\n } catch (error) {\n res.status(500).json({error: error.message})\n }\n })\n"
},
{
"answer_id": 74642749,
"author": "dangarfield",
"author_id": 3265253,
"author_profile": "https://Stackoverflow.com/users/3265253",
"pm_score": 2,
"selected": true,
"text": "unwind db.collection.aggregate([\n {\n $unwind: \"$products\"\n },\n {\n $group: {\n _id: \"$products.productId.category\",\n total: {\n $sum: 1\n }\n }\n },\n {\n $sort: {\n total: -1\n }\n },\n {\n $project: {\n _id: 0,\n category: \"$_id\",\n total: 1\n }\n },\n {\n $limit: 1\n }\n])\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20623945/"
] |
74,641,706
|
<p>This is a parking app which refresh the available parking slots every 30 seconds WITHOUT refreshing page.</p>
<p>This is my .py with the route and render template</p>
<pre><code>@views.route('/')
def home():
while True:
try:
token=getToken()
if(token!='null' or token!=''):
plazas=getInfo(token,parkingID)
except:
print('Error en la conexion')
time.sleep(secs)
return render_template("home.html", plazas=plazas)
</code></pre>
<p>My HTML is:</p>
<pre><code> <script src="{{ url_for('static', filename='js/main.js') }}"></script>
<script type="text/javascript">
myVar = setInterval(refresh,30000,{{plazas}});
</script>
</head>
<title>Home</title>
</head>
<body>
<table>
{% for parking in parkings %}
<tr>
<td class="par"><img src={{parking.image}} alt="img"></td>
<td class="nombre">{{parking.nombre}}</td>
{% if plazas|int >= (totalplazas*30)/100 %}
<td class="num" style="color:#39FF00">
{{plazas}}</td>
{% elif plazas|int < 1%}
<td class="num" style="color:red"><p class="an">COMPLETO</p></td>
{% elif plazas|int <= (totalplazas*10)/100%}
<td class="num" style="color:red">
{{plazas}}</td>
{% else %}
<td class="num" style="color:yellow">
{{plazas}}</td>
{% endif %}
<td class="dir"><img src={{parking.direccion}} alt="img"></td>
</tr>
{% endfor %}
</table>
</body>
</html>
</code></pre>
<p>And my JS:</p>
<pre><code>var elements = document.getElementsByClassName("num");
function refresh(pl){
elements.innerHTML = pl;
}
</code></pre>
<p>My problem is that the {{plazas}} variable always takes the initial value and is not updated every 30 seconds even if i use while true: loop in my .py.
Any help?</p>
|
[
{
"answer_id": 74642006,
"author": "Hugo Dias",
"author_id": 20656032,
"author_profile": "https://Stackoverflow.com/users/20656032",
"pm_score": 0,
"selected": false,
"text": "router.get('/top', async (req, res) => {\n \n try {\n const order = await Order.aggregate([\n {\n $group: {\n _id: \"$products.productId.category\",\n total: {$sum: 1}\n }\n },\n {\n $sort: {\n total: -1\n }\n },\n {\n $limit: 1\n }\n ])\n\n res.status(200).json(order); \n\n } catch (error) {\n res.status(500).json({error: error.message})\n }\n })\n"
},
{
"answer_id": 74642749,
"author": "dangarfield",
"author_id": 3265253,
"author_profile": "https://Stackoverflow.com/users/3265253",
"pm_score": 2,
"selected": true,
"text": "unwind db.collection.aggregate([\n {\n $unwind: \"$products\"\n },\n {\n $group: {\n _id: \"$products.productId.category\",\n total: {\n $sum: 1\n }\n }\n },\n {\n $sort: {\n total: -1\n }\n },\n {\n $project: {\n _id: 0,\n category: \"$_id\",\n total: 1\n }\n },\n {\n $limit: 1\n }\n])\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20538016/"
] |
74,641,722
|
<p>I have an Inventory DBone which has around 4000 servers.<br />
There are two groups Windows and Linux. Linux has around 2000 servers.</p>
<p>So in my template I kept as below:<br />
Invnetory name: DBone<br />
Limit: Linux</p>
<p>So the Ansible job will run in 2000 linux servers.<br />
But the linux servers has many servers like a****,b****,c****,d****,e****<br />
I need to run the job only on the a*** and b*** servers.</p>
<p>My playbook has:<br />
hosts: all</p>
<p>How can I modify the playbook or template to run the job on a*** and b*** servers only.</p>
|
[
{
"answer_id": 74643333,
"author": "DavidL",
"author_id": 4656551,
"author_profile": "https://Stackoverflow.com/users/4656551",
"pm_score": 0,
"selected": false,
"text": "[windows] [linux] - name: run play on linux servers\n hosts: linux\n tasks: ...\n -i"
},
{
"answer_id": 74643489,
"author": "Vladimir Botka",
"author_id": 6482561,
"author_profile": "https://Stackoverflow.com/users/6482561",
"pm_score": 1,
"selected": false,
"text": "shell> ansible-doc -t inventory constructed\n shell> cat inventory/01-hosts \na0001\nb0001\nb0002\nc0001\n shell> cat inventory/02-constructed.yml \nplugin: constructed\ngroups:\n group_a: inventory_hostname.startswith('a')\n group_b: inventory_hostname.startswith('b')\n shell> ansible-inventory -i inventory --list --yaml\nall:\n children:\n group_a:\n hosts:\n a0001: {}\n group_b:\n hosts:\n b0001: {}\n b0002: {}\n ungrouped:\n hosts:\n c0001: {}\n shell> cat pb.yml \n- hosts: group_a\n gather_facts: false\n tasks:\n - debug:\n var: inventory_hostname\n- hosts: group_b\n gather_facts: false\n tasks:\n - debug:\n var: inventory_hostname\n shell> ansible-playbook -i inventory pb.yml \n\nPLAY [group_a] *******************************************************************************\n\nTASK [debug] *********************************************************************************\nok: [a0001] => \n inventory_hostname: a0001\n\nPLAY [group_b] *******************************************************************************\n\nTASK [debug] *********************************************************************************\nok: [b0001] => \n inventory_hostname: b0001\nok: [b0002] => \n inventory_hostname: b0002\n\nPLAY RECAP ***********************************************************************************\na0001: ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 \nb0001: ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 \nb0002: ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0\n shell> ansible-doc -t inventory script\n shell> cat inventory/01-custom.py \n#!/usr/bin/env python3\n\nimport argparse\n\ntry:\n import json\nexcept ImportError:\n import simplejson as json\n\ncustom_inv_conf = [{'group': 'a', 'start': 1, 'stop': 4},\n {'group': 'b', 'start': 1, 'stop': 3},\n {'group': 'c', 'start': 1, 'stop': 2}]\n\n\nclass CustomInventory(object):\n\n def __init__(self):\n self.inventory = {}\n self.read_cli_args()\n\n if self.args.list:\n self.inventory = self.example_inventory()\n elif self.args.host:\n self.inventory = self.empty_inventory()\n else:\n self.inventory = self.empty_inventory()\n\n print(json.dumps(self.inventory))\n\n def example_inventory(self):\n return {\n 'test_hosts': {\n 'hosts': [i['group'] + str(\"%04d\" % j)\n for i in custom_inv_conf\n for j in range(i['start'], i['stop'])]\n },\n '_meta': {\n 'hostvars': {}\n }\n }\n\n def empty_inventory(self):\n return {'_meta': {'hostvars': {}}}\n\n def read_cli_args(self):\n parser = argparse.ArgumentParser()\n parser.add_argument('--list', action='store_true')\n parser.add_argument('--host', action='store')\n self.args = parser.parse_args()\n\n\nCustomInventory()\n shell> tree inventory\ninventory\n├── 01-custom.py\n└── 02-constructed.yml\n shell> ansible-inventory -i inventory --list --yaml\nall:\n children:\n group_a:\n hosts:\n a0001: {}\n a0002: {}\n a0003: {}\n group_b:\n hosts:\n b0001: {}\n b0002: {}\n test_hosts:\n hosts:\n a0001: {}\n a0002: {}\n a0003: {}\n b0001: {}\n b0002: {}\n c0001: {}\n ungrouped: {}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11399171/"
] |
74,641,763
|
<p>I have this application which needs some initialization before starting.
I'm using the recommended way, with the APP_INITIALIZER, the factory function, etc. along with the syntax in the factory function that allows the use of observables instead of promises.</p>
<p><strong>init.service.ts</strong></p>
<pre><code>...
constructor(private http: HttpClient){}
...
public init(){
return this.http.get(url).subscribe((data) => {
// save data in local variables
});
}
...
</code></pre>
<p><strong>app.module.ts</strong></p>
<pre><code>...
export function initializeApp(initService: InitService) {
return () => initService.init(); // this should convert the Obs into a Promise before return
}
...
providers: [
{
provider: APP_INITIALIZER,
useFactory: initializeApp,
deps: [InitService],
multi; true
}
]
...
</code></pre>
<p>Now, this is not working, meaning that the application starts (components rendering and all) before the initialization is completed.</p>
<p>As far as I understand the problem is that the function <code>init()</code> should return an Observable object. Still, I want the <code>.subscribe()</code> part to be defined <em>inside</em> the service function.
Is there any way of subscribing to an Observable and returning the Observable object in the same line? (simply prepending a <code>return</code> as I did, did not work)</p>
<p>I guess this is the only thing missing, as the provider will ensure that the Promise is resolved before starting the App ?</p>
<p>Thanks for any help,</p>
<p>--Thomas</p>
|
[
{
"answer_id": 74642059,
"author": "zeroquaranta",
"author_id": 2867242,
"author_profile": "https://Stackoverflow.com/users/2867242",
"pm_score": 0,
"selected": false,
"text": "public init(): Observable<any>{\n let obs this.http.get(url);\n obs.subscribe((data) => {\n // save data in local variables\n });\n return obs;\n}\n"
},
{
"answer_id": 74643103,
"author": "spots",
"author_id": 821918,
"author_profile": "https://Stackoverflow.com/users/821918",
"pm_score": 1,
"selected": false,
"text": "APP_INITIALIZER Observable InitService return this.http.get(url).pipe(map(data) => {\n // save data in local variables\n }));\n APP_INITIALIZER AppComponent"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2867242/"
] |
74,641,768
|
<p>that's what i need to find where the error is (. Make a scatter plot of Nsteps versus starting number. You should adjust your marker symbol
and size such that you can discern patterns in the data, rather than just seeing a solid mass of
points.)</p>
<p>*** basically this is my code:***</p>
<p><strong>#in[]</strong></p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
def collatz(N):
iteration=0
listNumbers=[N]
while N != 1:
iteration += 1
if (N%2) == 0:
N = N/2
else:
N= (N*3) + 1
print(i,'number of interactions',iteration)
print(listNumbers)
return iteration
N= int(input(' enter a number:'))
iteration=collatz(N)
</code></pre>
<p><strong>#out[]</strong></p>
<pre><code> enter a number:7
10000 number of interactions 16
[7]
</code></pre>
<p><strong>#in[]</strong></p>
<pre><code>s=np.array([])
for i in range(1,10001,1):
K=collatz(i)
s=np.append(s,K)
print(s)
</code></pre>
<p><strong>#out</strong>
(too big to paste here but i put the first 10 lines)</p>
<pre><code>1 number of interactions 0
[1]
2 number of interactions 1
[2]
3 number of interactions 7
[3]
4 number of interactions 2
[4]
5 number of interactions 5
[5]
6 number of interactions 8
[6]
7 number of interactions 16
[7]
8 number of interactions 3
[8]
9 number of interactions 19
[9]
10 number of interactions 6
[10]
</code></pre>
<p><strong>#in[]</strong></p>
<pre><code>plt.figure()
plt.scatter(range(1,100001,1),s) #gives me the x and y must be the same size error here plt.xlabel('number of interations')
plt.ylabel('numbes')
plt.ylim(0,355)
plt.xlim(0,100000)
plt.show()
#Make a scatter plot of Nsteps versus starting number. You should adjust your marker symbol
and size such that you can discern patterns in the data, rather than just seeing a solid mass of
points.
</code></pre>
|
[
{
"answer_id": 74642059,
"author": "zeroquaranta",
"author_id": 2867242,
"author_profile": "https://Stackoverflow.com/users/2867242",
"pm_score": 0,
"selected": false,
"text": "public init(): Observable<any>{\n let obs this.http.get(url);\n obs.subscribe((data) => {\n // save data in local variables\n });\n return obs;\n}\n"
},
{
"answer_id": 74643103,
"author": "spots",
"author_id": 821918,
"author_profile": "https://Stackoverflow.com/users/821918",
"pm_score": 1,
"selected": false,
"text": "APP_INITIALIZER Observable InitService return this.http.get(url).pipe(map(data) => {\n // save data in local variables\n }));\n APP_INITIALIZER AppComponent"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20623369/"
] |
74,641,792
|
<p>The code:</p>
<pre><code>df = pd.DataFrame({
'MNumber':['M03400001','M00000021','M10450001','M00003420','M02635915','M51323275','M63061229','M63151022'],
'GPA':[3.01, 4.00, 2.95, 2.90, 3.50, 3.33, 2.99, 3.98],
'major':['IS','BANA','IS','IS','IS','BANA','IS', 'BANA'],
'internship':['P&G', 'IBM', 'P&G', 'IBM', 'P&G', 'EY','EY', 'Great American'],
'job_offers':[2,0,0,3,2,1,4,3],
'graduate_credits':[5,1,0,5,2,2,3,4]
})
x = df.groupby('internship').describe()
#print(x.info())
print(x["IBM"])
</code></pre>
<p>The error:</p>
<pre><code>KeyError: 'IBM'
</code></pre>
|
[
{
"answer_id": 74641816,
"author": "cavalcantelucas",
"author_id": 5114495,
"author_profile": "https://Stackoverflow.com/users/5114495",
"pm_score": 0,
"selected": false,
"text": "x IBM print(x)\n print(x.columns)\n"
},
{
"answer_id": 74641829,
"author": "timgeb",
"author_id": 3620003,
"author_profile": "https://Stackoverflow.com/users/3620003",
"pm_score": 3,
"selected": true,
"text": "x['IBM'] 'IBM' x.loc['IBM'] 'IBM'"
},
{
"answer_id": 74641897,
"author": "Sam",
"author_id": 16660603,
"author_profile": "https://Stackoverflow.com/users/16660603",
"pm_score": 0,
"selected": false,
"text": "column index DataFrame row column"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1169091/"
] |
74,641,899
|
<p>Here is my code, how can i solve that?
<a href="https://i.stack.imgur.com/aeUKn.png" rel="nofollow noreferrer">enter image description here</a></p>
<p><a href="https://i.stack.imgur.com/xL9ID.png" rel="nofollow noreferrer">enter image description here</a>
<a href="https://i.stack.imgur.com/KZfr0.png" rel="nofollow noreferrer">enter image description here</a></p>
|
[
{
"answer_id": 74641816,
"author": "cavalcantelucas",
"author_id": 5114495,
"author_profile": "https://Stackoverflow.com/users/5114495",
"pm_score": 0,
"selected": false,
"text": "x IBM print(x)\n print(x.columns)\n"
},
{
"answer_id": 74641829,
"author": "timgeb",
"author_id": 3620003,
"author_profile": "https://Stackoverflow.com/users/3620003",
"pm_score": 3,
"selected": true,
"text": "x['IBM'] 'IBM' x.loc['IBM'] 'IBM'"
},
{
"answer_id": 74641897,
"author": "Sam",
"author_id": 16660603,
"author_profile": "https://Stackoverflow.com/users/16660603",
"pm_score": 0,
"selected": false,
"text": "column index DataFrame row column"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20624219/"
] |
74,641,937
|
<p>Adobe After Effects supports Javascript and provides a hany method of <code>time</code>.</p>
<p>It provides a floating point number of current time of the composition and can be used in numerous ways.</p>
<pre><code>60 - time // Starts the countdown timer from 60.
</code></pre>
<p><strong>I'm trying to create countdown timer that starts from a random number and resets to 59 once it hits 0.</strong></p>
<p>There are few ways to achieve it but I need a <code>expressions-only</code> solution as I want multiple repetitions and want to avoid multiple comps and layers.</p>
<pre><code>seedRandom(45, timeless=true) // Random shouldn't generate at every frame.
r = random(1, 59)
sec = r - time
if (sec < 0) {
sec = 60 - (time%60);
}
Math.floor(sec);
</code></pre>
<p><strong>Problem:</strong></p>
<p>The above code works but repeats from the <code>random number</code> for the first <code>two iterations</code> rather than start from first time only.</p>
<p>Any help is much appreciated.</p>
|
[
{
"answer_id": 74641816,
"author": "cavalcantelucas",
"author_id": 5114495,
"author_profile": "https://Stackoverflow.com/users/5114495",
"pm_score": 0,
"selected": false,
"text": "x IBM print(x)\n print(x.columns)\n"
},
{
"answer_id": 74641829,
"author": "timgeb",
"author_id": 3620003,
"author_profile": "https://Stackoverflow.com/users/3620003",
"pm_score": 3,
"selected": true,
"text": "x['IBM'] 'IBM' x.loc['IBM'] 'IBM'"
},
{
"answer_id": 74641897,
"author": "Sam",
"author_id": 16660603,
"author_profile": "https://Stackoverflow.com/users/16660603",
"pm_score": 0,
"selected": false,
"text": "column index DataFrame row column"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797819/"
] |
74,641,938
|
<p>I have a sheet with 3 columns: <code>player_a</code>, <code>player_b</code>, <code>result</code>
Where player_a and player_b are normalised strings representing the different players in the tournament, and result is either 'W' or 'L'</p>
<p>I would like to create a sheet with the following data:</p>
<p><code>player_a</code>, <code>player_b</code>, <code>num wins</code>, <code>num losses</code>, <code>winrate</code> as seen on the screenshot above</p>
<p>In SQL, I would do:</p>
<pre><code>
SELECT
player_a,
player_b,
num_wins, num_loss,
(num_wins*100/(num_wins+num_loss)) as winrate
FROM (
SELECT
player_a,
player_b,
count(case when result = 'W' THEN 1 END) as num_wins,
count(case when result = 'L' THEN 1 END) as num_loss
FROM `scores`
GROUP BY player_a, player_b) as grouped_scores;
</code></pre>
<p>In Google Sheets I tried:</p>
<p><code>Query(Sheet1!A3:C, "SELECT A, B, count(case when C = 'W' THEN 1 END), count(case when C = 'L' THEN 1 END)", 0)</code></p>
<p>But <code>case</code> is not supported in count</p>
<p>So to make this work I ended up doing a first query counting the wins:
<code>Query(Sheet1!A3:C, "select A, B, count(I) where C = 'W' group by A, B label count(C) 'num wins'", 1)</code></p>
<p>Then, for each created row, I manually created a <code>num_losses</code> column and added this formula for each cell below</p>
<p><code>=IFNA(query(Sheet1!A3:C, "select count(C) where C = 'L' AND A='"&INDIRECT("A"&row())&"' AND B='"&INDIRECT("B"&row())&"' group by A, B label count(C)''", 0), 0)</code></p>
<p>I then also created a column <code>winrate</code> where I made formulas for each cell to calculate the winrate</p>
<p>This works but I would like to do all of this in a single formula/query to make it more clean and easier to maintain.</p>
<p>Is there a way to translate my SQL query above into google sheets to do what I described?</p>
|
[
{
"answer_id": 74641816,
"author": "cavalcantelucas",
"author_id": 5114495,
"author_profile": "https://Stackoverflow.com/users/5114495",
"pm_score": 0,
"selected": false,
"text": "x IBM print(x)\n print(x.columns)\n"
},
{
"answer_id": 74641829,
"author": "timgeb",
"author_id": 3620003,
"author_profile": "https://Stackoverflow.com/users/3620003",
"pm_score": 3,
"selected": true,
"text": "x['IBM'] 'IBM' x.loc['IBM'] 'IBM'"
},
{
"answer_id": 74641897,
"author": "Sam",
"author_id": 16660603,
"author_profile": "https://Stackoverflow.com/users/16660603",
"pm_score": 0,
"selected": false,
"text": "column index DataFrame row column"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20656225/"
] |
74,641,988
|
<p>I am using a pandas data-frame and for some reason when trying to access one entry after another in a for loop it does gives me an error.</p>
<p>Here is my (simplified) code snippet:</p>
<pre><code>
df_original = pd.read_csv(csv_dataframe_filename, sep='\t', header=[0, 1], encoding_errors="replace")
df_original.columns = ['A', 'B',
'Count_Number', 'D',
'E', 'F',
'use_first', 'H', 'I']
df_use = df_original
df_use = df_use.drop(df_use[((df_use['use_first']=='no'))].index)
df_use.columns = ['A', 'B',
'Count_Number', 'D',
'E', 'F',
'use_first', 'H', 'I']
c_mag = np.zeros((len(df_use), 1))
x = 0
for i in range(len(df_use)):
print(df_use['Count_Number'][x]) #THIS IS THE LINE THAT IS THE ISSUE
x += 1
print(c_mag)
print(df_use['Count_Number'][x])
</code></pre>
<p>The line that is the issue is marked by a comment. If I enter a specific number instead of the variable x, it works (both outside and inside the loop, but inside the loop it of course then prints always the same value each time which is not what I want). It also works with df_original instead of df_use (but for my purpose I really need df_use). The printing in the very last line also works (even with variable x that at that point has a certain value).
I also entered the column naming for df_use in the middle later on, so I got the issue with and without it in the same way. I tried whether all other parts of the code work and they do, so both dataframes can be printed correctly etc.
Using x instead of i as a variable is also a result of playing around and trying to find a solution, so using i was giving the same result.</p>
<p>The column contains floats, if that matters.</p>
<p>But for the code as it is I get the following error message ("folder of file" is of course just a replacement for the actual file path):</p>
<pre><code>
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 3361, in get_loc
return self._engine.get_loc(casted_key)
File "pandas\_libs\index.pyx", line 76, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\hashtable_class_helper.pxi", line 2131, in pandas._libs.hashtable.Int64HashTable.get_item
File "pandas\_libs\hashtable_class_helper.pxi", line 2140, in pandas._libs.hashtable.Int64HashTable.get_item
KeyError: 0
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "[folder of file]", line 74, in <module>
print(df_use['Count_Number'][x])
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\series.py", line 942, in __getitem__
return self._get_value(key)
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\series.py", line 1051, in _get_value
loc = self.index.get_loc(label)
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 3363, in get_loc
raise KeyError(key) from err
KeyError: 0
Process finished with exit code 1
</code></pre>
<p>I searched for answers and tried out different things, such as checking the spelling etc. But I can not find a solution and do not understand what I am doing wrong.
Does anyone have an idea on how to solve this issue?</p>
<p>Thank you in advance for any helpful comment!</p>
<p>UPDATE: Found a solution after all. using .iloc[x] instead of just [x] solves the issue. Now I am still curious though why that happens - for other variables it worked even without the .iloc, so why not in this case? I feel like an answer would help me to better understand how things are working in python, so thanks for any hints even if I got the code working already.</p>
<p>What I already tried:
The line that is the issue is marked by a comment. If I enter a specific number instead of the variable x, it works. It also works with df_original instead of df_use (but for my purpose I really need df_use). The printing in the very last line also works (even with variable x that at that point has a certain value).
I also entered the column naming for df_use in the middle later on, so I got the issue with and without it in the same way. I tried whether all other parts of the code work and they do, so both data-frames can be printed correctly etc.
Using x instead of i as a variable is also a result of playing around and trying to find a solution, so using i was giving the same result. I also played around with different ways of how to run the loop, but that did not help either.
I searched for answers and tried out different things, such as checking the spelling etc.</p>
<p>What I am expecting:
The entries of the data-frame columns can be called and used successfully (in this simplified case: can be printed) in the for loop one entry after another. If the printing itself can be done differently, that does not help me (of course I can just print the whole column, that is working), because my actual purpose is to do further calculations with each value. print() is just for now to simplify the issue and try to find a solution.</p>
|
[
{
"answer_id": 74641816,
"author": "cavalcantelucas",
"author_id": 5114495,
"author_profile": "https://Stackoverflow.com/users/5114495",
"pm_score": 0,
"selected": false,
"text": "x IBM print(x)\n print(x.columns)\n"
},
{
"answer_id": 74641829,
"author": "timgeb",
"author_id": 3620003,
"author_profile": "https://Stackoverflow.com/users/3620003",
"pm_score": 3,
"selected": true,
"text": "x['IBM'] 'IBM' x.loc['IBM'] 'IBM'"
},
{
"answer_id": 74641897,
"author": "Sam",
"author_id": 16660603,
"author_profile": "https://Stackoverflow.com/users/16660603",
"pm_score": 0,
"selected": false,
"text": "column index DataFrame row column"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74641988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19726928/"
] |
74,642,016
|
<p>I'm using MikroOrm inside nestJs, and I added the following script inside <code>package.json</code></p>
<pre><code>"orm": "npx mikro-orm",
</code></pre>
<p>and these are the configurations</p>
<pre><code>seeder: {
path: 'src/misc/db/',
defaultSeeder: 'DatabaseSeeder',
glob: '!(*.d).{js,ts}',
emit: 'ts',
fileName: (className: string) => className,
}
</code></pre>
<p>I need to specify a specific seeder file when writing <code>npm run orm seeder:run --class=ClassNameSeeder</code> as the documentation mentioned, but I'm getting the following error</p>
<pre><code>Unknown argument: ClassName
</code></pre>
<p>I tried also to run the following script in <code>package.json</code> and see if it'll work or not but I got the same error</p>
<pre><code>"db:seed": "npm run mikro-orm seeder:run --class=ClassName"
</code></pre>
<h2>Note</h2>
<p>The seeder class is inside <code>misc/db/</code> as I added it in my configuration file.</p>
|
[
{
"answer_id": 74642094,
"author": "Martin Adámek",
"author_id": 3665878,
"author_profile": "https://Stackoverflow.com/users/3665878",
"pm_score": 1,
"selected": false,
"text": "--class npm run mikro-orm \"orm\": \"npx mikro-orm\" npx npx mikro-orm seeder:run --class=ClassNameSeeder\n -- npm run orm seeder:run -- --class=ClassNameSeeder\n"
},
{
"answer_id": 74652794,
"author": "Fabien",
"author_id": 5751901,
"author_profile": "https://Stackoverflow.com/users/5751901",
"pm_score": 0,
"selected": false,
"text": "npm run orm seeder:run\n src/misc/db/DatabaseSeeder.ts"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74642016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14810505/"
] |
74,642,053
|
<p>hello i am writing basic calculator. everytime i use 90 degrees on cos function it gives -0 as result</p>
<pre><code> int deg;
float rad,result;
printf("\ndegree\n");
scanf("%d",&deg);
rad = deg * (M_PI/180);
result=cos(rad);
printf("\nresult= %f",result);
</code></pre>
<p><a href="https://i.stack.imgur.com/lvjN5.png" rel="nofollow noreferrer">result</a></p>
<p>i dont even know what to try.
i just googled it and did not see any similar results.</p>
|
[
{
"answer_id": 74642166,
"author": "Adrian Maire",
"author_id": 903651,
"author_profile": "https://Stackoverflow.com/users/903651",
"pm_score": 3,
"selected": true,
"text": "3.141593... 3.1415926 float double printf std::setprecision"
},
{
"answer_id": 74642712,
"author": "vinc17",
"author_id": 3782797,
"author_profile": "https://Stackoverflow.com/users/3782797",
"pm_score": 2,
"selected": false,
"text": "%g %f %f double float rad result cos double double cos cospi cospi cos"
},
{
"answer_id": 74642789,
"author": "Steve Summit",
"author_id": 3923896,
"author_profile": "https://Stackoverflow.com/users/3923896",
"pm_score": 2,
"selected": false,
"text": "float double float double cos() cos() printf char tmp[50];\nsnprintf(tmp, sizeof(tmp), \"%f\", result);\nif(*tmp == '-' && atof(tmp) == 0) result = -result;\nprintf(\"result = %f\\n\", result);\n"
},
{
"answer_id": 74647060,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 0,
"selected": false,
"text": "\"%f\" \"-0.000000\" \"%g\" printf(\"\\nresult= %g\",result);\n// result= -4.37114e-08\n rad = deg * (M_PI/180); M_PI rad = deg * (M_PI/180); cos(rad) cos() #include <math.h>\n#include <stdio.h>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\nstatic double d2r(double d) {\n return (d / 180.0) * ((double) M_PI);\n}\n\ndouble cosd(double x) {\n if (!isfinite(x)) {\n return cos(x);\n }\n int quo;\n double d_45 = remquo(fabs(x), 90.0, &quo);\n // d_45 is in the range [-45...45]\n double r_pidiv4 = d2r(d_45);\n switch (quo % 4) {\n case 0:\n return cos(r_pidiv4);\n case 1:\n // Add 0.0 to avoid -0.0\n return 0.0 - sin(r_pidiv4);\n case 2:\n return -cos(r_pidiv4);\n case 3:\n return sin(r_pidiv4);\n\n }\n return 0.0;\n}\n int main(void) {\n int prec = DBL_DECIMAL_DIG - 1;\n for (int d = -360; d <= 360; d += 15) {\n double r = d2r(d);\n printf(\"cos (%6.1f degrees) = % .*e\\n\", 1.0 * d, prec, cos(r));\n printf(\"cosd(%6.1f degrees) = % .*e\\n\", 1.0 * d, prec, cosd(d));\n }\n return 0;\n}\n cos (-360.0 degrees) = 1.0000000000000000e+00\ncosd(-360.0 degrees) = 1.0000000000000000e+00\n...\ncos (-270.0 degrees) = -1.8369701987210297e-16\ncosd(-270.0 degrees) = 0.0000000000000000e+00 // Exactly zero\n...\ncos ( 0.0 degrees) = 1.0000000000000000e+00\ncosd( 0.0 degrees) = 1.0000000000000000e+00\n...\ncos ( 60.0 degrees) = 5.0000000000000011e-01 // Not 0.5\ncosd( 60.0 degrees) = 4.9999999999999994e-01 // Not 0.5, yet closer\n...\ncos ( 90.0 degrees) = 6.1232339957367660e-17\ncosd( 90.0 degrees) = 0.0000000000000000e+00 // Exactly zero, OP's goal\n...\ncos ( 270.0 degrees) = -1.8369701987210297e-16\ncosd( 270.0 degrees) = 0.0000000000000000e+00 // Exactly zero\n...\ncos ( 360.0 degrees) = 1.0000000000000000e+00\ncosd( 360.0 degrees) = 1.0000000000000000e+00\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74642053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20654747/"
] |
74,642,124
|
<p>I am trying to write a function based on this formula.</p>
<pre><code>(x − x0)^ r+ = { (x-x0)^r if x>x0
0 otherwise
</code></pre>
<p>what I understood from above is;</p>
<p>y= (x-x0)^r unless x<= x0</p>
<p>so for each element of, identify if greater and x0 if so return y that equals the formula.</p>
<pre><code>tp <- function(x,x0,r) {
y<-list()
if (x[i] >x0) {
for (i in seq_along(x)) {
y<- append((x[i]-x0)^r)
} else {
y <- append(0)
}
}
return(y)
}
</code></pre>
<p>I have tried doing this but I couldn't make it work. Could anyone advise me if I understood the formula right and if so what is the correct way to coed it.</p>
|
[
{
"answer_id": 74642189,
"author": "Rui Barradas",
"author_id": 8245406,
"author_profile": "https://Stackoverflow.com/users/8245406",
"pm_score": 2,
"selected": false,
"text": "ifelse tp <- function(x, x0, r) {\n ifelse(x > x0, (x - x0)^r, 0)\n}\n\nx0 <- 2\ntp(-2:5, x0, r = 2)\n#> [1] 0 0 0 0 0 1 4 9\n"
},
{
"answer_id": 74642241,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 1,
"selected": false,
"text": "append y <- append(y, ...) for x[i] > x0 y <- numeric(0) list tp <- function(x,x0,r) {\n y <- numeric(0)\n for (i in seq_along(x)) {\n if (x[i] > x0) {\n y <- append(y, (x[i]-x0)^r)\n } else {\n y <- append(y, 0)\n }\n }\n return(y)\n}\n for"
},
{
"answer_id": 74642253,
"author": "DashdotdotDashdotdot",
"author_id": 20548300,
"author_profile": "https://Stackoverflow.com/users/20548300",
"pm_score": 2,
"selected": false,
"text": "tp <- function(x, x0, r) {\n# ifelse(x > x0, (x - x0)^r, 0)\n (x > x0)*(x - x0)^r\n}\n\nx0 <- 2\ntp(-2:5, x0, r = 2)\n#> [1] 0 0 0 0 0 1 4 9\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74642124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20585881/"
] |
74,642,138
|
<p>I have this data in MongoDB.</p>
<pre><code>{ _id: "abc*hello*today*123", "value": 123 },
{ _id: "abc*hello*today*999", "value": 999 },
{ _id: "xyz*hello*tomorrow*123", "value": 123 }
</code></pre>
<p>What I want is to group by the first part before "*{number}". This is what I want to achieve:</p>
<pre><code>{
_id: "abc*hello*today",
results: [
{ _id: "abc*hello*today*123", "value": 123 },
{ _id: "abc*hello*today*999", "value": 999 }
]
},
{
_id: "xyz*hello*tomorrow",
results: [
{ _id: "xyz*hello*tomorrow*123", "value": 123 }
]
}
</code></pre>
<p>I tried this:</p>
<pre><code>{
$group:{
"_id":"$_id".slice(0, -4)
}
}
</code></pre>
|
[
{
"answer_id": 74642509,
"author": "Yong Shun",
"author_id": 8017690,
"author_profile": "https://Stackoverflow.com/users/8017690",
"pm_score": 2,
"selected": true,
"text": ".*(?=\\*\\d+)\n $set firstPart $getField match $regexFind _id $group firstPart $unset results.firstPart db.collection.aggregate([\n {\n $set: {\n firstPart: {\n $getField: {\n field: \"match\",\n input: {\n $regexFind: {\n input: \"$_id\",\n regex: \".*(?=\\\\*\\\\d+)\"\n }\n }\n }\n }\n }\n },\n {\n $group: {\n _id: \"$firstPart\",\n results: {\n $push: \"$$ROOT\"\n }\n }\n },\n {\n $unset: \"results.firstPart\"\n }\n])\n"
},
{
"answer_id": 74644373,
"author": "Valijon",
"author_id": 3710490,
"author_profile": "https://Stackoverflow.com/users/3710490",
"pm_score": 0,
"selected": false,
"text": "_id (field1*field2*field3*numbers) $split $slice $reduce $split('field1*field2*field3*numbers', '*') -> ['field1', 'field2', 'field3','number']\n$slice(['item1', 'item2', 'item3'], 2) -> ['item1', 'item2']\n$reduce(['field1', 'field2', 'field3'], 'Concatenate with *') -> 'field1*field2*field3'\n db.collection.aggregate([\n {\n $group: {\n _id: {\n $slice: [\n { $split: [ \"$_id\", \"*\"] },\n 3\n ]\n },\n results: {\n $push: \"$$ROOT\"\n }\n }\n },\n {\n $project: {\n _id: {\n $reduce: {\n input: \"$_id\",\n initialValue: \"\",\n in: { $concat: [ \"$$value\", \"*\", \"$$this\" ] }\n }\n },\n results: 1\n }\n }\n])\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74642138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19256727/"
] |
74,642,156
|
<p>I am using Vue (<code>vuetify</code>) <code>v-data-table</code> to show some data, Its working fine, in the same time I am trying to show some data from another api, So I need to know how to push a items inside of a array of object.</p>
<pre><code>axiosThis.tableDataFinal[i].push(axiosThis.printsumget[i])
</code></pre>
<p>I am getting an error <code>.push is not a function</code></p>
|
[
{
"answer_id": 74642509,
"author": "Yong Shun",
"author_id": 8017690,
"author_profile": "https://Stackoverflow.com/users/8017690",
"pm_score": 2,
"selected": true,
"text": ".*(?=\\*\\d+)\n $set firstPart $getField match $regexFind _id $group firstPart $unset results.firstPart db.collection.aggregate([\n {\n $set: {\n firstPart: {\n $getField: {\n field: \"match\",\n input: {\n $regexFind: {\n input: \"$_id\",\n regex: \".*(?=\\\\*\\\\d+)\"\n }\n }\n }\n }\n }\n },\n {\n $group: {\n _id: \"$firstPart\",\n results: {\n $push: \"$$ROOT\"\n }\n }\n },\n {\n $unset: \"results.firstPart\"\n }\n])\n"
},
{
"answer_id": 74644373,
"author": "Valijon",
"author_id": 3710490,
"author_profile": "https://Stackoverflow.com/users/3710490",
"pm_score": 0,
"selected": false,
"text": "_id (field1*field2*field3*numbers) $split $slice $reduce $split('field1*field2*field3*numbers', '*') -> ['field1', 'field2', 'field3','number']\n$slice(['item1', 'item2', 'item3'], 2) -> ['item1', 'item2']\n$reduce(['field1', 'field2', 'field3'], 'Concatenate with *') -> 'field1*field2*field3'\n db.collection.aggregate([\n {\n $group: {\n _id: {\n $slice: [\n { $split: [ \"$_id\", \"*\"] },\n 3\n ]\n },\n results: {\n $push: \"$$ROOT\"\n }\n }\n },\n {\n $project: {\n _id: {\n $reduce: {\n input: \"$_id\",\n initialValue: \"\",\n in: { $concat: [ \"$$value\", \"*\", \"$$this\" ] }\n }\n },\n results: 1\n }\n }\n])\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74642156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16896963/"
] |
74,642,159
|
<p>I am doing advent of code, which is a collection of 25 programming problems, one for each of day of the advent.</p>
<p>I structure each day in it's own separate file/module, so for example year 2021 day 7 would be at <code>src/years/year2021/day07.rs</code>. So <code>src/years/year2021/mod.rs</code> ends up being just <code>pub mod</code>s</p>
<pre><code>pub mod day01;
pub mod day02;
pub mod day04;
// and so on...
</code></pre>
<p>Is there a way I could generate this list dynamically (with something like a recursive macro), so check if module day01 is accessible from this context (or alternatively if ./day01.rs exists) and generate the <code>pub mod</code> automatically, and add more as files are created.</p>
<p>The best would be the ability to check if any name exists, like a module or a function inside a module.</p>
|
[
{
"answer_id": 74642617,
"author": "pigeonhands",
"author_id": 2691759,
"author_profile": "https://Stackoverflow.com/users/2691759",
"pm_score": 3,
"selected": true,
"text": "let years_path = path::Path::new(\"./src/years\");\nlet mut mod_file = fs::File::create(years_path.join(\"mod.rs\")).unwrap();\n\nlet paths = fs::read_dir(years_path).unwrap();\n\nfor entry in paths {\n let entry = entry.unwrap();\n if entry.metadata().unwrap().is_dir() {\n writeln!(\n mod_file,\n \"mod {};\",\n entry.path().file_name().unwrap().to_str().unwrap()\n )\n .unwrap();\n }\n}\n"
},
{
"answer_id": 74643024,
"author": "cafce25",
"author_id": 442760,
"author_profile": "https://Stackoverflow.com/users/442760",
"pm_score": 0,
"selected": false,
"text": "build.rs use std::{\n error::Error,\n ffi::OsString,\n fs::{self, File},\n io::Write,\n path::Path,\n};\n\nfn main() -> Result<(), Box<dyn Error>> {\n println!(\"cargo:rerun-if-changed=src/years\");\n let years_path = Path::new(\"src/years\");\n let mut years_mod_file = File::create(years_path.join(\"mod.rs\"))?;\n for year in fs::read_dir(\"src/years\")? {\n let Ok(year) = year else {continue};\n let year_name = year.file_name();\n let Some(year_name) = year_name.to_str() else {continue};\n if year_name != OsString::from(\"mod.rs\") {\n writeln!(years_mod_file, \"pub mod {year_name};\")?;\n let mut year_mod_file = File::create(year.path().join(\"mod.rs\"))?;\n\n for day in fs::read_dir(year.path())? {\n let Ok(day) = day else {continue};\n if day.file_name() != OsString::from(\"mod.rs\") {\n let day_name = day.path();\n let Some(day_name) = day_name.file_stem() else {continue};\n let Some(day_name) = day_name.to_str() else {continue};\n writeln!(year_mod_file, \"pub mod {day_name};\")?;\n println!(\"{:?}\", day_name);\n }\n }\n }\n }\n Ok(())\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74642159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2974775/"
] |
74,642,172
|
<p>current code:</p>
<pre><code>list = [1,2,3,4,5]
for i in list:
Dev.step(2)
if i == 2 or 1 or 0:
Dev.turnLeft()
Dev.step(Dev.x-Item[i].x)
Dev.step(Dev.x-15)
Dev.turnRight()
else:
Dev.turnRight()
Dev.step(Item[i].x-Dev.x)
Dev.step(15-Dev.x)
Dev.turnLeft()
</code></pre>
<p>How do I create an if statement for the Dev / Character do something for a specific list element or filter the list elements. Example I want, if the number of 'i' is equal to
2 or 1 or 0 the Dev will turnLeft. So the output of the list is seperated with the other numbers.</p>
<p>Example:
[2,1,0] and [4,5]</p>
<p>Create an if statement for a specific list elements / numbers.</p>
|
[
{
"answer_id": 74642222,
"author": "Effie",
"author_id": 11060338,
"author_profile": "https://Stackoverflow.com/users/11060338",
"pm_score": 2,
"selected": false,
"text": "if i in {0, 1, 2}:\n #do logic\n"
},
{
"answer_id": 74642224,
"author": "brenodacosta",
"author_id": 18091040,
"author_profile": "https://Stackoverflow.com/users/18091040",
"pm_score": 0,
"selected": false,
"text": "i list = [1,2,3,4,5]\n\nfor i in list:\n Dev.step(2)\n if i == 2 or i == 1 or i == 0:\n Dev.turnLeft()\n Dev.step(Dev.x-Item[i].x)\n Dev.step(Dev.x-15)\n Dev.turnRight()\n else:\n Dev.turnRight()\n Dev.step(Item[i].x-Dev.x)\n Dev.step(15-Dev.x)\n Dev.turnLeft()\n"
},
{
"answer_id": 74642230,
"author": "realhuman",
"author_id": 15690172,
"author_profile": "https://Stackoverflow.com/users/15690172",
"pm_score": 2,
"selected": true,
"text": "if i == 2 or 1 or 0 or i == if i == 2 or i == 1 or i == 0:\n list = [1,2,3,4,5]\n\nfor i in list:\n Dev.step(2)\n if i == 2 or i == 1 or i == 0:\n Dev.turnLeft()\n Dev.step(Dev.x-Item[i].x)\n Dev.step(Dev.x-15)\n Dev.turnRight()\n else:\n Dev.turnRight()\n Dev.step(Item[i].x-Dev.x)\n Dev.step(15-Dev.x)\n Dev.turnLeft()\n in i if i in (0,1,2): # This checks if i is in the tuple, so basically if i is one of those elements in the tuple\n list = [1,2,3,4,5]\n\nfor i in list:\n Dev.step(2)\n if i in (0,1,2):\n Dev.turnLeft()\n Dev.step(Dev.x-Item[i].x)\n Dev.step(Dev.x-15)\n Dev.turnRight()\n else:\n Dev.turnRight()\n Dev.step(Item[i].x-Dev.x)\n Dev.step(15-Dev.x)\n Dev.turnLeft()\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74642172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20591508/"
] |
74,642,178
|
<pre><code>public postForObjecty(endpoint: any, data: any) {
return new Promise((resolve, reject) => {
let url = this.createBasicUrl(endpoint);
let _data = this.arrangeData(data);
let headers: any = new Headers()
let token = `Bearer ${RestProvider.BEARER_TOKEN}`;
headers.append('Authorization', token);
this.http.post(url, _data, { headers: headers })
.map((res: { json: () => any; }) => res.json())
.subscribe((data: unknown) => {
resolve(data);
}, (err: any) => {
reject(err);
});
});
}
</code></pre>
<p>i want to post and get methond to backend but i cant fix this code</p>
<pre><code>.map
</code></pre>
<p>this doesnt work,</p>
<p>if i could fix this .map method it will be done</p>
|
[
{
"answer_id": 74642249,
"author": "Philipp Meissner",
"author_id": 3686898,
"author_profile": "https://Stackoverflow.com/users/3686898",
"pm_score": 1,
"selected": false,
"text": "map .pipe public postForObjecty(endpoint: any, data: any) {\n return new Promise((resolve, reject) => {\n let url = this.createBasicUrl(endpoint);\n let _data = this.arrangeData(data);\n let headers: any = new Headers()\n let token = `Bearer ${RestProvider.BEARER_TOKEN}`;\n headers.append('Authorization', token);\n this.http.post(url, _data, { headers: headers })\n .pipe(map((res: { json: () => any; }) => res.json()))\n .subscribe((data: unknown) => {\n resolve(data);\n }, (err: any) => {\n reject(err);\n });\n });\n }\n"
},
{
"answer_id": 74642891,
"author": "spots",
"author_id": 821918,
"author_profile": "https://Stackoverflow.com/users/821918",
"pm_score": 0,
"selected": false,
"text": "HttpClient map public postForObjecty(endpoint: any, data: any) {\n return new Promise((resolve, reject) => {\n let url = this.createBasicUrl(endpoint);\n let _data = this.arrangeData(data);\n let headers: any = new Headers()\n let token = `Bearer ${RestProvider.BEARER_TOKEN}`;\n headers.append('Authorization', token);\n this.http.post(url, _data, { headers: headers })\n .subscribe((data: unknown) => {\n resolve(data);\n }, (err: any) => {\n reject(err);\n });\n });\n }\n observe: 'response' options post Http .json()"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74642178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20426315/"
] |
74,642,185
|
<p>I'm trying to create a new object that only contains the a product array with the seller I req. I have an order object that has a product array. I'd like to return a specific seller. I tried:</p>
<pre><code>const newOrders = orders.map((element) => {
return {
...element,
product: element.product.filter(
(seller) => seller === req.currentUser!.id
),
};
});
</code></pre>
<p>does mongoose have a preferred method for doing what I bring to achieve? I've read through the find queries but none of the methods seem useful to this use case.</p>
<pre><code>orders: [
{
userId: "638795ad742ef7a17e258693",
status: "pending",
shippingInfo: {
line1: "599 East Liberty Street",
line2: null,
city: "Toronto",
country: "CA",
postal_code: "M7K 8P3",
state: "MT"
},
product: [
{
title: "new image",
description: "a log description",
seller: "6369589f375b5196f62e3675",
__v: 1,
id: "63737e4b0adf387c5e863d33"
},
{
title: "Mekks",
description: "Ple",
seller: "6369589f375b5196f62e3675",
__v: 1,
id: "6376706808cf1adafd5af32f"
},
{
title: "Meeks Prodyuct",
description: "long description",
seller: "63868795a6196afbc3677cfe",
__v: 1,
id: "63868812a6196afbc3677d06"
}
],
version: 1,
id: "6388138170892249e01bdcba"
}
],
</code></pre>
|
[
{
"answer_id": 74642249,
"author": "Philipp Meissner",
"author_id": 3686898,
"author_profile": "https://Stackoverflow.com/users/3686898",
"pm_score": 1,
"selected": false,
"text": "map .pipe public postForObjecty(endpoint: any, data: any) {\n return new Promise((resolve, reject) => {\n let url = this.createBasicUrl(endpoint);\n let _data = this.arrangeData(data);\n let headers: any = new Headers()\n let token = `Bearer ${RestProvider.BEARER_TOKEN}`;\n headers.append('Authorization', token);\n this.http.post(url, _data, { headers: headers })\n .pipe(map((res: { json: () => any; }) => res.json()))\n .subscribe((data: unknown) => {\n resolve(data);\n }, (err: any) => {\n reject(err);\n });\n });\n }\n"
},
{
"answer_id": 74642891,
"author": "spots",
"author_id": 821918,
"author_profile": "https://Stackoverflow.com/users/821918",
"pm_score": 0,
"selected": false,
"text": "HttpClient map public postForObjecty(endpoint: any, data: any) {\n return new Promise((resolve, reject) => {\n let url = this.createBasicUrl(endpoint);\n let _data = this.arrangeData(data);\n let headers: any = new Headers()\n let token = `Bearer ${RestProvider.BEARER_TOKEN}`;\n headers.append('Authorization', token);\n this.http.post(url, _data, { headers: headers })\n .subscribe((data: unknown) => {\n resolve(data);\n }, (err: any) => {\n reject(err);\n });\n });\n }\n observe: 'response' options post Http .json()"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74642185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17127423/"
] |
74,642,219
|
<p>I have recently read "Clean Architecture" by Bob Martin. Even though the principles he explains there apply to all languages it is harder for me to grasp those concepts around JavaScript (functional languages in general).</p>
<p>I have a React application where I have applied React Redux but now when I have read the book I wonder if I am not too dependent on Redux and how can I make myself more independent so that I can easily substitute Redux with any other approach (React Hooks for instance) any time I want.</p>
<p>Bob Martin is emphasizing on the fact that we need to be careful about architecture boundaries but I am really not sure where I can put Redux in that case?</p>
<p>Do I do business logic in Redux? If yes, does not this break the Clean Architecture recommendation to keep business logic independent? If I put my logic in Redux I become too dependent on it?</p>
<p>I have my pure view components only to display data on them them some viewModel components that handle view logic but from there I am not sure what is happening next.</p>
|
[
{
"answer_id": 74642249,
"author": "Philipp Meissner",
"author_id": 3686898,
"author_profile": "https://Stackoverflow.com/users/3686898",
"pm_score": 1,
"selected": false,
"text": "map .pipe public postForObjecty(endpoint: any, data: any) {\n return new Promise((resolve, reject) => {\n let url = this.createBasicUrl(endpoint);\n let _data = this.arrangeData(data);\n let headers: any = new Headers()\n let token = `Bearer ${RestProvider.BEARER_TOKEN}`;\n headers.append('Authorization', token);\n this.http.post(url, _data, { headers: headers })\n .pipe(map((res: { json: () => any; }) => res.json()))\n .subscribe((data: unknown) => {\n resolve(data);\n }, (err: any) => {\n reject(err);\n });\n });\n }\n"
},
{
"answer_id": 74642891,
"author": "spots",
"author_id": 821918,
"author_profile": "https://Stackoverflow.com/users/821918",
"pm_score": 0,
"selected": false,
"text": "HttpClient map public postForObjecty(endpoint: any, data: any) {\n return new Promise((resolve, reject) => {\n let url = this.createBasicUrl(endpoint);\n let _data = this.arrangeData(data);\n let headers: any = new Headers()\n let token = `Bearer ${RestProvider.BEARER_TOKEN}`;\n headers.append('Authorization', token);\n this.http.post(url, _data, { headers: headers })\n .subscribe((data: unknown) => {\n resolve(data);\n }, (err: any) => {\n reject(err);\n });\n });\n }\n observe: 'response' options post Http .json()"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74642219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11342139/"
] |
74,642,228
|
<p>I would like to return a http-response status 200 to http-requests which are send on port 8883.
The port is used for mqtt but we would like to catch http-requests on it.</p>
<p>The configuration I have now is (Haproxy 2.2) :</p>
<pre><code>frontend smqtt
bind :8883
mode tcp
use_backend port_check if HTTP
default_backend smqtt-broker
backend smqtt-broker
mode tcp
server A-SMQTT <ip>:<port> check
server B-SMQTT <ip>:<port> check
backend port_check
mode http
http-response return status 200 content-type "text/plain" lf-string "Port Check Success"
</code></pre>
<p>The MQTT backend (default_backend) is working but the 'catching' of HTTP-requests is not.
How can I detect (and change the backend) if a HTTP-request is coming in mode tcp?</p>
|
[
{
"answer_id": 74642249,
"author": "Philipp Meissner",
"author_id": 3686898,
"author_profile": "https://Stackoverflow.com/users/3686898",
"pm_score": 1,
"selected": false,
"text": "map .pipe public postForObjecty(endpoint: any, data: any) {\n return new Promise((resolve, reject) => {\n let url = this.createBasicUrl(endpoint);\n let _data = this.arrangeData(data);\n let headers: any = new Headers()\n let token = `Bearer ${RestProvider.BEARER_TOKEN}`;\n headers.append('Authorization', token);\n this.http.post(url, _data, { headers: headers })\n .pipe(map((res: { json: () => any; }) => res.json()))\n .subscribe((data: unknown) => {\n resolve(data);\n }, (err: any) => {\n reject(err);\n });\n });\n }\n"
},
{
"answer_id": 74642891,
"author": "spots",
"author_id": 821918,
"author_profile": "https://Stackoverflow.com/users/821918",
"pm_score": 0,
"selected": false,
"text": "HttpClient map public postForObjecty(endpoint: any, data: any) {\n return new Promise((resolve, reject) => {\n let url = this.createBasicUrl(endpoint);\n let _data = this.arrangeData(data);\n let headers: any = new Headers()\n let token = `Bearer ${RestProvider.BEARER_TOKEN}`;\n headers.append('Authorization', token);\n this.http.post(url, _data, { headers: headers })\n .subscribe((data: unknown) => {\n resolve(data);\n }, (err: any) => {\n reject(err);\n });\n });\n }\n observe: 'response' options post Http .json()"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74642228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3097526/"
] |
74,642,232
|
<p>I want to remove predefined parts of the strings in the following table and save the values in an array. For some reason I get an error stating that I'm outside of the index. The lengths of the strings in the table can vary.</p>
<pre><code>Sub New_1()
Dim i, j, k As Integer
Dim Endings As Variant
k = 0
Endings = Array("/A", "/BB", "/CCC", "/DDDD", "/EEEEE")
Dim ArrayValues() As Variant
With Worksheets("table1")
Dim lastRow As Long: lastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
ReDim ArrayValues(lastRow)
For i = lastRow To 1 Step -1
For j = 0 To UBound(Endings)
ArrayValues(k) = Replace(.Range("A" & i), Endings(j), "")
k = k + 1
Next j
Next i
End With
End Sub
</code></pre>
<p><a href="https://i.stack.imgur.com/EskvR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EskvR.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74642249,
"author": "Philipp Meissner",
"author_id": 3686898,
"author_profile": "https://Stackoverflow.com/users/3686898",
"pm_score": 1,
"selected": false,
"text": "map .pipe public postForObjecty(endpoint: any, data: any) {\n return new Promise((resolve, reject) => {\n let url = this.createBasicUrl(endpoint);\n let _data = this.arrangeData(data);\n let headers: any = new Headers()\n let token = `Bearer ${RestProvider.BEARER_TOKEN}`;\n headers.append('Authorization', token);\n this.http.post(url, _data, { headers: headers })\n .pipe(map((res: { json: () => any; }) => res.json()))\n .subscribe((data: unknown) => {\n resolve(data);\n }, (err: any) => {\n reject(err);\n });\n });\n }\n"
},
{
"answer_id": 74642891,
"author": "spots",
"author_id": 821918,
"author_profile": "https://Stackoverflow.com/users/821918",
"pm_score": 0,
"selected": false,
"text": "HttpClient map public postForObjecty(endpoint: any, data: any) {\n return new Promise((resolve, reject) => {\n let url = this.createBasicUrl(endpoint);\n let _data = this.arrangeData(data);\n let headers: any = new Headers()\n let token = `Bearer ${RestProvider.BEARER_TOKEN}`;\n headers.append('Authorization', token);\n this.http.post(url, _data, { headers: headers })\n .subscribe((data: unknown) => {\n resolve(data);\n }, (err: any) => {\n reject(err);\n });\n });\n }\n observe: 'response' options post Http .json()"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74642232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11535108/"
] |
74,642,250
|
<p>I have recently learnt about incomplete types and that under certain conditions they can be used as template arguments. In particular, like <code>void</code>, <code>struct incomplete;</code> are both incomplete types. Then I wrote the following program that works with gcc but not with msvc and clang. <a href="https://godbolt.org/z/WGz3f75da" rel="nofollow noreferrer">Live demo</a></p>
<pre><code>struct incomplete;
template<typename T> struct C
{
static constexpr T t{};
};
template<class T>
struct myClass {
C<T> new_t() { return {}; }
};
int main() {
myClass<incomplete> d;
d.new_t();
}
</code></pre>
<p>As we can see the above program compiles with gcc but not with msvc and clang. So I want to know which is the correct technical behavior.</p>
<p>Clang says:</p>
<pre><code><source>:4:24: error: constexpr variable cannot have non-literal type 'const incomplete'
static constexpr T t{};
</code></pre>
<p>while msvc says:</p>
<pre><code><source>(4): error C2027: use of undefined type 'incomplete'
<source>(1): note: see declaration of 'incomplete'
</code></pre>
<p>while GCC accepts the code with both c++17 as well as c++20.</p>
<p>Which compiler is correct here?</p>
|
[
{
"answer_id": 74642460,
"author": "Jason Liam",
"author_id": 12002570,
"author_profile": "https://Stackoverflow.com/users/12002570",
"pm_score": 2,
"selected": false,
"text": "C<incomplete> constexpr inline C<incomplete> constexpr inline"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74642250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20562802/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.