qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,328,510 | <p><a href="https://i.stack.imgur.com/HCfwd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HCfwd.png" alt="enter image description here" /></a></p>
<ol>
<li><p>I want to get the uid using name
for eg: someFunctionToFindUidOfName('Akt') //should return uid = 0, but don't know how to get that i am new to dataFrames please explain the answer</p>
</li>
<li><p>I also want to checkif dataFrame has username and password if it has it will print "user found!"</p>
</li>
</ol>
<p>please answer in 1 and 2 differently and please explain as much as u can in simple terms </p>
| [
{
"answer_id": 74328548,
"author": "Anh Le Hoang",
"author_id": 16315750,
"author_profile": "https://Stackoverflow.com/users/16315750",
"pm_score": 1,
"selected": false,
"text": "display: flex;"
},
{
"answer_id": 74328600,
"author": "Jericho",
"author_id": 12033989,
"author_profile": "https://Stackoverflow.com/users/12033989",
"pm_score": 0,
"selected": false,
"text": "display: grid;"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74328510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20089880/"
] |
74,328,516 | <p>i have a string like so:</p>
<pre><code>${1}${2}${3}${4}%9${5}00
</code></pre>
<p>And I'm wanting to wrap all the numbers and vars in span tags But the issue is there can be an unlimited number of <strong>"${1}"</strong> variables in this string.</p>
<p>The current regex I'm using is</p>
<pre><code>str.replace(/([0-9\/\+\(\)\%\-\*v]{1})/g, '<span>$1</span>')
</code></pre>
<p>But the problem with this regex is it wraps the $, { and } in a separate span tag. I'm wanting to wrap the <strong>"${1}"</strong> in its own span tag.</p>
<p>How would I do this and if possible can you explain the regex.</p>
<p>Thanks</p>
<hr />
<p>Working example:</p>
<pre><code>et str = '${1}${2}${3}${4}%9${5}00';
let copy = str.replace(/(\$\{\d+\}|[\d/+()%*v-])/g, '<span>$1</span>');
console.log('Copy: ', copy)
</code></pre>
| [
{
"answer_id": 74328559,
"author": "Nathan Furnal",
"author_id": 9479128,
"author_profile": "https://Stackoverflow.com/users/9479128",
"pm_score": 2,
"selected": false,
"text": "str.replace(/(\\$\\{\\d\\})/g, '<span>$1</span>')\n"
},
{
"answer_id": 74329958,
"author": "MikeM",
"author_id": 1565512,
"author_profile": "https://Stackoverflow.com/users/1565512",
"pm_score": 2,
"selected": true,
"text": "let str = '${1}${2}${3}${4}%9${5}00';\n\nstr = str.replace(/\\$\\{\\d+\\}|[\\d/+()%*v-]/g, '<span>$&</span>');\n\nconsole.log(str);"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74328516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2057056/"
] |
74,328,533 | <p>I have a table Wallets:</p>
<pre><code>[id] [address]
1 ABC
2 ABC
3 DEF
4 GHI
5 JKL
</code></pre>
<p>I have a table Cards</p>
<pre><code>[company] [color] [wallet_id]
Facebook blue 1
Facebook blue 2
Youtube red 3
Facebook blue 3
Orkut pink 4
Microsoft green 5
Facebook blue 5
</code></pre>
<p>I want to get all the different wallet addresses that have the same cards, so if i pass wallet id 1, it should return:</p>
<pre><code> [id] [address]
3 DEF // Because wallet with id 1 and 3 have same blue Facebook card
5 JKL // Because wallet with id 1 and 5 have same blue Facebook card
</code></pre>
<p>In this case it should not return Wallet with ID 2, even having the same card, because it is the same address (ABC) that we are doing the lookup.</p>
<p>I've tried a bunch of different solutions, but im confused on how to organize the SQL to do this.</p>
<blockquote>
<p>I tried going with:</p>
</blockquote>
<ul>
<li>First select the wallet we want to lookup
<ul>
<li><code>SELECT id, address FROM wallets w WHERE w.id = 1</code></li>
</ul>
</li>
<li>Select all the cards of this wallet
<ul>
<li><code>SELECT company, color FROM cards c WHERE c.wallet_id = w.id</code></li>
</ul>
</li>
<li>Merge these two queries with INNER JOIN
<ul>
<li><code>SELECT id, address FROM wallets w INNER JOIN cards c ON w.id = c.id WHERE w.id = 1 GROUP BY id</code></li>
</ul>
</li>
</ul>
<blockquote>
<p>Now i need to merge the result of the query above with other wallets that have the same cards</p>
</blockquote>
<p>... Here's where i cant proceed, im confused on how to do this :c</p>
| [
{
"answer_id": 74328559,
"author": "Nathan Furnal",
"author_id": 9479128,
"author_profile": "https://Stackoverflow.com/users/9479128",
"pm_score": 2,
"selected": false,
"text": "str.replace(/(\\$\\{\\d\\})/g, '<span>$1</span>')\n"
},
{
"answer_id": 74329958,
"author": "MikeM",
"author_id": 1565512,
"author_profile": "https://Stackoverflow.com/users/1565512",
"pm_score": 2,
"selected": true,
"text": "let str = '${1}${2}${3}${4}%9${5}00';\n\nstr = str.replace(/\\$\\{\\d+\\}|[\\d/+()%*v-]/g, '<span>$&</span>');\n\nconsole.log(str);"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74328533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15781720/"
] |
74,328,544 | <p>Let's assume we create a Ternary tree using an array implementation. The root is stored in the index 1, the left child is stored in index = 3(index)-1, middle child is stored in 3(index), and right child is stored in 3(index)+1. So for example. Assume the following Ternary Tree.</p>
<pre><code> A
B C D
E F G H I J K L M
</code></pre>
<p>The array implementation would be <code>[None, A, B, C, D, E, F, G, H, I, J, K, L, M]</code></p>
<p>If we take F for random, F is the middle child go B, and B is the left child of A. A has an index of 1, so B has an index of 2, so F has an index of 6.</p>
<p>My question is, how can I get the depth from the indexes. F has an index of 6 and a depth of 2. If this was a binary tree, the depth would simply be equal to <code>int(math.log(index, 2))</code>. What is the equation for the depth for a ternary tree, I can't think of any.</p>
| [
{
"answer_id": 74328559,
"author": "Nathan Furnal",
"author_id": 9479128,
"author_profile": "https://Stackoverflow.com/users/9479128",
"pm_score": 2,
"selected": false,
"text": "str.replace(/(\\$\\{\\d\\})/g, '<span>$1</span>')\n"
},
{
"answer_id": 74329958,
"author": "MikeM",
"author_id": 1565512,
"author_profile": "https://Stackoverflow.com/users/1565512",
"pm_score": 2,
"selected": true,
"text": "let str = '${1}${2}${3}${4}%9${5}00';\n\nstr = str.replace(/\\$\\{\\d+\\}|[\\d/+()%*v-]/g, '<span>$&</span>');\n\nconsole.log(str);"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74328544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17430837/"
] |
74,328,577 | <p>I create an arrayList and set all it's elements to 0</p>
<p>When all elements are set to 1, I try to turn them all back to 0 with a lambda and only the first 2 indices are changed.</p>
<pre class="lang-java prettyprint-override"><code>// create a list freeFrames, size 5, all elements set to 0:
List<Integer> freeFrame = new ArrayList<Integer>(Collections.nCopies(5, 0));
// freeFrame= [0, 0, 0, 0, 0]
// code executes and eventually freeFrame =[1, 1, 1, 1, 1]
// try to change all values to 0 if none are present
if(!freeFrame.contains(0))
freeFrame.forEach((b) -> freeFrame.set(b, 0));
// freeFrame= [0, 0, 1, 1, 1]
</code></pre>
<p>I ended up using a standard loop. Why are only the first 2 indexes getting changed with the above?
This post seemed close <a href="https://stackoverflow.com/a/20040292/20419870">https://stackoverflow.com/a/20040292/20419870</a> but I don't think I'm changing the size of the list, just changing the values. This one <a href="https://stackoverflow.com/a/56399619/20419870">https://stackoverflow.com/a/56399619/20419870</a> suggests to use stream and map to safely modify the list while iterating. I had thought only removing and adding to list while iterating was unsafe, does modifying the contents cause an exception I'm not seeing?</p>
| [
{
"answer_id": 74328789,
"author": "vinsce",
"author_id": 3811895,
"author_profile": "https://Stackoverflow.com/users/3811895",
"pm_score": 2,
"selected": true,
"text": "forEach"
},
{
"answer_id": 74328820,
"author": "sanurah",
"author_id": 4079056,
"author_profile": "https://Stackoverflow.com/users/4079056",
"pm_score": 0,
"selected": false,
"text": "if(!freeFrame.contains(0)) freeFrame.forEach((b) -> freeFrame.set(b, 0));\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74328577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20419870/"
] |
74,328,599 | <p>I have a <code>base.html</code> template file for Django (4.1.2) as:</p>
<pre><code><!DOCTYPE html>
<html lang="en">
{% load static %}
{% load i18n %}
<head>
<meta charset="utf-8">
{% block title %}
<title>My Title</title>
{% endblock %}
</head>
<body>
{% block content %}
{% endblock content %}
</body>
</html>
</code></pre>
<p>and an <code>index.html</code> page, at the same level in the <code>/templates</code> folder of my app, extending the base one, as:</p>
<pre><code>{% extends "base.html" %}
{% block content %}
<h1>My Django project</h1>
<ul>
<li><a href="/admin">{% trans "Admin" %}</a></li>
<li><a href="{% url 'foo' %}">{% trans "Foo" %}</a></li>
</ul>
{% endblock %}
</code></pre>
<p>But when I browse the latter page, the server returns the following error:</p>
<pre><code>django.template.exceptions.TemplateSyntaxError:
Invalid block tag on line 6:
'trans', expected 'endblock'.
Did you forget to register or load this tag?
</code></pre>
<p>But if I simply add <code>{% load i18n %}</code> at the second line of the <code>index.html</code>, the page loads fine.</p>
<p>What is wrong with the loading of the base template in the index.html page?</p>
<p><a href="https://stackoverflow.com/questions/20560222/is-it-possible-to-load-a-custom-template-tag-in-base-and-use-it-in-extented-temp">This</a> doesn't help as it doesn't differentiate the behaviour encountered here with the fact that loading, e.g. <code>{% load django_bootstrap5 %}</code> in <code>base.html</code> is working very well through <em>all</em> child pages without having to ever specify it again in those pages.</p>
| [
{
"answer_id": 74328789,
"author": "vinsce",
"author_id": 3811895,
"author_profile": "https://Stackoverflow.com/users/3811895",
"pm_score": 2,
"selected": true,
"text": "forEach"
},
{
"answer_id": 74328820,
"author": "sanurah",
"author_id": 4079056,
"author_profile": "https://Stackoverflow.com/users/4079056",
"pm_score": 0,
"selected": false,
"text": "if(!freeFrame.contains(0)) freeFrame.forEach((b) -> freeFrame.set(b, 0));\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74328599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6630397/"
] |
74,328,605 | <p>I'm very new to R, and I heard it's best to replace loops with apply functions, however I couldn't wrap my head around on how to transform my loop with this example. Any help would be appreciated.</p>
<pre><code>file_path is a list of file names
file_path[1] = "/home/user/a.rds"
file_path[2] = "/home/user/b.rds"
...
vector_sum <- rep(0,50000)
for(i in 1:5){
temp_data <- readRDS(file_path[i])
temp_data <- as.matrix(temp_data[,c("loss_amount")])
vector_sum <- vector_sum + temp_data
}
</code></pre>
<p>My goal is to loop through all the files, in each file only keep loss_amount column and add it to vector_sum, so in the end vector_sum is the sum of all loss_amount columns from all files</p>
| [
{
"answer_id": 74328789,
"author": "vinsce",
"author_id": 3811895,
"author_profile": "https://Stackoverflow.com/users/3811895",
"pm_score": 2,
"selected": true,
"text": "forEach"
},
{
"answer_id": 74328820,
"author": "sanurah",
"author_id": 4079056,
"author_profile": "https://Stackoverflow.com/users/4079056",
"pm_score": 0,
"selected": false,
"text": "if(!freeFrame.contains(0)) freeFrame.forEach((b) -> freeFrame.set(b, 0));\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74328605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20426162/"
] |
74,328,620 | <p>I have following nested object as state.</p>
<pre><code>interface name {
firstName: string;
lastName: string;
}
type NameType = name;
interface employer {
name: string;
state: string;
}
type EmployerType = employer;
interface person {
name: NameType;
age: number;
employer: EmployerType;
}
type PersonType = person;
const defaultPerson: PersonType = {
name: {
firstName: "The",
lastName: "Rock"
},
age: 25,
employer: {
name: "Noone",
state: "Nowhere"
}
};
</code></pre>
<p>To update the nested object in state when I use [...] spread operator at second level in case of useState hook, it works just as expected <a href="https://codesandbox.io/s/goofy-ardinghelli-l73zkr" rel="nofollow noreferrer">See this working code.</a></p>
<pre><code>export default function App() {
const [person, setPerson] = useState<PersonType>(defaultPerson);
function handleInputChange(input: string) {
setPerson({
...person,
name: {
...person.name,
firstName: input
}
});
}
return (
<div className="App">
<input onChange={(e) => handleInputChange(e.target.value)} />
<h2>{JSON.stringify(person, null, 4)}</h2>
</div>
);
}
</code></pre>
<p>But if I do same thing with a reducer and useReducer hook, Typescript is not liking it and gives error that I am not able to understand. The type error can be seen in codesandbox. <a href="https://codesandbox.io/s/stoic-scooby-rr3q06?file=/src/App.tsx" rel="nofollow noreferrer">See this broken code.</a></p>
<pre><code>interface action {
type: string;
fieldName: string;
value: string | number;
}
type ActionType = action;
function reducer(state: PersonType, action: ActionType) {
switch (action.type) {
case "firstName": {
return {
...state,
name: {
...state.name,
firstName: action.value
}
};
}
}
return state;
}
export default function App() {
const [person, dispatch] = useReducer(reducer, defaultPerson);
return (
<div className="App">
<input
onChange={(e) =>
dispatch({
type: "test",
fieldName: "firstName",
value: e.target.value
})
}
/>
<h2>{JSON.stringify(person, null, 4)}</h2>
</div>
);
}
</code></pre>
<p>Though I am able to cope the state to an entirely new object and update that new object instead, but that feels like a hack and not the right way.</p>
<pre><code>const newState = {...state}
const newName = {...newState.name}
newName.firstName = action.value
newState.name = newName
return newState
</code></pre>
| [
{
"answer_id": 74328789,
"author": "vinsce",
"author_id": 3811895,
"author_profile": "https://Stackoverflow.com/users/3811895",
"pm_score": 2,
"selected": true,
"text": "forEach"
},
{
"answer_id": 74328820,
"author": "sanurah",
"author_id": 4079056,
"author_profile": "https://Stackoverflow.com/users/4079056",
"pm_score": 0,
"selected": false,
"text": "if(!freeFrame.contains(0)) freeFrame.forEach((b) -> freeFrame.set(b, 0));\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74328620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2353460/"
] |
74,328,660 | <p>I have this as an object (indiErr):</p>
<pre><code>[
{ errorType: 'color-contrast', errorImpact: 'serious', errorCount: 8 },
{ errorType: 'heading-order', errorImpact: 'moderate', errorCount: 1 },
{ errorType: 'image-alt', errorImpact: 'critical', errorCount: 1 },
{ errorType: 'image-redundant-alt', errorImpact: 'minor', errorCount: 1},
{ errorType: 'landmark-no-duplicate-contentinfo', errorImpact: 'moderate', errorCount: 1},
{ errorType: 'landmark-unique', errorImpact: 'moderate', errorCount: 1 },
{ errorType: 'link-name', errorImpact: 'serious', errorCount: 7 },
{ errorType: 'meta-viewport', errorImpact: 'critical', errorCount: 1 },
{ errorType: 'region', errorImpact: 'moderate', errorCount: 30 },
{ errorType: 'tabindex', errorImpact: 'serious', errorCount: 18 },
{ errorType: 'color-contrast', errorImpact: 'serious', errorCount: 28 },
{ errorType: 'landmark-one-main', errorImpact: 'moderate', errorCount: 1 },
{ errorType: 'page-has-heading-one', errorImpact: 'moderate', errorCount: 1
}
]
</code></pre>
<p>With the following code I deduplicate items and sum the errorCount:</p>
<pre><code> const holder = {};
indiErr.forEach(function(d) {
if (holder.hasOwnProperty(d.errorType)) {
holder[d.errorType] = holder[d.errorType] + d.errorCount;
// d.errorImpact= d.errorImpact
// holder[d.errorImpact] = d.errorImpact
} else {
holder[d.errorType] = d.errorCount;
// d.errorImpact= d.errorImpact
// holder[d.errorImpact] = d.errorImpact
}
});
console.log('holder:', holder)
const obj2 = [];
for (const prop in holder) {
obj2.push({ errorType: prop, errorCount: holder[prop] });
}
console.log('Error Object:', obj2);
</code></pre>
<p>In the deduplication the values for 'errorImpact' get lost. This is the result:</p>
<pre><code>Error Object: [
{ errorType: 'color-contrast', errorCount: 36 },
{ errorType: 'heading-order', errorCount: 1 },
{ errorType: 'image-alt', errorCount: 1 },
{ errorType: 'image-redundant-alt', errorCount: 1 },
{ errorType: 'landmark-no-duplicate-contentinfo', errorCount: 1 },
{ errorType: 'landmark-unique', errorCount: 1 },
{ errorType: 'link-name', errorCount: 7 },
{ errorType: 'meta-viewport', errorCount: 1 },
{ errorType: 'region', errorCount: 30 },
{ errorType: 'tabindex', errorCount: 18 },
{ errorType: 'landmark-one-main', errorCount: 1 },
{ errorType: 'page-has-heading-one', errorCount: 1 }
]
</code></pre>
<p><em>(color-contrast is deduplicated, and errorCount is summed to: 36)</em></p>
<p>Is there any way to change the forEach function to also push 'errorImpact' value to 'obj2'?
Have tried several things, but am stuck. Also don't know where to search for to solve this. Hope you have some pointers. Tnx!</p>
<p>I would like to have this as result:</p>
<pre><code>[
{ errorType: 'color-contrast', errorImpact: 'serious', errorCount: 36 },
{ errorType: 'heading-order', errorImpact: 'moderate', errorCount: 1 },
{ errorType: 'image-alt', errorImpact: 'critical', errorCount: 1 },
{ errorType: 'image-redundant-alt', errorImpact: 'minor', errorCount: 1},
{ errorType: 'landmark-no-duplicate-contentinfo', errorImpact: 'moderate', errorCount: 1},
{ errorType: 'landmark-unique', errorImpact: 'moderate', errorCount: 1 },
{ errorType: 'link-name', errorImpact: 'serious', errorCount: 7 },
{ errorType: 'meta-viewport', errorImpact: 'critical', errorCount: 1 },
{ errorType: 'region', errorImpact: 'moderate', errorCount: 30 },
{ errorType: 'tabindex', errorImpact: 'serious', errorCount: 18 },
{ errorType: 'landmark-one-main', errorImpact: 'moderate', errorCount: 1 },
{ errorType: 'page-has-heading-one', errorImpact: 'moderate', errorCount: 1
}
]
</code></pre>
| [
{
"answer_id": 74329065,
"author": "Andrew Parks",
"author_id": 5898421,
"author_profile": "https://Stackoverflow.com/users/5898421",
"pm_score": 0,
"selected": false,
"text": "const errors = [\n { errorType: 'color-contrast', errorImpact: 'serious', errorCount: 8 },\n { errorType: 'heading-order', errorImpact: 'moderate', errorCount: 1 },\n { errorType: 'image-alt', errorImpact: 'critical', errorCount: 1 },\n { errorType: 'image-redundant-alt', errorImpact: 'minor', errorCount: 1},\n { errorType: 'landmark-no-duplicate-contentinfo', errorImpact: 'moderate', errorCount: 1},\n { errorType: 'landmark-unique', errorImpact: 'moderate', errorCount: 1 },\n { errorType: 'link-name', errorImpact: 'serious', errorCount: 7 },\n { errorType: 'meta-viewport', errorImpact: 'critical', errorCount: 1 },\n { errorType: 'region', errorImpact: 'moderate', errorCount: 30 },\n { errorType: 'tabindex', errorImpact: 'serious', errorCount: 18 },\n { errorType: 'color-contrast', errorImpact: 'serious', errorCount: 28 },\n { errorType: 'landmark-one-main', errorImpact: 'moderate', errorCount: 1 },\n { errorType: 'page-has-heading-one', errorImpact: 'moderate', errorCount: 1\n }\n];\n\nlet r = {};\nerrors.forEach(({errorType,errorImpact,errorCount})=>\n (r[errorType]??= {errorType, errorImpact, errorCount:0}).errorCount += errorCount);\nconsole.log(Object.values(r));"
},
{
"answer_id": 74329480,
"author": "Jan Willem",
"author_id": 15058684,
"author_profile": "https://Stackoverflow.com/users/15058684",
"pm_score": 2,
"selected": false,
"text": "const holder = {};\n\n indiErr.forEach(function(d) {\n if (!holder.hasOwnProperty(d.errorType)) {\n holder[d.errorType] = {errorImpact: d.errorImpact, errorCount: 0};\n }\n holder[d.errorType].errorCount+=d.errorCount\n });\n\nconsole.log('holder:', holder)\nconst obj2 = [];\n\nfor (const prop in holder) {\n obj2.push({ errorType: prop, ...holder[prop] });\n }\n\nconsole.log('Error Object:', obj2);\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74328660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15058684/"
] |
74,328,667 | <p>I have a form with 2 input elements and I want to get value with i. But the value is nan.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let inputN1 = parseInt(document.getElementById("input_number1").value)
let inputN2 = parseInt(document.getElementById("input_number2").value)</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="myForm">
<input type="text" id="input_number1" style="margin-left:430px">
<input type="text" id="input_number2">
</form></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74328721,
"author": "Dharmik_403",
"author_id": 19864266,
"author_profile": "https://Stackoverflow.com/users/19864266",
"pm_score": -1,
"selected": false,
"text": "parseInt()"
},
{
"answer_id": 74328741,
"author": "majusebetter",
"author_id": 16305607,
"author_profile": "https://Stackoverflow.com/users/16305607",
"pm_score": 1,
"selected": false,
"text": "function printValues() {\n let inputN1 = parseInt(document.getElementById(\"input_number1\").value);\n let inputN2 = parseInt(document.getElementById(\"input_number2\").value);\n console.log(\"inputN1: \" + inputN1);\n console.log(\"inputN2: \" + inputN2);\n}"
},
{
"answer_id": 74328803,
"author": "MatthiasDunkel",
"author_id": 13728674,
"author_profile": "https://Stackoverflow.com/users/13728674",
"pm_score": 0,
"selected": false,
"text": "let inputN1 = document.getElementById(\"input_number1\")\ninputN1.addEventListener(\"input\", (ev) => {\n console.log(ev.target.value);\n});\n"
},
{
"answer_id": 74328817,
"author": "Shreyansh Gupta",
"author_id": 18046485,
"author_profile": "https://Stackoverflow.com/users/18046485",
"pm_score": 1,
"selected": false,
"text": "function getvalue() {\n let inputN1 = parseInt(document.getElementById(\"input_number1\").value);\n console.log(\"inputN1: \" + inputN1);\n}"
},
{
"answer_id": 74328824,
"author": "Acodecs",
"author_id": 20021407,
"author_profile": "https://Stackoverflow.com/users/20021407",
"pm_score": 0,
"selected": false,
"text": "document.getElementById(\"submit\").onclick = function() {\n let inputN1 = parseInt(document.getElementById(\"input_number1\").value)\n let inputN2 = parseInt(document.getElementById(\"input_number2\").value)\n}\n\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74328667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19220799/"
] |
74,328,692 | <p>Is there a way to create a sequence that replicates itself excluding the last element without a loop? Say we have a starting sequence <code>4:1</code> and the function <code>fun</code> that generates the rest of the sequence like:</p>
<pre><code>> fun(4:1)
[1] 4 3 2 1 4 3 2 4 3 4
</code></pre>
| [
{
"answer_id": 74328805,
"author": "danlooo",
"author_id": 16853114,
"author_profile": "https://Stackoverflow.com/users/16853114",
"pm_score": 0,
"selected": false,
"text": "fun <- function(x) {\n x |>\n length() |>\n seq() |>\n sapply(function(y) x[1:y]) |>\n rev() |>\n purrr::simplify()\n}\n\nfun(4:1)\n#> [1] 4 3 2 1 4 3 2 4 3 4\n"
},
{
"answer_id": 74328856,
"author": "B. Christian Kamgang",
"author_id": 10848898,
"author_profile": "https://Stackoverflow.com/users/10848898",
"pm_score": 1,
"selected": false,
"text": "v = 4:1\nunlist(lapply(4:1, rep_len, x=rev(seq_along(v)))\n\n[1] 4 3 2 1 4 3 2 4 3 4\n"
},
{
"answer_id": 74328949,
"author": "jay.sf",
"author_id": 6574038,
"author_profile": "https://Stackoverflow.com/users/6574038",
"pm_score": 2,
"selected": false,
"text": "sequence"
},
{
"answer_id": 74329070,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 1,
"selected": false,
"text": "matrix"
},
{
"answer_id": 74329416,
"author": "Gregor Thomas",
"author_id": 903061,
"author_profile": "https://Stackoverflow.com/users/903061",
"pm_score": 1,
"selected": false,
"text": "head()"
},
{
"answer_id": 74332288,
"author": "M.Viking",
"author_id": 10276092,
"author_profile": "https://Stackoverflow.com/users/10276092",
"pm_score": 1,
"selected": false,
"text": "sequence()"
},
{
"answer_id": 74334283,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 2,
"selected": false,
"text": "sequence"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74328692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17720640/"
] |
74,328,702 | <p>Could someone tell me if im right about what these parts of the code do:</p>
<p>This is JSON to string conversion?</p>
<pre><code>factory Post.fromJson(Map<String, dynamic> json) => Post(
userId: json["userId"],
id: json["id"],
title: json["title"],
body: json["body"],
);
</code></pre>
<p>And this would be string to JSON conversion?</p>
<pre><code>Map<String, dynamic> toJson() => {
"userId": userId,
"id": id,
"title": title,
"body": body,
};
</code></pre>
| [
{
"answer_id": 74328805,
"author": "danlooo",
"author_id": 16853114,
"author_profile": "https://Stackoverflow.com/users/16853114",
"pm_score": 0,
"selected": false,
"text": "fun <- function(x) {\n x |>\n length() |>\n seq() |>\n sapply(function(y) x[1:y]) |>\n rev() |>\n purrr::simplify()\n}\n\nfun(4:1)\n#> [1] 4 3 2 1 4 3 2 4 3 4\n"
},
{
"answer_id": 74328856,
"author": "B. Christian Kamgang",
"author_id": 10848898,
"author_profile": "https://Stackoverflow.com/users/10848898",
"pm_score": 1,
"selected": false,
"text": "v = 4:1\nunlist(lapply(4:1, rep_len, x=rev(seq_along(v)))\n\n[1] 4 3 2 1 4 3 2 4 3 4\n"
},
{
"answer_id": 74328949,
"author": "jay.sf",
"author_id": 6574038,
"author_profile": "https://Stackoverflow.com/users/6574038",
"pm_score": 2,
"selected": false,
"text": "sequence"
},
{
"answer_id": 74329070,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 1,
"selected": false,
"text": "matrix"
},
{
"answer_id": 74329416,
"author": "Gregor Thomas",
"author_id": 903061,
"author_profile": "https://Stackoverflow.com/users/903061",
"pm_score": 1,
"selected": false,
"text": "head()"
},
{
"answer_id": 74332288,
"author": "M.Viking",
"author_id": 10276092,
"author_profile": "https://Stackoverflow.com/users/10276092",
"pm_score": 1,
"selected": false,
"text": "sequence()"
},
{
"answer_id": 74334283,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 2,
"selected": false,
"text": "sequence"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74328702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17349296/"
] |
74,328,755 | <p>Hi i am new to python and i have a little problems with my code.</p>
<pre><code>def Sumn(mylist):
i = 0
sum = 0
for i in mylist[1]:
sum += mylist[i]
return sum
i+=1
</code></pre>
<pre><code>import myFunctions
mylist = [6, 12, 645, 3, -8]
print(myFunctions.Sumn(mylist))
</code></pre>
<p>I was expecting that the numbers from the list will add and then the anwser will get printed</p>
| [
{
"answer_id": 74328784,
"author": "maciek97x",
"author_id": 10626495,
"author_profile": "https://Stackoverflow.com/users/10626495",
"pm_score": 2,
"selected": false,
"text": "for"
},
{
"answer_id": 74328795,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 2,
"selected": false,
"text": "def Sumn(mylist):\n i = 0 # this variable is unused\n sum = 0 # variable name overrides builtin 'sum' function\n for i in mylist[1]: # this will error because mylist[1] is a single int\n sum += mylist[i] # this only works if i is an index of mylist\n return sum # returns in first iteration\n i+=1 # this variable still isn't used for anything\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74328755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20426212/"
] |
74,328,787 | <p>I'm teaching myself CRUD in MERN stack and I've come across a bug. The onClick inside GET function is not firing, it only fires after multiple times of clicking.
Here's the code:</p>
<p>`</p>
<pre><code>function GetData() {
try{
useEffect(()=>{
axios.get('http://localhost:3000/app/profile', {
})
.then((response)=>{
const userdata = response.data;
setUser(userdata)
console.log(userdata)
})
},[])
if (User.length > 0){
try{
return User.map((user) => {
return(
<div style={{ display:'flex', marginTop:'1em'}}>
<div style={{ marginLeft:'15em', width:'500px'}}>
<h style={h2}>{user.name}</h>
</div>
<div style={{ width:'350px' }}>
<h style={h2}>{user.email}</h>
</div>
<div>
<button onClick={()=>{alert('update');}}>UPDATE</button>
<button onClick={()=>{alert('delete');}}>DELETE</button>
</div>
</div>
);
})
} catch(e){
console.log(e)
}
}
} catch(e){
console.log(e)
}
}
</code></pre>
<p>`</p>
<p>I spent a whole day looking for a solution but the problem is still there.
Here' my package.json:</p>
<p>`</p>
<pre><code>{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.1.3",
"bootstrap": "^5.2.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@babel/preset-react": "^7.18.6"
}
}
</code></pre>
<p>`</p>
<p>Also just for testing, when I place the buttons outside on the GET function they work fine. But they won't work inside GET where I need them to be placed.</p>
| [
{
"answer_id": 74328784,
"author": "maciek97x",
"author_id": 10626495,
"author_profile": "https://Stackoverflow.com/users/10626495",
"pm_score": 2,
"selected": false,
"text": "for"
},
{
"answer_id": 74328795,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 2,
"selected": false,
"text": "def Sumn(mylist):\n i = 0 # this variable is unused\n sum = 0 # variable name overrides builtin 'sum' function\n for i in mylist[1]: # this will error because mylist[1] is a single int\n sum += mylist[i] # this only works if i is an index of mylist\n return sum # returns in first iteration\n i+=1 # this variable still isn't used for anything\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74328787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20426302/"
] |
74,328,810 | <p>When trying to set a value in a 2D array like this:</p>
<pre><code>let a = Array.make 5 (Array.make 5 0);;
a.(0).(0) <- 4;
</code></pre>
<p>It will for some reason put <code>4</code> at index <code>j</code> in every array contained in the 2D array <code>a</code>.</p>
<p>Why is this, and how do i get it to only set <code>a[i][j]</code> to <code>4</code>?</p>
| [
{
"answer_id": 74329073,
"author": "glennsl",
"author_id": 7943564,
"author_profile": "https://Stackoverflow.com/users/7943564",
"pm_score": 3,
"selected": false,
"text": "let inner = Array.make 5 0 in\nlet outer = Array.make 5 inner in\ninner.(0) <- 4\n"
},
{
"answer_id": 74332225,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 0,
"selected": false,
"text": "let arr =\n let x = ref 5 in\n Array.make 5 x\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74328810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15026297/"
] |
74,328,826 | <p><a href="https://i.stack.imgur.com/TuM9Y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TuM9Y.png" alt="enter image description here" /></a></p>
<p>I want to center the image on the right vertically, so that it is centered between the two green titles, can somebody help me with this?</p>
<p>my CSS code:</p>
<pre><code>.vorigejaren img {
width: 25%;
height: auto;
float: right;
}
.vorigejaren p {
display: inline;
}
</code></pre>
<p>My HTML code:</p>
<pre><code><div class="vorigejaren">
<img src="../fotos/leden/Praesidium/Groepsfoto_2022_aangepast.jpg" alt="foto">
<p><?php echo $jaar['leden']; ?></p>
</div>
</code></pre>
<p>I tried looking it up on the internet, but noru-yhing seemed to work...</p>
| [
{
"answer_id": 74329190,
"author": "Aymen Missaoui",
"author_id": 14157115,
"author_profile": "https://Stackoverflow.com/users/14157115",
"pm_score": 2,
"selected": true,
"text": "You can try this:\n\n\n\n .vorigejaren {\n display:flex;\n justify-content: center;\n }\n\nimg {\n margin:auto;}\n"
},
{
"answer_id": 74329353,
"author": "Ken Lee",
"author_id": 11854986,
"author_profile": "https://Stackoverflow.com/users/11854986",
"pm_score": 0,
"selected": false,
"text": "<div style=\"display:flex;flex-direction:row;\">\n\n<div style=\"width:50%;float:left;\">\n<ul>\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse \n\n</ul>\n</div>\n\n<div style=\"width:50%;float:center;text-align:center;align-self:center;\">\n <img src=\"https://i.stack.imgur.com/IGD9N.jpg\" style=\"width:150px;\">\n</div>\n\n</div>\n\n\n<div style=\"display:flex;flex-direction:row;\">\n\n<div style=\"width:50%;float:left;\">\n<ul>\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse \n\n</ul>\n</div>\n\n<div style=\"width:50%;float:center;text-align:center;align-self:center;\">\n <img src=\"https://i.stack.imgur.com/IGD9N.jpg\" style=\"width:150px;\">\n</div>\n\n</div>"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74328826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20426320/"
] |
74,328,831 | <p>I'm working on a MSTest project which has a reference to a .NET 6.0 project.</p>
<p>I'd like to use Moq for constructing unit tests.</p>
<p>In my .Net project I have an interface <code>IDataAccees</code> with a method declaration which has the following signature:</p>
<pre><code>Task<(TypeA, Resource[,])> LoadAsync(Int32 size);
</code></pre>
<p><code>FileDataAccess</code> class implements this interface. Inside
the class definition there's the <code>LoadAsync</code> implementation as well.</p>
<pre><code>public async Task<(TypeA, Resource[,])> LoadAsync(Int32 size)
{
...
}
</code></pre>
<p>private fields in my UnitTest.cs file:</p>
<pre><code>private Resource[,] _mockedTable = null!;
private Mock<IDataAccess> _mock = null!;
private TypeA _a = null;
</code></pre>
<p>I'd like to correct / complete the statement <code>_mock.Setup(...)</code> seen below inside my Unittest.cs file in order to establish the appropriate Moq-management of my <code>LoadAsync()</code> method, however I have doubts about this.</p>
<pre><code>_mockedTable = new Resource[100, 100];
_mock = new Mock<IDataAccess>();
_mock.Setup(mock => mock.LoadAsync(It.IsAny<Int32>()))
.Returns(() => Task.FromResult( ));
</code></pre>
| [
{
"answer_id": 74329190,
"author": "Aymen Missaoui",
"author_id": 14157115,
"author_profile": "https://Stackoverflow.com/users/14157115",
"pm_score": 2,
"selected": true,
"text": "You can try this:\n\n\n\n .vorigejaren {\n display:flex;\n justify-content: center;\n }\n\nimg {\n margin:auto;}\n"
},
{
"answer_id": 74329353,
"author": "Ken Lee",
"author_id": 11854986,
"author_profile": "https://Stackoverflow.com/users/11854986",
"pm_score": 0,
"selected": false,
"text": "<div style=\"display:flex;flex-direction:row;\">\n\n<div style=\"width:50%;float:left;\">\n<ul>\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse \n\n</ul>\n</div>\n\n<div style=\"width:50%;float:center;text-align:center;align-self:center;\">\n <img src=\"https://i.stack.imgur.com/IGD9N.jpg\" style=\"width:150px;\">\n</div>\n\n</div>\n\n\n<div style=\"display:flex;flex-direction:row;\">\n\n<div style=\"width:50%;float:left;\">\n<ul>\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse\n<li>Vice-prases: Tibe VanHaudenhuyse \n\n</ul>\n</div>\n\n<div style=\"width:50%;float:center;text-align:center;align-self:center;\">\n <img src=\"https://i.stack.imgur.com/IGD9N.jpg\" style=\"width:150px;\">\n</div>\n\n</div>"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74328831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12470264/"
] |
74,328,832 | <p>Consider a 2D square tiled grid (chess board like) which contains conveyor belt like structures that can curve and move game pieces around.</p>
<p>I need to calculate the <em>turn movement</em> (<code>TURN_LEFT</code>, <code>TURN_RIGHT</code> or <code>STAY</code>), depending on</p>
<ol>
<li>the direction from which a piece moves <em>onto</em> the field</li>
<li>the direction from which the underlying belt <em>exits</em> the field</li>
</ol>
<p>Example:</p>
<pre><code> 1 2
1 |>X>|>v |
2 | | v |
</code></pre>
<p>The belt makes a <code>RIGHT</code> turn. As such, the result of <code>calcTurn(LEFT, DOWN)</code> should be <code>TURN_RIGHT</code>. Meaning the <code>X</code> game piece will be rotated 90° right when it moves over the curve at <code>(1,2)</code>.</p>
<p>I already implemented a function but it only works on <em>some</em> of my test cases.</p>
<pre><code>enum class Direction {
NONE,
UP,
RIGHT,
DOWN,
LEFT;
fun isOpposite(other: Direction) = this == UP && other == DOWN
|| this == DOWN && other == UP
|| this == LEFT && other == RIGHT
|| this == RIGHT && other == LEFT
}
data class Vec2(val x: Float, val y: Float)
fun Direction.toVec2() = when (this) {
Direction.NONE -> Vec2(0f, 0f)
Direction.UP -> Vec2(0f, 1f)
Direction.RIGHT -> Vec2(1f, 0f)
Direction.DOWN -> Vec2(0f, -1f)
Direction.LEFT -> Vec2(-1f, 0f)
}
fun getTurnMovement(incomingDirection: Direction, outgoingDirection: Direction): Movement {
if (incomingDirection.isOpposite(outgoingDirection) || incomingDirection == outgoingDirection) {
return Movement.STAY
}
val incVec = incomingDirection.toVec2()
val outVec = outgoingDirection.toVec2()
val angle = atan2(
incVec.x * outVec.x - incVec.y * outVec.y,
incVec.x * outVec.x + incVec.y * outVec.y
)
return when {
angle < 0 -> Movement.TURN_RIGHT
angle > 0 -> Movement.TURN_LEFT
else -> Movement.STAY
}
}
</code></pre>
<p>I can't quite figure out what's going wrong here, especially not because <em>some</em> test cases work (like <code>DOWN+LEFT=TURN_LEFT</code>) but others don't (like <code>DOWN+RIGHT=STAY</code> instead of <code>TURN_LEFT</code>)</p>
| [
{
"answer_id": 74330128,
"author": "Simon Jacobs",
"author_id": 10928439,
"author_profile": "https://Stackoverflow.com/users/10928439",
"pm_score": 3,
"selected": true,
"text": "val angle = atan2(outVec.y, outVec.x) - atan2(incVec.y, incVec.x)\n"
},
{
"answer_id": 74330879,
"author": "cactustictacs",
"author_id": 13598222,
"author_profile": "https://Stackoverflow.com/users/13598222",
"pm_score": 2,
"selected": false,
"text": "enum class Direction {\n \n UP, RIGHT, DOWN, LEFT;\n \n companion object {\n // storing thing means you only need to generate the array once\n private val directions = values()\n private fun getPositionWrapped(pos: Int) = directions[(pos).mod(directions.size)]\n }\n \n // using getters here as a general example\n val toLeft get() = getPositionWrapped(ordinal - 1)\n val toRight get() = getPositionWrapped(ordinal + 1)\n val opposite get() = getPositionWrapped(ordinal + 2)\n}\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74328832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/204693/"
] |
74,328,834 | <p>I made rock paper scissors game with score counter. Although it works well, I realized that the code is too heavy.</p>
<pre class="lang-py prettyprint-override"><code>import random
game = 3
userScore = 0
computerScore = 0
while game != 0:
print(f"game left : {game}")
user = input("'r' for rock, 'p' for paper and 's' for scissors : ")
computer = random.choice(['r', 'p', 's'])
if user != computer:
if user == 'p' and computer == 'r' or user == 's' and computer == 'p' or user == 'r' and computer == 's':
userScore += 1
else:
computerScore += 1
else:
userScore += 0
computerScore += 0
print(f"you({userScore}) : {user} & computer({computerScore}) : {computer}\n")
game -= 1
if userScore > computerScore:
print("You Won")
elif computerScore > userScore:
print("You Lost")
else:
print("Drawn")
</code></pre>
<p>I am trying to clean up this code so that it is more readable and soft.</p>
| [
{
"answer_id": 74328932,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 2,
"selected": true,
"text": "# use 'for' and 'range' to iterate over a sequence of numbers\nfor game in range(3, 0, -1):\n\n print(f\"game left : {game}\")\n user = input(\"'r' for rock, 'p' for paper and 's' for scissors : \")\n # an iterable of single-character strings can be swapped for a single string\n computer = random.choice('rps')\n\n if user != computer:\n # use 'in' to concisely test a bunch of different possibilities\n if user + computer in ('pr', 'sp', 'rs'):\n userScore += 1\n else:\n computerScore += 1\n # eliminate 'else' that doesn't do anything\n\n print(f\"you({userScore}) : {user} & computer({computerScore}) : {computer}\\n\")\n"
},
{
"answer_id": 74329945,
"author": "Right.Orphée",
"author_id": 20426298,
"author_profile": "https://Stackoverflow.com/users/20426298",
"pm_score": 0,
"selected": false,
"text": "import random\n\ngame = 3\nuserScore = 0\ncomputerScore = 0\n\nwhile game > 0:\n print(f\"game left : {game}\")\n user = input(\"'r' for rock, 'p' for paper and 's' for scissors : \")\n computer = random.choice('rps')\n if user in 'rps': \n if user != computer:\n if user + computer in ('pr', 'sp', 'rs'): \n userScore += 1\n else:\n computerScore += 1\n print(f\"you({userScore}): {user} | computer({computerScore}): {computer}\\n\")\n game -= 1\n else:\n print(f\"'{user}' is not valid, try again\")\n\nif userScore > computerScore:\n print(\"You Won\")\nelif computerScore > userScore: \n print(\"You Lost\")\nelse:\n print(\"Drawn\")\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74328834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20426298/"
] |
74,328,938 | <p>I have data as follows:</p>
<pre><code>avec <- c("somevar", NA ,"anothervar", NA, "thisvar","thatvar", NA, "lastvar", NA )
</code></pre>
<p>All I want to do is to replace all <code>NA</code> values in <code>avec</code>, with a consecutive variable name, like <code>x001</code> to <code>x00n</code>. I thought that this would be very easy but I could not find anything on stack.</p>
<p>Desired output:</p>
<pre><code>avec <- c("somevar", "x001","anothervar", "x002", "thisvar","thatvar", "x003", "lastvar", "x004")
</code></pre>
<p>How should I do this?</p>
| [
{
"answer_id": 74328977,
"author": "danlooo",
"author_id": 16853114,
"author_profile": "https://Stackoverflow.com/users/16853114",
"pm_score": 2,
"selected": false,
"text": "\navec <- c(\"somevar\", NA ,\"anothervar\", NA, \"thisvar\",\"thatvar\", NA, \"lastvar\", NA )\nna_pos <- 1\nfor (i in avec |> length() |> seq()) {\n if (is.na(avec[[i]])) {\n avec[[i]] <- sprintf(\"X%03i\", na_pos)\n na_pos <- na_pos + 1\n }\n}\navec\n\n# [1] \"somevar\" \"X001\" \"anothervar\" \"X002\" \"thisvar\" \"thatvar\" \"X003\" \"lastvar\" \"X004\" \n"
},
{
"answer_id": 74329012,
"author": "jay.sf",
"author_id": 6574038,
"author_profile": "https://Stackoverflow.com/users/6574038",
"pm_score": 2,
"selected": false,
"text": "replace"
},
{
"answer_id": 74329039,
"author": "B. Christian Kamgang",
"author_id": 10848898,
"author_profile": "https://Stackoverflow.com/users/10848898",
"pm_score": 2,
"selected": false,
"text": "avec[is.na(avec)] = paste0(\"x00\", seq_along(avec[is.na(avec)]))\n\n[1] \"somevar\" \"x001\" \"anothervar\" \"x002\" \"thisvar\" \"thatvar\" \"x003\" \"lastvar\" \"x004\"\n"
},
{
"answer_id": 74329083,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 2,
"selected": false,
"text": "dplyr::coalesce(avec, sprintf(\"X%03i\", cumsum(is.na(avec))))\n#> [1] \"somevar\" \"X001\" \"anothervar\" \"X002\" \"thisvar\" \n#> [6] \"thatvar\" \"X003\" \"lastvar\" \"X004\"\n"
},
{
"answer_id": 74329108,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 2,
"selected": false,
"text": "library(dplyr)\n\nas.data.frame(avec) %>% \n mutate(avec = ifelse(is.na(avec), paste0(\"x00\", cumsum(is.na(avec))), avec)) %>% \n pull(avec)\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74328938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8071608/"
] |
74,328,978 | <p>Basically i have 3 tables and these tables have 3 titles on the top. Each time i click this title i want to hide the table and show it back. How can i make that happen?</p>
<p>I added a on click to each of the titles, but i can't hide only the table which belongs to this button, it's hiding all the tables? Keep in ming they are all rendered through.</p>
<p>Is there any way to find like if the indexes of the button with the indexes of the table match, then <code>display: none;</code> or something?
I tried doing it with dom.querySelectorAll, and mapped through the array but it's hiding everything.</p>
| [
{
"answer_id": 74329005,
"author": "sdev",
"author_id": 16161630,
"author_profile": "https://Stackoverflow.com/users/16161630",
"pm_score": 0,
"selected": false,
"text": "tables = [true,true,true]\n"
},
{
"answer_id": 74329538,
"author": "Vikram Singh",
"author_id": 20424966,
"author_profile": "https://Stackoverflow.com/users/20424966",
"pm_score": -1,
"selected": false,
"text": " \n const [table1, settable1] = useState(true);\n const [table2, settable2] = useState(true);\n const [table3, settable3] = useState(true);\n\nasync function table1(){\nsettable1(!table1)\n }\n\nasync function table2(){\nsettable2(!table2)\n }\nasync function table3(){\nsettable3(!table3)\n }\n\n\nreturn (\n{table1== true ? <Table1/> : null}\n{table2== true ? <Table1/> : null}\n{table3== true ? <Table1/> : null}\n)\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74328978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18174677/"
] |
74,328,986 | <p>in my laravel app I have to put the whole path of my file, like this:</p>
<pre><code>$credentialsFilePath = "C:\xampp\htdocs\myapp.com\json\myapp-dda63-firebase-adminsdk-a84ay-19eb8e8646.json"
</code></pre>
<p>However this doesn't look so good to me, in production I will have to change the string path for it to work.</p>
<p>Is there a laravel method to do something like this:</p>
<pre><code>absolutePath().'/json/myapp-dda63-firebase-adminsdk-a84ay-19eb8e8646.json'
</code></pre>
| [
{
"answer_id": 74329196,
"author": "Mohammed Jhosawa",
"author_id": 5599067,
"author_profile": "https://Stackoverflow.com/users/5599067",
"pm_score": 2,
"selected": false,
"text": "base_path()\n"
},
{
"answer_id": 74329306,
"author": "khawar Ali",
"author_id": 12719616,
"author_profile": "https://Stackoverflow.com/users/12719616",
"pm_score": 0,
"selected": false,
"text": "php"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74328986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10646944/"
] |
74,328,992 | <p>I have an existing model that was trained on Azure. I want to fully integrate and start using the model on Databricks. Whats the best way to do this? How can I successfully load the model into databricks model workflow? I have the model in a pickle file</p>
<p>I have read almost all the documentation on databricks, but 99% of it is regarding new models trained on databricks and never about importing existing models.</p>
| [
{
"answer_id": 74329196,
"author": "Mohammed Jhosawa",
"author_id": 5599067,
"author_profile": "https://Stackoverflow.com/users/5599067",
"pm_score": 2,
"selected": false,
"text": "base_path()\n"
},
{
"answer_id": 74329306,
"author": "khawar Ali",
"author_id": 12719616,
"author_profile": "https://Stackoverflow.com/users/12719616",
"pm_score": 0,
"selected": false,
"text": "php"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74328992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20044772/"
] |
74,328,997 | <p>I have a spring boot api that works with a postgresql database. My frontend is an angular application. I am working with the HttpClient. Now I always have to refrsh the website to fetch new data from my api. My question is: How can I fetch new data without refreshing the website??</p>
<p>Service:</p>
<pre><code>getMaxId() : Observable<object>
{
return this.client.get(url);
}
</code></pre>
<p>Typscript file:</p>
<pre><code>export class AktuelleWerteComponent implements OnInit {
messwerte : any;
maxId : any;
constructor(private service : MesswerteService) { }
ngOnInit(): void {
this.service.getMaxId().subscribe(data => {
this.maxId = data;
})
}
}
</code></pre>
<p>HTML file:</p>
<pre><code><p style="font-size: 50px;">{{maxId.temperatur}}°C</p>
</code></pre>
<p>I hope someone can help me with my Problem.</p>
| [
{
"answer_id": 74329704,
"author": "Eli Porush",
"author_id": 14598976,
"author_profile": "https://Stackoverflow.com/users/14598976",
"pm_score": 1,
"selected": false,
"text": "interval"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74328997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20308284/"
] |
74,329,008 | <p>I'm trying to use the Clarifai API to build a face detection app, but I'm getting no response from it. I'm new to this, and I've done just about everything to get it to work, but I'm getting no response.</p>
<p>This is my code</p>
<blockquote>
</blockquote>
<pre><code>import React, { Component } from 'react';
import Clarifai from 'clarifai';
import Navigation from "./Components/Navigation/Navigation";
import Rank from './Components/Rank/Rank';
import ImageLinkForm from "./Components/ImageLinkForm/ImageLinkForm";
import FaceDetection from './Components/FaceDetection/FaceDetection';
import Logo from './Components/Logo/Logo';
import ParticlesBg from 'particles-bg';
import './App.css';
const app = new Clarifai.App({
apiKey: 'e391552cf63245cd91a43b97168d54c7'
});
const Particles = () => {
return (
<>
<div>...</div>
<ParticlesBg
type="cobweb"
bg={true}
num={40}
/>
</>
)
};
class App extends Component {
constructor() {
super();
this.state = {
input: '',
imageUrl: ''
}
};
onInputChange = (event) => {
console.log(event.target.value)
};
onButtonClick = () => {
console.log('click');
app.models.predict("https://samples.clarifai.com/face-det.jpg%22").then(
function(response) {
console.log(response)
},
function(err) {
}
)
};
render() {
return (
<div className="App">
<Particles />
<Navigation />
<Logo />
<Rank />
<ImageLinkForm onInputChange={this.onInputChange} onButtonClick={this.onButtonClick} />
<FaceDetection />
</div>
);
};
};
export default App;
</code></pre>
<p><a href="https://i.stack.imgur.com/f5kkT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f5kkT.png" alt="And this is the response I'm looking for.. And also the click event works just fine" /></a></p>
<p>I tried switching my API key in the hopes that it was the one that wasn't working, but it still wasn't working. And also it's not throwing no error!</p>
| [
{
"answer_id": 74329890,
"author": "George A....",
"author_id": 12850027,
"author_profile": "https://Stackoverflow.com/users/12850027",
"pm_score": 0,
"selected": false,
"text": "app.models.predict(\"https://samples.clarifai.com/face-det.jpg%22\").then(response => {\n console.log(response)\n}).catch(err => {\n console.log(err)\n})\n"
},
{
"answer_id": 74522738,
"author": "cavemutt",
"author_id": 20565345,
"author_profile": "https://Stackoverflow.com/users/20565345",
"pm_score": 0,
"selected": false,
"text": "onButtonSubmit = () => {\nconsole.log('button clicked');\nthis.setState({imageUrl: this.state.input});\nconst USER_ID = 'oxxxxxxxxxx';//(the code by your name)\nconst PAT = '96d20xxxxxxxxxxxx';//(your Clarifai api key)\nconst APP_ID = 'facerec';//(what you named your app in Clarifai)\nconst MODEL_ID = 'face-detection';\nconst MODEL_VERSION_ID = '6dc7e46bc9124c5c8824be4822abe105'; \nconst IMAGE_URL = this.state.input;\nconst raw = JSON.stringify({\n \"user_app_id\": {\n \"user_id\": USER_ID,\n \"app_id\": APP_ID\n },\n \"inputs\": [{\"data\": {\"image\": {\"url\": IMAGE_URL}}}]\n});\n\nconst requestOptions = {\n method: 'POST',\n headers: {\n 'Accept': 'application/json',\n 'Authorization': 'Key ' + PAT\n }, body: raw\n};\nfetch(\"https://api.clarifai.com/v2/models/\" + MODEL_ID + \"/versions/\" + MODEL_VERSION_ID + \"/outputs\", requestOptions)\n .then(response => response.text())\n .then(response => {\n const parser = JSON.parse(response)\n console.log('hi', parser.outputs[0].data.regions[0].region_info.bounding_box)\n // console.log(response[])\n if (response) {\n fetch('http://localhost:3000/image', {\n method: 'put',\n headers: {'Content-Type': 'application/json'},\n body: JSON.stringify({\n id: this.state.user.id\n })\n })\n .then(response => response.json())\n .then(count => {\n this.setState(Object.assign(this.state.user, { entries: count }))\n })\n }\n this.displayFaceBox(this.calculateFaceLocation(response))\n })\n .then(result => console.log(result))\n .catch(error => console.log('error', error));\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19135295/"
] |
74,329,064 | <p>I made this exercise on SQL server: write a query that lists for each cluster the quantity of products that fall within it. The company wants to obtain an analysis of sales with respect to the average quantity of each product present in each order, classifying them into six clusters: Q1 (<15), Q2 (15-20), Q3 (21-25), Q4 (26-30), Q5 (31-35), Q6(>35). Write a query that lists, for each product, the product name and the cluster to which it belong. The database is northwind</p>
<pre><code>select count(ProductName) as prod_num ,cluster
from (
select ProductName,
case
when avg(Quantity) < 15 then 'Q1'
when avg(Quantity) <= 20 then 'Q2'
when avg(Quantity) between 21 and 25 then 'Q3'
when avg(Quantity) between 26 and 30 then 'Q4'
when avg(Quantity) between 31 and 35 then 'Q5'
else 'Q6'
end
as cluster
from [Order Details] od join Products pr on od.ProductID=pr.ProductID
group by ProductName
) as clusters
group by cluster
order by cluster
</code></pre>
<pre><code>OUTPUT
22 Q2
35 Q3
18 Q4
2 Q6
</code></pre>
<p>I also need to display values for Q1 and Q5.</p>
| [
{
"answer_id": 74329214,
"author": "topsail",
"author_id": 1467914,
"author_profile": "https://Stackoverflow.com/users/1467914",
"pm_score": 3,
"selected": true,
"text": "declare @clusters table (prod_num int, cluster nchar(2));\ninsert into @clusters values\n (0, 'Q1'),(0, 'Q2'),(0, 'Q3'),(0, 'Q4'),(0, 'Q5'),(0, 'Q6');\n \nselect \n t1.cluster,\n t1.prod_num + isnull(t2.prod_num, 0) as prod_num\nfrom \n @clusters t1\n left join\n (\n select count(ProductName) as prod_num ,cluster\n from (\n select ProductName,\n case \n when avg(Quantity) < 15 then 'Q1'\n when avg(Quantity) between 15 and 20 then 'Q2'\n when avg(Quantity) between 21 and 25 then 'Q3'\n when avg(Quantity) between 26 and 30 then 'Q4'\n when avg(Quantity) between 31 and 35 then 'Q5'\n else 'Q6'\n end\n as cluster\n from [Order Details] od join Products pr on od.ProductID=pr.ProductID\n group by ProductName\n ) as clusters \n group by cluster\n ) t2\n on t1.cluster = t2.cluster\norder by t1.cluster;\n"
},
{
"answer_id": 74329378,
"author": "Stuck at 1337",
"author_id": 20091109,
"author_profile": "https://Stackoverflow.com/users/20091109",
"pm_score": 1,
"selected": false,
"text": "CREATE TABLE #clusters(cluster char(2), lo int, hi int,\n INDEX cix_cl CLUSTERED(lo,hi));\n\nINSERT #clusters VALUES('Q1', 0,14),('Q2',15,20),('Q3',21,25),\n ('Q4',26,30),('Q5',31,35),('Q6',36,2000000000);\n\nSELECT prod_num = COUNT(p.ProductName), cl.cluster\nFROM #clusters AS cl\nLEFT OUTER JOIN\n(\n SELECT pr.ProductName, avgQ = AVG(od.Quantity) \n FROM dbo.[Order Details] AS od\n INNER JOIN dbo.Products AS pr\n ON od.ProductID = pr.ProductID\n GROUP BY pr.ProductName\n) AS p\nON p.avgQ BETWEEN cl.lo AND cl.hi\n GROUP BY cl.cluster;\n"
},
{
"answer_id": 74336370,
"author": "Charlieface",
"author_id": 14868997,
"author_profile": "https://Stackoverflow.com/users/14868997",
"pm_score": 1,
"selected": false,
"text": "VALUES"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20426481/"
] |
74,329,069 | <p>I currently have 2 methods. The first method says what is the row with the highest average and the second one says what is the column with the highest average. I want to merge these two methods into one but I don't know how. the parameter is an array of doubles and the return type should be a string that says for the rows (R3 for example) and for the columns (C3)</p>
<p>What I tried to do is create 4 for-loops (2 for loops for the rows and 2 for loops for the columns) but when I try to return the highest average of the column it will say "unreachable statement" because I can't use return twice. Any suggestions?</p>
<p>the code below is the two methods I have right now. what the methods are doing is getting the averages of each row/column and then compare them.</p>
<pre><code>public static double findHighestRow(double[][] grid) {
int i, j;
double sum = 0;
double average = 0;
double averageGreater = 0;
for (i = 0; i < grid.length; i++) {
for (j = 0; j < grid[i].length; j++) {
sum = sum + grid[i][j];
}
average=sum/grid[i].length;
sum=0;
averageGreater = Math.max(average, sum / grid[i].length);
System.out.println("Average of row " + (i+1) + " = " + average);
}
System.out.println(" row with highest average is " + (i) + " = " + averageGreater);
return averageGreater;
}
public static double findHighestColumn(double grid[][]) {
int k, l;
double sum2 = 0;
double average2 = 0;
double averageGreater2 = 0;
for (k = 0; k < grid.length; k++) {
for (l = 0; l < grid[k].length; l++) {
sum2=sum2+grid[k][l];
}
average2=sum2/grid[k].length;
sum2 = 0;
averageGreater2 = Math.max(average2, sum2 / grid[k].length);
System.out.println("Average of column " + (k+1) + " = " + average2);
}
System.out.println(" column with highest average is " + (k) + " = " + averageGreater2);
return averageGreater2;
}
</code></pre>
<p>This is the code that is failing. Another problem is that I do not know how to convert the result into a string.</p>
<pre><code>public static double findHighestRow(double[][] grid) {
int i, j;
double sum = 0;
double average = 0;
double averageGreater = 0;
for (i = 0; i < grid.length; i++) {
for (j = 0; j < grid[i].length; j++) {
sum = sum + grid[i][j];
}
average=sum/grid[i].length;
sum=0;
averageGreater = Math.max(average, sum / grid[i].length);
System.out.println("Average of row " + (i+1) + " = " + average);
}
System.out.println(" row with highest average is " + (i) + " = " + averageGreater);
return averageGreater;
int k, l;
double sum2 = 0;
double average2 = 0;
double averageGreater2 = 0;
for (k = 0; k < grid.length; k++) {
for (l = 0; l < grid[k].length; l++) {
sum2=sum2+grid[k][l];
}
average2=sum2/grid[k].length;
sum2 = 0;
averageGreater2 = Math.max(average2, sum2 / grid[k].length);
System.out.println("Average of column " + (k+1) + " = " + average2);
}
System.out.println(" column with highest average is " + (k) + " = " + averageGreater2);
return averageGreater2;
}
</code></pre>
| [
{
"answer_id": 74329214,
"author": "topsail",
"author_id": 1467914,
"author_profile": "https://Stackoverflow.com/users/1467914",
"pm_score": 3,
"selected": true,
"text": "declare @clusters table (prod_num int, cluster nchar(2));\ninsert into @clusters values\n (0, 'Q1'),(0, 'Q2'),(0, 'Q3'),(0, 'Q4'),(0, 'Q5'),(0, 'Q6');\n \nselect \n t1.cluster,\n t1.prod_num + isnull(t2.prod_num, 0) as prod_num\nfrom \n @clusters t1\n left join\n (\n select count(ProductName) as prod_num ,cluster\n from (\n select ProductName,\n case \n when avg(Quantity) < 15 then 'Q1'\n when avg(Quantity) between 15 and 20 then 'Q2'\n when avg(Quantity) between 21 and 25 then 'Q3'\n when avg(Quantity) between 26 and 30 then 'Q4'\n when avg(Quantity) between 31 and 35 then 'Q5'\n else 'Q6'\n end\n as cluster\n from [Order Details] od join Products pr on od.ProductID=pr.ProductID\n group by ProductName\n ) as clusters \n group by cluster\n ) t2\n on t1.cluster = t2.cluster\norder by t1.cluster;\n"
},
{
"answer_id": 74329378,
"author": "Stuck at 1337",
"author_id": 20091109,
"author_profile": "https://Stackoverflow.com/users/20091109",
"pm_score": 1,
"selected": false,
"text": "CREATE TABLE #clusters(cluster char(2), lo int, hi int,\n INDEX cix_cl CLUSTERED(lo,hi));\n\nINSERT #clusters VALUES('Q1', 0,14),('Q2',15,20),('Q3',21,25),\n ('Q4',26,30),('Q5',31,35),('Q6',36,2000000000);\n\nSELECT prod_num = COUNT(p.ProductName), cl.cluster\nFROM #clusters AS cl\nLEFT OUTER JOIN\n(\n SELECT pr.ProductName, avgQ = AVG(od.Quantity) \n FROM dbo.[Order Details] AS od\n INNER JOIN dbo.Products AS pr\n ON od.ProductID = pr.ProductID\n GROUP BY pr.ProductName\n) AS p\nON p.avgQ BETWEEN cl.lo AND cl.hi\n GROUP BY cl.cluster;\n"
},
{
"answer_id": 74336370,
"author": "Charlieface",
"author_id": 14868997,
"author_profile": "https://Stackoverflow.com/users/14868997",
"pm_score": 1,
"selected": false,
"text": "VALUES"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20187389/"
] |
74,329,236 | <p>This is my code:</p>
<pre><code>struct Account: View {
var body: some View {
VStack {
ScrollView {
HStack {
Text("Account")
.font(.largeTitle)
.fontWeight(.bold)
Spacer(minLength: 0)
}
.padding()
.background(Color.indigo)
VStack {
Text("Doe, John Jack")
.font(.title)
Divider()
.foregroundColor(Color.indigo)
HStack {
Text("")
}
}
Spacer(minLength: 0)
VStack {
Button(action: {
}) {
Text("Log Out")
.foregroundColor(.red)
.fontWeight(.bold)
}
}
}
}
}
}
</code></pre>
<p>If you run the code above, you will see that the indigo doesn't go behind the time and battery precentage. How can I make it do that?</p>
| [
{
"answer_id": 74329214,
"author": "topsail",
"author_id": 1467914,
"author_profile": "https://Stackoverflow.com/users/1467914",
"pm_score": 3,
"selected": true,
"text": "declare @clusters table (prod_num int, cluster nchar(2));\ninsert into @clusters values\n (0, 'Q1'),(0, 'Q2'),(0, 'Q3'),(0, 'Q4'),(0, 'Q5'),(0, 'Q6');\n \nselect \n t1.cluster,\n t1.prod_num + isnull(t2.prod_num, 0) as prod_num\nfrom \n @clusters t1\n left join\n (\n select count(ProductName) as prod_num ,cluster\n from (\n select ProductName,\n case \n when avg(Quantity) < 15 then 'Q1'\n when avg(Quantity) between 15 and 20 then 'Q2'\n when avg(Quantity) between 21 and 25 then 'Q3'\n when avg(Quantity) between 26 and 30 then 'Q4'\n when avg(Quantity) between 31 and 35 then 'Q5'\n else 'Q6'\n end\n as cluster\n from [Order Details] od join Products pr on od.ProductID=pr.ProductID\n group by ProductName\n ) as clusters \n group by cluster\n ) t2\n on t1.cluster = t2.cluster\norder by t1.cluster;\n"
},
{
"answer_id": 74329378,
"author": "Stuck at 1337",
"author_id": 20091109,
"author_profile": "https://Stackoverflow.com/users/20091109",
"pm_score": 1,
"selected": false,
"text": "CREATE TABLE #clusters(cluster char(2), lo int, hi int,\n INDEX cix_cl CLUSTERED(lo,hi));\n\nINSERT #clusters VALUES('Q1', 0,14),('Q2',15,20),('Q3',21,25),\n ('Q4',26,30),('Q5',31,35),('Q6',36,2000000000);\n\nSELECT prod_num = COUNT(p.ProductName), cl.cluster\nFROM #clusters AS cl\nLEFT OUTER JOIN\n(\n SELECT pr.ProductName, avgQ = AVG(od.Quantity) \n FROM dbo.[Order Details] AS od\n INNER JOIN dbo.Products AS pr\n ON od.ProductID = pr.ProductID\n GROUP BY pr.ProductName\n) AS p\nON p.avgQ BETWEEN cl.lo AND cl.hi\n GROUP BY cl.cluster;\n"
},
{
"answer_id": 74336370,
"author": "Charlieface",
"author_id": 14868997,
"author_profile": "https://Stackoverflow.com/users/14868997",
"pm_score": 1,
"selected": false,
"text": "VALUES"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17864647/"
] |
74,329,238 | <p>I am trying to create a new list by taking values from the user. Then I want to display the values in this list along with their indexes. For example for the values 5,4,3,2 I want the output to be:</p>
<p>5 0</p>
<p>4 1</p>
<p>3 2</p>
<p>2 3</p>
<p>This is my code:</p>
<pre><code>(setq n (getint "How many elements you want to input"))
(defun CreateList(n)
(setq lista '())
(repeat n
(setq temp (getstring "Enter value"))
(setq lista (append lista (list temp)))
)
(foreach el lista
(print(strcat el vl-position el lista))
)
)
(CreateList n)
</code></pre>
<p>As result I am getting: <code>error: bad argument type: stringp #<SUBR @0000027b44742e88 VL-POSITION></code></p>
<p>I have tried to change the print line to something like <code>(print(strcat el (rtos vl-position el lista)))</code></p>
<p>But It didn't work also. Any ideas?</p>
| [
{
"answer_id": 74339421,
"author": "CAD Developer",
"author_id": 5796526,
"author_profile": "https://Stackoverflow.com/users/5796526",
"pm_score": 2,
"selected": false,
"text": "vl-position"
},
{
"answer_id": 74347760,
"author": "Lee Mac",
"author_id": 7531598,
"author_profile": "https://Stackoverflow.com/users/7531598",
"pm_score": 3,
"selected": true,
"text": "(defun CreateList(n)\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15567924/"
] |
74,329,303 | <p>I am trying to make a simple clicker game that you try and generate money through clicking a button. And I want a upgrade button to become visible after you have $10.</p>
<p>Here is the code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var money = 0
const addMoneyButton = document.getElementById('Clicker')
const addMoney = () => {
money += 1
document.getElementById("money").innerHTML = money
console.log(money)
function upgrade1() {
var upgrade1 = document.getElementById('upgrade1')
if (money > 10) {
upgrade1.style.visibility = 'visible'
}
}
}
addMoneyButton.addEventListener("click", addMoney)</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="Clicker">Click To Begin Making Money</button>
<br>
<button id='upgrade1' style="visibility:hidden;">Upgrade Money Amount</button>
<h1>Money Amount: <span id='money'></span></h1></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74339421,
"author": "CAD Developer",
"author_id": 5796526,
"author_profile": "https://Stackoverflow.com/users/5796526",
"pm_score": 2,
"selected": false,
"text": "vl-position"
},
{
"answer_id": 74347760,
"author": "Lee Mac",
"author_id": 7531598,
"author_profile": "https://Stackoverflow.com/users/7531598",
"pm_score": 3,
"selected": true,
"text": "(defun CreateList(n)\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20426737/"
] |
74,329,322 | <p>I have a simulation time, starting from zero and counting upwards. Then I have some if-statements, in which I set the speed of a motor to a specific value. I want to execute different stuff depending on the simulation time.</p>
<p>E.g.,</p>
<pre><code>if simulation_time % 5000 <= 0:
motorSpeed = actionList[choice1]
elif simulation_time % 10000 <= 0:
motorSpeed = actionList[choice2]
elif simulation_time % 15000 <= 0:
motorSpeed = actionList[choice3]
else:
motorSpeed = dict(speedLeft=0, speedRight=0)
</code></pre>
<p>As seen above, my thought was, if the time is less than 5000 do according to choice1, if the time is less than 10000 do according to choice2, etc. However when the time exceeds these values and become larger than 15000 it will get stuck in the last else-statement. It will keep doing the stuff provided there. I don't want that to happen. Instead I want to go back to the first if-statement and do the job there and then to the second if-statement and so on. I know that I should use the modulo (%) operator in somehow, but I didn't manage to.</p>
<p>To summerize, I want to execute the first if statement for 5000 ms and the second if statement from 5000 to 10000 and the third from 10000 to 15000 and repeat. I can not reset the time. It is the time of the simulator and it should not be reset to zero.</p>
| [
{
"answer_id": 74329359,
"author": "mlokos",
"author_id": 19570235,
"author_profile": "https://Stackoverflow.com/users/19570235",
"pm_score": -1,
"selected": false,
"text": "motor_speed_cycle = simulation_time\n\nif motor_speed_cycle % 5000 <= 0:\n motorSpeed = actionList[choice1]\nelif motor_speed_cycle % 10000 <= 0:\n motorSpeed = actionList[choice2]\nelif motor_speed_cycle % 15000 <= 0:\n motorSpeed = actionList[choice3]\nelse:\n motorSpeed = dict(speedLeft=0, speedRight=0)\n motor_speed_cycle = int(simulation_time / 15000)\n"
},
{
"answer_id": 74329407,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 0,
"selected": false,
"text": "motor_speed_cycle = (simulation_time // 5000) % 3\ncycle_list = [actionList[choice] for choice in (choice1, choice2, choice3)]\nmotorSpeed = cycle_list[motor_speed_cycle]\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12347671/"
] |
74,329,358 | <p>I would like to pass quoted variables in the <code>group</code> argument of <code>geom_col_wrap</code> to the <code>split_group</code> function.</p>
<pre><code># I deleted the rest of the function for readability
geom_col_wrap = function(data, mapping, group, ...) {
data |>
split_group(group)
}
</code></pre>
<pre><code># This function was based on the `tidytable` package
split_group = function(data, ...) {
by_quote = as.list(substitute(...()))
by = sapply(by_quote, deparse)
split = vctrs::vec_split(data, data[c(by)])
out = split[["val"]]
names = do.call(paste, c(split[["key"]], sep = "_"))
names(out) = names
return(out)
}
</code></pre>
<p><code>split_group</code> use <code>substitute</code> to quote variables, here is the problem. How can I make <code>split_group</code> recognize quote variables from <code>group</code> argument? I know it is easy to solve using <code>rlang</code>, but I need a R base solution.</p>
<pre><code>split_group(mtcars, vs, am)
$`0_1`
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
...
$`1_1`
mpg cyl disp hp drat wt qsec vs am gear carb
Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
...
$`1_0`
mpg cyl disp hp drat wt qsec vs am gear carb
Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1
Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1
...
$`0_0`
mpg cyl disp hp drat wt qsec vs am gear carb
Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2
Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4
...
</code></pre>
<pre><code>geom_col_wrap(
mtcars,
mapping = ggplot2::aes(x = cyl, y = hp, color = am),
group = c(vs, am)
)
Error in `[.data.frame`(data, c(by)) : undefined columns selected
</code></pre>
<p>This error comes from <code>as.list(substitute(...()))</code>. It does not unquoted the <code>group</code> argument. Why?</p>
<p>Note: I cannot use dots arg to solve the problem.</p>
| [
{
"answer_id": 74329359,
"author": "mlokos",
"author_id": 19570235,
"author_profile": "https://Stackoverflow.com/users/19570235",
"pm_score": -1,
"selected": false,
"text": "motor_speed_cycle = simulation_time\n\nif motor_speed_cycle % 5000 <= 0:\n motorSpeed = actionList[choice1]\nelif motor_speed_cycle % 10000 <= 0:\n motorSpeed = actionList[choice2]\nelif motor_speed_cycle % 15000 <= 0:\n motorSpeed = actionList[choice3]\nelse:\n motorSpeed = dict(speedLeft=0, speedRight=0)\n motor_speed_cycle = int(simulation_time / 15000)\n"
},
{
"answer_id": 74329407,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 0,
"selected": false,
"text": "motor_speed_cycle = (simulation_time // 5000) % 3\ncycle_list = [actionList[choice] for choice in (choice1, choice2, choice3)]\nmotorSpeed = cycle_list[motor_speed_cycle]\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9204125/"
] |
74,329,372 | <p>I'd like to link elements from a string with numbers in Python.</p>
<p>Users need to give an input string (one word such as "world") and then the elements of that string (here the letters of the word "world") needs to be linked to numbers starting from 0.</p>
<p>Then, when you give another string as an input, the corresponding numbers need to be printed.</p>
<p>What I tried:</p>
<pre><code># input
string = str(input())
# loop to link numbers with string input
number = -1
for letter in string:
number += 1
</code></pre>
<p>Now I'd like to link the first letter of the input string with the number 0 and so on.</p>
<p>E.g.:</p>
<pre><code>string = "world"
</code></pre>
<p>than "w" = 0, "o" = 1, "r" = 2, "l" = 3 and "d" = 4.</p>
<p>And then when you give another string such as "lord" I want to get the following output:</p>
<pre><code>3124
</code></pre>
<p>Because "lord" --> "l" = 3, "o" = 1, "r" = 2 and "d" = 4</p>
<p>I don't know how I can save these numbers to their corresponding letter.</p>
| [
{
"answer_id": 74329359,
"author": "mlokos",
"author_id": 19570235,
"author_profile": "https://Stackoverflow.com/users/19570235",
"pm_score": -1,
"selected": false,
"text": "motor_speed_cycle = simulation_time\n\nif motor_speed_cycle % 5000 <= 0:\n motorSpeed = actionList[choice1]\nelif motor_speed_cycle % 10000 <= 0:\n motorSpeed = actionList[choice2]\nelif motor_speed_cycle % 15000 <= 0:\n motorSpeed = actionList[choice3]\nelse:\n motorSpeed = dict(speedLeft=0, speedRight=0)\n motor_speed_cycle = int(simulation_time / 15000)\n"
},
{
"answer_id": 74329407,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 0,
"selected": false,
"text": "motor_speed_cycle = (simulation_time // 5000) % 3\ncycle_list = [actionList[choice] for choice in (choice1, choice2, choice3)]\nmotorSpeed = cycle_list[motor_speed_cycle]\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20279847/"
] |
74,329,374 | <p>Edit: as per the answers, this works in 21C but not before. Looks like it is an Oracle bug that was fixed. The workaround in previous versions is provided as the accepted answer.</p>
<p>In PL/SQL, a subtype of a nested table behaves inconsistently compared to a regular nested table. It seems like it is not possible to use a subtype of a nested table. Is this correct?</p>
<pre><code>create or replace package test_subtype_pkg
is
type t_foos is table of varchar2(10);
subtype t_bars is t_foos;
procedure main;
end;
/
</code></pre>
<p>The following <code>l_bars := t_bars()</code> fails to compile with <code>PLS-00355: use of pl/sql table not allowed in this context</code></p>
<pre><code>create or replace package body test_subtype_pkg
is
procedure main
is
l_foos t_foos;
l_bars t_bars;
begin
l_foos := t_foos(); -- compiles correctly
l_bars := t_bars(); -- PLS-00355: use of pl/sql table not allowed in this context
end;
end;
/
</code></pre>
<p>However, the following compiles without error. During run time it fails with <code>ORA-06531: Reference to uninitialized collection</code>:</p>
<pre><code>create or replace package body test_subtype_pkg
is
procedure main
is
l_bars t_bars;
begin
l_bars.extend; -- At run time, ORA-06531: Reference to uninitialized collection
l_bars(1) := 'foo';
end;
end;
/
</code></pre>
<p>Is it possible to use a subtype of a nested table?</p>
| [
{
"answer_id": 74329359,
"author": "mlokos",
"author_id": 19570235,
"author_profile": "https://Stackoverflow.com/users/19570235",
"pm_score": -1,
"selected": false,
"text": "motor_speed_cycle = simulation_time\n\nif motor_speed_cycle % 5000 <= 0:\n motorSpeed = actionList[choice1]\nelif motor_speed_cycle % 10000 <= 0:\n motorSpeed = actionList[choice2]\nelif motor_speed_cycle % 15000 <= 0:\n motorSpeed = actionList[choice3]\nelse:\n motorSpeed = dict(speedLeft=0, speedRight=0)\n motor_speed_cycle = int(simulation_time / 15000)\n"
},
{
"answer_id": 74329407,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 0,
"selected": false,
"text": "motor_speed_cycle = (simulation_time // 5000) % 3\ncycle_list = [actionList[choice] for choice in (choice1, choice2, choice3)]\nmotorSpeed = cycle_list[motor_speed_cycle]\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1391717/"
] |
74,329,387 | <p>I have this python server code here, which is waiting to receive a message digest and an encrypted message from a python client.</p>
<p>Clientside socket:</p>
<pre><code>with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s=socket.socket()
s.connect((HOST, PORT))
s.sendall(transmit)
</code></pre>
<p>Server Side:</p>
<pre><code>with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
print("\n Server is listing on port :", PORT, "\n")
fragments = []
#Execution stops here
with conn:
print(f"Connected by {addr}")
while True:
chunk = s.recv(4096)
if not chunk:
break
fragments.append(chunk)
arr = 'b'.join(fragments)
#Test to see if the array was being populated
print(arr[0])
</code></pre>
<p><a href="https://stackoverflow.com/questions/17667903/python-socket-receive-large-amount-of-data">I have tried the methods this stackOF post here</a>, specifically above is the provided list method implementation as my client is sending a "packet" of information as a list encoded as a string</p>
<pre><code>packet = [signeddigest, ciphertext]
transmit = str(packet)
transmit = transmit.encode()
s.sendall(transmit)
</code></pre>
<p>I have tested my client code on a different server codebase with the same localhost and port number, and that server was receiving the information, so there's something I'm missing in the server side.</p>
<p>The output from the test server was</p>
<p><code>File [b'HT\xb0\x00~f\xde\xc8G)\xaf*\xcc\x90\xac\xca\x124\x7f\xa0\xaa\ requested from ('127.0.0.1', 49817)</code></p>
<p>That "file" is the encoded string sent from my client to the test server. So I'm confident there's something wrong with my server implementation.</p>
<p>Further information:
When I run the server it listens, then I run the client.</p>
<p>python ClientTest.py
Please enter the message to send</p>
<p>Then the server side immediately closes the connection</p>
<blockquote>
<p>line 23, in
chunk = s.recv(4096) OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and
(when sending on a datagram socket using a sendto call) no address was
supplied</p>
</blockquote>
| [
{
"answer_id": 74329359,
"author": "mlokos",
"author_id": 19570235,
"author_profile": "https://Stackoverflow.com/users/19570235",
"pm_score": -1,
"selected": false,
"text": "motor_speed_cycle = simulation_time\n\nif motor_speed_cycle % 5000 <= 0:\n motorSpeed = actionList[choice1]\nelif motor_speed_cycle % 10000 <= 0:\n motorSpeed = actionList[choice2]\nelif motor_speed_cycle % 15000 <= 0:\n motorSpeed = actionList[choice3]\nelse:\n motorSpeed = dict(speedLeft=0, speedRight=0)\n motor_speed_cycle = int(simulation_time / 15000)\n"
},
{
"answer_id": 74329407,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 0,
"selected": false,
"text": "motor_speed_cycle = (simulation_time // 5000) % 3\ncycle_list = [actionList[choice] for choice in (choice1, choice2, choice3)]\nmotorSpeed = cycle_list[motor_speed_cycle]\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15585688/"
] |
74,329,403 | <p>I'm having trouble accessing multiple values in a dictionary. Let's say I have this dictionary:</p>
<pre><code>{'1': 0, '2': 1, '3': 2, '4': 3, '5': 4, '6': 5}
</code></pre>
<p>I want to find two keys that sum to 6 and display their values. Here, the keys 4 and 2 add to 6, so the 2 values are 3 and 1.</p>
<p>Where do I start? This is the code I have so far:</p>
<pre><code>for key in dico:
if sum(key + key) == 6:
print(f"Numbers @ {key:dico} have a sum of 6")
</code></pre>
| [
{
"answer_id": 74329488,
"author": "mlokos",
"author_id": 19570235,
"author_profile": "https://Stackoverflow.com/users/19570235",
"pm_score": 0,
"selected": false,
"text": "a = {'1': 0, '2': 1, '3': 2, '4': 3, '5': 4, '6': 5}\n\nresults = list()\n\nfor key_1 in a.keys():\n for key_2 in a.keys():\n if key_1 != key_2:\n if a[key_1] + a[key_2] == 6:\n if a[key_1] < a[key_2]:\n results.append((key_1, key_2))\n\nprint(results)\n"
},
{
"answer_id": 74329498,
"author": "Michael M.",
"author_id": 13376511,
"author_profile": "https://Stackoverflow.com/users/13376511",
"pm_score": 2,
"selected": false,
"text": "dct = {'1': 0, '2': 1, '3': 2, '4': 3, '5': 4, '6': 5}\n\nfor i, key in enumerate(dct):\n if i + 2 > len(dct)/2:\n break\n \n matchIndex = str(6 - int(key))\n if dct.get(matchIndex) is not None:\n print(f'Keys {key} and {matchIndex} have values {dct[key]} and {dct[matchIndex]}')\n"
},
{
"answer_id": 74329530,
"author": "mcardenas13",
"author_id": 14440408,
"author_profile": "https://Stackoverflow.com/users/14440408",
"pm_score": 1,
"selected": false,
"text": "itertools"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20402809/"
] |
74,329,438 | <p>I extracted some text from a web page.</p>
<p>But I have some whitespaces or speciual characters that I can not remove easily.</p>
<p>I tried this:</p>
<pre><code>library(dplyr)
library(rvest)
url <- "http://www.scielo.org.mx/scielo.php?script=sci_arttext&pid=S1607-40412016000100014&lang=es"
page <- read_html(url)
referenes_whitout_end_spaces <- page %>%
html_elements("p") %>%
.[grepl("(Links)|(doi:)", as.character(.))] %>%
html_text() %>%
gsub("[\n\t\b]", "", .) %>%
gsub("\\[.*Links.*\\]", "", .) %>%
gsub("\\s|\\n", " ", .) %>%
trimws("both", whitespace = "[ \t\r\n\b]")
referenes_whitout_end_spaces
</code></pre>
<p>but the whitespaces at the end of the references stands.</p>
<p>how I can remove this whitespaces?</p>
| [
{
"answer_id": 74329573,
"author": "G5W",
"author_id": 4752675,
"author_profile": "https://Stackoverflow.com/users/4752675",
"pm_score": 2,
"selected": false,
"text": "trimws"
},
{
"answer_id": 74329899,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 3,
"selected": true,
"text": " "
},
{
"answer_id": 74329972,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 2,
"selected": false,
"text": "str_squish"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10108383/"
] |
74,329,583 | <p>Have tried,</p>
<pre><code>export "INDEX_SET"="{"index_all":false,"index_group":true,"index_channel":true,"exclude_chats":[],"include_chats":[1522205730]}"
</code></pre>
<p>but received this error:</p>
<blockquote>
<p>json.decoder.JSONDecodeError: Expecting property name enclosed in
double quotes: line 1 column 2 (char 1)</p>
<p>Please set the INDEX_SETTINGS environment variable correctly</p>
</blockquote>
<p>from the python code as:</p>
<pre><code>index_set_str = os.environ["INDEX_SET"].strip()
index_settings = json.loads(index_settings_str)
</code></pre>
| [
{
"answer_id": 74329629,
"author": "declension",
"author_id": 604382,
"author_profile": "https://Stackoverflow.com/users/604382",
"pm_score": 3,
"selected": true,
"text": "export INDEX_SET='{\"index_all\":false,\"index_group\":true,\"index_channel\":true,\"exclude_chats\":[],\"include_chats\":[1522205730]}'\n"
},
{
"answer_id": 74329651,
"author": "stdunbar",
"author_id": 2933977,
"author_profile": "https://Stackoverflow.com/users/2933977",
"pm_score": 0,
"selected": false,
"text": "export INDEX_SET=\"{\\\"index_all\\\":false,\\\"index_group\\\":true,\\\"index_channel\\\":true,\\\"exclude_chats\\\":[],\\\"include_chats\\\":[1522205730]}\"\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18308985/"
] |
74,329,588 | <p>I have a table with the following structure:</p>
<pre class="lang-none prettyprint-override"><code> name | version | processed | processing | updated | ref_time
------+---------+-----------+------------+----------+----------
abc | 1 | t | f | 27794395 | 27794160
def | 1 | t | f | 27794395 | 27793440
ghi | 1 | t | f | 27794395 | 27793440
jkl | 1 | f | f | 27794395 | 27794160
mno | 1 | t | f | 27794395 | 27793440
pqr | 1 | f | t | 27794395 | 27794160
</code></pre>
<p>I can use the following query to count the total number within each <code>ref_time</code>:</p>
<pre><code>SELECT ref_time, COUNT (*) AS total
FROM (SELECT * FROM status_table) AS _
GROUP BY ref_time;
</code></pre>
<pre class="lang-none prettyprint-override"><code> ref_time | total
----------+-------
27794160 | 2259
27793440 | 2259
</code></pre>
<p>And the following query to count the total number within each <code>ref_time</code> where <code>processed=true</code>:</p>
<pre><code>SELECT ref_time, COUNT (*) AS processed FROM (SELECT * FROM status_table WHERE processed=true) AS _ GROUP BY ref_time;
</code></pre>
<pre class="lang-none prettyprint-override"><code> ref_time | processed
----------+-----------
27794160 | 1057
27793440 | 2259
</code></pre>
<p>I then try to merge the information using an <code>INNER JOIN</code> on <code>ref_time</code>:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT * FROM
(SELECT ref_time, COUNT (*) AS total
FROM (SELECT * FROM status_table) AS _
GROUP BY ref_time) result_total
INNER JOIN
(SELECT ref_time, COUNT (*) AS processed
FROM (SELECT * FROM status_table WHERE processed=true) AS _
GROUP BY ref_time) result_processed
ON result_total.ref_time = result_processed.ref_time;
</code></pre>
<pre class="lang-none prettyprint-override"><code> ref_time | total | ref_time | processed
----------+-------+----------+-----------
27794160 | 2259 | 27794160 | 1057
27793440 | 2259 | 27793440 | 2259
</code></pre>
<p>First question: how do I avoid the duplicated <code>ref_time</code> column?</p>
<p>Second question: how do I add an additional <code>percent</code> column derived as <code>(100 * processed / total)</code> (to one d.p.), i.e. to give:</p>
<pre class="lang-none prettyprint-override"><code> ref_time | total | processed | percent
----------+-------+-----------+---------
27794160 | 2259 | 1057 | 46.8
27793440 | 2259 | 2259 | 100.0
</code></pre>
<p>Third question: is there a more efficient way to do this? Can I avoid making two separate <code>SELECT</code> queries?</p>
| [
{
"answer_id": 74329653,
"author": "Sergey",
"author_id": 14535517,
"author_profile": "https://Stackoverflow.com/users/14535517",
"pm_score": 1,
"selected": false,
"text": "SELECT ref_time,count(*)as total,\nSUM\n(\n CASE\n WHEN processed='t' then 1\n else 0\n END\n)processed\nFROM YOUR_TABLE\nGROUP BY ref_time\n"
},
{
"answer_id": 74329763,
"author": "trillion",
"author_id": 12513693,
"author_profile": "https://Stackoverflow.com/users/12513693",
"pm_score": 1,
"selected": false,
"text": "with main as (\n select\n ref_time,\n sum(case when processed = 'true' then 1 else 0 end ) as total_processed,\n count(*) as total\n \n from <table_name>\n group by 1\n)\nselect *, round((total_processed::numeric / nullif(total::numeric,0)) * 100),2) as percent from main\n"
},
{
"answer_id": 74331971,
"author": "GMB",
"author_id": 10676716,
"author_profile": "https://Stackoverflow.com/users/10676716",
"pm_score": 3,
"selected": true,
"text": "filter"
},
{
"answer_id": 74386503,
"author": "Erwin Brandstetter",
"author_id": 939860,
"author_profile": "https://Stackoverflow.com/users/939860",
"pm_score": 1,
"selected": false,
"text": "SELECT ref_time\n , count(*) AS total\n , count(*) FILTER (WHERE processed) AS processed\n , round(count(*) FILTER (WHERE processed) * 100.0 / count(*), 2) AS percent\nFROM status_table\nGROUP BY 1;\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4070848/"
] |
74,329,676 | <p>I'm beginning to learn HTML/CSS and I have to make a header, and I'm having some troubles in the spacing I need to get between the texts on it. After trying a lot of things, I got the spacing right, but now somewhy the texts aint getting the interaction they should.</p>
<p>The HTML code is:</p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8"/>
<link rel="stylesheet" href="_css/estilo.css"/>
</head>
<body>
<div class="header" id="header">
<div class="header_sn">
<a href="sobre-nos.html">Sobre nós</a></div>
<div class="header_serv">
<a href="servicos.html">Serviços</a></div>
<div class="header_logo">
<figure>
<a href="home.html"><img id="logo_header" src="_imagens/logoimagem.png">
<figcaption>Palavras Cafeinadas</figcaption></a>
</figure>
</div>
<div class="header_cont">
<a href="contato.html">Contato</a></div>
<div class="header_tel">
<a><img id="logotel" src="_imagens/icone-telefone.png">19-99126972</a>
</div>
</body>
</html>
</code></pre>
<p>And the CSS code is:</p>
<pre><code>@charset "UTF-8";
@import url('https://fonts.googleapis.com/css2?family=Cormorant+Garamond&display=swap');
@font-face{
font-family: 'FontePadrao';
src: url("../_fontes/CormorantGaramond-SemiBold.otf");
}
:root{
--color-fundo: #57290B;
--color-letra: #EBDACC;
}
*{
margin: 0;
padding: 0;
}
/* Formatação header fundo */
/* Format header writings */
body{
font-family: 'Cormorant Garamond', serif;
font-size: 18px;
line-height: 22px;
color: var(--color-letra);
}
.header, .header-esquerda, .header-direita{
display: flex;
flex-direction: row;
align-items: center;
}
.header{
background-color: var(--color-fundo);
height: 100px;
justify-content: space-between;
padding: 0 0 0 0;
}
.header_sn{
position: absolute;
padding: 39px 0px 39px 119px;
}
.header_serv{
position: absolute;
padding: 39px 0px 39px 324px;
}
.header_logo{
position: absolute;
padding: 39px 0px 39px 698px;
}
.header_cont{
position: absolute;
padding: 39px 0px 39px 1400px;
}
.header_tel{
position: absolute;
padding: 39px 0px 39px 1650px;
}
.header a{
text-decoration: none;
color: var(--color-letra);
}
/* Format header imgs */
img#logo_header{
position: absolute;
width: 43px;
height: 54.86px;
top:7px;
padding: 0 181px;
}
img#logotel{
position: relative;
top: 7px;
right: 10px;
}
figure figcaption{
position: relative;
top:15px;
left: 135px;
}
</code></pre>
<p>And this is how the header looks right now, it is almost as it should be looking but I got that problem and couldn't finish it.
<a href="https://i.stack.imgur.com/fkiS4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fkiS4.png" alt="" /></a></p>
<p>Before I got to this final code, the interactions were working in my several others attempts, in this one they didn't work anymore.</p>
| [
{
"answer_id": 74329931,
"author": "BagMan",
"author_id": 20426770,
"author_profile": "https://Stackoverflow.com/users/20426770",
"pm_score": 2,
"selected": true,
"text": "@charset \"UTF-8\";\n@import url('https://fonts.googleapis.com/css2?family=Cormorant+Garamond&display=swap');\n@font-face{\n font-family: 'FontePadrao';\n src: url(\"../_fontes/CormorantGaramond-SemiBold.otf\");\n}\n :root{\n --color-fundo: #57290B;\n --color-letra: #EBDACC;\n \n }\n *{\n margin: 0;\n padding: 0;\n }\n \nbody{\n font-family: 'Cormorant Garamond', serif;\n font-size: 18px; \n line-height: 22px;\n color: var(--color-letra);\n }\n.header, .header-esquerda, .header-direita{\n display: flex;\n flex-direction: row;\n align-items: center;\n}\n.header{\n background-color: var(--color-fundo);\n height: 100px;\n justify-content: space-between;\n padding: 0 0 0 0;\n\n}\n.header_sn{\n position: absolute;\n top: 39px;\n left: 119px;\n}\n\n.header_serv{\n position: absolute;\n top: 39px;\n left: 324px;\n}\n.header_logo{\n position: absolute;\n top: 39px;\n left: 698px;\n}\n.header_cont{\n position: absolute;\n top: 39px;\n left: 1400px;\n}\n.header_tel{\n position: absolute;\n top: 39px;\n left : 1650px;\n}\n\n.header a{\n text-decoration: none;\n color: var(--color-letra);\n\n}\n.header a{\n text-decoration: none;\n color: var(--color-letra);\n\n}\n\n/* Format header imgs */\nimg#logo_header{\n position: absolute;\n width: 43px;\n height: 54.86px;\n top:7px;\n padding: 0 181px;\n}\nimg#logotel{\n position: relative;\n top: 7px;\n right: 10px;\n}\nfigure figcaption{\n position: relative;\n top:15px;\n left: 135px;\n}"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20427057/"
] |
74,329,696 | <p>Numpy allows to pass a <code>numpy.array</code> as argument into a function and evaluate the function for every element of the array.:</p>
<pre class="lang-py prettyprint-override"><code>def f(n):
return n**2
arr = np.array([1,2,3])
f(arr)
</code></pre>
<p>outputs:</p>
<pre class="lang-py prettyprint-override"><code>>>>[1 4 9]
</code></pre>
<p>This works fine, as long as <code>f(n)</code>doesn't perform boolean operations on <code>n</code> like this:</p>
<pre class="lang-py prettyprint-override"><code>def f(n):
if n%2 == 0:
print(n)
</code></pre>
<p>The above code throws following exception:
<code>ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()</code></p>
<p>This makes sense since the debugger showed, that the function <code>f(n)</code> received the entire <code>numpy.array</code>as input. Now, I'm looking for a way to change the code behaviour, so that I can perform boolean operations on the inputs. Is this possible while passing the entire <code>numpy.array</code>, or do I have to call the function by manually iterating over each element of the array?</p>
<p>---Edit:---</p>
<pre><code>def get_far_field_directivity(k,a,theta):
temp = k*a*np.sin(theta)
if temp == 0: return 1
else: return (2*sp.jn(1,(temp)))/(temp)
</code></pre>
<p>The function returns to other functions, which have to use its value on further calculation which is why the indexing approach by @Chrysophylaxs won't work.</p>
| [
{
"answer_id": 74329880,
"author": "Chrysophylaxs",
"author_id": 9499196,
"author_profile": "https://Stackoverflow.com/users/9499196",
"pm_score": 0,
"selected": false,
"text": "np.array([1, 2, 3, 4, 5])"
},
{
"answer_id": 74332189,
"author": "Alex L",
"author_id": 9792594,
"author_profile": "https://Stackoverflow.com/users/9792594",
"pm_score": 2,
"selected": true,
"text": "import numpy as np\n\narr = np.array([1,2,3])\n\ndef f(n):\n if n%2 == 0:\n print(n)\n return n**2\n\nvfunc = np.vectorize(f) \nvfunc(arr) \n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8588512/"
] |
74,329,698 | <p>I'm sampling 3 numbers with their given probabilities, and I would like to turn the results into a data frame counting the occurrences of each value per sample.</p>
<p>Like this:</p>
<pre><code>[0] [1] [2]
3 4 3
1 6 3
</code></pre>
<p>The code I am using to create the samples and count them is this:</p>
<pre><code>replicate(10,table(sample(x=c(0,1,2), size=10, replace=TRUE, prob=c(.3,.4,.3))))
</code></pre>
<p>This gives me a result that can have a sample where only 2 of the numbers were selected. When I try to turn the samples into a data frame, I get an error given that those samples with only 2 numbers selected don't match the number of columns that the other samples have (see the below images for reference). Any ideas on how to get the data frame to fill the row of 2 counts with a third count that is 0 but respecting the order of the rows (i.e. can't only add 0s to the end of the row if the value not counted is the first value)?</p>
<p><a href="https://i.stack.imgur.com/m7n93.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/m7n93.png" alt="Example result of the sample fucntion" /></a></p>
<p><a href="https://i.stack.imgur.com/F89JL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/F89JL.png" alt="df error when the rows are less than 3 columns long" /></a></p>
| [
{
"answer_id": 74329877,
"author": "Ric Villalba",
"author_id": 6912817,
"author_profile": "https://Stackoverflow.com/users/6912817",
"pm_score": 0,
"selected": false,
"text": "replicate(\n 10, table(factor(\n sample(x=c(0,1,2), size=10, replace=TRUE, prob=c(.3,.4,.3)),\n levels = c(0,1,2))), simplify = F)\n"
},
{
"answer_id": 74329882,
"author": "jpsmith",
"author_id": 12109788,
"author_profile": "https://Stackoverflow.com/users/12109788",
"pm_score": 0,
"selected": false,
"text": "for"
},
{
"answer_id": 74329883,
"author": "jay.sf",
"author_id": 6574038,
"author_profile": "https://Stackoverflow.com/users/6574038",
"pm_score": 2,
"selected": true,
"text": "+ 1"
},
{
"answer_id": 74330232,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 0,
"selected": false,
"text": "table"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13260546/"
] |
74,329,729 | <p>This code pop all the required strings from the stack. But i want to store those string elements in a final one string variable. How to do it?</p>
<pre><code>#include <sstream>
#include <stack>
#include <string>
#include<iostream>
using namespace std;
int main()
{
istringstream iss("abdd hhh |post_exp| a * b / (c + d) ^ f - g |\\post_exp| anndd jjss");
stack <string> mudassir;
string subs;
while (iss >> subs) {
if (subs == "|post_exp|")
{
while (iss >> subs && subs.find("|\\post_exp|") == string::npos)
{
mudassir.push(subs);
}
}
}
while (!mudassir.empty()) {
mudassir.top();
mudassir.pop();
}
cout << endl;
return 0;
}
</code></pre>
| [
{
"answer_id": 74329745,
"author": "lorro",
"author_id": 6292621,
"author_profile": "https://Stackoverflow.com/users/6292621",
"pm_score": 3,
"selected": true,
"text": "while"
},
{
"answer_id": 74329788,
"author": "Pepijn Kramer",
"author_id": 16649550,
"author_profile": "https://Stackoverflow.com/users/16649550",
"pm_score": 2,
"selected": false,
"text": "#include <iostream>\n#include <stack>\n#include <string>\n#include <vector>\n\nint main()\n{\n std::stack<std::string> stack;\n stack.push(\"!\");\n stack.push(\"world\");\n stack.push(\"hello \");\n \n std::string str;\n\n while (!stack.empty())\n {\n str.append(stack.top());\n stack.pop();\n }\n\n std::cout << str; \n \n return 0;\n}\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12422272/"
] |
74,329,761 | <p>I tried to insert a node before a given node by specifying the position of the node before which I want to insert the newnode. I got the data present inside that node's position and using a while loop, compared this data with each node's data till I reached the point where I was supposed to insert the node.</p>
<p>But when I tried displaying the elements using a while statement my program went into an infinte loop.I checked where the head node was pointing to and its to pointing to the first node of the singly list only.
Could someone please help me out?</p>
<pre><code>
#include <iostream>
#include<stdlib.h>
using namespace std;
void display(struct node *);
struct node{
int data;
struct node *next;
};
struct node *ptr,*head=NULL;
void insertt(struct node *head){ //insert function to insert node before a node
struct node *ptr1=head;
int pos,poss,value;
cin>>poss; //getting position and value
cin>>value;
pos=poss-1;
while(pos--){ //moving to that position
ptr1=ptr1->next;
}
struct node *ptr2=ptr1;
struct node *newnode = (struct node*)malloc(sizeof(struct node)); //creating new node for insertion
newnode->next=NULL;
newnode->data=value;
struct node *preptr;
preptr=ptr1;
int c=ptr2->data; //getting value present in that particular position(node) of the list
while(ptr1->data!=c){ //inserting before node
preptr=ptr1;
ptr1=ptr1->next;
}
preptr->next=newnode;
newnode->next=ptr1;
display(head);
}
void display(struct node *head){ //displaying linked list
struct node *ptr2=head;
while(ptr2!=NULL){
cout<<ptr2->data;
ptr2=ptr2->next;
}
}
int main()
{
int n,val,i;
cin>>n; //number of nodes
for(i=0;i<n;i++){ //node creation
cin>>val;
struct node *newnode = (struct node*)malloc(sizeof(struct node));
newnode->data=val;
newnode->next=NULL;
if(head==NULL){
ptr=head;
head=newnode;
}
else{
ptr=head;
while(ptr->next!=NULL){
ptr=ptr->next;
}
ptr->next=newnode;
}
}
insertt(head); //insertion
return 0;
}
</code></pre>
| [
{
"answer_id": 74329745,
"author": "lorro",
"author_id": 6292621,
"author_profile": "https://Stackoverflow.com/users/6292621",
"pm_score": 3,
"selected": true,
"text": "while"
},
{
"answer_id": 74329788,
"author": "Pepijn Kramer",
"author_id": 16649550,
"author_profile": "https://Stackoverflow.com/users/16649550",
"pm_score": 2,
"selected": false,
"text": "#include <iostream>\n#include <stack>\n#include <string>\n#include <vector>\n\nint main()\n{\n std::stack<std::string> stack;\n stack.push(\"!\");\n stack.push(\"world\");\n stack.push(\"hello \");\n \n std::string str;\n\n while (!stack.empty())\n {\n str.append(stack.top());\n stack.pop();\n }\n\n std::cout << str; \n \n return 0;\n}\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17610052/"
] |
74,329,770 | <p>I need to create a program that searches for a user inserted number from an array using pointers. This is my current code</p>
<pre><code>#include <iostream>
using namespace std;
void FindNumber(int *ptrArr, int size, int *ptr1) {
for (int *p = ptrArr; p < ptrArr + size; ++p) {
if (ptrArr[*p] == *ptr1) {
cout << "Number (" << *ptr1 << ") found in the array with an index of: " << *p;
break;
}
if (*p == size) {
cout << "No such number in given array\n";
}
}
}
int main () {
int numbers[10] = {5, 4, 7, 10, 24, 15, 8, 2, 9, 13};
int num;
cout << "What number do you want to search for?\n";
cin >> num;
FindNumber(numbers, sizeof(numbers) / sizeof(int), &num);
return 0;
}
</code></pre>
<p>The problem is with for loop, but I don't know what it is
Sometimes it finds the number with right index, sometimes it doesn't find it even though there is that particular number in the array, sometimes it finds the number but outputs the wrong index</p>
<pre><code>What number do you want to search for?
7
No such number in given array
Number (7) found in the array with an index of: 2
What number do you want to search for?
5
No such number in given array
</code></pre>
<p>Tried changing the for loop on my own but no successo. Hoping for some help.</p>
| [
{
"answer_id": 74329745,
"author": "lorro",
"author_id": 6292621,
"author_profile": "https://Stackoverflow.com/users/6292621",
"pm_score": 3,
"selected": true,
"text": "while"
},
{
"answer_id": 74329788,
"author": "Pepijn Kramer",
"author_id": 16649550,
"author_profile": "https://Stackoverflow.com/users/16649550",
"pm_score": 2,
"selected": false,
"text": "#include <iostream>\n#include <stack>\n#include <string>\n#include <vector>\n\nint main()\n{\n std::stack<std::string> stack;\n stack.push(\"!\");\n stack.push(\"world\");\n stack.push(\"hello \");\n \n std::string str;\n\n while (!stack.empty())\n {\n str.append(stack.top());\n stack.pop();\n }\n\n std::cout << str; \n \n return 0;\n}\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18487151/"
] |
74,329,796 | <p>What is the time complexity of the second loop?</p>
<pre><code> for(int i =1; i<=n;i++)
{
for(int j=i ; j<=n; j+=i*2);
}
</code></pre>
<p>I have gone this far:</p>
<pre><code>i=1 ==> j=n/2
i=2 ==> j=(n-1)/4
i=3 ==> j=(n-2)/6
i=4 ==> j=(n-3)/8
i=n ==> j=1/2n
</code></pre>
<p>but i cant find any algorithm for this series!!</p>
| [
{
"answer_id": 74329868,
"author": "lorro",
"author_id": 6292621,
"author_profile": "https://Stackoverflow.com/users/6292621",
"pm_score": 0,
"selected": false,
"text": "floor((n - i + 1) / (2 * i))"
},
{
"answer_id": 74330080,
"author": "templatetypedef",
"author_id": 501557,
"author_profile": "https://Stackoverflow.com/users/501557",
"pm_score": 3,
"selected": true,
"text": "for (int i = 1; i <= n; i++) {\n for (int j = i; j <= n; j += i*2) {\n /* ... do nothing ... */\n }\n}\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19605618/"
] |
74,329,803 | <p>I have been trying to make my custom component for Adminjs dashboard. My project is made in Nodejs and Adminjs can be customized in React, so I created dashboard.jsx file inside components/dashboard folders, but when I implement that in Adminjs.bundle I get given file "./components/dashboard/dashboard doesn't exist". It just doesn't want to find the path to my component. please help!</p>
<p>i Have opened a new question with ComponentLoader:
<a href="https://stackoverflow.com/questions/74502027/adminjs-componentloader-not-found">Adminjs ComponentLoader not found</a></p>
<pre><code>import React, {useEffect, useState} from 'react'
import {ApiClient} from "adminjs";
const api = new ApiClient();
const Dashboard = () => {
const [data, setData] = useState({})
useEffect(() => {
api.getDashboard().then((response) => {
setData(response.data)
})
}, [])
return(
<div>
<h1>it works!</h1>
</div>
)
};
export default Dashboard
</code></pre>
<p>index.js:</p>
<pre><code>AdminJS.registerAdapter(AdminJSSequelize)
const admin = new AdminJS({
databases: [],
rootPath: '/admin',
dashboard:{
component: AdminJS.bundle("./components/dashboard/dashboard"),
},
resources:[UsersResources, GuestResources, SalesResources, FinancesResources]
})
</code></pre>
<p><a href="https://i.stack.imgur.com/eBc7I.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eBc7I.png" alt="folder structure" /></a></p>
| [
{
"answer_id": 74329868,
"author": "lorro",
"author_id": 6292621,
"author_profile": "https://Stackoverflow.com/users/6292621",
"pm_score": 0,
"selected": false,
"text": "floor((n - i + 1) / (2 * i))"
},
{
"answer_id": 74330080,
"author": "templatetypedef",
"author_id": 501557,
"author_profile": "https://Stackoverflow.com/users/501557",
"pm_score": 3,
"selected": true,
"text": "for (int i = 1; i <= n; i++) {\n for (int j = i; j <= n; j += i*2) {\n /* ... do nothing ... */\n }\n}\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12880330/"
] |
74,329,829 | <p>i'm just learning asyncio and threads, so if someting is wrong, sorry</p>
<p>this is my code:</p>
<pre><code>async def callback_onlyAlert(update: Update, context):
await update.message.reply_text('Ok! \nI will send you a message only when you can withdraw your USDN')
#run alert
t = threading.Thread(target=middleware_alert, args=(update, context,))
t.start()
def middleware_alert(update: Update,context):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(alert(update, context))
loop.close()
async def alert(update: Update, context):
global block
global withdrawal_block
while True:
await update.message.reply_text("⚠️⚠️ -10 MINUTES! ⚠️⚠️")
time.sleep(20)
</code></pre>
<p>when i run it, i get <code>got Future <Future pending> attached to a different loop</code> error, i know that asyncio make a loop for the main thread, and you can't pass object trough loops, so i think that's why i get this error</p>
<p>anyway i get update and context outside that loop, when app starts, so i can't create it after the loop starts, there is any turnaround? or i'm doing something wrong? thanks</p>
| [
{
"answer_id": 74329868,
"author": "lorro",
"author_id": 6292621,
"author_profile": "https://Stackoverflow.com/users/6292621",
"pm_score": 0,
"selected": false,
"text": "floor((n - i + 1) / (2 * i))"
},
{
"answer_id": 74330080,
"author": "templatetypedef",
"author_id": 501557,
"author_profile": "https://Stackoverflow.com/users/501557",
"pm_score": 3,
"selected": true,
"text": "for (int i = 1; i <= n; i++) {\n for (int j = i; j <= n; j += i*2) {\n /* ... do nothing ... */\n }\n}\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13461401/"
] |
74,329,830 | <p>I have a JSON file with 28 million strings, the size is roughly 15 GB. Some of the strings are duplicates, so I need to create a new JSON file with just the unique ones. I'm guessing 240 million of them are unique, but I need to find out the exact number. The strings are all less than 100 characters. Here is an example of the data:</p>
<pre><code>[
'4zWMS2IHAKcsrVtrUBFXIFjkwvbiCyiK',
'btFqRsglI1Dh81jpgmnRhKPGIBbe2cU7',
'8Us6mE6zWfyOpjhXsJssE65LrOFc7yr6',
...
]
</code></pre>
<p>My first approach was to create a JavaScript object and set all of the keys of the object to the strings. Then I would check the length of the keys and that would be my unique count. Unfortunately, I ran into a limit and JavaScript objects can only have ~8M keys.</p>
<p>My next approach was to create a new array in JavaScript and then iterate through my strings and then use the <code>.indexOf</code> method to see if I already added the string to my array. Unfortunately, this is way too slow.</p>
<p>Can anyone think of a way I can do this in JavaScript? I am also OK switching to a different language if this is not the right tool for the job.</p>
| [
{
"answer_id": 74330064,
"author": "Kirk Ouimet",
"author_id": 102635,
"author_profile": "https://Stackoverflow.com/users/102635",
"pm_score": 3,
"selected": false,
"text": "// Find the files we want to count\nlet files = NodeFileSystem.readdirSync('data/imported');\nlet keyArray = [];\nlet keyArrayLength = 0;\n\n// Add all of the keys to an array\nfor(let file of files) {\n if(file.endsWith('.json')) {\n console.log('Parsing file', file);\n let data = JSON.parse(NodeFileSystem.readFileSync('data/imported/'+file));\n\n // Add the data item.key to the array\n for(let item of data) {\n keyArray.push(item.key);\n keyArrayLength++;\n }\n }\n}\nconsole.log('Total array length:', keyArrayLength);\n\n// JavaScript will only allow us to have 8 million keys in an object, so we need to shard the array\n// into several objects, using the first characters of each key\nlet characterCountToUseForSharding = 2;\n\n// An object to store the sharded objects\nlet shardedObjects = {};\n\n// Loop through the key array\nlet processedCount = 0;\nfor(let key of keyArray) {\n processedCount++;\n if(processedCount % 1000000 === 0) {\n let processCountWithCommas = processedCount.toLocaleString();\n console.log('Processed', processCountWithCommas, 'of', keyArrayLength.toLocaleString());\n }\n\n // Get the first characterCountToUseForSharding characters of the key\n let shardingKey = key.substring(0, characterCountToUseForSharding);\n\n // If the sharded object doesn't exist, create it\n if(!shardedObjects[shardingKey]) {\n shardedObjects[shardingKey] = {};\n // console.log('Created sharded object', shardingKey);\n }\n\n // Add the key to the sharded object\n shardedObjects[shardingKey][key] = true;\n}\n\n// Count the keys in each sharded object\nlet total = 0;\nfor(let shardingKey in shardedObjects) {\n let keyCount = Object.keys(shardedObjects[shardingKey]).length;\n console.log('Sharding key', shardingKey, 'has', keyCount, 'keys');\n total += keyCount;\n}\n\n// Log the total\nconsole.log('Total keys:', keyArrayLength);\nconsole.log('Total unique keys:', total);\n\n// Percentage\nlet percentage = (total / keyArrayLength) * 100;\nconsole.log('Unique percentage:', percentage);\n\n// Duplicate keys\nlet duplicateKeys = keyArrayLength - total;\nconsole.log('Duplicate keys:', duplicateKeys);\n"
},
{
"answer_id": 74421180,
"author": "Sifat Haque",
"author_id": 5146848,
"author_profile": "https://Stackoverflow.com/users/5146848",
"pm_score": 1,
"selected": false,
"text": "Array"
},
{
"answer_id": 74458201,
"author": "OpenGG",
"author_id": 918978,
"author_profile": "https://Stackoverflow.com/users/918978",
"pm_score": 1,
"selected": false,
"text": "ShardSet()"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/102635/"
] |
74,329,841 | <p>I'm trying to create a confusion matrix, in order to build it I need to convert this matrix of predictions from my model into a label vector. (to compare it with the vector of actual labels)</p>
<p>Matrix:</p>
<pre><code> Africa America CentralAsiaSiberia EastAsia Oceania SouthAsia WestEurasia
196 1 0 0 0 0 0 0
203 0 1 0 0 0 0 0
239 0 0 0 1 0 0 0
240 0 0 0 1 0 0 0
252 0 0 0 0 0 0 1
253 0 0 0 0 0 1 0
</code></pre>
<p>Vector:</p>
<pre><code>Africa
America
EastAsia
EastAsia
WestEurasia
SouthAsia
</code></pre>
<p>I could iterate through all rows using a for loop in order to get the colname associated with the value in row which is equal to 1, but I wonder if there is a simpler way in R to do this.</p>
<p>Thanks!</p>
| [
{
"answer_id": 74330025,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 2,
"selected": true,
"text": "max.col"
},
{
"answer_id": 74330354,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 0,
"selected": false,
"text": "library(tidyverse)\n\n#option 1\ndf |>\n pivot_longer(everything()) |>\n filter(value == 1) |>\n pull(name)\n#> [1] \"Africa\" \"America\" \"EastAsia\" \"EastAsia\" \"WestEurasia\"\n#> [6] \"SouthAsia\"\n\n\n#option 2\napply(df, 1, \\(x) colnames(df)[(which(x == 1))])\n#> [1] \"Africa\" \"America\" \"EastAsia\" \"EastAsia\" \"WestEurasia\"\n#> [6] \"SouthAsia\"\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14525393/"
] |
74,329,846 | <p>How Do I make a token untransferable by the wallet owner and only transferable by the token smart contract</p>
| [
{
"answer_id": 74330025,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 2,
"selected": true,
"text": "max.col"
},
{
"answer_id": 74330354,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 0,
"selected": false,
"text": "library(tidyverse)\n\n#option 1\ndf |>\n pivot_longer(everything()) |>\n filter(value == 1) |>\n pull(name)\n#> [1] \"Africa\" \"America\" \"EastAsia\" \"EastAsia\" \"WestEurasia\"\n#> [6] \"SouthAsia\"\n\n\n#option 2\napply(df, 1, \\(x) colnames(df)[(which(x == 1))])\n#> [1] \"Africa\" \"America\" \"EastAsia\" \"EastAsia\" \"WestEurasia\"\n#> [6] \"SouthAsia\"\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20354129/"
] |
74,329,859 | <p>I have created an enum for accessories and used the switch statement in the class property to determine the price depending on the accessories chosen. A class that has two constructors implements this enum, one of the constructors accepts types from this enum as arguments while the other does not. See codes below:</p>
<p><strong>Expected result</strong></p>
<ul>
<li>If an instance of the class is instantiated with a type of the enum, switch to enum type and return price</li>
<li>If an instance of the class is instantiated without providing an enum type price should be zero.</li>
</ul>
<p><strong>Problem statement</strong></p>
<p>When an instance is initialized without providing an enum type the switch statement runs and breaks in the first case</p>
<pre class="lang-cs prettyprint-override"><code>using System;
///<summary>
/// specifies the accessories of a vehicle
///</summary>
public enum Accessories
{
StereoSystem = 0,
LeatherInterior = 1,
StereoAndLeather = 2,
ComputerNavigation = 3,
StereoAndNavigation = 4,
LeatherAndNavigation = 5,
All = 6,
None = 7
}
public SalesQuote(decimal vehicleSalePrice, decimal tradeInAmount,
decimal salesTaxRate, Accessories accessoriesChosen,
ExteriorFinish exteriorFinishChosen)
{
if (vehicleSalePrice <= 0)
throw new ArgumentOutOfRangeException("vehicleSalePrice", "The argument cannot" +
" be less than or equal to zero");
if (tradeInAmount < 0 || salesTaxRate < 0)
{
string myValue = tradeInAmount < 0 ? "tradeInAmount" : "salesTaxRate";
throw new ArgumentOutOfRangeException(myValue,
"The argument cannot be less than zero");
}
if(salesTaxRate > 1)
throw new ArgumentOutOfRangeException("salesTaxRate",
"The argument cannot be greater than 1");
if((!(accessoriesChosen.GetType() == typeof(Accessories) ||!(Enum.IsDefined(typeof(Accessories),accessoriesChosen)) )
||((!(exteriorFinishChosen.GetType() == typeof(ExteriorFinish)) || !(Enum.IsDefined(typeof(ExteriorFinish),exteriorFinishChosen))))))
throw new System.ComponentModel.InvalidEnumArgumentException
("The argument is an invalid enumeration value");
this.vehicleSalePrice = vehicleSalePrice;
this.tradeInAmount = tradeInAmount;
this.salesTaxRate = salesTaxRate;
this.accessoriesChosen = accessoriesChosen;
this.exteriorFinishChosen = exteriorFinishChosen;
}
/// Second Constructor
public SalesQuote(decimal vehicleSalePrice, decimal tradeInAmount, decimal salesTaxRate)
{
if (vehicleSalePrice <= 0 || tradeInAmount < 0)
{
string myValue = vehicleSalePrice <= 0 ? "vehicleSalePrice" : "tradeInAmount";
string completionString = tradeInAmount < 0 ? "0" : "or equal to zero";
throw new ArgumentOutOfRangeException(myValue, "The argument cannot be less than " +
completionString);
}
if (salesTaxRate < 0 || salesTaxRate > 1)
{
string completionString = salesTaxRate < 0 ? "less than 0" : "greater than 1";
throw new ArgumentOutOfRangeException("salesTaxRate", "The argument cannot be " +
completionString);
}
this.vehicleSalePrice = vehicleSalePrice;
this.tradeInAmount = tradeInAmount;
this.salesTaxRate = salesTaxRate;
}
/// cost property
public decimal AccessoryCost
{
get
{
decimal accessoryPrice = 0;
switch (this.AccessoriesChosen)
{
case Accessories.StereoSystem:
accessoryPrice = 505.05m;
break;
case Accessories.LeatherInterior:
accessoryPrice = 1010.10m;
break;
case Accessories.ComputerNavigation:
accessoryPrice = 1515.15m;
break;
case Accessories.StereoAndNavigation:
decimal total = 505.05m + 1515.15m;
accessoryPrice = total;
break;
case Accessories.LeatherAndNavigation:
total = 1010.10m + 1515.15m;
accessoryPrice = total;
break;
case Accessories.All:
total = 1010.10m + 1515.15m + 505.05m;
accessoryPrice = total;
break;
default:
accessoryPrice = 0;
break;
}
return accessoryPrice;
}
}
</code></pre>
<p>Initialize with second constructor</p>
<pre class="lang-cs prettyprint-override"><code>SalesQuote mySalesQuote = new SalesQuote(500,200,.5);
decimal cost = mySalesQuote.AccessoryCost;
/// cost should be zero in this instance since no accessory was selected but I am getting 505.05
</code></pre>
<p>Please can someone let me know why this is and how to resolve this.</p>
<p>Thanks</p>
<p>I have tried using conditions in the different cases but it appears the type is implicitly casted to the Accessories type which I don't understand why.</p>
<pre><code>case Accessories.StereoSystem:
accessoryPrice = !Enum.IsDefined(typeof(Accessories),accessoriesChosen) ? 0 : 505.05m;
break;
</code></pre>
| [
{
"answer_id": 74330337,
"author": "Thomas Weller",
"author_id": 480982,
"author_profile": "https://Stackoverflow.com/users/480982",
"pm_score": 1,
"selected": false,
"text": "SalesQuote(decimal vehicleSalePrice, decimal tradeInAmount, decimal salesTaxRate)\n"
},
{
"answer_id": 74330488,
"author": "Olivier Jacot-Descombes",
"author_id": 880990,
"author_profile": "https://Stackoverflow.com/users/880990",
"pm_score": 3,
"selected": true,
"text": "None"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13206046/"
] |
74,329,891 | <pre><code>leading: Padding(
padding: EdgeInsets.only(left: 20),
child: IconButton(
onPressed: () => print('Menu Tapped'),
icon: Image.asset(
'assets/images/vecteezy_triangle_1200693.png',
fit: BoxFit.fitWidth,
),
),
),
</code></pre>
<p>I try adding height: and width: to the Image.asset and iconsize: to IconButton but it does't work</p>
<p>Does it have something to do with edgeInsets?</p>
<p>PS* I'm quite new here, I'm follow YouTube to write a financial management app</p>
| [
{
"answer_id": 74330337,
"author": "Thomas Weller",
"author_id": 480982,
"author_profile": "https://Stackoverflow.com/users/480982",
"pm_score": 1,
"selected": false,
"text": "SalesQuote(decimal vehicleSalePrice, decimal tradeInAmount, decimal salesTaxRate)\n"
},
{
"answer_id": 74330488,
"author": "Olivier Jacot-Descombes",
"author_id": 880990,
"author_profile": "https://Stackoverflow.com/users/880990",
"pm_score": 3,
"selected": true,
"text": "None"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20427219/"
] |
74,329,902 | <p>I want to use stripe android sdk pre build UI <strong>payment sheet</strong> for recurring payment (Subscription) in my android app.
I see payment sheet example for <strong>non recurring payment</strong> on stripe document but i didn't found document for <strong>subscription in android</strong>. I have spend lot of time to find example of same but i didn't get any solution.</p>
<p>If anyone help me then it's save my day.</p>
| [
{
"answer_id": 74341841,
"author": "orakaro",
"author_id": 3631795,
"author_profile": "https://Stackoverflow.com/users/3631795",
"pm_score": 1,
"selected": false,
"text": "latest_invoice.payment_intent.client_secret"
},
{
"answer_id": 74360212,
"author": "Pavel K",
"author_id": 7864454,
"author_profile": "https://Stackoverflow.com/users/7864454",
"pm_score": 2,
"selected": false,
"text": "https://api.stripe.com/v1/subscriptions"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8740243/"
] |
74,329,912 | <p>This is my first question here and this is also one of my first codes ever so please be understanding :D</p>
<p>I need to create something like this: <a href="https://i.stack.imgur.com/mH18n.png" rel="nofollow noreferrer">https://i.stack.imgur.com/mH18n.png</a>.</p>
<p>I don't know what I can do to make span class="price" to the next line. This is still in the same line with class="annual".</p>
<p>Here is my HTML code:</p>
<pre><code><div class="priceinfo">
<img src="order-summary-component-main/images/icon-music.svg" />
<span class="annual">Annual plan</span>
<span class="price">&#x24; 59.99/year</span>
<a class="change" href="">Change</a>
</div>
</code></pre>
<p>And here is my CSS:</p>
<pre><code>.priceinfo {
display: flex;
justify-content: space-between;
align-items: center;
}
</code></pre>
<p>Do you have any ideas what I did wrong and what can I correct?</p>
<p>Thank you in advance!</p>
| [
{
"answer_id": 74341841,
"author": "orakaro",
"author_id": 3631795,
"author_profile": "https://Stackoverflow.com/users/3631795",
"pm_score": 1,
"selected": false,
"text": "latest_invoice.payment_intent.client_secret"
},
{
"answer_id": 74360212,
"author": "Pavel K",
"author_id": 7864454,
"author_profile": "https://Stackoverflow.com/users/7864454",
"pm_score": 2,
"selected": false,
"text": "https://api.stripe.com/v1/subscriptions"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20420241/"
] |
74,329,922 | <p>I wrote a code to calculate an average, but it takes only the first item in the list.
I want to input a list of key=value and it should add all the values and then divide by the total number, so it gives me the average.</p>
<pre><code>def average_price_petrol(**args):
result = 0
total = 0
for key,value in args.items():
result += value
total +=1
return result/total
average_price_petrol(aral = 1.799, bft = 1.629, esso = 1.799, shell = 1.829, jet = 1.719)
</code></pre>
| [
{
"answer_id": 74329979,
"author": "m_j_alkarkhi",
"author_id": 16138689,
"author_profile": "https://Stackoverflow.com/users/16138689",
"pm_score": 2,
"selected": false,
"text": "def average_price_petrol(**args):\n result = 0\n total = 0\n for key,value in args.items():\n result += value\n total +=1\n return result/total\n"
},
{
"answer_id": 74330047,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 3,
"selected": true,
"text": "return"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20310544/"
] |
74,329,940 | <p>New to python. Here's a nested dictionary with two books each having 8 attributes.</p>
<pre><code>book_collection ={17104: {'Title': 'A River', 'Author': 'Elisha Mitchell', 'Publisher': 'FPG Publishing', 'Pages': '345', 'Year': '2014', 'Copies': 2, 'Available': 2, 'ID': 17104}, 37115: {'Title': 'Aim High', 'Author': 'George Tayloe Winston', 'Publisher': 'Manning Hall Press', 'Pages': '663', 'Year': '2014', 'Copies': 5, 'Available': 5, 'ID': 37115}}
for id, book in book_collection.items():
for book_attribute, attribute_value in book.items():
print(book_attribute, ': ', attribute_value, sep='')
</code></pre>
<p>The output:</p>
<pre><code>Title: A River
Author: Elisha Mitchell
Publisher: FPG Publishing
Pages: 345
Year: 2014
Copies: 2
Available: 2
ID: 17104
Title: Aim High
Author: George Tayloe Winston
Publisher: Manning Hall Press
Pages: 663
Year: 2014
Copies: 5
Available: 5
ID: 37115
</code></pre>
<p>How can I add a blank space between each book, and bring the 'ID' attribute to the first row of each book. The output is supposed to look like this:</p>
<pre><code>ID: 17104
Title: A River
Author: Elisha Mitchell
Publisher: FPG Publishing
Pages: 345
Year: 2014
Copies: 2
Available: 2
ID: 37115
Title: Aim High
Author: George Tayloe Winston
Publisher: Manning Hall Press
Pages: 663
Year: 2014
Copies: 5
Available: 5
</code></pre>
<p>If there are 20 books, how can I just print the first 10 and ask the user for permission to continue?</p>
| [
{
"answer_id": 74329979,
"author": "m_j_alkarkhi",
"author_id": 16138689,
"author_profile": "https://Stackoverflow.com/users/16138689",
"pm_score": 2,
"selected": false,
"text": "def average_price_petrol(**args):\n result = 0\n total = 0\n for key,value in args.items():\n result += value\n total +=1\n return result/total\n"
},
{
"answer_id": 74330047,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 3,
"selected": true,
"text": "return"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20178894/"
] |
74,329,949 | <p>I use <code>boost::intrusive_ptr</code> in my project and have such code:</p>
<pre><code>void foo(boost::intrusive_ptr<MyObject> obj) {
// do something with obj
}
</code></pre>
<p>And I have clang-tidy diagnostic:</p>
<pre><code>Clang-Tidy: The parameter 'obj' is copied for each invocation but only used as a const reference; consider making it a const reference
</code></pre>
<p>But <code>boost::intrusive_ptr</code> copying on function invocation is intended usage of it, because it's wrapping a pointer and usually we don't want to add one more level of indirection. There are no such diagnostic for <code>std::shared_ptr</code> which have similar usage.</p>
<p>How to add <code>boost::intrusive_ptr</code> to the list of clang-tidy exceptions for this diagnostic rule to avoid false warnings?</p>
| [
{
"answer_id": 74329979,
"author": "m_j_alkarkhi",
"author_id": 16138689,
"author_profile": "https://Stackoverflow.com/users/16138689",
"pm_score": 2,
"selected": false,
"text": "def average_price_petrol(**args):\n result = 0\n total = 0\n for key,value in args.items():\n result += value\n total +=1\n return result/total\n"
},
{
"answer_id": 74330047,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 3,
"selected": true,
"text": "return"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7549594/"
] |
74,329,954 | <p>Hi everyone <br> So basically I have to code a website that calculates a certain amount using javascript, here is the exemple of the website :
<a href="https://i.stack.imgur.com/I21yf.png" rel="nofollow noreferrer">Check here</a>. <br> So basically the client fills the form with the quantity and I have to display the total of his command, he doesn't need to submit the form</p>
<p>The uncomplete code is this one :</p>
<pre><code><h1>Vente de Pizza</h1>
<form method="post" action="#">
Nom du client<input type="text" name="nom" /> <br> <BR></BR>
adresse<input type="text" name="adresse" /><br>
<h1>Produits à acheter</h1>
<table border = "1">
<tr><th>Nom du produit</th>
<th>Prix unitaire</th>
<th>Quantité</th>
</tr>
<tr>
<td>Pizza 4 fromages</td>
<td>80</td>
<td><input type="text" name="QTE1" id = "x1" /></td>
</tr>
<tr>
<td>Pizza Herbo</td>
<td>75</td>
<td><input type="text" name="QTE2" id = "x2"/></td>
</tr>
<tr>
<td>Pizza viande hachée</td>
<td>100</td>
<td><input type="text" name="QTE3" id = "x3"/></td>
</tr>
<tr>
<td>Pizza Fruit de mer</td>
<td>120</td>
<td><input type="text" name="QTE4" id = "x4"/></td>
</tr>
</table>
<p font = "bold" style="font-weight: BOLD;"> Paiment par: </p><br>
<input type="radio" name="banque" id="">Carte bancaire
<input type="radio" name="banque" id="">Chèque <BR></BR>
Numéro de la carte bancaire<input type="text" name="numCB" id = "x5" style="width: 400px;"/> <br><BR>
<button class="btn" type="submit" onkeydown = "mySubmit()" id ="bouton">Envoyer</button> <BR></BR>
<script>
function TotalCalculate(){
var x1 = document.getElementById("x1").value;
var x2 = document.getElementById("x2").value;
var x3 = document.getElementById("x3").value;
var x4 = document.getElementById("x4").value;
var tot = x1*80;
document.getElementById("Total").addEventListener("click", writeTotal);
function writeTotal(){
document.getElementById("Total").write(tot);
}
}
</script>
Merci de votre visite le montant total de votre commande est :
<input type="text" name="Total" onclick="TotalCalculate()" id = "Total"/>
</form>
</code></pre>
<p>So as you can see I get the value from the user and calculates the total to pay, but it doesn't show anything. laybe i need to add a listner but i can't find how to add a listner that writes something.
Please help</p>
| [
{
"answer_id": 74329979,
"author": "m_j_alkarkhi",
"author_id": 16138689,
"author_profile": "https://Stackoverflow.com/users/16138689",
"pm_score": 2,
"selected": false,
"text": "def average_price_petrol(**args):\n result = 0\n total = 0\n for key,value in args.items():\n result += value\n total +=1\n return result/total\n"
},
{
"answer_id": 74330047,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 3,
"selected": true,
"text": "return"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19615773/"
] |
74,329,965 | <p>As described in the title, I have the following problem:</p>
<p>Data is prepared as a pandas dataframe incoming as follows:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Article</th>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr>
<td>A0</td>
<td>A00183</td>
</tr>
<tr>
<td>BB2</td>
<td>BB2725</td>
</tr>
<tr>
<td>C2C3</td>
<td>C2C3945</td>
</tr>
</tbody>
</table>
</div>
<p>As you can see, the "Title" column is repeating the string value of the <code>Article</code> column.</p>
<p>I want this to be deleted, so that the table looks as follows:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Article</th>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr>
<td>A0</td>
<td>0183</td>
</tr>
<tr>
<td>BB2</td>
<td>725</td>
</tr>
<tr>
<td>C2C3</td>
<td>945</td>
</tr>
</tbody>
</table>
</div>
<p>I want to do this with Pandas.</p>
<p>I already found out how to read the length of the string row in column <code>Article</code>, so that I already know the amount of characters to be deducted with this:</p>
<pre><code>df1['Length of Article string:'] = df1['Article:'].apply(len)
</code></pre>
<p>But now I am to stupid to figure out how to delete the strings, that can change in amount for every row, in the <code>Title</code> column.</p>
<p>Thanks for your help!</p>
<p>Kind regards</p>
<p>Tried Pandas Documentation, found some hints regarding split and strip, but I do not have enough know-how to implement...</p>
| [
{
"answer_id": 74329979,
"author": "m_j_alkarkhi",
"author_id": 16138689,
"author_profile": "https://Stackoverflow.com/users/16138689",
"pm_score": 2,
"selected": false,
"text": "def average_price_petrol(**args):\n result = 0\n total = 0\n for key,value in args.items():\n result += value\n total +=1\n return result/total\n"
},
{
"answer_id": 74330047,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 3,
"selected": true,
"text": "return"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17872048/"
] |
74,329,966 | <p>I'm building on my practice web app and I'm tried to filter the data from fetched data but it filter real time. My question is how to make it not real time, like when searchbar is empty it will fetch all data but when type a text in searchbar it will fetch data from input text.</p>
<p>Here is my code</p>
<pre><code> const { data, loading, error } = useFetch(BASE_URL)
const [search, setSearch] = useState("")
const [inp, setInp] = useState("")
const handleChange = (e) => {
setSearch(e.target.value)
}
if (loading) return <h1> LOADING...</h1>
if (error) console.log(error)
return (
<div className="App" >
<div className="Container">
<label className='header'>Topic</label>
<div className="Container-searchBar">
<input type="Text" value={search} placeholder="Search . . ." onChange={handleChange}/>
</div>
{data.filter((val) => {
if (search === "") {
return val
}
else if (val.tags.includes(search)) {
return val
}
}).map((post) => {
return
.
My return
.
})}
</div>
</div>
);
</code></pre>
<p>I'm new to React and JS so sorry for some bad question.</p>
| [
{
"answer_id": 74329979,
"author": "m_j_alkarkhi",
"author_id": 16138689,
"author_profile": "https://Stackoverflow.com/users/16138689",
"pm_score": 2,
"selected": false,
"text": "def average_price_petrol(**args):\n result = 0\n total = 0\n for key,value in args.items():\n result += value\n total +=1\n return result/total\n"
},
{
"answer_id": 74330047,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 3,
"selected": true,
"text": "return"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18642394/"
] |
74,329,987 | <p>I have two dataframes of different length. The first looks like this and is the dataframe I want to add the True/False column to:</p>
<pre><code>chr_snp loc_snp ma_snp
1 184319928 T
1 276998062 A
1 278255864 G
2 243012470 G
2 123072103 T
3 526785124 A
</code></pre>
<p>The second data frame is the reference dataframe that is smaller:</p>
<pre><code>chr_QTL loc_QTL ma_QTL
1 281788173 G
1 203085725 C
2 241577141 C
</code></pre>
<p>For each row in dataframe 1 (<code>df1</code>), I want to first check if the value of <code>df1$chr_snp</code> matches a value in df2$chr_QTL. If this match is true, then I want to determine if the value in <code>df1$loc_snp</code> is within 10 million units (these are DNA base-pairs) above OR below any values based on the first condition in <code>df2$loc_QTL</code>. Now, what is tricky is that for the first three rows of <code>df1</code>, there are three possible row matches in <code>df2</code> (rows 1 and 2) based on the first criteria alone. However, only two match based on the second criteria (10M base-pairs greater than OR less than value in <code>df2$loc_QTL</code>). Note: <code>df1$ma_snp</code> and <code>df2$ma_QTL</code> can be totally ignored. So, based on these criteria, <code>df1</code> should now look like:</p>
<pre><code>chr_snp loc_snp ma_snp Match
1 184319928 T FALSE
1 276998062 A TRUE
1 278255864 G TRUE
2 243012470 G TRUE
2 123072103 T FALSE
3 526785124 A FALSE
</code></pre>
| [
{
"answer_id": 74330060,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 2,
"selected": true,
"text": "library(tidyverse)\n\nleft_join(df1 |>\n mutate(rw_id = row_number()), \n df2, by = c(\"chr_snp\" = \"chr_QTL\")) |>\n mutate(less = abs(loc_snp -loc_QTL) < 10e6) |>\n group_by(rw_id)|>\n summarise(across(contains(colnames(df1)), ~.[[1]]),\n Match = any(less),\n Match = ifelse(is.na(Match), FALSE, Match))\n#> # A tibble: 6 x 5\n#> rw_id chr_snp loc_snp ma_snp Match\n#> <int> <dbl> <dbl> <chr> <lgl>\n#> 1 1 1 184319928 T FALSE\n#> 2 2 1 276998062 A TRUE \n#> 3 3 1 278255864 G TRUE \n#> 4 4 2 243012470 G TRUE \n#> 5 5 2 123072103 T FALSE\n#> 6 6 3 526785124 A FALSE\n"
},
{
"answer_id": 74330136,
"author": "Ric Villalba",
"author_id": 6912817,
"author_profile": "https://Stackoverflow.com/users/6912817",
"pm_score": 0,
"selected": false,
"text": "split(df1, 1:NROW(df1)) <- lapply(split(df1, 1:NROW(df1)), function(x) \n x$Match <- any(df2$chr_QTL==x$chr_snp & abs(df2$loc_QTL - x$loc_snp) < 1e7))\n\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6836719/"
] |
74,329,994 | <p>I have a problem getting data through related_name, it can't find the attribute all(). =(<a href="https://i.stack.imgur.com/JcrYV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JcrYV.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/bC4AO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bC4AO.png" alt="enter image description here" /></a></p>
<p>The picture shows my attempts, but they did not lead to a result.</p>
| [
{
"answer_id": 74330060,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 2,
"selected": true,
"text": "library(tidyverse)\n\nleft_join(df1 |>\n mutate(rw_id = row_number()), \n df2, by = c(\"chr_snp\" = \"chr_QTL\")) |>\n mutate(less = abs(loc_snp -loc_QTL) < 10e6) |>\n group_by(rw_id)|>\n summarise(across(contains(colnames(df1)), ~.[[1]]),\n Match = any(less),\n Match = ifelse(is.na(Match), FALSE, Match))\n#> # A tibble: 6 x 5\n#> rw_id chr_snp loc_snp ma_snp Match\n#> <int> <dbl> <dbl> <chr> <lgl>\n#> 1 1 1 184319928 T FALSE\n#> 2 2 1 276998062 A TRUE \n#> 3 3 1 278255864 G TRUE \n#> 4 4 2 243012470 G TRUE \n#> 5 5 2 123072103 T FALSE\n#> 6 6 3 526785124 A FALSE\n"
},
{
"answer_id": 74330136,
"author": "Ric Villalba",
"author_id": 6912817,
"author_profile": "https://Stackoverflow.com/users/6912817",
"pm_score": 0,
"selected": false,
"text": "split(df1, 1:NROW(df1)) <- lapply(split(df1, 1:NROW(df1)), function(x) \n x$Match <- any(df2$chr_QTL==x$chr_snp & abs(df2$loc_QTL - x$loc_snp) < 1e7))\n\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16829846/"
] |
74,329,999 | <p>Dear Stackoverflow community,</p>
<p>I have been trying to read these set of daily stock market data using xts object and been getting different types of error messages, listed below.
The dataset contains 5030 observations, from 4/01/2000-22/07/2019.</p>
<ol>
<li>I have checked for NAs in the dataset, and there are none</li>
<li>I have tried changing the format of the dataset from dd/mm/yyyy to yyyy/mm/dd, it doesnt seem to work</li>
<li>i checked to see if I change it to quarterly and then try to read it if it works, and it does.
So I think there is a problem with the code that I am using to read the daily data.</li>
<li>The dataset is the package <code>SystemicR</code> author's dataset called <code>data_stock_returns</code>, and im trying to recreate the results before I try my own dataset.
Below is the dataset and the code I tried.
Would really appreciate it if someone in the community could help out with this problem.
Thank You</li>
</ol>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">Date</th>
<th style="text-align: center;">SXXP</th>
<th style="text-align: right;">STJ</th>
<th style="text-align: left;">ISP</th>
<th style="text-align: center;">INGA</th>
<th style="text-align: center;">Index</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">4/01/2000</td>
<td style="text-align: center;">0</td>
<td style="text-align: right;">0</td>
<td style="text-align: left;">-0.0209</td>
<td style="text-align: center;">-0.0274</td>
<td style="text-align: center;">1</td>
</tr>
<tr>
<td style="text-align: left;">5/01/2000</td>
<td style="text-align: center;">0</td>
<td style="text-align: right;">-0.02484</td>
<td style="text-align: left;">-0.0020</td>
<td style="text-align: center;">-0.00854</td>
<td style="text-align: center;">2</td>
</tr>
<tr>
<td style="text-align: left;">6/01/2000</td>
<td style="text-align: center;">0</td>
<td style="text-align: right;">0.0995</td>
<td style="text-align: left;">-0.0212</td>
<td style="text-align: center;">-0.00689</td>
<td style="text-align: center;">3</td>
</tr>
<tr>
<td style="text-align: left;">7/01/2000</td>
<td style="text-align: center;">0</td>
<td style="text-align: right;">0.061</td>
<td style="text-align: left;">0.02303</td>
<td style="text-align: center;">0.01961</td>
<td style="text-align: center;">4</td>
</tr>
<tr>
<td style="text-align: left;">10/01/2000</td>
<td style="text-align: center;">-0.00147</td>
<td style="text-align: right;">-0.0456</td>
<td style="text-align: left;">-0.0172</td>
<td style="text-align: center;">0.00119</td>
<td style="text-align: center;">5</td>
</tr>
<tr>
<td style="text-align: left;">..........</td>
<td style="text-align: center;">........</td>
<td style="text-align: right;">.......</td>
<td style="text-align: left;">.......</td>
<td style="text-align: center;">........</td>
<td style="text-align: center;">....</td>
</tr>
<tr>
<td style="text-align: left;">22/07/2019</td>
<td style="text-align: center;">0</td>
<td style="text-align: right;">-0.0127</td>
<td style="text-align: left;">0.00124</td>
<td style="text-align: center;">0.0029756</td>
<td style="text-align: center;">5030</td>
</tr>
</tbody>
</table>
</div>
<pre><code>df_my_data <- read.csv(('C:/Users/s/Desktop/R/intro/data/data_stock_returns.csv'), sep = ";")
str(df_my_data)
'data.frame': 5030 obs. of 74 variables:
$ Index : int 1 2 3 4 5 6 7 8 9 10 ...
$ SXXP : num 0 0 0 0 0 ...
$ STJ : num 0 -0.0248 0.0995 0.0611 -0.0456 ...
$ ISP : num -0.021 -0.0021 -0.0212 0.023 -0.0173 ...
xts(df_my_data, order.by = as.Date(rownames(df_my_data$Date), "%d/%m/%Y"))
df_my_data$Date <- as.Date(df_my_data$Date)
</code></pre>
<p>I get the below 2 error message</p>
<blockquote>
<p>Error in <code>$<-.data.frame</code>(<code>*tmp*</code>, Date, value = numeric(0)) : replacement has 0 rows, data has 5030</p>
</blockquote>
<blockquote>
<p>Error in xts(df_my_data, order.by = as.Date(rownames(df_my_data), "%d/%m/%Y")) :
'order.by' cannot contain 'NA', 'NaN', or 'Inf'</p>
</blockquote>
<pre><code>df_my_data$Date_xts <- as.xts(df_my_data[, -1], order.by = (df_my_data$Date))
</code></pre>
<p>I get another error message</p>
<blockquote>
<p>Error in xts(x, order.by = order.by, frequency = frequency, ...) :
order.by requires an appropriate time-based object</p>
</blockquote>
<pre><code>library(SystemicR)
l_result<- f_CoVaR_Delta_CoVaR_i_q(data_stock_returns)
</code></pre>
| [
{
"answer_id": 74331528,
"author": "Chris",
"author_id": 794450,
"author_profile": "https://Stackoverflow.com/users/794450",
"pm_score": 2,
"selected": false,
"text": "df <- data.frame(Date = c('4/01/2000', '5/01/2000'), SXXP=c(0,0), STJ=c(0,-0.02484), ISP=c(-0.0209,-0.0020), INGA=c(-0.0274, -0.00854))\ndf\n Date SXXP STJ ISP INGA\n1 4/01/2000 0 0.00000 -0.0209 -0.02740\n2 5/01/2000 0 -0.02484 -0.0020 -0.00854\n"
},
{
"answer_id": 74332898,
"author": "G. Grothendieck",
"author_id": 516548,
"author_profile": "https://Stackoverflow.com/users/516548",
"pm_score": 2,
"selected": false,
"text": "df"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74329999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17940819/"
] |
74,330,012 | <p>Assume <code>P: nat -> T -> Prop</code> is a proposition that for any given <code>t: T</code>,</p>
<ul>
<li>either there exists a <code>k: nat</code> such that <code>P</code> holds for all numbers greater than or equal to <code>k</code> and no number less than <code>k</code>.</li>
<li>or <code>P k t</code> is false for all <code>k : nat</code>.</li>
</ul>
<p>I want to define <code>min_k : T -> nat + undef</code> to be the minimum number <code>k</code> such that <code>P k t</code> holds, and <code>undef</code> otherwise.</p>
<p>Is that even possible? I tried to define something like</p>
<pre><code>Definition halts (t : T) := exists k : nat, P k t.
</code></pre>
<p>Or maybe</p>
<pre><code>Definition halts (t : T) := exists! k : nat, (~ P k t /\ P (S k) t).
</code></pre>
<p>and then use it like</p>
<pre><code>Definition min_k (t : T) := match halts T with
| True => ??
| False => undef
end.
</code></pre>
<p>but I don't know how to go further from there.</p>
<p>Any ideas would be appreciated.</p>
| [
{
"answer_id": 74332663,
"author": "Ana Borges",
"author_id": 2305458,
"author_profile": "https://Stackoverflow.com/users/2305458",
"pm_score": 3,
"selected": true,
"text": "match"
},
{
"answer_id": 74348332,
"author": "Arthur Azevedo De Amorim",
"author_id": 1633770,
"author_profile": "https://Stackoverflow.com/users/1633770",
"pm_score": 1,
"selected": false,
"text": "option nat"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5774661/"
] |
74,330,024 | <p>I have encountered some challenge, I just want to confirm my knowledge is correct.</p>
<p>How are you going to implement this?</p>
<blockquote>
<p>For example, if your program is written in Java the Sieve of Eratosthenes testing should run in one thread, and the Brute Force testing should run concurrently in a separate thread. Finally, your program should report the results of the benchmarking to the screen and exit.</p>
</blockquote>
<p>Thank you Guys!</p>
<p>Is it Something like this?</p>
<pre><code>class TestMultitasking4{
public static void main(String args[]){
Thread t1=new Thread(){
public void run(){
System.out.println("task one");
}
};
Thread t2=new Thread(){
public void run(){
System.out.println("task two");
}
};
t1.start();
t2.start();
}
}
</code></pre>
| [
{
"answer_id": 74332663,
"author": "Ana Borges",
"author_id": 2305458,
"author_profile": "https://Stackoverflow.com/users/2305458",
"pm_score": 3,
"selected": true,
"text": "match"
},
{
"answer_id": 74348332,
"author": "Arthur Azevedo De Amorim",
"author_id": 1633770,
"author_profile": "https://Stackoverflow.com/users/1633770",
"pm_score": 1,
"selected": false,
"text": "option nat"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20427317/"
] |
74,330,041 | <p>I am trying to format these 2 user inputs into a file on seperate lines I know I have to us the \n to use a new line but I keep getting errors with where I put it, is there another way to get each user input on a new line?</p>
<p>'''</p>
<pre><code>def userfile():
text = []
text.append(input("Enter sentence 1: "))
text.append(input("Enter sentence 2: "))
file = open(os.path.join(sys.path[0], "sample2.txt"), "w")
file.writelines(text)
file.close()
newfile = open(os.path.join(sys.path[0],"sample2.txt"), "r")
print(newfile.read())
def main():
#txtfile()
userfile()
if __name__ == "__main__":
main()
</code></pre>
| [
{
"answer_id": 74332663,
"author": "Ana Borges",
"author_id": 2305458,
"author_profile": "https://Stackoverflow.com/users/2305458",
"pm_score": 3,
"selected": true,
"text": "match"
},
{
"answer_id": 74348332,
"author": "Arthur Azevedo De Amorim",
"author_id": 1633770,
"author_profile": "https://Stackoverflow.com/users/1633770",
"pm_score": 1,
"selected": false,
"text": "option nat"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15235615/"
] |
74,330,055 | <p>I have the following problem, and I am not sure how to access the item from a nested json file.
Could anyone help me out here, please!</p>
<pre><code>intents = {"intents": [
{"tag": "greeting",
"patterns": ["Hi", "Hey", "Is anyone there?", "Hello", "Hay"],
"responses": ["Hello", "Hi", "Hi there"]
},
{"tag": "goodbye",
"patterns": ["Bye", "See you later", "Goodbye"],
"responses": ["See you later", "Have a nice day", "Bye! Come back again"]
},
{"tag": "thanks",
"patterns": ["Thanks", "Thank you", "That's helpful", "Thanks for the help"],
"responses": ["Happy to help!", "Any time!", "My pleasure", "You're most welcome!"]
},
{"tag": "about",
"patterns": ["Who are you?", "What are you?", "Who you are?" ],
"responses": ["I.m Joana, your bot assistant", "I'm Joana, an Artificial Intelligent bot"]
},
{"tag": "name",
"patterns": ["what is your name", "what should I call you", "whats your name?"],
"responses": ["You can call me Joana.", "I'm Joana!", "Just call me as Joana"]
},
{"tag": "help",
"patterns": ["Could you help me?", "give me a hand please", "Can you help?", "What can you do for me?", "I need a support", "I need a help", "support me please"],
"responses": ["Tell me how can assist you", "Tell me your problem to assist you", "Yes Sure, How can I support you"]
},
{"tag": "createaccount",
"patterns": ["I need to create a new account", "how to open a new account", "I want to create an account", "can you create an account for me", "how to open a new account"],
"responses": ["You can just easily create a new account from our web site", "Just go to our web site and follow the guidelines to create a new account"]
},
{"tag": "complaint",
"patterns": ["have a complaint", "I want to raise a complaint", "there is a complaint about a service"],
"responses": ["Please provide us your complaint in order to assist you", "Please mention your complaint, we will reach you and sorry for any inconvenience caused"]
}
]
}
</code></pre>
<p>I wanted to print out ['intents'], see my attemps below.
Here is my attempt, but I got an error as shown below:</p>
<pre><code>new_intents = json.dumps(intents, indent=4)
</code></pre>
<pre><code>with open('json_data.json', 'w') as outfile:
json.dump(new_intents, outfile)
</code></pre>
<pre><code>with open('json_data.json') as json_file:
data = json.load(json_file)
print(data['intents'])
</code></pre>
<p>I got a TypeError: string indices must be integers
I am not sure what's the problem and how to fix it.</p>
| [
{
"answer_id": 74330157,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 2,
"selected": true,
"text": "new_intents = json.dumps(intents, indent=4)"
},
{
"answer_id": 74330178,
"author": "Muhammad Mirab Br.",
"author_id": 12824833,
"author_profile": "https://Stackoverflow.com/users/12824833",
"pm_score": 0,
"selected": false,
"text": "import json\n\nintents = {\"intents\": [\n {\"tag\": \"greeting\",\n \"patterns\": [\"Hi\", \"Hey\", \"Is anyone there?\", \"Hello\", \"Hay\"],\n \"responses\": [\"Hello\", \"Hi\", \"Hi there\"]\n },\n {\"tag\": \"goodbye\",\n \"patterns\": [\"Bye\", \"See you later\", \"Goodbye\"],\n \"responses\": [\"See you later\", \"Have a nice day\", \"Bye! Come back again\"]\n },\n ...\n {\"tag\": \"createaccount\",\n \"patterns\": [\"I need to create a new account\", \"how to open a new account\", \"I want to create an account\", \"can you create an account for me\", \"how to open a new account\"],\n \"responses\": [\"You can just easily create a new account from our web site\", \"Just go to our web site and follow the guidelines to create a new account\"]\n },\n {\"tag\": \"complaint\",\n \"patterns\": [\"have a complaint\", \"I want to raise a complaint\", \"there is a complaint about a service\"],\n \"responses\": [\"Please provide us your complaint in order to assist you\", \"Please mention your complaint, we will reach you and sorry for any inconvenience caused\"]\n }\n]\n}\nwith open('json_data.json', 'w') as outfile:\n json.dump(intents, outfile)\nwith open('json_data.json') as json_file:\n data = json.load(json_file)\nprint(data['intents'])\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18369373/"
] |
74,330,058 | <p><a href="https://i.stack.imgur.com/Rdqig.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Rdqig.png" alt="Data Image" /></a></p>
<p>data.info()
data['Timestamp']=pd.to_datetime(data['Timestamp'], errors='coerce')</p>
<pre><code>import datetime as dt
#function for month
def get_month(x):
return dt.datetime(x.year, x.month,1)
#apply the function
data['get_Timestamp'] = data['Timestamp'].apply(get_month)
data.tail()
</code></pre>
<p>i want get my timestamp month like 2022-10-01</p>
| [
{
"answer_id": 74330234,
"author": "Abhi",
"author_id": 7430727,
"author_profile": "https://Stackoverflow.com/users/7430727",
"pm_score": 1,
"selected": false,
"text": "df['get_Timestamp'] = df['ArrivalDate'].dt.month\n"
},
{
"answer_id": 74330268,
"author": "Bushmaster",
"author_id": 15415267,
"author_profile": "https://Stackoverflow.com/users/15415267",
"pm_score": 0,
"selected": false,
"text": "data['Timestamp']=pd.to_datetime(data['Timestamp'], errors='coerce',format='%Y-%d-%m %H:%M:%S')\ndata['get_Timestamp'] = data['Timestamp'].dt.strftime('%Y-%m-01')\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20303505/"
] |
74,330,085 | <p>I am trying to combine words like "my", "I", "for" etc, with their neighbor word.</p>
<p>I was thinking that I may check each word's length and if it's shorter than 4 for example, join them with the next word.</p>
<p>Let's say I have the string <code>'about my projects'</code>:
What I did was split it into a separate words like this</p>
<pre><code>const words = string.split(" ");
</code></pre>
<p>Once I had the words I looped through them like this</p>
<pre><code> for (let i = 0; i <= words.length; i++) {
if (words[1 + i].length <= 3) {
const joinedWords = words[1] + " " + words[1 + i];
formattedWords.push(joinedWords);
}
}
</code></pre>
<p>The reason I used [1 + i] is that I wanted the first word of the string to always be a separate word.</p>
<p>Unfortunately trying this does not work and the console throws an error: Uncaught TypeError: Cannot read properties of undefined (reading 'length')</p>
<p>Is there a way I could join words that are shorter than 4 characters with the next word like this?</p>
<pre><code>input ['about', 'my', 'projects'];
output ['about', 'my projects'];
</code></pre>
<pre><code>input ['something','for','something','for'];
output ['something'.'for something'.'for'];
</code></pre>
| [
{
"answer_id": 74330234,
"author": "Abhi",
"author_id": 7430727,
"author_profile": "https://Stackoverflow.com/users/7430727",
"pm_score": 1,
"selected": false,
"text": "df['get_Timestamp'] = df['ArrivalDate'].dt.month\n"
},
{
"answer_id": 74330268,
"author": "Bushmaster",
"author_id": 15415267,
"author_profile": "https://Stackoverflow.com/users/15415267",
"pm_score": 0,
"selected": false,
"text": "data['Timestamp']=pd.to_datetime(data['Timestamp'], errors='coerce',format='%Y-%d-%m %H:%M:%S')\ndata['get_Timestamp'] = data['Timestamp'].dt.strftime('%Y-%m-01')\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20025773/"
] |
74,330,092 | <p>I'm working with a file right now where every line of data is sorted like " Dog 15 28 0 58 79 01" and I'm trying to convert it to a dictionary where Dog is the key and the others are the values.</p>
<p>Because its not split by comma's I've figured out that I should probably .split it to convert it to a list then use a for each loop to set the values in the dictionary but i'm struggling with the execution. This is all in python by the way. How might I go about doing it?</p>
| [
{
"answer_id": 74330234,
"author": "Abhi",
"author_id": 7430727,
"author_profile": "https://Stackoverflow.com/users/7430727",
"pm_score": 1,
"selected": false,
"text": "df['get_Timestamp'] = df['ArrivalDate'].dt.month\n"
},
{
"answer_id": 74330268,
"author": "Bushmaster",
"author_id": 15415267,
"author_profile": "https://Stackoverflow.com/users/15415267",
"pm_score": 0,
"selected": false,
"text": "data['Timestamp']=pd.to_datetime(data['Timestamp'], errors='coerce',format='%Y-%d-%m %H:%M:%S')\ndata['get_Timestamp'] = data['Timestamp'].dt.strftime('%Y-%m-01')\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20257226/"
] |
74,330,126 | <p>Can You Guys Help me</p>
<p>like input 1 or 2 checked color RED
if both checked input checked turn green</p>
<p>its for XNOR gate logic gates in java</p>
<p>i dont know how to do this is for my college but they dont teach me how to do that i cant find a good docs for that</p>
<p>i tried so much things but when i try its keep give red when i check both</p>
<pre><code>class XNOR extends JPanel {
JFrame frame = new JFrame("XNOR Gate");
JCheckBox input1 = new JCheckBox("Input 1");
JCheckBox input2 = new JCheckBox("Input 2");
JPanel outputPanel = new Box(Color.PINK);
public XNOR() {
input1.addActionListener(actionEvent -> {
updateOutputState1();
});
input2.addActionListener(actionEvent -> {
updateOutputState1();
});
input1.addActionListener(actionEvent -> {
updateOutputState();
});
input2.addActionListener(actionEvent -> {
updateOutputState();
});
createFrame();
}
private void createFrame() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
JPanel inputPanel = new JPanel();
inputPanel.add(input1);
inputPanel.add(input2);
frame.add(inputPanel);
frame.add(outputPanel);
frame.setSize(300, 300);
frame.setVisible(true);
}
private void updateOutputState() {
if(input1.isSelected() && input2.isSelected()){
frame.remove(outputPanel);
this.outputPanel = new Box(Color.GREEN);
frame.add(outputPanel);
}
else {
frame.remove(outputPanel);
this.outputPanel = new Box(Color.RED);
frame.add(outputPanel);
}
frame.revalidate();
frame.repaint();
}
private void updateOutputState1() {
if(input1.isSelected() || input2.isSelected()){
frame.remove(outputPanel);
this.outputPanel = new Box(Color.RED);
frame.add(outputPanel);
}
else {
frame.remove(outputPanel);
this.outputPanel = new Box(Color.GREEN);
frame.add(outputPanel);
}
frame.revalidate();
frame.repaint();
}
}
class Box extends JPanel {
Color color;
public Box(Color color) {
this.color = color;
}
public Dimension getPreferredSize() {
return new Dimension(200,200);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2=(Graphics2D) g;
g2.setPaint(color);
Rectangle2D rect=new Rectangle2D.Double(20,20,200,200);
g2.draw(rect);
g2.fill(rect);
}
}
class RunXNOR {
public static void main(String[] args) {
new XNOR();
}
}
</code></pre>
| [
{
"answer_id": 74330275,
"author": "sanurah",
"author_id": 4079056,
"author_profile": "https://Stackoverflow.com/users/4079056",
"pm_score": 2,
"selected": true,
"text": "import java.awt.Color;\nimport java.awt.Dimension;\nimport java.awt.FlowLayout;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.geom.Rectangle2D;\nimport javax.swing.JCheckBox;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\n\nclass AndGate extends JPanel {\n\n JFrame frame = new JFrame(\"And Gate\");\n JCheckBox input1 = new JCheckBox(\"Input 1\");\n JCheckBox input2 = new JCheckBox(\"Input 2\");\n Box outputPanel = new Box();\n\n public AndGate() {\n\n input1.addActionListener(actionEvent -> {\n updateOutputState();\n });\n\n\n input2.addActionListener(actionEvent -> {\n updateOutputState();\n });\n\n createFrame();\n }\n\n private void createFrame() {\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setLayout(new FlowLayout());\n\n JPanel inputPanel = new JPanel();\n inputPanel.add(input1);\n inputPanel.add(input2);\n frame.add(inputPanel);\n\n outputPanel.repaint();\n frame.add(outputPanel);\n\n\n frame.setSize(300, 300);\n frame.setVisible(true);\n }\n\n private void updateOutputState() {\n if(input1.isSelected() && input2.isSelected()) {\n this.outputPanel.changeColor(Color.GREEN);\n } else {\n this.outputPanel.changeColor(Color.RED);\n }\n }\n}\n\nclass Box extends JPanel {\n\n Graphics2D g2;\n Color color = Color.RED;\n Rectangle2D rect=new Rectangle2D.Double(20,20,200,200);\n\n public Box() {\n }\n\n public Dimension getPreferredSize() {\n return new Dimension(200,200);\n }\n\n public void changeColor(Color color) {\n this.color = color;\n g2.setPaint(color);\n g2.fill(rect);\n this.repaint();\n }\n\n public void paintComponent(Graphics g){\n super.paintComponent(g);\n g2 = (Graphics2D) g;\n g2.setPaint(color);\n g2.draw(rect);\n g2.fill(rect);\n }\n}\n\nclass RunAndGate {\n public static void main(String[] args) {\n new AndGate();\n }\n}\n"
},
{
"answer_id": 74330501,
"author": "WJS",
"author_id": 1552534,
"author_profile": "https://Stackoverflow.com/users/1552534",
"pm_score": 0,
"selected": false,
"text": "JFrame"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19323597/"
] |
74,330,148 | <p>I'm retrieving data from an API, right now there are only two endpoints, one for adding users and other one for get the users added. The users are added using a button and its textbox.</p>
<pre><code> let [showAlert, setAlertState] = useState(false);
let [twitterAccount, setTwitterAcount] = useState("Twitter Account here");
let [dataInfo, setDataInfo] = useState([]);
const getCurrentSpiedUsers = async () => {
fetch("https://localhost:7021/GetCurrentSpiedUsers")
.then((res) => res.json())
.then((res) => {setDataInfo(res)});
}
useEffect(function () {
getCurrentSpiedUsers();
}, []);
</code></pre>
<p>This part works as expected, the first time I enter into the website it loads data from the API.</p>
<p>This one is the other method for adding users.</p>
<pre class="lang-js prettyprint-override"><code> const addTwitterAccount = (account) => {
fetch(`https://localhost:7021/AddTwitterAccount?account=${account}`, {
method:'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
}
)
.then((res) => res.json())
.then((res) => { });
}
</code></pre>
<p>and this is the function inside of the <code>onClick</code> event button.</p>
<pre class="lang-js prettyprint-override"><code> const activeAlert = () => {
addTwitterAccount(twitterAccount);
getCurrentSpiedUsers();
setAlertState(true);
setTimeout(() => {
setAlertState(false);
}, 5000);
};
</code></pre>
<p>but this is not working as expected, once I click the button I add the account correctly, but can't reload the component using the <code>getCurrentSpiedUsers();</code> function. I noticed that when I click twice, I can get the last one but not the actual one, so I assume it's because the code it's executed faster than my function is retrieving the data from the API.</p>
<p>I tried using <code>async</code>/<code>await</code> for both methods, but the result is always the same. What can I do?</p>
<p>Updated with the server-side:</p>
<p><code>AddTwitterAcccount</code> endpoint:</p>
<pre><code>[ApiController]
[Route("[controller]")]
public class AddTwitterAccount : ControllerBase
{
private readonly ISpiedAccounts _spiedAccounts;
public AddTwitterAccount(ISpiedAccounts spiedAccounts)
{
_spiedAccounts = spiedAccounts;
}
[HttpPost(Name = "AddTwitterAccount")]
public void AddAccount([FromQuery] string account)
{
_spiedAccounts.AddTwitterAccount(account);
}
}
</code></pre>
<p><code>SpiedAccounts</code> class:</p>
<pre><code>public interface ISpiedAccounts
{
public void AddTwitterAccount(string accountName);
public List<TwitterAccount> GetTwitterAccounts();
}
public class SpiedAccounts : ISpiedAccounts
{
private List<TwitterAccount> accounts = new();
private ResponseMessage _responseMessage;
public void AddTwitterAccount(string accountName)
{
if (accounts.Any(account => account.ScreenName == accountName))
{
_responseMessage = ResponseMessage.UserExists;
return;
}
int maxUsersSpied = 5;
if (accounts.Count <= maxUsersSpied)
{
accounts.Add(new TwitterAccount
{
ScreenName = accountName
});
_responseMessage = ResponseMessage.Added;
return;
}
_responseMessage = ResponseMessage.LimitUsersExceeded;
}
public string GetResponseMessage()
{
return _responseMessage switch
{
ResponseMessage.Added
=> "The account was added correctly.",
ResponseMessage.LimitUsersExceeded
=> "Only can be spied 6 accounts at the time. Please, wait for one of them to be free.",
ResponseMessage.UserExists
=> "This account is currently being spied.",
_
=> string.Empty
};
}
public List<TwitterAccount> GetTwitterAccounts()
=> accounts;
}
public enum ResponseMessage
{
Added,
LimitUsersExceeded,
UserExists
}
</code></pre>
| [
{
"answer_id": 74330203,
"author": "acdcjunior",
"author_id": 1850609,
"author_profile": "https://Stackoverflow.com/users/1850609",
"pm_score": 3,
"selected": true,
"text": "addTwitterAccount"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9514144/"
] |
74,330,153 | <p>So, I have a project on R and I have to create a variable 'month' and 'day', so I decided to use 'lubridate' package. But the displayed days and months are in French, but I want to have it in English.</p>
<p>I hope that somebody can answer me.
Thank you in advance.</p>
<p>I have just used these two lines of code, they are good, except the language...</p>
<p><code>crime19clean$Day <- wday(crime19clean$Newdate, label = TRUE, abbr = TRUE) crime19clean$Month <- month(crime19clean$Newdate, label = TRUE, abbr = TRUE)</code></p>
| [
{
"answer_id": 74330203,
"author": "acdcjunior",
"author_id": 1850609,
"author_profile": "https://Stackoverflow.com/users/1850609",
"pm_score": 3,
"selected": true,
"text": "addTwitterAccount"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20427454/"
] |
74,330,172 | <p>I have always been used to blocking programming and working in the Spring MVC framework. Recently, I considered learning reactive programming. I was full of doubts about how to convert the previous logic into a new style.</p>
<p>See the following processing(Pseudocode):</p>
<pre class="lang-java prettyprint-override"><code>public Mono<List<String>> a() {
// 1...
List<String> strings = new ArrayList<>();
for (int i = 0; i < 100; i++) {
strings.add("hello " + i);
}
Mono<List<String>> mono = Mono.just(strings);
// 2...
mono.subscribe(e -> {
b();
});
// 3...
mono.subscribe(e -> {
c();
});
mono.subscribeOn(Schedulers.boundedElastic());
return mono;
}
// Simulate a time-consuming process.
public void b() {
try {
Thread.sleep(100);
} catch (InterruptedException err) {
throw new RuntimeException(err);
}
}
// Simulate the process of requesting an external HTTP interface once.
public int c() {
try {
Thread.sleep(300);
} catch (InterruptedException err) {
throw new RuntimeException(err);
}
return 1;
}
</code></pre>
<p>I tried to convert it into code that conforms to the responsive programming style, but found that the time-consuming code logic has blocked the current thread, which is inconsistent with my expectation.</p>
<p><a href="https://i.stack.imgur.com/0lYXZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0lYXZ.png" alt="enter image description here" /></a></p>
<p>I tested Webflux and Tomcat respectively, and the results show that the performance of the former is very poor. I suspect that the IO thread is blocked, which can be seen from the thread sleep time.</p>
| [
{
"answer_id": 74330283,
"author": "Karol Dowbecki",
"author_id": 1602555,
"author_profile": "https://Stackoverflow.com/users/1602555",
"pm_score": 2,
"selected": false,
"text": "Thread.sleep()"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6607559/"
] |
74,330,177 | <pre><code> public void getDeviceinfo()
{
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "C:\\Users\\username\\Desktop\\repo\\project\\executable\\ideviceinfo.exe",
Arguments = "-s",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
string line = proc.StandardOutput.ReadLine();
Console.WriteLine(line);
}
}
</code></pre>
<p>I want to run a .exe file and get some output from it using C# project.
When I'm having the .exe file within the project, it's executing but not giving any output. But If I keep the .exe outside of the project and if i give that location , then the executable file is executing and output is returned.</p>
<p>I tried keeping the executable in the debug folder also. But same issue.</p>
<p><strong>I want to keep the executable file within the C# project and i want to execute it.</strong></p>
<p>Any help please? Thanks.</p>
| [
{
"answer_id": 74330283,
"author": "Karol Dowbecki",
"author_id": 1602555,
"author_profile": "https://Stackoverflow.com/users/1602555",
"pm_score": 2,
"selected": false,
"text": "Thread.sleep()"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8997427/"
] |
74,330,190 | <p>Below I try to respond with a stream when I receive ticker updates.</p>
<p><strong>+page.server.js:</strong></p>
<pre><code>import YahooFinanceTicker from "yahoo-finance-ticker";
const ticker = new YahooFinanceTicker();
const tickerListener = await ticker.subscribe(["BTC-USD"])
const stream = new ReadableStream({
start(controller) {
tickerListener.on("ticker", (ticker) => {
console.log(ticker.price);
controller.enqueue(ticker.price);
});
}
});
export async function load() {
return response????
};
</code></pre>
<p>Note: The YahooFinanceTicker can't run in the browser.</p>
<p>How to handle / set the response in the Sveltekit load function.</p>
| [
{
"answer_id": 74331423,
"author": "H.B.",
"author_id": 546730,
"author_profile": "https://Stackoverflow.com/users/546730",
"pm_score": 1,
"selected": false,
"text": "load"
},
{
"answer_id": 74336207,
"author": "voscausa",
"author_id": 675006,
"author_profile": "https://Stackoverflow.com/users/675006",
"pm_score": 0,
"selected": false,
"text": "import YahooFinanceTicker from \"yahoo-finance-ticker\";\n\nconst ticker = new YahooFinanceTicker();\nconst tickerListener = await ticker.subscribe([\"BTC-USD\"])\n\n/** @type {import('./$types').RequestHandler} */\nexport function GET({ request }) {\n const ac = new AbortController();\n\n console.log(\"GET api: yahoo-finance-ticker\")\n const stream = new ReadableStream({\n start(controller) {\n tickerListener.on(\"ticker\", (ticker) => {\n console.log(ticker.price);\n controller.enqueue(String(ticker.price));\n }, { signal: ac.signal });\n },\n cancel() {\n console.log(\"cancel and abort\");\n ac.abort();\n },\n })\n\n return new Response(stream, {\n headers: {\n 'content-type': 'text/event-stream',\n }\n });\n}\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/675006/"
] |
74,330,211 | <p>I'm learning how classes works and I got stuck on a thing which I can't explain, I also didn't find a solution on the Internet so here am I with my first question on StackOverflow.</p>
<pre><code>class Swords:
damage = 5
</code></pre>
<p>Here is a class with only one line, with attribute damage.
Let's make an instance of the class:</p>
<pre><code>sharp_sword = Swords()
</code></pre>
<p>And here is the moment of truth.
My class doesn't have an init function, so right now my <code>sharp_sword.__dict__</code> is empty - my object of the class has an empty namespace, it doesn't have any attributes or methods. Well, we can create an attribute since we already defined it in the class itself:</p>
<pre><code>sharp_sword.damage = 10
</code></pre>
<p>Now if we <code>print(sharp_sword.damage)</code> the return will be 10, if we <code>print(Swords.damage)</code>, the return will be 5. <strong>That means that our instance of the class has its own attribute - and it is without any <strong>init</strong> inside my class</strong>.
I can create another object, set its damage to 15, and I will have two objects with different damage. Since we didn't change damage in class, if we print(Swords.damage), the return will be 5.</p>
<p>The question coming by itself - why then should I use <code>__init__</code> inside my class to set properties for objects if I can do it without it with even fewer lines of code in my class?</p>
<pre><code>class SwordsWithoutInit:
damage = 5
class SwordsWithInit:
def __init__(self):
self.damage = 5
big_sword = SwordsWithoutInit()
big_sword.damage = 10
sharp_sword = SwordsWithInit()
sharp_sword.damage = 20
print(f'big sword (class {type(big_sword)}) damage equals {big_sword.damage}')
print(f'sharp sword (class {type(sharp_sword)}) damage equals {sharp_sword.damage}')
# it both works the same way
# note that even if you create another object of class without init, it still will work the same as with init, there won't be any errors
another_sword = SwordsWithoutInit()
another_sword.damage = 33
print(f'big sword (class {type(big_sword)}) damage equals {big_sword.damage}')
print(f'another sword (class {type(another_sword)}) damage equals {another_sword.damage}')
print(f'Class without init still will have damage attribute equals to {SwordsWithoutInit.damage} in itself - we didnt change it')
'''
output:
big sword (class <class '__main__.SwordsWithoutInit'>) damage equals 10
#sharp sword (class <class '__main__.SwordsWithInit'>) damage equals 20
big sword (class <class '__main__.SwordsWithoutInit'>) damage equals 10
another sword (class <class '__main__.SwordsWithoutInit'>) damage equals 33
Class without init still will have damage attribute equals to 5 in itself - we didnt change it
'''
</code></pre>
| [
{
"answer_id": 74330267,
"author": "Ultimate48",
"author_id": 19702144,
"author_profile": "https://Stackoverflow.com/users/19702144",
"pm_score": 0,
"selected": false,
"text": "sword = Sword(5)\n"
},
{
"answer_id": 74330367,
"author": "Ryan Haining",
"author_id": 1013719,
"author_profile": "https://Stackoverflow.com/users/1013719",
"pm_score": 3,
"selected": true,
"text": "class Sword:\n pass\n\nclass Spear:\n pass\n\n# All players get a sword by default\nclass Items:\n weapons = [Sword()]\n \nplayer1_items = Items()\nplayer2_items = Items()\n\n# give player2 a spear\nplayer2_items.weapons.append(Spear())\n\n# player1 should still just have a sword right?\n# whoops! they have a spear too!\nprint(player1_items.weapons)\n"
},
{
"answer_id": 74330810,
"author": "pythonista",
"author_id": 20269454,
"author_profile": "https://Stackoverflow.com/users/20269454",
"pm_score": 0,
"selected": false,
"text": "__init__"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20427423/"
] |
74,330,214 | <p>I am trying to detect whenever the following script (<code>random_fail.sh</code>) fails --which happens rarely-- by running it inside a while loop in the second script (<code>catch_error.sh</code>):</p>
<pre class="lang-bash prettyprint-override"><code>#!/usr/bin/env bash
# random_fail.sh
n=$(( RANDOM % 100 ))
if [[ n -eq 42 ]]; then
echo "Something went wrong"
>&2 echo "The error was using magic numbers"
exit 1
fi
echo "Everything went according to plan"
</code></pre>
<pre class="lang-bash prettyprint-override"><code>#!/usr/bin/env bash
# catch_error.sh
count=0 # The number of times before failing
error=0 # assuming everything initially ran fine
while [ "$error" != 1 ]; do
# running till non-zero exit
# writing the error code from the radom_fail script into /tmp/error
bash ./random_fail.sh 1>/tmp/msg 2>/tmp/error
# reading from the file, assuming 0 written inside most of the times
error="$(cat /tmp/error)"
echo "$error"
# updating the count
count=$((count + 1))
done
echo "random_fail.sh failed!: $(cat /tmp/msg)"
echo "Error code: $(cat /tmp/error)"
echo "Ran ${count} times, before failing"
</code></pre>
<p>I was expecting that the catch_error.sh will read from /tmp/error and come out of the loop once a particular run of random_fail.sh exits with 1.</p>
<p>Instead, the catch script seems to be running forever. I think this is because the error code is not being redirected to the /tmp/error file at all.</p>
<p>Please help.</p>
| [
{
"answer_id": 74332763,
"author": "Eric Marceau",
"author_id": 9716110,
"author_profile": "https://Stackoverflow.com/users/9716110",
"pm_score": 1,
"selected": false,
"text": "#!/usr/bin/env bash\n# catch_error.sh\n\ncount=0 # The number of times before failing\nerror=0 # assuming everything initially ran fine\n\nwhile [ \"$error\" != 1 ]; do\n # running till non-zero exit\n\n # writing the error code from the radom_fail script into /tmp/error\n ./random_fail.sh 1>/tmp/msg 2>/tmp/error\n error=$?\n\n echo \"$error\"\n\n # updating the count\n count=$((count + 1))\n\ndone\n\necho \"random_fail.sh failed!: $(cat /tmp/msg)\"\necho \"Error code: ${error}\"\necho \"Ran ${count} times, before failing\"\n"
},
{
"answer_id": 74346279,
"author": "user1934428",
"author_id": 1934428,
"author_profile": "https://Stackoverflow.com/users/1934428",
"pm_score": 0,
"selected": false,
"text": "[ \"$error\" != 1 ]"
},
{
"answer_id": 74346523,
"author": "William Pursell",
"author_id": 140750,
"author_profile": "https://Stackoverflow.com/users/140750",
"pm_score": 0,
"selected": false,
"text": "/tmp/error"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16249489/"
] |
74,330,244 | <p>I want to make a widget window, but the Bottom and Text part aren't working properly and it keps getting sintax errors at the same part:</p>
<pre><code>import PySimpleGUI as sg
layout = [
[sg.Text("Hello from PySimpleGUI")],
[sg.Button("Close")]
window = sg.Window("Demo, layout")
]
while true:
event, values = window.read()
if event == "Close" or event == sg.WIN_CLOSED:
break
window.close()
</code></pre>
<p>it says I forgot a comma, but the references I checked for this code didn't use one, and I tried changing the elements or just putting the comma, but it didn't work either.</p>
<pre><code>ERROR message:
line 5
[sg.Buttom("OK")]
^^^^^^^^^^^^^^^^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?
</code></pre>
| [
{
"answer_id": 74332763,
"author": "Eric Marceau",
"author_id": 9716110,
"author_profile": "https://Stackoverflow.com/users/9716110",
"pm_score": 1,
"selected": false,
"text": "#!/usr/bin/env bash\n# catch_error.sh\n\ncount=0 # The number of times before failing\nerror=0 # assuming everything initially ran fine\n\nwhile [ \"$error\" != 1 ]; do\n # running till non-zero exit\n\n # writing the error code from the radom_fail script into /tmp/error\n ./random_fail.sh 1>/tmp/msg 2>/tmp/error\n error=$?\n\n echo \"$error\"\n\n # updating the count\n count=$((count + 1))\n\ndone\n\necho \"random_fail.sh failed!: $(cat /tmp/msg)\"\necho \"Error code: ${error}\"\necho \"Ran ${count} times, before failing\"\n"
},
{
"answer_id": 74346279,
"author": "user1934428",
"author_id": 1934428,
"author_profile": "https://Stackoverflow.com/users/1934428",
"pm_score": 0,
"selected": false,
"text": "[ \"$error\" != 1 ]"
},
{
"answer_id": 74346523,
"author": "William Pursell",
"author_id": 140750,
"author_profile": "https://Stackoverflow.com/users/140750",
"pm_score": 0,
"selected": false,
"text": "/tmp/error"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20293469/"
] |
74,330,248 | <p>I am making a program that generates the phrase,
"The enemy of my friend is my enemy!"
actually, I want this phrase to print out a random permutation of (Friend/Enemy)
in each place every time it is re-ran.</p>
<p>so far I got the code to print out the same word 3 times in each,
but not a different word in each place.</p>
<p>I couldn't get python to access each string individually from a list.
Any ideas?</p>
<p>Thanks!</p>
<p>`</p>
<pre><code>import random
en = 'Enemy'
fr = 'Friend'
words = en, fr
for word in words:
sentence = f"The {word} of my {word} is my {word}!"
print(sentence)
</code></pre>
<p>`</p>
| [
{
"answer_id": 74330286,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 2,
"selected": false,
"text": "random.choices"
},
{
"answer_id": 74331539,
"author": "Sam Mason",
"author_id": 1358308,
"author_profile": "https://Stackoverflow.com/users/1358308",
"pm_score": 1,
"selected": false,
"text": "import random\n\nwords = ['Enemy', 'Friend']\n\n# three independent draws from your words\nw1 = random.choice(words)\nw2 = random.choice(words)\nw3 = random.choice(words)\n\n# assemble together using an f-string\nsentence = f\"The {w1} of my {w2} is my {w3}!\"\nprint(sentence)\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2780254/"
] |
74,330,255 | <p>I am given prime factorization of a number as a map: <code>std::map<int, int> m</code>, where key is a prime number, and value is how many times this prime number occured in product.</p>
<p>Example: Prime factorization of 100 is 2 * 2 * 5 *5, so <code>m[2] = 2</code>, and <code>m[5] = 2</code></p>
<p>My question is how can I get number of all divisors of a number given it's prime factorization (in the form as above)?</p>
| [
{
"answer_id": 74330341,
"author": "Arty",
"author_id": 941531,
"author_profile": "https://Stackoverflow.com/users/941531",
"pm_score": 4,
"selected": true,
"text": "0, 1, 2, ..., PrimeCnt"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19809278/"
] |
74,330,301 | <p>Code :</p>
<pre class="lang-py prettyprint-override"><code>from sys import exit
didlogcorrect = 1
Minecraft = 'Minecraft'
Roblox = 'Roblox'
Exit = 'Exit'
chrome = 'chrome'
print('Welcome To PotatOS')
user_input = input("What would you like to do on PotatOS: ")
if user_input == Roblox:
print('Unable to connect to wifi Now terminating process')
elif user_input == Exit:
exit()
elif user_input == chrome:
print('You open Chrome Thinking What should i do now Maybe youtube idk, Then you close Chrome cause your bored!')
elif user_input == Minecraft:
print('Crashed, Reason 1, you close it cause your mad it crashed')
else:
print('PotatOS : BEEERGZ Unable to understand')
</code></pre>
<p>crash :</p>
<pre class="lang-py prettyprint-override"><code>Welcome To PotatOS
What would you like to do on PotatOS: Minecraft
Traceback (most recent call last):
File "/home/Username/Coding/PotatOS-1.0.1.txt", line 27, in <module>
if user_input == Roblox:
NameError: name 'Roblox' is not defined
</code></pre>
<p>Please help I would like someone with python knowledge to look at this I still cant find out why this wont work =(</p>
<p>I tried Multiple things but it still crashed, Sadly.</p>
<p>Thanks for being here and reading if you can help please let me know or help</p>
| [
{
"answer_id": 74330361,
"author": "Code-Apprentice",
"author_id": 1440565,
"author_profile": "https://Stackoverflow.com/users/1440565",
"pm_score": -1,
"selected": false,
"text": "user_input = input(\"What would you like to do on PotatOS\")\n"
},
{
"answer_id": 74330415,
"author": "Danna",
"author_id": 19595981,
"author_profile": "https://Stackoverflow.com/users/19595981",
"pm_score": 1,
"selected": false,
"text": ">>> What would you like to do on PotatOS\n>>> Here,Type,Your,Answer\n\n--\nresult:\nchrome -> 'Here'\nRoblox -> 'Types'\nExit -> 'Your'\nMinecraft -> 'Answer'\n"
},
{
"answer_id": 74330446,
"author": "Wolric",
"author_id": 20163209,
"author_profile": "https://Stackoverflow.com/users/20163209",
"pm_score": 3,
"selected": true,
"text": "input"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20427591/"
] |
74,330,344 | <p>Build of my project is failing - it is throwing the below mentioned error.</p>
<p><strong>React version - 17.0.2</strong></p>
<p><strong>react-scripts - 4.0.3</strong></p>
<p>app-frontend\App>yarn build
yarn run v1.22.17
$ react-app-rewired build
Creating an optimized production build...
Failed to compile.</p>
<p>./node_modules/tempa-xlsx/node_modules/pako/lib/zlib/trees.js 237:106
Module parse failed: Unexpected token (237:106)
File was processed with these loaders:</p>
<ul>
<li>./node_modules/react-scripts/node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| * not null.
| */</li>
</ul>
<blockquote>
<p>function gen_bitlen(s, desc) /* deflate_state <em>s;</em>/ /* tree_desc <em>desc; /</em> the tree descriptor <em>/</em>/{
| var tree = desc.dyn_tree;
| var max_code = desc.max_code;</p>
</blockquote>
<p>error Command failed with exit code 1.
info Visit <a href="https://yarnpkg.com/en/docs/cli/run" rel="nofollow noreferrer">https://yarnpkg.com/en/docs/cli/run</a> for documentation about this command.</p>
<p>I've tried by upgrading react-scripts from 3.44 to 4.0.3</p>
<p>I've removed the node_modules and re-ran the yarn install and yarn build again.</p>
| [
{
"answer_id": 74346108,
"author": "thatGuyDaki",
"author_id": 17043195,
"author_profile": "https://Stackoverflow.com/users/17043195",
"pm_score": 2,
"selected": false,
"text": "\"@babel/core\": \"7.19.6\",\n\"@babel/generator\": \"7.19.6\",\n\"@babel/compat-data\": \"7.19.4\",\n\"@babel/helper-compilation-targets\": \"7.19.3\",\n\"@babel/helper-create-class-features-plugin\": \"7.19.0\",\n\"@babel/helper-module-transforms\": \"7.19.6\",\n"
},
{
"answer_id": 74355425,
"author": "Ankit Singh",
"author_id": 14058058,
"author_profile": "https://Stackoverflow.com/users/14058058",
"pm_score": 1,
"selected": true,
"text": " resolutions : {\n\"@babel/core\": \"7.19.6\",\n\"@babel/generator\": \"7.19.6\",\n\"@babel/compat-data\": \"7.19.4\",\n\"@babel/helper-compilation-targets\": \"7.19.3\",\n\"@babel/helper-create-class-features-plugin\": \"7.19.0\",\n\"@babel/helper-module-transforms\": \"7.19.6\"\n}\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18772414/"
] |
74,330,368 | <p>I was trying for CRUD services using springboot with mongodb.</p>
<p>Getting error while running main application.</p>
<p><code>ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'productController': Unsatisfied dependency expressed through field 'productServiceImpl'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.cts.eaution.impl.ProductServiceImpl' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}</code></p>
<p>Controller class :</p>
<pre><code>@RestController
@RequestMapping("/e-auction/api/v1/seller/")
public class ProductController {
@Autowired
public ProductServiceImpl productServiceImpl;
/* @Autowired
public ProductRepository productRepository;
*/
@GetMapping("/show-bids")
public List<Product> getAllProducts() {
System.out.println("Hello Product...");
return productServiceImpl.findAll();
//return productRepository.findAll();
}
}
</code></pre>
<p>ServiceImpl class :</p>
<pre><code>class ProductServiceImpl implements ProductService {
@Autowired
private ProductRepository productRepository;
@Override
public List<Product> findAll() {
return productRepository.findAll();
}
}
</code></pre>
<p>Service interface :</p>
<pre><code>@Service
public interface ProductService {
List<Product> findAll();
}
</code></pre>
<p>Repository interface :</p>
<pre><code>public interface ProductRepository extends MongoRepository<Product, String> {
}
</code></pre>
<p>Pom xml :</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<!-- <version>2.7.5</version> -->
<version>2.6.13</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.cts</groupId>
<artifactId>eauction</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>eauction</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
</code></pre>
<p>I tried multiple option by adding annotation like (service, repository, component, componentscan) non of this solve the problem.</p>
<p>application properties :
#server
server.port=8082</p>
<pre><code>spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=productdb
</code></pre>
<p>Full Error logs :</p>
<p><code> Error creating bean with name 'productController': Unsatisfied dependency expressed through field 'productService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'productServiceImpl': Unsatisfied dependency expressed through field 'productRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productRepository' defined in com.cts.eauction.repository.ProductRepository defined in @EnableMongoRepositories declared on MongoRepositoriesRegistrar.EnableMongoRepositoriesConfiguration: Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mongoTemplate' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryDependentConfiguration.class]: Unsatisfied dependency expressed through method 'mongoTemplate' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDatabaseFactory' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoDatabaseFactorySupport]: Factory method 'mongoDatabaseFactory' threw exception; nested exception is java.lang.IllegalArgumentException: Database name must not contain slashes, dots, spaces, quotes, or dollar signs!</code></p>
| [
{
"answer_id": 74330670,
"author": "void void",
"author_id": 18969611,
"author_profile": "https://Stackoverflow.com/users/18969611",
"pm_score": 2,
"selected": true,
"text": "@Service"
},
{
"answer_id": 74336811,
"author": "Rakesh Chavan",
"author_id": 20312963,
"author_profile": "https://Stackoverflow.com/users/20312963",
"pm_score": 0,
"selected": false,
"text": "@ComponentScan(basePackages = {\"com.package.class\", \"com.package.anotherClass\"}) \n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8793412/"
] |
74,330,370 | <p>I have a table of an "Id" column and multiple integer columns that I want to convert to categorical variables. Therefore, I want to apply this transformation only to those multiple integer columns, but leave the ID column unchanged.</p>
<p>All the other methods involve dropping the ID column. How do I do this without dropping the ID column?</p>
<p>This is the current code i have:</p>
<pre><code>df= df.loc[:, df.columns != 'Id'].apply(lambda x: x.astype('category'))
</code></pre>
<p><strong>Sample dataframe</strong>:</p>
<pre><code>{'Id': {0: 0, 1: 1, 2: 2, 3: 3, 4: 4},
'Foundation': {0: 2, 1: 1, 2: 2, 3: 0, 4: 2},
'GarageFinish': {0: 1, 1: 1, 2: 1, 3: 2, 4: 1},
'LandSlope': {0: 0, 1: 0, 2: 0, 3: 0, 4: 0},
'LotConfig': {0: 4, 1: 2, 2: 4, 3: 0, 4: 2},
'GarageQual': {0: 4, 1: 4, 2: 4, 3: 4, 4: 4},
'GarageCond': {0: 4, 1: 4, 2: 4, 3: 4, 4: 4},
'LandContour': {0: 3, 1: 3, 2: 3, 3: 3, 4: 3},
'Utilities': {0: 0, 1: 0, 2: 0, 3: 0, 4: 0},
'GarageType': {0: 1, 1: 1, 2: 1, 3: 5, 4: 1},
'LotShape': {0: 3, 1: 3, 2: 0, 3: 0, 4: 0},
'Alley': {0: 2, 1: 2, 2: 2, 3: 2, 4: 2},
'Street': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1},
'PoolQC': {0: 3, 1: 3, 2: 3, 3: 3, 4: 3},
'Fence': {0: 4, 1: 4, 2: 4, 3: 4, 4: 4},
'MiscFeature': {0: 4, 1: 4, 2: 4, 3: 4, 4: 4},
'MSZoning': {0: 3, 1: 3, 2: 3, 3: 3, 4: 3},
'SaleType': {0: 8, 1: 8, 2: 8, 3: 8, 4: 8},
'PavedDrive': {0: 2, 1: 2, 2: 2, 3: 2, 4: 2},
'FireplaceQu': {0: 5, 1: 4, 2: 4, 3: 2, 4: 4},
'Condition1': {0: 2, 1: 1, 2: 2, 3: 2, 4: 2},
'Functional': {0: 6, 1: 6, 2: 6, 3: 6, 4: 6},
'BsmtQual': {0: 2, 1: 2, 2: 2, 3: 3, 4: 2},
'BsmtCond': {0: 3, 1: 3, 2: 3, 3: 1, 4: 3},
'BsmtExposure': {0: 3, 1: 1, 2: 2, 3: 3, 4: 0},
'BsmtFinType1': {0: 2, 1: 0, 2: 2, 3: 0, 4: 2},
'ExterQual': {0: 2, 1: 3, 2: 2, 3: 3, 4: 2},
'BsmtFinType2': {0: 5, 1: 5, 2: 5, 3: 5, 4: 5},
'MasVnrType': {0: 1, 1: 2, 2: 1, 3: 2, 4: 1},
'Exterior2nd': {0: 13, 1: 8, 2: 13, 3: 15, 4: 13},
'Heating': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1},
'Neighborhood': {0: 5, 1: 24, 2: 5, 3: 6, 4: 15},
'SaleCondition': {0: 4, 1: 4, 2: 4, 3: 0, 4: 4},
'Electrical': {0: 4, 1: 4, 2: 4, 3: 4, 4: 4},
'Exterior1st': {0: 12, 1: 8, 2: 12, 3: 13, 4: 12},
'RoofMatl': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1},
'RoofStyle': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1},
'HouseStyle': {0: 5, 1: 2, 2: 5, 3: 5, 4: 5},
'BldgType': {0: 0, 1: 0, 2: 0, 3: 0, 4: 0},
'Condition2': {0: 2, 1: 2, 2: 2, 3: 2, 4: 2},
'KitchenQual': {0: 2, 1: 3, 2: 2, 3: 2, 4: 2},
'ExterCond': {0: 4, 1: 4, 2: 4, 3: 4, 4: 4},
'CentralAir': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1},
'HeatingQC': {0: 0, 1: 0, 2: 0, 3: 2, 4: 0}}
</code></pre>
| [
{
"answer_id": 74330670,
"author": "void void",
"author_id": 18969611,
"author_profile": "https://Stackoverflow.com/users/18969611",
"pm_score": 2,
"selected": true,
"text": "@Service"
},
{
"answer_id": 74336811,
"author": "Rakesh Chavan",
"author_id": 20312963,
"author_profile": "https://Stackoverflow.com/users/20312963",
"pm_score": 0,
"selected": false,
"text": "@ComponentScan(basePackages = {\"com.package.class\", \"com.package.anotherClass\"}) \n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3713236/"
] |
74,330,374 | <p>How to make time from len of array...</p>
<p>Picture 1:
<a href="https://i.stack.imgur.com/4jFh9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4jFh9.png" alt="enter image description here" /></a></p>
<p>Picture 2:
<a href="https://i.stack.imgur.com/72kZV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/72kZV.png" alt="enter image description here" /></a></p>
<p>How to make the picture 1 as picture 2</p>
<p>Picture 1 come from below:</p>
<p>`</p>
<pre><code>x=[]
colors=['red','green','brown','teal','gray','black','maroon','orange','purple']
colors2=['green','red','orange','black','maroon','teal','blue','gray','brown']
for i in range(0,1950):
x.append(i)
for i in range(0,1):
plt.figure(figsize=(15,6))
# plt.figure()
plt.plot(x,out[0:1950,i],color=colors[i])
plt.plot(x,predictions[0:1950,i],markerfacecolor='none',color=colors2[i])
plt.title('LSTM Regression (Training Data)')
plt.ylabel('Force/Fz (N)')
plt.xlabel('Time/s')
plt.legend(['Real value', 'Predicted Value'], loc='upper right')
plt.savefig('Regression Result.png'[i])
plt.show()
</code></pre>
<p>`</p>
| [
{
"answer_id": 74330422,
"author": "ahrensaj",
"author_id": 20324675,
"author_profile": "https://Stackoverflow.com/users/20324675",
"pm_score": 1,
"selected": false,
"text": "plt.plot()"
},
{
"answer_id": 74330508,
"author": "Umang Gupta",
"author_id": 3236925,
"author_profile": "https://Stackoverflow.com/users/3236925",
"pm_score": 1,
"selected": true,
"text": "x=[]\ncolors=['red','green','brown','teal','gray','black','maroon','orange','purple']\ncolors2=['green','red','orange','black','maroon','teal','blue','gray','brown']\n# just update the x with correct scaling; use numpy array for faster computations\nx = numpy.arange(0,1950)*40/1950 \nfor i in range(0,1):\n plt.figure(figsize=(15,6))\n # plt.figure()\n plt.plot(x,out[0:1950,i],color=colors[i])\n plt.plot(x,predictions[0:1950,i],markerfacecolor='none',color=colors2[i])\n plt.title('LSTM Regression (Training Data)')\n plt.ylabel('Force/Fz (N)')\n plt.xlabel('Time/s')\n plt.legend(['Real value', 'Predicted Value'], loc='upper right')\n plt.savefig('Regression Result.png'[i])\n plt.show()\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17877163/"
] |
74,330,398 | <p>I need to find a node with input from a customer in the linked list but I have an error CS1503. How can I solve a problem?</p>
<p>In this code, I create the LinkList name "customerList" to collect string data such as name, contact number, and payment from the user. After that, I need to find the contact number which input from the user to show data in the node and delete it. In code show that input in "searchCustomerDetail" cannot convert 'string' to ....</p>
<pre><code>Error Message: Argument 1: cannot convert from 'string' to 'IFN564.Customer' [IFN564]csharp(CS1503)
</code></pre>
<pre class="lang-cs prettyprint-override"><code>public class Customer {
public string Name { get; set; }
public string Phone { get; set; }
public string Payment { get; set; }
public int[] Screening { get; set; }
public static LinkedList<Customer> customerList = new LinkedList<Customer>();
public static string input;
public static void addCustomerDetail() {
Console.WriteLine("Please enter your information detail");
Console.WriteLine("");
Console.Write("Full Name: ");
string inputName = Console.ReadLine();
Console.Write("Contact Number: ");
string inputPhone = Console.ReadLine();
Console.Write("Payment Method: ");
string inputPayment = Console.ReadLine();
Console.Clear();
Console.WriteLine("");
Console.WriteLine("Please check your information detail!!");
Console.WriteLine("");
Console.WriteLine($"Full Name: {inputName}");
Console.WriteLine($"Contact Number: {inputPhone}");
Console.WriteLine($"Payment Method: {inputPayment}");
Console.WriteLine("");
Console.WriteLine("Please 1 to confirm or 0 to cancel");
int input = Convert.ToInt32(Console.ReadLine());
switch (input) {
case 1:
insert(inputName, inputPhone, inputPayment);
break;
case 2:
Program.Main();
break;
}
}
public static void insert(string name, string phone, string payment) {
Console.WriteLine("");
Console.WriteLine("Please 1 to confirm buy ticket or 0 to cancel");
int input = Convert.ToInt32(Console.ReadLine());
Customer customerDetail = new Customer() {
Name = name,
Phone = phone,
Payment = payment,
};
switch (input) {
case 0: Program.Main(); break;
case 1:
customerList.AddLast(customerDetail);
Program.Main();
break;
}
}
public static void searchCunstomerDetail() {
Console.WriteLine("Please enter contact number!!");
Console.WriteLine("");
Console.Write("Contact number: ");
input = Console.ReadLine();
LinkedListNode<Customer> node = customerList.Find(input);
Console.WriteLine(node);
}
}
</code></pre>
<p>I try to use LinkListNode to find but It show error with input CS1503</p>
| [
{
"answer_id": 74330481,
"author": "pm100",
"author_id": 173397,
"author_profile": "https://Stackoverflow.com/users/173397",
"pm_score": 2,
"selected": true,
"text": " var node = customerList.Where(c=>c.Phone == input).First();\n"
},
{
"answer_id": 74330540,
"author": "John Paul R",
"author_id": 8105643,
"author_profile": "https://Stackoverflow.com/users/8105643",
"pm_score": -1,
"selected": false,
"text": "LinkedListNode<Customer> node = customerList.Find(input);\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18910525/"
] |
74,330,416 | <p>I'm dev an app that use a recycler view to show items composed by an image and a text. The user can add an item with a custom image, doing this in a normal activity it's easy:</p>
<pre><code>Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
launcher.launch(intent);
private final ActivityResultLauncher<Intent> launcher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == Activity.RESULT_OK
&& result.getData() != null) {
Uri photoUri = result.getData().getData();
image_to_up = photoUri;
image_uploaded = true;
element_image_add.setImageURI(photoUri);
}
}
);
</code></pre>
<p>But if I want let the user edit a recycler view item image, then the same code wont work inside the custom adapter, I get:</p>
<pre><code>Cannot resolve method 'registerForActivityResult' in Adapter
</code></pre>
<p>So, how can I do it? How can I let the user open the gallery and select an image inside a custom adapter class?</p>
| [
{
"answer_id": 74432240,
"author": "Kaushal Rola",
"author_id": 14252468,
"author_profile": "https://Stackoverflow.com/users/14252468",
"pm_score": 0,
"selected": false,
"text": "ActivityResultLauncher<Intent> launcher = ((YourActivityClass) activity).registerForActivityResult(\n new ActivityResultContracts.StartActivityForResult(),\n result -> {\n if (result.getResultCode() == Activity.RESULT_OK\n && result.getData() != null) {\n //your logic\n }\n });\n"
},
{
"answer_id": 74432686,
"author": "shybaka",
"author_id": 15573213,
"author_profile": "https://Stackoverflow.com/users/15573213",
"pm_score": 2,
"selected": true,
"text": "private final ActivityResultLauncher<Intent> launcher = registerForActivityResult(\n new ActivityResultContracts.StartActivityForResult(),\n result -> {\n if (result.getResultCode() == Activity.RESULT_OK\n && result.getData() != null) {\n Uri photoUri = result.getData().getData();\n image_to_up = photoUri;\n image_uploaded = true;\n element_image_add.setImageURI(photoUri);\n }\n }\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12615735/"
] |
74,330,433 | <p>Need to create new array object from two other arrays in JS</p>
<pre><code>var array1 = ['one', 'two', 'one, 'two'];
var array2 = ['3', '4', '5', '6'];
</code></pre>
<p>Here array1[0] = one represents array2[0] = 3 and vice versa.</p>
<p>Need to create a new array object with array1's value as its key and array2's value as its value</p>
<p>Output needed</p>
<pre><code>var arrayObj = {"one": [{"0":"3", "1":5} ],"two": [{"0":"4", "1":6}]}
</code></pre>
<p>Here 3 and 5 in array2 should push to index "one" and 4 and 6 in array2 should push to index "two" ?</p>
| [
{
"answer_id": 74330518,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 1,
"selected": true,
"text": "const\n combine = (a, b) => {\n const temp = {};\n for (let i = 0; i < array1.length; i++) (temp[a[i]] ??= []).push(b[i]);\n return temp;\n },\n array1 = ['one', 'two', 'one', 'two'],\n array2 = ['3', '4', '5', '6'],\n result = Object.fromEntries(Object\n .entries(combine(array1, array2))\n .map(([k, a]) => [k, Object.assign({}, a)])\n );\n\nconsole.log(result);"
},
{
"answer_id": 74330766,
"author": "Carsten Massmann",
"author_id": 2610061,
"author_profile": "https://Stackoverflow.com/users/2610061",
"pm_score": 1,
"selected": false,
"text": "function map2(a1,a2){\n return a1.reduce((a,c,i)=>{\n (a[c]??=[]).push(a2[i]);\n return a;\n },{})\n}\nconst\n array1 = ['one', 'two', 'one', 'two'],\n array2 = ['3', '4', '5', '6'];\n \nconsole.log(map2(array1,array2));"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14142973/"
] |
74,330,458 | <p>What is the best way to know the amount of white pixels that are anove the red areas using python and OpenCV?</p>
<p><a href="https://i.stack.imgur.com/R5qoS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/R5qoS.png" alt="enter image description here" /></a></p>
<p>I imagine drawing a straight vertical line from each white pixel to height Y = 512 might be one of the ways, but I have no idea how to make that happen</p>
| [
{
"answer_id": 74330518,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 1,
"selected": true,
"text": "const\n combine = (a, b) => {\n const temp = {};\n for (let i = 0; i < array1.length; i++) (temp[a[i]] ??= []).push(b[i]);\n return temp;\n },\n array1 = ['one', 'two', 'one', 'two'],\n array2 = ['3', '4', '5', '6'],\n result = Object.fromEntries(Object\n .entries(combine(array1, array2))\n .map(([k, a]) => [k, Object.assign({}, a)])\n );\n\nconsole.log(result);"
},
{
"answer_id": 74330766,
"author": "Carsten Massmann",
"author_id": 2610061,
"author_profile": "https://Stackoverflow.com/users/2610061",
"pm_score": 1,
"selected": false,
"text": "function map2(a1,a2){\n return a1.reduce((a,c,i)=>{\n (a[c]??=[]).push(a2[i]);\n return a;\n },{})\n}\nconst\n array1 = ['one', 'two', 'one', 'two'],\n array2 = ['3', '4', '5', '6'];\n \nconsole.log(map2(array1,array2));"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20372455/"
] |
74,330,467 | <p>Full component:</p>
<pre><code>const Column = ({ form, setForm, fieldset, blocks, selectedFieldsetId, setFieldBeingEdited }) => {
//Sends block being edited to App component
const editField = (e) => {
const blockId = e.currentTarget.getAttribute('data-blockid')
const data = form.blocks[blockId]
setFieldBeingEdited({ active: true, data })
}
const deleteBlock = (e) => {
const blockId = e.currentTarget.getAttribute('data-blockid')
const updatedForm = { ...form }
delete updatedForm.blocks[blockId]
for (const fieldset in updatedForm.fieldsets) {
for (let i = 0; i < updatedForm.fieldsets[fieldset].blockIds.length; i++) {
if (updatedForm.fieldsets[fieldset].blockIds[i] === blockId) {
updatedForm.fieldsets[fieldset].blockIds.splice(i, 1)
return
}
}
}
setForm(updatedForm)
}
return <BlockList fieldset={fieldset} blocks={blocks} selectedFieldsetId={selectedFieldsetId} editField={editField} deleteBlock={deleteBlock} />
}
</code></pre>
<p>I have an object stored in state, but one of my setState calls is not triggering a re render immediately; I have to force some other state change through some other interaction on the page, and only then will the latest state be reflected.</p>
<p>As you can see I'm making a copy of the state object before I make changes to it, and calling setState (setForm) with the new object which has the changes made to it. Is anyone able to tell me where I'm going wrong? Thank you.</p>
<p>In case it's relevant at all, here is the data structure:</p>
<pre><code>const initialData = {
blocks: {},
fieldsets: {
[initialFieldsetId]: {
id: initialFieldsetId,
blockIds: [],
},
},
fieldsetOrder: [initialFieldsetId],
}
</code></pre>
| [
{
"answer_id": 74330518,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 1,
"selected": true,
"text": "const\n combine = (a, b) => {\n const temp = {};\n for (let i = 0; i < array1.length; i++) (temp[a[i]] ??= []).push(b[i]);\n return temp;\n },\n array1 = ['one', 'two', 'one', 'two'],\n array2 = ['3', '4', '5', '6'],\n result = Object.fromEntries(Object\n .entries(combine(array1, array2))\n .map(([k, a]) => [k, Object.assign({}, a)])\n );\n\nconsole.log(result);"
},
{
"answer_id": 74330766,
"author": "Carsten Massmann",
"author_id": 2610061,
"author_profile": "https://Stackoverflow.com/users/2610061",
"pm_score": 1,
"selected": false,
"text": "function map2(a1,a2){\n return a1.reduce((a,c,i)=>{\n (a[c]??=[]).push(a2[i]);\n return a;\n },{})\n}\nconst\n array1 = ['one', 'two', 'one', 'two'],\n array2 = ['3', '4', '5', '6'];\n \nconsole.log(map2(array1,array2));"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16611081/"
] |
74,330,471 | <p>I'm currently working on a problem which requires me to return true if n is divisible by 11 without using the division or modulous operator.</p>
<p>It's mentioned that if we add and subtract the digits alternatively and it adds up to be 0, -11 or 11 it means that it is divisible by 11:</p>
<p>Example1: 121
1 - 2 + 1 = 0</p>
<p>Example 2: 509
3 - 5 + 0 - 9 = -11</p>
<p>Both of these are divisible by 11.</p>
<p>Currently I have this for my code.</p>
<pre><code>def div_11(n):
alternative = (sum(n[0::2]))
second_alternative = (sum(n[1::2]))
if (alternative1 - alternative2) % 11 == 0:
return True
else:
return False
</code></pre>
<p>I was hoping that for alternative, I would have the second, fourth, sixth, etc value in a list, and for second_alternative, I would have the first, third, fifth, etc value. With that, I would do alternative subtracted by the second_alternative divided by 11, and if it returned 0 I would deem that as true.</p>
<p>My error comes from saying the int object is not subscriptable. Does anyone have any solutions?</p>
<p>This is the test code we are given:</p>
<pre><code> nlst = [587657752,11,22,2728,31415,1358016]
for n in nlst:
print(div_11(n), n / 11)
</code></pre>
<p>I have tried subtracting the alternative and the second_alternative to return 0 which I believe would make it divisible by 11, however I received a Type:Error which said int subscript is not subscriptable.</p>
| [
{
"answer_id": 74330535,
"author": "Danna",
"author_id": 19595981,
"author_profile": "https://Stackoverflow.com/users/19595981",
"pm_score": 2,
"selected": false,
"text": "listNum = list(map(int, str(num)))\n"
},
{
"answer_id": 74330582,
"author": "ahmadjanan",
"author_id": 15052608,
"author_profile": "https://Stackoverflow.com/users/15052608",
"pm_score": 0,
"selected": false,
"text": "def div_11(n):\n n = str(n)\n alternative = sum(int(digit) for digit in n[::2]) \n second_alternative = sum(int(digit) for digit in n[1::2])\n\n if (alternative - second_alternative) in [-11, 0, 11]:\n return True\n else:\n return False\n"
},
{
"answer_id": 74330585,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "def div_11(n):\n while n > 9:\n s = str(n)\n x = sum([int(s[i]) for i in range(0,len(s),2)]) # sum of digits in even places\n y = sum([int(s[i]) for i in range(1,len(s),2)]) # sum of digits in odd places\n n = abs(x - y) # just in case the intermediate result is negative\n return n == 0\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20427274/"
] |
74,330,472 | <p>My dropdown list items populated from the database table and working fine and want to save the selected dropdown list item into another sql database table but saving only value (id) instead text. Somebody helps me to solve these problems.</p>
<p>I have tried below codes but save only id instead save text</p>
<p>Model:</p>
<pre><code>public class BiodataSingle
{
public BiodataSingle()
{
this.MDA = new List<SelectListItem>();
this.ZoneDept = new List<SelectListItem>();
}
public List<SelectListItem> MDA { get; set; }
public List<SelectListItem> ZoneDept { get; set; }
public int MDAId { get; set;
public int ZoDepId { get; set; }
}
</code></pre>
<p>Controller:</p>
<pre><code>[HttpPost]
public JsonResult AjaxMethod(string type, int value)
{
BiodataSingle model = new BiodataSingle();
switch (type)
{
case "ddlmdaName":
model.ZoneDept = (from z in this._context.ZoneDept
where z.MDAId == value
select new SelectListItem
{
Value = z.ZoDepId.ToString(),
Text = z.ZoneDeptname
}).ToList();
break;
}
return Json(model);
}
[HttpPost]
public async Task<IActionResult> SaveBiodata(BiodataSingle biodataSingle)
{
if (ModelState.IsValid)
{
var newbiodata = new BiodataViewModel()
{
MDA = biodataSingle.MDAId,
Department = biodataSingle.ZoDepId,
};
await _context.BiodataA.AddAsync(newbiodata);
await _context.SaveChangesAsync();
}
return View(biodataSingle);
</code></pre>
<p>}</p>
<p>View:</p>
<pre><code><select id="ddlmdaName" name="MDAId" asp-for="MDAId" asp-items="Model.MDA" class="form-control">
<option value="">--Please select--</option>
</select>
<select id="ddlzoneDept" name="ZoDepId" asp-for="ZoDepId" asp-items="Model.ZoneDept" class="form-control">
<option value="">--Please select--</option>
</select>
</code></pre>
| [
{
"answer_id": 74342912,
"author": "Xinran Shen",
"author_id": 17438579,
"author_profile": "https://Stackoverflow.com/users/17438579",
"pm_score": 1,
"selected": false,
"text": "TempData[\"xx\"]"
},
{
"answer_id": 74343051,
"author": "Waleed.alhasan",
"author_id": 3066323,
"author_profile": "https://Stackoverflow.com/users/3066323",
"pm_score": 0,
"selected": false,
"text": "<select id=\"ddlzoneDept\" name=\"ZoDepId\" asp-for=\"ZoDepId\" asp-items=\"@(new SelectList(Model.ZoneDept , \"ZoDepId\", \"ZoneDeptname\"))\" class=\"form-control\">\n <option value=\"\">--Please select--</option>\n</select>\n"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16437954/"
] |
74,330,475 | <p>I've got 3 models: <code>Order</code>, <code>OrderItem</code> and <code>Product</code> (for simplicity just showing the relationships):</p>
<pre><code>class Order extends BaseModel
{
use Uuid;
protected $casts = [
'status' => OrderStatuses::class,
];
/**
* An Order has multiple OrderItems associated to it.
* @return HasMany
*/
public function orderItems(): HasMany
{
return $this->hasMany(OrderItem::class);
}
</code></pre>
<pre><code>class OrderItem extends BaseModel
{
/**
* Get the Order the OrderItem belongs to.
* @return BelongsTo
*/
public function order(): BelongsTo
{
return $this->belongsTo(Order::class)
->withDefault();
}
/**
* Get the product associated to this OrderItem.
* @return HasOne
*/
public function product(): HasOne
{
return $this->hasOne(Product::class, 'id');
}
}
</code></pre>
<pre><code>class Product extends BaseModel
{
use Uuid;
/**
* Get the category the product belongs to.
* @return BelongsTo
*/
public function category(): BelongsTo
{
return $this->belongsTo(Category::class, 'category_id');
}
</code></pre>
<p>with their respective DB tables:</p>
<pre><code>orders: id, status, subtotal, total
order_items: id, order_id, product_id, qty, price, total
products: id, name, slug, sku, description, price
</code></pre>
<p>I've got only a controller for <code>Order</code> and <code>Product</code> but I do have resources for all 3:</p>
<pre><code>class OrdersResource extends JsonResource
{
public function toArray($request): array
{
return [
'id' => (string)$this->id,
'type' => 'orders',
'attributes' => [
'status' => ($this->status)->value(),
'payment_type' => $this->payment_type,
'payment_transaction_no' => $this->payment_transaction_no,
'subtotal' => $this->subtotal,
'taxes' => $this->taxes,
'total' => $this->total,
'items' => OrderItemsResource::collection($this->whenLoaded('orderItems')),
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
]
];
}
}
</code></pre>
<pre><code>class ProductsResource extends JsonResource
{
public function toArray($request) : array
{
return [
'id' => $this->id,
'type' => 'products',
'attributes' => [
'barcode' => $this->barcode,
'name' => $this->name,
'slug' => $this->slug,
'sku' => $this->sku,
'description' => $this->description,
'type' => $this->type,
// todo return category object?
'category' => new CategoriesResource($this->whenLoaded('category')),
'wholesale_price' => $this->wholesale_price,
'retail_price' => $this->retail_price,
'base_picture' => ($this->base_picture ? asset('images/products/' . $this->base_picture) : null),
'current_stock_level' => $this->current_stock_level,
'active' => $this->active,
]
];
}
}
</code></pre>
<pre><code>class OrderItemsResource extends JsonResource
{
public function toArray($request): array
{
return [
'id' => $this->id,
'order_id' => $this->order_id,
'product_id' => $this->product_id,
'qty' => $this->qty,
'price' => $this->price,
'total' => $this->total,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}
</code></pre>
<p>When hitting my orders controller I return the data (in this case for displaying an order) like this:</p>
<pre><code>public function show(Order $order): JsonResponse
{
return (new OrdersResource($order->loadMissing('orderItems')))
->response()
->setStatusCode(Response::HTTP_OK);
}
</code></pre>
<p>So far so go, the order is returned like this:</p>
<pre><code>{
"data": {
"id": "20d9b0f3-2b32-45a7-8814-12c77210ad50",
"type": "orders",
"attributes": {
"status": "new",
"payment_type": "",
"payment_transaction_no": "",
"subtotal": 71000,
"taxes": 0,
"total": 71000,
"items": [
{
"id": 9,
"product_id": "444b0f3-2b12-45ab-3434-4453121231ad51",
"order_id": "20d9b0f3-2b32-45a7-8814-12c77210ad50",
"qty": 10,
"price": 200,
"total": 2000,
"created_at": "2022-11-05T16:26:07.000000Z",
"updated_at": "2022-11-05T16:28:02.000000Z"
},
{
"id": 10,
"product_id": "324b0f3-2b12-45ab-3434-12312330ad50",
"order_id": "20d9b0f3-2b32-45a7-8814-12c77210ad50",
"qty": 3,
"price": 23000,
"total": 69000,
"created_at": "2022-11-05T16:26:29.000000Z",
"updated_at": "2022-11-05T16:26:29.000000Z"
}
],
"created_at": "2022-11-05T16:26:07.000000Z",
"updated_at": "2022-11-05T16:28:02.000000Z"
}
}
}
</code></pre>
<p>but now I'm in need of returning the actual product as part of <code>OrderItem</code> instead of just the product ID, so I updated my resource to include:
<code>'product' => new ProductsResource($this->whenLoaded('product')),</code></p>
<p>my resource ended up looking like this:</p>
<pre><code>public function toArray($request): array
{
return [
'id' => $this->id,
'order_id' => $this->order_id,
'product' => new ProductsResource($this->whenLoaded('product')),
'qty' => $this->qty,
'price' => $this->price,
'total' => $this->total,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
</code></pre>
<p>yet the product is not visible in my response, what am I missing? Isn't that the right way to load it? do i need to load it from my controller?</p>
<p>Thanks</p>
<p><strong>UPDATE</strong></p>
<p>I've updated the relationship in <code>OrderItem</code>, now it looks like the following:</p>
<pre><code>public function product(): HasOne
{
return $this->hasOne(Product::class, 'id', 'product_id');
}
</code></pre>
<p>Where <code>id</code> points to the <code>id</code> column in <code>products</code> table, and <code>product_id</code> is the FK in <code>order_item</code>.</p>
<p>At this point if I do the following:</p>
<pre><code>// just get any orderItem
$orderItem = OrderItem::first();
dd($orderItem->product);
</code></pre>
<p>I do see that the relationship is working because the product is being printed, but the object is still not part of the API response, meaning that in my resource this line is not working as expected:</p>
<pre><code>'product' => new ProductsResource($this->whenLoaded('product')),
</code></pre>
<p><strong>UPDATE 2</strong></p>
<p>I updated the way I was trying to load <code>product</code> in the resource to be either of these two:</p>
<pre><code>'product' => $this->load('product'),
</code></pre>
<pre><code>'product' => $this->loadMissing('product'),
</code></pre>
<p>but that's giving me a nested object over the already nested one like this:</p>
<pre><code>{
"data": {
"id": "20d9b0f3-2b32-45a7-8814-12c77210ad50",
"type": "orders",
"attributes": {
"status": "new",
"payment_type": "",
"payment_transaction_no": "",
"subtotal": 71000,
"taxes": 0,
"total": 71000,
"items": [
{
"id": 9,
"order_id": "20d9b0f3-2b32-45a7-8814-12c77210ad50",
"product": {
"id": 9,
"order_id": "20d9b0f3-2b32-45a7-8814-12c77210ad50",
"product_id": "f6bd3290-7748-49fa-8995-e0de47291fc9",
"qty": 10,
"price": 200,
"total": 2000,
"created_at": "2022-11-05T16:26:07.000000Z",
"updated_at": "2022-11-05T16:28:02.000000Z",
"product": {
"id": "f6bd3290-7748-49fa-8995-e0de47291fc9",
"barcode": "010101010101010101",
"name": "Test 5",
"slug": "test-5",
"sku": "t55te345c",
"description": "asd asd asd asd asd",
"type": "goods",
"category_id": 4,
"wholesale_price": 34,
"retail_price": 200,
"base_picture": null,
"current_stock_level": 0,
"active": 1,
"created_at": "2022-09-23T16:29:18.000000Z",
"updated_at": "2022-09-23T22:00:40.000000Z"
}
},
"qty": 10,
"price": 200,
"total": 2000,
"created_at": "2022-11-05T16:26:07.000000Z",
"updated_at": "2022-11-05T16:28:02.000000Z"
}
]
}
}
}
</code></pre>
<p>Notice how <code>product</code> now has all over again the data from <code>items</code></p>
| [
{
"answer_id": 74330566,
"author": "Vlad",
"author_id": 20382571,
"author_profile": "https://Stackoverflow.com/users/20382571",
"pm_score": 1,
"selected": false,
"text": "$order->loadMissing('orderItems.product')\n"
},
{
"answer_id": 74332314,
"author": "Don't Panic",
"author_id": 6089612,
"author_profile": "https://Stackoverflow.com/users/6089612",
"pm_score": 1,
"selected": false,
"text": "Product"
},
{
"answer_id": 74354309,
"author": "MrCujo",
"author_id": 2882913,
"author_profile": "https://Stackoverflow.com/users/2882913",
"pm_score": 0,
"selected": false,
"text": "OrderItem"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2882913/"
] |
74,330,510 | <p>I am currently using the following code to combine Col A and Col B to get Col A & B in DataFrame B below:</p>
<pre><code>out = (df
.groupby('Col A', group_keys=False, sort=False)
.apply(lambda d: d.iloc[:, ::-1].unstack().drop_duplicates())
.reset_index(drop=True).to_frame(name='Col A&B')
)
</code></pre>
<p>My question is: how can I create the Col C in DataFrame B that uses the column headers from DataFrame A to label where each value in Col A & B came from?</p>
<p>DataFrame A</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Col A</th>
<th>Col B</th>
<th>Col C</th>
</tr>
</thead>
<tbody>
<tr>
<td>1000</td>
<td>100</td>
<td>10</td>
</tr>
<tr>
<td>1000</td>
<td>100</td>
<td>20</td>
</tr>
<tr>
<td>2000</td>
<td>200</td>
<td>30</td>
</tr>
<tr>
<td>2000</td>
<td>200</td>
<td>40</td>
</tr>
</tbody>
</table>
</div>
<p>DataFrame B</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Col A & B</th>
<th>Col C</th>
</tr>
</thead>
<tbody>
<tr>
<td>10</td>
<td>Col C</td>
</tr>
<tr>
<td>20</td>
<td>Col C</td>
</tr>
<tr>
<td>100</td>
<td>Col B</td>
</tr>
<tr>
<td>1000</td>
<td>Col A</td>
</tr>
<tr>
<td>30</td>
<td>Col C</td>
</tr>
<tr>
<td>40</td>
<td>Col C</td>
</tr>
<tr>
<td>200</td>
<td>Col B</td>
</tr>
<tr>
<td>2000</td>
<td>Col A</td>
</tr>
</tbody>
</table>
</div> | [
{
"answer_id": 74330566,
"author": "Vlad",
"author_id": 20382571,
"author_profile": "https://Stackoverflow.com/users/20382571",
"pm_score": 1,
"selected": false,
"text": "$order->loadMissing('orderItems.product')\n"
},
{
"answer_id": 74332314,
"author": "Don't Panic",
"author_id": 6089612,
"author_profile": "https://Stackoverflow.com/users/6089612",
"pm_score": 1,
"selected": false,
"text": "Product"
},
{
"answer_id": 74354309,
"author": "MrCujo",
"author_id": 2882913,
"author_profile": "https://Stackoverflow.com/users/2882913",
"pm_score": 0,
"selected": false,
"text": "OrderItem"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8371891/"
] |
74,330,519 | <p>Consider a few vectors v1,v2,v3 to which you need to apply one function (for example clear()).</p>
<pre><code>vector <int> v1;
vector <int> v2;
vector <int> v3;
v1.clear();
v2.clear();
v3.clear();
</code></pre>
<p>Can I do it in one line? So I need something like that</p>
<pre><code>someHOF(clear(), ls[v1, v2, v3]);
</code></pre>
| [
{
"answer_id": 74330531,
"author": "HolyBlackCat",
"author_id": 2752075,
"author_profile": "https://Stackoverflow.com/users/2752075",
"pm_score": 2,
"selected": false,
"text": "for (auto v : {&v1, &v2, &v3})\n v->clear();\n"
},
{
"answer_id": 74330662,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 0,
"selected": false,
"text": "std::for_each"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20427708/"
] |
74,330,529 | <p>I'm trying to display in the Message dialog on the <code>JOptionPane</code> the highest number of sales from my array of sales.</p>
<p>And I also want to show in which month they happened, but I am failing to find a way to display the month.</p>
<pre><code>public static void main(String[] args) {
int[] CarSales= {1234,2343,1456,4567,8768,2346,9876,4987,7592,9658,7851,2538};
String [] Months = {"January","February","March","April","May","June"
,"July ","August","September","October","November","December" };
int HighNum = CarSales[0];
for(int i = 0; i < CarSales.length; i++)
{
if(CarSales[i] > HighNum)
{
HighNum = CarSales[i];
}
}
JOptionPane.showMessageDialog(null,"The highest car sales value is :"+HighNum +
"-which happened in the month of");
}
</code></pre>
| [
{
"answer_id": 74330748,
"author": "Melron",
"author_id": 8920328,
"author_profile": "https://Stackoverflow.com/users/8920328",
"pm_score": 1,
"selected": false,
"text": "public static void main(String[] args) {\n int[] CarSales= {1234,2343,1456,4567,8768,2346,9876,4987,7592,9658,7851,2538};\n\n String [] Months = {\"January\",\"February\",\"March\",\"April\",\"May\",\"June\"\n ,\"July \",\"August\",\"September\",\"October\",\"November\",\"December\" };\n\n int HighNum = CarSales[0];\n String month = Months[0];\n\n for(int i = 0; i < CarSales.length; i++)\n {\n if(CarSales[i] > HighNum)\n {\n HighNum = CarSales[i];\n month = Months[i];\n }\n }\n JOptionPane.showMessageDialog(null,\"The highest car sales value is :\"+HighNum +\n \"-which happened in the month of \" + month);\n}\n"
},
{
"answer_id": 74330779,
"author": "Old Dog Programmer",
"author_id": 5103317,
"author_profile": "https://Stackoverflow.com/users/5103317",
"pm_score": 0,
"selected": false,
"text": "public static void main(String[] args) {\n int[] CarSales= {1234,2343,1456,4567,8768,2346,\n 9876,4987,7592,9658,7851,2538};\n\n String [] Months = {\"January\",\"February\",\"March\",\"April\",\"May\",\"June\"\n ,\"July \",\"August\",\"September\",\"October\",\"November\",\"December\" };\n\n int HighNum = CarSales[0];\n int highMonth = 0;\n\n for(int i = 0; i < CarSales.length; i++)\n {\n if(CarSales[i] > HighNum)\n {\n HighNum = CarSales[i];\n highMonth = i;\n }\n }\n JOptionPane.showMessageDialog\n (null,\"The highest car sales value is :\"+HighNum +\n \"-which happened in the month of \" + Months[highMonth]);\n}\n"
},
{
"answer_id": 74331177,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 2,
"selected": false,
"text": "CarSale"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19717601/"
] |
74,330,538 | <p>I've got a MongoDB collection, which looks like this:</p>
<pre class="lang-js prettyprint-override"><code>// sites
// note that these urls all have paths, this is important.
// The path can only be longer, e.g. amazon.com/Coffee-Mug
[
{
name: "MySite",
urls: ['google.com/search', 'amazon.com/Coffee', 'amazon.com/Mug']
},
{
name: "OtherSite",
urls: ['google.com/search', 'microsoft.com/en-us']
}
]
</code></pre>
<p>What I'm trying to do is the following:</p>
<pre><code>class Service {
/**
* @param url Is a full url, like "https://www.google.com/search?q=stackoverflow"
* or "https://www.amazon.com/Coffee-Program-Ceramic-Makes-Programmers/dp/B07D2XJLLG/"
*/
public async lookup(findUrl: string) {
const trimmed = trim(findUrl); // remove variables and https, but NOT the path!
// return the "Site" in which the base url is matched with the full url
// see description below
}
}
</code></pre>
<p>For example, using these cases</p>
<p><strong>Case 1:</strong></p>
<ul>
<li><code>url = 'https://www.amazon.com/Coffee-Program-Ceramic-Makes-Programmers/dp/B07D2XJLLG/'</code></li>
<li>returned site(s): <code>[MySite]</code></li>
</ul>
<p><strong>Case 2:</strong></p>
<ul>
<li><code>url = 'https://www.google.com/search?q=stackoverflow'</code></li>
<li>returned site(s): <code>[MySite, OtherSite]</code></li>
</ul>
<p><strong>Case 3 (same as case 1 but with other value):</strong></p>
<ul>
<li><code>url = 'https://www.microsoft.com/en-us/surface'</code></li>
<li>returned site(s): <code>[OtherSite]</code></li>
</ul>
<p><strong>Case 4 (when not to match):</strong></p>
<ul>
<li><code>url = 'https://microsoft.com/nl-nl'</code>
OR</li>
<li><code>url = 'https://microsoft.com'</code></li>
<li>returned site(s): <code>[]</code></li>
</ul>
<p>I've tried to do something like this:</p>
<pre class="lang-js prettyprint-override"><code>Site.find({ url: { $in: trimmed }})
</code></pre>
<p>Above kind of works, but the problem is, this only does exact matches. I want to match the url from MongoDB with the url provided by the function. How does one do this?</p>
<p>I've received the suggestion to use <a href="https://stackoverflow.com/questions/60783023/check-if-field-is-substring-of-a-string-or-text-search-on-mongodb">check if field is substring of a string or text search on MongoDB</a>, but this is too inaccurate. I can basically enter the base domain without a path and it will find it, this is definitely not supposed to be happening.</p>
| [
{
"answer_id": 74330748,
"author": "Melron",
"author_id": 8920328,
"author_profile": "https://Stackoverflow.com/users/8920328",
"pm_score": 1,
"selected": false,
"text": "public static void main(String[] args) {\n int[] CarSales= {1234,2343,1456,4567,8768,2346,9876,4987,7592,9658,7851,2538};\n\n String [] Months = {\"January\",\"February\",\"March\",\"April\",\"May\",\"June\"\n ,\"July \",\"August\",\"September\",\"October\",\"November\",\"December\" };\n\n int HighNum = CarSales[0];\n String month = Months[0];\n\n for(int i = 0; i < CarSales.length; i++)\n {\n if(CarSales[i] > HighNum)\n {\n HighNum = CarSales[i];\n month = Months[i];\n }\n }\n JOptionPane.showMessageDialog(null,\"The highest car sales value is :\"+HighNum +\n \"-which happened in the month of \" + month);\n}\n"
},
{
"answer_id": 74330779,
"author": "Old Dog Programmer",
"author_id": 5103317,
"author_profile": "https://Stackoverflow.com/users/5103317",
"pm_score": 0,
"selected": false,
"text": "public static void main(String[] args) {\n int[] CarSales= {1234,2343,1456,4567,8768,2346,\n 9876,4987,7592,9658,7851,2538};\n\n String [] Months = {\"January\",\"February\",\"March\",\"April\",\"May\",\"June\"\n ,\"July \",\"August\",\"September\",\"October\",\"November\",\"December\" };\n\n int HighNum = CarSales[0];\n int highMonth = 0;\n\n for(int i = 0; i < CarSales.length; i++)\n {\n if(CarSales[i] > HighNum)\n {\n HighNum = CarSales[i];\n highMonth = i;\n }\n }\n JOptionPane.showMessageDialog\n (null,\"The highest car sales value is :\"+HighNum +\n \"-which happened in the month of \" + Months[highMonth]);\n}\n"
},
{
"answer_id": 74331177,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 2,
"selected": false,
"text": "CarSale"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10546688/"
] |
74,330,550 | <p>Eh so hello. I Cant frikin figure how to build SLASH COMMANDS!!!! Tbh i dont even want to anymore but still asking (I am here for the 3d day trying to figure it out) so bruh. It is working, but it DOESN'T show the command in discord even if i type the command out it still DOESNT WORK.
So anyways heres my code:</p>
<pre><code>const { Server } = require('discord.io');
const Discord = require('discord.js');
const { Client, GatewayIntentBits, messageLink, InteractionResponseType } = require('discord.js');
const logger = require('winston');
const { EmbedBuilder, SlashCommandBuilder, Events } = require('discord.js');
const bot = new Discord.Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildEmojisAndStickers,
GatewayIntentBits.GuildMessageReactions,
],
});
const token = "heheheha"
//text
bot.on('ready', () => { // when the bot is ready and online
console.log('bot is now online!')
});
new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with Pong!'),
async execute(interaction)
{
await interaction.reply('Pong!');
}
</code></pre>
<p>oh and also, this is my Error log</p>
<pre><code> async execute(interaction)
^^^^^^^
SyntaxError: Unexpected identifier
at compileFunction (vm:360:18)
at wrapSafe (internal/modules/cjs/loader:1084:15)
at Module._compile (internal/modules/cjs/loader:1119:27)
at Module._extensions..js (internal/modules/cjs/loader:1209:10)
at Module.load (internal/modules/cjs/loader:1033:32)
at Module._load (internal/modules/cjs/loader:868:12)
at executeUserEntryPoint (internal/modules/run_main:81:12)
at <anonymous> (internal/main/run_main_module:22:47)
</code></pre>
| [
{
"answer_id": 74330748,
"author": "Melron",
"author_id": 8920328,
"author_profile": "https://Stackoverflow.com/users/8920328",
"pm_score": 1,
"selected": false,
"text": "public static void main(String[] args) {\n int[] CarSales= {1234,2343,1456,4567,8768,2346,9876,4987,7592,9658,7851,2538};\n\n String [] Months = {\"January\",\"February\",\"March\",\"April\",\"May\",\"June\"\n ,\"July \",\"August\",\"September\",\"October\",\"November\",\"December\" };\n\n int HighNum = CarSales[0];\n String month = Months[0];\n\n for(int i = 0; i < CarSales.length; i++)\n {\n if(CarSales[i] > HighNum)\n {\n HighNum = CarSales[i];\n month = Months[i];\n }\n }\n JOptionPane.showMessageDialog(null,\"The highest car sales value is :\"+HighNum +\n \"-which happened in the month of \" + month);\n}\n"
},
{
"answer_id": 74330779,
"author": "Old Dog Programmer",
"author_id": 5103317,
"author_profile": "https://Stackoverflow.com/users/5103317",
"pm_score": 0,
"selected": false,
"text": "public static void main(String[] args) {\n int[] CarSales= {1234,2343,1456,4567,8768,2346,\n 9876,4987,7592,9658,7851,2538};\n\n String [] Months = {\"January\",\"February\",\"March\",\"April\",\"May\",\"June\"\n ,\"July \",\"August\",\"September\",\"October\",\"November\",\"December\" };\n\n int HighNum = CarSales[0];\n int highMonth = 0;\n\n for(int i = 0; i < CarSales.length; i++)\n {\n if(CarSales[i] > HighNum)\n {\n HighNum = CarSales[i];\n highMonth = i;\n }\n }\n JOptionPane.showMessageDialog\n (null,\"The highest car sales value is :\"+HighNum +\n \"-which happened in the month of \" + Months[highMonth]);\n}\n"
},
{
"answer_id": 74331177,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 2,
"selected": false,
"text": "CarSale"
}
] | 2022/11/05 | [
"https://Stackoverflow.com/questions/74330550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18269108/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.