qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,590,699
|
<p>I have this array of objects returned from server</p>
<pre><code>{
"Code": 200,
"Message": "Success",
"response": [
{
"UserId": null,
"FullName": test,
"Status": null,
"IsActive": 1
},
{
"UserId": null,
"FullName": null,
"Status": 'Active',
"IsActive": 0
}...
...
]
}
</code></pre>
<p>getting response in <code>List</code> variable</p>
<pre><code> this.Service.getUser(payload).subscribe(result => {
this.List = result['response'];
});
</code></pre>
<p>i need some way to manipulate <code>Status</code> value such as if Status is <code>null</code> the assign it <code>Active</code> value.</p>
<p>and again store it in <code>this.List</code> variable without using any loop.</p>
<p>Please suggest some solution.</p>
<p>Thanks</p>
|
[
{
"answer_id": 74590769,
"author": "DecPK",
"author_id": 9153448,
"author_profile": "https://Stackoverflow.com/users/9153448",
"pm_score": 1,
"selected": true,
"text": "map response State Active Status === null const apiData = {\n \"Code\": 200,\n \"Message\": \"Success\",\n \"response\": [{\n \"UserId\": null,\n \"FullName\": 'test',\n \"Status\": null,\n \"IsActive\": 1\n },\n {\n \"UserId\": null,\n \"FullName\": null,\n \"Status\": 'Active',\n \"IsActive\": 0\n }\n ]\n}\n\nconst result = apiData.response.map(o => ({ ...o, Status: o.Status ?? \"Active\" }));\nconsole.log(result);"
},
{
"answer_id": 74590787,
"author": "Philipp Meissner",
"author_id": 3686898,
"author_profile": "https://Stackoverflow.com/users/3686898",
"pm_score": 1,
"selected": false,
"text": "Array map {...user} Status this.List = result['response'].map((user) => ({...user, Status: user.status === null ? 'Active' : user.status}));\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3653474/"
] |
74,590,759
|
<p>I am trying to extract the m/z data for different ions from "https://www.lipidmaps.org/databases/lmsd/LMFA08040013".
I can get access to the ions and thier data, however to extract the formula and m/z, I am thinking to convert it to a string and the use striping tool to extract it. Is thier another way using beautifulsoup?</p>
<pre><code>
from bs4 import BeautifulSoup #used to interact with the website
import requests
soup = BeautifulSoup(requests.get("https://www.lipidmaps.org/databases/lmsd/LMFA08040013").text, "html.parser")
for option in soup.find_all('option'):
ion = option.text
option = str(option)
m_z = ion
ion_formula =
return ([m_z,ion-formula,ion]
</code></pre>
<p>example of option data:</p>
<pre><code><option data-display-formula="C&lt;sub&gt;18&lt;/sub&gt;H&lt;sub&gt;38&lt;/sub&gt;NO&lt;sub&gt;2&lt;/sub&gt;" data-formula="C18H38NO2" data-mass-z-ratio="300.2897" value="MplusH">
[M+H]+
</option>
</code></pre>
<p>Example of output data:</p>
<pre><code>
m_z = 300.2897
ion-formula = C18H38NO2
ion = \[M+H\]+
</code></pre>
|
[
{
"answer_id": 74590769,
"author": "DecPK",
"author_id": 9153448,
"author_profile": "https://Stackoverflow.com/users/9153448",
"pm_score": 1,
"selected": true,
"text": "map response State Active Status === null const apiData = {\n \"Code\": 200,\n \"Message\": \"Success\",\n \"response\": [{\n \"UserId\": null,\n \"FullName\": 'test',\n \"Status\": null,\n \"IsActive\": 1\n },\n {\n \"UserId\": null,\n \"FullName\": null,\n \"Status\": 'Active',\n \"IsActive\": 0\n }\n ]\n}\n\nconst result = apiData.response.map(o => ({ ...o, Status: o.Status ?? \"Active\" }));\nconsole.log(result);"
},
{
"answer_id": 74590787,
"author": "Philipp Meissner",
"author_id": 3686898,
"author_profile": "https://Stackoverflow.com/users/3686898",
"pm_score": 1,
"selected": false,
"text": "Array map {...user} Status this.List = result['response'].map((user) => ({...user, Status: user.status === null ? 'Active' : user.status}));\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20298996/"
] |
74,590,765
|
<p>We are migrating to Azure devops environment and have a problem.
In our old environment, we used a Jenkins server to automate a release procedure ran a gradle maven deploy plugin script using following info:
groupId example: "com.foo"
artifactId example: "Hello"
artifact: example: 'jar'
feed url example: 'https://pkgs.dev.azure.com/......maven/v1'
password:...
, and the binaries then landed on a JFrog Artifactory server.</p>
<p>Now in Azure devops, we can't figure out how to publish the artifacts to an Artifact feed using any of its standard tasks. I have been looking at the universal packges tasks, and on the Maven@3, but none of them seems to provide the correct parameters.</p>
<p>More over, we are not sure of we should use the Release pipelines or "normal" pipelines. Can any Azure Devops whiz give some advice here?</p>
|
[
{
"answer_id": 74595854,
"author": "jasonroy7dct",
"author_id": 13416171,
"author_profile": "https://Stackoverflow.com/users/13416171",
"pm_score": -1,
"selected": false,
"text": "mvn deploy --settings c:\\user\\user-settings.xml"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7752058/"
] |
74,590,770
|
<p>I have a matrix of stores and their relative distance to each other similar to this table with 3000 rows and 3000 columns. I want to create a new table that shows the number of stores that are 5km or closer to each store.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th></th>
<th>store 1</th>
</tr>
</thead>
<tbody>
<tr>
<td>store 1</td>
<td>NA</td>
</tr>
<tr>
<td>store 2</td>
<td>200 (M)</td>
</tr>
</tbody>
</table>
</div>
<p>I have created this distance matrix using a data frame, which has the x coordinates and y coordinates of each store.</p>
<pre><code>dist_matrix <- st_distance(df)
diag(dist_matrix) <- NA
</code></pre>
<p>This gives me a matrix containing store distance to the next one in meters.</p>
<p>I want to find the number of stores that are located in a 5km radius to each store. I have tried to do this:
`</p>
<pre><code>
#making the matrix into a data frame
dist_matrix <- data.frame(dist_matrix)
names(dist_matrix) <- df$store_id
rownames(dist_matrix) <- df$store_id
close <- dist_matrix %>%
mutate(ID=rownames(.)) %>%
gather('closest','dist',-ID) %>%
filter(!is.na(dist)) %>%
arrange(dist)
</code></pre>
<p>But it does not seem to work. Does anyone have input on how to solve this?</p>
|
[
{
"answer_id": 74595854,
"author": "jasonroy7dct",
"author_id": 13416171,
"author_profile": "https://Stackoverflow.com/users/13416171",
"pm_score": -1,
"selected": false,
"text": "mvn deploy --settings c:\\user\\user-settings.xml"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20157038/"
] |
74,590,772
|
<p>when the bottom sheet appears it does not has that much height. but when a checkbox clicked in the bottom sheet it is expanding to the top regardless the screen size. what I have been trying to do is to set max height for bottom sheet. can't find proper solution for that so far. any helps are welcome!</p>
<p>ps: what I have been trying do is open bottom sheet dialog as wrap content initially. after the checkbox is checked its height should have max value. in other words I want to expand it regarding the max height of bottom sheet that will be given.</p>
<p>senario:</p>
<ol>
<li>bottom model should be opened as <code>wrap_content</code></li>
<li>when an item in bottom sheet is clicked the height of the bottom sheet should change to specific a value.</li>
</ol>
|
[
{
"answer_id": 74595854,
"author": "jasonroy7dct",
"author_id": 13416171,
"author_profile": "https://Stackoverflow.com/users/13416171",
"pm_score": -1,
"selected": false,
"text": "mvn deploy --settings c:\\user\\user-settings.xml"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4862911/"
] |
74,590,800
|
<p>I have a dataset that looks like the following:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>INCOME</th>
<th>WEALTH</th>
</tr>
</thead>
<tbody>
<tr>
<td>10.000</td>
<td>100000</td>
</tr>
<tr>
<td>15.000</td>
<td>111000</td>
</tr>
<tr>
<td>14.200</td>
<td>123456</td>
</tr>
<tr>
<td>12.654</td>
<td>654321</td>
</tr>
</tbody>
</table>
</div>
<p>I have many more rows.</p>
<p>I now want to now find how much INCOME a household in a specific WEALTH percentile has. The following quantiles are relevant:</p>
<pre><code>c(0.01,0.05,0.1,0.25,0.5,0.75,0.9,0.95,0.99)
</code></pre>
<p>I have always used the following code to get specific percentile values:</p>
<pre><code>a <- quantile(WEALTH, probs = c(0.01,0.05,0.1,0.25,0.5,0.75,0.9,0.95,0.99))
</code></pre>
<p>But now I want to base my percentiles on WEALTH but get the respective INCOME. I have tried the following code but the results are not plausible:</p>
<pre><code>df$percentile = ntile(df$WEALTH,100)
df <- df[df$percentile %in% c(1,5,10,25,50,75,90,95,99), ]
a <- df %>%
group_by(percentile) %>%
summarise(max = max(INCOME))
</code></pre>
<p>The results that I get a not consistent with other parts of the analysis that I have done. I assume that the percentile when using the "quantile" function are calculated differently that simply taking the maximum.</p>
|
[
{
"answer_id": 74591084,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 0,
"selected": false,
"text": "dplyr::ntile(x, 100) library(dplyr)\n\ndf %>% \n mutate(percentile = ntile(WEALTH, 100))\n # A tibble: 4 × 3\n INCOME WEALTH percentile\n <dbl> <dbl> <int>\n1 10 100000 1\n2 15 111000 2\n3 14.2 123456 3\n4 12.7 654321 4\n scales::rescale() library(scales)\n\ndf %>% \n mutate(percentile = rescale(\n ntile(WEALTH, 100),\n c(1, 100)\n ))\n # A tibble: 4 × 3\n INCOME WEALTH percentile\n <dbl> <dbl> <dbl>\n1 10 100000 1\n2 15 111000 34\n3 14.2 123456 67\n4 12.7 654321 100\n"
},
{
"answer_id": 74591698,
"author": "RYann",
"author_id": 19110927,
"author_profile": "https://Stackoverflow.com/users/19110927",
"pm_score": 3,
"selected": true,
"text": "?quantile"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20615065/"
] |
74,590,801
|
<p>I have a scraper of headlines, but I want a publication date also.</p>
<p>That's my code:</p>
<pre class="lang-py prettyprint-override"><code>news = []
url = 1
while url != 100:
website = f"https://www.newscientist.com/subject/space/page/{url}"
r = requests.get(
website,
headers={
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0",
"Referer": website
}
)
soup = bs(r.text, 'html.parser')
for h2 in soup.find_all("h2"):
news.append(h2.get_text(strip=True))
</code></pre>
<p>The problem is the publication date is ''inside'' <code>news</code> and I don't know how to get there.</p>
|
[
{
"answer_id": 74590960,
"author": "HedgeHog",
"author_id": 14460824,
"author_profile": "https://Stackoverflow.com/users/14460824",
"pm_score": 1,
"selected": false,
"text": "import pandas as pd\npd.read_xml('https://www.newscientist.com/subject/space/feed/', xpath='*/item')\n for a in soup.select('h2+a'):\n soup_article = BeautifulSoup(\n requests.get(\n 'https://www.newscientist.com'+a.get('href'),\n headers={\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0\",\n }\n ).text\n )\n news.append(\n {\n 'title':soup_article.h1.text,\n 'date':soup_article.select_one('.published-date').get_text(strip=True) if soup_article.select_one('.published-date') else None\n }\n )\nnews\n"
},
{
"answer_id": 74591332,
"author": "accdias",
"author_id": 6789321,
"author_profile": "https://Stackoverflow.com/users/6789321",
"pm_score": 0,
"selected": false,
"text": "import requests\nfrom bs4 import BeautifulSoup as bs\n\nspace_rss = \"https://www.newscientist.com/subject/space/feed/\"\n\nr = requests.get(\n space_rss,\n headers={\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0\",\n \"Referer\": space_rss,\n },\n)\n\nif r.ok:\n soup = bs(r.text, \"xml\")\n news = [\n (item.select_one(\"pubDate\").text, item.select_one(\"title\").text)\n for item in soup.find_all(\"item\")\n ]\n news tuple(pubDate, title) RSS"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18355160/"
] |
74,590,808
|
<p>I am trying to parse the JSON from <code>aws ecr describe-images</code>, and return a result with a specific image tag, matching a pattern, from the list. In particular I get an array with many of these entries:</p>
<pre class="lang-json prettyprint-override"><code>{
"imageDetails": [
{
"registryId": "997652729005",
"repositoryName": "events",
"imageDigest": "sha256:5b649219a3abc5e903b27fd947f375df8634c883432a69e40d245ac2393d67b2",
"imageTags": [
"events-test-build-340"
],
"imageSizeInBytes": 314454408,
"imagePushedAt": "2021-01-12T10:42:51-05:00",
"imageScanStatus": {
"status": "COMPLETE",
"description": "The scan was completed successfully."
},
"imageScanFindingsSummary": {
"imageScanCompletedAt": "2021-01-12T10:43:00-05:00",
"vulnerabilitySourceUpdatedAt": "2021-01-12T04:45:25-05:00",
"findingSeverityCounts": {}
},
"imageManifestMediaType": "application/vnd.docker.distribution.manifest.v2+json",
"artifactMediaType": "application/vnd.docker.container.image.v1+json"
},
{
"registryId": "997652729005",
"repositoryName": "events",
"imageDigest": "sha256:0fae259bcfe02c8cf0ec3746aae668b3166960e7119467496df9aedfbc2c8c5b",
"imageTags": [
"6debaabc26cc82a4011ea9c71854cebac7a57250-433",
"6debaabc26cc82a4011ea9c71854cebac7a57250",
"6debaabc26cc82a4011ea9c71854cebac7a57250-433-dev",
"events-prod-build-433"
],
"imageSizeInBytes": 316110570,
"imagePushedAt": "2020-12-21T03:11:52-05:00",
"imageScanStatus": {
"status": "COMPLETE",
"description": "The scan was completed successfully."
},
"imageScanFindingsSummary": {
"imageScanCompletedAt": "2020-12-21T03:12:02-05:00",
"vulnerabilitySourceUpdatedAt": "2020-11-03T20:21:09-05:00",
"findingSeverityCounts": {}
},
"imageManifestMediaType": "application/vnd.docker.distribution.manifest.v2+json",
"artifactMediaType": "application/vnd.docker.container.image.v1+json"
}
]
}
</code></pre>
<p>I would like the output to be something like this:</p>
<pre class="lang-json prettyprint-override"><code>{
"tag": [
"6debaabc26cc82a4011ea9c71854cebac7a57250"
],
"sha": "sha256:5b649219a3abc5e903b27fd947f375df8634c883432a69e40d245ac2393d67b2",
"imagePushedAt": "2021-01-12T10:42:51-05:00"
}
</code></pre>
<p>The challenge is to pick the images that have a tag whose name includes <strong><code>*prod-build*</code></strong> (a deployed production build), but then return a the tag having <strong>no dashes</strong> in it, which is the tag we actually use. (Yes, this is entirely defective, I know).</p>
<p>I have gotten pretty far:</p>
<pre class="lang-bash prettyprint-override"><code>cat ecr-describe-images-events.json
| jq '.imageDetails[]
| {tag: .imageTags, sha: .imageDigest, date_pushed: .imagePushedAt}
| select( .tag | contains(["prod-build"]))
.tag[] |= walk(
if type=="string" then
select(
match("^[^-]+$")
)
else
null
end
)'
</code></pre>
<p>So, from the <code>imageDetails</code> array, get and name elements, then from the array of tags select the nodes that have a tag with the string <code>prod-build</code>. From these nodes, find the<br />
<code>tags</code> array element whose name does not include dashes, and return that.</p>
<p>The last part, which I have done with <code>select</code>, <code>walk</code>, and <code>match</code> is behaving differently than I expect. I am getting:</p>
<pre class="lang-json prettyprint-override"><code>{
"tag": [
"events-test-build-340"
],
"sha": "sha256:5b649219a3abc5e903b27fd947f375df8634c883432a69e40d245ac2393d67b2",
"date_pushed": "2021-01-12T10:42:51-05:00"
}
{
"tag": [
"6debaabc26cc82a4011ea9c71854cebac7a57250",
"events-prod-build-433",
null,
null
],
"sha": "sha256:8638389b7d83869b17b1c74ff30740d7cf8eff4574100c1270f20d4686252552",
"date_pushed": "2021-02-17T13:11:42-05:00"
}
</code></pre>
<p>If I don't include the last part, starting <code>walk(...)</code> I get the correct nodes. But when I do use <code>walk</code> with match or test, I get back array elements that don't match my regexp.</p>
<p>I am not fixed on my approach, or on the output format: I just need the three fields in some structure. What have I failed to understand?</p>
|
[
{
"answer_id": 74590960,
"author": "HedgeHog",
"author_id": 14460824,
"author_profile": "https://Stackoverflow.com/users/14460824",
"pm_score": 1,
"selected": false,
"text": "import pandas as pd\npd.read_xml('https://www.newscientist.com/subject/space/feed/', xpath='*/item')\n for a in soup.select('h2+a'):\n soup_article = BeautifulSoup(\n requests.get(\n 'https://www.newscientist.com'+a.get('href'),\n headers={\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0\",\n }\n ).text\n )\n news.append(\n {\n 'title':soup_article.h1.text,\n 'date':soup_article.select_one('.published-date').get_text(strip=True) if soup_article.select_one('.published-date') else None\n }\n )\nnews\n"
},
{
"answer_id": 74591332,
"author": "accdias",
"author_id": 6789321,
"author_profile": "https://Stackoverflow.com/users/6789321",
"pm_score": 0,
"selected": false,
"text": "import requests\nfrom bs4 import BeautifulSoup as bs\n\nspace_rss = \"https://www.newscientist.com/subject/space/feed/\"\n\nr = requests.get(\n space_rss,\n headers={\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0\",\n \"Referer\": space_rss,\n },\n)\n\nif r.ok:\n soup = bs(r.text, \"xml\")\n news = [\n (item.select_one(\"pubDate\").text, item.select_one(\"title\").text)\n for item in soup.find_all(\"item\")\n ]\n news tuple(pubDate, title) RSS"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/414127/"
] |
74,590,813
|
<p><a href="https://i.stack.imgur.com/OAD4t.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OAD4t.png" alt="enter image description here" /></a></p>
<p>so im trying to make the names stay below even at different sizes of screen.
I can't make the category names stay below. <a href="https://i.stack.imgur.com/vrDEc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vrDEc.png" alt="enter image description here" /></a></p>
<p>this is the source code so far</p>
<pre><code>class CategoryItem extends StatelessWidget {
final Category category;
const CategoryItem({super.key, required this.category});
@override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Container(
padding: EdgeInsets.only(top: 20),
decoration: BoxDecoration(
color: category.backColor,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(10),
topRight: Radius.circular(10)
)
),
child: Stack(
children: [
Image.asset(
category.image,
height: 80,
width: 80,
alignment: Alignment.topCenter,
),
Container(
padding: EdgeInsets.all(10),
width: double.infinity,
margin: EdgeInsets.only(top: 60),
color: Colors.white,
child: Text(category.title)
)
]
),
);
}
}
</code></pre>
|
[
{
"answer_id": 74590960,
"author": "HedgeHog",
"author_id": 14460824,
"author_profile": "https://Stackoverflow.com/users/14460824",
"pm_score": 1,
"selected": false,
"text": "import pandas as pd\npd.read_xml('https://www.newscientist.com/subject/space/feed/', xpath='*/item')\n for a in soup.select('h2+a'):\n soup_article = BeautifulSoup(\n requests.get(\n 'https://www.newscientist.com'+a.get('href'),\n headers={\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0\",\n }\n ).text\n )\n news.append(\n {\n 'title':soup_article.h1.text,\n 'date':soup_article.select_one('.published-date').get_text(strip=True) if soup_article.select_one('.published-date') else None\n }\n )\nnews\n"
},
{
"answer_id": 74591332,
"author": "accdias",
"author_id": 6789321,
"author_profile": "https://Stackoverflow.com/users/6789321",
"pm_score": 0,
"selected": false,
"text": "import requests\nfrom bs4 import BeautifulSoup as bs\n\nspace_rss = \"https://www.newscientist.com/subject/space/feed/\"\n\nr = requests.get(\n space_rss,\n headers={\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0\",\n \"Referer\": space_rss,\n },\n)\n\nif r.ok:\n soup = bs(r.text, \"xml\")\n news = [\n (item.select_one(\"pubDate\").text, item.select_one(\"title\").text)\n for item in soup.find_all(\"item\")\n ]\n news tuple(pubDate, title) RSS"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18069814/"
] |
74,590,831
|
<p>Given type definitions</p>
<pre><code>struct a { int a; };
struct b { int b; struct a ba;};
</code></pre>
<p>and a function taking <code>struct a* a</code> and <code>struct b* b</code>, the type information expresses possible overlap between <code>a->a</code> and <code>b->ba.a</code> but no overlap on <code>b->b</code>.</p>
<p>Therefore in a function such as:</p>
<pre><code>int possibleOverlapOn2ndInt(struct a *a, struct b *b){
b->b = 0xbb; //unaliased
b->ba.a = 0xba; //may alias a->a
a->a = 0xaa; //may alias b->ba.a;
return b->b /*0xbb*/ + b->ba.a;
}
</code></pre>
<p>compilers need not reload <code>b->b</code> in the return line and instead they may substitute the stored constant. Gcc and clang indeed do this.</p>
<p>I am curious if this case of possible partial overlap could be expressed without via <code>restrict</code> without using <code>struct</code>s.</p>
<p>I've tried:</p>
<pre><code>int possibleOverlapOn2ndInt_(int a[1], int b[2]){ //<=> (int *a, int *b)
int *restrict bp = &b[0];
bp[0] = 0xbb; //unaliased
b[1] = 0xba; //may alias a[0]
a[0] = 0xaa; //may alias b[1]
return bp[0] /*0xbb?*/ + b[1];
}
</code></pre>
<p>but got no effect from having the <code>restrict</code>ed pointer there. <a href="https://godbolt.org/z/9Y7zz37rs" rel="nofollow noreferrer">https://godbolt.org/z/9Y7zz37rs</a></p>
<p>Am I using <code>restrict</code> wrong here is it the compilers not optimizing as well as they could?</p>
|
[
{
"answer_id": 74590954,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 0,
"selected": false,
"text": "bp int possibleOverlapOn2ndInt_(int * restrict a, int *b){ //<=> (int *a, int *b)\n b[0] = 0xbb; //unaliased\n b[1] = 0xba; //may alias a[0]\n a[0] = 0xaa; //may alias b[1]\n return b[0] /*0xbb?*/ + b[1];\n"
},
{
"answer_id": 74591180,
"author": "John Bollinger",
"author_id": 2402272,
"author_profile": "https://Stackoverflow.com/users/2402272",
"pm_score": 3,
"selected": true,
"text": "restrict restrict restrict restrict D P restrict T D int *restrict bp = &b[0]; P bp T int B B possibleOverlapOn2ndInt_() E P B E P E possibleOverlapOn2ndInt_() bp a b B L &L P a[0] b[0] b[1] possibleOverlapOn2ndInt_() bp[0] L X bp[0] X bp[0] bp[0] X P a[0] bp[0] b[0] possibleOverlapOn2ndInt_() possibleOverlapOn2ndInt_() restrict int possibleOverlapOn2ndInt_2(int a[1], int b[2]) {\n b[0] = 0xbb;\n b[1] = 0xba; // cannot alias b[0]\n a[0] = 0xaa; // must not alias b[0], may alias b[1]\n return 0xbb + b[1];\n}\n"
},
{
"answer_id": 74605417,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 1,
"selected": false,
"text": "int x[10];\nint test1(int *restrict p, int i)\n{\n if (p+i != x)\n return 0;\n p[0] = 1;\n p[i] = 2;\n return 23 * p[0];\n}\nint test2(int *p, int *q)\n{\n int *restrict pp = p;\n *pp = 1;\n *q = 2;\n return 23 * *pp;\n}\n test1 i p x test2 *pp pp q"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1084774/"
] |
74,590,885
|
<p>I am learning flutter. I have few doubts.</p>
<p>For flutter app to run we do need a flutter engine, right?</p>
<p>But when I download a flutter app from Play Store(android) or App store(ios) when do the flutter engine gets installed into mobile ?</p>
<p>For a reference I have saw this <a href="https://github.com/flutter/flutter/issues/56863" rel="nofollow noreferrer">https://github.com/flutter/flutter/issues/56863</a> , is this how it happens ?</p>
|
[
{
"answer_id": 74590954,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 0,
"selected": false,
"text": "bp int possibleOverlapOn2ndInt_(int * restrict a, int *b){ //<=> (int *a, int *b)\n b[0] = 0xbb; //unaliased\n b[1] = 0xba; //may alias a[0]\n a[0] = 0xaa; //may alias b[1]\n return b[0] /*0xbb?*/ + b[1];\n"
},
{
"answer_id": 74591180,
"author": "John Bollinger",
"author_id": 2402272,
"author_profile": "https://Stackoverflow.com/users/2402272",
"pm_score": 3,
"selected": true,
"text": "restrict restrict restrict restrict D P restrict T D int *restrict bp = &b[0]; P bp T int B B possibleOverlapOn2ndInt_() E P B E P E possibleOverlapOn2ndInt_() bp a b B L &L P a[0] b[0] b[1] possibleOverlapOn2ndInt_() bp[0] L X bp[0] X bp[0] bp[0] X P a[0] bp[0] b[0] possibleOverlapOn2ndInt_() possibleOverlapOn2ndInt_() restrict int possibleOverlapOn2ndInt_2(int a[1], int b[2]) {\n b[0] = 0xbb;\n b[1] = 0xba; // cannot alias b[0]\n a[0] = 0xaa; // must not alias b[0], may alias b[1]\n return 0xbb + b[1];\n}\n"
},
{
"answer_id": 74605417,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 1,
"selected": false,
"text": "int x[10];\nint test1(int *restrict p, int i)\n{\n if (p+i != x)\n return 0;\n p[0] = 1;\n p[i] = 2;\n return 23 * p[0];\n}\nint test2(int *p, int *q)\n{\n int *restrict pp = p;\n *pp = 1;\n *q = 2;\n return 23 * *pp;\n}\n test1 i p x test2 *pp pp q"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13952947/"
] |
74,590,893
|
<p>I'm currently using a TensorFlow model that I've made to predict the X next prices for a curve using a for loop that calls the append() fonction of the pandas dataframe.</p>
<p>The model is a time series one so at each loop I calculate the "next date" uing the last dataframe row and I calculate the predicted price using the last row of the Dataframe, then I append the new row containing the "next date" and the predicted price to the dataframe so that it can predict the next price in the following loop.</p>
<p>The problem is that the dataframe doesn't get appended</p>
<p>Here's the code if anyone knows, also if it's not the way that it should be done don't hesitate to correct me I did this knowing that I'm new to the whole TensorFlow / Pandas modules</p>
<pre><code>last_data = pd.read_excel("Nickel.xlsx")
print('Old dataset before loop : ', last_data)
for i in range(10):
new_df = last_data.filter(['Valeur'])
last_60_days = new_df[-60+(-i):].values
last_60_days_scaled = scaler.transform(last_60_days)
X_test = []
X_test.append(last_60_days_scaled)
X_test = np.array(X_test)
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
pred_price = model.predict(X_test)
pred_price = scaler.inverse_transform(pred_price)
#print('Prix predit : ', pred_price)
dernieredate = last_data['Date'].iloc[-1]
datecorrect = pd.to_datetime(dernieredate)
print('Old date : ', datecorrect)
nextdate = datecorrect + pd.to_timedelta(1,unit='d')
print('New date : ', nextdate)
last_data.append([nextdate, pred_price])
print('New dataset final after loop : ', last_data)
</code></pre>
<p>Here's the log :</p>
<pre><code>Old dataset before loop : Date Valeur
0 2002-09-16 6770
1 2002-09-17 6550
2 2002-09-18 6590
3 2002-09-19 6610
4 2002-09-20 6580
... ... ...
4995 2022-11-14 27000
4996 2022-11-15 29595
4997 2022-11-16 28550
4998 2022-11-17 26050
4999 2022-11-18 24800
[5000 rows x 2 columns]
1/1 [==============================] - 0s 20ms/step
Prix predit : [[26672.488]]
Old date : 2022-11-18 00:00:00
New date : 2022-11-19 00:00:00
1/1 [==============================] - 0s 22ms/step
Old date : 2022-11-18 00:00:00
New date : 2022-11-19 00:00:00
1/1 [==============================] - 0s 21ms/step
Old date : 2022-11-18 00:00:00
New date : 2022-11-19 00:00:00
1/1 [==============================] - 0s 20ms/step
Old date : 2022-11-18 00:00:00
New date : 2022-11-19 00:00:00
1/1 [==============================] - 0s 22ms/step
Old date : 2022-11-18 00:00:00
New date : 2022-11-19 00:00:00
1/1 [==============================] - 0s 21ms/step
Old date : 2022-11-18 00:00:00
New date : 2022-11-19 00:00:00
1/1 [==============================] - 0s 22ms/step
Old date : 2022-11-18 00:00:00
New date : 2022-11-19 00:00:00
1/1 [==============================] - 0s 21ms/step
Old date : 2022-11-18 00:00:00
New date : 2022-11-19 00:00:00
1/1 [==============================] - 0s 20ms/step
Old date : 2022-11-18 00:00:00
New date : 2022-11-19 00:00:00
1/1 [==============================] - 0s 22ms/step
Old date : 2022-11-18 00:00:00
New date : 2022-11-19 00:00:00
New dataset final after loop : Date Valeur
0 2002-09-16 6770
1 2002-09-17 6550
2 2002-09-18 6590
3 2002-09-19 6610
4 2002-09-20 6580
... ... ...
4995 2022-11-14 27000
4996 2022-11-15 29595
4997 2022-11-16 28550
4998 2022-11-17 26050
4999 2022-11-18 24800
[5000 rows x 2 columns]
</code></pre>
<p>Thank you a lot!</p>
|
[
{
"answer_id": 74591006,
"author": "gtomer",
"author_id": 10836309,
"author_profile": "https://Stackoverflow.com/users/10836309",
"pm_score": 1,
"selected": false,
"text": "last_data.append([nextdate, pred_price])\n last_data = last_data.append([nextdate, pred_price])\n last_data = pd.concat([nextdate, pred_price])\n"
},
{
"answer_id": 74591060,
"author": "Adam Ben kahla",
"author_id": 11622880,
"author_profile": "https://Stackoverflow.com/users/11622880",
"pm_score": 1,
"selected": false,
"text": "last_data = pd.read_excel(\"Nickel.xlsx\")\nprint('Old dataset before loop : ', last_data)\nfor i in range(10):\n new_df = last_data.filter(['Valeur'])\n last_60_days = new_df[-60+(-i):].values\n last_60_days_scaled = scaler.transform(last_60_days)\n X_test = []\n X_test.append(last_60_days_scaled)\n X_test = np.array(X_test)\n X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))\n pred_price = model.predict(X_test)\n pred_price = scaler.inverse_transform(pred_price)\n #print('Prix predit : ', pred_price)\n dernieredate = last_data['Date'].iloc[-1]\n datecorrect = pd.to_datetime(dernieredate)\n print('Old date : ', datecorrect)\n nextdate = datecorrect + pd.to_timedelta(1,unit='d')\n print('New date : ', nextdate)\n Data_Temp = {'Date':nextdate, 'Valeur':pred_price[0]}\n New_data = last_data.append(Data_Temp, ignore_index=True)\n \nprint('New dataset final after loop : ', New_data)\n"
},
{
"answer_id": 74591437,
"author": "Jirayu Kaewprateep",
"author_id": 7848579,
"author_profile": "https://Stackoverflow.com/users/7848579",
"pm_score": 0,
"selected": false,
"text": "import tensorflow as tf\nimport pandas as pd\n\n\nvariables = pd.read_excel('F:\\\\temp\\\\20220305\\\\Book 2.xlsx', , index_col=None, header=[0])\nprint( 'variables: ' )\nprint( variables )\nprint( tf.constant(variables).numpy() ) # (6, 6)\nprint( 'variables.append: ' )\ntemp = tf.constant(variables.append( pd.DataFrame([[0, 0, 0, 0, 0, 2], [0, 0, 0, 0, 2, 0], [0, 0, 0, 2, 0, 0]]) ) ).numpy()\ntemp = pd.DataFrame( temp )\nprint( temp ) \nprint( 'variables.append: ' )\nprint( tf.constant(temp.append( pd.DataFrame([[0, 0, 0, 0, 0, 0, 0, 4]]) ) ).numpy() ) \n\n\nprint( 'pd.concat: ' )\ntemp = tf.constant( pd.concat([ variables, pd.DataFrame([0, 0, 0, 0, 0, 2]) ], axis=1) ).numpy()\nprint( temp )\nprint( 'pd.concat: ' )\nprint( tf.constant( pd.concat([ pd.DataFrame(temp), pd.DataFrame([0, 0, 0, 0, 0, 3]) ], axis=1) ).numpy() )\n for Index, Image, Label in variables.values:\n print( Label )\n list_label.append( Label )\n\n image = tf.io.read_file( Image )\n image = tfio.experimental.image.decode_tiff(image, index=0)\n list_file_actual.append(image)\n image = tf.image.resize(image, [32,32], method='nearest')\n list_Image.append(image)\n\n list_label = tf.cast( list_label, dtype=tf.int32 )\n list_label = tf.constant( list_label, shape=( 33, 1, 1 ) )\n list_Image = tf.cast( list_Image, dtype=tf.int32 )\n list_Image = tf.constant( list_Image, shape=( 33, 1, 32, 32, 4 ) )\n\ndataset = tf.data.Dataset.from_tensor_slices(( list_Image, list_label ))\n 0 1 2 3 4 5\n0 1 0 0 0 0 0\n1 0 1 0 0 0 0\n2 0 0 1 0 0 0\n3 0 0 0 1 0 0\n4 0 0 0 0 1 0\n5 0 0 0 0 0 1\n\n[[1 0 0 0 0 0]\n [0 1 0 0 0 0]\n [0 0 1 0 0 0]\n [0 0 0 1 0 0]\n [0 0 0 0 1 0]\n [0 0 0 0 0 1]]\n variables.append:\n\n 0 1 2 3 4 5\n0 1 0 0 0 0 0\n1 0 1 0 0 0 0\n2 0 0 1 0 0 0\n3 0 0 0 1 0 0\n4 0 0 0 0 1 0\n5 0 0 0 0 0 1\n6 0 0 0 0 0 2\n7 0 0 0 0 2 0\n8 0 0 0 2 0 0\n variables.append:\n\n[[ 1. 0. 0. 0. 0. 0. nan nan]\n [ 0. 1. 0. 0. 0. 0. nan nan]\n [ 0. 0. 1. 0. 0. 0. nan nan]\n [ 0. 0. 0. 1. 0. 0. nan nan]\n [ 0. 0. 0. 0. 1. 0. nan nan]\n [ 0. 0. 0. 0. 0. 1. nan nan]\n [ 0. 0. 0. 0. 0. 2. nan nan]\n [ 0. 0. 0. 0. 2. 0. nan nan]\n [ 0. 0. 0. 2. 0. 0. nan nan]\n [ 0. 0. 0. 0. 0. 0. 0. 4.]]\n pd.concat:\n[[1 0 0 0 0 0 0]\n [0 1 0 0 0 0 0]\n [0 0 1 0 0 0 0]\n [0 0 0 1 0 0 0]\n [0 0 0 0 1 0 0]\n [0 0 0 0 0 1 2]]\n pd.concat:\n[[1 0 0 0 0 0 0 0]\n [0 1 0 0 0 0 0 0]\n [0 0 1 0 0 0 0 0]\n [0 0 0 1 0 0 0 0]\n [0 0 0 0 1 0 0 0]\n [0 0 0 0 0 1 2 3]]\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11622880/"
] |
74,590,913
|
<p>Lets say I want to extract current <code>State</code> (D/R/S/T/Z) and command <code>Name</code> from processes with given <code>PID</code>.</p>
<p>For example I have this code:</p>
<pre><code>pids=$(pidof firefox) #returns all PID-s of firefox processes (random example)
for v in ${pids[*]}
do
echo "PID: $v" #here I also want to write status and name of the command (PID, Name, Status)
done
</code></pre>
<pre><code>more /proc/$$/status
</code></pre>
<p>returns</p>
<pre><code>Name: bash
Umask: 002
State: S (sleeping)
....
Pid: 3234
...
</code></pre>
<p>From all that information I only need some. I want to know how to extract desired property (<code>Name</code>, <code>Status</code>,...) from <code>proc</code>.</p>
|
[
{
"answer_id": 74591446,
"author": "markp-fuso",
"author_id": 7366100,
"author_profile": "https://Stackoverflow.com/users/7366100",
"pm_score": 0,
"selected": false,
"text": "awk Name State $ awk '$1==\"Name:\"{name=$2;next}$1==\"State:\"{print name,$2;exit}' /proc/$$/status\nbash S\n awk pids=( $(pidof firefox) #returns all PID-s of firefox processes (random example) )\n\nfor v in \"${pids[*]}\"\ndo\n read -r name state < <(awk '$1==\"Name:\"{name=$2;next}$1==\"State:\"{print name,$2;exit}' /proc/${v}/status)\n echo \"PID: ${v} / Name: ${name} / State: ${state}\"\ndone\n PID: 3234 / Name: bash / State: S\n"
},
{
"answer_id": 74592952,
"author": "Paul Hodges",
"author_id": 8656552,
"author_profile": "https://Stackoverflow.com/users/8656552",
"pm_score": 0,
"selected": false,
"text": "awk $: awk '/^Pid:/{ pid[FILENAME]=$2 } /^Name:/{ name[FILENAME]=$2 } /^State:/{ state[FILENAME]=$2 } END{ for (k in pid) printf \"PID:\\t%s\\tName:\\t%s\\tState:\\t%s\\n\", pid[k],name[k],state[k] }' $( sed -E 's,(.*),/proc/\\1/status,' <(pidof firefox) ) \nPID: 1619 Name: firefox State: S\nPID: 1620 Name: firefox State: S\n cat lst pidof firefox $: cat lst # the file\n1619\n1620\n$: sed -E 's,(.*),/proc/\\1/status,' <(cat lst) # the status inputs\n/proc/1619/status\n/proc/1620/status\n$: awk '/^Pid:/{ pid[FILENAME]=$2 }\n /^Name:/{ name[FILENAME]=$2 }\n /^State:/{ state[FILENAME]=$2 }\n END{ for (k in pid) printf \"PID:\\t%s\\tName:\\t%s\\tState:\\t%s\\n\", pid[k],name[k],state[k] }\n ' $( sed -E 's,(.*),/proc/\\1/status,' <(cat lst) )\nPID: 1619 Name: mintty State: S\nPID: 1620 Name: bash State: S\n"
},
{
"answer_id": 74593899,
"author": "j_b",
"author_id": 16482938,
"author_profile": "https://Stackoverflow.com/users/16482938",
"pm_score": 1,
"selected": false,
"text": "grep pids=$(pidof firefox); pids=${pids// /,}; grep '^Pid\\|Name\\|State' < <(bash <<<\"cat /proc/{$pids}/status\"\n Name: Isolated Servic\nState: S (sleeping)\nPid: 1052298\nName: Isolated Web Co\nState: S (sleeping)\nPid: 981127\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20433724/"
] |
74,590,923
|
<p>I have two json files that I would like to concatenate into one. Is there any approach to combine these json?</p>
<pre class="lang-py prettyprint-override"><code>json1 = {
"105912": {
"name": "Avatar - Tocasia, Dig Site Mentor",
"cardset": "VAN",
"rarity": "Rare",
"foil": 0,
"price": 0.05
},
"105911": {
"name": "Avatar - Yotian Frontliner",
"cardset": "VAN",
"rarity": "Rare",
"foil": 0,
"price": 0.05
}
}
json2 = {
"105912": {
"name": "Avatar - Tocasia, Dig Site Mentor",
"cardset": "VAN",
"rarity": "Rare",
"foil": 0,
"price": 0.0007
},
"105911": {
"name": "Avatar - Yotian Frontliner",
"cardset": "VAN",
"rarity": "Rare",
"foil": 0,
"price": 0.0007
}
}
import pandas as pd
from glob import glob
arquivos = sorted(glob('price-history\*.json'))
todos_dados = pd.concat((pd.read_json(cont, lines=True, orient='records') for cont in
arquivos))
print(todos_dados)
</code></pre>
<p>the error that is returning is <code>ValueError: Expected object or value</code></p>
<p>The expected output would be a dataframe to be able to filter data.</p>
|
[
{
"answer_id": 74591153,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 3,
"selected": true,
"text": "import pandas as pd\n\njson1 = {\n \"105912\": {\n \"name\": \"Avatar - Tocasia, Dig Site Mentor\",\n \"cardset\": \"VAN\",\n \"rarity\": \"Rare\",\n \"foil\": 0,\n \"price\": 0.05,\n },\n \"105911\": {\n \"name\": \"Avatar - Yotian Frontliner\",\n \"cardset\": \"VAN\",\n \"rarity\": \"Rare\",\n \"foil\": 0,\n \"price\": 0.05,\n },\n}\n\njson2 = {\n \"105912\": {\n \"name\": \"Avatar - Tocasia, Dig Site Mentor\",\n \"cardset\": \"VAN\",\n \"rarity\": \"Rare\",\n \"foil\": 0,\n \"price\": 0.0007,\n },\n \"105911\": {\n \"name\": \"Avatar - Yotian Frontliner\",\n \"cardset\": \"VAN\",\n \"rarity\": \"Rare\",\n \"foil\": 0,\n \"price\": 0.0007,\n },\n}\n\njsons = json1, json2\n\ndf = pd.DataFrame(\n [v for j in jsons for v in j.values()], index=[k for j in jsons for k in j]\n)\nprint(df)\n name cardset rarity foil price\n105912 Avatar - Tocasia, Dig Site Mentor VAN Rare 0 0.0500\n105911 Avatar - Yotian Frontliner VAN Rare 0 0.0500\n105912 Avatar - Tocasia, Dig Site Mentor VAN Rare 0 0.0007\n105911 Avatar - Yotian Frontliner VAN Rare 0 0.0007\n"
},
{
"answer_id": 74591256,
"author": "lackti",
"author_id": 18060154,
"author_profile": "https://Stackoverflow.com/users/18060154",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\n\njson1 = {\n \"105912\": {\n \"name\": \"Avatar - Tocasia, Dig Site Mentor\",\n \"cardset\": \"VAN\",\n \"rarity\": \"Rare\",\n \"foil\": 0,\n \"price\": 0.05\n },\n \"105911\": {\n \"name\": \"Avatar - Yotian Frontliner\",\n \"cardset\": \"VAN\",\n \"rarity\": \"Rare\",\n \"foil\": 0,\n \"price\": 0.05\n }\n}\n\njson2 = {\n \"105912\": {\n \"name\": \"Avatar - Tocasia, Dig Site Mentor\",\n \"cardset\": \"VAN\",\n \"rarity\": \"Rare\",\n \"foil\": 0,\n \"price\": 0.0007\n },\n \"105911\": {\n \"name\": \"Avatar - Yotian Frontliner\",\n \"cardset\": \"VAN\",\n \"rarity\": \"Rare\",\n \"foil\": 0,\n \"price\": 0.0007\n }\n}\n\nlist_jsons = [json1,json2]\ntodos_dados = pd.concat(([pd.DataFrame.from_dict(json_obj,orient='index') for json_obj in list_jsons]))\n\ntodos_dados\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18543007/"
] |
74,590,930
|
<p>I have an ingress service where I can curl to "/" to the UI of the project, but everything but the slash is not routing properly. Below is my last ingress service I tried.</p>
<pre><code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
annotations:
kubernetes.io/ingress.class: nginx
meta.helm.sh/release-name: ingress
meta.helm.sh/release-namespace: default
creationTimestamp: "2022-11-26T15:57:15Z"
generation: 1
labels:
app.kubernetes.io/managed-by: Helm
name: ingress-service
namespace: default
resourceVersion: "53584"
uid: fccbcc20-e365-42cd-be29-0fff80611ddc
spec:
rules:
- host: project.k8s.com
http:
paths:
- backend:
service:
name: project-backend
port:
number: 8080
path: /api/
pathType: Prefix
- backend:
service:
name: project-backend
port:
number: 8080
path: /api/general/details/
pathType: Prefix
- backend:
service:
name: project-backend
port:
number: 8080
path: /api/general/
pathType: Prefix
- backend:
service:
name: project-ui
port:
number: 8080
path: /
pathType: Prefix
status:
loadBalancer:
ingress:
- ip: xxx.xxx.xx.x
</code></pre>
<p>The curls I try</p>
<pre><code>curl http://xx.xxx.xxx.xx/api/general/detail -H "Host: project.k8s.com"
{"timestamp":"2022-11-27T14:29:31.899+00:00","status":404,"error":"Not Found","path":"/api/general/detail"}
curl http://xx.xxx.xxx.xx/ -H "Host: project.k8s.com" <-- The UI as expected
</code></pre>
<p>In the Spring logs I read</p>
<pre><code>Tomcat started on port(s): 8080 (http) with context path '/api'
</code></pre>
<p>Which makes me think that the backend service is working correctly and in the ingress logs I see the requests being made. It is a simple backend with a controller with @RequestMapping("api/general/detail/") which I tested outside the cluster.</p>
<p>Am I correct? Is the backend service working correctly? Is there anything else to do than looking at the logs / output of the ingress yaml / k get all ?</p>
|
[
{
"answer_id": 74591195,
"author": "Stanislav Kovalenko",
"author_id": 8099169,
"author_profile": "https://Stackoverflow.com/users/8099169",
"pm_score": 2,
"selected": true,
"text": "- path: /api/()(.*)\n pathType: ImplementationSpecific\n backend:\n service:\n name: project-backend\n port:\n number: 8080\n"
},
{
"answer_id": 74592418,
"author": "Long",
"author_id": 9190646,
"author_profile": "https://Stackoverflow.com/users/9190646",
"pm_score": 0,
"selected": false,
"text": "path: / pathType: Prefix"
},
{
"answer_id": 74592520,
"author": "Sahan Gunathilaka",
"author_id": 10031128,
"author_profile": "https://Stackoverflow.com/users/10031128",
"pm_score": 0,
"selected": false,
"text": "/api/general"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11856842/"
] |
74,590,994
|
<p>I'm currently trying to use atomic design in my vue app.</p>
<p>Below is the code for my button atom:</p>
<pre><code><template>
<ElButton
:type="button?.type"
:plain="button?.plain"
:rounded="button?.rounded"
:icon="button?.icon"
:disabled="button?.disabled"
:loading="button?.loading"
:size="button?.size"
>
{{ button?.label }}
</ElButton>
</template>
<script lang="ts">
import { ElButton } from "element-plus"
import { PropType, defineComponent } from "vue"
interface IButton {
label: String
type: String
plain?: boolean
rounded?: boolean
icon?: String
disabled?: boolean
loading?: boolean
size?: String
rest?: any
}
export default defineComponent({
name: "Button",
props: {
button: Object as PropType<IButton>,
},
components: {
ElButton,
},
})
</script>
</code></pre>
<p>And i'm using the button in my <code>HelloWorld.vue</code></p>
<pre><code><script lang="ts">
import {defineComponent } from "vue"
import Button from "./atom/input/index.vue"
export default defineComponent({
components: {
Button,
},
})
</script>
<template>
<Button type="success" size="large" label="Primary Button" />
</template>
</code></pre>
<p>With the above setup, I can use my button component with ease. Only issue is that the button doesn't show it's text.</p>
<p>Though I have passed label prop to the component it is shown as attribute of the button when I inspect the button element.</p>
<p>Like this:</p>
<p><code><button class="el-button el-button--success el-button--large" type="button" label="Primary Button"></button></code></p>
<p>Can anyone help me to figure out what I'm missing here ?</p>
|
[
{
"answer_id": 74591195,
"author": "Stanislav Kovalenko",
"author_id": 8099169,
"author_profile": "https://Stackoverflow.com/users/8099169",
"pm_score": 2,
"selected": true,
"text": "- path: /api/()(.*)\n pathType: ImplementationSpecific\n backend:\n service:\n name: project-backend\n port:\n number: 8080\n"
},
{
"answer_id": 74592418,
"author": "Long",
"author_id": 9190646,
"author_profile": "https://Stackoverflow.com/users/9190646",
"pm_score": 0,
"selected": false,
"text": "path: / pathType: Prefix"
},
{
"answer_id": 74592520,
"author": "Sahan Gunathilaka",
"author_id": 10031128,
"author_profile": "https://Stackoverflow.com/users/10031128",
"pm_score": 0,
"selected": false,
"text": "/api/general"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7512296/"
] |
74,591,001
|
<p>I am trying to fetch an API with the weekly schedule for the NFL provided by Rapid API. I'm having trouble reading the data and displaying it. It returns an array (below) but any time I reference the data within the array it results in an error of not being able to locate it as each game is referenced as 0, 1, 2, etc. This is my starting point.</p>
<p>data results from API</p>
<p><a href="https://i.stack.imgur.com/qitLu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qitLu.png" alt="" /></a></p>
<pre><code>const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': 'my-api-key',
'X-RapidAPI-Host': 'nfl-schedule.p.rapidapi.com'
}
};
fetch('https://nfl-schedule.p.rapidapi.com/v1/schedules', options)
.then(function(response){
let data = response.json();
return data;
})
.then(data => {
console.log(data)
const game = Array(16);
for(i=0; i < game.length; i++){
const matchup = data[i].shortName;
const gameDate = data[i].date;
document.getElementById('matchup').innerText = matchup;
document.getElementById('gameDate').innerText = gameDate;
}
})
.catch(err => console.error(err));
});
</code></pre>
<p>This is the data from the API.</p>
<pre><code>{message: 'NFL Scheduled games', data: Array(16)}
data
:
Array(16)
0
:
awayTeam
:
{name: 'Buccaneers', score: '0'}
date
:
"2022-11-27T18:00Z"
homeTeam
:
{name: 'Browns', score: '0'}
name
:
"Tampa Bay Buccaneers at Cleveland Browns"
shortName
:
"TB @ CLE"
venue
:
"FirstEnergy Stadium"
[[Prototype]]
:
Object
1
:
awayTeam
:
{name: 'Bengals', score: '0'}
date
:
"2022-11-27T18:00Z"
homeTeam
:
{name: 'Titans', score: '0'}
name
:
"Cincinnati Bengals at Tennessee Titans"
shortName
:
"CIN @ TEN"
venue
:
"Nissan Stadium"
[[Prototype]]
:
Object
2
:
{date: '2022-11-27T18:00Z', venue: 'Hard Rock Stadium', name: 'Houston Texans at Miami Dolphins', shortName: 'HOU @ MIA', awayTeam: {…}, …}
3
:
{date: '2022-11-27T18:00Z', venue: 'MetLife Stadium', name: 'Chicago Bears at New York Jets', shortName: 'CHI @ NYJ', awayTeam: {…}, …}
4
:
{date: '2022-11-27T18:00Z', venue: 'FedExField', name: 'Atlanta Falcons at Washington Commanders', shortName: 'ATL @ WSH', awayTeam: {…}, …}
5
:
{date: '2022-11-27T18:00Z', venue: 'Bank of America Stadium', name: 'Denver Broncos at Carolina Panthers', shortName: 'DEN @ CAR', awayTeam: {…}, …}
6
:
{date: '2022-11-27T18:00Z', venue: 'TIAA Bank Field', name: 'Baltimore Ravens at Jacksonville Jaguars', shortName: 'BAL @ JAX', awayTeam: {…}, …}
7
:
{date: '2022-11-27T21:05Z', venue: 'State Farm Stadium', name: 'Los Angeles Chargers at Arizona Cardinals', shortName: 'LAC @ ARI', awayTeam: {…}, …}
8
:
{date: '2022-11-27T21:05Z', venue: 'Lumen Field', name: 'Las Vegas Raiders at Seattle Seahawks', shortName: 'LV @ SEA', awayTeam: {…}, …}
9
:
{date: '2022-11-27T21:25Z', venue: 'GEHA Field at Arrowhead Stadium', name: 'Los Angeles Rams at Kansas City Chiefs', shortName: 'LAR @ KC', awayTeam: {…}, …}
10
:
{date: '2022-11-27T21:25Z', venue: "Levi's Stadium", name: 'New Orleans Saints at San Francisco 49ers', shortName: 'NO @ SF', awayTeam: {…}, …}
11
:
{date: '2022-11-28T01:20Z', venue: 'Lincoln Financial Field', name: 'Green Bay Packers at Philadelphia Eagles', shortName: 'GB @ PHI', awayTeam: {…}, …}
12
:
{date: '2022-11-24T17:30Z', venue: 'Ford Field', name: 'Buffalo Bills at Detroit Lions', shortName: 'BUF @ DET', awayTeam: {…}, …}
13
:
{date: '2022-11-24T21:30Z', venue: 'AT&T Stadium', name: 'New York Giants at Dallas Cowboys', shortName: 'NYG @ DAL', awayTeam: {…}, …}
14
:
{date: '2022-11-25T01:20Z', venue: 'U.S. Bank Stadium', name: 'New England Patriots at Minnesota Vikings', shortName: 'NE @ MIN', awayTeam: {…}, …}
15
:
{date: '2022-11-29T01:15Z', venue: 'Lucas Oil Stadium', name: 'Pittsburgh Steelers at Indianapolis Colts', shortName: 'PIT @ IND', awayTeam: {…}, …}
length
:
16
[[Prototype]]
:
Array(0)
message
:
"NFL Scheduled games"
[[Prototype]]
:
Object
</code></pre>
<p>I've tried parsing the results with a for loop since it returns an array and have tried calling based on the property path given.</p>
|
[
{
"answer_id": 74591195,
"author": "Stanislav Kovalenko",
"author_id": 8099169,
"author_profile": "https://Stackoverflow.com/users/8099169",
"pm_score": 2,
"selected": true,
"text": "- path: /api/()(.*)\n pathType: ImplementationSpecific\n backend:\n service:\n name: project-backend\n port:\n number: 8080\n"
},
{
"answer_id": 74592418,
"author": "Long",
"author_id": 9190646,
"author_profile": "https://Stackoverflow.com/users/9190646",
"pm_score": 0,
"selected": false,
"text": "path: / pathType: Prefix"
},
{
"answer_id": 74592520,
"author": "Sahan Gunathilaka",
"author_id": 10031128,
"author_profile": "https://Stackoverflow.com/users/10031128",
"pm_score": 0,
"selected": false,
"text": "/api/general"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20615241/"
] |
74,591,005
|
<p>I’m trying to figure out how to keep “Mark as Read” as “Mark as Unread” even after refreshing the page. Vice versa too. How do I save the data with localStorage? So far, this is my code for “Mark as Read”:</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>function readunread() {
currentvalue = document.getElementById("readunread").value;
if(currentvalue == "Mark as Unread"){
document.getElementById("readunread").value = "Mark as Read";
} else{
document.getElementById("readunread").value = "Mark as Unread";
}
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
background:black;
}
.button {
border: none;
color: white;
font-family: Corbel;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
background-color: black;
}
input[type=button] {
font-size: 20px;
font-family: Corbel;
text-decoration: none;
color: white;
border: none;
background: none;
cursor: pointer;
margin: 0;
padding: 0;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type = "button" value = "Mark as Read" id = "readunread" onclick = "readunread();"></code></pre>
</div>
</div>
</p>
<p>I click the “Mark as Read” and it becomes “Mark as Unread.” But after refreshing the page, it goes back to “Mark as Read.” How do I avoid that?</p>
|
[
{
"answer_id": 74591195,
"author": "Stanislav Kovalenko",
"author_id": 8099169,
"author_profile": "https://Stackoverflow.com/users/8099169",
"pm_score": 2,
"selected": true,
"text": "- path: /api/()(.*)\n pathType: ImplementationSpecific\n backend:\n service:\n name: project-backend\n port:\n number: 8080\n"
},
{
"answer_id": 74592418,
"author": "Long",
"author_id": 9190646,
"author_profile": "https://Stackoverflow.com/users/9190646",
"pm_score": 0,
"selected": false,
"text": "path: / pathType: Prefix"
},
{
"answer_id": 74592520,
"author": "Sahan Gunathilaka",
"author_id": 10031128,
"author_profile": "https://Stackoverflow.com/users/10031128",
"pm_score": 0,
"selected": false,
"text": "/api/general"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20615177/"
] |
74,591,012
|
<p>I'd Like to get data in home screen of my flutter app, where I have list of OfferCards, these are generated from firestore via FirestoreQueryBuilder in my homeView like this</p>
<pre><code>FirestoreQueryBuilder<OfferData>(
pageSize: 10,
query: FirebaseFirestore.instance
.collection('Offers')
.orderBy('CreatedAt', descending: true)
.withConverter<OfferData>(
fromFirestore: ((snapshot, options) =>
OfferData.fromJson(snapshot.data()!)),
toFirestore: (value, options) => value.toJson()),
builder: (context, snapshot, _) {
if (snapshot.isFetching) {
return const Center(
child: CircularProgressIndicator(color: Colors.greenAccent),
);
} else if (snapshot.hasError) {
return const Center(
child: Text('Server error'),
);
} else if (snapshot.docs.isEmpty) {
return const Center(
child: Text('No offers'),
);
} else {
return ListView.builder(
itemBuilder: (context, index) {
final hasReachEnd = snapshot.hasMore &&
index + 1 == snapshot.docs.length &&
!snapshot.isFetchingMore;
if (hasReachEnd) {
snapshot.fetchMore();
}
final post = snapshot.docs[index].data();
homeController.offers[index] = post;
return OfferCardView();
},
itemCount: snapshot.docs.length);
}
},
)
</code></pre>
<p>As on the end of this example, inside HomeController I have Map of int and UserData, which is filled with all offers. Each offerCardView has Get.find to HomeController to have access to this map. And here's my question, how do I determine inside of OfferCardView and later in OfferView(after tapping on given OfferCardView) which entry from map is being clicked on/view filled with. I don't know how to acomplish this, I'm aware that using Map here is bad decision, but I don't have clue how this should be done</p>
|
[
{
"answer_id": 74592700,
"author": "Paulo",
"author_id": 15649348,
"author_profile": "https://Stackoverflow.com/users/15649348",
"pm_score": 0,
"selected": false,
"text": "Get.lazyPut<OfferCardsController>(() => OfferCardsController());\n var offerCardsController = Get.find<OfferCardsController>();\n OfferCardsController OfferController offerCardsController.variableFromCardsController;\n"
},
{
"answer_id": 74619468,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 2,
"selected": true,
"text": "index OfferView() OfferCardView() OfferView() GetxController GetxController Getx Get.delete() Get.find() GetPage"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5153786/"
] |
74,591,083
|
<p>The following codes are from Locust examples - <a href="https://github.com/locustio/locust/blob/master/examples/use_as_lib.py" rel="nofollow noreferrer">use_as_lib</a>.</p>
<pre class="lang-py prettyprint-override"><code>import gevent
from locust import HttpUser, task
from locust.env import Environment
from locust.stats import stats_printer, stats_history
from locust.log import setup_logging
setup_logging("INFO", None)
class MyUser(HttpUser):
host = "https://docs.locust.io"
@task
def t(self):
self.client.get("/")
env = Environment(user_classes=[MyUser])
runner = env.create_local_runner()
web_ui = env.create_web_ui("127.0.0.1", 8089)
env.events.init.fire(environment=env, runner=runner, web_ui=web_ui)
gevent.spawn(stats_printer(env.stats))
gevent.spawn(stats_history, env.runner)
runner.start(1, spawn_rate=10)
gevent.spawn_later(60, lambda: runner.quit())
runner.greenlet.join()
web_ui.stop()
</code></pre>
<p>If I run it with <code>python use_as_lib.py</code>, everything works fine. But if I run it with <code>python use_as_lib.py -c argument01 -b argument02</code>, it will fail with:</p>
<pre><code>use_as_lib.py: error: unrecognized arguments: -c -b argument02
</code></pre>
<p>In my case, the snippet above is part of a big program, which has its own command line arguments.</p>
<p>I checked a bit, seems <code>argument_parser.ui_extra_args_dict()</code> <a href="https://github.com/locustio/locust/blob/b0baaebbcd2e7705a5c6ee298ac17799c96b02bb/locust/web.py#L529" rel="nofollow noreferrer">here</a> invoked by <code>env.create_web_ui("127.0.0.1", 8089)</code> will parse all the arguments, which cause this issue.</p>
<p>Any ideas on how to fix it ? Thanks!</p>
|
[
{
"answer_id": 74592700,
"author": "Paulo",
"author_id": 15649348,
"author_profile": "https://Stackoverflow.com/users/15649348",
"pm_score": 0,
"selected": false,
"text": "Get.lazyPut<OfferCardsController>(() => OfferCardsController());\n var offerCardsController = Get.find<OfferCardsController>();\n OfferCardsController OfferController offerCardsController.variableFromCardsController;\n"
},
{
"answer_id": 74619468,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 2,
"selected": true,
"text": "index OfferView() OfferCardView() OfferView() GetxController GetxController Getx Get.delete() Get.find() GetPage"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1476512/"
] |
74,591,093
|
<p>I have the below list represents images sources coming from Flask backend,</p>
<pre><code>[
"www.example.com","www.example2.com","www.example3.com"...
]
</code></pre>
<p>Now I'm trying to use the react react-image-gallery to display all those images. From the tutorial I see I need to make it like below:</p>
<pre><code>const images = [
{
original: "www.example.com",
thumbnail: "www.example.com/thumbnail",
}
]
</code></pre>
<p>I'm confused about how to make the array list of images URLs mapped into this object/dictionary array? Ideally I need to make it like:</p>
<pre><code>const images = [
{
original: "www.example.com",
thumbnail: "www.example.com/thumbnail",
},
{
original: "www.example2.com",
thumbnail: "www.example2.com/thumbnail",
},
{
original: "www.example3.com",
thumbnail: "www.example3.com/thumbnail",
}......
]
</code></pre>
<p>Could anyone please enlighten me?
Any help will be much appreciated!</p>
|
[
{
"answer_id": 74591115,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 2,
"selected": false,
"text": "map const list = [\n \"www.example.com\",\"www.example2.com\",\"www.example3.com\",\n \n]\n\nconst result = list.map(item => {\n return {\n original: item,\n thumbnail: `${item}/thumbnail`,\n }\n})\n\nconsole.log(result)"
},
{
"answer_id": 74591117,
"author": "DecPK",
"author_id": 9153448,
"author_profile": "https://Stackoverflow.com/users/9153448",
"pm_score": 3,
"selected": true,
"text": "map const srcArr = [\"www.example.com\", \"www.example2.com\", \"www.example3.com\"]\n\nconst result = srcArr.map(original => ({ original, thumbnail: `${original}/thumbnail`}));\nconsole.log(result)"
},
{
"answer_id": 74591156,
"author": "king",
"author_id": 20612326,
"author_profile": "https://Stackoverflow.com/users/20612326",
"pm_score": 0,
"selected": false,
"text": "Array.prototype.map()"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10841577/"
] |
74,591,136
|
<p>I can sort a 2D-array in Javascript like the following:</p>
<pre><code>const a = [[-1, 5], [3, 2], [-25, 1], [12, 3], [12, 1]]
a.sort((a,b) => {
if (a[0] != b[0]) {
return a[0] - b[0]
}
else {
return b[1] - a[1] * 2 + 3
}
})
</code></pre>
<p>How to perform the same task in Python?</p>
|
[
{
"answer_id": 74591115,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 2,
"selected": false,
"text": "map const list = [\n \"www.example.com\",\"www.example2.com\",\"www.example3.com\",\n \n]\n\nconst result = list.map(item => {\n return {\n original: item,\n thumbnail: `${item}/thumbnail`,\n }\n})\n\nconsole.log(result)"
},
{
"answer_id": 74591117,
"author": "DecPK",
"author_id": 9153448,
"author_profile": "https://Stackoverflow.com/users/9153448",
"pm_score": 3,
"selected": true,
"text": "map const srcArr = [\"www.example.com\", \"www.example2.com\", \"www.example3.com\"]\n\nconst result = srcArr.map(original => ({ original, thumbnail: `${original}/thumbnail`}));\nconsole.log(result)"
},
{
"answer_id": 74591156,
"author": "king",
"author_id": 20612326,
"author_profile": "https://Stackoverflow.com/users/20612326",
"pm_score": 0,
"selected": false,
"text": "Array.prototype.map()"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12076036/"
] |
74,591,165
|
<p>I have a df like so:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({"code": [sp,wh,sp], "qty": [20, 30, 10]})
</code></pre>
<p>I want to create a new column based on data from the two columns with the value the new column as the same as an existing column if a condition is met. This is what I’ve tried:</p>
<pre><code>df['out'] = df.apply(lambda x: x['qty']) if x['code'] == 'sp' else 0)
</code></pre>
<p>so my output in this case should be:</p>
<pre><code>df = [
{'code':'sp', 'qty':20, 'out':20}
{'code':'wh', 'qty':30, 'out':0}
{'code':'sp', 'qty':10, 'out':10}
]
</code></pre>
|
[
{
"answer_id": 74591115,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 2,
"selected": false,
"text": "map const list = [\n \"www.example.com\",\"www.example2.com\",\"www.example3.com\",\n \n]\n\nconst result = list.map(item => {\n return {\n original: item,\n thumbnail: `${item}/thumbnail`,\n }\n})\n\nconsole.log(result)"
},
{
"answer_id": 74591117,
"author": "DecPK",
"author_id": 9153448,
"author_profile": "https://Stackoverflow.com/users/9153448",
"pm_score": 3,
"selected": true,
"text": "map const srcArr = [\"www.example.com\", \"www.example2.com\", \"www.example3.com\"]\n\nconst result = srcArr.map(original => ({ original, thumbnail: `${original}/thumbnail`}));\nconsole.log(result)"
},
{
"answer_id": 74591156,
"author": "king",
"author_id": 20612326,
"author_profile": "https://Stackoverflow.com/users/20612326",
"pm_score": 0,
"selected": false,
"text": "Array.prototype.map()"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14923964/"
] |
74,591,202
|
<p>I have the following function, inside of a Context file in my React app:</p>
<pre><code>const fetchAll = (userId) => {
try {
fetchDetails(userId)
// To be clear... There's multiple functions here, i.e:
// fetchContact(userId)
} catch (err) {
console.log(err)
}
setPending(false)
}
</code></pre>
<p>I've removed some of the functions - but the main premise of the function is to combine multiple promises together, and until these are complete, display a 'pending' component.</p>
<p>This pending component is displayed if the 'pending' state is set to true:</p>
<pre><code>const [pending, setPending] = useState(true)
</code></pre>
<p>However, at the moment, what is happening is that the try is attempted, but the setPending is executed at the same time.</p>
<p>I thought one way around this would be to utilise a 'finally' call at the end of the my try / catch, but that still executes at the same time. Like this:</p>
<pre><code>const fetchAll = (userId) => {
try {
fetchDetails(userId)
} catch (err) {
console.log(err)
} finally {
setPending(false)
}
}
</code></pre>
<p>I don't want any of my functions to be run asynchronously: I want them all to execute at the same time to prevent a waterfall effect of multiple network requests at once.</p>
<p>For reference, my individual 'fetch' functions call an endpoint and set state data based upon the response:</p>
<pre><code>const fetchDetails = (userId) => {
axios.post("/api/fetch/fetchDetails", {
id: userId
})
.then((response) => {
console.log(response.data)
setName(response.data.name)
setPreviewPhoto(response.data.profile_picture_url)
setPhotoName(response.data.profile_picture_name)
setPhotoFile(response.data.profile_picture_url)
})
}
</code></pre>
<p>Does anyone have any suggestions as to how I could make this work?</p>
|
[
{
"answer_id": 74591224,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 0,
"selected": false,
"text": "fetchDetails const fetchAll = async (userId) => {\n\n try {\n await fetchDetails(userId)\n } catch (err) {\n console.log(err)\n } finally {\n setPending(false)\n }\n\n}\n"
},
{
"answer_id": 74591553,
"author": "jgurbanov",
"author_id": 5589483,
"author_profile": "https://Stackoverflow.com/users/5589483",
"pm_score": 0,
"selected": false,
"text": "Promise.all() Promise.allSettled() setPending(true)\ntry {\n await Promise.all([() => fetchAll(1), () => fetchAll(2)])\n} finally {\n setPending(false)\n}\n"
},
{
"answer_id": 74591602,
"author": "Amirhossein",
"author_id": 11342834,
"author_profile": "https://Stackoverflow.com/users/11342834",
"pm_score": 2,
"selected": true,
"text": "Promise.all([fetchAll('123'), fetchAll('321')]).then((responses) => {\n setPending(false)\n}\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12640056/"
] |
74,591,286
|
<p>I want to run several commands independently in different bash scripts. If they are all finished the computer should shut down. Therefor I created a counter, called "n" in a txt file, which goes up one number every time a script is executed and goes down one number after finishing. If the counter is not zero the script shouldn't shutdown my computer.</p>
<pre><code>#!/bin/bash
source /home/user/bin/log/counter.txt
$n = $n + 1
echo "backup"
$n = $n -1
if [ "$n" == "0" ] ; then
echo "shutdown"
#shutdown -P now
else
exit 0
fi
</code></pre>
|
[
{
"answer_id": 74591802,
"author": "acred",
"author_id": 20615477,
"author_profile": "https://Stackoverflow.com/users/20615477",
"pm_score": -1,
"selected": false,
"text": "/home/bin/rsnapshot-custom.sh daily 1\n #!/bin/bash\nsource /home/bin/log/counter.txt\nfrequence=\"$1\"\npause=\"$2\"\nsleep $pause\nn=$((n+1))\necho \"n=$n\" > /home/bin/log/counter.txt\n/var/lib/openmediavault/cron.d/rsnapshot $frequence\nsource /home/bin/log/counter.txt\nn=$((n-1))\necho \"n=$n\" > /home/bin/log/counter.txt\nif [ $n == \"0\" ] ; then\n shutdown -P now\nelse\n exit 0\nfi\n"
},
{
"answer_id": 74593954,
"author": "Andrej Podzimek",
"author_id": 8584929,
"author_profile": "https://Stackoverflow.com/users/8584929",
"pm_score": 0,
"selected": false,
"text": "increment decrement flock #!/bin/bash\nset -euo pipefail\n\n_atomically_modify() {\n local -r file_name=\"$1\" # file name for descriptor 0\n local -r operation=\"$2\" # the transformation to perform\n flock 0 # atomic from here until return\n trap 'trap - return; flock -u 0' return\n local after\n after=\"$(\"$operation\")\" # read + modify\n printf '%s' \"$after\" > \"$file_name\" # write\n printf '%s' \"$after\" # fetch (for the caller to use)\n}\n\n_increment_operation() { printf '%d' \"$((\"$(< /dev/stdin)\" + 1))\"; }\n_decrement_operation() { printf '%d' \"$((\"$(< /dev/stdin)\" - 1))\"; }\n\nincrement() { _atomically_modify \"$1\" '_increment_operation' < \"$1\"; }\ndecrement() { _atomically_modify \"$1\" '_decrement_operation' < \"$1\"; }\n n_processes n_rmw #!/bin/bash\nset -euo pipefail\n\ndeclare -ri n_processes=20\ndeclare -ri n_rmw=30\ndeclare -i i j counter\ncounter_file=\"$(mktemp)\"\ndeclare -r counter_file\ntrap 'rm \"$counter_file\"' exit\n\nprintf '%d' \"$((n_processes + 1))\" > \"$counter_file\"\nfor ((i = 0; i < n_processes; ++i)); do (\n for ((j = 0; j < n_rmw; ++j)); do # play with the counter\n increment \"$counter_file\" > /dev/null\n decrement \"$counter_file\" > /dev/null\n done\n counter=\"$(decrement \"$counter_file\")\" # work finished\n ((! counter)) && printf 'Process %d finished last.\\n' \"$i\"\n)& done\ncounter=\"$(decrement \"$counter_file\")\" # track the starter process\n((! counter)) && printf 'The starter process finished last.\\n'\n\nwait # only to check the counter\nprintf 'Final counter value: %d\\n' \"$(< \"$counter_file\")\"\n flock 0 increment printf '%d' \"$((n_processes + 1))\" > \"$counter_file\" n_processes + 1 shutdown"
},
{
"answer_id": 74594098,
"author": "KamilCuk",
"author_id": 9072753,
"author_profile": "https://Stackoverflow.com/users/9072753",
"pm_score": 0,
"selected": false,
"text": "log echo \"$0\" >> /home/user/bin/log/done.txt\nlines=$(wc -l </home/user/bin/log/done.txt)\nif ((lines == n)); then\n echo \"shutdown\"\nfi\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20615477/"
] |
74,591,301
|
<p>I have a table <code>per_person_names_f</code> with columns <code>full_name</code> and <code>name_type</code>, when <code>name_type</code> is equal to <code>SA</code>, then <code>fullname</code> is Arabic, if <code>GLOBAL</code> then it's English. I want the result to show 2 columns for Arabic and English names.</p>
<pre><code>SELECT
rownum,
CASE name_type
WHEN 'Global' THEN full_name
END AS "english name",
CASE name_type
WHEN 'SA' THEN full_name
END AS "arabic name"
FROM
per_person_names_f
</code></pre>
<p>But it ends with weird results, column <code>english name</code> is empty and <code>arabic name</code> shows some <code>null</code> values, what's wrong here knowing that data does certainly exist?</p>
|
[
{
"answer_id": 74591365,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 1,
"selected": false,
"text": "SQL> with per_person_names_f (name_type, full_name) as\n 2 (select 'Global', 'my English name' from dual union all\n 3 select 'SA' , 'my Arabic name' from dual\n 4 )\n 5 select name_type,\n 6 case when name_type = 'Global' then full_name end as english_name,\n 7 case when name_type = 'SA' then full_name end as arabic_name\n 8 from per_person_names_f;\n\nNAME_T ENGLISH_NAME ARABIC_NAME\n------ --------------- ---------------\nGlobal my English name\nSA my Arabic name\n\nSQL>\n"
},
{
"answer_id": 74591469,
"author": "Sergey",
"author_id": 14535517,
"author_profile": "https://Stackoverflow.com/users/14535517",
"pm_score": 0,
"selected": false,
"text": "WITH PERSON_NAMES_F(FULL_NAME,NAME_TYPE) AS\n(\n SELECT 'ABDUL','SA' FROM DUAL UNION ALL\n SELECT 'JONNY','GLOBAL' FROM DUAL\n)\nSELECT \n CASE \n WHEN P.NAME_TYPE='SA' THEN P.FULL_NAME\n ELSE NULL\n END ARABIC_NAME,\n CASE\n WHEN P.NAME_TYPE='GLOBAL' THEN P.FULL_NAME\n ELSE NULL\nEND INTERNATIONAL_NAME\nFROM PERSON_NAMES_F P\n"
},
{
"answer_id": 74591610,
"author": "Alex Poole",
"author_id": 266304,
"author_profile": "https://Stackoverflow.com/users/266304",
"pm_score": 0,
"selected": false,
"text": "GLOBAL 'Global' 'GLOBAL' person_id person_id SELECT\n person_id,\n MAX(CASE name_type\n WHEN 'GLOBAL' THEN full_name \n END) AS \"english name\",\n MAX(CASE name_type\n WHEN 'SA' THEN full_name \n END) AS \"arabic name\"\nFROM \n per_person_names_f\nGROUP BY\n person_id\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20403738/"
] |
74,591,309
|
<p>I'm trying to do the following (consider this list):</p>
<pre><code>['Hello, 'Hi', 'Nice', Cool']
</code></pre>
<p>I would like to change 'Hi' to 'Love'</p>
<p>But, I wouldn't want it to stay that way:</p>
<pre><code>['Hello, 'Love', 'Nice', Cool']
</code></pre>
<p>I'm trying to get ahead of the others, even cropping the last one, getting like this:</p>
<pre><code>['Hello, 'Love', 'Hi', Nice']
</code></pre>
<p>Note that Hi passed one along with the entire list, that's what I want!</p>
<p>Anybody know? Thanks in advance!</p>
|
[
{
"answer_id": 74591365,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 1,
"selected": false,
"text": "SQL> with per_person_names_f (name_type, full_name) as\n 2 (select 'Global', 'my English name' from dual union all\n 3 select 'SA' , 'my Arabic name' from dual\n 4 )\n 5 select name_type,\n 6 case when name_type = 'Global' then full_name end as english_name,\n 7 case when name_type = 'SA' then full_name end as arabic_name\n 8 from per_person_names_f;\n\nNAME_T ENGLISH_NAME ARABIC_NAME\n------ --------------- ---------------\nGlobal my English name\nSA my Arabic name\n\nSQL>\n"
},
{
"answer_id": 74591469,
"author": "Sergey",
"author_id": 14535517,
"author_profile": "https://Stackoverflow.com/users/14535517",
"pm_score": 0,
"selected": false,
"text": "WITH PERSON_NAMES_F(FULL_NAME,NAME_TYPE) AS\n(\n SELECT 'ABDUL','SA' FROM DUAL UNION ALL\n SELECT 'JONNY','GLOBAL' FROM DUAL\n)\nSELECT \n CASE \n WHEN P.NAME_TYPE='SA' THEN P.FULL_NAME\n ELSE NULL\n END ARABIC_NAME,\n CASE\n WHEN P.NAME_TYPE='GLOBAL' THEN P.FULL_NAME\n ELSE NULL\nEND INTERNATIONAL_NAME\nFROM PERSON_NAMES_F P\n"
},
{
"answer_id": 74591610,
"author": "Alex Poole",
"author_id": 266304,
"author_profile": "https://Stackoverflow.com/users/266304",
"pm_score": 0,
"selected": false,
"text": "GLOBAL 'Global' 'GLOBAL' person_id person_id SELECT\n person_id,\n MAX(CASE name_type\n WHEN 'GLOBAL' THEN full_name \n END) AS \"english name\",\n MAX(CASE name_type\n WHEN 'SA' THEN full_name \n END) AS \"arabic name\"\nFROM \n per_person_names_f\nGROUP BY\n person_id\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20046377/"
] |
74,591,327
|
<p>I need some help with the current VBA code I am using.</p>
<p>The aim is first to count the .xlsx files in a folder and state the number in a defined cell, then in a table below on the same sheet, it lists files from selected folders....
Counting the files is fine but when listing .xlsx files from a selected folder it lists all the files regardless of the type...</p>
<p>This is currently the code I'm using, wanted to see if there is a way to list .xlsx files only?</p>
<p>Sub Outstanding39()</p>
<pre><code>'Count files from selected folder
Dim folder_path As String
Dim strtype As String
Dim totalfiles As Variant
strtype = "*.xlsx*"
folder_path = Worksheets("Data2").Cells(83, 2).Value
If Right(folder_path, 1) <> "\" Then folder_path = folder_path & "\"
totalfiles = Dir(folder_path & strtype)
Dim i As Integer
While (totalfiles <> "")
i = i + 1
totalfiles = Dir
Wend
Worksheets("Open").Cells(15, 7).Value = i
Worksheets("Open").Cells(15, 7).Select
'List Files from selected folder
Dim objFSO As Scripting.FileSystemObject
Dim objFile As Scripting.File
Dim objFolder As Scripting.Folder
Dim nextRow As Long
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(Worksheets("Data2").Cells(83, 2).Value)
nextRow = Cells(Rows.Count, 2).End(xlUp).Row + 1
For Each objFile In objFolder.Files
Cells(nextRow, 2) = objFile.Name
Cells(nextRow, 16) = objFile.ParentFolder
nextRow = nextRow + 1
Next
</code></pre>
<p>End Sub</p>
<p>I am hoping someone is able to assist with doing this...</p>
|
[
{
"answer_id": 74591365,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 1,
"selected": false,
"text": "SQL> with per_person_names_f (name_type, full_name) as\n 2 (select 'Global', 'my English name' from dual union all\n 3 select 'SA' , 'my Arabic name' from dual\n 4 )\n 5 select name_type,\n 6 case when name_type = 'Global' then full_name end as english_name,\n 7 case when name_type = 'SA' then full_name end as arabic_name\n 8 from per_person_names_f;\n\nNAME_T ENGLISH_NAME ARABIC_NAME\n------ --------------- ---------------\nGlobal my English name\nSA my Arabic name\n\nSQL>\n"
},
{
"answer_id": 74591469,
"author": "Sergey",
"author_id": 14535517,
"author_profile": "https://Stackoverflow.com/users/14535517",
"pm_score": 0,
"selected": false,
"text": "WITH PERSON_NAMES_F(FULL_NAME,NAME_TYPE) AS\n(\n SELECT 'ABDUL','SA' FROM DUAL UNION ALL\n SELECT 'JONNY','GLOBAL' FROM DUAL\n)\nSELECT \n CASE \n WHEN P.NAME_TYPE='SA' THEN P.FULL_NAME\n ELSE NULL\n END ARABIC_NAME,\n CASE\n WHEN P.NAME_TYPE='GLOBAL' THEN P.FULL_NAME\n ELSE NULL\nEND INTERNATIONAL_NAME\nFROM PERSON_NAMES_F P\n"
},
{
"answer_id": 74591610,
"author": "Alex Poole",
"author_id": 266304,
"author_profile": "https://Stackoverflow.com/users/266304",
"pm_score": 0,
"selected": false,
"text": "GLOBAL 'Global' 'GLOBAL' person_id person_id SELECT\n person_id,\n MAX(CASE name_type\n WHEN 'GLOBAL' THEN full_name \n END) AS \"english name\",\n MAX(CASE name_type\n WHEN 'SA' THEN full_name \n END) AS \"arabic name\"\nFROM \n per_person_names_f\nGROUP BY\n person_id\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20162249/"
] |
74,591,331
|
<p>I have the following code snippet as a Python script. I get the proper job output files with no errors. However the <code>stdout</code> <code>subprocess</code> log files (i.e. <code>COSMOSIS_output_XXX.txt</code> etc) don't store the expected runtime logs. Instead, these files have <code><_io.TextIOWrapper name=9 encoding='UTF-8'></code> as the only output written in the files. What is it I am doing wrong?</p>
<pre><code>import subprocess
from subprocess import Popen
jobname = "cosmosis"
arg2 = "output.filename="
Vector = (
" " + ini + " " + arg2 + COSMOSIS_PATH + os.path.splitext(ini)[0] + ".txt"
)
job3 = subprocess.Popen(
["cosmosis" + Vector],
shell=True,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
file = open("%sCOSMOSIS_output_%s.txt" % (ERROR_PATH, ini), "a")
sys.stdout = file
print(job3.stdout)
file_e = open("%sCOSMOSIS_output_ERROR_%s.txt" % (ERROR_PATH, ini), "a")
sys.stdout = file_e
print(job3.stderr)
try:
outs, errs = job3.communicate(timeout=2000)
except TimeoutExpired:
outs, errs = job3.communicate()
job3.kill()
file.close()
file_e.close()
</code></pre>
|
[
{
"answer_id": 74592271,
"author": "Aru",
"author_id": 12216053,
"author_profile": "https://Stackoverflow.com/users/12216053",
"pm_score": 1,
"selected": false,
"text": "<_io.TextIOWrapper name=9 encoding='UTF-8'> file = open(\"testtextf.txt\",\"a\")\nprint(file)\n .read() data = file.read()\n"
},
{
"answer_id": 74596869,
"author": "Ayan Mitra",
"author_id": 4792565,
"author_profile": "https://Stackoverflow.com/users/4792565",
"pm_score": -1,
"selected": false,
"text": "with open(\"%sCOSMOSIS_output_%s.txt\" % (ERROR_PATH, ini), \"wb\") as file, open(\"%sCOSMOSIS_output_ERROR_%s.txt\" % (ERROR_PATH, ini), \"wb\") as file_e:\n job3 = subprocess.Popen(\n [\"cosmosis\" + Vector],\n shell=True,\n text=True,\n stdout=file,\n stderr=file_e,\n )\n"
},
{
"answer_id": 74597263,
"author": "tripleee",
"author_id": 874188,
"author_profile": "https://Stackoverflow.com/users/874188",
"pm_score": 2,
"selected": true,
"text": "shell=True with open(\"%sCOSMOSIS_output_%s.txt\" % (ERROR_PATH, ini), \"ab\") as file,\n open(\"%sCOSMOSIS_output_ERROR_%s.txt\" % (ERROR_PATH, ini), \"a\") as file_e:\n try:\n job3 = subprocess.run(\n [\"cosmosis\", ini, arg2, COSMOSIS_PATH, os.path.splitext(ini)[0] + \".txt\"],\n stdout=file, stderr=file_e, check=True,\n timeout=2000)\n except TimeoutExpired:\n pass\n job3.stdout job3.stderr subprocess subprocess.run Popen shell=True Popen with open(\"%sCOSMOSIS_output_%s.txt\" % (ERROR_PATH, ini), \"ab\") as file,\n open(\"%sCOSMOSIS_output_ERROR_%s.txt\" % (ERROR_PATH, ini), \"a\") as file_e:\n job3 = subprocess.Popen(\n [\"cosmosis\", ini, arg2, COSMOSIS_PATH, os.path.splitext(ini)[0] + \".txt\"],\n stdout=file, stderr=file_e)\n...\n# time passes and your script does other things ...\njob3.wait()\n poll"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4792565/"
] |
74,591,347
|
<p>Basically I don't want a user to input the following: (!@#$%^&*()_+[]{}';:".<>?)
given that this is my code:</p>
<pre><code><div class = "form-item">
<label for = "Name">Name: </label>
<input type = "text" id = "Name" name="Cname">
</div>
</code></pre>
<p>how do i do this? hopefully you can do it using the code given</p>
<p>We tried the regex on JavaScript but to be honest i don't understand it.</p>
|
[
{
"answer_id": 74591516,
"author": "DCR",
"author_id": 4398966,
"author_profile": "https://Stackoverflow.com/users/4398966",
"pm_score": -1,
"selected": true,
"text": "var sc = \"(!@#$%^&*()_+[]{}';:\\\".<>?)\"\n\n\nfunction test() {\n\n let input = document.getElementById('Name').value\n let last = input.substring(input.length - 1, input.length)\n \n for (i = 0; i < sc.length; i++) {\n if (last == sc.substring(i, i + 1)) document.getElementById('Name').value = input.substring(0, input.length - 1)\n }\n\n\n\n} <div class=\"form-item\">\n <label for=\"Name\">Name: </label>\n <input type=\"text\" id=\"Name\" name=\"Cname\" oninput=\"test()\">\n</div>"
},
{
"answer_id": 74591556,
"author": "Yato",
"author_id": 11946373,
"author_profile": "https://Stackoverflow.com/users/11946373",
"pm_score": -1,
"selected": false,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Document</title>\n <style>\n input {\n width: 250px;\n padding: 4px 10px;\n font-size: 16px;\n }\n </style>\n</head>\n\n<body>\n <input type=\"text\" placeholder=\"type\" />\n <script>\n // This will prevent special character and allow only a-z A-Z 0-9 and space\n document.querySelector('input').addEventListener('keypress', function (e) {\n // [^a-zA-Z0-9 ] means anything except a-z A-Z 0-9 and space\n var regex = new RegExp(\"^[a-zA-Z0-9 ]+$\");\n // if keypress is not a-z A-Z 0-9 and space then prevent it\n var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);\n if (regex.test(str)) {\n return true;\n }\n e.preventDefault();\n return false;\n });\n </script>\n</body>\n\n</html>"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20615559/"
] |
74,591,394
|
<p>Let's explain my problem..
suppose have a json object like</p>
<p><a href="https://i.stack.imgur.com/USIHw.png" rel="nofollow noreferrer">from this picture i want to handle offer_price key</a>
<a href="https://i.stack.imgur.com/wz0rM.png" rel="nofollow noreferrer">enter image description here</a></p>
<pre><code> {
"product": [
{
"id": 1,
"price": 100.0,
"offer_price": 40
},
{
"id": 2,
"price": 80.0,
"offer_price": 10.50
},
{
"id": 3,
"price": 200.0,
"offer_price": "40.5"
},
{
"id": 4,
"price": 100.0,
"offer_price": null,
}
]
}
</code></pre>
|
[
{
"answer_id": 74591516,
"author": "DCR",
"author_id": 4398966,
"author_profile": "https://Stackoverflow.com/users/4398966",
"pm_score": -1,
"selected": true,
"text": "var sc = \"(!@#$%^&*()_+[]{}';:\\\".<>?)\"\n\n\nfunction test() {\n\n let input = document.getElementById('Name').value\n let last = input.substring(input.length - 1, input.length)\n \n for (i = 0; i < sc.length; i++) {\n if (last == sc.substring(i, i + 1)) document.getElementById('Name').value = input.substring(0, input.length - 1)\n }\n\n\n\n} <div class=\"form-item\">\n <label for=\"Name\">Name: </label>\n <input type=\"text\" id=\"Name\" name=\"Cname\" oninput=\"test()\">\n</div>"
},
{
"answer_id": 74591556,
"author": "Yato",
"author_id": 11946373,
"author_profile": "https://Stackoverflow.com/users/11946373",
"pm_score": -1,
"selected": false,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Document</title>\n <style>\n input {\n width: 250px;\n padding: 4px 10px;\n font-size: 16px;\n }\n </style>\n</head>\n\n<body>\n <input type=\"text\" placeholder=\"type\" />\n <script>\n // This will prevent special character and allow only a-z A-Z 0-9 and space\n document.querySelector('input').addEventListener('keypress', function (e) {\n // [^a-zA-Z0-9 ] means anything except a-z A-Z 0-9 and space\n var regex = new RegExp(\"^[a-zA-Z0-9 ]+$\");\n // if keypress is not a-z A-Z 0-9 and space then prevent it\n var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);\n if (regex.test(str)) {\n return true;\n }\n e.preventDefault();\n return false;\n });\n </script>\n</body>\n\n</html>"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20497216/"
] |
74,591,396
|
<p>I wish to call the parent function (without super) instead of the inherited child function. What options do I have without using ES classes?</p>
<pre><code> function Queue() {
this.items = [];
this.enqueue = function enqueue(item) {
this.items.push(item);
return item;
}
}
function AsyncQueue() {
Queue.call(this);
this.awaiters = new Queue();
this.enqueue = function enqueue(item) {
const awaiter = this.awaiters.dequeue();
if (awaiter !== undefined) {
setImmediate(() => {
awaiter(item);
});
} else {
super.enqueue(item);
}
return item;
}
}
AsyncQueue.prototype = Object.create(Queue.prototype);
AsyncQueue.prototype.constructor = AsyncQueue;
</code></pre>
|
[
{
"answer_id": 74591516,
"author": "DCR",
"author_id": 4398966,
"author_profile": "https://Stackoverflow.com/users/4398966",
"pm_score": -1,
"selected": true,
"text": "var sc = \"(!@#$%^&*()_+[]{}';:\\\".<>?)\"\n\n\nfunction test() {\n\n let input = document.getElementById('Name').value\n let last = input.substring(input.length - 1, input.length)\n \n for (i = 0; i < sc.length; i++) {\n if (last == sc.substring(i, i + 1)) document.getElementById('Name').value = input.substring(0, input.length - 1)\n }\n\n\n\n} <div class=\"form-item\">\n <label for=\"Name\">Name: </label>\n <input type=\"text\" id=\"Name\" name=\"Cname\" oninput=\"test()\">\n</div>"
},
{
"answer_id": 74591556,
"author": "Yato",
"author_id": 11946373,
"author_profile": "https://Stackoverflow.com/users/11946373",
"pm_score": -1,
"selected": false,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Document</title>\n <style>\n input {\n width: 250px;\n padding: 4px 10px;\n font-size: 16px;\n }\n </style>\n</head>\n\n<body>\n <input type=\"text\" placeholder=\"type\" />\n <script>\n // This will prevent special character and allow only a-z A-Z 0-9 and space\n document.querySelector('input').addEventListener('keypress', function (e) {\n // [^a-zA-Z0-9 ] means anything except a-z A-Z 0-9 and space\n var regex = new RegExp(\"^[a-zA-Z0-9 ]+$\");\n // if keypress is not a-z A-Z 0-9 and space then prevent it\n var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);\n if (regex.test(str)) {\n return true;\n }\n e.preventDefault();\n return false;\n });\n </script>\n</body>\n\n</html>"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3204942/"
] |
74,591,397
|
<p>I want to compare lst2 with lst and set zero for value who is not exist</p>
<pre><code>lst = ['IDP','Remote.CMD.Shell','log4j']
lst2 = ['IDP']
</code></pre>
<p>I want output like this in for example loop</p>
<pre><code>{
IDP:1,
Remote.CMD.Shell:0,
log4j:0
}
{
IDP:0,
Remote.CMD.Shell:0,
log4j:0
}
{
IDP:0,
Remote.CMD.Shell:0,
log4j:0
}
</code></pre>
<p>I would be glad if anyone can help me</p>
|
[
{
"answer_id": 74591516,
"author": "DCR",
"author_id": 4398966,
"author_profile": "https://Stackoverflow.com/users/4398966",
"pm_score": -1,
"selected": true,
"text": "var sc = \"(!@#$%^&*()_+[]{}';:\\\".<>?)\"\n\n\nfunction test() {\n\n let input = document.getElementById('Name').value\n let last = input.substring(input.length - 1, input.length)\n \n for (i = 0; i < sc.length; i++) {\n if (last == sc.substring(i, i + 1)) document.getElementById('Name').value = input.substring(0, input.length - 1)\n }\n\n\n\n} <div class=\"form-item\">\n <label for=\"Name\">Name: </label>\n <input type=\"text\" id=\"Name\" name=\"Cname\" oninput=\"test()\">\n</div>"
},
{
"answer_id": 74591556,
"author": "Yato",
"author_id": 11946373,
"author_profile": "https://Stackoverflow.com/users/11946373",
"pm_score": -1,
"selected": false,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Document</title>\n <style>\n input {\n width: 250px;\n padding: 4px 10px;\n font-size: 16px;\n }\n </style>\n</head>\n\n<body>\n <input type=\"text\" placeholder=\"type\" />\n <script>\n // This will prevent special character and allow only a-z A-Z 0-9 and space\n document.querySelector('input').addEventListener('keypress', function (e) {\n // [^a-zA-Z0-9 ] means anything except a-z A-Z 0-9 and space\n var regex = new RegExp(\"^[a-zA-Z0-9 ]+$\");\n // if keypress is not a-z A-Z 0-9 and space then prevent it\n var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);\n if (regex.test(str)) {\n return true;\n }\n e.preventDefault();\n return false;\n });\n </script>\n</body>\n\n</html>"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18466173/"
] |
74,591,413
|
<p>I want to play text to speech but I can't hear anything using Xamarin.essential. I 'm sure I don't have muted smartphone. The code:</p>
<pre><code> using Xamarin.Essential
private void PlayTextMethod()
{
if(do sth)
{
SpeekFrommethodAsync();
}
}
private async SpeekFrommethodAsync()
{
await TextToSpeech.SpeakAsync(Tasklabel.Text, new SpeechOptions
{
Volume = 1f
});
}
</code></pre>
|
[
{
"answer_id": 74591516,
"author": "DCR",
"author_id": 4398966,
"author_profile": "https://Stackoverflow.com/users/4398966",
"pm_score": -1,
"selected": true,
"text": "var sc = \"(!@#$%^&*()_+[]{}';:\\\".<>?)\"\n\n\nfunction test() {\n\n let input = document.getElementById('Name').value\n let last = input.substring(input.length - 1, input.length)\n \n for (i = 0; i < sc.length; i++) {\n if (last == sc.substring(i, i + 1)) document.getElementById('Name').value = input.substring(0, input.length - 1)\n }\n\n\n\n} <div class=\"form-item\">\n <label for=\"Name\">Name: </label>\n <input type=\"text\" id=\"Name\" name=\"Cname\" oninput=\"test()\">\n</div>"
},
{
"answer_id": 74591556,
"author": "Yato",
"author_id": 11946373,
"author_profile": "https://Stackoverflow.com/users/11946373",
"pm_score": -1,
"selected": false,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Document</title>\n <style>\n input {\n width: 250px;\n padding: 4px 10px;\n font-size: 16px;\n }\n </style>\n</head>\n\n<body>\n <input type=\"text\" placeholder=\"type\" />\n <script>\n // This will prevent special character and allow only a-z A-Z 0-9 and space\n document.querySelector('input').addEventListener('keypress', function (e) {\n // [^a-zA-Z0-9 ] means anything except a-z A-Z 0-9 and space\n var regex = new RegExp(\"^[a-zA-Z0-9 ]+$\");\n // if keypress is not a-z A-Z 0-9 and space then prevent it\n var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);\n if (regex.test(str)) {\n return true;\n }\n e.preventDefault();\n return false;\n });\n </script>\n</body>\n\n</html>"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20585999/"
] |
74,591,436
|
<p>im trying to make the divs that have the h1 elements as shown in the picture provided below to move away from each other and not be this close to each other but i cant seem to do so i dont know if adding a width to each does anything. i tried adding margin and padding aswell but it moves the whole page instead of each div indivdually</p>
<p>here is the main section in the html file</p>
<pre><code><main>
<div class="who">
<h1>Who We Are</h1>
</div>
<div class="what">
<h1>What We Do</h1>
</div>
<div class="where">
<h1>Where We Work</h1>
</div>
</main>
</code></pre>
<p>and here is the css file</p>
<pre><code>
*{
padding:0;
margin: 0;
box-sizing: border-box;
}
body{
font-family: 'Calibri';
color: #222;
padding-bottom: 50px;
}
header{
height:100px;
display:flex;
justify-content: space-around;
align-items: center;
}
ul{
display:flex;
list-style-type:none;
align-items: center;
justify-content: center;
}
ul li a{
color: rgb(0,0,0);
text-decoration: none;
padding:7px 15px;
transition: all 0.3s ease-in-out;
font-size: 17px;
font-weight: 600;
letter-spacing: 1px;
text-transform: uppercase;
display:inline-block;
}
li a::after{
content:'';
display:block;
height:4px;
width:0;
background: #FCAE1E;
}
li a:hover::after{
width:100%;
}
main{
display: flex;
height:calc(100vh - 100px);
align-items: center;
justify-content: center;
}
.who{
width: 30%;
}
.what{
width: 30%;
}
.where{
width: 30%;
}
</code></pre>
<p><a href="https://i.stack.imgur.com/VnnV0.png" rel="nofollow noreferrer">here is the image</a></p>
|
[
{
"answer_id": 74591531,
"author": "Hammad Muhammad",
"author_id": 20615635,
"author_profile": "https://Stackoverflow.com/users/20615635",
"pm_score": -1,
"selected": false,
"text": "h1 {\n margin: 30px 0px 30px 0px;\n}\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16758122/"
] |
74,591,439
|
<p>I have a pandas dataframe that I want to randomly pick samples from it. The first time I want to pick 10, then 20, 30, 40, and 50 random samples (without replacment).
I'm trying to do it with a for loop, altough I don't know how good this is cause a list can't contain data frames, right? (my coding is better with R and there the lists can contain dataframes).</p>
<pre><code>number = [10,20,30,40,50]
sample = []
for i in range(len(number)):
sample[i].append(data.sample(n = number[i]))
</code></pre>
<p>And the error is <code>IndexError: list index out of range</code></p>
<p>I dont want to copy past the code so what is the right way to do it?</p>
|
[
{
"answer_id": 74591531,
"author": "Hammad Muhammad",
"author_id": 20615635,
"author_profile": "https://Stackoverflow.com/users/20615635",
"pm_score": -1,
"selected": false,
"text": "h1 {\n margin: 30px 0px 30px 0px;\n}\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17945841/"
] |
74,591,451
|
<p>i have a problem with the info div overflowing it parent container but not it content ,some other component are also overflowing but it's not a problem and a margins problem some are just there and the others won't appear at all this is happening in width under 375px
plus if any one has an idea why the font awesome icon appears as a square i couldn't find a solution</p>
<p>update</p>
<p>the overflow problem has been solved but i still have a problem with the extra margin of the html on the right and the lack of for the container</p>
<p>`</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<title>Document</title>
</head>
<body>
<div class="container">
<img src="images/image-product-desktop.jpg" alt="">
<div class="info">
<span class="type">Perfume</span>
<h1 class="title">Gabrielle Essence Eau De Parfume</h1>
<p>A floral, solar and voluptuous interpretation composed by Oliver Polge, Perfumer-Creator for the House of CHANEL.</p>
<div class="prices">
<span class="newprice">$149.99</span>
<span class="oldprice">$169.99</span>
</div>
<button><i class="fa-regular fa-cart-shopping"></i> Add To Cart</button>
</div>
</div>
</body>
</html>
</code></pre>
<p>`</p>
<p>`</p>
<pre><code>@import url('https://fonts.googleapis.com/css2?family=Fraunces:opsz,wght@9..144,700&family=Montserrat:wght@500;700&display=swap');
*{
margin: 0;
padding: 0;
font-family: 'Montserrat', sans-serif;
color: hsl(228, 12%, 48%);
}
html{
margin: 0;
}
body{
background-color: hsl(30, 38%, 92%);
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
width: 100vw;
}
.container{
max-width: 37rem;
max-height: 45rem;
display: flex;
background-color: #fff;
border-top-right-radius: .5rem;
border-bottom-right-radius: .5rem;
}
img{
max-width: 18.5rem;
max-height: 45rem;
border-top-left-radius: .5rem;
border-bottom-left-radius: .5rem;
}
.title{
font-family: 'Fraunces', serif;
color: black;
margin: .8rem auto 1rem;
}
.info{
padding: 1.9rem;
}
p{
font-size: 14px;
line-height: 1.3rem;
}
.prices{
margin: 1.5rem auto 1.3rem;
display: flex;
align-items: center;
}
.newprice{
font-family: 'Fraunces', serif;
font-weight: 700;
color: #658354;
font-size: 2rem;
}
.oldprice{
text-decoration:line-through;
font-size: .7rem;
margin: 1rem;
}
button{
color: #fff;
background-color: #658354;
width: 100%;
padding: 1.5rem 1rem;
font-size: .8rem;
border: none;
padding: .7rem;
border-radius: .5rem;
cursor: pointer;
}
button:active{
background-color: #2f4125;
}
@media(max-width : 375px){
*{
margin: 1rem;
}
img{
width: 100%;
height: 40%;
border-radius: .5rem;
}
.container{
display: block;
}
.info{
margin-bottom: 1rem;
padding: 0;
height: 100%;
}
}
</code></pre>
<p>`</p>
|
[
{
"answer_id": 74591531,
"author": "Hammad Muhammad",
"author_id": 20615635,
"author_profile": "https://Stackoverflow.com/users/20615635",
"pm_score": -1,
"selected": false,
"text": "h1 {\n margin: 30px 0px 30px 0px;\n}\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20027944/"
] |
74,591,455
|
<p>I want to create an array of pointers to methods, so I can quickly select a method to call, based on a integer. But I am struggling a little with the syntax.</p>
<p>What I have now is this:</p>
<pre><code>class Foo {
private:
void method1();
void method2();
void method3();
void(Foo::*display_functions[3])() = {
Foo::method1,
Foo::method2,
Foo::method3
};
};
</code></pre>
<p>But I get the following error message:</p>
<pre><code>[bf@localhost method]$ make test
g++ test.cpp -o test
test.cpp:11:9: error: cannot convert ‘Foo::method1’ from type ‘void (Foo::)()’ to type ‘void (Foo::*)()’
11 | };
| ^
test.cpp:11:9: error: cannot convert ‘Foo::method2’ from type ‘void (Foo::)()’ to type ‘void (Foo::*)()’
test.cpp:11:9: error: cannot convert ‘Foo::method3’ from type ‘void (Foo::)()’ to type ‘void (Foo::*)()’
make: *** [<builtin>: test] Error 1
</code></pre>
|
[
{
"answer_id": 74591486,
"author": "lorro",
"author_id": 6292621,
"author_profile": "https://Stackoverflow.com/users/6292621",
"pm_score": 4,
"selected": true,
"text": " void(Foo::*display_functions[3])() = {\n &Foo::method1,\n &Foo::method2,\n &Foo::method3\n };\n virtual"
},
{
"answer_id": 74591512,
"author": "wohlstad",
"author_id": 18519921,
"author_profile": "https://Stackoverflow.com/users/18519921",
"pm_score": 1,
"selected": false,
"text": "typedef std::array class Foo {\nprivate:\n void method1() {};\n void method2() {};\n void method3() {};\n\n typedef void (Foo::* FooMemFn)();\n\n std::array<FooMemFn,3> display_functions = {\n &Foo::method1,\n &Foo::method2,\n &Foo::method3\n };\n};\n typedef using using FooMemFn = void (Foo::*)();\n operator& display_functions"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1145666/"
] |
74,591,465
|
<p>Let's say I have theese words in a text file</p>
<h1>Dictionary.txt</h1>
<pre><code>artificial
intelligence
abbreviation
hybrid
hysteresis
illuminance
identity
inaccuracy
impedance
impenetrable
imperfection
impossible
independent
</code></pre>
<p>How can I make each word a different object and print them on the console?</p>
|
[
{
"answer_id": 74591486,
"author": "lorro",
"author_id": 6292621,
"author_profile": "https://Stackoverflow.com/users/6292621",
"pm_score": 4,
"selected": true,
"text": " void(Foo::*display_functions[3])() = {\n &Foo::method1,\n &Foo::method2,\n &Foo::method3\n };\n virtual"
},
{
"answer_id": 74591512,
"author": "wohlstad",
"author_id": 18519921,
"author_profile": "https://Stackoverflow.com/users/18519921",
"pm_score": 1,
"selected": false,
"text": "typedef std::array class Foo {\nprivate:\n void method1() {};\n void method2() {};\n void method3() {};\n\n typedef void (Foo::* FooMemFn)();\n\n std::array<FooMemFn,3> display_functions = {\n &Foo::method1,\n &Foo::method2,\n &Foo::method3\n };\n};\n typedef using using FooMemFn = void (Foo::*)();\n operator& display_functions"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20615580/"
] |
74,591,497
|
<p>I have made a tiny client/server app, but I was wondering if the default value of the field <strong>s_addr</strong> was <strong>INADDR_ANY</strong> or not as when I don't specify an address for the socket, for both the client and the server, it works the same as with this flag given in the structure. I haven't find anything on the doc about that</p>
<pre><code>struct sockaddr_in {
short sin_family;
unsigned short sin_port;
struct in_addr sin_addr;
};
</code></pre>
<pre><code>struct in_addr {
unsigned long s_addr;
};
</code></pre>
|
[
{
"answer_id": 74591486,
"author": "lorro",
"author_id": 6292621,
"author_profile": "https://Stackoverflow.com/users/6292621",
"pm_score": 4,
"selected": true,
"text": " void(Foo::*display_functions[3])() = {\n &Foo::method1,\n &Foo::method2,\n &Foo::method3\n };\n virtual"
},
{
"answer_id": 74591512,
"author": "wohlstad",
"author_id": 18519921,
"author_profile": "https://Stackoverflow.com/users/18519921",
"pm_score": 1,
"selected": false,
"text": "typedef std::array class Foo {\nprivate:\n void method1() {};\n void method2() {};\n void method3() {};\n\n typedef void (Foo::* FooMemFn)();\n\n std::array<FooMemFn,3> display_functions = {\n &Foo::method1,\n &Foo::method2,\n &Foo::method3\n };\n};\n typedef using using FooMemFn = void (Foo::*)();\n operator& display_functions"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19176243/"
] |
74,591,555
|
<p>How to compare only the values of two dictonaries?</p>
<p>So I have this:</p>
<pre><code>dict1 = {"appe": 3962.00, "waspeen": 3304.08}
dic2 = {"appel": 3962.00, "waspeen": 3304.08}
def compare_value_dict(dic):
return dic
def compare_value_dict2(dic2):
return dic2
def compare_dic(dic1, dic2):
if dic1 == dic2:
print('the same dictionary')
else:
print('difference dictionary')
compare_dic(compare_value_dict(dict1).values(), compare_value_dict2(dic2.values()))
</code></pre>
<p>but I get the print statement:</p>
<pre><code> print('difference dictionary')
</code></pre>
<p>But the values are the same. And can this be shorter with list comprohension?</p>
<p>this works:</p>
<pre><code>compare_dic(compare_value_dict(dict1).keys(), compare_value_dict2(dic2.keys()))
</code></pre>
<p>if I change only the key then it outputs the difference.</p>
<p>But with values. it doesn't work. if the values are the same, but the keys are different, that it returns difference. But it has to be of course not difference</p>
|
[
{
"answer_id": 74591629,
"author": "Martijn Pieters",
"author_id": 100297,
"author_profile": "https://Stackoverflow.com/users/100297",
"pm_score": 3,
"selected": false,
"text": "== dict.values() values_view_foo == values_view_bar def compare_dict_values(dv1, dv2):\n \"\"\"Compare two dictionary values views\n\n Values are assumed to be unique and hashable\n\n \"\"\"\n return set(dv1) == set(dv2)\n def compare_dict_values(dv1, dv2):\n \"\"\"Compare two dictionary value views\n\n Values are assumed to be orderable, but do not need to be unique\n or hashable.\n\n \"\"\"\n return len(dv1) == len(dv2) and sorted(dv1) == sorted(dv2)\n len() ('foo', 'bar', 'foo') ('foo', 'bar', 'bar') Counter() from collections import Counter\n\ndef compare_dict_values(dv1, dv2):\n \"\"\"Compare two dictionary value views\n\n Values are assumed to be hashable, but do not need to be unique.\n\n \"\"\"\n return Counter(dv1) == Counter(dv2)\n math.isclose() zip(sorted(dv1), sorted(dv2)) def float_dict_values_close(dv1, dv2, **kwargs):\n \"\"\"Compare two dictionary view objects with floats\n\n Returns true if the values in both dictionary views are\n *close* in value.\n\n \"\"\"\n if len(dv1) != len(dv2):\n return False\n v1, v2 = sorted(dv1), sorted(dv2)\n return all(is_close(*vs, **kwargs) for vs in zip(v1, v2))\n"
},
{
"answer_id": 74592010,
"author": "Alibederchi ",
"author_id": 20598580,
"author_profile": "https://Stackoverflow.com/users/20598580",
"pm_score": 0,
"selected": false,
"text": "dict1 = {\"appe\": 3962.00, \"waspeen\": 3304.08}\ndic2 = {\"appel\": 3304.08, \"waspeen\": 3962.00}\ndef comparision(*dicts):\n instanceToCompare , values = len(dicts[0].values()) , set()\n for d in dicts:\n for value in d.values():\n values.add(value)\n return True if len(values) == instanceToCompare else False\nprint('all dictionaries has same values') if comparision(dict1 , dic2) else \nprint('input dictionaries are not same at all')\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7713770/"
] |
74,591,592
|
<p>I have several js objects, obj1{}, obj2{}...</p>
<p>My code is taking values from a js obj{}</p>
<p>This obj has to change when user click at on different elements of document which have a dataset with the name of corresponding object.</p>
<p>Example:</p>
<pre><code><button data-itemname="obj1>item 1</button>
<button data-itemname="obj2>item 2</button>
</code></pre>
<p>Following user click, I have obj1, obj2 as string variable.</p>
<p>How to retrieve the object obj1{} from this string obj1</p>
<p>I tried several syntax, but not working.</p>
<p>Actually, all values coming from an object obj{}. If can change obj{} to obj1{}, obj2{}... that would be the best.</p>
<p>I can also restructure my code. Or put everything in 1 obj: obj = { obj1:{} , obj2{}, ...}
thanks</p>
|
[
{
"answer_id": 74591699,
"author": "innocent",
"author_id": 8405085,
"author_profile": "https://Stackoverflow.com/users/8405085",
"pm_score": 0,
"selected": false,
"text": "event.target.dataset const item1 = document.querySelector(\"#btn1\");\nconst item2 = document.querySelector(\"#btn2\");\n\nconst data = {\n object1: {\n a: 1,\n b: 2\n },\n object2: {\n a: 3,\n b: 4\n },\n}\n\nconst handleBtnClick = (e) => {\n const targetElemName = e.target.dataset[\"itemname\"];\n console.log(`access the ${targetElemName} val:`, data[targetElemName]);\n};\n\nitem1.addEventListener('click', handleBtnClick);\nitem2.addEventListener('click', handleBtnClick); <button id=\"btn1\" data-itemname=\"object1\">item 1</button>\n<button id=\"btn2\" data-itemname=\"object2\">item 2</button>"
},
{
"answer_id": 74591752,
"author": "StefanBD",
"author_id": 4814628,
"author_profile": "https://Stackoverflow.com/users/4814628",
"pm_score": 1,
"selected": false,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Parcel Sandbox</title>\n <meta charset=\"UTF-8\" />\n </head>\n\n <body>\n <div id=\"app\"></div>\n <button data-itemname=\"obj1\">item 1</button>\n <button data-itemname=\"obj2\">item 2</button>\n\n <script>\n let all = { obj1: \"hello 1\", obj2: \"hello 2\" };\n\n function getObj(sel) {\n return all[sel.dataset.itemname];\n }\n\n (function () {\n var buttons = document.getElementsByTagName(\"button\");\n for (i = 0; i < buttons.length; i++) {\n buttons[i].addEventListener(\"click\", function () {\n console.log(getObj(this));\n });\n }\n })();\n </script>\n </body>\n</html>"
},
{
"answer_id": 74591779,
"author": "Carsten Massmann",
"author_id": 2610061,
"author_profile": "https://Stackoverflow.com/users/2610061",
"pm_score": 1,
"selected": false,
"text": "var obj1={a:123,b:456},obj2={c:789,d:10123};\nconst obj={obj1,obj2};\n\ndocument.body.addEventListener('click',(e)=>{\n if(e.target.tagName==\"BUTTON\")\n console.log(obj[e.target.dataset[\"itemname\"]]);\n}); <button data-itemname=\"obj1\">item 1</button>\n<button data-itemname=\"obj2\">item 2</button> window obj"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19996700/"
] |
74,591,606
|
<p>I am trying to check if in an array of objects I have duplicates <code>date</code>, then I have to concat the duplicate obj with <code>name</code> and remove one of them.</p>
<p>This is what I could do:</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 arr = [
{name: "Adam", date: "25/11/2022" },
{name: "Jorge", date: "25/11/2022" },
{name: "Lucas", date: "24/11/2022" },
{name: "Bob", date: "23/11/2022" }
]
function getUniqueListBy(arr, key) {
return [...new Map(arr.map(item => [item[key], item])).values()]
}
const arr1 = getUniqueListBy(arr, 'date')
console.log(JSON.stringify(arr1))</code></pre>
</div>
</div>
</p>
<p>What I need is this result:</p>
<pre><code>var arr1 = [{"name":"Adam / Jorge","date":"25/11/2022"},{"name":"Lucas","date":"24/11/2022"},{"name":"Bob","date":"23/11/2022"}]
</code></pre>
<p>So the object with duplicated date would be like this:</p>
<pre><code>{"name":"Adam / Jorge","date":"25/11/2022"}
</code></pre>
<p>Any suggestion ?</p>
|
[
{
"answer_id": 74591751,
"author": "Amila Senadheera",
"author_id": 8510405,
"author_profile": "https://Stackoverflow.com/users/8510405",
"pm_score": 3,
"selected": true,
"text": "const arr = [\n { name: \"Adam\", date: \"25/11/2022\" },\n { name: \"Jorge\", date: \"25/11/2022\" },\n { name: \"Lucas\", date: \"24/11/2022\" },\n { name: \"Bob\", date: \"23/11/2022\" },\n];\n\nconst result = Object.entries(\n arr.reduce((prev, { date, name }) => {\n prev[date] = prev[date] ? prev[date] + \" / \" + name : name;\n return prev;\n }, {})\n).map(([date, name]) => ({ name, date }));\n\nconsole.log(result);"
},
{
"answer_id": 74591853,
"author": "Christian Fritz",
"author_id": 1087119,
"author_profile": "https://Stackoverflow.com/users/1087119",
"pm_score": 1,
"selected": false,
"text": "var arr = [\n {name: \"Adam\", date: \"25/11/2022\" },\n {name: \"Jorge\", date: \"25/11/2022\" },\n {name: \"Lucas\", date: \"24/11/2022\" },\n {name: \"Bob\", date: \"23/11/2022\" }\n];\n\nconst grouped = {};\narr.forEach(({name, date}) =>\n (grouped[date] || (grouped[date] = [])).push(name)\n);\n\nconst result = {};\nObject.entries(grouped).forEach(([date, names]) =>\n result[names.join(' / ')] = date\n);\n\nconsole.log(result);"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16900056/"
] |
74,591,646
|
<p>As a beginner in c#, I’ve been making some simple console apps. In one, I have a simple game to solve a computer-generated number code. For each attempt at solving the code, the user enters 5 digits in the form of an input string. The issue is with the error checking, and I’ve put together a simple section of code that shows the problem. If I enter 5 digits, say 12345, the code passes through the errorCheck() and is displayed correctly. If instead, I press a random key, say “a”, the error is recognised, and I can enter again. But this time if I enter a valid number, the output will be “a”.</p>
<p>What I am trying to do is reject an invalid input and replace with a valid one that can be passed to the rest of the program.</p>
<p>Why is this code not working the way I expected?</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ErrorCheck
{
internal class Program
{
static void Main(string[] args)
{
string code=enterCode();
errorCheck(code);
Console.WriteLine(code);
Console.ReadLine();
}
private static string enterCode()
{
Console.Write("Please enter code ");
string code = Console.ReadLine();
return code;
}
private static void errorCheck(string code)
{
bool valid = true;
int number;
valid = Int32.TryParse(code, out number);
if (number > 99999) valid = false;
if (number < 0) valid = false;
if (valid == false)
{
Console.WriteLine("You did not enter a valid code");
Console.WriteLine("Press any key to try again");
Console.ReadLine();
enterCode();
}
return;
}
}
}
</code></pre>
|
[
{
"answer_id": 74591814,
"author": "Stijn",
"author_id": 13561091,
"author_profile": "https://Stackoverflow.com/users/13561091",
"pm_score": 3,
"selected": true,
"text": "string code;\ndo\n{\n code = enterCode();\n} while (errorCheck(code) == false) // or !errorCheck(code)\n\n// Should return true or false depending on success\nprivate static bool errorCheck() \n{\n ...\n}\n"
},
{
"answer_id": 74593244,
"author": "Karen Payne",
"author_id": 5509738,
"author_profile": "https://Stackoverflow.com/users/5509738",
"pm_score": 0,
"selected": false,
"text": "int string answer.ToString() internal partial class Program\n{\n static void Main(string[] args)\n {\n int answer = GetNumber();\n Console.WriteLine(answer);\n Console.ReadLine();\n }\n\n private const int Max = 99999;\n public static int GetNumber() =>\n AnsiConsole.Prompt(\n new TextPrompt<int>(\"[white on blue]Enter a number:[/]\")\n .PromptStyle(\"cyan\")\n .ValidationErrorMessage(\"[red]Must be integer[/]\")\n .Validate(value => value switch\n {\n < 0 or > Max => ValidationResult.Error($\"[red]Must be greater than 0 and less than {Max}[/]\"),\n _ => ValidationResult.Success(),\n }));\n}\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20366497/"
] |
74,591,662
|
<p>I am studying binary search trees right now, and I came across this code</p>
<pre><code>void free_tree(Node* root) {
// Deallocates memory corresponding
// to every node in the tree.
Node* temp = root;
if (!temp)
return;
free_tree(temp->left);
free_tree(temp->right);
if (!temp->left && !temp->right) {
free(temp);
return;
}
}
</code></pre>
<p>what does !temp mean in this context? Does it mean <code>if temp == NULL?</code> and does that mean <code>!temp->left</code> or <code>!temp->right</code> mean "if right of temp == NULL"? I'm kind of confused with this code in general.</p>
<p>I tried searching for related questions, but so far got no answers.</p>
|
[
{
"answer_id": 74591846,
"author": "John Bollinger",
"author_id": 2402272,
"author_profile": "https://Stackoverflow.com/users/2402272",
"pm_score": 0,
"selected": false,
"text": "if temp == NULL? Node* temp = root;\n if (!temp)\n return;\n NULL pointer != NULL ! !pointer pointer == NULL !temp->left !temp->right -> ! !x->y !(x->y) temp->left temp->right !temp->left !temp->right temp->left == NULL temp->right == NULL"
},
{
"answer_id": 74591903,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 2,
"selected": false,
"text": "if (!temp)\n if (!temp->left && !temp->right) {\n if ( temp == NULL )\n if ( temp->left == NULL && temp->right == NULL ) {\n left right void free_tree( Node *root ) \n{\n // Deallocates memory corresponding\n // to every node in the tree.\n if ( root != NULL )\n {\n free_tree( root->left );\n free_tree( root->right );\n\n free( root );\n }\n}\n void free_tree( Node **root ) \n{\n // Deallocates memory corresponding\n // to every node in the tree.\n if ( *root != NULL )\n {\n free_tree( &( *root )->left );\n free_tree( &( *root )->right );\n\n free( *root );\n *root = NULL;\n }\n}\n NULL"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14041146/"
] |
74,591,682
|
<p>I am using the below code to make a HTTPS <code>GET</code> request.</p>
<p>I'd like to keep the connection alive to make multiple requests without having to connect each time, so I set <code>"Connection: Keep-Alive\r\n"</code>. However, once I did this, the behaviour changed and the code now blocks on <code>BIO_read()</code> (equivalent to <code>::recv()</code>). Now I cannot return to process the received data.</p>
<p>How can I only connect once, but not block on <code>BIO_read()</code>/<code>::recv()</code>?</p>
|
[
{
"answer_id": 74591846,
"author": "John Bollinger",
"author_id": 2402272,
"author_profile": "https://Stackoverflow.com/users/2402272",
"pm_score": 0,
"selected": false,
"text": "if temp == NULL? Node* temp = root;\n if (!temp)\n return;\n NULL pointer != NULL ! !pointer pointer == NULL !temp->left !temp->right -> ! !x->y !(x->y) temp->left temp->right !temp->left !temp->right temp->left == NULL temp->right == NULL"
},
{
"answer_id": 74591903,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 2,
"selected": false,
"text": "if (!temp)\n if (!temp->left && !temp->right) {\n if ( temp == NULL )\n if ( temp->left == NULL && temp->right == NULL ) {\n left right void free_tree( Node *root ) \n{\n // Deallocates memory corresponding\n // to every node in the tree.\n if ( root != NULL )\n {\n free_tree( root->left );\n free_tree( root->right );\n\n free( root );\n }\n}\n void free_tree( Node **root ) \n{\n // Deallocates memory corresponding\n // to every node in the tree.\n if ( *root != NULL )\n {\n free_tree( &( *root )->left );\n free_tree( &( *root )->right );\n\n free( *root );\n *root = NULL;\n }\n}\n NULL"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1107474/"
] |
74,591,692
|
<p>When I enter <code>yes</code> to repeat the game, then instead of repeating, this message appears:</p>
<blockquote>
<p>do you want to play again (yes or no):</p>
</blockquote>
<p>This only happens when I enter <code>yes</code>. But if I enter <code>no</code>, then it exits from the game.</p>
<h3>Code I have</h3>
<pre><code>print(' Welcome to the gussing game :)')
print("\n\nyou have only 3 attempts to win ")
hidden_word = 'zak'
guess_word = ''
count_attempts = 0
limit_attempts = 3
play_again = 'yes'
while play_again == 'yes':
while (guess_word != hidden_word) and (count_attempts < limit_attempts):
guess_word = input("\nplease enter your word: ")
count_attempts += 1
if count_attempts == limit_attempts and guess_word != hidden_word:
print("Sorry, you lose due to Out of attempts ")
elif guess_word != hidden_word:
print("Wrong attempt, try again ...")
#Remember that {the order of the if statments is imporatnt and can change your result to be the unwanted one }
else:
print(" Wow you won !!")
play_again = input('\ndo you want to play again (yes or no): ').lower()
</code></pre>
<h3>Question</h3>
|
[
{
"answer_id": 74591930,
"author": "wavetitan",
"author_id": 19069334,
"author_profile": "https://Stackoverflow.com/users/19069334",
"pm_score": 2,
"selected": true,
"text": "guess_word count_attempts while (guess_word != hidden_word) and (count_attempts < limit_attempts): while play_again == 'yes':\n guess_word = ''\n count_attempts = 0\n while (guess_word != hidden_word) and (count_attempts < limit_attempts):\n guess_word = input(\"\\nplease enter your word: \")\n count_attempts += 1\n if count_attempts == limit_attempts and guess_word != hidden_word:\n print(\"Sorry, you lose due to Out of attempts \")\n elif guess_word != hidden_word:\n print(\"Wrong attempt, try again ...\")\n #Remember that {the order of the if statments is imporatnt and can change your result to be the unwanted one }\n else:\n print(\" Wow you won !!\")\n play_again = input('\\ndo you want to play again (yes or no): ').lower()\n"
},
{
"answer_id": 74591938,
"author": "nigh_anxiety",
"author_id": 17030540,
"author_profile": "https://Stackoverflow.com/users/17030540",
"pm_score": 0,
"selected": false,
"text": "guess_word count_attempts limit_attempts = 3\nplay_again = 'yes'\n\n\nwhile play_again == 'yes':\n print(' Welcome to the gussing game :)')\n print(\"\\n\\nyou have only 3 attempts to win \")\n\n hidden_word = 'zak'\n guess_word = ''\n count_attempts = 0\n while (guess_word != hidden_word) and (count_attempts < limit_attempts):\n guess_word = input(\"\\nplease enter your word: \")\n count_attempts += 1\n if count_attempts == limit_attempts and guess_word != hidden_word:\n print(\"Sorry, you lose due to Out of attempts \")\n elif guess_word != hidden_word:\n print(\"Wrong attempt, try again ...\")\n #Remember that {the order of the if statments is imporatnt and can change your result to be the unwanted one }\n else:\n print(\" Wow you won !!\")\n play_again = input('\\ndo you want to play again (yes or no): ').lower()\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20615833/"
] |
74,591,697
|
<p>I'm using two constexpr std::array:</p>
<pre><code>constexpr std::array full = { 1,2,3 };
constexpr std::array subset = { 3 };
</code></pre>
<p>I would like to static assert if the second is a subset of the first.</p>
<p>In the above example, the assertion should succeed, and in the following, it supposes to fail:</p>
<pre><code>constexpr std::array full = { 1,2,3 };
constexpr std::array subset = { 3, 4 };
</code></pre>
<p>I wrote a working constexpr function:</p>
<pre><code>constexpr bool isSubset(decltype(full)& a, decltype(subset)& b)
{
for (const auto& subsetElement : b) {
bool found = false;
for (const auto& fullElement : a) {
if (subsetElement == fullElement) {
found = true;
break;
}
}
if (!found) {
return false;
}
}
return true;
}
</code></pre>
<p>But I wondered if there is another, more straightforward (without decltype, maybe without constexpr function?) way of doing it (latest CPP).</p>
|
[
{
"answer_id": 74591749,
"author": "Stack Danny",
"author_id": 6039995,
"author_profile": "https://Stackoverflow.com/users/6039995",
"pm_score": 2,
"selected": false,
"text": "std::ranges::sort std::ranges::includes constexpr bool is_subset(auto a, auto b) {\n std::ranges::sort(a);\n std::ranges::sort(b);\n return std::ranges::includes(a, b);\n}\n\nint main() {\n constexpr std::array full = { 1,3,2 };\n constexpr std::array subset = { 3, 2 };\n\n static_assert(is_subset(full, subset), \"Has to be a subset\");\n}\n\n"
},
{
"answer_id": 74592118,
"author": "Ranoiaetep",
"author_id": 12861639,
"author_profile": "https://Stackoverflow.com/users/12861639",
"pm_score": 1,
"selected": false,
"text": "constexpr bool isSubset(auto sup, auto sub)\n{\n if (sub.size() > sup.size()) return false;\n std::ranges::sort(sup);\n return std::ranges::all_of(sup, \n [&](auto i){ return std::ranges::binary_search(sub, i); }\n );\n}\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1693118/"
] |
74,591,706
|
<p>Hello I have a connect four game who worked before null safety but I try to make the migration, but I have a problem with <code>scores[i] = null;</code> I can't write like that but without it I have a freeze when CPU is certain to loose</p>
<pre><code> int _compute(Board board, int step, int deepness, List<double> scores) {
for (var i = 0; i < 7; ++i) {
final boardCopy = board.clone();
final target = boardCopy.getColumnTarget(i);
if (target == -1) {
scores[i] = null; // <<<---- HERE I CAN'T USE NULL
continue;
}
final coordinate = Coordinate(i, target);
boardCopy.setBox(coordinate, player);
if (boardCopy.checkWinner(coordinate, player)) {
scores[i] += deepness / (step + 1);
continue;
}
for (var j = 0; j < 7; ++j) {
final target = boardCopy.getColumnTarget(j);
if (target == -1) {
continue;
}
final coordinate = Coordinate(j, target);
boardCopy.setBox(coordinate, otherPlayer);
if (boardCopy.checkWinner(coordinate, otherPlayer)) {
scores[i] -= deepness / (step + 1);
continue;
}
if (step + 1 < deepness) {
_compute(board, step + 1, deepness, scores);
}
}
}
return _getBestScoreIndex(scores);
}
int _getBestScoreIndex(List<double> scores) {
int bestScoreIndex = scores.indexWhere((s) => s != null);
scores.asMap().forEach((index, score) {
if (score != null &&
(score > scores[bestScoreIndex] ||
(score == scores[bestScoreIndex] && _random.nextBool()))) {
bestScoreIndex = index;
}
});
return bestScoreIndex;
}
</code></pre>
<hr />
<p>if I use <code>List<double?></code></p>
<pre><code>int _compute(Board board, int step, int deepness, List<double?> scores) {
for (var i = 0; i < 7; ++i) {
final boardCopy = board.clone();
final target = boardCopy.getColumnTarget(i);
if (target == -1) {
scores[i] = null;
continue;
}
final coordinate = Coordinate(i, target);
boardCopy.setBox(coordinate, player);
if (boardCopy.checkWinner(coordinate, player)) {
scores[i] += deepness / (step + 1);//<<<---- HERE I CAN'T USE +=
continue;
}
for (var j = 0; j < 7; ++j) {
final target = boardCopy.getColumnTarget(j);
if (target == -1) {
continue;
}
final coordinate = Coordinate(j, target);
boardCopy.setBox(coordinate, otherPlayer);
if (boardCopy.checkWinner(coordinate, otherPlayer)) {
scores[i] -= deepness / (step + 1); //<<<---- HERE I CAN'T USE -=
continue;
}
if (step + 1 < deepness) {
_compute(board, step + 1, deepness, scores);
}
}
}
return _getBestScoreIndex(scores);
}
int _getBestScoreIndex(List<double?> scores) {
int bestScoreIndex = scores.indexWhere((s) => s != null);
scores.asMap().forEach((index, score) {
if (score != null && // <<<---- HERE I CAN'T USE score !=
(score > scores[bestScoreIndex] || // <<<---- HERE I CAN'T USE score >
(score == scores[bestScoreIndex] && _random.nextBool()))) {
bestScoreIndex = index;
}
});
return bestScoreIndex;
}
</code></pre>
|
[
{
"answer_id": 74591749,
"author": "Stack Danny",
"author_id": 6039995,
"author_profile": "https://Stackoverflow.com/users/6039995",
"pm_score": 2,
"selected": false,
"text": "std::ranges::sort std::ranges::includes constexpr bool is_subset(auto a, auto b) {\n std::ranges::sort(a);\n std::ranges::sort(b);\n return std::ranges::includes(a, b);\n}\n\nint main() {\n constexpr std::array full = { 1,3,2 };\n constexpr std::array subset = { 3, 2 };\n\n static_assert(is_subset(full, subset), \"Has to be a subset\");\n}\n\n"
},
{
"answer_id": 74592118,
"author": "Ranoiaetep",
"author_id": 12861639,
"author_profile": "https://Stackoverflow.com/users/12861639",
"pm_score": 1,
"selected": false,
"text": "constexpr bool isSubset(auto sup, auto sub)\n{\n if (sub.size() > sup.size()) return false;\n std::ranges::sort(sup);\n return std::ranges::all_of(sup, \n [&](auto i){ return std::ranges::binary_search(sub, i); }\n );\n}\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9611719/"
] |
74,591,726
|
<pre><code>head(Data)
Gene1 Gene2 Gene3 Gene4 Gene5 Gene6 Gene7 Gene8
SAMPLE1 0 1 0 0 0 1 1 1
SAMPLE2 0 1 0 1 0 1 0 1
SAMPLE3 0 0 0 1 0 0 1 1
SAMPLE4 1 0 0 0 1 0 0 0
</code></pre>
<p>I am running fisher test and chi square test like following</p>
<pre><code>Gene7_Gene8<- table (Data[, c ("Gene7", "Gene8")])
chisq.test( Gene7_Gene8) and
fisher.test(Gene7_Gene8)
</code></pre>
<p>How can i run the chisq.test by <code>for loop</code> in all the data sets at once. I am looking for p.value against each possible pair of gene in my data set. (my original data has around 60 columns)</p>
|
[
{
"answer_id": 74591908,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "combn lst1 <- combn(seq_len(ncol(Data)), 2, function(i) \n FUN = chisq.test(table(Data[, i])), simplify = FALSE)\nnames(lst1) <- combn(colnames(Data), 2, FUN = paste, collapse = \"_\")\n"
},
{
"answer_id": 74591955,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 3,
"selected": true,
"text": "for com <- data.frame(t(combn(colnames(Data), 2)))\ncom\n# X1 X2\n# 1 Gene1 Gene2\n# 2 Gene1 Gene3\n# 3 Gene1 Gene4\n# 4 Gene1 Gene5\n# 5 Gene1 Gene6\n# 6 Gene1 Gene7\n# 7 Gene1 Gene8\n# 8 Gene2 Gene3\n# ...\n\nchisq <- apply(com, 1, function(i) chisq.test(table(Data[,i]))$p.value)\n# Warning in chisq.test(table(Data[, i])) :\n# Chi-squared approximation may be incorrect\n# Warning in chisq.test(table(Data[, i])) :\n# Chi-squared approximation may be incorrect\n# Warning in chisq.test(table(Data[, i])) :\n# Chi-squared approximation may be incorrect\n# ...\n\nchisq\n# [1] 1.0000000 0.3173105 1.0000000 0.5049851 1.0000000 1.0000000 0.5049851 1.0000000 1.0000000 1.0000000 0.3173105\n# [12] 1.0000000 1.0000000 1.0000000 0.3173105 1.0000000 1.0000000 0.3173105 1.0000000 1.0000000 1.0000000 1.0000000\n# [23] 1.0000000 1.0000000 0.5049851 1.0000000 1.0000000 1.0000000\n fisher <- apply(com, 1, function(i) fisher.test(table(Data[,i]))$p.value)\n# Error in fisher.test(table(Data[, i])) : \n# 'x' must have at least 2 rows and columns\n NA fisher <- apply(com, 1, function(i) tryCatch(fisher.test(table(Data[,i]))$p.value, error = function(e) NA_real_))\nfisher\n# [1] 1.0000000 NA 1.0000000 0.2500000 1.0000000 1.0000000 0.2500000 NA 1.0000000 1.0000000 0.3333333\n# [12] 1.0000000 1.0000000 NA NA NA NA NA 1.0000000 1.0000000 1.0000000 1.0000000\n# [23] 1.0000000 1.0000000 0.2500000 1.0000000 1.0000000 1.0000000\n out <- cbind(com, chisq=chisq, fisher=fisher)\nout\n# X1 X2 chisq fisher\n# 1 Gene1 Gene2 1.0000000 1.0000000\n# 2 Gene1 Gene3 0.3173105 NA\n# 3 Gene1 Gene4 1.0000000 1.0000000\n# 4 Gene1 Gene5 0.5049851 0.2500000\n# 5 Gene1 Gene6 1.0000000 1.0000000\n# 6 Gene1 Gene7 1.0000000 1.0000000\n# 7 Gene1 Gene8 0.5049851 0.2500000\n# 8 Gene2 Gene3 1.0000000 NA\n# 9 Gene2 Gene4 1.0000000 1.0000000\n# ...\n combn FUN= fisher.test"
},
{
"answer_id": 74592026,
"author": "RYann",
"author_id": 19110927,
"author_profile": "https://Stackoverflow.com/users/19110927",
"pm_score": 2,
"selected": false,
"text": "# This is a fake dataset similar to the one in the Opening post:\ndf <- data.frame(\n \n gene1 = sample(c(0,1),10,T),\n gene2 = sample(c(0,1),10,T),\n gene3 = sample(c(0,1),10,T),\n gene4 = sample(c(0,1),10,T),\n gene5 = sample(c(0,1),10,T)\n)\nrownames(df) <- paste0(\"sample\",1:nrow(df))\n\n\n\n# ldf stands for long df, and is a longer version, which will make it easier to analysie.\nldf <- df %>% pivot_longer(cols = everything(),names_to = \"gene_type\",\n values_to = \"true_false\") %>%\n arrange(gene_type)\n# ndf stands for nested df, and is the already nested-by-genes data frame we will analyse\nndf <- ldf %>% nest_by(gene_type)\n\n# Here we create a new colum named p_value and in the map() function\n# we extract the p values from a chiq.test erformed on each gene\nndf$p_value <- map(ndf$data,~chisq.test(table(.x))$p.value) %>% unlist()\n\n\n# Now we have our final data frame and can further anlyse and create plots.\nfinal_df <- ndf %>% unnest(cols = data)\nfinal_df %>% group_by(gene_type) %>% summarise(p.value=mean(p_value)) %>% \n mutate(is_significant=p.value<0.05)\n\n# In my personal opinion, leaving the data frame in a long version is best suited for further anlysis.\n\nfinal_df %>% group_by(gene_type) %>% summarise(p.value=mean(p_value)) %>% \n mutate(is_significant=p.value<0.05) %>% \n ggplot(aes(x=gene_type,y=p.value,color=is_significant))+\n geom_text(aes(label=gene_type),show.legend = F)+\n labs(title = \"P values of different genes\")+\n theme_minimal()\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13071518/"
] |
74,591,735
|
<p>I have a list of files to be imported into the data frame</p>
<p>cdoe:</p>
<pre><code># list contains the dataset name followed by the column name to match all the datasets; this list keeps changing and even the file formats. These dataset file names are provided by the user, and they are unique.
# First: find the file extension format and select appropriate pd.read_ to import
# second: merge the dataframes on the index
# in the below list,
file_list = ['dataset1.csv','datetime','dataset2.xlsx','timestamp']
df = pd.DataFrame()
for i in range(0:2:len(file_list)):
# find the file type first
# presently, I don't know how to find the file type; so
file_type = 'csv'
# second: merge the dataframe into the existing dataframe on the index
tdf = pd.DataFrame()
if file_type == 'csv':
tdf = pd.read_csv('%s'%(file_list[i])))
if file_type == 'xlsx':
tdf = pd.read_excel('%s'%(file_list[i])))
tdf.set_index('%s'%(file_list[i+1]),inplace=True)
# Merge dataframe with the existing dataframe
df = df.merge(tdf,right_index=True,left_index=True)
</code></pre>
<p>I reached this far. Is any direct module available to find the file type? I found <code>magic</code> but it has issues while importing it. Also, suggest a better approach to merge the files?
<strong>Update: Working solution</strong>
Inspired from the @ljdyer answer below, I came with the following and this is working perfectly:</p>
<pre><code> def find_file_type_import(file_name):
# Total file extensions possible for importing data
file_type = {'csv':'pd.read_csv(file_name)',
'xlsx':'pd.read_excel(file_name)',
'txt':'pd.read_csv(file_name)',
'parquet':'pd.read_parquet(file_name)',
'json':'pd.read_json(file_name)'
}
df = [eval(val) for key,val in file_type.items() if file_name
.endswith(key)][0]
return df
df = find_file_type_import(file_list [0])
</code></pre>
<p>This is working perfectly. Thank you for your valuable suggestions. ALso, correct me with the use of <code>eval</code> is good one or not?</p>
|
[
{
"answer_id": 74591908,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "combn lst1 <- combn(seq_len(ncol(Data)), 2, function(i) \n FUN = chisq.test(table(Data[, i])), simplify = FALSE)\nnames(lst1) <- combn(colnames(Data), 2, FUN = paste, collapse = \"_\")\n"
},
{
"answer_id": 74591955,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 3,
"selected": true,
"text": "for com <- data.frame(t(combn(colnames(Data), 2)))\ncom\n# X1 X2\n# 1 Gene1 Gene2\n# 2 Gene1 Gene3\n# 3 Gene1 Gene4\n# 4 Gene1 Gene5\n# 5 Gene1 Gene6\n# 6 Gene1 Gene7\n# 7 Gene1 Gene8\n# 8 Gene2 Gene3\n# ...\n\nchisq <- apply(com, 1, function(i) chisq.test(table(Data[,i]))$p.value)\n# Warning in chisq.test(table(Data[, i])) :\n# Chi-squared approximation may be incorrect\n# Warning in chisq.test(table(Data[, i])) :\n# Chi-squared approximation may be incorrect\n# Warning in chisq.test(table(Data[, i])) :\n# Chi-squared approximation may be incorrect\n# ...\n\nchisq\n# [1] 1.0000000 0.3173105 1.0000000 0.5049851 1.0000000 1.0000000 0.5049851 1.0000000 1.0000000 1.0000000 0.3173105\n# [12] 1.0000000 1.0000000 1.0000000 0.3173105 1.0000000 1.0000000 0.3173105 1.0000000 1.0000000 1.0000000 1.0000000\n# [23] 1.0000000 1.0000000 0.5049851 1.0000000 1.0000000 1.0000000\n fisher <- apply(com, 1, function(i) fisher.test(table(Data[,i]))$p.value)\n# Error in fisher.test(table(Data[, i])) : \n# 'x' must have at least 2 rows and columns\n NA fisher <- apply(com, 1, function(i) tryCatch(fisher.test(table(Data[,i]))$p.value, error = function(e) NA_real_))\nfisher\n# [1] 1.0000000 NA 1.0000000 0.2500000 1.0000000 1.0000000 0.2500000 NA 1.0000000 1.0000000 0.3333333\n# [12] 1.0000000 1.0000000 NA NA NA NA NA 1.0000000 1.0000000 1.0000000 1.0000000\n# [23] 1.0000000 1.0000000 0.2500000 1.0000000 1.0000000 1.0000000\n out <- cbind(com, chisq=chisq, fisher=fisher)\nout\n# X1 X2 chisq fisher\n# 1 Gene1 Gene2 1.0000000 1.0000000\n# 2 Gene1 Gene3 0.3173105 NA\n# 3 Gene1 Gene4 1.0000000 1.0000000\n# 4 Gene1 Gene5 0.5049851 0.2500000\n# 5 Gene1 Gene6 1.0000000 1.0000000\n# 6 Gene1 Gene7 1.0000000 1.0000000\n# 7 Gene1 Gene8 0.5049851 0.2500000\n# 8 Gene2 Gene3 1.0000000 NA\n# 9 Gene2 Gene4 1.0000000 1.0000000\n# ...\n combn FUN= fisher.test"
},
{
"answer_id": 74592026,
"author": "RYann",
"author_id": 19110927,
"author_profile": "https://Stackoverflow.com/users/19110927",
"pm_score": 2,
"selected": false,
"text": "# This is a fake dataset similar to the one in the Opening post:\ndf <- data.frame(\n \n gene1 = sample(c(0,1),10,T),\n gene2 = sample(c(0,1),10,T),\n gene3 = sample(c(0,1),10,T),\n gene4 = sample(c(0,1),10,T),\n gene5 = sample(c(0,1),10,T)\n)\nrownames(df) <- paste0(\"sample\",1:nrow(df))\n\n\n\n# ldf stands for long df, and is a longer version, which will make it easier to analysie.\nldf <- df %>% pivot_longer(cols = everything(),names_to = \"gene_type\",\n values_to = \"true_false\") %>%\n arrange(gene_type)\n# ndf stands for nested df, and is the already nested-by-genes data frame we will analyse\nndf <- ldf %>% nest_by(gene_type)\n\n# Here we create a new colum named p_value and in the map() function\n# we extract the p values from a chiq.test erformed on each gene\nndf$p_value <- map(ndf$data,~chisq.test(table(.x))$p.value) %>% unlist()\n\n\n# Now we have our final data frame and can further anlyse and create plots.\nfinal_df <- ndf %>% unnest(cols = data)\nfinal_df %>% group_by(gene_type) %>% summarise(p.value=mean(p_value)) %>% \n mutate(is_significant=p.value<0.05)\n\n# In my personal opinion, leaving the data frame in a long version is best suited for further anlysis.\n\nfinal_df %>% group_by(gene_type) %>% summarise(p.value=mean(p_value)) %>% \n mutate(is_significant=p.value<0.05) %>% \n ggplot(aes(x=gene_type,y=p.value,color=is_significant))+\n geom_text(aes(label=gene_type),show.legend = F)+\n labs(title = \"P values of different genes\")+\n theme_minimal()\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11922765/"
] |
74,591,750
|
<p>If in a cell there are few texts like, <code>Hi, How are you, Hello</code>.
I want to show in another cell if that cell contains either <code>Hi</code> and/or <code>Hello</code> and display the exact text on another cell.</p>
<p><a href="https://i.stack.imgur.com/2fLtp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2fLtp.png" alt="enter image description here" /></a></p>
<p>I'm using Google Sheets.</p>
<p>I'm a beginner and searched a lot about my question but didn't find any.</p>
|
[
{
"answer_id": 74591908,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "combn lst1 <- combn(seq_len(ncol(Data)), 2, function(i) \n FUN = chisq.test(table(Data[, i])), simplify = FALSE)\nnames(lst1) <- combn(colnames(Data), 2, FUN = paste, collapse = \"_\")\n"
},
{
"answer_id": 74591955,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 3,
"selected": true,
"text": "for com <- data.frame(t(combn(colnames(Data), 2)))\ncom\n# X1 X2\n# 1 Gene1 Gene2\n# 2 Gene1 Gene3\n# 3 Gene1 Gene4\n# 4 Gene1 Gene5\n# 5 Gene1 Gene6\n# 6 Gene1 Gene7\n# 7 Gene1 Gene8\n# 8 Gene2 Gene3\n# ...\n\nchisq <- apply(com, 1, function(i) chisq.test(table(Data[,i]))$p.value)\n# Warning in chisq.test(table(Data[, i])) :\n# Chi-squared approximation may be incorrect\n# Warning in chisq.test(table(Data[, i])) :\n# Chi-squared approximation may be incorrect\n# Warning in chisq.test(table(Data[, i])) :\n# Chi-squared approximation may be incorrect\n# ...\n\nchisq\n# [1] 1.0000000 0.3173105 1.0000000 0.5049851 1.0000000 1.0000000 0.5049851 1.0000000 1.0000000 1.0000000 0.3173105\n# [12] 1.0000000 1.0000000 1.0000000 0.3173105 1.0000000 1.0000000 0.3173105 1.0000000 1.0000000 1.0000000 1.0000000\n# [23] 1.0000000 1.0000000 0.5049851 1.0000000 1.0000000 1.0000000\n fisher <- apply(com, 1, function(i) fisher.test(table(Data[,i]))$p.value)\n# Error in fisher.test(table(Data[, i])) : \n# 'x' must have at least 2 rows and columns\n NA fisher <- apply(com, 1, function(i) tryCatch(fisher.test(table(Data[,i]))$p.value, error = function(e) NA_real_))\nfisher\n# [1] 1.0000000 NA 1.0000000 0.2500000 1.0000000 1.0000000 0.2500000 NA 1.0000000 1.0000000 0.3333333\n# [12] 1.0000000 1.0000000 NA NA NA NA NA 1.0000000 1.0000000 1.0000000 1.0000000\n# [23] 1.0000000 1.0000000 0.2500000 1.0000000 1.0000000 1.0000000\n out <- cbind(com, chisq=chisq, fisher=fisher)\nout\n# X1 X2 chisq fisher\n# 1 Gene1 Gene2 1.0000000 1.0000000\n# 2 Gene1 Gene3 0.3173105 NA\n# 3 Gene1 Gene4 1.0000000 1.0000000\n# 4 Gene1 Gene5 0.5049851 0.2500000\n# 5 Gene1 Gene6 1.0000000 1.0000000\n# 6 Gene1 Gene7 1.0000000 1.0000000\n# 7 Gene1 Gene8 0.5049851 0.2500000\n# 8 Gene2 Gene3 1.0000000 NA\n# 9 Gene2 Gene4 1.0000000 1.0000000\n# ...\n combn FUN= fisher.test"
},
{
"answer_id": 74592026,
"author": "RYann",
"author_id": 19110927,
"author_profile": "https://Stackoverflow.com/users/19110927",
"pm_score": 2,
"selected": false,
"text": "# This is a fake dataset similar to the one in the Opening post:\ndf <- data.frame(\n \n gene1 = sample(c(0,1),10,T),\n gene2 = sample(c(0,1),10,T),\n gene3 = sample(c(0,1),10,T),\n gene4 = sample(c(0,1),10,T),\n gene5 = sample(c(0,1),10,T)\n)\nrownames(df) <- paste0(\"sample\",1:nrow(df))\n\n\n\n# ldf stands for long df, and is a longer version, which will make it easier to analysie.\nldf <- df %>% pivot_longer(cols = everything(),names_to = \"gene_type\",\n values_to = \"true_false\") %>%\n arrange(gene_type)\n# ndf stands for nested df, and is the already nested-by-genes data frame we will analyse\nndf <- ldf %>% nest_by(gene_type)\n\n# Here we create a new colum named p_value and in the map() function\n# we extract the p values from a chiq.test erformed on each gene\nndf$p_value <- map(ndf$data,~chisq.test(table(.x))$p.value) %>% unlist()\n\n\n# Now we have our final data frame and can further anlyse and create plots.\nfinal_df <- ndf %>% unnest(cols = data)\nfinal_df %>% group_by(gene_type) %>% summarise(p.value=mean(p_value)) %>% \n mutate(is_significant=p.value<0.05)\n\n# In my personal opinion, leaving the data frame in a long version is best suited for further anlysis.\n\nfinal_df %>% group_by(gene_type) %>% summarise(p.value=mean(p_value)) %>% \n mutate(is_significant=p.value<0.05) %>% \n ggplot(aes(x=gene_type,y=p.value,color=is_significant))+\n geom_text(aes(label=gene_type),show.legend = F)+\n labs(title = \"P values of different genes\")+\n theme_minimal()\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17791081/"
] |
74,591,767
|
<p>Is there a way to <strong>modify</strong> a previously-declared CSS variable inside a media query with just vanilla CSS? What I'm after would look like this (which of course doesn't work as the variables all get computed in the end):</p>
<pre><code>#container {
--elem-size: 20px;
}
@media only screen and (min-width: 800px) {
#container {
--elem-size: calc(var(--elem-size) * 2);
}
}
</code></pre>
<p>I'm aware that it would be possible to declare a "base variable" (e.g. --base-elem-size) and then use it to generate new variable values for different viewports. However, I'm working with a very large number of CSS variables which makes it undesirable to create a duplicate base set out of them. The ideal solution would be able to "modify" a previously-declared value.</p>
|
[
{
"answer_id": 74591908,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "combn lst1 <- combn(seq_len(ncol(Data)), 2, function(i) \n FUN = chisq.test(table(Data[, i])), simplify = FALSE)\nnames(lst1) <- combn(colnames(Data), 2, FUN = paste, collapse = \"_\")\n"
},
{
"answer_id": 74591955,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 3,
"selected": true,
"text": "for com <- data.frame(t(combn(colnames(Data), 2)))\ncom\n# X1 X2\n# 1 Gene1 Gene2\n# 2 Gene1 Gene3\n# 3 Gene1 Gene4\n# 4 Gene1 Gene5\n# 5 Gene1 Gene6\n# 6 Gene1 Gene7\n# 7 Gene1 Gene8\n# 8 Gene2 Gene3\n# ...\n\nchisq <- apply(com, 1, function(i) chisq.test(table(Data[,i]))$p.value)\n# Warning in chisq.test(table(Data[, i])) :\n# Chi-squared approximation may be incorrect\n# Warning in chisq.test(table(Data[, i])) :\n# Chi-squared approximation may be incorrect\n# Warning in chisq.test(table(Data[, i])) :\n# Chi-squared approximation may be incorrect\n# ...\n\nchisq\n# [1] 1.0000000 0.3173105 1.0000000 0.5049851 1.0000000 1.0000000 0.5049851 1.0000000 1.0000000 1.0000000 0.3173105\n# [12] 1.0000000 1.0000000 1.0000000 0.3173105 1.0000000 1.0000000 0.3173105 1.0000000 1.0000000 1.0000000 1.0000000\n# [23] 1.0000000 1.0000000 0.5049851 1.0000000 1.0000000 1.0000000\n fisher <- apply(com, 1, function(i) fisher.test(table(Data[,i]))$p.value)\n# Error in fisher.test(table(Data[, i])) : \n# 'x' must have at least 2 rows and columns\n NA fisher <- apply(com, 1, function(i) tryCatch(fisher.test(table(Data[,i]))$p.value, error = function(e) NA_real_))\nfisher\n# [1] 1.0000000 NA 1.0000000 0.2500000 1.0000000 1.0000000 0.2500000 NA 1.0000000 1.0000000 0.3333333\n# [12] 1.0000000 1.0000000 NA NA NA NA NA 1.0000000 1.0000000 1.0000000 1.0000000\n# [23] 1.0000000 1.0000000 0.2500000 1.0000000 1.0000000 1.0000000\n out <- cbind(com, chisq=chisq, fisher=fisher)\nout\n# X1 X2 chisq fisher\n# 1 Gene1 Gene2 1.0000000 1.0000000\n# 2 Gene1 Gene3 0.3173105 NA\n# 3 Gene1 Gene4 1.0000000 1.0000000\n# 4 Gene1 Gene5 0.5049851 0.2500000\n# 5 Gene1 Gene6 1.0000000 1.0000000\n# 6 Gene1 Gene7 1.0000000 1.0000000\n# 7 Gene1 Gene8 0.5049851 0.2500000\n# 8 Gene2 Gene3 1.0000000 NA\n# 9 Gene2 Gene4 1.0000000 1.0000000\n# ...\n combn FUN= fisher.test"
},
{
"answer_id": 74592026,
"author": "RYann",
"author_id": 19110927,
"author_profile": "https://Stackoverflow.com/users/19110927",
"pm_score": 2,
"selected": false,
"text": "# This is a fake dataset similar to the one in the Opening post:\ndf <- data.frame(\n \n gene1 = sample(c(0,1),10,T),\n gene2 = sample(c(0,1),10,T),\n gene3 = sample(c(0,1),10,T),\n gene4 = sample(c(0,1),10,T),\n gene5 = sample(c(0,1),10,T)\n)\nrownames(df) <- paste0(\"sample\",1:nrow(df))\n\n\n\n# ldf stands for long df, and is a longer version, which will make it easier to analysie.\nldf <- df %>% pivot_longer(cols = everything(),names_to = \"gene_type\",\n values_to = \"true_false\") %>%\n arrange(gene_type)\n# ndf stands for nested df, and is the already nested-by-genes data frame we will analyse\nndf <- ldf %>% nest_by(gene_type)\n\n# Here we create a new colum named p_value and in the map() function\n# we extract the p values from a chiq.test erformed on each gene\nndf$p_value <- map(ndf$data,~chisq.test(table(.x))$p.value) %>% unlist()\n\n\n# Now we have our final data frame and can further anlyse and create plots.\nfinal_df <- ndf %>% unnest(cols = data)\nfinal_df %>% group_by(gene_type) %>% summarise(p.value=mean(p_value)) %>% \n mutate(is_significant=p.value<0.05)\n\n# In my personal opinion, leaving the data frame in a long version is best suited for further anlysis.\n\nfinal_df %>% group_by(gene_type) %>% summarise(p.value=mean(p_value)) %>% \n mutate(is_significant=p.value<0.05) %>% \n ggplot(aes(x=gene_type,y=p.value,color=is_significant))+\n geom_text(aes(label=gene_type),show.legend = F)+\n labs(title = \"P values of different genes\")+\n theme_minimal()\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/244932/"
] |
74,591,795
|
<p>I am new to React and learning about states and props.
I am following a React Wes Bos course and the teacher is using class components, so I am sort of refactoring as I go along to functional component (for exercise and because I have to learn those).</p>
<p>We are coding an app that is supposed to be a fish restaurant, and at some point, we want to load to the order section some values.</p>
<p>I have <strong>two main problems</strong>:</p>
<p>1 - When I try to <strong>run the method addToOrder(key) manually in the React dev tool</strong> by using $r on App.js, I get an error
<code>VM761:1 Uncaught TypeError: $r.addToOrder is not a function</code></p>
<p>2 - The second issue is that when I click on the button Add To Order, the one that is supposed to update the order{} object, <strong>the order object itself does not get updated</strong>.</p>
<p>I have been searching for a good half day now and I am not sure what could be wrong.</p>
<p>As a self-check:</p>
<ul>
<li>the prop index is passed correctly from to as I can console.log(index) and do get the current one.</li>
</ul>
<p>I am sorry if I am not explaining myself properly, it's a bit hard to condense into a short post. Do ask questions and clarifications as needed, I'll do my best to provide the correct info.</p>
<p>Here's the two components code:</p>
<p>App</p>
<pre><code>import React from "react";
import { Header } from "./Header";
import { Order } from "./Order";
import { Inventory } from "./Inventory";
import { useState } from "react";
import sampleFishes from "../sample-fishes";
import { Fish } from "./Fish";
export const App = () => {
const [state, setState] = useState({
fishes: {},
order: {},
});
/**
* Structure of the function served in <AddFishForm>
* Making a copy of the state to avoid mutations ...state.fishes
* Date.now() used to assign a unique key
*
*/
const addFish = (fish) => {
const fishes = { ...state.fishes };
fishes[`fish${Date.now()}`] = fish;
setState({
fishes: fishes,
});
};
/**
* Function to display a sample fishes in the list
* Made to avoid manual typing
* Fish data comes from ../sample-fishes
*/
const loadSampleFishes = () => {
setState({ fishes: sampleFishes });
};
/**
* Take a copy of state
* Either add to the order or update the number in order
* (if order exists, adds one to it, if not, set it to one)
* Call setState() to update state object
*/
const addToOrder = (key) => {
const order = { ...state.order };
order[key] = order[key] + 1 || 1;
setState({
order: order,
});
};
return (
<div className="catch-of-the-day">
<div className="menu">
<Header tagline="Fresh Seafood Market" />
<ul className="fishes">
{Object.keys(state.fishes).map((key) => {
return (
<Fish
key={key}
details={state.fishes[key]}
addToOrder={addToOrder}
></Fish>
);
})}
</ul>
</div>
<Order />
<Inventory addFish={addFish} loadSampleFishes={loadSampleFishes} />
</div>
);
};
</code></pre>
<p>Fish</p>
<pre><code>import React from "react";
import { formatPrice } from "../helpers";
export const Fish = ({ details, addToOrder, index }) => {
const isAvailable = details.status === "available";
const handleClick = () => {
addToOrder[index];
};
return (
<li className="menu-fish">
<img src={details.image} alt="" />
<h3 className="fish-names">
{details.name}
<span className="price">{formatPrice(details.price)}</span>
</h3>
<p>{details.desc}</p>
<button type="submit" disabled={!isAvailable} onClick={() => handleClick}>
{isAvailable ? "Add to order" : "Sold out!"}
</button>
</li>
);
};
</code></pre>
<p><a href="https://i.stack.imgur.com/CiS4q.png" rel="nofollow noreferrer">calling the function from $r</a></p>
<p><strong>TL;DR Solution</strong></p>
<p>Now that I know what I am looking for, this was the issue: <strong>updating and merging an object using React useState hook.</strong></p>
<p>I was missing to copy the previous state when updating order{}
The rest was pretty much correct, so the bit of code with the improvement is:</p>
<pre><code> const addOrder = (key) => {
const order = { ...state.order };
order[key] = order[key] + 1 || 1;
setState({
...state,
order: order,
});
};
</code></pre>
<p>This post (as well as the last answer on this one) really explains it well: <a href="https://stackoverflow.com/a/61243124/20615843">https://stackoverflow.com/a/61243124/20615843</a></p>
<p>This is the relative bit in the React docs:<a href="https://reactjs.org/docs/hooks-reference.html#functional-updates" rel="nofollow noreferrer">https://reactjs.org/docs/hooks-reference.html#functional-updates</a></p>
<p>Apparently, and even better practice is using useReducer() as stated: <a href="https://stackoverflow.com/a/71093607/20615843">https://stackoverflow.com/a/71093607/20615843</a></p>
|
[
{
"answer_id": 74591908,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "combn lst1 <- combn(seq_len(ncol(Data)), 2, function(i) \n FUN = chisq.test(table(Data[, i])), simplify = FALSE)\nnames(lst1) <- combn(colnames(Data), 2, FUN = paste, collapse = \"_\")\n"
},
{
"answer_id": 74591955,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 3,
"selected": true,
"text": "for com <- data.frame(t(combn(colnames(Data), 2)))\ncom\n# X1 X2\n# 1 Gene1 Gene2\n# 2 Gene1 Gene3\n# 3 Gene1 Gene4\n# 4 Gene1 Gene5\n# 5 Gene1 Gene6\n# 6 Gene1 Gene7\n# 7 Gene1 Gene8\n# 8 Gene2 Gene3\n# ...\n\nchisq <- apply(com, 1, function(i) chisq.test(table(Data[,i]))$p.value)\n# Warning in chisq.test(table(Data[, i])) :\n# Chi-squared approximation may be incorrect\n# Warning in chisq.test(table(Data[, i])) :\n# Chi-squared approximation may be incorrect\n# Warning in chisq.test(table(Data[, i])) :\n# Chi-squared approximation may be incorrect\n# ...\n\nchisq\n# [1] 1.0000000 0.3173105 1.0000000 0.5049851 1.0000000 1.0000000 0.5049851 1.0000000 1.0000000 1.0000000 0.3173105\n# [12] 1.0000000 1.0000000 1.0000000 0.3173105 1.0000000 1.0000000 0.3173105 1.0000000 1.0000000 1.0000000 1.0000000\n# [23] 1.0000000 1.0000000 0.5049851 1.0000000 1.0000000 1.0000000\n fisher <- apply(com, 1, function(i) fisher.test(table(Data[,i]))$p.value)\n# Error in fisher.test(table(Data[, i])) : \n# 'x' must have at least 2 rows and columns\n NA fisher <- apply(com, 1, function(i) tryCatch(fisher.test(table(Data[,i]))$p.value, error = function(e) NA_real_))\nfisher\n# [1] 1.0000000 NA 1.0000000 0.2500000 1.0000000 1.0000000 0.2500000 NA 1.0000000 1.0000000 0.3333333\n# [12] 1.0000000 1.0000000 NA NA NA NA NA 1.0000000 1.0000000 1.0000000 1.0000000\n# [23] 1.0000000 1.0000000 0.2500000 1.0000000 1.0000000 1.0000000\n out <- cbind(com, chisq=chisq, fisher=fisher)\nout\n# X1 X2 chisq fisher\n# 1 Gene1 Gene2 1.0000000 1.0000000\n# 2 Gene1 Gene3 0.3173105 NA\n# 3 Gene1 Gene4 1.0000000 1.0000000\n# 4 Gene1 Gene5 0.5049851 0.2500000\n# 5 Gene1 Gene6 1.0000000 1.0000000\n# 6 Gene1 Gene7 1.0000000 1.0000000\n# 7 Gene1 Gene8 0.5049851 0.2500000\n# 8 Gene2 Gene3 1.0000000 NA\n# 9 Gene2 Gene4 1.0000000 1.0000000\n# ...\n combn FUN= fisher.test"
},
{
"answer_id": 74592026,
"author": "RYann",
"author_id": 19110927,
"author_profile": "https://Stackoverflow.com/users/19110927",
"pm_score": 2,
"selected": false,
"text": "# This is a fake dataset similar to the one in the Opening post:\ndf <- data.frame(\n \n gene1 = sample(c(0,1),10,T),\n gene2 = sample(c(0,1),10,T),\n gene3 = sample(c(0,1),10,T),\n gene4 = sample(c(0,1),10,T),\n gene5 = sample(c(0,1),10,T)\n)\nrownames(df) <- paste0(\"sample\",1:nrow(df))\n\n\n\n# ldf stands for long df, and is a longer version, which will make it easier to analysie.\nldf <- df %>% pivot_longer(cols = everything(),names_to = \"gene_type\",\n values_to = \"true_false\") %>%\n arrange(gene_type)\n# ndf stands for nested df, and is the already nested-by-genes data frame we will analyse\nndf <- ldf %>% nest_by(gene_type)\n\n# Here we create a new colum named p_value and in the map() function\n# we extract the p values from a chiq.test erformed on each gene\nndf$p_value <- map(ndf$data,~chisq.test(table(.x))$p.value) %>% unlist()\n\n\n# Now we have our final data frame and can further anlyse and create plots.\nfinal_df <- ndf %>% unnest(cols = data)\nfinal_df %>% group_by(gene_type) %>% summarise(p.value=mean(p_value)) %>% \n mutate(is_significant=p.value<0.05)\n\n# In my personal opinion, leaving the data frame in a long version is best suited for further anlysis.\n\nfinal_df %>% group_by(gene_type) %>% summarise(p.value=mean(p_value)) %>% \n mutate(is_significant=p.value<0.05) %>% \n ggplot(aes(x=gene_type,y=p.value,color=is_significant))+\n geom_text(aes(label=gene_type),show.legend = F)+\n labs(title = \"P values of different genes\")+\n theme_minimal()\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20615843/"
] |
74,591,838
|
<p>I use React for my front-end web app. When I call back-end API, I got this array:</p>
<pre><code>[
{
id: 1,
fullname: ABC,
email: abc@gmail.com
...
},
{
id: 2,
fullname: DEF,
email: def@gmail.com
...
},
{
id: 2,
fullname: DEF,
email: def@gmail.com
...
},
{
id: 3,
fullname: GHI,
email: ghi@gmail.com
...
},
{
id: 1,
fullname: ABC,
email: abc@gmail.com
...
}
]
</code></pre>
<p>Now, I need to create a new array from this old array but just contain <code>id</code> and <code>fullname</code> and not duplicates. I have try this code:</p>
<pre><code>const oldArray = //this is the array above
const temp = [];
for (let i = 0; i < oldArray .length; i++) {
temp.push({
value: oldArray [i]._id,
display: oldArray [i].fullname
});
}
const newArray = Array.from(new Set(temp));
</code></pre>
<p>The result I receive:</p>
<pre><code>[
{
value: 1,
display: ABC
},
{
value: 2,
display: DEF
},
{
value: 2,
display: DEF
},
{
value: 3,
display: GHI
},
{
value: 1,
display: ABC
}
]
</code></pre>
<p>As you can see, the result is still duplicated. How can I fix it?</p>
|
[
{
"answer_id": 74591874,
"author": "InfiniteStack",
"author_id": 1244611,
"author_profile": "https://Stackoverflow.com/users/1244611",
"pm_score": -1,
"selected": false,
"text": "Set() Set.add"
},
{
"answer_id": 74592043,
"author": "Suhail Qureshi",
"author_id": 20308649,
"author_profile": "https://Stackoverflow.com/users/20308649",
"pm_score": 0,
"selected": false,
"text": "const tempArray=[];\nconst filteredArr = oldArray.filter(value =>{\n if(!tempArray.includes(value.id)) {\n tempArray.push(value.id)\n return true\n } \n })\n"
},
{
"answer_id": 74592439,
"author": "Unmitigated",
"author_id": 9513184,
"author_profile": "https://Stackoverflow.com/users/9513184",
"pm_score": 0,
"selected": false,
"text": "Array#filter Set const arr=[{id:1,fullname:\"ABC\",email:\"abc@gmail.com\"},{id:2,fullname:\"DEF\",email:\"def@gmail.com\"},{id:2,fullname:\"DEF\",email:\"def@gmail.com\"},{id:3,fullname:\"GHI\",email:\"ghi@gmail.com\"},{id:1,fullname:\"ABC\",email:\"abc@gmail.com\"}];\nlet ids = new Set, res = arr.filter(x => !ids.has(x.id) && ids.add(x.id));\nconsole.log(res);"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16731421/"
] |
74,591,839
|
<p>I am trying to scrape the table from:
<a href="https://worldpopulationreview.com/states" rel="nofollow noreferrer">https://worldpopulationreview.com/states</a></p>
<p>My code:</p>
<pre><code>from bs4 import BeautifulSoup
import requests
import pandas as pd
url = 'https://worldpopulationreview.com/states'
page = requests.get(url)
soup = BeautifulSoup(page.text,'lxml')
table = soup.find('table', {'class': 'jsx-a3119e4553b2cac7 table is-striped is-hoverable is-fullwidth tp-table-body is-narrow'})
headers = []
for i in table.find_all('th'):
title = i.text.strip()
headers.append(title)
df = pd.DataFrame(columns=headers)
for row in table.find_all('tr')[1:]:
data = row.find_all('td')
row_data = [td.text.strip() for td in data]
length = len(df)
df.loc[length] = row_data
df
</code></pre>
<p>Currently returns</p>
<pre><code>'NoneType' object has no attribute 'find_all'
</code></pre>
<p>Clearly the error is because the table variable is returning nothing, but I believe I have the table tag correct.</p>
|
[
{
"answer_id": 74592088,
"author": "Fazlul",
"author_id": 12848411,
"author_profile": "https://Stackoverflow.com/users/12848411",
"pm_score": 3,
"selected": true,
"text": "JavaScript from selenium import webdriver\nimport time\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nfrom selenium.webdriver.chrome.service import Service\n\nwebdriver_service = Service(\"./chromedriver\") #Your chromedriver path\ndriver = webdriver.Chrome(service=webdriver_service)\n\ndriver.get('https://worldpopulationreview.com/states')\ndriver.maximize_window()\ntime.sleep(8)\n\n\nsoup = BeautifulSoup(driver.page_source,\"lxml\")\n\n\n#You can pull the table directly from the web page\ndf = pd.read_html(str(soup))[0]\nprint(df)\n\n#OR\n#table= soup.select_one('table[class=\"jsx-a3119e4553b2cac7 table is-striped is-hoverable is-fullwidth tp-table-body is-narrow\"]')\n# df = pd.read_html(str(table))[0]\n# print(df)\n Rank State 2022 Population Growth Rate ... 2010 Population Growth Since 2010 % of US Density (/mi²)\n0 1 California 39995077 0.57% ... 37253956 7.36% 11.93% 257\n1 2 Texas 29945493 1.35% ... 25145561 19.09% 8.93% 115\n2 3 Florida 22085563 1.25% ... 18801310 17.47% 6.59% 412\n3 4 New York 20365879 0.41% ... 19378102 5.10% 6.07% 432\n4 5 Pennsylvania 13062764 0.23% ... 12702379 2.84% 3.90% 292\n5 6 Illinois 12808884 -0.01% ... 12830632 -0.17% 3.82% 231\n6 7 Ohio 11852036 0.22% ... 11536504 2.74% 3.53% 290\n7 8 Georgia 10916760 0.95% ... 9687653 12.69% 3.26% 190\n8 9 North Carolina 10620168 0.86% ... 9535483 11.38% 3.17% 218\n9 10 Michigan 10116069 0.19% ... 9883640 2.35% 3.02% 179\n10 11 New Jersey 9388414 0.53% ... 8791894 6.78% 2.80% 1277\n11 12 Virginia 8757467 0.73% ... 8001024 9.45% 2.61% 222\n12 13 Washington 7901429 1.26% ... 6724540 17.50% 2.36% 119\n13 14 Arizona 7303398 1.05% ... 6392017 14.26% 2.18% 64\n14 15 Massachusetts 7126375 0.68% ... 6547629 8.84% 2.13% 914\n15 16 Tennessee 7023788 0.81% ... 6346105 10.68% 2.09% 170\n16 17 Indiana 6845874 0.44% ... 6483802 5.58% 2.04% 191\n17 18 Maryland 6257958 0.65% ... 5773552 8.39% 1.87% 645\n18 19 Missouri 6188111 0.27% ... 5988927 3.33% 1.85% 90\n19 20 Wisconsin 5935064 0.35% ... 5686986 4.36% 1.77% 110\n20 21 Colorado 5922618 1.27% ... 5029196 17.76% 1.77% 57\n21 22 Minnesota 5787008 0.70% ... 5303925 9.11% 1.73% 73\n22 23 South Carolina 5217037 0.95% ... 4625364 12.79% 1.56% 174\n23 24 Alabama 5073187 0.48% ... 4779736 6.14% 1.51% 100\n24 25 Louisiana 4682633 0.27% ... 4533372 3.29% 1.40% 108\n25 26 Kentucky 4539130 0.37% ... 4339367 4.60% 1.35% 115\n26 27 Oregon 4318492 0.95% ... 3831074 12.72% 1.29% 45\n27 28 Oklahoma 4000953 0.52% ... 3751351 6.65% 1.19% 58\n28 29 Connecticut 3612314 0.09% ... 3574097 1.07% 1.08% 746\n29 30 Utah 3373162 1.53% ... 2763885 22.04% 1.01% 41\n30 31 Iowa 3219171 0.45% ... 3046355 5.67% 0.96% 58\n31 32 Nevada 3185426 1.28% ... 2700551 17.95% 0.95% 29\n32 33 Arkansas 3030646 0.32% ... 2915918 3.93% 0.90% 58\n33 34 Mississippi 2960075 -0.02% ... 2967297 -0.24% 0.88% 63\n34 35 Kansas 2954832 0.29% ... 2853118 3.57% 0.88% 36\n35 36 New Mexico 2129190 0.27% ... 2059179 3.40% 0.64% 18\n36 37 Nebraska 1988536 0.68% ... 1826341 8.88% 0.59% 26\n37 38 Idaho 1893410 1.45% ... 1567582 20.79% 0.56% 23\n38 39 West Virginia 1781860 -0.33% ... 1852994 -3.84% 0.53% 74\n39 40 Hawaii 1474265 0.65% ... 1360301 8.38% 0.44% 230\n40 41 New Hampshire 1389741 0.44% ... 1316470 5.57% 0.41% 155\n41 42 Maine 1369159 0.25% ... 1328361 3.07% 0.41% 44\n42 43 Rhode Island 1106341 0.41% ... 1052567 5.11% 0.33% 1070\n43 44 Montana 1103187 0.87% ... 989415 11.50% 0.33%\n8\n44 45 Delaware 1008350 0.92% ... 897934 12.30% 0.30% 517\n45 46 South Dakota 901165 0.81% ... 814180 10.68% 0.27% 12\n46 47 North Dakota 800394 1.35% ... 672591 19.00% 0.24% 12\n47 48 Alaska 738023 0.31% ... 710231 3.91% 0.22%\n1\n48 49 Vermont 646545 0.27% ... 625741 3.32% 0.19% 70\n49 50 Wyoming 579495 0.23% ... 563626 2.82% 0.17%\n6\n\n[50 rows x 9 columns]\n"
},
{
"answer_id": 74592204,
"author": "HedgeHog",
"author_id": 14460824,
"author_profile": "https://Stackoverflow.com/users/14460824",
"pm_score": 2,
"selected": false,
"text": "selenium soup = BeautifulSoup(requests.get('https://worldpopulationreview.com/states').text)\n\njson.loads(soup.select_one('#__NEXT_DATA__').text)['props']['pageProps']['data']\n import requests, json\nimport pandas as pd\nfrom bs4 import BeautifulSoup\n\nsoup = BeautifulSoup(requests.get('https://worldpopulationreview.com/states').text)\n\npd.DataFrame(\n json.loads(soup.select_one('#__NEXT_DATA__').text)['props']['pageProps']['data']\n)\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8469209/"
] |
74,591,842
|
<p>I am trying to extract the date from multiple PDF's to create a date column in a dataset.</p>
<p>I have a folder holding all the pdf's and am trying to do a topic modelling over a time period, hence I need to extract the dates.</p>
<p>Below is the dataset I have just containing the filenames.</p>
<pre><code># A tibble: 260 x 1
filename
<chr>
1 ./2012.01.18.pdf
2 ./2012.02.07.pdf
3 ./2012.03.12.pdf
4 ./2012.03.26.pdf
5 ./2012.04.02.pdf
6 ./2012.04.04.pdf
7 ./2012.04.19.pdf
8 ./2012.05.01.pdf
9 ./2012.05.07.pdf
10 ./2012.06.14.pdf
</code></pre>
<p>Tried "as.Date" with no luck, as I am unable to extract the dates from a file holding the all the PDFs</p>
|
[
{
"answer_id": 74591906,
"author": "Rui Barradas",
"author_id": 8245406,
"author_profile": "https://Stackoverflow.com/users/8245406",
"pm_score": 1,
"selected": false,
"text": "\"Date\" df1 <-'1 ./2012.01.18.pdf\n 2 ./2012.02.07.pdf\n 3 ./2012.03.12.pdf\n 4 ./2012.03.26.pdf\n 5 ./2012.04.02.pdf\n 6 ./2012.04.04.pdf\n 7 ./2012.04.19.pdf\n 8 ./2012.05.01.pdf\n 9 ./2012.05.07.pdf\n10 ./2012.06.14.pdf'\ndf1 <- read.table(textConnection(df1))\n\ndf1$V2 <- sub(\".*(\\\\d{4}.\\\\d{2}.\\\\d{2}).*\", \"\\\\1\", df1$V2)\ndf1$V2 <- as.Date(df1$V2, \"%Y.%m.%d\")\ndf1\n#> V1 V2\n#> 1 1 2012-01-18\n#> 2 2 2012-02-07\n#> 3 3 2012-03-12\n#> 4 4 2012-03-26\n#> 5 5 2012-04-02\n#> 6 6 2012-04-04\n#> 7 7 2012-04-19\n#> 8 8 2012-05-01\n#> 9 9 2012-05-07\n#> 10 10 2012-06-14\n"
},
{
"answer_id": 74591921,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 3,
"selected": true,
"text": "format %Y %m %d df$V2 <- as.Date(df$V2, format = \"./%Y.%m.%d.pdf\")\n > df\n V1 V2\n1 1 2012-01-18\n2 2 2012-02-07\n3 3 2012-03-12\n4 4 2012-03-26\n5 5 2012-04-02\n6 6 2012-04-04\n7 7 2012-04-19\n8 8 2012-05-01\n9 9 2012-05-07\n10 10 2012-06-14\n df <- structure(list(V1 = 1:10, V2 = c(\"./2012.01.18.pdf\", \"./2012.02.07.pdf\", \n\"./2012.03.12.pdf\", \"./2012.03.26.pdf\", \"./2012.04.02.pdf\", \"./2012.04.04.pdf\", \n\"./2012.04.19.pdf\", \"./2012.05.01.pdf\", \"./2012.05.07.pdf\", \"./2012.06.14.pdf\"\n)), class = \"data.frame\", row.names = c(NA, -10L))\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20615988/"
] |
74,591,879
|
<p>I want to compare three variable in three dataframe columns. but it gave me an error <strong>TypeError: unhashable type: 'Series'</strong>. below is my code</p>
<pre><code>import pandas as pd
df = pd.DataFrame(columns=['Entry','Middle','Exit'])
entry_value = '17.98'
middle_value = '12.16'
exit_value = '1.2'
df = df.append({'Entry' : entry_value , 'Middle' : middle_value, 'Exit' : exit_value}, ignore_index = True)
entry_value = '19.98'
middle_value = '192.16'
exit_value = '1.1'
if entry_value in {df['Entry'] , df['Middle'] , df['Exit']} :
print('entry')
elif middle_value in {df['Entry'] , df['Middle'] , df['Exit']} :
print('middle')
elif exit_value in {df['Entry'] , df['Middle'] , df['Exit']} :
print('exit')
else:
print('wawo')`
</code></pre>
|
[
{
"answer_id": 74591906,
"author": "Rui Barradas",
"author_id": 8245406,
"author_profile": "https://Stackoverflow.com/users/8245406",
"pm_score": 1,
"selected": false,
"text": "\"Date\" df1 <-'1 ./2012.01.18.pdf\n 2 ./2012.02.07.pdf\n 3 ./2012.03.12.pdf\n 4 ./2012.03.26.pdf\n 5 ./2012.04.02.pdf\n 6 ./2012.04.04.pdf\n 7 ./2012.04.19.pdf\n 8 ./2012.05.01.pdf\n 9 ./2012.05.07.pdf\n10 ./2012.06.14.pdf'\ndf1 <- read.table(textConnection(df1))\n\ndf1$V2 <- sub(\".*(\\\\d{4}.\\\\d{2}.\\\\d{2}).*\", \"\\\\1\", df1$V2)\ndf1$V2 <- as.Date(df1$V2, \"%Y.%m.%d\")\ndf1\n#> V1 V2\n#> 1 1 2012-01-18\n#> 2 2 2012-02-07\n#> 3 3 2012-03-12\n#> 4 4 2012-03-26\n#> 5 5 2012-04-02\n#> 6 6 2012-04-04\n#> 7 7 2012-04-19\n#> 8 8 2012-05-01\n#> 9 9 2012-05-07\n#> 10 10 2012-06-14\n"
},
{
"answer_id": 74591921,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 3,
"selected": true,
"text": "format %Y %m %d df$V2 <- as.Date(df$V2, format = \"./%Y.%m.%d.pdf\")\n > df\n V1 V2\n1 1 2012-01-18\n2 2 2012-02-07\n3 3 2012-03-12\n4 4 2012-03-26\n5 5 2012-04-02\n6 6 2012-04-04\n7 7 2012-04-19\n8 8 2012-05-01\n9 9 2012-05-07\n10 10 2012-06-14\n df <- structure(list(V1 = 1:10, V2 = c(\"./2012.01.18.pdf\", \"./2012.02.07.pdf\", \n\"./2012.03.12.pdf\", \"./2012.03.26.pdf\", \"./2012.04.02.pdf\", \"./2012.04.04.pdf\", \n\"./2012.04.19.pdf\", \"./2012.05.01.pdf\", \"./2012.05.07.pdf\", \"./2012.06.14.pdf\"\n)), class = \"data.frame\", row.names = c(NA, -10L))\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20584885/"
] |
74,591,884
|
<p>I do have a state like this:</p>
<pre><code> const [serviceListData, setserviceListData] = React.useState({});
</code></pre>
<p>I want to add <code>Id</code> to my current state, so I implemented my code inside of <code>useEffect</code> hook.
it triggers every time <code>Insurance</code> and <code>count</code> changes.</p>
<pre><code> React.useEffect(() => {
if (selectInsurance) {
setserviceListData({
...serviceListData,
ID: filtered.ID,
});
}
}, [selectInsurance, count]);
</code></pre>
<p>but with this code, I only get my new state. previous state is getting removed. I console logged it and get this result:</p>
<pre><code>Object { }
EachInsurance.js:56
Object { ID: 189256 }
EachInsurance.js:56
Object { ID: 189256 }
EachInsurance.js:56
Object { }
EachInsurance.js:56
Object { }
EachInsurance.js:56
Object { ID: 189257 }
</code></pre>
<p>so at first stage my state is a empty object. then it gets the <code>ID</code> but as soon as I select another <code>Insurace</code>, the state gets erased and replaced with the new one.</p>
<p>what is the problem with my code. I thought it would spread old value (keeping it) and then adds new <code>ID</code></p>
|
[
{
"answer_id": 74591906,
"author": "Rui Barradas",
"author_id": 8245406,
"author_profile": "https://Stackoverflow.com/users/8245406",
"pm_score": 1,
"selected": false,
"text": "\"Date\" df1 <-'1 ./2012.01.18.pdf\n 2 ./2012.02.07.pdf\n 3 ./2012.03.12.pdf\n 4 ./2012.03.26.pdf\n 5 ./2012.04.02.pdf\n 6 ./2012.04.04.pdf\n 7 ./2012.04.19.pdf\n 8 ./2012.05.01.pdf\n 9 ./2012.05.07.pdf\n10 ./2012.06.14.pdf'\ndf1 <- read.table(textConnection(df1))\n\ndf1$V2 <- sub(\".*(\\\\d{4}.\\\\d{2}.\\\\d{2}).*\", \"\\\\1\", df1$V2)\ndf1$V2 <- as.Date(df1$V2, \"%Y.%m.%d\")\ndf1\n#> V1 V2\n#> 1 1 2012-01-18\n#> 2 2 2012-02-07\n#> 3 3 2012-03-12\n#> 4 4 2012-03-26\n#> 5 5 2012-04-02\n#> 6 6 2012-04-04\n#> 7 7 2012-04-19\n#> 8 8 2012-05-01\n#> 9 9 2012-05-07\n#> 10 10 2012-06-14\n"
},
{
"answer_id": 74591921,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 3,
"selected": true,
"text": "format %Y %m %d df$V2 <- as.Date(df$V2, format = \"./%Y.%m.%d.pdf\")\n > df\n V1 V2\n1 1 2012-01-18\n2 2 2012-02-07\n3 3 2012-03-12\n4 4 2012-03-26\n5 5 2012-04-02\n6 6 2012-04-04\n7 7 2012-04-19\n8 8 2012-05-01\n9 9 2012-05-07\n10 10 2012-06-14\n df <- structure(list(V1 = 1:10, V2 = c(\"./2012.01.18.pdf\", \"./2012.02.07.pdf\", \n\"./2012.03.12.pdf\", \"./2012.03.26.pdf\", \"./2012.04.02.pdf\", \"./2012.04.04.pdf\", \n\"./2012.04.19.pdf\", \"./2012.05.01.pdf\", \"./2012.05.07.pdf\", \"./2012.06.14.pdf\"\n)), class = \"data.frame\", row.names = c(NA, -10L))\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20395245/"
] |
74,591,889
|
<p>Consider the following template class:</p>
<pre><code>//Node.hh
template<class dataType>
class impNode
{
private:
dataType _data;
public:
explicit impNode(const dataType &data) { std::cout << "this constructor is called!" << std::endl; };
virtual ~impNode() { };
dataType getData() { }; //This is where the error triggers
};
</code></pre>
<p>Now, when instantiating this class:</p>
<pre><code>//main.cpp
int main(int, char**)
{
impNode a{98};
impNode b{false};
impNode c{"hello"};
}
</code></pre>
<p>I get the following compile time error:</p>
<pre><code>error: function returning an array
[build] 27 | dataType getData() { };
</code></pre>
<p>One way to avoid this is to specialize the class template:</p>
<pre><code>template<>
class impNode<char[6]>
{
private:
public:
explicit impNode(const char data[6]) { std::cout << "This class template specialization is needed for the program to compile" << std::endl; };
virtual ~impNode() { };
char* getData() { };
};
</code></pre>
<p>Doing so, the program compiles and runs successfully, being this the output of the program:</p>
<pre><code>this constructor is called!
this constructor is called!
This class template specialization is needed for the program to compile
</code></pre>
<p>However I would like to be able to instantiate the class with any cstyle rvalue string without having to specialize for each different size.</p>
|
[
{
"answer_id": 74591906,
"author": "Rui Barradas",
"author_id": 8245406,
"author_profile": "https://Stackoverflow.com/users/8245406",
"pm_score": 1,
"selected": false,
"text": "\"Date\" df1 <-'1 ./2012.01.18.pdf\n 2 ./2012.02.07.pdf\n 3 ./2012.03.12.pdf\n 4 ./2012.03.26.pdf\n 5 ./2012.04.02.pdf\n 6 ./2012.04.04.pdf\n 7 ./2012.04.19.pdf\n 8 ./2012.05.01.pdf\n 9 ./2012.05.07.pdf\n10 ./2012.06.14.pdf'\ndf1 <- read.table(textConnection(df1))\n\ndf1$V2 <- sub(\".*(\\\\d{4}.\\\\d{2}.\\\\d{2}).*\", \"\\\\1\", df1$V2)\ndf1$V2 <- as.Date(df1$V2, \"%Y.%m.%d\")\ndf1\n#> V1 V2\n#> 1 1 2012-01-18\n#> 2 2 2012-02-07\n#> 3 3 2012-03-12\n#> 4 4 2012-03-26\n#> 5 5 2012-04-02\n#> 6 6 2012-04-04\n#> 7 7 2012-04-19\n#> 8 8 2012-05-01\n#> 9 9 2012-05-07\n#> 10 10 2012-06-14\n"
},
{
"answer_id": 74591921,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 3,
"selected": true,
"text": "format %Y %m %d df$V2 <- as.Date(df$V2, format = \"./%Y.%m.%d.pdf\")\n > df\n V1 V2\n1 1 2012-01-18\n2 2 2012-02-07\n3 3 2012-03-12\n4 4 2012-03-26\n5 5 2012-04-02\n6 6 2012-04-04\n7 7 2012-04-19\n8 8 2012-05-01\n9 9 2012-05-07\n10 10 2012-06-14\n df <- structure(list(V1 = 1:10, V2 = c(\"./2012.01.18.pdf\", \"./2012.02.07.pdf\", \n\"./2012.03.12.pdf\", \"./2012.03.26.pdf\", \"./2012.04.02.pdf\", \"./2012.04.04.pdf\", \n\"./2012.04.19.pdf\", \"./2012.05.01.pdf\", \"./2012.05.07.pdf\", \"./2012.06.14.pdf\"\n)), class = \"data.frame\", row.names = c(NA, -10L))\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17288970/"
] |
74,591,900
|
<p>On my ecommerce project I wanna impelement a search bar where you can search products by name through drf api, I installed django_filters and created a class like so:</p>
<pre><code>class ProductFilter(generics.ListCreateAPIView):
queryset = Product.objects.all()
serializer_class = ProductSerializer
filter_backends = [filters.SearchFilter]
search_fields = ['^name']
</code></pre>
<p>I tested the endpoint and it works but I don't know how to make it work on the frontend part with react, I have the saerchbar in the header like so:</p>
<pre><code><Form className="d-flex">
<Form.Control
type="search"
placeholder="Search"
className="me-2"
aria-label="Search"
/>
<Button variant="outline-success">Search</Button>
</Form>
</code></pre>
<p>Using axios for api calls, I have no idea how to set this up and if I need reducers, actions, store too</p>
|
[
{
"answer_id": 74591906,
"author": "Rui Barradas",
"author_id": 8245406,
"author_profile": "https://Stackoverflow.com/users/8245406",
"pm_score": 1,
"selected": false,
"text": "\"Date\" df1 <-'1 ./2012.01.18.pdf\n 2 ./2012.02.07.pdf\n 3 ./2012.03.12.pdf\n 4 ./2012.03.26.pdf\n 5 ./2012.04.02.pdf\n 6 ./2012.04.04.pdf\n 7 ./2012.04.19.pdf\n 8 ./2012.05.01.pdf\n 9 ./2012.05.07.pdf\n10 ./2012.06.14.pdf'\ndf1 <- read.table(textConnection(df1))\n\ndf1$V2 <- sub(\".*(\\\\d{4}.\\\\d{2}.\\\\d{2}).*\", \"\\\\1\", df1$V2)\ndf1$V2 <- as.Date(df1$V2, \"%Y.%m.%d\")\ndf1\n#> V1 V2\n#> 1 1 2012-01-18\n#> 2 2 2012-02-07\n#> 3 3 2012-03-12\n#> 4 4 2012-03-26\n#> 5 5 2012-04-02\n#> 6 6 2012-04-04\n#> 7 7 2012-04-19\n#> 8 8 2012-05-01\n#> 9 9 2012-05-07\n#> 10 10 2012-06-14\n"
},
{
"answer_id": 74591921,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 3,
"selected": true,
"text": "format %Y %m %d df$V2 <- as.Date(df$V2, format = \"./%Y.%m.%d.pdf\")\n > df\n V1 V2\n1 1 2012-01-18\n2 2 2012-02-07\n3 3 2012-03-12\n4 4 2012-03-26\n5 5 2012-04-02\n6 6 2012-04-04\n7 7 2012-04-19\n8 8 2012-05-01\n9 9 2012-05-07\n10 10 2012-06-14\n df <- structure(list(V1 = 1:10, V2 = c(\"./2012.01.18.pdf\", \"./2012.02.07.pdf\", \n\"./2012.03.12.pdf\", \"./2012.03.26.pdf\", \"./2012.04.02.pdf\", \"./2012.04.04.pdf\", \n\"./2012.04.19.pdf\", \"./2012.05.01.pdf\", \"./2012.05.07.pdf\", \"./2012.06.14.pdf\"\n)), class = \"data.frame\", row.names = c(NA, -10L))\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19778871/"
] |
74,591,909
|
<p>I've got a bottomSheetScaffold, which contains a BottomSheet</p>
<p>That BottomSheet uses device's Camera, where I use CameraX alongside with Google's MLkit for bar scanning</p>
<p>Let's consider permission is accepted
What happens (Not correct): once I expand the bottomsheet upward, I show the CameraPreview, show camera preview, and ImageAnalyzer which analyzes the preview image.</p>
<p>Now the bottomSheet is expanded, the camera preview is visible and working as expected
then I collapse the bottomSheet, but the camera is still working (analyzer as well,
<code>imageAnalysis.clearAnalyzer()</code> clear the analyzing part)</p>
<p>The outcome: is not correct behavior I intended</p>
<p>so How can I stop camera from working, and using resources once the bottomSheetState is collapsed, and only allow camera when bottomSheetState is Expanded</p>
<p>How it works(Wrong):</p>
<p><a href="https://i.stack.imgur.com/HjjkV.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HjjkV.gif" alt="Wrong Behavior(Check Log)" /></a></p>
<p>The problem I got is, camera is binded to the lifecycle of the activity, and not the composable itself, when re-composition happens, it still consider the camera live, since it's not attached to the composition lifecycle</p>
<p>How does Composition work:</p>
<p><a href="https://i.stack.imgur.com/a1LEo.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/a1LEo.gif" alt="Recompositions" /></a></p>
<p>Code:</p>
<pre><code>@OptIn(ExperimentalMaterialApi::class)
@Composable
fun BottomSheetContent(
modifier: Modifier = Modifier,
bottomSheetState: BottomSheetState
) {
Column(
modifier = modifier
.fillMaxWidth()
.fillMaxHeight(0.8f)
) {
PeekBar()
ScanningSerialTextTitle(modifier)
if (bottomSheetState.isExpanded) {
CameraBox(modifier)
} else {
EmptyBox()
}
}
}
@Composable
fun EmptyBox(modifier: Modifier = Modifier) {
Box(
modifier = modifier
.fillMaxSize()
.background(color = Color.DarkGray)
)
}
@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun CameraBox(modifier: Modifier = Modifier) {
val cameraPermissionState = rememberPermissionState(permission = Manifest.permission.CAMERA)
val lifeCycleOwner = LocalLifecycleOwner.current
DisposableEffect(key1 = lifeCycleOwner, effect = {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_START) {
cameraPermissionState.launchPermissionRequest()
}
}
lifeCycleOwner.lifecycle.addObserver(observer)
onDispose { lifeCycleOwner.lifecycle.removeObserver(observer) }
})
cameraPermissionState.handlePermissionCases(
ShouldShowRationaleContent = {
ShouldShowRationaleContent(cameraPermissionState = cameraPermissionState)
},
PermissionDeniedPermanentlyContent = {
PermissionDeniedPermanentContent()
}) {
val context = LocalContext.current
val barCodeVal = remember { mutableStateOf("") }
CameraPreview(onBarcodeDetected = { barcodes ->
barcodes.forEach { barcode ->
barcode.rawValue?.let { barcodeValue ->
barCodeVal.value = barcodeValue
Toast.makeText(context, barcodeValue, Toast.LENGTH_SHORT).show()
}
}
}, onBarcodeFailed = {}, onBarcodeNotFound = {})
}
}
@Composable
fun CameraPreview(
modifier: Modifier = Modifier,
onBarcodeDetected: (barcodes: List<Barcode>) -> Unit,
onBarcodeFailed: (exception: Exception) -> Unit,
onBarcodeNotFound: (text: String) -> Unit,
) {
val context = LocalContext.current
val lifecycleOwner = LocalLifecycleOwner.current
AndroidView(
modifier = modifier.fillMaxSize(),
factory = { androidViewContext -> initPreviewView(androidViewContext) },
update = { previewView: PreviewView ->
val cameraSelector: CameraSelector = buildCameraSelector(CameraSelector.LENS_FACING_BACK)
val cameraExecutor: ExecutorService = Executors.newSingleThreadExecutor()
val cameraProviderFuture: ListenableFuture<ProcessCameraProvider> =
ProcessCameraProvider.getInstance(context)
val preview = buildPreview().also {
it.setSurfaceProvider(previewView.surfaceProvider)
}
val barcodeAnalyser = BarCodeAnalyser(
onBarcodeDetected = onBarcodeDetected,
onBarcodeFailed = onBarcodeFailed,
onBarCodeNotFound = onBarcodeNotFound
)
val imageAnalysis: ImageAnalysis =
buildImageAnalysis(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST).also {
it.setAnalyzer(cameraExecutor, barcodeAnalyser)
}
cameraProviderFuture.addListener({
val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
try {
cameraProvider.unbindAll() //Make sure we only use 1 usecase related to camera
val camera = cameraProvider.bindToLifecycle(
lifecycleOwner,
cameraSelector,
preview,
imageAnalysis
)
camera.cameraControl.enableTorch(true)
} catch (e: Exception) {
Log.d("TAG", "CameraPreview: ${e.localizedMessage}")
}
}, ContextCompat.getMainExecutor(context))
}
)
}
private fun initPreviewView(androidViewContext: Context): PreviewView {
val previewView = PreviewView(androidViewContext).apply {
implementationMode = PreviewView.ImplementationMode.COMPATIBLE
}
return previewView
}
private fun buildPreview(): Preview {
return Preview.Builder().build()
}
private fun buildImageAnalysis(imageAnalysisStrategy: Int): ImageAnalysis {
return ImageAnalysis.Builder()
.setBackpressureStrategy(imageAnalysisStrategy)
.build()
}
private fun buildCameraSelector(cameraLens: Int): CameraSelector {
return CameraSelector.Builder()
.requireLensFacing(cameraLens)
.build()
}
</code></pre>
<p>What I tried:
I tried passing down the state of BottomSheetState to the composable, and checking for state, which should triggers re-composition, but since I'm using Android's Camera as View, this doesn't solve the problem</p>
|
[
{
"answer_id": 74592261,
"author": "Mark S. Khalil",
"author_id": 10993327,
"author_profile": "https://Stackoverflow.com/users/10993327",
"pm_score": 1,
"selected": false,
"text": "var showCamera by remember {mutableStateOf(false)}\n val modalBottomSheetState = rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)\nval scope = rememberCoroutineScope()\nLaunchedEffect(modalBottomSheetState.currentValue) {\n println(modalBottomSheetState.currentValue)\n}\nif (modalBottomSheetState.currentValue != ModalBottomSheetValue.Hidden) {\n DisposableEffect(Unit) {\n onDispose {\n }\n }\n}\n if(showcamera){\nAndroidView(\n modifier = modifier.fillMaxSize(),\n factory = { androidViewContext -> initPreviewView(androidViewContext) },\n update = { previewView: PreviewView ->........\nlast of android view camera\n}\n"
},
{
"answer_id": 74605151,
"author": "devMohaned",
"author_id": 11558444,
"author_profile": "https://Stackoverflow.com/users/11558444",
"pm_score": 1,
"selected": true,
"text": "DisposableEffect CameraPreview ProcessCameraProvider var cameraProvider: ProcessCameraProvider? = null\n DisposableEffect cameraProvider DisposableEffect(key1 = cameraProvider) {\n onDispose {\n cameraProvider?.let { it.unbindAll() } // closes the camera\n }\n}\n val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()\n cameraProvider cameraProvider = cameraProviderFuture.get()\n try-catch try {\n cameraProvider?.let {\n it.unbindAll() //Make sure we only use 1 usecase related to camera\n\n val camera = it.bindToLifecycle(\n lifecycleOwner, cameraSelector, preview, imageAnalysis\n )\n\n camera.cameraControl.enableTorch(true) // TODO: Debug mode only\n }\n\n\n} catch (e: Exception) {\n Log.d(\"TAG\", \"CameraPreview: ${e.localizedMessage}\")\n}\n @Composable\nfun CameraPreview( \n modifier: Modifier = Modifier,\n onBarcodeDetected: (barcodes: List<Barcode>) -> Unit,\n onBarcodeFailed: (exception: Exception) -> Unit,\n onBarcodeNotFound: (text: String) -> Unit,\n) {\n val context = LocalContext.current\n val lifecycleOwner = LocalLifecycleOwner.current\n\n var cameraProvider: ProcessCameraProvider? = null\n DisposableEffect(key1 = cameraProvider) {\n onDispose {\n cameraProvider?.let { it.unbindAll() }\n }\n }\n\n AndroidView(\n modifier = modifier.fillMaxSize(),\n factory = { androidViewContext -> initPreviewView(androidViewContext) },\n update = { previewView: PreviewView ->\n val cameraSelector: CameraSelector =\n buildCameraSelector(CameraSelector.LENS_FACING_BACK)\n val cameraExecutor: ExecutorService = Executors.newSingleThreadExecutor()\n val cameraProviderFuture: ListenableFuture<ProcessCameraProvider> =\n ProcessCameraProvider.getInstance(context)\n\n\n cameraProviderFuture.addListener({\n cameraProvider = cameraProviderFuture.get()\n\n val preview = buildPreview().also {\n it.setSurfaceProvider(previewView.surfaceProvider)\n }\n\n\n val barcodeAnalyser = BarCodeAnalyser(\n onBarcodeDetected = onBarcodeDetected,\n onBarcodeFailed = onBarcodeFailed,\n onBarCodeNotFound = onBarcodeNotFound\n )\n val imageAnalysis: ImageAnalysis =\n buildImageAnalysis(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST).also {\n it.setAnalyzer(cameraExecutor, barcodeAnalyser)\n }\n\n\n\n try {\n cameraProvider?.let {\n it.unbindAll() //Make sure we only use 1 usecase related to camera\n\n val camera = it.bindToLifecycle(\n lifecycleOwner, cameraSelector, preview, imageAnalysis\n )\n\n camera.cameraControl.enableTorch(true) // TODO: Debug mode only\n } \n\n\n } catch (e: Exception) {\n Log.d(\"TAG\", \"CameraPreview: ${e.localizedMessage}\")\n }\n }, ContextCompat.getMainExecutor(context))\n }\n )\n\n\n}\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11558444/"
] |
74,591,913
|
<p>I am trying to write a VBA function where I produce a new sheet, give a lists of all the sheet names in the workbook and match the cell color of the sheet name, with the tab color of the sheet name. The pseudocode will look something like this:</p>
<p>Create a new sheet
Loop through all sheets in the workbook
Write down the sheet name in the created sheet
Retrieve the sheet ThemeColor (e.g. xlThemeColorLight2)
Retrieve the sheet TintAndShade (e.g. 0.799981688894314
Set the cell in which the name of the sheet is to the correct ThemeColor and TintAndShade
End</p>
<p>Is there a way in which this is possible?</p>
<pre><code>Sub SheetList()
Dim ws As Worksheet
Dim x As Integer
x = 1
Sheets.Add
sheet_name = InputBox("Please enter a sheet name")
ActiveSheet.Name = sheet_name # Create a new sheet name
For Each ws In Worksheets
Sheets(sheet_name).Cells(x, 1) = ws.Name # Set cell value to sheet name
Dim theme_color As String
Dim tint_and_shade As Single
theme_color = ... # Attain sheet ThemeColor of current ws here
tint_and_shade = ... # Attain sheet TintAndShade of current ws here
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = theme_color # Set current cell to theme_color
.TintAndShade = tint_and_shade # Set current cell to tint_and_shade
.PatternTintAndShade = 0
End With
x = x + 1
Next ws
</code></pre>
|
[
{
"answer_id": 74592261,
"author": "Mark S. Khalil",
"author_id": 10993327,
"author_profile": "https://Stackoverflow.com/users/10993327",
"pm_score": 1,
"selected": false,
"text": "var showCamera by remember {mutableStateOf(false)}\n val modalBottomSheetState = rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)\nval scope = rememberCoroutineScope()\nLaunchedEffect(modalBottomSheetState.currentValue) {\n println(modalBottomSheetState.currentValue)\n}\nif (modalBottomSheetState.currentValue != ModalBottomSheetValue.Hidden) {\n DisposableEffect(Unit) {\n onDispose {\n }\n }\n}\n if(showcamera){\nAndroidView(\n modifier = modifier.fillMaxSize(),\n factory = { androidViewContext -> initPreviewView(androidViewContext) },\n update = { previewView: PreviewView ->........\nlast of android view camera\n}\n"
},
{
"answer_id": 74605151,
"author": "devMohaned",
"author_id": 11558444,
"author_profile": "https://Stackoverflow.com/users/11558444",
"pm_score": 1,
"selected": true,
"text": "DisposableEffect CameraPreview ProcessCameraProvider var cameraProvider: ProcessCameraProvider? = null\n DisposableEffect cameraProvider DisposableEffect(key1 = cameraProvider) {\n onDispose {\n cameraProvider?.let { it.unbindAll() } // closes the camera\n }\n}\n val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()\n cameraProvider cameraProvider = cameraProviderFuture.get()\n try-catch try {\n cameraProvider?.let {\n it.unbindAll() //Make sure we only use 1 usecase related to camera\n\n val camera = it.bindToLifecycle(\n lifecycleOwner, cameraSelector, preview, imageAnalysis\n )\n\n camera.cameraControl.enableTorch(true) // TODO: Debug mode only\n }\n\n\n} catch (e: Exception) {\n Log.d(\"TAG\", \"CameraPreview: ${e.localizedMessage}\")\n}\n @Composable\nfun CameraPreview( \n modifier: Modifier = Modifier,\n onBarcodeDetected: (barcodes: List<Barcode>) -> Unit,\n onBarcodeFailed: (exception: Exception) -> Unit,\n onBarcodeNotFound: (text: String) -> Unit,\n) {\n val context = LocalContext.current\n val lifecycleOwner = LocalLifecycleOwner.current\n\n var cameraProvider: ProcessCameraProvider? = null\n DisposableEffect(key1 = cameraProvider) {\n onDispose {\n cameraProvider?.let { it.unbindAll() }\n }\n }\n\n AndroidView(\n modifier = modifier.fillMaxSize(),\n factory = { androidViewContext -> initPreviewView(androidViewContext) },\n update = { previewView: PreviewView ->\n val cameraSelector: CameraSelector =\n buildCameraSelector(CameraSelector.LENS_FACING_BACK)\n val cameraExecutor: ExecutorService = Executors.newSingleThreadExecutor()\n val cameraProviderFuture: ListenableFuture<ProcessCameraProvider> =\n ProcessCameraProvider.getInstance(context)\n\n\n cameraProviderFuture.addListener({\n cameraProvider = cameraProviderFuture.get()\n\n val preview = buildPreview().also {\n it.setSurfaceProvider(previewView.surfaceProvider)\n }\n\n\n val barcodeAnalyser = BarCodeAnalyser(\n onBarcodeDetected = onBarcodeDetected,\n onBarcodeFailed = onBarcodeFailed,\n onBarCodeNotFound = onBarcodeNotFound\n )\n val imageAnalysis: ImageAnalysis =\n buildImageAnalysis(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST).also {\n it.setAnalyzer(cameraExecutor, barcodeAnalyser)\n }\n\n\n\n try {\n cameraProvider?.let {\n it.unbindAll() //Make sure we only use 1 usecase related to camera\n\n val camera = it.bindToLifecycle(\n lifecycleOwner, cameraSelector, preview, imageAnalysis\n )\n\n camera.cameraControl.enableTorch(true) // TODO: Debug mode only\n } \n\n\n } catch (e: Exception) {\n Log.d(\"TAG\", \"CameraPreview: ${e.localizedMessage}\")\n }\n }, ContextCompat.getMainExecutor(context))\n }\n )\n\n\n}\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12168276/"
] |
74,591,934
|
<p>I am trying to compare elements of two arrays according their order
for example:</p>
<pre><code>int a[] = { 1, 2, 3 };
int b[] = { 1, 2, 4 };
</code></pre>
<p>Having 3 elements there is no problem with a <code>for</code>-loop and condition</p>
<pre><code>if (a[0] == b[0] && a[1] == b[1] && a[2] == b[2])
</code></pre>
<p>But how can I do the same with n elements in arrays?
The condition should looks like: <code>if (a[0] == b[0] && a[1] == b[1] && a[2] == b[2] && ... && a[n] == b[n])</code> but it's inappropriate.</p>
<pre><code>// Comparing elements of two one-dimensional arrays with
// equal sets of elements according their order.
#include <stdio.h>
int main(void) {
// two one-dimensional arrays with 3 elements for example
int a[] = { 1, 2, 3 };
int b[] = { 1, 2, 4 };
// comparing elements:
for (int i = 0; i < 3; i++) {
if (a[0] == b[0] && a[1] == b[1] && a[2] == b[2]) // but if I have n - elements the problem appears
{
printf("all right\n");
}
else
{
printf("no all right\n");
}
}
}
</code></pre>
|
[
{
"answer_id": 74592261,
"author": "Mark S. Khalil",
"author_id": 10993327,
"author_profile": "https://Stackoverflow.com/users/10993327",
"pm_score": 1,
"selected": false,
"text": "var showCamera by remember {mutableStateOf(false)}\n val modalBottomSheetState = rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)\nval scope = rememberCoroutineScope()\nLaunchedEffect(modalBottomSheetState.currentValue) {\n println(modalBottomSheetState.currentValue)\n}\nif (modalBottomSheetState.currentValue != ModalBottomSheetValue.Hidden) {\n DisposableEffect(Unit) {\n onDispose {\n }\n }\n}\n if(showcamera){\nAndroidView(\n modifier = modifier.fillMaxSize(),\n factory = { androidViewContext -> initPreviewView(androidViewContext) },\n update = { previewView: PreviewView ->........\nlast of android view camera\n}\n"
},
{
"answer_id": 74605151,
"author": "devMohaned",
"author_id": 11558444,
"author_profile": "https://Stackoverflow.com/users/11558444",
"pm_score": 1,
"selected": true,
"text": "DisposableEffect CameraPreview ProcessCameraProvider var cameraProvider: ProcessCameraProvider? = null\n DisposableEffect cameraProvider DisposableEffect(key1 = cameraProvider) {\n onDispose {\n cameraProvider?.let { it.unbindAll() } // closes the camera\n }\n}\n val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()\n cameraProvider cameraProvider = cameraProviderFuture.get()\n try-catch try {\n cameraProvider?.let {\n it.unbindAll() //Make sure we only use 1 usecase related to camera\n\n val camera = it.bindToLifecycle(\n lifecycleOwner, cameraSelector, preview, imageAnalysis\n )\n\n camera.cameraControl.enableTorch(true) // TODO: Debug mode only\n }\n\n\n} catch (e: Exception) {\n Log.d(\"TAG\", \"CameraPreview: ${e.localizedMessage}\")\n}\n @Composable\nfun CameraPreview( \n modifier: Modifier = Modifier,\n onBarcodeDetected: (barcodes: List<Barcode>) -> Unit,\n onBarcodeFailed: (exception: Exception) -> Unit,\n onBarcodeNotFound: (text: String) -> Unit,\n) {\n val context = LocalContext.current\n val lifecycleOwner = LocalLifecycleOwner.current\n\n var cameraProvider: ProcessCameraProvider? = null\n DisposableEffect(key1 = cameraProvider) {\n onDispose {\n cameraProvider?.let { it.unbindAll() }\n }\n }\n\n AndroidView(\n modifier = modifier.fillMaxSize(),\n factory = { androidViewContext -> initPreviewView(androidViewContext) },\n update = { previewView: PreviewView ->\n val cameraSelector: CameraSelector =\n buildCameraSelector(CameraSelector.LENS_FACING_BACK)\n val cameraExecutor: ExecutorService = Executors.newSingleThreadExecutor()\n val cameraProviderFuture: ListenableFuture<ProcessCameraProvider> =\n ProcessCameraProvider.getInstance(context)\n\n\n cameraProviderFuture.addListener({\n cameraProvider = cameraProviderFuture.get()\n\n val preview = buildPreview().also {\n it.setSurfaceProvider(previewView.surfaceProvider)\n }\n\n\n val barcodeAnalyser = BarCodeAnalyser(\n onBarcodeDetected = onBarcodeDetected,\n onBarcodeFailed = onBarcodeFailed,\n onBarCodeNotFound = onBarcodeNotFound\n )\n val imageAnalysis: ImageAnalysis =\n buildImageAnalysis(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST).also {\n it.setAnalyzer(cameraExecutor, barcodeAnalyser)\n }\n\n\n\n try {\n cameraProvider?.let {\n it.unbindAll() //Make sure we only use 1 usecase related to camera\n\n val camera = it.bindToLifecycle(\n lifecycleOwner, cameraSelector, preview, imageAnalysis\n )\n\n camera.cameraControl.enableTorch(true) // TODO: Debug mode only\n } \n\n\n } catch (e: Exception) {\n Log.d(\"TAG\", \"CameraPreview: ${e.localizedMessage}\")\n }\n }, ContextCompat.getMainExecutor(context))\n }\n )\n\n\n}\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17621042/"
] |
74,591,950
|
<p>I'am beginner at frontend, and got some design-layout to train. Designer expects that on hover part of string or even letter will change color <a href="https://i.stack.imgur.com/3ThDQ.jpg" rel="nofollow noreferrer">Example</a></p>
<p>I thought about CSS 'clip', but doubt</p>
|
[
{
"answer_id": 74592261,
"author": "Mark S. Khalil",
"author_id": 10993327,
"author_profile": "https://Stackoverflow.com/users/10993327",
"pm_score": 1,
"selected": false,
"text": "var showCamera by remember {mutableStateOf(false)}\n val modalBottomSheetState = rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)\nval scope = rememberCoroutineScope()\nLaunchedEffect(modalBottomSheetState.currentValue) {\n println(modalBottomSheetState.currentValue)\n}\nif (modalBottomSheetState.currentValue != ModalBottomSheetValue.Hidden) {\n DisposableEffect(Unit) {\n onDispose {\n }\n }\n}\n if(showcamera){\nAndroidView(\n modifier = modifier.fillMaxSize(),\n factory = { androidViewContext -> initPreviewView(androidViewContext) },\n update = { previewView: PreviewView ->........\nlast of android view camera\n}\n"
},
{
"answer_id": 74605151,
"author": "devMohaned",
"author_id": 11558444,
"author_profile": "https://Stackoverflow.com/users/11558444",
"pm_score": 1,
"selected": true,
"text": "DisposableEffect CameraPreview ProcessCameraProvider var cameraProvider: ProcessCameraProvider? = null\n DisposableEffect cameraProvider DisposableEffect(key1 = cameraProvider) {\n onDispose {\n cameraProvider?.let { it.unbindAll() } // closes the camera\n }\n}\n val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()\n cameraProvider cameraProvider = cameraProviderFuture.get()\n try-catch try {\n cameraProvider?.let {\n it.unbindAll() //Make sure we only use 1 usecase related to camera\n\n val camera = it.bindToLifecycle(\n lifecycleOwner, cameraSelector, preview, imageAnalysis\n )\n\n camera.cameraControl.enableTorch(true) // TODO: Debug mode only\n }\n\n\n} catch (e: Exception) {\n Log.d(\"TAG\", \"CameraPreview: ${e.localizedMessage}\")\n}\n @Composable\nfun CameraPreview( \n modifier: Modifier = Modifier,\n onBarcodeDetected: (barcodes: List<Barcode>) -> Unit,\n onBarcodeFailed: (exception: Exception) -> Unit,\n onBarcodeNotFound: (text: String) -> Unit,\n) {\n val context = LocalContext.current\n val lifecycleOwner = LocalLifecycleOwner.current\n\n var cameraProvider: ProcessCameraProvider? = null\n DisposableEffect(key1 = cameraProvider) {\n onDispose {\n cameraProvider?.let { it.unbindAll() }\n }\n }\n\n AndroidView(\n modifier = modifier.fillMaxSize(),\n factory = { androidViewContext -> initPreviewView(androidViewContext) },\n update = { previewView: PreviewView ->\n val cameraSelector: CameraSelector =\n buildCameraSelector(CameraSelector.LENS_FACING_BACK)\n val cameraExecutor: ExecutorService = Executors.newSingleThreadExecutor()\n val cameraProviderFuture: ListenableFuture<ProcessCameraProvider> =\n ProcessCameraProvider.getInstance(context)\n\n\n cameraProviderFuture.addListener({\n cameraProvider = cameraProviderFuture.get()\n\n val preview = buildPreview().also {\n it.setSurfaceProvider(previewView.surfaceProvider)\n }\n\n\n val barcodeAnalyser = BarCodeAnalyser(\n onBarcodeDetected = onBarcodeDetected,\n onBarcodeFailed = onBarcodeFailed,\n onBarCodeNotFound = onBarcodeNotFound\n )\n val imageAnalysis: ImageAnalysis =\n buildImageAnalysis(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST).also {\n it.setAnalyzer(cameraExecutor, barcodeAnalyser)\n }\n\n\n\n try {\n cameraProvider?.let {\n it.unbindAll() //Make sure we only use 1 usecase related to camera\n\n val camera = it.bindToLifecycle(\n lifecycleOwner, cameraSelector, preview, imageAnalysis\n )\n\n camera.cameraControl.enableTorch(true) // TODO: Debug mode only\n } \n\n\n } catch (e: Exception) {\n Log.d(\"TAG\", \"CameraPreview: ${e.localizedMessage}\")\n }\n }, ContextCompat.getMainExecutor(context))\n }\n )\n\n\n}\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19772640/"
] |
74,591,954
|
<p>I am trying to query a MySQL database and display the results on a php webpage as below ,</p>
<p><a href="https://i.stack.imgur.com/I1epF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/I1epF.png" alt="enter image description here" /></a> however i get the error Parse error: syntax error, unexpected 'position' (T_STRING) in C:\wamp64\www\webform\display-data.php on line 5.Below is my PHP code</p>
<pre><code><?php
$mysqli = mysqli_connect('localhost','staff','staff','webform');
$query ="SELECT position FROM entries";
$result = $mysqli->query($query);
if($result->num_rows> 0){
$options= mysqli_fetch_all($result, MYSQLI_ASSOC);
}
<?php
<?php
include("dbconfig.php");
include("fetch-data.php");
?>
<select name="position">
<option>Select staff</option>
<?php
foreach ($options as $option) {
?>
<option><?php echo $option['position']; ?> </option>
<?php
}
?>
</select>
</code></pre>
|
[
{
"answer_id": 74595291,
"author": "Bob D. Builder",
"author_id": 8274730,
"author_profile": "https://Stackoverflow.com/users/8274730",
"pm_score": 0,
"selected": false,
"text": "<select name=\"position\">\n <option>Select staff</option>\n <?php \n foreach ($options as $option) {\n echo \"<option>$option['position'];</option>\";\n }\n ?>\n</select>\n value='$option['position'];'"
},
{
"answer_id": 74596219,
"author": "CHMAV",
"author_id": 20436894,
"author_profile": "https://Stackoverflow.com/users/20436894",
"pm_score": -1,
"selected": false,
"text": "<?php\ninclude(\"dbconfig.php\");\ninclude(\"fetch-data.php\");\n\necho'<select name=\"position\">\n <option>Select staff</option>'; \n foreach ($options as $option) { \n echo'<option value='.$option['position'].'>'.$option['position'].'</option>';\n } \necho'</select>';\n"
},
{
"answer_id": 74601576,
"author": "Ajju Bhai",
"author_id": 20580686,
"author_profile": "https://Stackoverflow.com/users/20580686",
"pm_score": -1,
"selected": false,
"text": "<!-- Database connection file code (dbconfig.php) -->\n<?php\n// $mysqli=mysqli_connect(hostname, username, password, databaname)\n$mysqli = mysqli_connect('localhost', 'staff', 'staff', 'webform');\n?>\n\n<!-- Fetch data file code (fetch-data.php) -->\n<?php\n$query = \"SELECT position FROM entries\";\n$result = $mysqli->query($query);\nif ($result->num_rows > 0) {\n $options = mysqli_fetch_all($result, MYSQLI_ASSOC);\n}\n?>\n\n<!-- Your display dropdown file -->\n<?php\ninclude(\"dbconfig.php\");\ninclude(\"fetch-data.php\");\n?>\n\n<select name=\"position\">\n <option>Select staff</option>\n <?php\n foreach ($options as $option) {\n ?>\n <option><?php echo $option['position']; ?> </option>\n <?php\n }\n ?>\n</select>\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6791918/"
] |
74,591,960
|
<pre><code>let arr1 =[{name:'mani',age:2},{name:'raj',age:2},{name:'s',age:1}];
let test = new Map();
for(const EI of arr1){
if( !test.has(EI.age)){
test.set(EI.age,new Array());
}
test.set(EI.age,test.get(EI.age).push(EI) );
}
</code></pre>
<p>when i console log this map, the array is empty for all the keys.</p>
<p>but it works as expected for the below code</p>
<pre><code>let arr1 =[3,4,5,6,6,7,8,8,8];
let test = new Map();
for(const EI of arr1){
if( !test.has(EI)){
test.set(EI,1);
continue;
}
test.set(EI,test.get(EI) + 1);
}
</code></pre>
<p>Even i tried taking copy of array test.set(EI,[test.get(EI)].push(1) ) still get empty array only</p>
<p><a href="https://i.stack.imgur.com/VxSZ1.png" rel="nofollow noreferrer">here the result is as expected</a></p>
<p><a href="https://i.stack.imgur.com/sopzx.png" rel="nofollow noreferrer">array is empty here .....</a></p>
|
[
{
"answer_id": 74592014,
"author": "ray",
"author_id": 636077,
"author_profile": "https://Stackoverflow.com/users/636077",
"pm_score": 3,
"selected": true,
"text": "push test.set(EI.age,test.get(EI.age).push(EI) );\n EI.age continue"
},
{
"answer_id": 74592068,
"author": "AryaveerSR",
"author_id": 20459167,
"author_profile": "https://Stackoverflow.com/users/20459167",
"pm_score": 0,
"selected": false,
"text": "test let arr1 =[{name:'mani',age:2},{name:'raj',age:2},{name:'s',age:1}];\n\nlet test = {};\n\nfor(const EI of arr1){\n if(!test[EI.age]){\n test[EI.age] = [];\n }\n \n test[EI.age].push(EI.name);\n // Or optionally, push the whole object instead\n // test[EI.age].push(EI);\n}\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17814533/"
] |
74,591,978
|
<p>I had my first class of micro code few days back and noticed that some syntax of micro coding Atmel AVR microcontroller is quite similar to that of Assembly Level Language.
However there are some syntax which do not match for common instructions. So are they the same?</p>
<p>For what I know, Assembly Level Language is just a programming language where the compiler translates that to machine language. Where is microcode coming in here?</p>
<p>Also what does the following sentence mean?
"The assembler instruction ADD R1,R0 corresponds to the binary instruction word in Hexadecimal:
OC(for Add) 01 (0001 for register 1 and 0000 for register 0)"</p>
<p>I know that the data/operands in the registers are in hexadecimal during ADD instruction but what is that 0C01?</p>
|
[
{
"answer_id": 74593023,
"author": "jwilo",
"author_id": 20595585,
"author_profile": "https://Stackoverflow.com/users/20595585",
"pm_score": 3,
"selected": true,
"text": "instruction set instruction set"
},
{
"answer_id": 74602563,
"author": "old_timer",
"author_id": 16007,
"author_profile": "https://Stackoverflow.com/users/16007",
"pm_score": 1,
"selected": false,
"text": "model name : AMD FX(tm)-8350 Eight-Core Processor\nstepping : 0\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17010897/"
] |
74,591,999
|
<p>I am trying to verify a credit card number by the steps below:</p>
<ol>
<li><p>Multiply every other digit by 2, starting with the number’s second-to-last digit, and then add those products’ digits together.</p>
</li>
<li><p>Add the sum to the sum of the digits that weren’t multiplied by 2.</p>
</li>
<li><p>Check if the last digit of the sum is 0.</p>
</li>
</ol>
<p>Here is my code. I've tried an AMEX card number <code>371449635398431</code> but it's giving me <code>INVALID</code> so I believe my calculation is incorrect but I've ran over how it would work and I'm not sure what I'm doing wrong.</p>
<p>Thanks in advance for any help!</p>
<pre><code>int main(void)
{
// TODO Prompt for input (DONE)
long cardnumber;
do
{
cardnumber = get_long("Card no: ");
}
while (cardnumber < 0); // Card number must be greater than 0
// TODO Calculate checksum
// Get every other digit
int second = ((cardnumber / 10) % 10);
int fourth = ((cardnumber / 1000) % 10);
int sixth = ((cardnumber / 100000) % 10);
int eighth = ((cardnumber / 10000000) % 10);
int tenth = ((cardnumber / 1000000000) % 10);
int twelth = ((cardnumber / 100000000000) % 10);
int fourteenth = ((cardnumber / 10000000000000) % 10);
int sixteenth = ((cardnumber / 1000000000000000) % 10);
// Multiply every other digit by 2 then add those digits
int checksumpart1 = (second * 2 + fourth * 2 + sixth * 2 + eighth * 2 + tenth * 2 + twelth * 2 + fourteenth * 2 + sixteenth * 2);
// Get every other other digit
int first = (cardnumber % 10);
int third = ((cardnumber / 100) % 10);
int fifth = ((cardnumber / 10000) % 10);
int seventh = ((cardnumber / 1000000) % 10);
int ninth = ((cardnumber / 100000000) % 10);
int eleventh = ((cardnumber / 10000000000) % 10);
int thirteenth = ((cardnumber / 1000000000000) % 10);
int fifteenth = ((cardnumber / 100000000000000) % 10);
// Sum of every other digit
int checksumpart2 = (first + third + fifth + seventh + ninth + eleventh + thirteenth + fifteenth);
// Validity check addition of first two sums
int checksumfinal = ((checksumpart1 + checksumpart2) % 10);
// Print AMEX or INVALID
// validate checksum
if (checksumfinal != 0) {
printf("INVALID\n");
} else {
printf("VALID\n");
}
}
</code></pre>
<p>Ran the program and was provided <code>INVALID</code> even though a valid card number of <code>371449635398431</code> was used.</p>
<p>I believe my calculations are incorrect but I'm not sure where my error is. Any help would be greatly appreciated as I've looked at this repeatedly and cannot figure out where I'm going wrong.</p>
|
[
{
"answer_id": 74592402,
"author": "chqrlie",
"author_id": 4593267,
"author_profile": "https://Stackoverflow.com/users/4593267",
"pm_score": 2,
"selected": false,
"text": "#include <stdio.h>\n#include <cs50.h>\n\nint main(void) {\n // TODO Prompt for input (DONE)\n long cardnumber;\n do {\n cardnumber = get_long(\"Card no: \");\n }\n while (cardnumber < 0); // Card number must be greater than 0\n\n // TODO Calculate checksum\n\n // Get every other digit\n int second = ((cardnumber / 10) % 10);\n int fourth = ((cardnumber / 1000) % 10);\n int sixth = ((cardnumber / 100000) % 10);\n int eighth = ((cardnumber / 10000000) % 10);\n int tenth = ((cardnumber / 1000000000) % 10);\n int twelth = ((cardnumber / 100000000000) % 10);\n int fourteenth = ((cardnumber / 10000000000000) % 10);\n int sixteenth = ((cardnumber / 1000000000000000) % 10);\n\n // Multiply every other digit by 2 then add those digits\n int val[10] = { 0, 2, 4, 6, 8, 1, 3, 5, 7, 9 };\n int checksumpart1 = (val[second] + val[fourth] + val[sixth] + val[eighth] +\n val[tenth] + val[twelth] + val[fourteenth] + val[sixteenth]);\n\n // Get every other other digit\n int first = ((cardnumber / 1) % 10);\n int third = ((cardnumber / 100) % 10);\n int fifth = ((cardnumber / 10000) % 10);\n int seventh = ((cardnumber / 1000000) % 10);\n int ninth = ((cardnumber / 100000000) % 10);\n int eleventh = ((cardnumber / 10000000000) % 10);\n int thirteenth = ((cardnumber / 1000000000000) % 10);\n int fifteenth = ((cardnumber / 100000000000000) % 10);\n\n // Sum of every other digit\n int checksumpart2 = (first + third + fifth + seventh +\n ninth + eleventh + thirteenth + fifteenth);\n\n // Validity check addition of first two sums\n int checksumfinal = (checksumpart1 + checksumpart2) % 10;\n\n // Print AMEX or INVALID\n\n // validate checksum\n if (checksumfinal) {\n printf(\"INVALID\\n\");\n } else {\n printf(\"VALID\\n\");\n }\n return 0;\n}\n #include <stdio.h>\n#include <cs50.h>\n\nint main(void) {\n long cardnumber;\n do {\n cardnumber = get_long(\"Card no: \");\n }\n while (cardnumber < 0); // Card number must be greater than 0\n\n int val[] = { 0, 2, 4, 6, 8, 1, 3, 5, 7, 9 };\n int sum = 0;\n for (long n = cardnumber; n; n /= 100) {\n sum += n % 10 + val[n / 10 % 10];\n }\n // Print AMEX or INVALID\n if (sum % 10)\n printf(\"INVALID\\n\");\n else\n printf(\"VALID\\n\");\n\n return 0;\n}\n long #include <stdio.h>\n#include <string.h>\n#include <cs50.h>\n\nint luhn_check(const char *str) {\n int val[10] = { 0, 2, 4, 6, 8, 1, 3, 5, 7, 9 };\n int sum = 0;\n size_t len = strlen(str);\n for (size_t i = 0; i < len; i++) {\n char c = str[len - i - 1];\n if (c >= '0' && c <= '9') {\n if (i % 2 == 0)\n sum += c - '0';\n else\n sum += val[c - '0'];\n } else {\n return 0;\n }\n }\n return sum % 10 == 0;\n}\n\nint main(void) {\n char *cardnumber = get_string(\"Card no: \");\n // Print AMEX or INVALID\n if (!luhn_check(cardnumber)) {\n printf(\"INVALID\\n\");\n } else {\n printf(\"VALID\\n\");\n }\n return 0;\n}\n"
},
{
"answer_id": 74611581,
"author": "Luis Colorado",
"author_id": 3899431,
"author_profile": "https://Stackoverflow.com/users/3899431",
"pm_score": 0,
"selected": false,
"text": " // Multiply every other digit by 2 then add those digits\n int checksumpart1 = (second * 2 + fourth * 2 + sixth * 2 + eighth * 2 + tenth * 2 + twelth * 2 + fourteenth * 2 + sixteenth * 2);\n int int long unsigned long #include <ctype.h>\n#include <stdio.h>\n#include <string.h>\n\nconst static char luhn_tab[][10] = {\n\n /* state 0, accepting state */\n { 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 },\n { 11, 12, 13, 14, 15, 16, 17, 18, 19, 10 },\n { 12, 13, 14, 15, 16, 17, 18, 19, 10, 11 },\n { 13, 14, 15, 16, 17, 18, 19, 10, 11, 12 },\n { 14, 15, 16, 17, 18, 19, 10, 11, 12, 13 },\n { 15, 16, 17, 18, 19, 10, 11, 12, 13, 14 },\n { 16, 17, 18, 19, 10, 11, 12, 13, 14, 15 },\n { 17, 18, 19, 10, 11, 12, 13, 14, 15, 16 },\n { 18, 19, 10, 11, 12, 13, 14, 15, 16, 17 },\n { 19, 10, 11, 12, 13, 14, 15, 16, 17, 18 },\n\n /* state 10, accepting state */\n { 0, 2, 4, 6, 8, 1, 3, 5, 7, 9 },\n { 1, 3, 5, 7, 9, 2, 4, 6, 8, 0 },\n { 2, 4, 6, 8, 0, 3, 5, 7, 9, 1 },\n { 3, 5, 7, 9, 1, 4, 6, 8, 0, 2 },\n { 4, 6, 8, 0, 2, 5, 7, 9, 1, 3 },\n { 5, 7, 9, 1, 3, 6, 8, 0, 2, 4 },\n { 6, 8, 0, 2, 4, 7, 9, 1, 3, 5 },\n { 7, 9, 1, 3, 5, 8, 0, 2, 4, 6 },\n { 8, 0, 2, 4, 6, 9, 1, 3, 5, 7 },\n { 9, 1, 3, 5, 7, 0, 2, 4, 6, 8 },\n};\n\nconst static int accepting = (1 << 0) | (1 << 10);\n\nint luhn_ok(char *s, size_t s_len)\n{\n s += s_len; /* point to the string end */\n char st = 0; /* automaton state, initially zero */\n while (s_len--) {\n if (isdigit(*--s)) {\n /* operate only on digits, skipping nondigits */\n st = luhn_tab[st][*s - '0'];\n }\n }\n return ((1 << st) & accepting) != 0;\n} /* luhn_ok */\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74591999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20608487/"
] |
74,592,007
|
<p>I'm currently working on an application which needs to automatically generate an HTML page which is based on the data provided by the server side. I have made the current code:
</p>
<pre><code>//Indicator class
class Button_class{
constructor(name)
{
this.buttonAva = false;
this.name = name;
this.buttonIdHTML = '"' + name + "But" + '"'
}
button_action()
{
//This is an abstract method
console.log("foo")
}
//This method creates the button
create_Button()
{
//Make sure that the method is only executed once
if (this.buttonAva == false)
{
//Get the element id
root22 = document.getElementById('root');
//create the HTML code
let html ="<button id="+this.indicatorIdHTML +"type='button' onclick = 'button_action()/> Click Me!";
root22.insertAdjacentHTML("beforeend", html);
html = "<p>"
root22.insertAdjacentHTML("beforeend", html);
}
}
}
//----------------------------------------------------------
//function for setting up the page
function process_init(){
for (let i = 0; i < data.Indicators.length; i++){
//Create the HTML for the indicators
let temp_indi = new Indicator(data.Indicators[i]);
indicators.push(temp_indi);
indicators.push(data.Indicators[i])
//Build the HTML page
indicators[i].create_Indicator()
indicators[i].create_Button()
}
}
</code></pre>
<p>The error i'm getting is the following: button_action is not defined I tried to call the function under THIS^.button_action() but no results here. Is a setup like this even possible in JS, and if yes how could I get this to work? Thank you in advance Greetings Alex</p>
|
[
{
"answer_id": 74592402,
"author": "chqrlie",
"author_id": 4593267,
"author_profile": "https://Stackoverflow.com/users/4593267",
"pm_score": 2,
"selected": false,
"text": "#include <stdio.h>\n#include <cs50.h>\n\nint main(void) {\n // TODO Prompt for input (DONE)\n long cardnumber;\n do {\n cardnumber = get_long(\"Card no: \");\n }\n while (cardnumber < 0); // Card number must be greater than 0\n\n // TODO Calculate checksum\n\n // Get every other digit\n int second = ((cardnumber / 10) % 10);\n int fourth = ((cardnumber / 1000) % 10);\n int sixth = ((cardnumber / 100000) % 10);\n int eighth = ((cardnumber / 10000000) % 10);\n int tenth = ((cardnumber / 1000000000) % 10);\n int twelth = ((cardnumber / 100000000000) % 10);\n int fourteenth = ((cardnumber / 10000000000000) % 10);\n int sixteenth = ((cardnumber / 1000000000000000) % 10);\n\n // Multiply every other digit by 2 then add those digits\n int val[10] = { 0, 2, 4, 6, 8, 1, 3, 5, 7, 9 };\n int checksumpart1 = (val[second] + val[fourth] + val[sixth] + val[eighth] +\n val[tenth] + val[twelth] + val[fourteenth] + val[sixteenth]);\n\n // Get every other other digit\n int first = ((cardnumber / 1) % 10);\n int third = ((cardnumber / 100) % 10);\n int fifth = ((cardnumber / 10000) % 10);\n int seventh = ((cardnumber / 1000000) % 10);\n int ninth = ((cardnumber / 100000000) % 10);\n int eleventh = ((cardnumber / 10000000000) % 10);\n int thirteenth = ((cardnumber / 1000000000000) % 10);\n int fifteenth = ((cardnumber / 100000000000000) % 10);\n\n // Sum of every other digit\n int checksumpart2 = (first + third + fifth + seventh +\n ninth + eleventh + thirteenth + fifteenth);\n\n // Validity check addition of first two sums\n int checksumfinal = (checksumpart1 + checksumpart2) % 10;\n\n // Print AMEX or INVALID\n\n // validate checksum\n if (checksumfinal) {\n printf(\"INVALID\\n\");\n } else {\n printf(\"VALID\\n\");\n }\n return 0;\n}\n #include <stdio.h>\n#include <cs50.h>\n\nint main(void) {\n long cardnumber;\n do {\n cardnumber = get_long(\"Card no: \");\n }\n while (cardnumber < 0); // Card number must be greater than 0\n\n int val[] = { 0, 2, 4, 6, 8, 1, 3, 5, 7, 9 };\n int sum = 0;\n for (long n = cardnumber; n; n /= 100) {\n sum += n % 10 + val[n / 10 % 10];\n }\n // Print AMEX or INVALID\n if (sum % 10)\n printf(\"INVALID\\n\");\n else\n printf(\"VALID\\n\");\n\n return 0;\n}\n long #include <stdio.h>\n#include <string.h>\n#include <cs50.h>\n\nint luhn_check(const char *str) {\n int val[10] = { 0, 2, 4, 6, 8, 1, 3, 5, 7, 9 };\n int sum = 0;\n size_t len = strlen(str);\n for (size_t i = 0; i < len; i++) {\n char c = str[len - i - 1];\n if (c >= '0' && c <= '9') {\n if (i % 2 == 0)\n sum += c - '0';\n else\n sum += val[c - '0'];\n } else {\n return 0;\n }\n }\n return sum % 10 == 0;\n}\n\nint main(void) {\n char *cardnumber = get_string(\"Card no: \");\n // Print AMEX or INVALID\n if (!luhn_check(cardnumber)) {\n printf(\"INVALID\\n\");\n } else {\n printf(\"VALID\\n\");\n }\n return 0;\n}\n"
},
{
"answer_id": 74611581,
"author": "Luis Colorado",
"author_id": 3899431,
"author_profile": "https://Stackoverflow.com/users/3899431",
"pm_score": 0,
"selected": false,
"text": " // Multiply every other digit by 2 then add those digits\n int checksumpart1 = (second * 2 + fourth * 2 + sixth * 2 + eighth * 2 + tenth * 2 + twelth * 2 + fourteenth * 2 + sixteenth * 2);\n int int long unsigned long #include <ctype.h>\n#include <stdio.h>\n#include <string.h>\n\nconst static char luhn_tab[][10] = {\n\n /* state 0, accepting state */\n { 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 },\n { 11, 12, 13, 14, 15, 16, 17, 18, 19, 10 },\n { 12, 13, 14, 15, 16, 17, 18, 19, 10, 11 },\n { 13, 14, 15, 16, 17, 18, 19, 10, 11, 12 },\n { 14, 15, 16, 17, 18, 19, 10, 11, 12, 13 },\n { 15, 16, 17, 18, 19, 10, 11, 12, 13, 14 },\n { 16, 17, 18, 19, 10, 11, 12, 13, 14, 15 },\n { 17, 18, 19, 10, 11, 12, 13, 14, 15, 16 },\n { 18, 19, 10, 11, 12, 13, 14, 15, 16, 17 },\n { 19, 10, 11, 12, 13, 14, 15, 16, 17, 18 },\n\n /* state 10, accepting state */\n { 0, 2, 4, 6, 8, 1, 3, 5, 7, 9 },\n { 1, 3, 5, 7, 9, 2, 4, 6, 8, 0 },\n { 2, 4, 6, 8, 0, 3, 5, 7, 9, 1 },\n { 3, 5, 7, 9, 1, 4, 6, 8, 0, 2 },\n { 4, 6, 8, 0, 2, 5, 7, 9, 1, 3 },\n { 5, 7, 9, 1, 3, 6, 8, 0, 2, 4 },\n { 6, 8, 0, 2, 4, 7, 9, 1, 3, 5 },\n { 7, 9, 1, 3, 5, 8, 0, 2, 4, 6 },\n { 8, 0, 2, 4, 6, 9, 1, 3, 5, 7 },\n { 9, 1, 3, 5, 7, 0, 2, 4, 6, 8 },\n};\n\nconst static int accepting = (1 << 0) | (1 << 10);\n\nint luhn_ok(char *s, size_t s_len)\n{\n s += s_len; /* point to the string end */\n char st = 0; /* automaton state, initially zero */\n while (s_len--) {\n if (isdigit(*--s)) {\n /* operate only on digits, skipping nondigits */\n st = luhn_tab[st][*s - '0'];\n }\n }\n return ((1 << st) & accepting) != 0;\n} /* luhn_ok */\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20616006/"
] |
74,592,035
|
<p>Trying to develop masking for email address using reg expression but not able to achieve the desired result.</p>
<p>Input : harrypotter@howarts.com</p>
<p>After masking I am looking for result something like this:</p>
<pre><code>Output: "ha*****er@how*****.com"
</code></pre>
<p>What I tried is this reg expression:</p>
<pre><code>(?<=.)[^@\n](?=[^@\n]*?[^@\n]@)|(?:(?<=@.)|(?!^)\G(?=[^@\n]*$)).(?=.*\.)
h*********r@h******.com
</code></pre>
|
[
{
"answer_id": 74592402,
"author": "chqrlie",
"author_id": 4593267,
"author_profile": "https://Stackoverflow.com/users/4593267",
"pm_score": 2,
"selected": false,
"text": "#include <stdio.h>\n#include <cs50.h>\n\nint main(void) {\n // TODO Prompt for input (DONE)\n long cardnumber;\n do {\n cardnumber = get_long(\"Card no: \");\n }\n while (cardnumber < 0); // Card number must be greater than 0\n\n // TODO Calculate checksum\n\n // Get every other digit\n int second = ((cardnumber / 10) % 10);\n int fourth = ((cardnumber / 1000) % 10);\n int sixth = ((cardnumber / 100000) % 10);\n int eighth = ((cardnumber / 10000000) % 10);\n int tenth = ((cardnumber / 1000000000) % 10);\n int twelth = ((cardnumber / 100000000000) % 10);\n int fourteenth = ((cardnumber / 10000000000000) % 10);\n int sixteenth = ((cardnumber / 1000000000000000) % 10);\n\n // Multiply every other digit by 2 then add those digits\n int val[10] = { 0, 2, 4, 6, 8, 1, 3, 5, 7, 9 };\n int checksumpart1 = (val[second] + val[fourth] + val[sixth] + val[eighth] +\n val[tenth] + val[twelth] + val[fourteenth] + val[sixteenth]);\n\n // Get every other other digit\n int first = ((cardnumber / 1) % 10);\n int third = ((cardnumber / 100) % 10);\n int fifth = ((cardnumber / 10000) % 10);\n int seventh = ((cardnumber / 1000000) % 10);\n int ninth = ((cardnumber / 100000000) % 10);\n int eleventh = ((cardnumber / 10000000000) % 10);\n int thirteenth = ((cardnumber / 1000000000000) % 10);\n int fifteenth = ((cardnumber / 100000000000000) % 10);\n\n // Sum of every other digit\n int checksumpart2 = (first + third + fifth + seventh +\n ninth + eleventh + thirteenth + fifteenth);\n\n // Validity check addition of first two sums\n int checksumfinal = (checksumpart1 + checksumpart2) % 10;\n\n // Print AMEX or INVALID\n\n // validate checksum\n if (checksumfinal) {\n printf(\"INVALID\\n\");\n } else {\n printf(\"VALID\\n\");\n }\n return 0;\n}\n #include <stdio.h>\n#include <cs50.h>\n\nint main(void) {\n long cardnumber;\n do {\n cardnumber = get_long(\"Card no: \");\n }\n while (cardnumber < 0); // Card number must be greater than 0\n\n int val[] = { 0, 2, 4, 6, 8, 1, 3, 5, 7, 9 };\n int sum = 0;\n for (long n = cardnumber; n; n /= 100) {\n sum += n % 10 + val[n / 10 % 10];\n }\n // Print AMEX or INVALID\n if (sum % 10)\n printf(\"INVALID\\n\");\n else\n printf(\"VALID\\n\");\n\n return 0;\n}\n long #include <stdio.h>\n#include <string.h>\n#include <cs50.h>\n\nint luhn_check(const char *str) {\n int val[10] = { 0, 2, 4, 6, 8, 1, 3, 5, 7, 9 };\n int sum = 0;\n size_t len = strlen(str);\n for (size_t i = 0; i < len; i++) {\n char c = str[len - i - 1];\n if (c >= '0' && c <= '9') {\n if (i % 2 == 0)\n sum += c - '0';\n else\n sum += val[c - '0'];\n } else {\n return 0;\n }\n }\n return sum % 10 == 0;\n}\n\nint main(void) {\n char *cardnumber = get_string(\"Card no: \");\n // Print AMEX or INVALID\n if (!luhn_check(cardnumber)) {\n printf(\"INVALID\\n\");\n } else {\n printf(\"VALID\\n\");\n }\n return 0;\n}\n"
},
{
"answer_id": 74611581,
"author": "Luis Colorado",
"author_id": 3899431,
"author_profile": "https://Stackoverflow.com/users/3899431",
"pm_score": 0,
"selected": false,
"text": " // Multiply every other digit by 2 then add those digits\n int checksumpart1 = (second * 2 + fourth * 2 + sixth * 2 + eighth * 2 + tenth * 2 + twelth * 2 + fourteenth * 2 + sixteenth * 2);\n int int long unsigned long #include <ctype.h>\n#include <stdio.h>\n#include <string.h>\n\nconst static char luhn_tab[][10] = {\n\n /* state 0, accepting state */\n { 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 },\n { 11, 12, 13, 14, 15, 16, 17, 18, 19, 10 },\n { 12, 13, 14, 15, 16, 17, 18, 19, 10, 11 },\n { 13, 14, 15, 16, 17, 18, 19, 10, 11, 12 },\n { 14, 15, 16, 17, 18, 19, 10, 11, 12, 13 },\n { 15, 16, 17, 18, 19, 10, 11, 12, 13, 14 },\n { 16, 17, 18, 19, 10, 11, 12, 13, 14, 15 },\n { 17, 18, 19, 10, 11, 12, 13, 14, 15, 16 },\n { 18, 19, 10, 11, 12, 13, 14, 15, 16, 17 },\n { 19, 10, 11, 12, 13, 14, 15, 16, 17, 18 },\n\n /* state 10, accepting state */\n { 0, 2, 4, 6, 8, 1, 3, 5, 7, 9 },\n { 1, 3, 5, 7, 9, 2, 4, 6, 8, 0 },\n { 2, 4, 6, 8, 0, 3, 5, 7, 9, 1 },\n { 3, 5, 7, 9, 1, 4, 6, 8, 0, 2 },\n { 4, 6, 8, 0, 2, 5, 7, 9, 1, 3 },\n { 5, 7, 9, 1, 3, 6, 8, 0, 2, 4 },\n { 6, 8, 0, 2, 4, 7, 9, 1, 3, 5 },\n { 7, 9, 1, 3, 5, 8, 0, 2, 4, 6 },\n { 8, 0, 2, 4, 6, 9, 1, 3, 5, 7 },\n { 9, 1, 3, 5, 7, 0, 2, 4, 6, 8 },\n};\n\nconst static int accepting = (1 << 0) | (1 << 10);\n\nint luhn_ok(char *s, size_t s_len)\n{\n s += s_len; /* point to the string end */\n char st = 0; /* automaton state, initially zero */\n while (s_len--) {\n if (isdigit(*--s)) {\n /* operate only on digits, skipping nondigits */\n st = luhn_tab[st][*s - '0'];\n }\n }\n return ((1 << st) & accepting) != 0;\n} /* luhn_ok */\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3998075/"
] |
74,592,109
|
<p>I want to do the following multiplication in tensorflow (TF 2.10), but I'm not sure how to.</p>
<p>I have an image tensor <code>a</code>, which is of shape <code>224x224x3</code> and a tensor <code>b</code>, which is of shape <code>224x224xf</code>. I want to multiply (element-wise) <code>a</code> by each 2D matrix of <code>b</code> sliced by <code>f</code> to get a matrix <code>c</code> of shape <code>224x224xf</code>.</p>
<p>So for example, the 1st multiplication would be done as follows:</p>
<p><code>tf.reduce_sum(a * b[:,:,0][:,:,None],axis=-1)</code></p>
<p>(broadcasting + summation, result is shape <code>224x224</code>)</p>
<p>and so on until the <code>f</code>th multiplication. Result would be the aggregation of <code>f</code> matrices of shape <code>224x224</code> in <code>c</code> matrix of shape <code>224x224xf</code>.</p>
<p>I would greatly appreciate help on how to do this using tensorflow functionality.</p>
<p>EDIT: I realize that what I want to do is equivalent to a Conv2D operation with kernel_size=1 and filters=f. Maybe it can help.</p>
|
[
{
"answer_id": 74594142,
"author": "AndrzejO",
"author_id": 7246805,
"author_profile": "https://Stackoverflow.com/users/7246805",
"pm_score": 3,
"selected": true,
"text": "a b X = a[:,:,0:1] * b + a[:,:,1:2] * b + a[:,:,2:3] * b\n (224, 224, f) (X[:, :, 0] == tf.reduce_sum(a * b[:, :, 0][:, :, None], axis=-1)).numpy().all()\n True\n tf.reduce_sum(a, axis=-1, keepdims=True) * b\n"
},
{
"answer_id": 74595080,
"author": "bui",
"author_id": 8990644,
"author_profile": "https://Stackoverflow.com/users/8990644",
"pm_score": 1,
"selected": false,
"text": "tf.reduce_sum(tf.expand_dims(a, axis=-2) * tf.expand_dims(b[..., :f+1], axis=-1), axis=-1)\n a = tf.random.uniform(shape=(224,224,3))\nb = tf.random.uniform(shape=(224,224,10))\nf = 4\nref = None\nfor i in range(f+1):\n if ref is None:\n ref = tf.reduce_sum(a * b[...,i][...,None], axis=-1)[...,None]\n else:\n ref = tf.concat([ref, tf.reduce_sum(a * b[...,i][...,None], axis=-1)[...,None]], axis=-1)\ntf.reduce_all(tf.reduce_sum(tf.expand_dims(a, axis=-2) * tf.expand_dims(b[..., :f+1], axis=-1), axis=-1) == ref)\n\n<tf.Tensor: shape=(), dtype=bool, numpy=True>\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/563130/"
] |
74,592,129
|
<p>Lets say this is the array i want to shuffle randomly, what would be the most efficient way to do so?
How could i populate this kind of array with three specific values (0, 0.5, 1) but in random order each time i start the program?</p>
<p><code>Can i use something like " a[i][j] = rand.nextDouble() " ? </code></p>
<p><code>Double a[][] = {{0, 1, 0.5, 0.5, 0.5},</code>
<code>{0, 1, 0, 1, 1},</code>
<code> {0.5, 1, 0.5, 0.5, 0},</code>
<code> {0, 0.5, 0, 0.5, 0},</code>
<code>{1, 1, 0.5, 1, 1},</code>
<code> {0, 0, 0, 0.5, 0.5},</code>
<code> {0, 0.5, 0, 0, 1}};</code></p>
<p>I tried generating this array with<code>a[i][j] = (rand..nextDouble() * (1-0))+0.5;</code>but it turns out values like 1.2 and 0.3 etc, is there a way to increase random values by 0.5 only? so that they can be in range from 0-1?</p>
<p>Thank you!</p>
|
[
{
"answer_id": 74592425,
"author": "NoobMaster24",
"author_id": 20616387,
"author_profile": "https://Stackoverflow.com/users/20616387",
"pm_score": 1,
"selected": true,
"text": "import java.lang.Math;\n\nclass MainRun {\n public static void main(String[] args) {\n double arr[][] = new double[5][7];\n double num[] = { 0, 0.5, 1, 1.5 };\n\n for (int i = 0; i < 5; i++) {\n for (int j = 0; j < 7; j++) {\n int rand = (int) (Math.floor(Math.random() * 4));\n arr[i][j] = num[rand];\n }\n }\n }\n}\n 0.0 0.0 0.0 0.5 1.5 0.5 0.0 \n0.0 0.5 0.5 1.5 0.5 1.5 1.0\n1.5 0.5 1.5 1.0 1.5 0.0 1.0\n1.0 0.0 1.5 0.5 0.0 1.0 1.5 \n0.5 1.5 0.0 1.5 0.5 0.0 0.0 \n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20616194/"
] |
74,592,145
|
<p>I am using Jinja and Flask blueprints. However, I have issues rendering the child templates (albums.html) when I let it inherit from the parent (base.html) and get a TemplateNotFound error.</p>
<p>I tried to use relative paths and absolute paths inside <code>{% extends 'path' %}</code> and also googled but didn't find a solution.</p>
<p>My app is structured in this way:</p>
<pre><code>flask/
app.py
statc/
templates/
base.html
blueprints/
albums/
__init__.py
templates/
albums.html
routes.py
</code></pre>
<p>The <code>base.html</code> file is very simple:</p>
<pre><code><!-- language-all: lang-html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>{% block title %}{{ title }}{% endblock%}</title>
<!-- what shows up on search engine -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="static/css/style.css">
</head>
<body>
<header>
{% block header %}
<h1>{{header}}</h1>{% endblock%}
</header>
<main> <h1> Hello </h1> </main>
<footer> Some footer </footer>
</body>
</code></pre>
<p>The child template (<code>albums.html</code>) looks like this:</p>
<pre><code>{% extends "static/templates/base.html" %}
{% block title %}{{title}}{% endblock %}
{% block header %}{{header}} {% endblock %}
</code></pre>
<p>And the <code>routes.py</code> file looks like this:</p>
<pre><code>from flask import Blueprint, render_template, abort, url_for
from jinja2.exceptions import TemplateNotFound
album_page = Blueprint('album_page', __name__,
template_folder='./templates/albums')
@album_page.route('/albums')
def albums():
try:
context = {
'title': 'Albums',
'header': 'Albums'
}
return render_template('albums.html', **context)
except TemplateNotFound:
print('error')
abort(404)
</code></pre>
<p>However I get a <code>TemplateNotFound</code> error. Is there a way to make Jinja search in the <code>static</code> folder outside of the blueprints' package? Thank you.</p>
|
[
{
"answer_id": 74592425,
"author": "NoobMaster24",
"author_id": 20616387,
"author_profile": "https://Stackoverflow.com/users/20616387",
"pm_score": 1,
"selected": true,
"text": "import java.lang.Math;\n\nclass MainRun {\n public static void main(String[] args) {\n double arr[][] = new double[5][7];\n double num[] = { 0, 0.5, 1, 1.5 };\n\n for (int i = 0; i < 5; i++) {\n for (int j = 0; j < 7; j++) {\n int rand = (int) (Math.floor(Math.random() * 4));\n arr[i][j] = num[rand];\n }\n }\n }\n}\n 0.0 0.0 0.0 0.5 1.5 0.5 0.0 \n0.0 0.5 0.5 1.5 0.5 1.5 1.0\n1.5 0.5 1.5 1.0 1.5 0.0 1.0\n1.0 0.0 1.5 0.5 0.0 1.0 1.5 \n0.5 1.5 0.0 1.5 0.5 0.0 0.0 \n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11120421/"
] |
74,592,174
|
<p>I am trying to get the "left" and "top" attributes to be set to the value gotten from "randomXValue" and "randomYValue" the two functions return integers.</p>
<pre><code>randomXValue = getRandomXValue();
randomYValue = getRandomYValue();
$("#gamespace").append(
'<img src="img/img.jpg" class="gameimg" style = "left: (randomXValue)px; top:
(randomYValue)px;"/>'
);
</code></pre>
<p>if I put in an integer instead of the randomValue it will display in the correct location. I am trying to get the image to appear at a random location in the "#gamespace"</p>
|
[
{
"answer_id": 74592211,
"author": "KreutzerCode",
"author_id": 14032911,
"author_profile": "https://Stackoverflow.com/users/14032911",
"pm_score": 2,
"selected": true,
"text": "randomXValue = getRandomXValue();\nrandomYValue = getRandomYValue();\n\n$(\"#gamespace\").append(\n '<img src=\"img/img.jpg\" class=\"gameimg\" style = \"left: \"'+randomXValue+'\"px; top:\"'+randomYValue+'\"px;\"/>'\n);\n"
},
{
"answer_id": 74592297,
"author": "naveen",
"author_id": 17447,
"author_profile": "https://Stackoverflow.com/users/17447",
"pm_score": 2,
"selected": false,
"text": "const left = getRandomXValue();\nconst top = getRandomYValue();\n$(\"#gamespace\").append(\n `<img src=\"img/img.jpg\" class=\"gameimg\" style=\"left:${left}px;top:${top}px;\"/>`\n);\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20616233/"
] |
74,592,265
|
<p>I am getting error. What does it mean by non-conforming parameters in Inprod()</p>
<pre><code>Error in jags.model(model.file, data = data, inits = init.values, n.chains = n.chains, :
RUNTIME ERROR:
Non-conforming parameters in function inprod
</code></pre>
<pre><code>#Jags code
jagsscript <- cat("
model {
# Estimate the initial state vector
for(i in 1:14) {
X[i,1] ~ dnorm(0,1) # weakly informative normal prior
xknot[i] <- X[i,1]
}
# B matrix of interactions
for (r in 3:14){
B[r,1] <- 0
}
for (r in c(2:14)){
B[r,2] <- 0
}
for (r in c(1:2, 4:14)){
B[r,3] <- 0
}
for (r in c(1:3, 5:14)){
B[r,4] <- 0
}
for (r in c(1:4, 6:14)){
B[r,5] <- 0
}
for (r in c(1:5, 7:14)){
B[r,6] <- 0
}
for (r in c(1:6, 8:14)){
B[r,7] <- 0
}
for (r in c(1:7, 9:14)){
B[r,8] <- 0
}
for (r in c(1:8, 10:14)){
B[r,9] <- 0
}
for (r in c(1:9, 11:14)){
B[r,10] <- 0
}
for (r in c(1:10, 12:14)){
B[r,11] <- 0
}
for (r in c(1:11, 13:14)){
B[r,12] <- 0
}
for (r in c(1:12, 14)){
B[r,13] <- 0
}
for (r in c(1:13)){
B[r,14] <- 0
}
B[1, 1] <- phi[1]
B[1, 2] <- phi[2]
B[2, 1] <- 1
for (n in 3:12){
B[n,n] <- rho[n-2]
}
B[13, 13] <- 1
B[14, 14] <- 1
for (n in 1:10){
rho[n] ~ dunif(-1, 1)
}
phi[1] ~ dnorm(0, 1.3)
phi[2] ~ dnorm(0, 1.3)
for (r in 1:10){
Z[r,2] <- 0
}
for (r in 2:11){
Z[r,3] <- 0
}
for (r in c(1, 3:11)){
Z[r,4] <- 0
}
for (r in c(1,2, 4:11)){
Z[r,5] <- 0
}
for (r in c(1:3, 5:11)){
Z[r,6] <- 0
}
for (r in c(1:4, 6:11)){
Z[r,7] <- 0
}
for (r in c(1:5, 7:11)){
Z[r,8] <- 0
}
for (r in c(1:6, 8:11)){
Z[r,9] <- 0
}
for (r in c(1:7, 9:11)){
Z[r,10] <- 0
}
for (r in c(1:8, 10:11)){
Z[r,11] <- 0
}
Z[11,1] <- beta[1]
Z[11,2] <- beta[2]
Z[1, 1] <- ld[1]
Z[2, 1] <- ld[2]
Z[3, 1] <- ld[3]
Z[4, 1] <- ld[4]
Z[5, 1] <- ld[5]
Z[6, 1] <- ld[6]
Z[7, 1] <- ld[7]
Z[8, 1] <- ld[8]
Z[9, 1] <- ld[9]
Z[10, 1] <- ld[10]
Z[11,12] <- 1
Z[1,3] <- 1
Z[2,4] <- 1
Z[3,5] <- 1
Z[4,6] <- 1
Z[5,7] <- 1
Z[6,8] <- 1
Z[7,9] <- 1
Z[8,10] <- 1
Z[9,11] <- 1
Z[10,12] <- 1
Z[11,13] <- 1
beta[1] ~ dbeta(2.21, 12.53)
beta[2] ~ dbeta(2.21, 12.53)
for (i in 1:10){
ld[i] ~ dnorm(0, 1.3)
}
# Autoregressive process
for(t in 2:nYears) {
for(i in 1:14) {
predX[i,t] <- inprod(B[i,], X[,t-1])
X[i,t] ~ dnorm(predX[i,t], tauQ[states[i]])
}
}
tauQ[1] ~ dscaled.gamma(1, 10)
Q1 <- 1 / tauQ[1]
Q2 <- 1 / tauQ[2]
Q2 <- 0
for( i in 3:14){
tauQ[i] ~ dscaled.gamma(1, 10)
}
Q3 <- 1 / tauQ[3]
Q4 <- 1 / tauQ[4]
Q5 <- 1 / tauQ[5]
Q6 <- 1 / tauQ[6]
Q7 <- 1 / tauQ[7]
Q8 <- 1 / tauQ[8]
Q9 <- 1 / tauQ[9]
Q10 <- 1 / tauQ[10]
Q11 <- 1 / tauQ[11]
Q12<- 1 / tauQ[12]
Q13 <- 1 / tauQ[13]
Q14 <- 1 / tauQ[14]
# Observation model
for(t in 1:nYears) {
for(i in 1:11) {
predY[i,t] <- inprod(Z[i,], X[,t])
Y[i,t] ~ dnorm(predY[i,t], tauR[hf[i]])
}
}
for( i in 1:11){
tauR[i] ~ dscaled.gamma(1, 10)
}
R1 <- 1 / tauR[1]
R2 <- 1 / tauR[2]
R3 <- 1 / tauR[3]
R4 <- 1 / tauR[4]
R5 <- 1 / tauR[5]
R6 <- 1 / tauR[6]
R7 <- 1 / tauR[7]
R8 <- 1 / tauR[8]
R9 <- 1 / tauR[9]
R10 <- 1 / tauR[10]
R11 <- 1 / tauR[11]
}
",file="marss-jags.txt")
#putting data
tdat <- t(hf_cycle)
jags.data <- list(Y = tdat,
nYears = ncol(tdat),
states = 1:14, hf = 1:11)
jags.params <- c("ld", "rho", "beta","phi", "xknot", "R1", "R2", "R3", "R4", "R5", "R6", "R7", "R8", "R9", "R10", "R11",
"Q1", "Q2", "Q3", "Q4","Q5","Q6","Q7","Q8","Q9","Q10", "Q11", "Q12","Q13","Q14")
model.loc <- "marss-jags.txt"
#running jags
mod_1 <- jags(jags.data,
parameters.to.save = jags.params,
model.file = model.loc,
n.chains = 2,
n.burnin = 2000,
n.thin = 1,
n.iter = 5000)
</code></pre>
<p>We are trying to estimate the demand index from high frequency indicator using bayesian technique. Specifically, the joint posterior
distribution for the unknown parameters and the unobserved factor can be
sampled using a Markov Chain Monte Carlo procedure on the full set of
conditional distributions</p>
|
[
{
"answer_id": 74592211,
"author": "KreutzerCode",
"author_id": 14032911,
"author_profile": "https://Stackoverflow.com/users/14032911",
"pm_score": 2,
"selected": true,
"text": "randomXValue = getRandomXValue();\nrandomYValue = getRandomYValue();\n\n$(\"#gamespace\").append(\n '<img src=\"img/img.jpg\" class=\"gameimg\" style = \"left: \"'+randomXValue+'\"px; top:\"'+randomYValue+'\"px;\"/>'\n);\n"
},
{
"answer_id": 74592297,
"author": "naveen",
"author_id": 17447,
"author_profile": "https://Stackoverflow.com/users/17447",
"pm_score": 2,
"selected": false,
"text": "const left = getRandomXValue();\nconst top = getRandomYValue();\n$(\"#gamespace\").append(\n `<img src=\"img/img.jpg\" class=\"gameimg\" style=\"left:${left}px;top:${top}px;\"/>`\n);\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7283098/"
] |
74,592,275
|
<p>I am building a Social Network project with Angular, Spring and MySQL.
I am trying to build a system in the backend that takes images and then stores it into the database.</p>
<pre><code>public class Image {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long imageId;
private String path;
@Lob
private byte[] data;
}
</code></pre>
<p>The idea was taking the image the user sent as a MultipartFile, convert it into bytes and then store it into the Image.data value.</p>
<p>I didn't try it yet, because I had some doubts: is it the most efficient way of storing a file into the database? And most importantly, can't a user just upload some sort of malicious file into the database? If yes, can I prevent that?</p>
|
[
{
"answer_id": 74592211,
"author": "KreutzerCode",
"author_id": 14032911,
"author_profile": "https://Stackoverflow.com/users/14032911",
"pm_score": 2,
"selected": true,
"text": "randomXValue = getRandomXValue();\nrandomYValue = getRandomYValue();\n\n$(\"#gamespace\").append(\n '<img src=\"img/img.jpg\" class=\"gameimg\" style = \"left: \"'+randomXValue+'\"px; top:\"'+randomYValue+'\"px;\"/>'\n);\n"
},
{
"answer_id": 74592297,
"author": "naveen",
"author_id": 17447,
"author_profile": "https://Stackoverflow.com/users/17447",
"pm_score": 2,
"selected": false,
"text": "const left = getRandomXValue();\nconst top = getRandomYValue();\n$(\"#gamespace\").append(\n `<img src=\"img/img.jpg\" class=\"gameimg\" style=\"left:${left}px;top:${top}px;\"/>`\n);\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19845343/"
] |
74,592,290
|
<p>Trying to set image for icon in flutter but not working. So, How to set path for ImageIcon in ListTile.</p>
<p>This line is not working:</p>
<blockquote>
<pre><code>leading: ImageIcon(AssetImage('images/abt.png'), size: 25),
</code></pre>
</blockquote>
<pre><code> GestureDetector(
onTap: ()
{
Navigator.push(context, MaterialPageRoute(builder: (c)=> AboutScreen()));
},
child: const ListTile(
tileColor: Colors.blue,
leading: ImageIcon(AssetImage('images/abt.png'), size: 25),
title: Text(
"About",
style: TextStyle(
color: Colors.black
),
),
),
),
</code></pre>
|
[
{
"answer_id": 74592211,
"author": "KreutzerCode",
"author_id": 14032911,
"author_profile": "https://Stackoverflow.com/users/14032911",
"pm_score": 2,
"selected": true,
"text": "randomXValue = getRandomXValue();\nrandomYValue = getRandomYValue();\n\n$(\"#gamespace\").append(\n '<img src=\"img/img.jpg\" class=\"gameimg\" style = \"left: \"'+randomXValue+'\"px; top:\"'+randomYValue+'\"px;\"/>'\n);\n"
},
{
"answer_id": 74592297,
"author": "naveen",
"author_id": 17447,
"author_profile": "https://Stackoverflow.com/users/17447",
"pm_score": 2,
"selected": false,
"text": "const left = getRandomXValue();\nconst top = getRandomYValue();\n$(\"#gamespace\").append(\n `<img src=\"img/img.jpg\" class=\"gameimg\" style=\"left:${left}px;top:${top}px;\"/>`\n);\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19099386/"
] |
74,592,293
|
<p>I'm trying to open links in my dataframe using selenium webdriver, the dataframe 'df1' looks like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th></th>
<th>user</th>
<th>repo1</th>
<th>repo2</th>
<th>repo3</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>breed</td>
<td>cs149-f22</td>
<td>kattis2canvas</td>
<td>grpc-maven-skeleton</td>
</tr>
<tr>
<td>1</td>
<td>GrahamDumpleton</td>
<td>mod_wsgi</td>
<td>wrapt</td>
<td>NaN</td>
</tr>
</tbody>
</table>
</div>
<p>The links I want to open include the content in column 'user' and one of 3 'repo' columns. I encounter a bug when I iterate the 'repo' columns.</p>
<p>Could anyone help me out? Thank you!</p>
<p>Here is my best try:</p>
<pre><code>repo_cols = [col for col in df1.columns if 'repo' in col]
for index, row in df1.iterrows():
user = row['user']
for repo_name in repo_cols:
try:
repo = row['repo_name']
current_url = f'https://github.com/{user}/{repo}/graphs/contributors'
driver.get(current_url)
time.sleep(0.5)
except:
pass
</code></pre>
<p>Here is the bug I encounter:</p>
<pre><code>KeyError: 'repo_name'
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
3079 try:
-> 3080 return self._engine.get_loc(casted_key)
3081 except KeyError as err:
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'repo_name'
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
<ipython-input-50-eb068230c3fd> in <module>
4 user = row['user']
5 for repo_name in repo_cols:
----> 6 repo = row['repo_name']
7 current_url = f'https://github.com/{user}/{repo}/graphs/contributors'
8 driver.get(current_url)
~\anaconda3\lib\site-packages\pandas\core\series.py in __getitem__(self, key)
851
852 elif key_is_scalar:
--> 853 return self._get_value(key)
854
855 if is_hashable(key):
~\anaconda3\lib\site-packages\pandas\core\series.py in _get_value(self, label, takeable)
959
960 # Similar to Index.get_value, but we do not fall back to positional
--> 961 loc = self.index.get_loc(label)
962 return self.index._get_values_for_loc(self, loc, label)
963
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
3080 return self._engine.get_loc(casted_key)
3081 except KeyError as err:
-> 3082 raise KeyError(key) from err
3083
3084 if tolerance is not None:
KeyError: 'repo_name'
</code></pre>
|
[
{
"answer_id": 74592211,
"author": "KreutzerCode",
"author_id": 14032911,
"author_profile": "https://Stackoverflow.com/users/14032911",
"pm_score": 2,
"selected": true,
"text": "randomXValue = getRandomXValue();\nrandomYValue = getRandomYValue();\n\n$(\"#gamespace\").append(\n '<img src=\"img/img.jpg\" class=\"gameimg\" style = \"left: \"'+randomXValue+'\"px; top:\"'+randomYValue+'\"px;\"/>'\n);\n"
},
{
"answer_id": 74592297,
"author": "naveen",
"author_id": 17447,
"author_profile": "https://Stackoverflow.com/users/17447",
"pm_score": 2,
"selected": false,
"text": "const left = getRandomXValue();\nconst top = getRandomYValue();\n$(\"#gamespace\").append(\n `<img src=\"img/img.jpg\" class=\"gameimg\" style=\"left:${left}px;top:${top}px;\"/>`\n);\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20616260/"
] |
74,592,308
|
<p>I am trying to remove all the consecutive numbers using exactly RegEx with JS. I tried two ways the second one passed but I am wondering what is wrong with the first one</p>
<p>First try:</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 a = "1 2 3 3 4 5 5 6 7 8 8 9";
a = a.split(" ").join("");
for (let i of a) {
a = a.replace(/ii/g, i);
}
console.log(a)</code></pre>
</div>
</div>
</p>
<p>Second one</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 a = "1 2 3 3 4 5 5 6 7 8 8 9";
a = a.split(" ").join("");
for (let i of a) {
a = a.replace(new RegExp(`(${i})(${i})`, "g"), "$1");
}
console.log(a)</code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74592379,
"author": "Michael M.",
"author_id": 13376511,
"author_profile": "https://Stackoverflow.com/users/13376511",
"pm_score": 2,
"selected": false,
"text": "let a = \"1 2 3 3 4 5 5 6 7 8 8 9\";\nlet b = (a + ' ').replace(/([1-9]\\s)\\1+/g, '$1').slice(0, -1);\n\nconsole.log(b) let a = \"1 2 3 3 4 5 5 6 7 8 8 9\";\nlet b = (a + ' ').replace(/([1-9]\\s)\\1+/g, '$1').replaceAll(' ', '');\n\nconsole.log(b) let a = \"1 2 3 3 4 5 5 6 7 8 8 9\";\n\nconsole.time()\nconsole.log(a.replaceAll(/(?<=(?<number>\\d))(\\s\\k<number>)/g, ''));\nconsole.timeEnd()\n\nconsole.time()\nconsole.log((a + ' ').replace(/([1-9]\\s)\\1+/g, '$1').slice(0, -1));\nconsole.timeEnd();"
},
{
"answer_id": 74592391,
"author": "Zehan Khan",
"author_id": 16884475,
"author_profile": "https://Stackoverflow.com/users/16884475",
"pm_score": 1,
"selected": false,
"text": "let a = \"1 2 3 3 4 5 5 6 7 8 8 9\";\n\na = a.split(\" \").join(\"\");\nlet b = a.replace(/(.)\\1+/g, '$1');\nlet c = b.split(\"\").join(\" \")\n\nconsole.log(c)"
},
{
"answer_id": 74592594,
"author": "damonholden",
"author_id": 17670742,
"author_profile": "https://Stackoverflow.com/users/17670742",
"pm_score": 2,
"selected": false,
"text": "/ii/g\n 'ii' RegExp() const removeSequentialNumbers = (string) =>\n string.replaceAll(/(?<=(?<number>\\d))(\\s\\k<number>)/g, '');\n"
},
{
"answer_id": 74592635,
"author": "Daniel Cruz",
"author_id": 17537072,
"author_profile": "https://Stackoverflow.com/users/17537072",
"pm_score": 2,
"selected": false,
"text": "a.replaceAll(/(?<number>\\d)\\s\\k<number>/g, \"$1\")\n let a = \"1 2 3 3 4 5 5 6 7 8 8 9\"; \nconst result = a.replaceAll(/(?<number>\\d)\\s\\k<number>/g, \"$1\")\nconsole.log(result)"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16940335/"
] |
74,592,310
|
<p>Wrote a program TroubleTicket which allows the user to create a trouble ticket with various parameters. Code is using <code>struct ticket {}</code> to store ticket data. Each a new_ticket is added to <code>tkt_array</code>. The code is rather lengthy so I posted the relevant files and the code snippet. This is not a school project but a personal interest in learning some C.</p>
<p>Anyhow, there are functions, <code>create_ticket()</code> and <code>update_ticket()</code> which use <code>_strdup()</code> to handle user inputs. It's my understanding that <code>_strdup()</code> uses <code>malloc()</code> and this requires call to <code>free()</code> the memory. My approach is to call <code>free()</code> at program exit with the assumption that this will release malloc()ed memory. This task is done by function <code>free_tkt_arr()</code>.</p>
<p>The function <code>create_ticket()</code> uses <code>_strdup()</code> when setting <code>name</code>, <code>problem</code>, <code>assigned_to</code> and <code>status</code> pointers.</p>
<p>Function <code>update_ticket()</code> is also using <code>_strdup()</code> to update ticket <code>name</code>, <code>problem</code>, <code>assigned_to</code> and <code>status</code>.</p>
<p>Upon code exit, function <code>free_tkt_arr()</code> is called to release memory allocated by <code>_strdup()</code>.</p>
<p>What I'd like to know if calling <code>free_ticket()</code> on system exit releases all memory that was allocated by calls to <code>_strdup()</code> in <code>create_ticket()</code> and <code>update_ticket()</code>?</p>
<pre><code>struct ticket {
int priority;
int number;
char *name;
char *problem;
char *assigned_to;
char *status;
};
</code></pre>
<p>The function <code>create_ticket()</code> uses <code>_strdup()</code> when setting <code>name</code>, <code>problem</code>, <code>assigned_to</code> and <code>status</code> pointers:</p>
<pre><code>struct ticket tkt_array[NUM_TICKETS];
void create_ticket() {
char *ptr;
struct ticket new_ticket;
printf("Enter your name: ");
new_ticket.name = _strdup(get_input(20));
printf("Enter problem description: ");
new_ticket.problem = _strdup(get_input(100));
printf("Assigned to: ");
new_ticket.assigned_to = _strdup(get_input(20));
//printf("Enter ticket status: ");
//using _strdup() in case status is updated using _strdup which requires call to free()
ptr = "new";
new_ticket.status = _strdup(ptr);
}
</code></pre>
<p>Function <code>update_ticket()</code> is also using <code>_strdup()</code> to update ticket <code>name</code>, <code>problem</code>, <code>assigned_to</code> and <code>status</code>.</p>
<pre><code>void update_ticket() {
printf("Enter ticket number: ");
ptr = get_input(8);
sscanf_s(ptr, "%d", &ticket_num);
if (*ptr == '1') {
printf("Updating Status.\n");
printf("Enter Status update: ");
tmp_ticket2.status = _strdup(get_input(20));
} else
if (*ptr == '2') {
printf("Updating Problem description.\n");
printf("Enter Problem description update. ");
tmp_ticket2.problem = _strdup(get_input(100));
} else
if (*ptr == '3') {
printf("Updating Assigned to.\n");
printf("Enter Assigned to update. ");
tmp_ticket2.assigned_to = _strdup(get_input(20));
}
}
</code></pre>
<p>function <code>free_tkt_array()</code> is called when exiting code and should be
freeing memory allocated by prior calls to <code>_strdup()</code></p>
<pre><code>void free_tkt_arr() {
for (int i = 0; i <= tkt_count - 1; i++) {
free(tkt_array[i].assigned_to);
free(tkt_array[i].name);
free(tkt_array[i].problem);
free(tkt_array[i].status);
}
}
</code></pre>
<blockquote>
<p>I thought about downloading and learning valgrind but maybe that's a bit over my head.</p>
</blockquote>
|
[
{
"answer_id": 74602145,
"author": "Luis Colorado",
"author_id": 3899431,
"author_profile": "https://Stackoverflow.com/users/3899431",
"pm_score": 0,
"selected": false,
"text": "free() NULL NULL memset(3) bzero(3) NULL malloc(3) free(ptr) ptr NULL free(ptr); ptr = NULL;"
},
{
"answer_id": 74602505,
"author": "chqrlie",
"author_id": 4593267,
"author_profile": "https://Stackoverflow.com/users/4593267",
"pm_score": 1,
"selected": false,
"text": "get_input() get_input() strdup() strdup() _strdup() _strdup() strdup() strdup() strdup() #include <stdlib.h>\n#include <string.h>\n\nchar *strdup(const char *s) {\n size_t size = strlen(s) + 1;\n char *p = malloc(size);\n if (p) {\n return memcpy(p, s, size);\n } else {\n return p;\n }\n}\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6669933/"
] |
74,592,342
|
<p>For compliance requirements, we would like to move all our Bigquery data and GCS data from US region to EU region.
From my understanding, multi-region is either within US or within EU. There is no cross-region option as such.</p>
<p>Question 1: In order to move the data from US to EU or vice versa, our understanding is that we need explicitly move the data using a storage transfer service. And assuming a cost associated with this movement even though it is within Google cloud?</p>
<p>Question 2: We also think if we can maintain copies at both locations. In this case, Is there a provision for cross-region replication? If so, what would be the associated cost for the same?</p>
|
[
{
"answer_id": 74602145,
"author": "Luis Colorado",
"author_id": 3899431,
"author_profile": "https://Stackoverflow.com/users/3899431",
"pm_score": 0,
"selected": false,
"text": "free() NULL NULL memset(3) bzero(3) NULL malloc(3) free(ptr) ptr NULL free(ptr); ptr = NULL;"
},
{
"answer_id": 74602505,
"author": "chqrlie",
"author_id": 4593267,
"author_profile": "https://Stackoverflow.com/users/4593267",
"pm_score": 1,
"selected": false,
"text": "get_input() get_input() strdup() strdup() _strdup() _strdup() strdup() strdup() strdup() #include <stdlib.h>\n#include <string.h>\n\nchar *strdup(const char *s) {\n size_t size = strlen(s) + 1;\n char *p = malloc(size);\n if (p) {\n return memcpy(p, s, size);\n } else {\n return p;\n }\n}\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8427453/"
] |
74,592,355
|
<p>I've got an API resource to fetch transaction list. There are few filters and params to make it sortable e.g. <code>per_page</code>, <code>status</code> etc. which may be passed on but only <code>user_id</code> is required. Now my method looks like this:</p>
<pre><code>def list(user_id:, page: nil, per_page: nil, status: nil, payment_id: nil, start_date: nil,
end_date: nil, max_amount: nil)
filters = { start_date:, end_date:, max_amount:, status:, payment_id: }.compact_blank!
params = { filters:, page:, per_page: }.compact_blank!
begin
body = get("users/#{user_id}/transactions", params:).body
rescue Errors::NotFoundError
nil
end
resource_list(body, BaseStruct::Transaction)
end
</code></pre>
<p>This code produces me Rubocop error of:
<code>Metrics/ParameterLists: Avoid parameter lists longer than 5 parameters. [8/5]</code>. I know I could get rid of it by <code># rubocop:disable Metrics/ParameterLists</code> but I don't think that's the best idea. Is it possible to pass those not required field in a different way to avoid that error?</p>
|
[
{
"answer_id": 74602145,
"author": "Luis Colorado",
"author_id": 3899431,
"author_profile": "https://Stackoverflow.com/users/3899431",
"pm_score": 0,
"selected": false,
"text": "free() NULL NULL memset(3) bzero(3) NULL malloc(3) free(ptr) ptr NULL free(ptr); ptr = NULL;"
},
{
"answer_id": 74602505,
"author": "chqrlie",
"author_id": 4593267,
"author_profile": "https://Stackoverflow.com/users/4593267",
"pm_score": 1,
"selected": false,
"text": "get_input() get_input() strdup() strdup() _strdup() _strdup() strdup() strdup() strdup() #include <stdlib.h>\n#include <string.h>\n\nchar *strdup(const char *s) {\n size_t size = strlen(s) + 1;\n char *p = malloc(size);\n if (p) {\n return memcpy(p, s, size);\n } else {\n return p;\n }\n}\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19143199/"
] |
74,592,368
|
<p>I want to write a SQL query in MS Access 2010 for creating a table such that an attribute 'day' should have a value within a constraint I give using 'check' keyword. The check constraint is giving an error on saving the query.</p>
<p>I wrote a SQL query in MS Access 2010 as follows-</p>
<pre><code>CREATE TABLE timeslot
(
time_slot_id varchar (4),
day varchar (1) check (day in ('M', 'T', 'W','R', 'F', 'S', 'U')),
start_time time,
end_time time,
primary key (time_slot_id, day, start_time)
);
</code></pre>
<p>But on saving the query, I get an error pop-up saying</p>
<blockquote>
<p>SYNTAX ERROR IN CREATE TABLE STATEMENT</p>
</blockquote>
<p>and it points at the check keyword. When I delete the check constraint, it runs successfully and the table timeslot is created without the constraint applied on 'day' attribute. Am I syntactically wrong in using 'check'? How do I apply the constraint on 'day' attribute?</p>
|
[
{
"answer_id": 74592586,
"author": "Lajos Arpad",
"author_id": 436560,
"author_profile": "https://Stackoverflow.com/users/436560",
"pm_score": 0,
"selected": false,
"text": "CHECK CREATE TABLE timeslot\n(\n time_slot_id varchar (4),\n day varchar (1),\n start_time time,\n end_time time,\n\n primary key (time_slot_id, day, start_time),\n check (day in ('M', 'T', 'W','R', 'F', 'S', 'U'))\n);\n"
},
{
"answer_id": 74593446,
"author": "HansUp",
"author_id": 77335,
"author_profile": "https://Stackoverflow.com/users/77335",
"pm_score": 2,
"selected": false,
"text": "Set cn = CurrentProject.Connection\nstrCreate = \"CREATE TABLE timeslot ([day] varchar(1), \" & _\n \"CONSTRAINT allowed_days CHECK ([day] IN ('M','T','W','R','F','S','U')))\"\ncn.Execute strCreate\n CurrentProject.Connection strCreate = \"CREATE TABLE timeslot ([day] varchar(1))\"\ncn.Execute strCreate\nstrRule = \"In ('M','T','W','R','F','S','U')\"\nSet db = CurrentDb\ndb.TableDefs(\"timeslot\").Fields(\"day\").ValidationRule = strRule\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20615981/"
] |
74,592,371
|
<p>I have a class that looks something like:</p>
<pre><code>@dataclass
class MyClass:
df1: pd.Series = None
df2: pd.Series = None
df3: pd.Series = None
df4: pd.Series = None
df5: pd.Series = None
@property
def series_mean(self) -> pd.Series:
series_mean = (
self.df1
+ self.df2
+ self.df3
+ self.df4
+ self.df5
).mean()
return series_mean
</code></pre>
<p>Generally this could just be done as a function alone, but for this case, let's just assume I do this.</p>
<p>Now, my issue now is, that none of the df's are mandatory, so I could just give it <code>df1</code> and <code>df5</code>. In that case, the mean doesn't work due to the <code>None</code> in the class.</p>
<p>So how do I go about just using the ones that are not None ? And on top of that, is there a way to get how many of them are not None? I mean, if I wanted to do <code>/ 2</code> instead of <code>.mean()</code> if there is two that are not None.</p>
|
[
{
"answer_id": 74592586,
"author": "Lajos Arpad",
"author_id": 436560,
"author_profile": "https://Stackoverflow.com/users/436560",
"pm_score": 0,
"selected": false,
"text": "CHECK CREATE TABLE timeslot\n(\n time_slot_id varchar (4),\n day varchar (1),\n start_time time,\n end_time time,\n\n primary key (time_slot_id, day, start_time),\n check (day in ('M', 'T', 'W','R', 'F', 'S', 'U'))\n);\n"
},
{
"answer_id": 74593446,
"author": "HansUp",
"author_id": 77335,
"author_profile": "https://Stackoverflow.com/users/77335",
"pm_score": 2,
"selected": false,
"text": "Set cn = CurrentProject.Connection\nstrCreate = \"CREATE TABLE timeslot ([day] varchar(1), \" & _\n \"CONSTRAINT allowed_days CHECK ([day] IN ('M','T','W','R','F','S','U')))\"\ncn.Execute strCreate\n CurrentProject.Connection strCreate = \"CREATE TABLE timeslot ([day] varchar(1))\"\ncn.Execute strCreate\nstrRule = \"In ('M','T','W','R','F','S','U')\"\nSet db = CurrentDb\ndb.TableDefs(\"timeslot\").Fields(\"day\").ValidationRule = strRule\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1045755/"
] |
74,592,390
|
<p>I am calling a third party REST endpoint.</p>
<p><strong>Request sample</strong></p>
<pre><code>{
"body": {
"accountNumber": "12345"
},
"header": {
"username": "someusername",
"password": "somepassword"
}
}
</code></pre>
<p>I have created 3 bean classes</p>
<p><strong>MyRequest.java</strong></p>
<pre><code>@Builder
@JsonDeserialize(builder = MyRequest.MyRequestBuilder.class)
public class MyRequest {
@JsonProperty("header")
private MyHeader header;
@JsonProperty("body")
private MyBody body;
}
</code></pre>
<p><strong>MyBody.java</strong></p>
<pre><code>@Getter
@Builder
public class MyBody {
private String accountNumber;
}
</code></pre>
<p><strong>MyHeader.java</strong></p>
<pre><code>@Getter
@Builder
public class MyHeader {
private String username;
private String password;
}
</code></pre>
<p>I'm creating request object using</p>
<pre><code>MyBody body = MyBody.builder().accountNumber("12345").build();
MyHeader header = MyHeader.builder().username("someusername").password("somepassword").build();
MyRequest request = MyRequest.builder().body(body).header(header).build();
</code></pre>
<p>Everything is working as expected. The code coverage for MyRequest.java is 100% but my MyBody.java and MyHeader.java is not.
For all the fields I get the error message "Not covered by tests".</p>
<p>Normally I add @Getter and @Setter for Response objects. For request, I just add @Builder annotation.
In this case, if I remove @Getter from MyBody and MyHeader, the third party REST endpoint is getting null values.
It looks like @Getter is invoked when setting the objects to MyRequest.java. But for some reason it is not covered by my test cases.</p>
<p>How to make this work without @Getter or is there a way to cover all the fields (accountNumber, username and password) with @Getter annotation? Any help is appreciated.</p>
|
[
{
"answer_id": 74592586,
"author": "Lajos Arpad",
"author_id": 436560,
"author_profile": "https://Stackoverflow.com/users/436560",
"pm_score": 0,
"selected": false,
"text": "CHECK CREATE TABLE timeslot\n(\n time_slot_id varchar (4),\n day varchar (1),\n start_time time,\n end_time time,\n\n primary key (time_slot_id, day, start_time),\n check (day in ('M', 'T', 'W','R', 'F', 'S', 'U'))\n);\n"
},
{
"answer_id": 74593446,
"author": "HansUp",
"author_id": 77335,
"author_profile": "https://Stackoverflow.com/users/77335",
"pm_score": 2,
"selected": false,
"text": "Set cn = CurrentProject.Connection\nstrCreate = \"CREATE TABLE timeslot ([day] varchar(1), \" & _\n \"CONSTRAINT allowed_days CHECK ([day] IN ('M','T','W','R','F','S','U')))\"\ncn.Execute strCreate\n CurrentProject.Connection strCreate = \"CREATE TABLE timeslot ([day] varchar(1))\"\ncn.Execute strCreate\nstrRule = \"In ('M','T','W','R','F','S','U')\"\nSet db = CurrentDb\ndb.TableDefs(\"timeslot\").Fields(\"day\").ValidationRule = strRule\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3909315/"
] |
74,592,392
|
<p>This is binary search algorithm that is showing output as None. I dont know why. And if you know any free course to learn data sctrucures and algorithm in python please let me know .</p>
<pre><code>import random
def binary_search(list,target):
start_index=0
end_index=len(list)-1
while start_index<=end_index:
midpoint=(start_index+end_index)//2
midpoint_value=list[midpoint]
if midpoint_value==target:
return midpoint+1
elif midpoint_value<target:
end_index=midpoint-1
else:
start_index=midpoint+1
print(binary_search([1,2,3,4,5,6,7,8],8))
</code></pre>
<p>8 on 7th index position</p>
|
[
{
"answer_id": 74592586,
"author": "Lajos Arpad",
"author_id": 436560,
"author_profile": "https://Stackoverflow.com/users/436560",
"pm_score": 0,
"selected": false,
"text": "CHECK CREATE TABLE timeslot\n(\n time_slot_id varchar (4),\n day varchar (1),\n start_time time,\n end_time time,\n\n primary key (time_slot_id, day, start_time),\n check (day in ('M', 'T', 'W','R', 'F', 'S', 'U'))\n);\n"
},
{
"answer_id": 74593446,
"author": "HansUp",
"author_id": 77335,
"author_profile": "https://Stackoverflow.com/users/77335",
"pm_score": 2,
"selected": false,
"text": "Set cn = CurrentProject.Connection\nstrCreate = \"CREATE TABLE timeslot ([day] varchar(1), \" & _\n \"CONSTRAINT allowed_days CHECK ([day] IN ('M','T','W','R','F','S','U')))\"\ncn.Execute strCreate\n CurrentProject.Connection strCreate = \"CREATE TABLE timeslot ([day] varchar(1))\"\ncn.Execute strCreate\nstrRule = \"In ('M','T','W','R','F','S','U')\"\nSet db = CurrentDb\ndb.TableDefs(\"timeslot\").Fields(\"day\").ValidationRule = strRule\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18919053/"
] |
74,592,406
|
<p>This is the setup for a calendar, is there a better way to create a count?</p>
<pre><code>for k,v in months.items():
print(k) # print the month name
print(month_header)
while month_daycount > 7:
month_daycount -= 7
count = month_daycount
</code></pre>
|
[
{
"answer_id": 74592586,
"author": "Lajos Arpad",
"author_id": 436560,
"author_profile": "https://Stackoverflow.com/users/436560",
"pm_score": 0,
"selected": false,
"text": "CHECK CREATE TABLE timeslot\n(\n time_slot_id varchar (4),\n day varchar (1),\n start_time time,\n end_time time,\n\n primary key (time_slot_id, day, start_time),\n check (day in ('M', 'T', 'W','R', 'F', 'S', 'U'))\n);\n"
},
{
"answer_id": 74593446,
"author": "HansUp",
"author_id": 77335,
"author_profile": "https://Stackoverflow.com/users/77335",
"pm_score": 2,
"selected": false,
"text": "Set cn = CurrentProject.Connection\nstrCreate = \"CREATE TABLE timeslot ([day] varchar(1), \" & _\n \"CONSTRAINT allowed_days CHECK ([day] IN ('M','T','W','R','F','S','U')))\"\ncn.Execute strCreate\n CurrentProject.Connection strCreate = \"CREATE TABLE timeslot ([day] varchar(1))\"\ncn.Execute strCreate\nstrRule = \"In ('M','T','W','R','F','S','U')\"\nSet db = CurrentDb\ndb.TableDefs(\"timeslot\").Fields(\"day\").ValidationRule = strRule\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20007197/"
] |
74,592,435
|
<p>I am using <code>mongoose</code> and have two schemas: <code>UserSchema</code> and <code>CommunitySchema</code>:</p>
<pre><code>const UserSchema = new Schema({
name: String,
communities: [{ type: Schema.Types.ObjectId, ref: CollectionModel }],
exCommunities: [{ type: Schema.Types.ObjectId, ref: CollectionModel }],
}, { timestamps: true });
</code></pre>
<pre><code>const CommunitySchema = new Schema({
slug: { type: String, unique: true },
name: String,
description: String,
users: [
{ type: Schema.Types.ObjectId, ref: "User" }
]
}, { timestamps: true });
</code></pre>
<p>User can be a part of multiple <code>communities</code> and also leave any community and be in the <code>exCommunities</code> field.</p>
<p>When an user joins a community, I have to do a double work: Add the user to a user <code>community</code> and update the <code>community</code> user field with the reference ID.</p>
<p>Questions:</p>
<ol>
<li>Is there a way to simplify it? For example, by managing the CommunitySchema <code>users</code> field automatically based on the UserSchema communities field?</li>
</ol>
<p>Now I have to do this:</p>
<pre><code> collection.users.push(userId);
user.communities.push(communityId);
</code></pre>
<p>Could the collection.users be automatically added when I push a community to user.communities? And how?)</p>
<ol start="2">
<li>Is it possible to add a date when the user is added to a community or leave a community? Something like: <code>communities: [{ type: Schema.Types.ObjectId, ref: CollectionModel, createdAt: "<DATE>" }]</code></li>
</ol>
<p>Thank you!</p>
|
[
{
"answer_id": 74675484,
"author": "Saurabh Mistry",
"author_id": 6943762,
"author_profile": "https://Stackoverflow.com/users/6943762",
"pm_score": 1,
"selected": false,
"text": "communities exCommunities const UserSchema = new Schema({\n name: String,\n}, { timestamps: true });\n\nconst communityUserSchema = new Schema({\n user_id:{type: Schema.Types.ObjectId, ref: \"User\"},\n joined_at:{type:Date},\n leaved_at:{type:Date},\n is_active:{type:Boolean},\n role:{type:String, enum:['user','admin'], default:'user'}\n});\n\nconst CommunitySchema = new Schema({\n slug: { type: String, unique: true },\n name: String, \n description: String, \n users:{\n type:[communityUserSchema],\n default:[]\n }\n}, { timestamps: true });\n let user_id = req.user._id;\nall_communities = await Community.find({\"users.user_id\":user_id});\n\nactive_communities = await Community.find({\"users.user_id\":user_id, \"is_active\":true});\n\nex_communities = await Community.find({\"users.user_id\":user_id,\"leaved_at\":{\"$ne\":null}});\n let current_user = {user_id:req.user.id,joined_at:new Date(),is_active:true,role:'admin'};\n\n // if you select users from frontend while creating new community \n\n let other_user = req.body.user_ids;\n let other_users_mapped = other_user.map((item)=>{ return {user_id:item,joined_at:new Date(),role:'user',is_active:true}}); \n\n let all_users = [current_user];\n all_users = all_users.concat(other_users_mapped);\n\n let community = new Community();\n community.name = req.body.name;\n community.slug = req.body.slug;\n community.description = req.body.description;\n community.users = all_users ;\n let created = await community.save();\n Community.updateOne({_id: community_id , 'users.user_id':user_id },{\n $set:{\n 'users.$.is_active':false,\n 'users.$.leaved_at':new Date()\n }\n});\n let community_id = req.params.community_id;\nlet data = await Community.findOne({_id:community_id},{ users: { $elemMatch: { is_active: true } } });\n"
},
{
"answer_id": 74678629,
"author": "Petr",
"author_id": 2250167,
"author_profile": "https://Stackoverflow.com/users/2250167",
"pm_score": 0,
"selected": false,
"text": "import * as mongoose from 'mongoose';\nconst Schema = mongoose.Schema;\n\ninterface User {\n name: string;\n email: string;\n communities: Community[];\n}\n\ninterface Community {\n name: string;\n description: string;\n users: User[];\n}\n\nconst userSchema = new Schema({\n name: String,\n email: String,\n}, {\n timestamps: true,\n});\n\nconst communitySchema = new Schema({\n name: String,\n description: String,\n}, {\n timestamps: true,\n});\n\n// Define the user_communities table using the communitySchema\nconst userCommunitySchema = new Schema({\n user: { type: Schema.Types.ObjectId, ref: 'User' },\n community: { type: Schema.Types.ObjectId, ref: 'Community' },\n joined_on: Date,\n}, {\n timestamps: true,\n});\n\n// Use the userCommunitySchema to create the UserCommunity model\nconst UserCommunity = mongoose.model('UserCommunity', userCommunitySchema);\n\n// Use the userSchema to create the User model, and define a virtual property\n// for accessing the user's communities\nuserSchema.virtual('communities', {\n ref: 'Community',\n localField: '_id',\n foreignField: 'user',\n justOne: false,\n});\n\nconst User = mongoose.model<User>('User', userSchema);\n\n// Use the communitySchema to create the Community model, and define a virtual property\n// for accessing the community's users\ncommunitySchema.virtual('users', {\n ref: 'User',\n localField: '_id',\n foreignField: 'community',\n justOne: false,\n});\n\nconst Community = mongoose.model<Community>('Community', communitySchema);\n userSchema communitySchema User Community User user.communities communitySchema community.users"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2250167/"
] |
74,592,444
|
<p>Reset may not be the right word here, but I am currently building a program that lets the user look up a name, and by scanning a txt file containing a list of names followed by numbers, the program then displays the numbers following said name. The way I am doing this is via .nextLine, but if the user inputs a name that's later in the list (say Samantha in the example) and then tries to look up a name at the top of the list (like Sally), the second name isn't found.</p>
<p>For reference, here is an example of that txt file:</p>
<pre><code>Sally 0 0 0 0 0 0 0 0 0 0 886
Sam 58 69 99 131 168 236 278 380 467 408 466
Samantha 0 0 0 0 0 0 272 107 26 5 7
Samir 0 0 0 0 0 0 0 0 920 0 798
</code></pre>
<pre><code>import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class BabyNames {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Scanner input = new Scanner (new File("BabyNames.txt"));
Scanner keyboard = new Scanner (System.in);
System.out.println("This program allows you to search through the data from the "
+ "Social Security Administration to see how popular a particular name has "
+ "been since 1900.");
System.out.print("Name? ");
String name = keyboard.nextLine();
do {
while(input.hasNextLine()) {
String text = input.nextLine();
String[] words = text.split(" ");
if (text.contains(name)) {
System.out.println("Statistics on name \"" + name + "\"");
for (int i = 1; i < words.length; i++) {
System.out.println((1900 + (i-1)*10) + ": " + words[i]);
}
System.out.println("Enter another name or type quit to exit.");
name = keyboard.nextLine();
break;
}
else if (name.contains("quit") || name.contains("quit")){
System.exit(0);
}
else {
continue;
}
System.out.print("Error, name not found.");
}
} while (!name.contains("quit") || name.contains("quit"));
}
}
</code></pre>
<p>I looked up the .reset method but that hasn't seemed to work. Honestly, I'm stumped here.</p>
|
[
{
"answer_id": 74592634,
"author": "EDITH",
"author_id": 20616524,
"author_profile": "https://Stackoverflow.com/users/20616524",
"pm_score": 0,
"selected": false,
"text": "Scanner systemInput = new Scanner(System.in);\n//new Scanner(new FileInputStream(\"file.t\"));\n BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(\"BabyNames.txt\"));\n Scanner input = new Scanner (inputStream);\n inputStream.mark(0);//saving a checkpoint\n inputStream.reset();\n"
},
{
"answer_id": 74593283,
"author": "Hovercraft Full Of Eels",
"author_id": 522444,
"author_profile": "https://Stackoverflow.com/users/522444",
"pm_score": 1,
"selected": false,
"text": "Map<String, SomeCustomClass> import java.util.*;\n\npublic class BabyName {\n String name;\n List<Integer> numberList = new ArrayList<>();\n \n public BabyName(String name, List<Integer> numberList) {\n this.name = name;\n this.numberList = numberList;\n }\n \n public String getName() {\n return name;\n }\n \n public List<Integer> getNumberList() {\n return numberList;\n }\n\n @Override\n public String toString() {\n return \"BabyName [name=\" + name + \", numberList=\" + numberList + \"]\";\n }\n\n // consider adding hashCode and equals methods that are based on the name field alone\n // ...\n \n}\n private static BabyName createBabyName(String line) {\n String[] tokens = line.split(\"\\\\s+\");\n String name = \"\";\n List<Integer> numberList = new ArrayList<>();\n \n // ... code to extract the data and that fills the numberList here\n // ... left blank for you to fill in\n\n BabyName babyName = new BabyName(name, numberList);\n return babyName;\n}\n Map<String, BabyName> babyNameMap = new HashMap<>(); Scanner fileScanner = null;\ntry {\n fileScanner = new Scanner(new File(FILE_PATH_NAME)); \n} catch (FileNotFoundException e) {\n e.printStackTrace();\n System.exit(-1);\n}\n\n// read file and fill the map\nwhile (fileScanner.hasNextLine()) {\n String line = fileScanner.nextLine();\n BabyName babyName = createBabyName(line);\n babyNameMap.put(babyName.getName(), babyName); \n}\n String nameEnteredByUser = keyboard.nextLine();\nBabyName selectedBabyName = babyNameMap.get(nameEnteredByUser);\n\n// check for null here first\nString name = nameEnteredByUser;\nList<Integer> numberList = selectedBabyName.getNumberList();\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20616426/"
] |
74,592,469
|
<p>I am getting typescript error ts(18048) inside of the BoxerCard. I imported the type's file, but it seems that the parameters are not taking it. I've tried manually adding the types in the parameters of the function, but it didn't change anything. the types should be what is in the types file but it changed them all to string.</p>
<p>in Types.tsx</p>
<pre><code>import React from "react";
export interface BoxerCardInterface {
name: string;
imgUrl: any;
age: number;
status: string;
}
export interface CoachCardInterface {
name: string;
imgUrl: any;
title: string;
}
</code></pre>
<p>in Boxers.tsx</p>
<pre><code>import React from "react";
import { BoxerCard } from "../components/BoxerCards";
import BoxerData from "../data/BoxerData";
import { BoxerCardInterface } from "../data/Types";
export function Boxers()
{
return (
<div className="flex flex-col md: flex-rows items-center justify-center">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{BoxerData.map(boxers => (
<BoxerCard
imgUrl={boxers.imgUrl}
name={boxers.name}
age={boxers.age}
status={boxers.status}
/>
))
}
</div>
</div>
)
}
</code></pre>
<p>In BoxerCard.tsx</p>
<pre><code>import React from "react";
import { BoxerCardInterface } from "../data/Types";
export function BoxerCard({name,imgUrl,age,status,}:BoxerCardInterface) {
return (
<div className="card w-96 glass m-12">
<figure><img src="https://placeimg.com/400/225/arch" alt="car!"/>{imgUrl}</figure>
<div className="card-body">
<h1 className="card-title flex-col">{name}</h1>
<div className="card-actions justify-end">
<button className="btn gap-2">age: {age}</button>
<button className="btn gap-2">{status}</button>
</div>
</div>
</div>
);
};
</code></pre>
<p>in BoxerData.tsx</p>
<pre><code>import React from "react";
export default [
{
name: 'Natalia Castaneda',
imgUrl: '',
age: '19',
status: 'Open'
},
,
{
name: 'Joel Sanchez',
imgUrl: '',
age: '19 years old',
status: 'Open'
},
{
name: 'Scott Mcfadden',
imgUrl: '',
age: '20 years old',
status: 'Open'
},
{
name: 'Augusta Grace',
imgUrl: '',
age: '26 years old',
status: 'Novice'
},
{
name: 'Alex Garcia',
imgUrl: '',
age: '19 years old',
status: 'Novice'
},
{
name: 'Mia Andre',
imgUrl: '',
age: '13 years old',
status: 'Novice'
},
{
name: 'Jocelyn Castaneda',
imgUrl: '',
age: '13 years old',
status: 'Novice'
}
];
</code></pre>
<p><a href="https://i.stack.imgur.com/DOAZD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DOAZD.png" alt="picture of the error" /></a></p>
|
[
{
"answer_id": 74592634,
"author": "EDITH",
"author_id": 20616524,
"author_profile": "https://Stackoverflow.com/users/20616524",
"pm_score": 0,
"selected": false,
"text": "Scanner systemInput = new Scanner(System.in);\n//new Scanner(new FileInputStream(\"file.t\"));\n BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(\"BabyNames.txt\"));\n Scanner input = new Scanner (inputStream);\n inputStream.mark(0);//saving a checkpoint\n inputStream.reset();\n"
},
{
"answer_id": 74593283,
"author": "Hovercraft Full Of Eels",
"author_id": 522444,
"author_profile": "https://Stackoverflow.com/users/522444",
"pm_score": 1,
"selected": false,
"text": "Map<String, SomeCustomClass> import java.util.*;\n\npublic class BabyName {\n String name;\n List<Integer> numberList = new ArrayList<>();\n \n public BabyName(String name, List<Integer> numberList) {\n this.name = name;\n this.numberList = numberList;\n }\n \n public String getName() {\n return name;\n }\n \n public List<Integer> getNumberList() {\n return numberList;\n }\n\n @Override\n public String toString() {\n return \"BabyName [name=\" + name + \", numberList=\" + numberList + \"]\";\n }\n\n // consider adding hashCode and equals methods that are based on the name field alone\n // ...\n \n}\n private static BabyName createBabyName(String line) {\n String[] tokens = line.split(\"\\\\s+\");\n String name = \"\";\n List<Integer> numberList = new ArrayList<>();\n \n // ... code to extract the data and that fills the numberList here\n // ... left blank for you to fill in\n\n BabyName babyName = new BabyName(name, numberList);\n return babyName;\n}\n Map<String, BabyName> babyNameMap = new HashMap<>(); Scanner fileScanner = null;\ntry {\n fileScanner = new Scanner(new File(FILE_PATH_NAME)); \n} catch (FileNotFoundException e) {\n e.printStackTrace();\n System.exit(-1);\n}\n\n// read file and fill the map\nwhile (fileScanner.hasNextLine()) {\n String line = fileScanner.nextLine();\n BabyName babyName = createBabyName(line);\n babyNameMap.put(babyName.getName(), babyName); \n}\n String nameEnteredByUser = keyboard.nextLine();\nBabyName selectedBabyName = babyNameMap.get(nameEnteredByUser);\n\n// check for null here first\nString name = nameEnteredByUser;\nList<Integer> numberList = selectedBabyName.getNumberList();\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16883589/"
] |
74,592,476
|
<p>I have two dates I'm trying to compare in this format: <code>a = '10.2022'</code> (october 2022) and <code>b = '02.2023'</code> (February 2023)</p>
<p>When I enter a > b I expect to have False</p>
<p>Here is my code:</p>
<pre><code>import datetime
a = '10-2022' # String date
b = '02-2023' # String date
date_format = '%m.%Y'
a = datetime.datetime.strptime(master_list[0][1], '%m-%Y').strftime(date_format)
b = datetime.datetime.strptime(master_list[0][2], '%m-%Y').strftime(date_format)
</code></pre>
<p>So I have <code>a = '10.2022 '</code> and <code>b = '02.2023'</code>.</p>
<p><code>a > b</code> returns True which is not correct because Oct 2022 is obviously before Feb 2023. Not sure what's not working</p>
|
[
{
"answer_id": 74595327,
"author": "AirSquid",
"author_id": 10789207,
"author_profile": "https://Stackoverflow.com/users/10789207",
"pm_score": 1,
"selected": true,
"text": "import datetime\n\ndate_format = '%m.%Y'\n\na = datetime.datetime.strptime('10-2022', '%m-%Y') \nb = datetime.datetime.strptime('02-2023', '%m-%Y') \n\nprint(type(a))\nprint(a)\nprint(f'a is greater than b when both are datetime: {a>b}')\nprint()\n\n# now convert back to format you want...\na_as_str = a.strftime(date_format)\nb_as_str = b.strftime(date_format)\n\nprint(type(a_as_str))\nprint(a_as_str)\nprint(f'a is greater than b when both are strings: {a_as_str>b_as_str}')\n <class 'datetime.datetime'>\n2022-10-01 00:00:00\na is greater than b when both are datetime: False\n\n<class 'str'>\n10.2022\na is greater than b when both are strings: True\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20592624/"
] |
74,592,497
|
<p>I have a data frame like this</p>
<pre><code>x1<- c(0,1,1,1,1,0)
df<-data.frame(x1)
</code></pre>
<p>I want to add another column that will take the sum of every two rows and store the value for the first two rows. This should look like this.</p>
<p><a href="https://i.stack.imgur.com/zyzKR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zyzKR.png" alt="enter image description here" /></a></p>
<p>You can see here that the first two rows' sum is 1 and that is given in the first two rows of the new column (x2). Next, the third and fourth-row sum is given in the 3rd and fourth row of the new column. Can anyone help?</p>
|
[
{
"answer_id": 74592515,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "gl library(dplyr)\ndf <- df %>%\n group_by(grp = as.integer(gl(n(), 2, n()))) %>% \n mutate(x2 = sum(x1)) %>% \n ungroup %>% \n select(-grp)\n df\n# A tibble: 6 × 2\n x1 x2\n <dbl> <dbl>\n1 0 1\n2 1 1\n3 1 2\n4 1 2\n5 1 1\n6 0 1\n collapse/data.table library(data.table)\nlibrary(collapse)\nsetDT(df)[, x2 := fsum(x1, g = rep(.I, each = 2, length.out = .N), TRA = 1)]\n > df\n x1 x2\n <num> <num>\n1: 0 1\n2: 1 1\n3: 1 2\n4: 1 2\n5: 1 1\n6: 0 1\n"
},
{
"answer_id": 74592522,
"author": "Vinícius Félix",
"author_id": 9696037,
"author_profile": "https://Stackoverflow.com/users/9696037",
"pm_score": 2,
"selected": false,
"text": "dplyr library(dplyr)\n\n\nx1<- c(0,1,1,1,1,0)\n\ndf <- data.frame(x1)\n\nlen_df <- nrow(df)\naux <- rep(seq(1:(len_df/2)),each = 2)[1:len_df]\n\ndf %>% \n mutate(aux = aux) %>% \n group_by(aux) %>% \n mutate(x2 = sum(x1)) %>% \n ungroup() %>%\n select(-aux)\n\n# A tibble: 6 x 2\n x1 x2\n <dbl> <dbl>\n1 0 1\n2 1 1\n3 1 2\n4 1 2\n5 1 1\n6 0 1\n"
},
{
"answer_id": 74592555,
"author": "Santiago",
"author_id": 13507658,
"author_profile": "https://Stackoverflow.com/users/13507658",
"pm_score": 3,
"selected": true,
"text": "library(dplyr)\n\ndf %>%\n mutate(group = (row_number() - 1) %/% 2) %>%\n group_by(group) %>%\n mutate(x2 = sum(x1)) %>%\n ungroup() %>%\n select(-group)\n# # A tibble: 6 × 2\n# x1 x2\n# <dbl> <dbl>\n# 1 0 1\n# 2 1 1\n# 3 1 2\n# 4 1 2\n# 5 1 1\n# 6 0 1\n"
},
{
"answer_id": 74592705,
"author": "M.Viking",
"author_id": 10276092,
"author_profile": "https://Stackoverflow.com/users/10276092",
"pm_score": 1,
"selected": false,
"text": "df<-data.frame(x1=c(0,1,1,1,1,0))\n\ndf$x2<-rep(lapply(split(df, rep(1:3, each=2)), sum), each=2)\n\n# x1 x2\n#1 0 1\n#2 1 1\n#3 1 2\n#4 1 2\n#5 1 1\n#6 0 1\n"
},
{
"answer_id": 74592806,
"author": "onyambu",
"author_id": 8380272,
"author_profile": "https://Stackoverflow.com/users/8380272",
"pm_score": 1,
"selected": false,
"text": " transform(df,x2 = ave(x1, gl(nrow(df)/2, 2), FUN = sum))\n\n x1 x2\n1 0 1\n2 1 1\n3 1 2\n4 1 2\n5 1 1\n6 0 1\n"
},
{
"answer_id": 74593420,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 2,
"selected": false,
"text": "ave ceiling > transform(df, x2 = ave(x1, ceiling(seq_along(x1) / 2)) * 2)\n x1 x2\n1 0 1\n2 1 1\n3 1 2\n4 1 2\n5 1 1\n6 0 1\n"
},
{
"answer_id": 74600878,
"author": "jblood94",
"author_id": 9463489,
"author_profile": "https://Stackoverflow.com/users/9463489",
"pm_score": 1,
"selected": false,
"text": "x1 <- sample(0:1, 1e4, 1)\n\nmicrobenchmark::microbenchmark(\n matrix = rep(colSums(matrix(x1, 2)), each = 2),\n recycle = x1 + x1[seq(x1) + c(1, -1)],\n cumsum = rep(diff(cumsum(c(0, x1))[seq(1, length(x1) + 1, 2)]), each = 2),\n Thomas = ave(x1, ceiling(seq_along(x1)/2))*2,\n onyambu = ave(x1, gl(length(x1)/2, 2), FUN = sum),\n check = \"equal\"\n)\n#> Unit: microseconds\n#> expr min lq mean median uq max neval\n#> matrix 65.001 69.6510 79.27203 78.4510 82.1510 148.501 100\n#> recycle 95.001 100.6505 108.65003 107.5510 110.6010 176.901 100\n#> cumsum 137.201 148.9010 169.61090 166.5505 177.7015 340.002 100\n#> Thomas 24645.401 25297.2010 26450.46994 25963.3515 27463.2010 31803.101 100\n#> onyambu 3774.902 3935.7510 4444.36500 4094.3520 4336.1505 11070.301 100\n data.table library(data.table)\nlibrary(collapse)\n\nx1 <- sample(0:1, 1e6, 1)\ndf <- data.frame(x1)\n\nmicrobenchmark::microbenchmark(\n matrix = setDT(df)[, x2 := rep(colSums(matrix(x1, 2)), each = 2)],\n recycle = setDT(df)[, x2 := x1 + x1[.I + c(1, -1)]],\n akrun = setDT(df)[, x2 := fsum(x1, g = rep(.I, each = 2, length.out = .N), TRA = 1)],\n check = \"identical\"\n)\n#> Unit: milliseconds\n#> expr min lq mean median uq max neval\n#> matrix 8.053302 8.937301 10.64786 9.376551 12.51890 17.2037 100\n#> recycle 12.117101 12.965950 16.57696 14.003151 17.09805 56.4729 100\n#> akrun 10.071701 10.611051 14.42578 11.291601 14.79090 55.1141 100\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9691385/"
] |
74,592,503
|
<p>i was writing a code to input a sentence of user then change its whitespaces to ... and print the sentence.</p>
<p>hi rocks
I intended to input a sentence and change its whitespaces to "..."
I wrote this code:</p>
<pre><code> a=input("inter your sentence: ")
#split in to n str
#print every str with ... as whitespace
a=a.split()
for x in a:
print(x, sep='...',end="")
</code></pre>
<p>if I input <strong>this is a test</strong>, i expected to see</p>
<p>this...is...a...test</p>
<p>but it doesn't work
it gives me</p>
<p>"thisisatest</p>
|
[
{
"answer_id": 74592515,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "gl library(dplyr)\ndf <- df %>%\n group_by(grp = as.integer(gl(n(), 2, n()))) %>% \n mutate(x2 = sum(x1)) %>% \n ungroup %>% \n select(-grp)\n df\n# A tibble: 6 × 2\n x1 x2\n <dbl> <dbl>\n1 0 1\n2 1 1\n3 1 2\n4 1 2\n5 1 1\n6 0 1\n collapse/data.table library(data.table)\nlibrary(collapse)\nsetDT(df)[, x2 := fsum(x1, g = rep(.I, each = 2, length.out = .N), TRA = 1)]\n > df\n x1 x2\n <num> <num>\n1: 0 1\n2: 1 1\n3: 1 2\n4: 1 2\n5: 1 1\n6: 0 1\n"
},
{
"answer_id": 74592522,
"author": "Vinícius Félix",
"author_id": 9696037,
"author_profile": "https://Stackoverflow.com/users/9696037",
"pm_score": 2,
"selected": false,
"text": "dplyr library(dplyr)\n\n\nx1<- c(0,1,1,1,1,0)\n\ndf <- data.frame(x1)\n\nlen_df <- nrow(df)\naux <- rep(seq(1:(len_df/2)),each = 2)[1:len_df]\n\ndf %>% \n mutate(aux = aux) %>% \n group_by(aux) %>% \n mutate(x2 = sum(x1)) %>% \n ungroup() %>%\n select(-aux)\n\n# A tibble: 6 x 2\n x1 x2\n <dbl> <dbl>\n1 0 1\n2 1 1\n3 1 2\n4 1 2\n5 1 1\n6 0 1\n"
},
{
"answer_id": 74592555,
"author": "Santiago",
"author_id": 13507658,
"author_profile": "https://Stackoverflow.com/users/13507658",
"pm_score": 3,
"selected": true,
"text": "library(dplyr)\n\ndf %>%\n mutate(group = (row_number() - 1) %/% 2) %>%\n group_by(group) %>%\n mutate(x2 = sum(x1)) %>%\n ungroup() %>%\n select(-group)\n# # A tibble: 6 × 2\n# x1 x2\n# <dbl> <dbl>\n# 1 0 1\n# 2 1 1\n# 3 1 2\n# 4 1 2\n# 5 1 1\n# 6 0 1\n"
},
{
"answer_id": 74592705,
"author": "M.Viking",
"author_id": 10276092,
"author_profile": "https://Stackoverflow.com/users/10276092",
"pm_score": 1,
"selected": false,
"text": "df<-data.frame(x1=c(0,1,1,1,1,0))\n\ndf$x2<-rep(lapply(split(df, rep(1:3, each=2)), sum), each=2)\n\n# x1 x2\n#1 0 1\n#2 1 1\n#3 1 2\n#4 1 2\n#5 1 1\n#6 0 1\n"
},
{
"answer_id": 74592806,
"author": "onyambu",
"author_id": 8380272,
"author_profile": "https://Stackoverflow.com/users/8380272",
"pm_score": 1,
"selected": false,
"text": " transform(df,x2 = ave(x1, gl(nrow(df)/2, 2), FUN = sum))\n\n x1 x2\n1 0 1\n2 1 1\n3 1 2\n4 1 2\n5 1 1\n6 0 1\n"
},
{
"answer_id": 74593420,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 2,
"selected": false,
"text": "ave ceiling > transform(df, x2 = ave(x1, ceiling(seq_along(x1) / 2)) * 2)\n x1 x2\n1 0 1\n2 1 1\n3 1 2\n4 1 2\n5 1 1\n6 0 1\n"
},
{
"answer_id": 74600878,
"author": "jblood94",
"author_id": 9463489,
"author_profile": "https://Stackoverflow.com/users/9463489",
"pm_score": 1,
"selected": false,
"text": "x1 <- sample(0:1, 1e4, 1)\n\nmicrobenchmark::microbenchmark(\n matrix = rep(colSums(matrix(x1, 2)), each = 2),\n recycle = x1 + x1[seq(x1) + c(1, -1)],\n cumsum = rep(diff(cumsum(c(0, x1))[seq(1, length(x1) + 1, 2)]), each = 2),\n Thomas = ave(x1, ceiling(seq_along(x1)/2))*2,\n onyambu = ave(x1, gl(length(x1)/2, 2), FUN = sum),\n check = \"equal\"\n)\n#> Unit: microseconds\n#> expr min lq mean median uq max neval\n#> matrix 65.001 69.6510 79.27203 78.4510 82.1510 148.501 100\n#> recycle 95.001 100.6505 108.65003 107.5510 110.6010 176.901 100\n#> cumsum 137.201 148.9010 169.61090 166.5505 177.7015 340.002 100\n#> Thomas 24645.401 25297.2010 26450.46994 25963.3515 27463.2010 31803.101 100\n#> onyambu 3774.902 3935.7510 4444.36500 4094.3520 4336.1505 11070.301 100\n data.table library(data.table)\nlibrary(collapse)\n\nx1 <- sample(0:1, 1e6, 1)\ndf <- data.frame(x1)\n\nmicrobenchmark::microbenchmark(\n matrix = setDT(df)[, x2 := rep(colSums(matrix(x1, 2)), each = 2)],\n recycle = setDT(df)[, x2 := x1 + x1[.I + c(1, -1)]],\n akrun = setDT(df)[, x2 := fsum(x1, g = rep(.I, each = 2, length.out = .N), TRA = 1)],\n check = \"identical\"\n)\n#> Unit: milliseconds\n#> expr min lq mean median uq max neval\n#> matrix 8.053302 8.937301 10.64786 9.376551 12.51890 17.2037 100\n#> recycle 12.117101 12.965950 16.57696 14.003151 17.09805 56.4729 100\n#> akrun 10.071701 10.611051 14.42578 11.291601 14.79090 55.1141 100\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20529592/"
] |
74,592,512
|
<p>The code is supposed to print out 13:Hello World!, but the output is only 13:.</p>
<pre><code>#include <stdio.h>
int main(){
char *str = "Hello World!\n";
int Laenge= 0;
while (*str++){
++Laenge;
}
printf(" %d:%c\n", Laenge, *str);
return 0;
}
</code></pre>
|
[
{
"answer_id": 74592536,
"author": "GaryMBloom",
"author_id": 3159059,
"author_profile": "https://Stackoverflow.com/users/3159059",
"pm_score": 2,
"selected": false,
"text": "str str str *str str %s str %c *str printf()"
},
{
"answer_id": 74592602,
"author": "NoobMaster24",
"author_id": 20616387,
"author_profile": "https://Stackoverflow.com/users/20616387",
"pm_score": 1,
"selected": true,
"text": "#include <stdio.h>\n\nint main()\n{\n char *str = \"HELLO WORLD!\\n\";\n int len = 0;\n \n while(*(str + len) != '\\0'){\n len++;\n }\n printf(\"%d:%s\", len, str);\n\n return 0;\n}\n"
},
{
"answer_id": 74592617,
"author": "pm100",
"author_id": 173397,
"author_profile": "https://Stackoverflow.com/users/173397",
"pm_score": 0,
"selected": false,
"text": "#include <stdio.h>\nint main(){\n\n char *str = \"Hello World!\\n\";\n char *temp = str;\n int Laenge= 0;\n\n while (*temp++){\n\n ++Laenge;\n } \n printf(\" %d:%c\\n\", Laenge, str);\n return 0;\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13963585/"
] |
74,592,543
|
<p>I have below list of text files , I wanted to combine group of files like below</p>
<p>Inv030001.txt - should have all data of files starting with Inv030001</p>
<p>Inv030002.txt - should have all data of files starting with Inv030002</p>
<p><a href="https://i.stack.imgur.com/GozGp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GozGp.png" alt="enter image description here" /></a></p>
<p>I tried below code but it's not working</p>
<pre><code>filenames = glob(textfile_dir+'*.txt')
for fname in filenames:
filename = fname.split('\\')[-1]
current_invoice_number = (filename.split('_')[0]).split('.')[0]
prev_invoice_number = current_invoice_number
with open(textfile_dir + current_invoice_number+'.txt', 'w') as outfile:
for eachfile in fnmatch.filter(os.listdir(textfile_dir), '*[!'+current_invoice_number+'].txt'):
current_invoice_number = (eachfile.split('_')[0]).split('.')[0]
if(current_invoice_number == prev_invoice_number):
with open(textfile_dir+eachfile) as infile:
for line in infile:
outfile.write(line)
prev_invoice_number = current_invoice_number
else:
with open(textfile_dir+eachfile) as infile:
for line in infile:
outfile.write(line)
prev_invoice_number = current_invoice_number
#break;
</code></pre>
|
[
{
"answer_id": 74592778,
"author": "Mark",
"author_id": 2203038,
"author_profile": "https://Stackoverflow.com/users/2203038",
"pm_score": 0,
"selected": false,
"text": "from glob import glob, fnmatch\nimport os\ntextfile_dir=\"invs\" + os.sep # # I changed this to os.sep since I'm on a MAC - hopefully works in windows, too\nfilenames = glob(textfile_dir+'*.txt')\nfor fname in filenames:\n filename = fname.split(os.sep)[-1] \n current_invoice_number = (filename.split('_')[0]).split('.')[0]\n with open(textfile_dir + current_invoice_number+'.txt', 'a') as outfile:\n with open(fname) as infile:\n for line in infile:\n outfile.write(line)\n 'a'"
},
{
"answer_id": 74592899,
"author": "OneMadGypsy",
"author_id": 10292330,
"author_profile": "https://Stackoverflow.com/users/10292330",
"pm_score": 2,
"selected": true,
"text": "task filenames import os\nfrom glob import glob\n\n#you'll have to change this path to yours\nroot = os.path.join(os.getcwd(), 'texts/')\n\n#sorting this may be redundant \npaths = sorted(glob(root+'*.txt'))\n\nfor path in paths:\n #task: get filename\n filename = path.split('\\\\')[-1]\n #task: get invoice number\n invnum = filename.split('_')[0]\n #task: open in and out files\n with open(f'{root}{invnum}.txt', 'a') as out_, open(path, 'r') as in_:\n #task: append in contents to out\n out_.write(in_.read())\n"
},
{
"answer_id": 74593128,
"author": "ZKS",
"author_id": 4324496,
"author_profile": "https://Stackoverflow.com/users/4324496",
"pm_score": 0,
"selected": false,
"text": "filenames = glob(textfile_dir+'*.txt')\ndd = defaultdict(list)\nfor filename in filenames:\nname, ext = os.path.splitext(filename)\nname = name.split('\\\\')[-1].split('_')[0]\ndd[name].append(filename)\n\nfor key, fnames in dd.items():\nwith open(textfile_dir+key+'.txt', \"w\") as newfile:\n for line in fileinput.FileInput(fnames):\n newfile.write(line)\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4324496/"
] |
74,592,548
|
<p>In fact When I do <code>pip freeze > requirements.txt</code> to put all the packages that I use in my project in a requirements.txt, it puts all python packages that I have in my pc and this despite I have activated my visual environment.</p>
<p>In my project path I activated my venv then I did <code>pip freeze > requirements.txt</code>
I had a requirement.txt with packages that had nothing to do with my project. I installed all my packages with pip. What did i did wrong.</p>
<p>Any help would be welcome</p>
|
[
{
"answer_id": 74592622,
"author": "Yaseen",
"author_id": 20616507,
"author_profile": "https://Stackoverflow.com/users/20616507",
"pm_score": 1,
"selected": false,
"text": "python -m venv (venv name here) --no-site-packages python3 -m venv (venv name here) --no-site-packages"
},
{
"answer_id": 74597795,
"author": "JL Peyret",
"author_id": 1394353,
"author_profile": "https://Stackoverflow.com/users/1394353",
"pm_score": 0,
"selected": false,
"text": "pip freeze > local.global.txt\n\ndeactivate\n\npip freeze > global.txt\n diff global.txt local.global.txt\n > < > Django==3.2.14\n> django-celery-results==2.4.0\n> django-debug-toolbar==3.5.0\n> django-redis-cache==3.0.1\n> django-waffle==2.5.0\n> django-webpack-loader==1.6.0\n jupyter==1.0.0\njupyter-client==7.1.2\njupyter-console==6.4.0\njupyter-core==4.9.2\njupyterlab-pygments==0.1.2\njupyterlab-widgets==1.0.2\n requirements.txt > # yes the 2 > are not a typo.\ndiff global.txt local.global.txt | grep '>' > requirements.txt \n > global.txt"
},
{
"answer_id": 74597983,
"author": "Jamiu Shaibu",
"author_id": 19290081,
"author_profile": "https://Stackoverflow.com/users/19290081",
"pm_score": 1,
"selected": false,
"text": "pip freeze pip freeze requirements.txt $ pipreqs --encoding=utf8 <project-dir> requirements.txt pip pipreqs pip install pipreqs\n requirements.txt $ pipreqs --encoding=utf8 [<path>]\n pipreqs --encoding=utf8 [<path>]\n \\ \\\\ FileNotFoundError: [Errno 2] No such file or directory: pipreqs --encoding=utf8 projects\\working_directory\n FileNotFoundError: [Errno 2] No such file or directory: 'projectsworking_directory\\\\requirements.txt'\n pipreqs --encoding=utf8 projects\\\\working_directory\n INFO: Successfully saved requirements file in projects\\working_directory\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20616501/"
] |
74,592,580
|
<p>Assume a dataframe <code>dat</code> with p-values.</p>
<pre><code>dat <- data.frame(var1 = c("0.12", "0.12", "0.12*"),
var2 = c("0.12", "0.12", "0.12"),
var3 = c("0.12", "0.12", "0.12"))
</code></pre>
<p>How do I test which rows contain an asterisk?</p>
<p>Attempt 1:</p>
<pre><code>dat %>%
+ mutate(anyTRUE = if_any(.rows = contains('\\*'), isTRUE))
var1 var2 var3 anyTRUE
1 0.12 0.12 0.12 TRUE
2 0.12 0.12 0.12 TRUE
3 0.12* 0.12 0.12 TRUE
</code></pre>
|
[
{
"answer_id": 74592592,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 4,
"selected": true,
"text": "str_detect/grepl contains/matches/starts_with/ends_with select-helpers library(stringr)\nlibrary(dplyr)\ndat <- dat %>%\n mutate(anyTRUE = if_any(everything(), ~ str_detect(.x, fixed(\"*\"))))\n dat\n var1 var2 var3 anyTRUE\n1 0.12 0.12 0.12 FALSE\n2 0.12 0.12 0.12 FALSE\n3 0.12* 0.12 0.12 TRUE\n fixed pattern regex * \\\\ fixed base R dat$anyTRUE <- Reduce(`|`, lapply(dat, grepl, pattern = \"*\", fixed = TRUE))\n"
},
{
"answer_id": 74592735,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 2,
"selected": false,
"text": "unite library(dplyr)\nlibrary(tidyr)\nlibrary(stringr)\n\ndat %>% \n unite(check, remove = FALSE) %>% \n mutate(check = str_detect(check, '\\\\*')) \n check var1 var2 var3\n1 FALSE 0.12 0.12 0.12\n2 FALSE 0.12 0.12 0.12\n3 TRUE 0.12* 0.12 0.12\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3981290/"
] |
74,592,600
|
<p>Developing a 3D VR application on Unity using OpenXR (2021.3.11f1).</p>
<p>I'm trying to make it so that a Canvas is hidden until a certain condition is met. That condition is that another 3D object's x position is under 45. Here is my script right now:</p>
<pre><code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OptionsBox : MonoBehaviour
{
public GameObject canvas;
public GameObject playerObj;
void Start()
{
canvas.SetActive(false);
}
void Update()
{
if (playerObj.transform.position.x < 45){
canvas.SetActive(true);
}
}
}
</code></pre>
<p>I then made an empty GameObject and inputted the script into there:</p>
<p><a href="https://i.stack.imgur.com/4XayH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4XayH.png" alt="enter image description here" /></a></p>
<p>However, when I run my scene, the canvas is still displayed. What have I done wrong?</p>
|
[
{
"answer_id": 74592651,
"author": "Orkad",
"author_id": 8656043,
"author_profile": "https://Stackoverflow.com/users/8656043",
"pm_score": -1,
"selected": false,
"text": "Canvas Alpha"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18883443/"
] |
74,592,604
|
<p>I'm trying to upload files to S3 using API Gateway and Lambda, all the processes work fine until I arrive at the Lambda, my lambda looks like this:</p>
<pre><code>import base64
import boto3
import os
s3_client = boto3.client('s3')
bucket_name = os.environ['S3_BUCKET_NAME']
def lambda_handler(event, context):
contend_decode = base64.b64decode(event['body'])
response = s3_client.put_object(Bucket=bucket_name, Body=contend_decode)
print(response)
return {
'statusCode': 200,
'body': 'File uploaded'
}
</code></pre>
<p>When I upload for example an mp3 file I receive an error that says:</p>
<pre><code>[ERROR] ValueError: string argument should contain only ASCII characters
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 10, in lambda_handler
contend_decode = base64.b64decode(event['body'])
File "/var/lang/lib/python3.8/base64.py", line 80, in b64decode
s = _bytes_from_decode_data(s)
File "/var/lang/lib/python3.8/base64.py", line 39, in _bytes_from_decode_data
raise ValueError('string argument should contain only ASCII characters')
[ERROR] ValueError: string argument should contain only ASCII characters Traceback (most recent call last): File "/var/task/lambda_function.py", line 10, in lambda_handler contend_decode = base64.b64decode(event['body']) File "/var/lang/lib/python3.8/base64.py", line 80, in b64decode s = _bytes_from_decode_data(s) File "/var/lang/lib/python3.8/base64.py", line 39, in _bytes_from_decode_data raise ValueError('string argument should contain only ASCII characters')
</code></pre>
<p>Any idea about this issue, please?</p>
<p><strong>Edit:</strong></p>
<p>The content of the event is something like this:</p>
<pre><code>{
"resource": "/upload",
"path": "/upload",
"httpMethod": "POST",
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br",
"CloudFront-Forwarded-Proto": "https",
"CloudFront-Is-Desktop-Viewer": "true",
"CloudFront-Is-Mobile-Viewer": "false",
"CloudFront-Is-SmartTV-Viewer": "false",
"CloudFront-Is-Tablet-Viewer": "false",
"CloudFront-Viewer-ASN": "5410",
"CloudFront-Viewer-Country": "FR",
"Content-Type": "audio/mpeg",
"Host": "um8xxxxpxx.execute-api.eu-west-1.amazonaws.com",
"Postman-Token": "fe49e15f-82c6-44c7-8399-4b6fba9b9abc",
"User-Agent": "PostmanRuntime/7.29.2",
"Via": "1.1 12bc6711250373a4xxxxxxxxxx44504.cloudfront.net (CloudFront)",
"X-Amz-Cf-Id": "5Zv2MVCxxxxxxxxxxxxyzMuv_CfIAxxxxxxxxxxxxJyz4JtHb-QImYZGQ==",
"X-Amzn-Trace-Id": "Root=1-6383d306-4e81300e0000000c3262b7a45",
"x-api-key": "g4KOPDl5zoB0E2QBpAAXSaESDFyGkR38f000",
"X-Forwarded-For": "1XX.XX9.2XX.XX9, 1XX.XX6.XX5.XXX",
"X-Forwarded-Port": "443",
"X-Forwarded-Proto": "https"
},
"multiValueHeaders": {
"Accept": [
"*/*"
],
"Accept-Encoding": [
"gzip, deflate, br"
],
"CloudFront-Forwarded-Proto": [
"https"
],
"CloudFront-Is-Desktop-Viewer": [
"true"
],
"CloudFront-Is-Mobile-Viewer": [
"false"
],
"CloudFront-Is-SmartTV-Viewer": [
"false"
],
"CloudFront-Is-Tablet-Viewer": [
"false"
],
"CloudFront-Viewer-ASN": [
"5410"
],
"CloudFront-Viewer-Country": [
"FR"
],
"Content-Type": [
"audio/mpeg"
],
"Host": [
"um8xxxxpxx.execute-api.eu-west-1.amazonaws.com"
],
"Postman-Token": [
"fDDDDf-82c8-44c9-DDD1-4b6f9QASFF9abc"
],
"User-Agent": [
"PostmanRuntime/7.29.2"
],
"Via": [
"1.1 12bVASD16aeca2DDD44504.cloudfront.net (CloudFront)"
],
"X-Amz-Cf-Id": [
"5Zv2MVCnaDDDzMuv_CfIA6iC89CiUnjDDDAZXAb-QImYZGQ=="
],
"X-Amzn-Trace-Id": [
"Root=1-6383AZDD-4e81002e022374c326hu8a45"
],
"x-api-key": [
"g4KOPDl5zoBia3cT4pYMkynzyGkX00aa"
],
"X-Forwarded-For": [
"1XX.XX9.2XX.XX9, 1XX.XX6.XX5.XXX"
],
"X-Forwarded-Port": [
"443"
],
"X-Forwarded-Proto": [
"https"
]
},
"queryStringParameters": "None",
"multiValueQueryStringParameters": "None",
"pathParameters": "None",
"stageVariables": "None",
"requestContext": {
"resourceId": "adddazq",
"resourcePath": "/upload",
"httpMethod": "POST",
"extendedRequestId": "cR3o-zddEFgazz=",
"requestTime": "27/Nov/2022:21:13:42 +0000",
"path": "/dev/upload",
"accountId": "114782879802",
"protocol": "HTTP/1.1",
"stage": "dev",
"domainPrefix": "ua8xjwxraf",
"requestTimeEpoch": 1669583622098,
"requestId": "23e099f9-eda4-42b2-8b4f-b1aaea589978",
"identity": {
"cognitoIdentityPoolId": "None",
"cognitoIdentityId": "None",
"apiKey": "h4KOPDl5zoqsdT4pYMkynzdddaz8f95560",
"principalOrgId": "None",
"cognitoAuthenticationType": "None",
"userArn": "None",
"apiKeyId": "z887qsddox4",
"userAgent": "PostmanRuntime/7.29.2",
"accountId": "None",
"caller": "None",
"sourceIp": "176.139.21.129",
"accessKey": "None",
"cognitoAuthenticationProvider": "None",
"user": "None"
},
"domainName": "um8xxxxpxx.execute-api.eu-west-1.amazonaws.com",
"apiId": "um8xxxxpxx"
},
"body": "\x04\x08-P�\x10,Gh�m\x0c\x06K����Te�U�-��\r\x01�Y��l�,3�\x11�Q�4$�........6��\x1872Ip�d�p\x1d�M�PX�0`�x�0����d�\x0f�\x0c.ǃ��\x12\x00\x00\r \x00\x00\x01\x18��........",
"isBase64Encoded": "False"
}
</code></pre>
<p>Note: I put just a little bit of characters that exist in the body, just for demonstration purpose.</p>
|
[
{
"answer_id": 74593716,
"author": "John Rotenstein",
"author_id": 174777,
"author_profile": "https://Stackoverflow.com/users/174777",
"pm_score": 1,
"selected": false,
"text": "contend_decode = base64.b64decode(event['body'])\n event['body'] content contend_decode = base64.b64decode(event['content'])\n"
},
{
"answer_id": 74594176,
"author": "Shmack",
"author_id": 3155240,
"author_profile": "https://Stackoverflow.com/users/3155240",
"pm_score": 2,
"selected": false,
"text": "event['body'] event['body'] \"\\x04\\x08-P�\\x10,Gh�m\\x0c\\x06K����Te�U�-��\\r\\x01�Y��l�,3�\\x11�Q�4$�........6��\\x1872Ip�d�p\\x1d�M�PX�0`�x�0����d�\\x0f�\\x0c.ǃ��\\x12\\x00\\x00\\r \\x00\\x00\\x01\\x18��........\"\n \"TWFueSBoYW5kcyBtYWtlIGxpZ2h0IHdvcmsu\" b64.b64decode(\"TWFueSBoYW5kcyBtYWtlIGxpZ2h0IHdvcmsu\") a = b\"Many hands make light work.\" b = list(a) [77, 97, 110, 121, 32, 104, 97, 110, 100, 115, 32, 109, 97, 107, 101, 32, 108, 105, 103, 104, 116, 32, 119, 111, 114, 107, 46] \"\".join([hex(c).replace(\"0x\", \"\\\\x\") for c in b]) \\x4d\\x61\\x6e\\x79\\x20\\x68\\x61\\x6e\\x64\\x73\\x20\\x6d\\x61\\x6b\\x65\\x20\\x6c\\x69\\x67\\x68\\x74\\x20\\x77\\x6f\\x72\\x6b\\x2e with open(filename, \"rb\") as f; a = f.read() event['body'] b\"hello world\" with open()... event['body'] \\x event['body'] \"\\x1872Ip�d�p\" a = \"hello world\"\nb = a.encode(\"utf-8\")\n# or\nc = bytes(a, \"utf-8\")\n# or - the one below I think defaults to utf8\na = b\"hello world\"\n\n# the closest I could get to hex representation of the string was from this\n# \"\".join([hex(ord(c)).replace(\"0x\", \"\\\\x\") for c in a])\n isBase64Encoded isBase64Encoded event['body'] import base64\n# pre edit\nif not event['isBase64Encoded']:\n event['body'] = bytes(event[body], \"whatever that encoding is\").decode()\n # b64encode takes a string and converts it to a bytes like object.\n # b64decode takes a bytes like object and converts it to a string.\n event['body'] = base64.b64decode(event['body'])\nprint(event['body'])\n\n# post edit\n# you might be able to read bytes with an arbitrary encoding using BytesIO\nfrom io import BytesIO \n\nif event['isBase64Encoded']:\n # this would've been sent as the default according to my notes from the edit\n # take the string, convert it to bytes, then decode it - should be a base64 string with a utf8 encoding\n event['body'] = bytes(event['body']).decode()\n # decode the utf8 string to base64 bytes\n event['body'] = base64.b64decode(event['body'])\nelse:\n #event['body'] = bytes(event[body], some encoding)\n event['body'] = BytesIO(event[body]).read()\n decode() base64decode() response = client.put_object(\n #Body=bytes(event[\"body\"], encoding),\n # event['body'] should already be bytes by now as per the post edit comments\n Body=event[\"body\"],\n Bucket=\"my_bucket\",\n #ContentEncoding=event[\"multiValueHeaders\"][\"Accept-Encoding\"],\n ContentType=event[\"multiValueHeaders\"][\"Content-Type\"],\n Key=\"my/object/name.mp4\"\n)\n put_object() isBase64Encoded event['body'] put_object() ContentEncoding import base64\nimport boto3\nimport os\n\ns3_client = boto3.client('s3')\nbucket_name = os.environ['S3_BUCKET_NAME']\n\n\ndef lambda_handler(event, context):\n if not event['isBase64Encoded']:\n try:\n event['body'] = bytes(event[body], \"whatever that encoding is\").decode()\n except:\n return {\n # AWS probably returns a 403, so maybe return something different for debugging?\n 'statusCode': 406,\n 'body': 'Misconfigured object.'\n }\n else:\n try:\n event['body'] = base64.b64decode(event['body'])\n except:\n return {\n # AWS probably returns a 403, so maybe return something different for debugging?\n 'statusCode': 406,\n 'body': 'Misconfigured object.'\n }\n\n try:\n response = client.put_object(\n Body=bytes(event[\"body\"], encoding),\n Bucket=\"my_bucket\",\n #ContentEncoding=event[\"multiValueHeaders\"][\"Accept-Encoding\"],\n ContentType=event[\"multiValueHeaders\"][\"Content-Type\"],\n Key=\"my/object/name.mp4\"\n )\n except:\n return {\n # AWS probably returns a 403, so maybe return something different for debugging?\n 'statusCode': 406,\n 'body': 'Misconfigured object.'\n }\n else:\n print(response)\n return {\n 'statusCode': 200,\n 'body': 'File uploaded'\n }\n import base64\nimport boto3\nimport os\nfrom io import BytesIO\n\ns3_client = boto3.client('s3')\nbucket_name = os.environ['S3_BUCKET_NAME']\n\n\ndef lambda_handler(event, context):\n\n if event['isBase64Encoded']:\n # this would've been sent as the default according to my notes from the edit\n # take the string, convert it to bytes, then decode it - should be a base64 string with a utf8 encoding\n event['body'] = bytes(event['body']).decode()\n # decode the utf8 string to base64 bytes\n event['body'] = base64.b64decode(event['body'])\n else:\n #event['body'] = bytes(event[body], some encoding)\n event['body'] = BytesIO(event[body]).read()\n\n try:\n response = client.put_object(\n Body=bytes(event[\"body\"], encoding),\n Bucket=\"my_bucket\",\n #ContentEncoding=event[\"multiValueHeaders\"][\"Accept-Encoding\"],\n ContentType=event[\"multiValueHeaders\"][\"Content-Type\"],\n Key=\"my/object/name.mp4\"\n )\n except:\n return {\n # AWS probably returns a 403, so maybe return something different for debugging?\n 'statusCode': 406,\n 'body': 'Misconfigured object.'\n }\n else:\n print(response)\n return {\n 'statusCode': 200,\n 'body': 'File uploaded'\n }\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74592604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13118086/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.