qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,515,977
|
<p>I have multiple dataframes (<code>sf</code> objects). Each dataframe contains a <code>geometry</code>, <code>name</code> and <code>probability</code> column. They all have the same extents, but only overlap in some regions.</p>
<p>Here is some example data using two dataframes:</p>
<pre><code>nc<-st_read(
system.file("gpkg/nc.gpkg",
package="sf"),
quiet=TRUE)
a<-nc %>%
select(c('geom')) %>%
slice(1:60) %>%
mutate(probability=runif(n=60,
min=1,
max=100)) %>%
mutate(name='A')
b<-nc %>%
select(c('geom')) %>%
slice(50:100) %>%
mutate(probability=runif(n=51,
min=1,
max=100)) %>%
mutate(name='B')
</code></pre>
<p>I would like to <code>merge</code>/<code>join</code> these two dataframes (<code>a</code> and <code>b</code>), but in the regions where they overlap, I would like to only keep the <code>name</code> where the <code>probability</code> is highest. The new dataframe should contain the <code>name</code> and <code>probability</code>.</p>
<p>How would I start with such a problem?</p>
|
[
{
"answer_id": 74517200,
"author": "margusl",
"author_id": 646761,
"author_profile": "https://Stackoverflow.com/users/646761",
"pm_score": 3,
"selected": true,
"text": "st_equals nc[50:60,] st_intersects st_intersects ?st_join library(dplyr)\nlibrary(sf)\nlibrary(ggplot2)\n\n# by default st_join uses st_intersects predicate & left_join\n# switching to st_equals & inner join\nab <- st_join(a, b, join = st_equals, suffix = c(\"_a\", \"_b\"), left = F) %>%\n mutate(\n name = if_else(probability_a > probability_b, name_a, name_b),\n probability = pmax(probability_a, probability_b)\n # uncomment to only keep unused columns\n # , .keep = \"unused\"\n )\n\nggplot() +\n geom_sf(data = a, aes(alpha = probability), color = \"gray80\", fill = \"red\") +\n geom_sf(data = b, aes(alpha = probability), color = \"gray80\", fill = \"green\") +\n geom_sf(data = ab, aes(alpha = probability), color = \"gray80\", fill = \"blue\") +\n geom_sf_label(data = ab, aes(label = name), alpha = .5) +\n theme_void()\n ab\n#> Simple feature collection with 11 features and 6 fields\n#> Geometry type: MULTIPOLYGON\n#> Dimension: XY\n#> Bounding box: xmin: -83.9547 ymin: 35.18983 xmax: -75.45698 ymax: 36.22926\n#> Geodetic CRS: NAD27\n#> First 10 features:\n#> probability_a name_a probability_b name_b geom\n#> 50 69.580424 A 91.374717 B MULTIPOLYGON (((-80.29824 3...\n#> 51 48.284343 A 30.066734 B MULTIPOLYGON (((-77.47388 3...\n#> 52 86.259738 A 46.447507 B MULTIPOLYGON (((-80.96143 3...\n#> 53 44.371614 A 33.907073 B MULTIPOLYGON (((-82.2581 35...\n#> 54 25.234930 A 65.436176 B MULTIPOLYGON (((-78.53874 3...\n#> 55 7.997226 A 26.543661 B MULTIPOLYGON (((-82.74389 3...\n#> 56 10.847150 A 48.375980 B MULTIPOLYGON (((-75.78317 3...\n#> 57 32.310899 A 76.864756 B MULTIPOLYGON (((-77.10377 3...\n#> 58 52.344792 A 9.340445 B MULTIPOLYGON (((-83.33182 3...\n#> 59 66.538503 A 87.656812 B MULTIPOLYGON (((-77.80518 3...\n#> name probability\n#> 50 B 91.37472\n#> 51 A 48.28434\n#> 52 A 86.25974\n#> 53 A 44.37161\n#> 54 B 65.43618\n#> 55 B 26.54366\n#> 56 B 48.37598\n#> 57 B 76.86476\n#> 58 A 52.34479\n#> 59 B 87.65681\n set.seed(1)\nnc <- st_read(\n system.file(\"gpkg/nc.gpkg\",\n package = \"sf\"\n ),\n quiet = TRUE\n)\na <- nc %>%\n select(c(\"geom\")) %>%\n slice(1:60) %>%\n mutate(probability = runif(\n n = 60,\n min = 1,\n max = 100\n )) %>%\n mutate(name = \"A\")\nb <- nc %>%\n select(c(\"geom\")) %>%\n slice(50:100) %>%\n mutate(probability = runif(\n n = 51,\n min = 1,\n max = 100\n )) %>%\n mutate(name = \"B\")\n library(purrr)\nlibrary(tidyr)\n\n# add c and d\nc <- nc %>%\n select(c(\"geom\")) %>% slice(45:65) %>%\n mutate(probability = runif(n = 21, min = 1,max = 100)) %>%\n mutate(name = \"C\")\n\nd <- nc %>%\n select(c(\"geom\")) %>% slice(40:70) %>%\n mutate(probability = runif(n = 31, min = 1,max = 100)) %>%\n mutate(name = \"D\")\n\n# collect sf objects into list\nabcd <- list(\"a\" = a,\n \"b\" = b,\n \"c\" = c,\n \"d\" = d) \n\nabcd_ijoin <- abcd %>% \n # rename columns in each sf, skip geom col\n imap(function(sf_, name_) sf_ %>% rename_with(~ paste(.x, name_, sep = '_'), -geom)) %>% \n # $a\n # geom probability_a name_a\n # 1 MULTIPOLYGON (((-81.47276 3... 27.285358 A\n # ...\n \n # \"Reduce a list to a single value by iteratively applying a binary function\"\n # basically st_join(a,b) %>% st_join(c) %>% st_join(d)\n # or st_join(st_join(st_join(a,b),c),d)\n # join = st_equals, left = F are passed to each st_join() call,\n # each call adds 2 columns\n reduce(st_join, join = st_equals, left = F) %>% \n # probability_a name_a probability_b name_b probability_c name_c probability_d name_d geom\n # 50 69.580424 A 91.374717 B 63.51060 C 13.78653 D MULTIPOLYGON (((-80.29824 3...\n # 51 48.284343 A 30.066734 B 39.61781 C 26.38039 D MULTIPOLYGON (((-77.47388 3... \n\n # remove name_* columns\n select(!starts_with(\"name\")) %>% \n # probability_a probability_b probability_c probability_d geom\n # 50 69.580424 91.374717 63.51060 13.78653 MULTIPOLYGON (((-80.29824 3...\n # 51 48.284343 30.066734 39.61781 26.38039 MULTIPOLYGON (((-77.47388 3... \n\n # pivot from wide to long format, \n # probability_a, probability_b, .. values are collected into single \"probability\" column and\n # name-part(a,b,c,..) of column name ends up in \"name\" column\n pivot_longer(starts_with(\"probability\"), names_pattern = \"probability_(.*)\", values_to = \"probability\") %>% \n # A tibble: 44 × 3\n # geom name probability\n # <MULTIPOLYGON [°]> <chr> <dbl>\n # 1 (((-80.29824 35.4949, -80.72652 35.50757, -80.766... a 69.6\n # 2 (((-80.29824 35.4949, -80.72652 35.50757, -80.766... b 91.4\n\n # group by some feature (by geom only works because objects were joined with st_equals)\n # and get row with max probabilty from each group\n group_by(geom) %>% \n slice_max(probability) %>% \n ungroup()\n # A tibble: 11 × 3\n # geom name probability\n # <MULTIPOLYGON [°]> <chr> <dbl>\n # 1 (((-80.29824 35.4949, -80.72652 35.50757, -80.766... b 91.4\n # 2 (((-77.47388 35.42153, -77.50456 35.48483, -77.50... a 48.3\n\nggplot() +\n geom_sf(data = bind_rows(abcd), color = \"gray80\", alpha = .1) +\n geom_sf(data = abcd_ijoin, aes(fill = name, alpha = probability), color = \"gray80\") +\n theme_void()\n"
},
{
"answer_id": 74548029,
"author": "kjtheron",
"author_id": 11858130,
"author_profile": "https://Stackoverflow.com/users/11858130",
"pm_score": 1,
"selected": false,
"text": "@margusl # Merge into one file\nabcd<-rbind(a,b,c,d)\n\n# Spatial selection\n abcd<-abcd %>%\n pivot_longer(prob) %>%\n group_by(geometry) %>%\n slice_max(value) %>% \n ungroup() %>%\n mutate(prob=value) %>%\n select(c(prob,name,geometry))\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74515977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11858130/"
] |
74,516,010
|
<p>I have a text data as</p>
<pre class="lang-none prettyprint-override"><code>A 00
B 05
C d1
D
</code></pre>
<p>I want to read the above text file and trigger a shell script <code>abc.sh</code> when <code>$2</code> is either <code>"05"</code> <code>" "</code> or <code>"d1"</code>. Using Awk, how can this be done?</p>
<p>I tried</p>
<pre><code>$ awk '{ if ($2 ==" " && $2 == "05" && $2 == "d1") run abc.sh else print "HELLO" }' –
</code></pre>
|
[
{
"answer_id": 74516677,
"author": "Dudi Boy",
"author_id": 6266192,
"author_profile": "https://Stackoverflow.com/users/6266192",
"pm_score": 1,
"selected": false,
"text": "awk awk '$2~\"05|d1\"||NF==1{system(\"./abc.sh\")}' input.txt\n"
},
{
"answer_id": 74518187,
"author": "Daweo",
"author_id": 10785975,
"author_profile": "https://Stackoverflow.com/users/10785975",
"pm_score": 2,
"selected": false,
"text": "{ if ($2 ==\" \" && $2 == \"05\" && $2 == \"d1\") run abc.sh else print \"HELLO\" }\n $2==\"\" && 05 d1 || 05 d1 ; else ; run system abc.sh { if ($2 ==\"\" || $2 == \"05\" || $2 == \"d1\"){system(\"bash abc.sh\")}else{print \"HELLO\"}}\n file.txt A 00 \nB 05 \nC d1 \nD \n abc.sh #!/bin/bash\necho 'I am abc.sh'\n awk '{ if ($2 ==\"\" || $2 == \"05\" || $2 == \"d1\"){system(\"bash abc.sh\")}else{print \"HELLO\"}}' file.txt\n HELLO\nI am abc.sh\nI am abc.sh\nI am abc.sh\n abc.sh bash abc.sh system"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20040019/"
] |
74,516,048
|
<p>This is the field.</p>
<pre><code>private static final long BUF_OFFSET
= U.objectFieldOffset(BufferedInputStream.class, "buf");
</code></pre>
<p>This is code which using BUF_OFFSET.</p>
<pre><code>private void fill() throws IOException {
byte[] buffer = getBufIfOpen();
if (markpos < 0)
pos = 0; /* no mark: throw away the buffer */
else if (pos >= buffer.length) { /* no room left in buffer */
if (markpos > 0) { /* can throw away early part of the buffer */
int sz = pos - markpos;
System.arraycopy(buffer, markpos, buffer, 0, sz);
pos = sz;
markpos = 0;
} else if (buffer.length >= marklimit) {
markpos = -1; /* buffer got too big, invalidate mark */
pos = 0; /* drop buffer contents */
} else { /* grow buffer */
int nsz = ArraysSupport.newLength(pos,
1, /* minimum growth */
pos /* preferred growth */);
if (nsz > marklimit)
nsz = marklimit;
byte[] nbuf = new byte[nsz];
System.arraycopy(buffer, 0, nbuf, 0, pos);
**if (!U.compareAndSetReference(this, BUF_OFFSET, buffer, nbuf)) {
// Can't replace buf if there was an async close.
// Note: This would need to be changed if fill()
// is ever made accessible to multiple threads.
// But for now, the only way CAS can fail is via close.
// assert buf == null;
throw new IOException("Stream closed");
}**
buffer = nbuf;
}
}
count = pos;
int n = getInIfOpen().read(buffer, pos, buffer.length - pos);
if (n > 0)
count = n + pos;
}
</code></pre>
<p>This is the code in JDK source about return the value of BUF_OFFSET.</p>
<pre><code>static jlong find_field_offset(jclass clazz, jstring name, TRAPS) {
assert(clazz != NULL, "clazz must not be NULL");
assert(name != NULL, "name must not be NULL");
ResourceMark rm(THREAD);
char *utf_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
InstanceKlass* k = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz)));
jint offset = -1;
for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
Symbol *name = fs.name();
if (name->equals(utf_name)) {
**offset** = fs.offset();
break;
}
}
if (offset < 0) {
THROW_0(vmSymbols::java_lang_InternalError());
}
return field_offset_from_byte_offset(offset);
}
</code></pre>
<p>What does BUF_OFFSET field mean in BufferedInputStream?</p>
<p>I check the BUF_OFFSET out in JDK source code
github:<a href="https://github.com/openjdk/jdk/tree/jdk-17%2B35" rel="nofollow noreferrer">https://github.com/openjdk/jdk/tree/jdk-17%2B35</a>
I have asked a question about what JavaFieldStream is in here.But I am still confused about the BUF_OFFSET.</p>
<p>I guess...Maybe BUF_OFFSET is simliar with the param off which is from FileInputStream's read method?</p>
<pre><code>public int read(byte b[], int off, int len) throws IOException {
return readBytes(b, off, len);
}
</code></pre>
<p>In here,off means where the data copys and fills in from C array to the Java array.So BUF_OFFSET means where data fills in JVM?It's just my guess.</p>
|
[
{
"answer_id": 74530699,
"author": "Generous Badger",
"author_id": 13418296,
"author_profile": "https://Stackoverflow.com/users/13418296",
"pm_score": 0,
"selected": false,
"text": "BUF_OFFSET buf BufferedInputStream Unsafe.compareAndSetReference sun.misc.Unsafe AtomicReferenceFieldUpdater"
},
{
"answer_id": 74547788,
"author": "Stefan Zobel",
"author_id": 1439733,
"author_profile": "https://Stackoverflow.com/users/1439733",
"pm_score": 3,
"selected": true,
"text": "fill() buf buf null close() fill() buf == null fill() if (buf == buffer) buf = null; buf close() Unsafe Unsafe /**\n * Atomically updates Java variable to {@code x} if it is currently\n * holding {@code expected}.\n *\n * <p>This operation has memory semantics of a {@code volatile} read\n * and write. Corresponds to C11 atomic_compare_exchange_strong.\n *\n * @return {@code true} if successful\n */\n@IntrinsicCandidate\npublic final native boolean compareAndSetReference(Object o, long offset,\n Object expected,\n Object x);\n /**\n * Reports the location of the field with a given name in the storage\n * allocation of its class.\n *\n * @throws NullPointerException if any parameter is {@code null}.\n * @throws InternalError if there is no field named {@code name} declared\n * in class {@code c}, i.e., if {@code c.getDeclaredField(name)}\n * would throw {@code java.lang.NoSuchFieldException}.\n *\n * @see #objectFieldOffset(Field)\n */\npublic long objectFieldOffset(Class<?> c, String name) {\n if (c == null || name == null) {\n throw new NullPointerException();\n }\n\n return objectFieldOffset1(c, name);\n}\n static final long buf if (!U.compareAndSetReference(this, BUF_OFFSET, buffer, nbuf)) {\n throw new IOException(\"Stream closed\");\n}\n if (buf == buffer) {\n buf = nbuf;\n} else {\n throw new IOException(\"Stream closed\");\n}\n compareAndSetReference"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20529695/"
] |
74,516,084
|
<p>I'm writing a app that runs on EC2, and currently moving from <strong>local</strong> to <strong>prod</strong> env.</p>
<p>I've read a few blogs that said I should store the env params in <strong>AWS SSM</strong> instead of <code>export</code> them in the terminal.</p>
<p>My question is that, should I fetch these <code>env variables</code> every time the app makes an API call (I think it's not a good option). Or, should I fetch and then store it somewhere within the app? If so, where should I store these env variables after I've fetched them?</p>
<pre><code>const getParametersResponse = await ssm.getParameters({
Names: [
"Client_key",
"Client_Id"
],
WithDecryption: true
}).promise();
</code></pre>
<p>I should run this fetch function <code>getParametersResponse</code> every time the app makes an API call or I should just run it once and then store it somewhere? If so, where do I store these keys?</p>
|
[
{
"answer_id": 74530699,
"author": "Generous Badger",
"author_id": 13418296,
"author_profile": "https://Stackoverflow.com/users/13418296",
"pm_score": 0,
"selected": false,
"text": "BUF_OFFSET buf BufferedInputStream Unsafe.compareAndSetReference sun.misc.Unsafe AtomicReferenceFieldUpdater"
},
{
"answer_id": 74547788,
"author": "Stefan Zobel",
"author_id": 1439733,
"author_profile": "https://Stackoverflow.com/users/1439733",
"pm_score": 3,
"selected": true,
"text": "fill() buf buf null close() fill() buf == null fill() if (buf == buffer) buf = null; buf close() Unsafe Unsafe /**\n * Atomically updates Java variable to {@code x} if it is currently\n * holding {@code expected}.\n *\n * <p>This operation has memory semantics of a {@code volatile} read\n * and write. Corresponds to C11 atomic_compare_exchange_strong.\n *\n * @return {@code true} if successful\n */\n@IntrinsicCandidate\npublic final native boolean compareAndSetReference(Object o, long offset,\n Object expected,\n Object x);\n /**\n * Reports the location of the field with a given name in the storage\n * allocation of its class.\n *\n * @throws NullPointerException if any parameter is {@code null}.\n * @throws InternalError if there is no field named {@code name} declared\n * in class {@code c}, i.e., if {@code c.getDeclaredField(name)}\n * would throw {@code java.lang.NoSuchFieldException}.\n *\n * @see #objectFieldOffset(Field)\n */\npublic long objectFieldOffset(Class<?> c, String name) {\n if (c == null || name == null) {\n throw new NullPointerException();\n }\n\n return objectFieldOffset1(c, name);\n}\n static final long buf if (!U.compareAndSetReference(this, BUF_OFFSET, buffer, nbuf)) {\n throw new IOException(\"Stream closed\");\n}\n if (buf == buffer) {\n buf = nbuf;\n} else {\n throw new IOException(\"Stream closed\");\n}\n compareAndSetReference"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13954573/"
] |
74,516,088
|
<p>I'm trying to find the pixel intensity at the center of bounding box</p>
<p>TO achieve this I'm finding the center coordinates of bounding box and get the pixel intensity of that coordinate as shown below</p>
<pre><code>img_read= cv2.imread(r'image.png')
cv2.rectangle(img_read,(xmin,ymin),(xmax,ymax),(0,0,255),3)
center_x = int((xmin+xmax)//2)
center_y = int((ymin+ymax)//2)
print(center_x,center_y)
cv2.circle(img_read,(center_x,center_y),50,(0,0,255),3)
print('Pixel intensity at:',img_read[center_x][center_y])
plt.imshow(img_read[:,:,::-1])
</code></pre>
<p>when I run this I get error as below</p>
<pre><code>IndexError: index 859 is out of bounds for axis 0 with size 815
</code></pre>
<p>but when I try to draw circle from that point with cv2.circle it draws circle without any errors
How can I access the pixel intensity value at point img_read[center_x][center_y]) ?
I tried with this as well img_read[center_x,center_y] but got same error</p>
<p>any help or suggestion to fix this issue will be appreciated thanks</p>
|
[
{
"answer_id": 74516172,
"author": "imkyjkk",
"author_id": 14790896,
"author_profile": "https://Stackoverflow.com/users/14790896",
"pm_score": -1,
"selected": false,
"text": "img_read[center_y,center_x] \n"
},
{
"answer_id": 74518646,
"author": "Kavya Kommuri",
"author_id": 18726537,
"author_profile": "https://Stackoverflow.com/users/18726537",
"pm_score": 0,
"selected": false,
"text": "#Read the image & get the dimensions \n img_read= cv2.imread(r\"C:\\Users\\Desktop\\test_center_px.tiff\")\n dimensions = img_read.shape\n h, w=dimensions[0], dimensions[1] \n\n#create the bounding box if necessary (not in mine) \n domain = cv2.rectangle(img_read,(0,0),(w,h),(255,0,0),20)\n plt.imshow(domain,cmap='gray')\n \n center_x = w/2\n center_y = h/2\n\n#all we need to do is pass in the (x, y)-coordinates as image[y, x]\n (b, g, r) = img_read[np.int16(center_y), np.int16(center_x)]\n print(\"Color at center pixel is - Red: {}, Green: {}, Blue: {}\".format(r, g, b))\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19669574/"
] |
74,516,103
|
<p>i am new to coding, do you guys create a new dart file for the next screen?</p>
<p>currently i have a homepage with have a start button , do i create a new .dart like a settingpage.dart or continue on homepage?</p>
<p>please advise , thanks.</p>
<p>If i create a new .dart file , what are the code i need to include ?</p>
<pre class="lang-dart prettyprint-override"><code>GestureDetector(
onLongPress: () => // Navigate,
child: const Image(
height: 110,
width: 110,
image: AssetImage("lib/images/start-png.png"),
),
)
</code></pre>
|
[
{
"answer_id": 74516172,
"author": "imkyjkk",
"author_id": 14790896,
"author_profile": "https://Stackoverflow.com/users/14790896",
"pm_score": -1,
"selected": false,
"text": "img_read[center_y,center_x] \n"
},
{
"answer_id": 74518646,
"author": "Kavya Kommuri",
"author_id": 18726537,
"author_profile": "https://Stackoverflow.com/users/18726537",
"pm_score": 0,
"selected": false,
"text": "#Read the image & get the dimensions \n img_read= cv2.imread(r\"C:\\Users\\Desktop\\test_center_px.tiff\")\n dimensions = img_read.shape\n h, w=dimensions[0], dimensions[1] \n\n#create the bounding box if necessary (not in mine) \n domain = cv2.rectangle(img_read,(0,0),(w,h),(255,0,0),20)\n plt.imshow(domain,cmap='gray')\n \n center_x = w/2\n center_y = h/2\n\n#all we need to do is pass in the (x, y)-coordinates as image[y, x]\n (b, g, r) = img_read[np.int16(center_y), np.int16(center_x)]\n print(\"Color at center pixel is - Red: {}, Green: {}, Blue: {}\".format(r, g, b))\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20438315/"
] |
74,516,128
|
<p>I started using headless chrome for jenkins integration and changed the code in my base file. but now when i run a test I see multiple chromedrivers are started and the driver doesn't close when the last test is finished.</p>
<p>I didn't have this problem before switching to headless mode.</p>
<p>Here is my TestBase class <a href="https://i.stack.imgur.com/JcdiH.png" rel="nofollow noreferrer">TestBase.class</a></p>
<p>And here is the problem. After all these new chromedrivers the test runs successfully, but a lot of chromedriver accumulates in the background.
<a href="https://i.stack.imgur.com/IE2aX.png" rel="nofollow noreferrer">problem</a></p>
<p>I tried to use driver.close and driver.quit functions in the test's @After method but it didn't work like old times too. After using headless mode, I can't close them because as you can see there are multiple chromedrivers in the background.</p>
|
[
{
"answer_id": 74516503,
"author": "Alexey R.",
"author_id": 8343843,
"author_profile": "https://Stackoverflow.com/users/8343843",
"pm_score": 1,
"selected": true,
"text": "DriverService ChromeOptions options = new ChromeOptions() // Your options here\nChromeDriverService service = ChromeDriverService\n .createServiceWithConfig(options);\nservice.start();\n\nWebDriver driver = new ChromeDriver(service);\n\n// Do your test here\n\ndriver.quit(); // close session\nservice.stop(); // stop service\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13807612/"
] |
74,516,151
|
<p>I have git project like this below</p>
<pre><code>% git --log
commit 39b6b1d894d0788fdfc09947e1a5f88bf962b142 (HEAD -> master, origin/master, origin/HEAD)
Author: whitebear man <whitebear@whitebearnoMacBook-Air.local>
Date: Wed Nov 9 15:29:13 2022 +0900
all
commit 2656df9fb80b5085b4e7a50032712b13e3c407c9
Author: whitebear man <whitebear@whitebearnoMacBook-Air.local>
Date: Thu Oct 13 13:48:36 2022 +0900
all
commit d72472d00c649fdc04805d10c856d729e114a014
Author: whitebear man <whitebear@whitebearnoMacBook-Air.local>
Date: Wed Oct 12 18:23:28 2022 +0900
all
commit 0878cd86de3a939e8c99e33676abcfe1cfd14daa
Author: whitebear man <whitebear@whitebearnoMacBook-Air.local>
Date: Tue Oct 11 11:38:58 2022 +0900
all
commit 21c78ba8cfb811e1ad7dfb035ef5236e619f5d53
Author: whitebear man <whitebear@whitebearnoMacBook-Air.local>
Date: Mon Oct 10 15:55:48 2022 +0900
all
commit 9568b4b53fd14febc1ed100efcc6d412d0668471
Author: whitebear man <whitebear@whitebearnoMacBook-Air.local>
Date: Mon Oct 10 15:37:27 2022 +0900
all
</code></pre>
<p>Now I want to roll back commit <code>21c78ba8cfb811e1ad7dfb035ef5236e619f5d53</code> and make new branch.
However I want to keep the latest commit <code>39b6b1d894d0788fdfc09947e1a5f88bf962b142</code> as master.</p>
<p>I should rollback and make new branch?</p>
<p>or make new branch and rollback??</p>
|
[
{
"answer_id": 74516210,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 3,
"selected": true,
"text": "21c78ba8 git branch new_branch 21c78ba8\n"
},
{
"answer_id": 74516366,
"author": "eftshift0",
"author_id": 2437508,
"author_profile": "https://Stackoverflow.com/users/2437508",
"pm_score": 1,
"selected": false,
"text": "git revert 39b6b1d894\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1942868/"
] |
74,516,175
|
<p>Ive been trying to generate a second random number less than my first random number in every scenario, but the code keeps breaking or sometimes returning null</p>
<pre><code>
Random randN = new Random();
int firstNumbereasy; //declaring variables for easy mode
int secondNumbereasy;
firstNumbereasy = randN.nextInt(11); //
secondNumbereasy= randN.nextInt(firstNumbereasy-1);
</code></pre>
|
[
{
"answer_id": 74516266,
"author": "Yonatan Karp-Rudin",
"author_id": 3899765,
"author_profile": "https://Stackoverflow.com/users/3899765",
"pm_score": 3,
"selected": true,
"text": "firstNumbereasy = randN.nextInt(MAX_RANDOM_NUM_NUMBER) + 2;\nsecondNumbereasy= randN.nextInt(firstNumbereasy - 1);\n"
},
{
"answer_id": 74516339,
"author": "Chaosfire",
"author_id": 17795888,
"author_profile": "https://Stackoverflow.com/users/17795888",
"pm_score": 0,
"selected": false,
"text": "bound nextInt() 0 1"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20545889/"
] |
74,516,178
|
<p>I have an array of object as follows <code>Array ( [0] => stdClass Object ( [id] => 14 [content] => সংবাদ [start] => 2022-10-17 00:00:00 ) [1] => stdClass Object ( [id] => 15 [content] => সংবাদ [start] => 2022-10-17 00:00:00 ) [2] => stdClass Object ( [id] => 11 [content] => সংবাদ [start] => 2022-09-28 00:00:00 ) [3] => stdClass Object ( [id] => 12 [content] => সংবাদ [start] => 2022-09-28 00:00:00 ) [4] => stdClass Object ( [id] => 1 [content] => সংবাদ [start] => 2022-09-27 00:00:00 ) )</code></p>
<p>Which i have passed from controller and want to assign in the script in the blade file. the final js should look like this</p>
<pre><code>var items = new vis.DataSet([
{id: 1, content: 'item 1', start: '2014-04-20'},
{id: 2, content: 'item 2', start: '2014-04-14'},
{id: 3, content: 'item 3', start: '2014-04-18'},
]);
</code></pre>
<p>I tried this.</p>
<pre><code>var items = new vis.DataSet({{$timeline}});
</code></pre>
<p>But it is throuhing an error</p>
<pre><code>htmlspecialchars(): Argument #1 ($string) must be of type string, array given
</code></pre>
<p>What i am missing. please help. Thanks</p>
|
[
{
"answer_id": 74516266,
"author": "Yonatan Karp-Rudin",
"author_id": 3899765,
"author_profile": "https://Stackoverflow.com/users/3899765",
"pm_score": 3,
"selected": true,
"text": "firstNumbereasy = randN.nextInt(MAX_RANDOM_NUM_NUMBER) + 2;\nsecondNumbereasy= randN.nextInt(firstNumbereasy - 1);\n"
},
{
"answer_id": 74516339,
"author": "Chaosfire",
"author_id": 17795888,
"author_profile": "https://Stackoverflow.com/users/17795888",
"pm_score": 0,
"selected": false,
"text": "bound nextInt() 0 1"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12747451/"
] |
74,516,186
|
<p>Starting to learn to code and I was doing the fantasy items exercise from automate boring stuff with python. I tried comparing each item of the addedItems array to the dictionary keys to see if they exist, if not I would create a new key with the default value 1. However it says that I have index out of range error, although creating a regular for loop and testing the array it seems to iterate without a problem, what am I missing?</p>
<p>`</p>
<pre><code>def displayInventory(inventory):
print("Inventory: ")
item_total = 0
for k, v in inventory.items():
item_total += v
print(v, k)
print("Total number of items: " + str(item_total))
def addToInventory(inventory, addedItems):
items = []
amount = []
print(addedItems)
for keys, values in inventory.items():
items.append(keys)
amount.append(values)
for i in range(len(addedItems)):
for j in range(len(inventory)):
if addedItems[i] == items[i]:
inventory[items[j]] =+ 1
else:
inventory.setdefault(addedItems[i], 1)
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)
</code></pre>
<p>`
Here is the error message</p>
<pre><code>['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-54-b83d92c005f4> in <module>
26 inv = {'gold coin': 42, 'rope': 1}
27 dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
---> 28 inv = addToInventory(inv, dragonLoot)
29 displayInventory(inv)
<ipython-input-54-b83d92c005f4> in addToInventory(inventory, addedItems)
19 for i in range(len(addedItems)):
20 for j in range(len(inventory)):
---> 21 if addedItems[i] == items[i]:
22 inventory[items[j]] =+ 1
23 else:
IndexError: list index out of range
</code></pre>
<p>I tried testing index i in regular for loops and it iterated through the items without issue, I am not sure why it says out of range.</p>
<p>EDIT: Solved! Thank you very much!!!</p>
|
[
{
"answer_id": 74516504,
"author": "Ghazouani Ahmed",
"author_id": 18937595,
"author_profile": "https://Stackoverflow.com/users/18937595",
"pm_score": 0,
"selected": false,
"text": "for k, v in inventory.items():\n"
},
{
"answer_id": 74516547,
"author": "user20561246",
"author_id": 20561246,
"author_profile": "https://Stackoverflow.com/users/20561246",
"pm_score": 2,
"selected": false,
"text": "def displayInventory(inventory):\n item_total = 0\n for k, v in inventory.items():\n item_total += int(v)\n print(v, k)\n print(\"Total number of items: \" + str(item_total))\n\ndef addToInventory(inventory, addedItems):\n items = []\n amount = []\n print(addedItems)\n for keys, values in inventory.items():\n items.append(keys)\n amount.append(values)\n for i in range(len(inventory)):\n for j in range(len(addedItems)):\n if addedItems[j] == items[i]:\n inventory[items[i]] += 1\n else:\n inventory.setdefault(addedItems[i], 1)\n return inventory\n\ninv = {'gold coin': 42, 'rope': 1}\ndragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']\ninv = addToInventory(inv, dragonLoot)\ndisplayInventory(inv)\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20560882/"
] |
74,516,238
|
<p>Google play store team mentioned that they found <strong>our app is not compliant with how REQUEST_INSTALL_PACKAGES permission is allowed to be used. Specifically, the use of the permission is not directly related to the core purpose of the app.</strong></p>
<p>But no where in our app, we have used REQUEST_INSTALL_PACKAGES permission but still it was rejected multiple times.</p>
<p>We have added below code snippet in android manifest to remove the REQUEST_INSTALL_PACKAGES from our build and sent for play store review. We have verified in the build permissions and could n't find REQUEST_INSTALL_PACKAGES but, still it was rejected by play store.</p>
<p>Please let us know if anyone faced this issue and how can we rectify this error and make our build approved by Play store team.</p>
|
[
{
"answer_id": 74516504,
"author": "Ghazouani Ahmed",
"author_id": 18937595,
"author_profile": "https://Stackoverflow.com/users/18937595",
"pm_score": 0,
"selected": false,
"text": "for k, v in inventory.items():\n"
},
{
"answer_id": 74516547,
"author": "user20561246",
"author_id": 20561246,
"author_profile": "https://Stackoverflow.com/users/20561246",
"pm_score": 2,
"selected": false,
"text": "def displayInventory(inventory):\n item_total = 0\n for k, v in inventory.items():\n item_total += int(v)\n print(v, k)\n print(\"Total number of items: \" + str(item_total))\n\ndef addToInventory(inventory, addedItems):\n items = []\n amount = []\n print(addedItems)\n for keys, values in inventory.items():\n items.append(keys)\n amount.append(values)\n for i in range(len(inventory)):\n for j in range(len(addedItems)):\n if addedItems[j] == items[i]:\n inventory[items[i]] += 1\n else:\n inventory.setdefault(addedItems[i], 1)\n return inventory\n\ninv = {'gold coin': 42, 'rope': 1}\ndragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']\ninv = addToInventory(inv, dragonLoot)\ndisplayInventory(inv)\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11032988/"
] |
74,516,269
|
<p>I am trying to update a column in the mainDB table, based on data in the engine table. The date in the main DB table is stored in (YYYY-MM_DD) format and I want to subtract only the year</p>
<p>I'm not sure how to properly join these two tables to update the percentage
</p>
<pre><code>UPDATE maindb
JOIN engine ON engine.COL_3 = CONCAT(maindb.COL_1,"-", SUBSTRING_INDEX(maindb.COL_2,"-",-1))
SET Maindb.COL_3 = engine.COL_4,
</code></pre>
<p><a href="https://i.stack.imgur.com/HImZh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HImZh.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74516504,
"author": "Ghazouani Ahmed",
"author_id": 18937595,
"author_profile": "https://Stackoverflow.com/users/18937595",
"pm_score": 0,
"selected": false,
"text": "for k, v in inventory.items():\n"
},
{
"answer_id": 74516547,
"author": "user20561246",
"author_id": 20561246,
"author_profile": "https://Stackoverflow.com/users/20561246",
"pm_score": 2,
"selected": false,
"text": "def displayInventory(inventory):\n item_total = 0\n for k, v in inventory.items():\n item_total += int(v)\n print(v, k)\n print(\"Total number of items: \" + str(item_total))\n\ndef addToInventory(inventory, addedItems):\n items = []\n amount = []\n print(addedItems)\n for keys, values in inventory.items():\n items.append(keys)\n amount.append(values)\n for i in range(len(inventory)):\n for j in range(len(addedItems)):\n if addedItems[j] == items[i]:\n inventory[items[i]] += 1\n else:\n inventory.setdefault(addedItems[i], 1)\n return inventory\n\ninv = {'gold coin': 42, 'rope': 1}\ndragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']\ninv = addToInventory(inv, dragonLoot)\ndisplayInventory(inv)\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19422735/"
] |
74,516,292
|
<p><strong>What am I trying to achieve:</strong></p>
<p>I have a collectionView which represents events in a timeline. These cells (events) have description label that is constrained to the left edge.</p>
<p>When scrolling to events to the left on the timeline, some events are too wide and are not showing the description label immediately (i must scroll to the very beginning of the cell on timeline to see it)</p>
<p>The idea was to setup constraints between cells label to collectionView frame so that you could see event description immediately, but these are different view hierarchies.</p>
<p>What would be the best way to approach this?</p>
<p><strong>What i have tried:</strong></p>
<p>Setting up the constraint crashes the app:
<code>Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with anchors <NSLayoutXAxisAnchor:0x600002cbe700 "UILabel:0x11ef0ea20.leading"> and <NSLayoutXAxisAnchor:0x600002cbf240 "UILayoutGuide:0x6000000289a0'UIScrollView-frameLayoutGuide'.leading"> because they have no common ancestor. Does the constraint or its anchors reference items in different view hierarchies? That's illegal.'</code></p>
<p><strong>Additional Info:</strong></p>
<p>UICollectionViewCompositionalLayout:</p>
<pre><code>UICollectionViewCompositionalLayout { sectionIndex, layoutEnvironment in
let item = data.items[sectionIndex]
let contentWidth = data.contentWidth
return context.coordinator.layout(item, contentWidth)
}
</code></pre>
<p>NSCollectionLayoutSection:</p>
<pre><code>var layout: (Item, CGFloat) -> NSCollectionLayoutSection = { item, contentWidth in
let groupSize = NSCollectionLayoutSize(widthDimension: .absolute(contentWidth), heightDimension: .absolute(100))
let itemSizes = item.items.map { NSCollectionLayoutItem(layoutSize: .init(widthDimension: .absolute(CGFloat($0.duration)), heightDimension: .absolute(100)))}
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: itemSizes)
group.interItemSpacing = .fixed(0)
group.contentInsets = .init(top: 0, leading: item.leftGap, bottom: 0, trailing: item.rightGap)
let section = NSCollectionLayoutSection(group: group)
section.interGroupSpacing = 0
let header = NSCollectionLayoutBoundarySupplementaryItem(
layoutSize: .init(widthDimension: .absolute(255), heightDimension: .absolute(100)),
elementKind: UICollectionView.elementKindSectionHeader,
alignment: .leading
)}
}
header.pinToVisibleBounds = true
section.boundarySupplementaryItems = [header]
return section
}
</code></pre>
<p>CollectionViewCell:</p>
<pre><code>class MyCollectionViewCell: UICollectionViewCell {
static let identifier: String = "MyCollectionViewCell"
var item: DataState.Item = .dummy {
didSet {
descriptionLabel.text = item.title
descriptionTimeLabel.text = item.timeDescription
}
}
var containerView: UIView = {
let containerView = UIView()
containerView.translatesAutoresizingMaskIntoConstraints = false
containerView.layer.cornerRadius = 15
containerView.clipsToBounds = true
return containerView
}()
var bg: UIView = {
let bg = UIView()
bg.translatesAutoresizingMaskIntoConstraints = false
bg.backgroundColor = .black
return bg
}()
var descriptionLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = .systemFont(ofSize: 31, weight: .regular)
return label
}()
var descriptionTimeLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = .systemFont(ofSize: 23, weight: .regular)
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(containerView)
containerView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 5).isActive = true
containerView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -5).isActive = true
containerView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -5).isActive = true
containerView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 5).isActive = true
containerView.addSubview(bg)
bg.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true
bg.bottomAnchor.constraint(equalTo: containerView.bottomAnchor).isActive = true
bg.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true
bg.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true
containerView.addSubview(descriptionLabel)
descriptionLabel.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 10).isActive = true
descriptionLabel.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 10).isActive = true
containerView.addSubview(descriptionTimeLabel)
descriptionTimeLabel.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -10).isActive = true
descriptionTimeLabel.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 10).isActive = true
}
}
</code></pre>
<p>Just to remind whole point is to make labels of cell visible immediately as the wide cell being revealed and be continously updated so when the cell is fully visible label's leadingAnchor and containerView leadingAnchor equals 10</p>
|
[
{
"answer_id": 74516504,
"author": "Ghazouani Ahmed",
"author_id": 18937595,
"author_profile": "https://Stackoverflow.com/users/18937595",
"pm_score": 0,
"selected": false,
"text": "for k, v in inventory.items():\n"
},
{
"answer_id": 74516547,
"author": "user20561246",
"author_id": 20561246,
"author_profile": "https://Stackoverflow.com/users/20561246",
"pm_score": 2,
"selected": false,
"text": "def displayInventory(inventory):\n item_total = 0\n for k, v in inventory.items():\n item_total += int(v)\n print(v, k)\n print(\"Total number of items: \" + str(item_total))\n\ndef addToInventory(inventory, addedItems):\n items = []\n amount = []\n print(addedItems)\n for keys, values in inventory.items():\n items.append(keys)\n amount.append(values)\n for i in range(len(inventory)):\n for j in range(len(addedItems)):\n if addedItems[j] == items[i]:\n inventory[items[i]] += 1\n else:\n inventory.setdefault(addedItems[i], 1)\n return inventory\n\ninv = {'gold coin': 42, 'rope': 1}\ndragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']\ninv = addToInventory(inv, dragonLoot)\ndisplayInventory(inv)\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12818143/"
] |
74,516,312
|
<p>I'm having issues connecting Logstash using Oracle wallet. I am getting an invalid login/password even though I am trying to connect through the wallet, without using said login/password.</p>
<pre><code>
[ERROR][logstash.inputs.jdbc ] Unable to connect to database. Tried 2 times {:error_message=>"Java::JavaSql::SQLException: ORA-01017 Invalid Username/Password"}
</code></pre>
<p>Here's my Logstash jdbc input file :</p>
<pre><code>input {
jdbc {
jdbc_driver_library => "${ORACLE_HOME}/dmu/jlib/ojdbc10.jar,${ORACLE_HOME}/ucp/lib/ucp.jar,${ORACLE_HOME}/jlib/oraclepki.jar,${ORACLE_HOME}/jlib/osdt_cert.jar,${ORACLE_HOME}/jlib/osdt_core.jar"
jdbc_driver_class => "Java::oracle.jdbc.driver.OracleDriver"
jdbc_connection_string => "jdbc:oracle:thin:/@name_high?TNS_ADMIN=${ORACLE_HOME}/network/admin/wallet"
jdbc_user => ""
schedule => "* * * * * *"
statement => "SELECT * from table"
connection_retry_attempts => 2
connection_retry_attempts_wait_time => 5
jdbc_pool_timeout => 20
jdbc_validation_timeout => 600
}
}
</code></pre>
<p>So I use the following drivers :</p>
<ul>
<li><p><code>ojdbc10.jar</code></p>
</li>
<li><p><code>ucp.jar</code></p>
</li>
<li><p><code>oraclepki.jar</code></p>
</li>
<li><p><code>osdt_cert.jar</code></p>
</li>
<li><p><code>osdt_core.jar</code></p>
</li>
<li><p>I made sure every environement variable paths are correct, every access rights correctly set.</p>
</li>
<li><p>I believe the connection string syntaxe is correct since it does find the tnsnames.ora and attempt a connexion to the right host, port, sid.</p>
</li>
<li><p>I omitted the field jdbc_password in the jdbc input as it is not required and I don't want jdbc to think I want to use it. I left the jdbc_user field but empty as it is apparently required even though I'm trying not to use it.</p>
</li>
<li><p>I'm able to connect to the database using sqlplus as follow :</p>
</li>
</ul>
<p><code>sqlplus /@name_high</code></p>
<p>So I am at my wit's end (however short that is). If anyone is able to point out what I am missing, I would be immensely grateful !</p>
|
[
{
"answer_id": 74516504,
"author": "Ghazouani Ahmed",
"author_id": 18937595,
"author_profile": "https://Stackoverflow.com/users/18937595",
"pm_score": 0,
"selected": false,
"text": "for k, v in inventory.items():\n"
},
{
"answer_id": 74516547,
"author": "user20561246",
"author_id": 20561246,
"author_profile": "https://Stackoverflow.com/users/20561246",
"pm_score": 2,
"selected": false,
"text": "def displayInventory(inventory):\n item_total = 0\n for k, v in inventory.items():\n item_total += int(v)\n print(v, k)\n print(\"Total number of items: \" + str(item_total))\n\ndef addToInventory(inventory, addedItems):\n items = []\n amount = []\n print(addedItems)\n for keys, values in inventory.items():\n items.append(keys)\n amount.append(values)\n for i in range(len(inventory)):\n for j in range(len(addedItems)):\n if addedItems[j] == items[i]:\n inventory[items[i]] += 1\n else:\n inventory.setdefault(addedItems[i], 1)\n return inventory\n\ninv = {'gold coin': 42, 'rope': 1}\ndragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']\ninv = addToInventory(inv, dragonLoot)\ndisplayInventory(inv)\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6172962/"
] |
74,516,332
|
<p>I have 2 questions concerning re-writting queries, so that no subquery is needed.</p>
<ol>
<li>Is it - using Oracle-SQL-statements - possible to write one of the following queries without using any type of subquery (e.g. subselect)?</li>
<li>If yes, how would this be possible.</li>
</ol>
<p>Query #1 is as follows:</p>
<pre><code>SELECT Stufe, (SELECT AVG(Stufe) FROM Charaktere) FROM Charaktere
WHERE Stufe > (SELECT AVG(Stufe) FROM Charaktere) ORDER BY Stufe DESC
</code></pre>
<p>Query #2 is as follows:</p>
<pre><code>SELECT d.Name, (d.Lebenspunkte-e.Gruppenschaden) as Zustand FROM (
SELECT c.Name, k.Schwächen, (k.Basisleben * c.Leben_Multiplikator) as Lebenspunkte FROM Charaktere c
INNER JOIN Klassen k
ON c.Klasse = k.Klasse) d
INNER JOIN (
SELECT Klasse, SUM(Schaden) as Gruppenschaden FROM Charaktere
GROUP BY Klasse) e
ON d.Schwächen = e.Klasse
WHERE d.Lebenspunkte-e.Gruppenschaden > 0
</code></pre>
<p>Test data:</p>
<p>`</p>
<pre><code>CREATE TABLE Charaktere (
Charakter_ID varchar(300),
Name varchar(300),
Klasse varchar(300),
Rasse varchar(300),
Stufe varchar(300),
Leben_Multiplikator varchar(300),
Mana_Multiplikator varchar(300),
Rüstung varchar(300),
Waffen_ID varchar(300),
Schaden varchar(300)
);
CREATE TABLE Klassen (
Klassen_ID varchar(300),
Klasse varchar(300),
Basisleben varchar(300),
Basismana varchar(300),
Schwächen varchar(300)
);
CREATE TABLE Ausrüstung (
Ausrüstung_ID varchar(300),
Rüstung varchar(300),
Schmuck varchar(300)
);
CREATE TABLE Waffen (
Waffen_ID varchar(300),
Links varchar(300),
Rechts varchar(300)
);
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('1','Herald','Zauberer','Mensch','67','2','8','Heilig','4','718');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('2','Roderic','Paladin','Mensch','55','10','3','Schwer','2','691');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('3','Favian','Schurke','Ork','32','4','1','Leicht','3','243');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('4','Vega','Berserker','Zwerg','44','9','8','Schwer','2','118');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('5','Matep','Jäger','Dunkel Elf','24','3','6','Leicht','1','368');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('6','Euris','Kleriker','Mensch','77','7','8','Resistent','4','774');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('7','Dara’a','Nekromant','Blut Elf','99','6','1','Verdorben','5','966');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('8','Eodriel','Magier','Hoch Elf','24','2','3','Resistent','5','399');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('9','Kerodan','Magier','Blut Elf','20','6','2','Heilig','4','758');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('10','Hans','Paladin','Mensch','67','7','9','Schwer','2','632');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('11','Falk','Berserker','Mensch','13','8','6','Leicht','2','149');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('12','Sethrak','Paladin','Ork','54','5','1','Schwer','3','657');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('13','Hozen','Kleriker','Zwerg','68','6','3','Heilig','4','710');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('14','Venthyr','Jäger','Dunkel Elf','23','4','7','Leicht','1','197');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('15','Stanford','Paladin','Mensch','56','3','7','Resistent','2','370');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('16','Celoevalin','Zauberer','Blut Elf','8','3','6','Heilig','4','383');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('17','Sylvar','Berserker','Hoch Elf','76','9','4','Verdorben','2','837');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('18','Kyrian','Zauberer','Zwerg','69','6','3','Heilig','5','756');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('19','Ithris','Kleriker','Dunkel Elf','88','9','6','Resistent','4','500');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('20','Diedrich','Magier','Mensch','1','2','2','Heilig','2','102');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('21','Dar’mir','Jäger','Blut Elf','14','1','7','Leicht','1','150');
INSERT INTO Klassen (Klassen_ID,Klasse,Basisleben,Basismana,Schwächen) VALUES ('1','Zauberer','70','170','Paladin');
INSERT INTO Klassen (Klassen_ID,Klasse,Basisleben,Basismana,Schwächen) VALUES ('2','Paladin','150','110','Zauberer');
INSERT INTO Klassen (Klassen_ID,Klasse,Basisleben,Basismana,Schwächen) VALUES ('3','Schurke','100','100','Magier');
INSERT INTO Klassen (Klassen_ID,Klasse,Basisleben,Basismana,Schwächen) VALUES ('4','Berserker','200','80','Jäger');
INSERT INTO Klassen (Klassen_ID,Klasse,Basisleben,Basismana,Schwächen) VALUES ('5','Jäger','110','100','Schurke');
INSERT INTO Klassen (Klassen_ID,Klasse,Basisleben,Basismana,Schwächen) VALUES ('6','Kleriker','95','120','Nekromant');
INSERT INTO Klassen (Klassen_ID,Klasse,Basisleben,Basismana,Schwächen) VALUES ('7','Nekromant','50','200','Paladin');
INSERT INTO Klassen (Klassen_ID,Klasse,Basisleben,Basismana,Schwächen) VALUES ('8','Magier','85','150','Berserker');
INSERT INTO Ausrüstung (Ausrüstung_ID,Rüstung,Schmuck) VALUES ('1','Schwer','Kette');
INSERT INTO Ausrüstung (Ausrüstung_ID,Rüstung,Schmuck) VALUES ('2','Leicht','Armreif');
INSERT INTO Ausrüstung (Ausrüstung_ID,Rüstung,Schmuck) VALUES ('3','Resistent','Anhänger');
INSERT INTO Ausrüstung (Ausrüstung_ID,Rüstung,Schmuck) VALUES ('4','Heilig','Ring');
INSERT INTO Ausrüstung (Ausrüstung_ID,Rüstung,Schmuck) VALUES ('5','Verdorben','Talisman');
INSERT INTO Waffen (Waffen_ID,Links,Rechts) VALUES ('1','Bogen','Dolch');
INSERT INTO Waffen (Waffen_ID,Links,Rechts) VALUES ('2','Langschwert',NULL);
INSERT INTO Waffen (Waffen_ID,Links,Rechts) VALUES ('3','Axt','Axt');
INSERT INTO Waffen (Waffen_ID,Links,Rechts) VALUES ('4','Zauberstab','Zauberbuch');
INSERT INTO Waffen (Waffen_ID,Links,Rechts) VALUES ('5','Zauberbuch','Zauberbuch');
</code></pre>
<p>`</p>
<p>I already searched on StackOverflow but cannot re-write these two queries based on the provided information. I guess, the use of JOINS and/or GROUP BY would suffice, ...?</p>
|
[
{
"answer_id": 74516504,
"author": "Ghazouani Ahmed",
"author_id": 18937595,
"author_profile": "https://Stackoverflow.com/users/18937595",
"pm_score": 0,
"selected": false,
"text": "for k, v in inventory.items():\n"
},
{
"answer_id": 74516547,
"author": "user20561246",
"author_id": 20561246,
"author_profile": "https://Stackoverflow.com/users/20561246",
"pm_score": 2,
"selected": false,
"text": "def displayInventory(inventory):\n item_total = 0\n for k, v in inventory.items():\n item_total += int(v)\n print(v, k)\n print(\"Total number of items: \" + str(item_total))\n\ndef addToInventory(inventory, addedItems):\n items = []\n amount = []\n print(addedItems)\n for keys, values in inventory.items():\n items.append(keys)\n amount.append(values)\n for i in range(len(inventory)):\n for j in range(len(addedItems)):\n if addedItems[j] == items[i]:\n inventory[items[i]] += 1\n else:\n inventory.setdefault(addedItems[i], 1)\n return inventory\n\ninv = {'gold coin': 42, 'rope': 1}\ndragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']\ninv = addToInventory(inv, dragonLoot)\ndisplayInventory(inv)\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11558281/"
] |
74,516,375
|
<p>I have this array</p>
<pre><code>[[11,12,13,14],[21,22,23,24],[31,32,33,34],[41],[43],[51]]
</code></pre>
<p>,</p>
<p>expected output like this: <code>11-14,21-24,31-34,41,43,51</code></p>
|
[
{
"answer_id": 74516504,
"author": "Ghazouani Ahmed",
"author_id": 18937595,
"author_profile": "https://Stackoverflow.com/users/18937595",
"pm_score": 0,
"selected": false,
"text": "for k, v in inventory.items():\n"
},
{
"answer_id": 74516547,
"author": "user20561246",
"author_id": 20561246,
"author_profile": "https://Stackoverflow.com/users/20561246",
"pm_score": 2,
"selected": false,
"text": "def displayInventory(inventory):\n item_total = 0\n for k, v in inventory.items():\n item_total += int(v)\n print(v, k)\n print(\"Total number of items: \" + str(item_total))\n\ndef addToInventory(inventory, addedItems):\n items = []\n amount = []\n print(addedItems)\n for keys, values in inventory.items():\n items.append(keys)\n amount.append(values)\n for i in range(len(inventory)):\n for j in range(len(addedItems)):\n if addedItems[j] == items[i]:\n inventory[items[i]] += 1\n else:\n inventory.setdefault(addedItems[i], 1)\n return inventory\n\ninv = {'gold coin': 42, 'rope': 1}\ndragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']\ninv = addToInventory(inv, dragonLoot)\ndisplayInventory(inv)\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10010354/"
] |
74,516,377
|
<p>I have a .js file with several functions that are getting exported. In one case, I need to call one of the exported functions from within the other exported function but It wont let me since it says it can not find the function. What am I doing wrong? I also tried using "this.SMA" but makes no difference.</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>exports.SMA = async function (ohlcv, period) {
const close = ohlcv.map((c) => c[OHLCV_INDEX.CLOSE]);
const result = await tulind.indicators.sma.indicator([close], [period]);
const sma = result[0][result[0].length - 1];
return sma;
};
exports.STRONG_UPTREND = async function (ohlcv, period1, period2, period3) {
const close = ohlcv.map((c) => c[OHLCV_INDEX.CLOSE]);
const sma1 = await SMA(ohlcv, period1); //want to call this
const sma2 = await SMA(ohlcv, period2); //want to call this
const sma3 = await SMA(ohlcv, period3); //want to call this
const last_close = close[close.length - 1];
if (last_close >= sma1 && last_close > sma2 && last_close > sma3) return true;
return false;
};</code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74516421,
"author": "tstrmn",
"author_id": 15605135,
"author_profile": "https://Stackoverflow.com/users/15605135",
"pm_score": 2,
"selected": false,
"text": "const sma = async function (ohlcv, period) {\n const close = ohlcv.map((c) => c[OHLCV_INDEX.CLOSE]);\n const result = await tulind.indicators.sma.indicator([close], [period]);\n const sma = result[0][result[0].length - 1];\n return sma;\n};\n\nexports.SMA = sma;\n sma()"
},
{
"answer_id": 74516461,
"author": "kuuhak-u",
"author_id": 20458458,
"author_profile": "https://Stackoverflow.com/users/20458458",
"pm_score": -1,
"selected": false,
"text": "module.exports.SMA = async function (ohlcv, period) {\n const close = ohlcv.map((c) => c[OHLCV_INDEX.CLOSE]);\n const result = await tulind.indicators.sma.indicator([close], [period]);\n const sma = result[0][result[0].length - 1];\n return sma;\n};\n"
},
{
"answer_id": 74516462,
"author": "Salim",
"author_id": 4478946,
"author_profile": "https://Stackoverflow.com/users/4478946",
"pm_score": 1,
"selected": false,
"text": "exports.SMA SMA exports.STRONG_UPTREND = async function (ohlcv, period1, period2, period3) {\n const close = ohlcv.map((c) => c[OHLCV_INDEX.CLOSE]);\n const sma1 = await exports.SMA(ohlcv, period1); //want to call this\n ...\n const SMA = async function (ohlcv, period) {\n const close = ohlcv.map((c) => c[OHLCV_INDEX.CLOSE]);\n const result = await tulind.indicators.sma.indicator([close], [period]);\n const sma = result[0][result[0].length - 1];\n return sma;\n};\n\nconst STRONG_UPTREND = async function (ohlcv, period1, period2, period3) {\n const close = ohlcv.map((c) => c[OHLCV_INDEX.CLOSE]);\n const sma1 = await SMA(ohlcv, period1); //want to call this\n const sma2 = await SMA(ohlcv, period2); //want to call this\n const sma3 = await SMA(ohlcv, period3); //want to call this\n\n const last_close = close[close.length - 1];\n\n if (last_close >= sma1 && last_close > sma2 && last_close > sma3) return true;\n\n return false;\n};\n\nexports.SMA = SMA;\nexports.STRONG_UPTREND = STRONG_UPTREND;\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11057811/"
] |
74,516,378
|
<p>I have a script generating a dataframe with multiple columns named with numbers 1, 2, 3 –> n</p>
<p>I want to rename the columns with the following names: "Cluster_1", "Cluster_2", "Cluster_3" –> "Cluster_n" (with incrementation).</p>
<p>As the number of columns in my dataframe can change accordingly to another part of my script, I would like to be able to have a kind of loop structure that would go through my dataframe and change columns accordingly.</p>
<p>I would like to do something like:</p>
<pre class="lang-r prettyprint-override"><code>for (i in colnames(df)){
an expression that would change the column name to a concatenation of "Cluster_" + i
}
</code></pre>
<p>Outside the loop context, I generally use this expression to rename a column:</p>
<pre class="lang-r prettyprint-override"><code>names(df)[names(df) == '1'] <- 'Cluster_1'
</code></pre>
<p>But I struggle to produce an adapted version of this expression that would properly integrate in my for loop with a concatenation of string and variable value.</p>
<p>How can I adjust the expression that renames the column of the dataframe to integrate in my <code>for</code> loop?</p>
<p>Or is there a better way than a <code>for</code> loop to do this?</p>
|
[
{
"answer_id": 74516538,
"author": "jay.sf",
"author_id": 6574038,
"author_profile": "https://Stackoverflow.com/users/6574038",
"pm_score": 0,
"selected": false,
"text": "paste0 names(df) <- paste0('cluster_', seq_len(length(df)))\n for for (i in seq_along(names(df))) {\n names(df)[i] <- paste0('cluster_', i)\n}\n\ndf\n# cluster_1 cluster_2 cluster_3 cluster_4\n# 1 1 4 7 10\n# 2 2 5 8 11\n# 3 3 6 9 12\n colnames()/rownames() \"matrix\" \"data.frame\" names()/row.names() df <- data.frame(matrix(1:12, 3, 4))\n"
},
{
"answer_id": 74516933,
"author": "Captain Hat",
"author_id": 4676560,
"author_profile": "https://Stackoverflow.com/users/4676560",
"pm_score": 2,
"selected": true,
"text": "rename_with() require(dplyr)\n\n## '~' notation can be used for formulae in this context:\ndf <- rename_with(df, ~ paste0(\"Cluster_\", .))\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1158344/"
] |
74,516,388
|
<h2>Problem</h2>
<p>I was trying to implement a clean prisma transaction architecture with a DDD architecture.
My problem is that i want to be able to perform <code>transactions</code> cross different modules without need to pass the <code>prisma</code> transaction client to each repository
ie:</p>
<pre class="lang-js prettyprint-override"><code>// repository layer
@injectable()
export class UserRepository{
constructor(@inject(PrismaClient) private prisma: PrismaClient)
save(user: IUser): Promise<User>{
return this.prisma.user.create({data: user});
}
}
@injectable()
export class OrderRepository{
constructor(@inject(PrismaClient) private prisma: PrismaClient)
save(order: IOrder): Promise<Order>{
return this.prisma.order.create({data: order});
}
}
</code></pre>
<pre class="lang-js prettyprint-override"><code>// service layer
export class UserService{
constructor(@inject(UserRepository) private userRepo: UserRepository)
create(request: CreateUserRequest){
return this.userRepo.save(request);
}
}
export class OrderService{
constructor(@inject(OrderRepository) private orderRepo: OrderRepository)
create(request: CreateOrderRequest){
return this.orderRepo.save(request);
}
}
</code></pre>
<pre class="lang-js prettyprint-override"><code>// controller layer
export UserController{
constructor(
@inject(UserService) private userService: UserService,
@inject(OrderService) private orderService: OrderService
){}
placeOrder(
userRequest: CreateUserRequest,
orderRequest: CreateOrderRequest
){
// perform transaction, if any fails go with rollback
// !THIS ACTUALLY DOESN'T WORK
prisma.$transaction([
await this.userService.create(userRequest),
await this.orderService.create(orderRequest)
])
}
}
</code></pre>
<p>I want to figure out a clean way to achieve this, has anyone faced a similar problem before?</p>
<p>Thank you all!</p>
|
[
{
"answer_id": 74516538,
"author": "jay.sf",
"author_id": 6574038,
"author_profile": "https://Stackoverflow.com/users/6574038",
"pm_score": 0,
"selected": false,
"text": "paste0 names(df) <- paste0('cluster_', seq_len(length(df)))\n for for (i in seq_along(names(df))) {\n names(df)[i] <- paste0('cluster_', i)\n}\n\ndf\n# cluster_1 cluster_2 cluster_3 cluster_4\n# 1 1 4 7 10\n# 2 2 5 8 11\n# 3 3 6 9 12\n colnames()/rownames() \"matrix\" \"data.frame\" names()/row.names() df <- data.frame(matrix(1:12, 3, 4))\n"
},
{
"answer_id": 74516933,
"author": "Captain Hat",
"author_id": 4676560,
"author_profile": "https://Stackoverflow.com/users/4676560",
"pm_score": 2,
"selected": true,
"text": "rename_with() require(dplyr)\n\n## '~' notation can be used for formulae in this context:\ndf <- rename_with(df, ~ paste0(\"Cluster_\", .))\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18715249/"
] |
74,516,401
|
<p>I'm brand new to this, 10 days in.
Ive been thinking how I could solve this for 30 min. Please help.</p>
<blockquote>
<h2>Find Average</h2>
<p>You need to calculate the average of a collection of values. Every value will be valid number. The average must be printed with two digits after the decimal point.</p>
<h3>Input-</h3>
<p>On the first line, you will receive N - the number of the values you must read
On the next N lines you will receive numbers.</p>
<h3>Output-</h3>
<p>On the only line of output, print the average with two digits after the decimal point.</p>
<pre><code>Input
4
1
1
1
1
Output
1.00
Input
3
2.5
1.25
3
Output
2.25
</code></pre>
</blockquote>
<p>From what I see, I figure I need to create as much inputs as the N of the first one is and then input the numbers Id like to avarage and then create a formula to avarage them. I may be completely wrong in my logic, in any case Id be happy for some advice.</p>
<p>So far I tried creating a while loop to create inputs from the first input. But have no clue how to properly sintax it and continue with making the new inputs into variables I can use</p>
<pre><code>a=int(input())
x=1
while x<a or x==a:
float(input())
x=x+1
</code></pre>
|
[
{
"answer_id": 74516738,
"author": "Lakshan Costa",
"author_id": 13601941,
"author_profile": "https://Stackoverflow.com/users/13601941",
"pm_score": 1,
"selected": true,
"text": "float int total = 0\n\nfirst_num=int(input(\"Number of inputs: \"))\nnumber = input(\"Enter numbers: \")\ninput_nums = number.split()\n \n\nfor i in range(first_num):\n total = total + int(input_nums[i])\n\n\naverage = total/first_num\nprint(average)\n \nfirst_num=int(input(\"Number of inputs: \"))\nx=1\ntotal = 0\nwhile x<first_num or x==first_num:\n number = float(input(\"Enter numbers: \"))\n total = total + number\n x=x+1\n\navg = total/first_num\nprint(avg)\n"
},
{
"answer_id": 74516878,
"author": "Ben. S.",
"author_id": 12261629,
"author_profile": "https://Stackoverflow.com/users/12261629",
"pm_score": 1,
"selected": false,
"text": "a=int(input('Total number of input: '))\n\ntotal = 0.0\n\nfor i in range(a):\n total += float(input(f'Input #{i+1}: '))\n \nprint('average: ', round(total/a,2))\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,516,433
|
<p>I read <a href="https://en.cppreference.com/w/c/language/main_function" rel="nofollow noreferrer">main function</a>, and came across following words:</p>
<blockquote>
<p>The main function has several special properties:</p>
<ol>
<li>A prototype for this function cannot be supplied by the program.</li>
</ol>
</blockquote>
<p>Then I wrote a simple program:</p>
<pre><code># cat foo.c
int main(void);
int main(void)
{
return 0;
}
</code></pre>
<p>And compiled it:</p>
<pre><code># gcc -Wall -Wextra -Wpedantic -Werror foo.c
#
</code></pre>
<p>All seems OK! So I am little confused about how to understand "A prototype for this function cannot be supplied by the program". Anyone can give some insights?</p>
|
[
{
"answer_id": 74516476,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 1,
"selected": false,
"text": "main main main"
},
{
"answer_id": 74516522,
"author": "Lundin",
"author_id": 584518,
"author_profile": "https://Stackoverflow.com/users/584518",
"pm_score": 3,
"selected": true,
"text": "main main main"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2106207/"
] |
74,516,452
|
<p>I have successfully encrypted the data and store it in the firebase as a string value, how do i retrieve the string and turn it into var type and allow it to be decrypt ?</p>
<pre><code>import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:encrypt/encrypt.dart' as encrypt;
import 'package:hupcarwashcustomer/validation.dart';
import '../../user_model/encrypt_data.dart';
import '../../user_model/payment.dart';
class createPayment extends StatefulWidget {
final String name;
createPayment({required this.name});
@override
State<createPayment> createState() => _createPaymentState();
}
class _createPaymentState extends State<createPayment> {
TextEditingController cardNameController = TextEditingController();
TextEditingController cvvController = TextEditingController();
TextEditingController cardNumController = TextEditingController();
TextEditingController expController = TextEditingController();
void dispose() {
cardNameController.dispose();
cvvController.dispose();
cardNumController.dispose();
expController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(title: Text('Payment Form'),),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: ListView(
children: [
Text(widget.name.toString()),
const SizedBox(
height: 10,
),
TextFormField(
controller: cardNameController,
decoration: const InputDecoration(border: OutlineInputBorder(), hintText: "Card Name"),
),
const SizedBox(
height: 10,
),
TextFormField(
controller: cardNumController,
decoration: const InputDecoration(border: OutlineInputBorder(), hintText: "Card Num"),
),
const SizedBox(
height: 10,
),
TextFormField(
controller: cvvController,
decoration: const InputDecoration(border: OutlineInputBorder(), hintText: "CVV"),
),
const SizedBox(
height: 10,
),
TextFormField(
controller: expController,
decoration: const InputDecoration(border: OutlineInputBorder(), hintText: "Exp Month/Year"),
),
const SizedBox(
height: 10,
),
ElevatedButton(onPressed: () async {
var encryptCardNum, encryptCVV, encryptExp;
encryptCardNum = MyEncryptionDecryption.encryptFernet(cardNumController.text);
encryptCVV = MyEncryptionDecryption.encryptFernet(cvvController.text);
encryptExp = MyEncryptionDecryption.encryptFernet(expController.text);
createPayment(payment(cardName: cardNameController.text,
cardNum: encryptCardNum.base64, name: widget.name.toString(),
cvv: encryptCVV.base64, exp: encryptExp.base64, id:''), widget.name.toString());
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Payment details have been successfully saved')));
Navigator.pop(context);
}
,child: const Text('Proceed')),
],
),
),
)
);
}
Future<void> createPayment(payment pay, String id) async{
String primarykey = '';
final userCollection = FirebaseFirestore.instance.collection("Payment").doc();
primarykey = userCollection.id;
final newPayment = payment(
id: primarykey,
name: pay.name,
cardName: pay.cardName,
cardNum: pay.cardNum,
cvv: pay.cvv,
exp: pay.exp
).toJson();
try {
await userCollection.set(newPayment);
} catch (e) {
print("some error occured $e");
}
}
}
import 'package:encrypt/encrypt.dart' as encrypt;
class MyEncryptionDecryption {
// For Fernet Encryption/Decryption
static final keyFernet = encrypt.Key.fromUtf8('my32lengthsupersecretnooneknows1');
// if you need to use the ttl feature, you'll need to use APIs in the algorithm itself
static final fernet = encrypt.Fernet(keyFernet);
static final encrypterFernet = encrypt.Encrypter(fernet);
static encryptFernet(text) {
final encrypted = encrypterFernet.encrypt(text);
return encrypted;
}
static decryptFernet(text) {
return encrypterFernet.decrypt(text);
}
}
//this part is to retrieve from firebase string and pass to decryption method
final service = userData[index];
final cardNum = service.cardNum;
var finalCardNum = MyEncryptionDecryption.decryptFernet(cardNum);
</code></pre>
<p>I have shared 2 of my files here, i hope someone can guide me, because if i pass the string value into the decrypt method, i will get error like Encrypt does not accept String value, the image i share is the image of firebase data
<a href="https://i.stack.imgur.com/cKuMf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cKuMf.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74516652,
"author": "Risheek Mittal",
"author_id": 16973338,
"author_profile": "https://Stackoverflow.com/users/16973338",
"pm_score": 0,
"selected": false,
"text": "final service = userData[index];\nvar cardNum = service.cardNum as Encrypted;\n MyEncryptionDecryption"
},
{
"answer_id": 74520222,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 2,
"selected": true,
"text": "MyEncryptionDecryption class MyEncryptionDecryption {\n static final keyFernet =\n encrypt.Key.fromUtf8('my32lengthsupersecretnooneknows1');\n\n static final fernet = encrypt.Fernet(keyFernet);\n static final encrypterFernet = encrypt.Encrypter(fernet);\n\n static encrypt.Encrypted encryptFernet(text) {\n final encrypted = encrypterFernet.encrypt(text);\n return encrypted;\n }\n\n static String decryptFernet(encrypt.Encrypted encrypted) {\n return encrypterFernet.decrypt(encrypted);\n }\n}\n encypted = MyEncryptionDecryption.encryptFernet('hi');\n encypted!.base64 var result = MyEncryptionDecryption.decryptFernet(encrypt.Encrypted.fromBase64(encoded!));\n\nprint(\"result = $result\");// hi\n encoded string"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20413390/"
] |
74,516,460
|
<p>I'm using Elastic search to analyze my logs in WSO2 API Manager. I'm using basic authentication mode. After setting up Elastic and Kibana and configuring its setting, these errors appear when I want to see Kibana dashboards. How can I solve these problems?</p>
<p><a href="https://i.stack.imgur.com/20Rjj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/20Rjj.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74516733,
"author": "Amit",
"author_id": 4039431,
"author_profile": "https://Stackoverflow.com/users/4039431",
"pm_score": 1,
"selected": false,
"text": "apim_event_faulty apim_event* _cat/indices?v"
},
{
"answer_id": 74517281,
"author": "chameerar",
"author_id": 15358155,
"author_profile": "https://Stackoverflow.com/users/15358155",
"pm_score": 0,
"selected": false,
"text": "/repository/logs/apim_metrics.log apim_metrics.log apim_metrics.log"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18079412/"
] |
74,516,481
|
<p>I have a df with 6 columns. I want to find the delta based on the date and also group by first few columns.</p>
<pre><code>df <- data.frame (col1 = c('A1','A1','A1','A2','A2','A2','A1','A1','A1','A2','A2','A2','A2','A2','A2'),
col2 = c('B1','B2','B3','B1','B2','B3','B1','B2','B3','B1','B2','B3','B1','B2','B3'),
col3 = c('C1','C2','C3','C1','C2','C3','C1','C2','C3','C1','C2','C3','C1','C2','C3'),
col4 = c('D1','D2','D22','D4','D5','D6','D1','D2','D3','D4','D5','D6','D7','D8','D9'),
col5 = c('1/01/2021','1/01/2021','1/01/2021','1/01/2021','1/01/2021','1/01/2021',
'1/01/2022','1/01/2022','1/01/2022','1/01/2022','1/01/2022','1/01/2022',
'1/01/2022','1/01/2022','1/01/2022'),
col6 = c(10,20,30,40,50,60,100, 200, 300,400,500,600,60,60, 60)
)
diff_na<-df%>%
group_by(col1,col2,col3,col4) %>%
mutate(diff = col6 - lag(col6, default = first(col6,default = 0), order_by = col5))
</code></pre>
<p>Expected output is :</p>
<pre><code>df11 <- data.frame (col1 = c('A1','A1','A1','A2','A2','A2','A1','A1','A1','A2','A2','A2','A2','A2','A2'),
col2 = c('B1','B2','B3','B1','B2','B3','B1','B2','B3','B1','B2','B3','B1','B2','B3'),
col3 = c('C1','C2','C3','C1','C2','C3','C1','C2','C3','C1','C2','C3','C1','C2','C3'),
col4 = c('D1','D2','D22','D4','D5','D6','D1','D2','D3','D4','D5','D6','D7','D8','D9'),
col5 = c('1/01/2021','1/01/2021','1/01/2021','1/01/2021','1/01/2021','1/01/2021',
'1/01/2022','1/01/2022','1/01/2022','1/01/2022','1/01/2022','1/01/2022',
'1/01/2022','1/01/2022','1/01/2022'),
col6 = c(10,20,30,40,50,60,100, 200, 300,400,500,600,60,60, 60),
dfiff =c(0,0,30,0,0,0,90,180,300,360,450,540,60,60,60)
)
</code></pre>
<p>I am facing an issue if the value in the previous col4 is not there , then it does not subtract the value. I mean it should treat the missing value as 0. I tried giving first default as 0. But somehow the last three diff values are 0 instead of 60.
Please guide where I am going wrong.</p>
<p>Row 3 has value in Col4 as D22 which is not there for date 01/01/2022 so 30 should be there. similary row 13,14,15 does not have corresponding value for date 01/01/2021. So diff col should have 60 .</p>
<p>Thanks & Regards,
R</p>
|
[
{
"answer_id": 74516733,
"author": "Amit",
"author_id": 4039431,
"author_profile": "https://Stackoverflow.com/users/4039431",
"pm_score": 1,
"selected": false,
"text": "apim_event_faulty apim_event* _cat/indices?v"
},
{
"answer_id": 74517281,
"author": "chameerar",
"author_id": 15358155,
"author_profile": "https://Stackoverflow.com/users/15358155",
"pm_score": 0,
"selected": false,
"text": "/repository/logs/apim_metrics.log apim_metrics.log apim_metrics.log"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10271423/"
] |
74,516,483
|
<p>I have successfully installed an AWS CLI on WSL. In addition I did follow these instructions:
<a href="https://aws.amazon.com/blogs/compute/introducing-the-c-lambda-runtime/" rel="nofollow noreferrer">https://aws.amazon.com/blogs/compute/introducing-the-c-lambda-runtime/</a></p>
<p>Now, the first example works and when I run a testcase all is functioning properly and the test succeeds. However, when I run the example from the link above with the encoder with a test, the execution fails.</p>
<p>This is the error log:</p>
<pre><code>s2n_init() failed: 402653268 (Failed to load or unload an openssl provider)
Fatal error condition occurred in /home/username/aws-sdk-cpp/crt/aws-crt-cpp/crt/aws-c-io/source/s2n/s2n_tls_channel_handler.c:197: 0 && "s2n_init() failed"
Exiting Application
No call stack information available
START RequestId: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx Version: $LATEST
2022-11-21T09:02:07.642Z xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx Task timed out after 1.02 seconds
END RequestId: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
REPORT RequestId: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx Duration: 1015.50 ms Billed Duration: 1000 ms Memory Size: 128 MB Max Memory Used: 16 MB
</code></pre>
<p>Now, there are two hints in here:</p>
<ol>
<li>failed to load or unload an openssl provider</li>
<li>something with certificates seen the location where the error occured. This location is my local machine which I Find odd since the (binary) code is uploaded to AWS and running there, not on my local machine I'd assume?</li>
</ol>
<p>Have I missed an installation step somewhere or is my configuration incorrect? What can I do to provide more information for myself and / or solve the issue?</p>
|
[
{
"answer_id": 74611780,
"author": "Mart",
"author_id": 3973269,
"author_profile": "https://Stackoverflow.com/users/3973269",
"pm_score": 0,
"selected": false,
"text": "S3::S3Client client(credentialsProvider, config);\n S3::S3Client client(config);\n nano ~/aws-sdk-cpp/crt/aws-crt-cpp/crt/s2n/CMakeLists.txt -l\n if (LIBCRYPTO_SUPPORTS_EVP_RC4)\n #target_compile_options(${PROJECT_NAME} PUBLIC -DS2N_LIBCRYPTO_SUPPORTS_EVP_RC4)\nendif()\n nano ~/aws-sdk-cpp/crt/aws-crt-cpp/crt/s2n/s2n.mk -l\n ifeq ($(TRY_EVP_RC4), 0)\n #DEFAULT_CFLAGS += -DS2N_LIBCRYPTO_SUPPORTS_EVP_RC4\nendif\n $ cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH=~/out\n$ make\n$ make aws-lambda-package-encoder\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3973269/"
] |
74,516,491
|
<p>I have async operation, in which I call a non-void method:</p>
<pre><code>var result = _controller.SendInvoice(this.ParentForm);
</code></pre>
<p>I was getting error <strong>"Cross-thread operation not valid: Control 'ParentForm' accessed from a thread other than the thread it was created on"</strong></p>
<p>I've managed to fix it by writing code like this:</p>
<pre><code>ParentForm.Invoke(new MethodInvoker(delegate { _controller.SendInvoice(ParentForm); }));
</code></pre>
<p>The problem is that I have to get the return result of the method SendInvoice, but the "solution" above does not solving it for me because it doesn't return value from SendInvoice() method.</p>
|
[
{
"answer_id": 74516553,
"author": "BWA",
"author_id": 5481787,
"author_profile": "https://Stackoverflow.com/users/5481787",
"pm_score": 1,
"selected": false,
"text": "Invoice Invoice invoice;\n//Here copy data\n_controller.SendInvoice(invoice); \n"
},
{
"answer_id": 74516685,
"author": "shingo",
"author_id": 6196568,
"author_profile": "https://Stackoverflow.com/users/6196568",
"pm_score": 0,
"selected": false,
"text": "ParentForm Invoke var result = (RETURN-TYPE)_controller.Invoke(\n new Func<RETURN-TYPE>(() => _controller.SendInvoice(ParentForm)));\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7785892/"
] |
74,516,500
|
<p>I have a YAML file with 2 documents</p>
<pre><code># template.yaml
a : 1
---
b : 2
</code></pre>
<p>I'm trying to edit the YAML file inplace. I've tried using</p>
<pre><code># yq4
yq -i '
select(documentIndex == 0) |
.a = 3 |
select(documentIndex == 1) |
.b = 4
' template.yaml
</code></pre>
<p>But figured out that this outputs an empty file. I figured that the output of <code>select(documentIndex == 0) | .a = 3</code> is a single document, which when piped to <code>select(documentIndex == 1)</code>, results in an empty document.</p>
<p>In yq3, I can do this by writing</p>
<pre><code>#yq3
yq w -d1 .a 3 | yq w -d2 .b 4` > template.yaml
</code></pre>
<p>Is there an equivalent to this yq4 command in yq3?</p>
|
[
{
"answer_id": 74517033,
"author": "Inian",
"author_id": 5291015,
"author_profile": "https://Stackoverflow.com/users/5291015",
"pm_score": 2,
"selected": true,
"text": "yq 'select(di == 0).a = 3 | select(di == 1).b = 5' yaml\n"
},
{
"answer_id": 74517247,
"author": "Anugerah Erlaut",
"author_id": 1940886,
"author_profile": "https://Stackoverflow.com/users/1940886",
"pm_score": 0,
"selected": false,
"text": "yq 'select(documentIndex == 0) | .a = 3' > doc_0.yaml\nyq 'select(documentIndex == 1) | .b = 4' > doc_0.yaml\n\nyq eval-all '. as $item' doc_0.yaml doc_1.yaml > $output.yaml\n\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1940886/"
] |
74,516,502
|
<p>So let's say, i want to do something thing like this</p>
<pre><code>a = ['AB', 'CD']
s = '1. \n'
print(s.join(a))
</code></pre>
<p>Expected Output:</p>
<pre><code>1. AB
2. CD
</code></pre>
<p>Actual Output:</p>
<pre><code>AB1.
CD1.
</code></pre>
<p>So my question is,
How can i add something at the beginning of the string <code>s</code>?
And also increase the number.</p>
<p>example:</p>
<pre><code>1. ...
2. ...
</code></pre>
|
[
{
"answer_id": 74517033,
"author": "Inian",
"author_id": 5291015,
"author_profile": "https://Stackoverflow.com/users/5291015",
"pm_score": 2,
"selected": true,
"text": "yq 'select(di == 0).a = 3 | select(di == 1).b = 5' yaml\n"
},
{
"answer_id": 74517247,
"author": "Anugerah Erlaut",
"author_id": 1940886,
"author_profile": "https://Stackoverflow.com/users/1940886",
"pm_score": 0,
"selected": false,
"text": "yq 'select(documentIndex == 0) | .a = 3' > doc_0.yaml\nyq 'select(documentIndex == 1) | .b = 4' > doc_0.yaml\n\nyq eval-all '. as $item' doc_0.yaml doc_1.yaml > $output.yaml\n\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20337001/"
] |
74,516,525
|
<p>I want to create a Switch like below :
<a href="https://i.stack.imgur.com/fVGXz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fVGXz.png" alt="enter image description here" /></a></p>
<p>I tried using <code>Transform.scale</code> as parent Widget but it doesn't match with that i want.
How should I increase Switch width? or any other suggestion for create similar(like Toggle or ...)?</p>
|
[
{
"answer_id": 74517033,
"author": "Inian",
"author_id": 5291015,
"author_profile": "https://Stackoverflow.com/users/5291015",
"pm_score": 2,
"selected": true,
"text": "yq 'select(di == 0).a = 3 | select(di == 1).b = 5' yaml\n"
},
{
"answer_id": 74517247,
"author": "Anugerah Erlaut",
"author_id": 1940886,
"author_profile": "https://Stackoverflow.com/users/1940886",
"pm_score": 0,
"selected": false,
"text": "yq 'select(documentIndex == 0) | .a = 3' > doc_0.yaml\nyq 'select(documentIndex == 1) | .b = 4' > doc_0.yaml\n\nyq eval-all '. as $item' doc_0.yaml doc_1.yaml > $output.yaml\n\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16728483/"
] |
74,516,534
|
<p>I'm trying to run a react project cloned from <strong>Github</strong> that works with <code>NodeJs</code>. In the <code>.readme</code> file, the dev tells that i just need to run <code>npm start</code> in backend folder, then on frontend folder.</p>
<p>The problem is that I'm receiving errors:</p>
<p>In backend folder:</p>
<pre><code>$ npm start
> backend@1.0.0 start
> nodemon server.js
[nodemon] 2.0.20
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
node:internal/modules/cjs/loader:959
throw err;
^
Error: Cannot find module 'nodemailer'
Require stack:
- C:\Users\alexia.borelvaéhotma\Desktop\stage\Site-centre-formation\backend\utils\emailSend.js
- C:\Users\alexia.borelvaéhotma\Desktop\stage\Site-centre-formation\backend\controllers\user.controllers.js
- C:\Users\alexia.borelvaéhotma\Desktop\stage\Site-centre-formation\backend\routes\userapi.js
- C:\Users\alexia.borelvaéhotma\Desktop\stage\Site-centre-formation\backend\server.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:956:15)
at Function.Module._load (node:internal/modules/cjs/loader:804:27)
at Module.require (node:internal/modules/cjs/loader:1028:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (C:\Users\alexia.borelvaéhotma\Desktop\stage\Site-centre-formation\backend\utils\emailSend.js:1:20)
at Function.Module._load (node:internal/modules/cjs/loader:839:12)
at Module.require (node:internal/modules/cjs/loader:1028:19) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\\Users\\alexia.borelvaéhotma\\Desktop\\stage\\Site-centre-formation\\backend\\utils\\emailSend.js',
'C:\\Users\\alexia.borelvaéhotma\\Desktop\\stage\\Site-centre-formation\\backend\\controllers\\user.controllers.js', ailSend.js',
'C:\\Users\\alexia.borelvaéhotma\\Desktop\\stage\\Site-centre-formation\\backend\\routes\\urs\\user.controllers.jsserapi.js',
'C:\\Users\\alexia.borelvaéhotma\\Desktop\\stage\\Site-centre-formation\\backend\\server.jsserapi.js',' '
]
}
[nodemon] app crashed - waiting for file changes before starting...
</code></pre>
<p>In frontend folder:</p>
<pre><code>$ npm start
> frontend@0.1.0 start
> react-scripts start
'react-scripts' n’est pas reconnu en tant que commande interne
ou externe, un programme exécutable ou un fichier de commandes.
</code></pre>
<p>Any idea? thanks for your answer.</p>
<p>I've tried <code>npm install</code> in the front folder, but it doesn't work:</p>
<pre><code>$ cd formation-frontend/
alexia.borelvaéhotma@AlexiaMac8 MINGW64 ~/Desktop/stage/Site-centre-formation/formation-frontend (main)
$ npm install
npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: react-typical@0.1.3
npm ERR! Found: react@17.0.2
npm ERR! node_modules/react
npm ERR! react@"^17.0.2" from the root project
npm ERR! peer react@"^16.8.0 || ^17.0.0-rc.1" from @react-aria/ssr@3.1.0
npm ERR! node_modules/@react-aria/ssr
npm ERR! @react-aria/ssr@"^3.0.1" from @restart/ui@0.2.6
npm ERR! node_modules/@restart/ui
npm ERR! @restart/ui@"^0.2.5" from react-bootstrap@2.1.1
npm ERR! node_modules/react-bootstrap
npm ERR! react-bootstrap@"^2.0.3" from the root project
npm ERR! 21 more (@restart/hooks, @restart/ui, @testing-library/react, ...)
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^15.0.0 || ^16.0.0" from react-typical@0.1.3
npm ERR! node_modules/react-typical
npm ERR! react-typical@"^0.1.3" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: react@16.14.0
npm ERR! node_modules/react
npm ERR! peer react@"^15.0.0 || ^16.0.0" from react-typical@0.1.3
npm ERR! node_modules/react-typical
npm ERR! react-typical@"^0.1.3" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR!
npm ERR! For a full report see:
npm ERR! C:\Users\alexia.borelvaéhotma\AppData\Local\npm-cache\_logs\2022-11-21T09_06_44_713Z-eresolve-report.txt
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\alexia.borelvaéhotma\AppData\Local\npm-cache\_logs\2022-11-21T09_06_44_713Z-debug-0.log
</code></pre>
|
[
{
"answer_id": 74517033,
"author": "Inian",
"author_id": 5291015,
"author_profile": "https://Stackoverflow.com/users/5291015",
"pm_score": 2,
"selected": true,
"text": "yq 'select(di == 0).a = 3 | select(di == 1).b = 5' yaml\n"
},
{
"answer_id": 74517247,
"author": "Anugerah Erlaut",
"author_id": 1940886,
"author_profile": "https://Stackoverflow.com/users/1940886",
"pm_score": 0,
"selected": false,
"text": "yq 'select(documentIndex == 0) | .a = 3' > doc_0.yaml\nyq 'select(documentIndex == 1) | .b = 4' > doc_0.yaml\n\nyq eval-all '. as $item' doc_0.yaml doc_1.yaml > $output.yaml\n\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7943153/"
] |
74,516,536
|
<p>I know this is a stupid question, but I'm asking as a newbie to flutter.</p>
<p>I created a getData() method to call Firebase's User data and display it on the app. And to call it, result.data() is saved as a variable name of resultData.</p>
<p>But as you know I can't use Text('user name: $resultData'). How do I solve this? It's a difficult problem for me, since I don't have any programming basics. thank you.</p>
<pre><code>import 'dart:math';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:shipda/screens/login/login_screen.dart';
import 'package:get/get.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
final _authentication = FirebaseAuth.instance;
User? loggedUser;
final firestore = FirebaseFirestore.instance;
void getData() async {
var result = await firestore.collection('user').doc('vUj4U27JoAU6zgFDk6sSZiwadQ13').get();
final resultData = result.data();
}
@override
void initState() {
super.initState();
getCurrentUser();
getData();
}
void getCurrentUser(){
try {
final user = _authentication.currentUser;
if (user != null) {
loggedUser = user;
print(loggedUser!.email);
}
} catch (e){
print(e);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Column(
children: [
Text('Home Screen'),
IconButton(
onPressed: () {
FirebaseAuth.instance.signOut();
Get.to(()=>LoginScreen());
},
icon: Icon(Icons.exit_to_app),
),
IconButton(
onPressed: () {
Get.to(() => LoginScreen());
},
icon: Icon(Icons.login),
),
Text('UserInfo'),
Text('user name: ')
],
),
),
);
}
}
</code></pre>
|
[
{
"answer_id": 74517033,
"author": "Inian",
"author_id": 5291015,
"author_profile": "https://Stackoverflow.com/users/5291015",
"pm_score": 2,
"selected": true,
"text": "yq 'select(di == 0).a = 3 | select(di == 1).b = 5' yaml\n"
},
{
"answer_id": 74517247,
"author": "Anugerah Erlaut",
"author_id": 1940886,
"author_profile": "https://Stackoverflow.com/users/1940886",
"pm_score": 0,
"selected": false,
"text": "yq 'select(documentIndex == 0) | .a = 3' > doc_0.yaml\nyq 'select(documentIndex == 1) | .b = 4' > doc_0.yaml\n\nyq eval-all '. as $item' doc_0.yaml doc_1.yaml > $output.yaml\n\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19443112/"
] |
74,516,540
|
<p>I am trying to write some synchronization code for a java app that runs on each of the cassandra servers in our cluster (so each server has 1 cassandra instance + our app). For this I wanted to make a method that will return the 'local' cassandra node, using the java driver.</p>
<p>Every process creates a cqlSession using the local address as contactPoint. The driver will figure out the rest of the cluster from that. But my assumption was that the local address would be its 'primary' node, at least for requesting things from the system.local table. This seems not so, when trying to run the code.</p>
<p>Is there a way in the Java driver to determine which of the x nodes the process its running on?</p>
<p>I tried this code:</p>
<pre><code>public static Node getLocalNode(CqlSession cqlSession) {
Metadata metadata = cqlSession.getMetadata();
Map<UUID, Node> allNodes = metadata.getNodes();
Row row = cqlSession.execute("SELECT host_id FROM system.local").one();
UUID localUUID = row.getUuid("host_id");
Node localNode = null;
for (Node node : allNodes.values()) {
if (node.getHostId().equals(localUUID)) {
localNode = node;
break;
}
}
return localNode;
}
</code></pre>
<p>But it seems to return random nodes - which makes sense if it just sends the query to one of the nodes in the cluster. I was hoping to find a way without providing hardcoded configuration to determine what node the app is running on.</p>
|
[
{
"answer_id": 74524169,
"author": "Aaron",
"author_id": 1054558,
"author_profile": "https://Stackoverflow.com/users/1054558",
"pm_score": 2,
"selected": false,
"text": "ResultSet rs = session.execute(\"select host_id from system.local\");\nRow row = rs.one();\nSystem.out.println(row.getUuid(\"host_id\"));\nSystem.out.println();\nSystem.out.println(rs.getExecutionInfo().getCoordinator());\n 9788de64-08ee-4ab6-86a6-fdf387a9e4a2\n\nNode(endPoint=/127.0.0.1:9042, hostId=9788de64-08ee-4ab6-86a6-fdf387a9e4a2, hashCode=2625653a)\n"
},
{
"answer_id": 74526610,
"author": "Erick Ramirez",
"author_id": 4269535,
"author_profile": "https://Stackoverflow.com/users/4269535",
"pm_score": 1,
"selected": false,
"text": "DefaultLoadBalancingPolicy"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/405834/"
] |
74,516,541
|
<p>I'm trying to create an app that uses drf-api-key for authorization. And I want to monitor which api key used in every connection used to database, Is there a way to that?</p>
<p>I tried to get the value of headers.get("Authorization") I get a none value, I just want to retrieve the name of api key used or the prefix of it.</p>
|
[
{
"answer_id": 74524169,
"author": "Aaron",
"author_id": 1054558,
"author_profile": "https://Stackoverflow.com/users/1054558",
"pm_score": 2,
"selected": false,
"text": "ResultSet rs = session.execute(\"select host_id from system.local\");\nRow row = rs.one();\nSystem.out.println(row.getUuid(\"host_id\"));\nSystem.out.println();\nSystem.out.println(rs.getExecutionInfo().getCoordinator());\n 9788de64-08ee-4ab6-86a6-fdf387a9e4a2\n\nNode(endPoint=/127.0.0.1:9042, hostId=9788de64-08ee-4ab6-86a6-fdf387a9e4a2, hashCode=2625653a)\n"
},
{
"answer_id": 74526610,
"author": "Erick Ramirez",
"author_id": 4269535,
"author_profile": "https://Stackoverflow.com/users/4269535",
"pm_score": 1,
"selected": false,
"text": "DefaultLoadBalancingPolicy"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20464787/"
] |
74,516,586
|
<p>I have a string query</p>
<pre><code>const query = '(travel OR explore OR vacation OR trip) NOT (app OR agency) AND flight';
</code></pre>
<p>I want to store the words inside "NOT" block in an array.
What could be the most effective approach for this?</p>
<p>Expected result - ["app", "agency"]</p>
|
[
{
"answer_id": 74516679,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 2,
"selected": false,
"text": "match() const query = '(travel OR explore OR vacation OR trip) NOT (app OR agency) AND flight';\nvar terms = query.match(/\\bNOT\\s*\\((.*?)\\)/)[1]\n .match(/\\w+/g)\n .filter(x => x !== \"OR\" && x !== \"AND\");\nconsole.log(terms);"
},
{
"answer_id": 74516730,
"author": "Emre",
"author_id": 6468955,
"author_profile": "https://Stackoverflow.com/users/6468955",
"pm_score": 2,
"selected": true,
"text": "const query = '(travel OR explore OR vacation OR trip) NOT (app OR agency) AND flight';\nfunction useRegex(input) {\n let regex = /\\(([a-zA-Z]+( [a-zA-Z]+)+)\\) NOT \\(([a-zA-Z]+( [a-zA-Z]+)+)\\) ([A-Za-z0-9]+( [A-Za-z0-9]+)+)/i;\n return input.match(regex);\n}\nconsole.log(useRegex(query)[3]);"
},
{
"answer_id": 74516802,
"author": "Maniraj Murugan",
"author_id": 7785337,
"author_profile": "https://Stackoverflow.com/users/7785337",
"pm_score": 1,
"selected": false,
"text": "NOT query.split('NOT') NOT query.split('NOT')[1] rx.exec(res)[1] OR const query = '(travel OR explore OR vacation OR trip) NOT (app OR agency) AND flight';\n\nconst res = query.split('NOT')[1]; \nconst rx = /\\(([^)]+)\\)/;\nconst result = rx.exec(res)[1].split(' OR ');\n\n\nconsole.log(result);"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14472667/"
] |
74,516,587
|
<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 arrayNames = ["Angela", "Ben", "Jenny", "Michael", "Chloe"];
function whosPaying(names) {
var bigBoss = arrayNames.length;
var ogaMi = Math.floor((Math.random() * bigBoss));
return ogaMi + " is paying for the bill"
}
console.log(whosPaying());</code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74516679,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 2,
"selected": false,
"text": "match() const query = '(travel OR explore OR vacation OR trip) NOT (app OR agency) AND flight';\nvar terms = query.match(/\\bNOT\\s*\\((.*?)\\)/)[1]\n .match(/\\w+/g)\n .filter(x => x !== \"OR\" && x !== \"AND\");\nconsole.log(terms);"
},
{
"answer_id": 74516730,
"author": "Emre",
"author_id": 6468955,
"author_profile": "https://Stackoverflow.com/users/6468955",
"pm_score": 2,
"selected": true,
"text": "const query = '(travel OR explore OR vacation OR trip) NOT (app OR agency) AND flight';\nfunction useRegex(input) {\n let regex = /\\(([a-zA-Z]+( [a-zA-Z]+)+)\\) NOT \\(([a-zA-Z]+( [a-zA-Z]+)+)\\) ([A-Za-z0-9]+( [A-Za-z0-9]+)+)/i;\n return input.match(regex);\n}\nconsole.log(useRegex(query)[3]);"
},
{
"answer_id": 74516802,
"author": "Maniraj Murugan",
"author_id": 7785337,
"author_profile": "https://Stackoverflow.com/users/7785337",
"pm_score": 1,
"selected": false,
"text": "NOT query.split('NOT') NOT query.split('NOT')[1] rx.exec(res)[1] OR const query = '(travel OR explore OR vacation OR trip) NOT (app OR agency) AND flight';\n\nconst res = query.split('NOT')[1]; \nconst rx = /\\(([^)]+)\\)/;\nconst result = rx.exec(res)[1].split(' OR ');\n\n\nconsole.log(result);"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19779482/"
] |
74,516,608
|
<p>I am writing a program aiming to flip the card while it is clicked. The javascript code looks like this:</p>
<pre><code>/* card flipping onclick */
import "./Stylesheets/FlipCardStyle.css"
var cards = document.querySelectorAll('.card');
[...cards].forEach((card)=>{
card.addEventListener( 'click', function() {
card.classList.toggle('flipped');
});
});
</code></pre>
<p>And the CSS code works like this:</p>
<pre><code>@import "GridLayouts.css";
.card {
background: transparent;
width: 117px;
height: 200px;
perspective: 1000px; /* Remove this if you don't want the 3D effect */
position: relative;
cursor: pointer;
text-align: center;
transition: transform 0.8s;
transform-style: preserve-3d;
}
.wrapper-horizontal .card {
float: left;
margin-right: -47px;
margin-bottom: 20px;
}
/* Do an horizontal flip when you move the mouse over the flip box container */
.card:hover {
transform: rotateY(180deg) translate(0, 40px);
}
/* Position the front and back side */
.card-face {
position: absolute;
width: 100%;
height: 100%;
-webkit-backface-visibility: hidden; /* Safari */
backface-visibility: hidden;
}
/* Style the front side (fallback if image is missing) */
.card-face-front {
background: url("...") -234px 0px;
}
/* Style the back side */
.card-face-back {
background: url("...");
background-size: 100% 100%;
transform: rotateY(180deg);
}
</code></pre>
<p>The HTML looks like this:</p>
<pre><code><!DOCTYPE html>
<link rel="stylesheet" href="Stylesheets/FlipCardStyle.css">
<link rel="stylesheet" href="Stylesheets/GridLayouts.css">
<link rel="stylesheet" href="Stylesheets/Buttons.css">
<html>
<div class="wrapper-horizontal">
<div class="card">
<div class="card-face card-face-front"></div>
<div class="card-face card-face-back"></div>
</div>
<div class="card">
<div class="card-face card-face-front"></div>
<div class="card-face card-face-back"></div>
</div>
<div class="card">
<div class="card-face card-face-front"></div>
<div class="card-face card-face-back"></div>
</div>
<div class="card">
<div class="card-face card-face-front"></div>
<div class="card-face card-face-back"></div>
</div>
<script src="./FlipCard.js"></script>
</div>
<button class="btn">Shuffle</button>
</html>
</code></pre>
<p><strong>Theoretically</strong>, when I clicked the card, js script will invoke the .card.flipped, which would rotate the card over. But it doesn't work... My logic of the code comes from <a href="https://codepen.io/mondal10/pen/WNNEvjV" rel="nofollow noreferrer">https://codepen.io/mondal10/pen/WNNEvjV</a>, it workds on codepen but it doesn't seem to work for me.</p>
<p>Could anyone help me? Thanks a lot!!!</p>
|
[
{
"answer_id": 74516976,
"author": "FUZIION",
"author_id": 13050564,
"author_profile": "https://Stackoverflow.com/users/13050564",
"pm_score": 1,
"selected": true,
"text": ".card:hover .flipped flipped var cards = document.querySelectorAll('.card');\n\n[...cards].forEach((card) => {\n card.addEventListener('click', function() {\n card.classList.toggle('flipped');\n });\n}); .card {\n background: transparent;\n width: 117px;\n height: 200px;\n perspective: 1000px;\n position: relative;\n cursor: pointer;\n text-align: center;\n transition: transform 0.8s;\n transform-style: preserve-3d;\n}\n\n.wrapper-horizontal .card {\n float: left;\n margin: 10px;\n margin-bottom: 20px;\n}\n\n\n/* changed .card:hover to .flipped because there was no class to be toggled. */\n\n.flipped {\n transform: rotateY(180deg) translate(0, 40px);\n}\n\n.card-face {\n position: absolute;\n width: 100%;\n height: 100%;\n -webkit-backface-visibility: hidden;\n /* Safari */\n backface-visibility: hidden;\n}\n\n.card-face-front {\n background: red;\n}\n\n.card-face-back {\n background: blue;\n transform: rotateY(180deg);\n} <div class=\"wrapper-horizontal\">\n <div class=\"card\">\n <div class=\"card-face card-face-front\"></div>\n <div class=\"card-face card-face-back\"></div>\n </div>\n <div class=\"card\">\n <div class=\"card-face card-face-front\"></div>\n <div class=\"card-face card-face-back\"></div>\n </div>\n <div class=\"card\">\n <div class=\"card-face card-face-front\"></div>\n <div class=\"card-face card-face-back\"></div>\n </div>\n\n <div class=\"card\">\n <div class=\"card-face card-face-front\"></div>\n <div class=\"card-face card-face-back\"></div>\n </div>\n <script src=\"./FlipCard.js\"></script>\n</div>\n<button class=\"btn\">Shuffle</button>"
},
{
"answer_id": 74517516,
"author": "Momin",
"author_id": 4672474,
"author_profile": "https://Stackoverflow.com/users/4672474",
"pm_score": -1,
"selected": false,
"text": "var cards = document.querySelectorAll('.card');\n\n[...cards].forEach((card) => {\n card.addEventListener('click', function() {\n card.classList.toggle('is-flipped');\n });\n}); body {\n font-family: sans-serif;\n}\n\n.scene {\n display: inline-block;\n width: 200px;\n height: 260px;\n /* border: 1px solid #CCC; */\n margin: 40px 0;\n perspective: 600px;\n}\n\n.card {\n position: relative;\n width: 100%;\n height: 100%;\n cursor: pointer;\n transform-style: preserve-3d;\n transform-origin: center right;\n transition: transform 1s;\n}\n\n.card.is-flipped {\n transform: translateX(-100%) rotateY(-180deg);\n}\n\n.card__face {\n position: absolute;\n width: 100%;\n height: 100%;\n line-height: 260px;\n color: white;\n text-align: center;\n font-weight: bold;\n font-size: 40px;\n backface-visibility: hidden;\n}\n\n.card__face--front {\n background: crimson;\n}\n\n.card__face--back {\n background: slateblue;\n transform: rotateY(180deg);\n} <!doctype html>\n<html class=\"no-js\" lang=\"\">\n\n<head>\n <meta charset=\"utf-8\">\n <title></title>\n <meta name=\"description\" content=\"\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\n <meta property=\"og:title\" content=\"\">\n <meta property=\"og:type\" content=\"\">\n <meta property=\"og:url\" content=\"\">\n <meta property=\"og:image\" content=\"\">\n\n <link rel=\"manifest\" href=\"site.webmanifest\">\n <link rel=\"apple-touch-icon\" href=\"icon.png\">\n <!-- Place favicon.ico in the root directory -->\n\n <link rel=\"stylesheet\" href=\"css/normalize.css\">\n <link rel=\"stylesheet\" href=\"css/main.css\">\n\n <meta name=\"theme-color\" content=\"#fafafa\">\n</head>\n\n<body>\n\n <!-- Add your site or application content here -->\n <div class=\"scene scene--card\">\n <div class=\"card\">\n <div class=\"card__face card__face--front\">front</div>\n <div class=\"card__face card__face--back\">back</div>\n </div>\n </div>\n <div class=\"scene scene--card\">\n <div class=\"card\">\n <div class=\"card__face card__face--front\">front</div>\n <div class=\"card__face card__face--back\">back</div>\n </div>\n </div>\n <p>Click card to flip.</p>\n\n <script src=\"js/main.js\"></script>\n\n\n</body>\n\n</html>"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20396550/"
] |
74,516,631
|
<p>Good day,
I run into the problem then returning DTO object.
I have these classes</p>
<pre><code>public class ProductBase
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public IEnumerable<ProductVariant> Variants { get; set; }
public int BaseImageId { get; set; } = 0;
}
public class ProductVariant
{
public int Id { get; set; }
public int Quantity { get; set; }
public int ProductBaseId { get; set; }
public ProductBase productBase { get; set; }
public int ProductSizeId { get; set; }
public ProductSize ProductSize { get; set; }
public int ProductColorId { get; set; }
public ProductColor ProductColor { get; set; }
public IEnumerable<ImageVariant> imageVariants { get; set; }
}
public class ProductColor
{
public int Id { get; set; }
public string Color { get; set; }
public IEnumerable<ProductVariant> productVariant { get; set; }
}
public class ProductSize
{
public int Id { get; set; }
public string Size { get; set; }
public IEnumerable<ProductVariant> productVariant { get; set; }
}
</code></pre>
<p>In productBaseRepository I have this call</p>
<pre><code>public async Task<IEnumerable<Models.ProductBase>> GetAllWithVariantsAsync()
{
var result = await _dataContext.ProductBases
.Include(pb => pb.Variants)
.ThenInclude(v => v.ProductSize)
.Include(pb => pb.Variants)
.ThenInclude(v => v.ProductColor)
.ToListAsync();
return result;
}
</code></pre>
<p>I have created DTO convertion function</p>
<pre><code>public static IEnumerable<ProductBaseDTO> ConvertToDto(this IEnumerable<ProductBase> productBases)
{
var returnProductBaseDto = (from product in productBases
select new ProductBaseDTO
{
Id = product.Id,
Name = product.Name,
Variants = product.Variants.ToList(),
Description = product.Description,
BaseImageId = product.BaseImageId,
}).ToList();
return returnProductBaseDto;
}
</code></pre>
<p>But then I call this function from swagger</p>
<pre><code> [HttpGet]
public async Task<ActionResult<List<ProductBaseDTO>>> GetAllProductsWithVariants()
{
var baseProductDomain = await _productBaseRepository.GetAllWithVariantsAsync();
var baseProduct = baseProductDomain.ConvertToDto();
return Ok(baseProduct);
}
</code></pre>
<p>I get that
System.Text.Json.JsonException: A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32</p>
<p>If I remove variants from call it works, so I need to some how remove Unecessry values from Variants</p>
|
[
{
"answer_id": 74516758,
"author": "sommmen",
"author_id": 4122889,
"author_profile": "https://Stackoverflow.com/users/4122889",
"pm_score": 0,
"selected": false,
"text": "Variants foreach(var x in baseProduct.SelectMany(c => c.Variants) { x.ProductBase = null } public class Order {\n public List<OrderLine> OrderLines {get;set}\n}\n\npublic class OrderLine {\n public Order Order {get;set}\n}\n\n// Gets mapped to the following viewmodels:\n\npublic class OrderViewModel {\n public List<OrderOrderLineViewModel > OrderLines {get;set}\n}\n\npublic class OrderOrderLineViewModel {\n public Order Order => null; // Stop object cycling\n}\n\n $.Variants.productBase.variants.productBase.variants"
},
{
"answer_id": 74516761,
"author": "NineBerry",
"author_id": 101087,
"author_profile": "https://Stackoverflow.com/users/101087",
"pm_score": 1,
"selected": false,
"text": "ProductVariant ProductSize ProductColor ProductSize ProductColor ProductVariant ProductVariant BaseProduct productVariant ProductSize ProductColor ProductSize ProductColor ProductVariant productBase ProductVariant"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17250130/"
] |
74,516,633
|
<p>When I try to create a new variable in dataframe Call08q1_09q1 by adding two float variable</p>
<pre><code>Call08q1_09q1['MBS']=Call08q1_09q1['RCFD8639']+Call08q1_09q1['RCFD2170']
</code></pre>
<p>the error below shows up:</p>
<p>'<' not supported between instances of 'str' and 'int' in Python</p>
<p>However, I don't have string in my dataframe.</p>
<pre><code>Call08q1_09q1.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 39675 entries, 0 to 39674
Data columns (total 20 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 RSSD9001 39675 non-null float64
1 RSSD9999 39675 non-null float64
2 RCFD2170 39673 non-null float64
3 RCFD8639 38166 non-null float64
4 RCFD8641 38166 non-null float64
5 RCFD8639 38166 non-null float64
6 RCFD0211 38166 non-null float64
7 RCFD1287 38166 non-null float64
8 RCON3531 1107 non-null float64
9 RCFD1289 38166 non-null float64
10 RCFD1294 38166 non-null float64
11 RCFD1293 38166 non-null float64
12 RCFD1298 38166 non-null float64
13 RCON3532 1111 non-null float64
14 RCFD3210 38443 non-null float64
15 RIAD4230 38398 non-null float64
16 RIAD4340 38441 non-null float64
17 RCFD2122 39644 non-null float64
18 RCFD2125 249 non-null float64
19 RCFD1600 52 non-null float64
dtypes: float64(20)
</code></pre>
|
[
{
"answer_id": 74516758,
"author": "sommmen",
"author_id": 4122889,
"author_profile": "https://Stackoverflow.com/users/4122889",
"pm_score": 0,
"selected": false,
"text": "Variants foreach(var x in baseProduct.SelectMany(c => c.Variants) { x.ProductBase = null } public class Order {\n public List<OrderLine> OrderLines {get;set}\n}\n\npublic class OrderLine {\n public Order Order {get;set}\n}\n\n// Gets mapped to the following viewmodels:\n\npublic class OrderViewModel {\n public List<OrderOrderLineViewModel > OrderLines {get;set}\n}\n\npublic class OrderOrderLineViewModel {\n public Order Order => null; // Stop object cycling\n}\n\n $.Variants.productBase.variants.productBase.variants"
},
{
"answer_id": 74516761,
"author": "NineBerry",
"author_id": 101087,
"author_profile": "https://Stackoverflow.com/users/101087",
"pm_score": 1,
"selected": false,
"text": "ProductVariant ProductSize ProductColor ProductSize ProductColor ProductVariant ProductVariant BaseProduct productVariant ProductSize ProductColor ProductSize ProductColor ProductVariant productBase ProductVariant"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19212804/"
] |
74,516,639
|
<p>I'm using a ParentComponent that sets inputs to a ChildComponent.
If the changed input is number, the ngOnChanges hook fires, but if it's an array, it does not.</p>
<p>Can someone tell me what am I doing wrong, or how to make ngOnChanges firing when the array is changed?</p>
<p>Thank you.</p>
<p><strong>child ts:</strong></p>
<pre><code>export class ChildComponent implements OnInit {
@Input() num = 0;
@Input() arr: Array<string> = [];
constructor() { }
ngOnInit(): void {
}
ngOnChanges() {
console.log('input changed');
}
}
</code></pre>
<p><strong>parent ts:</strong></p>
<pre><code>export class ParentComponent implements OnInit {
constructor() { }
num = 0;
arr : Array<string> =[];
ngOnInit(): void {
}
changeNumber() {
this.num = this.num + 1;
}
changeArray() {
this.arr.push('some value');
}
}
</code></pre>
<p><strong>parent html:</strong></p>
<pre><code><button (click)="changeNumber()">change num</button>
<button (click)="changeArray()">change array</button>
<app-child [num]="num" [arr]="arr"></app-child>
</code></pre>
|
[
{
"answer_id": 74516758,
"author": "sommmen",
"author_id": 4122889,
"author_profile": "https://Stackoverflow.com/users/4122889",
"pm_score": 0,
"selected": false,
"text": "Variants foreach(var x in baseProduct.SelectMany(c => c.Variants) { x.ProductBase = null } public class Order {\n public List<OrderLine> OrderLines {get;set}\n}\n\npublic class OrderLine {\n public Order Order {get;set}\n}\n\n// Gets mapped to the following viewmodels:\n\npublic class OrderViewModel {\n public List<OrderOrderLineViewModel > OrderLines {get;set}\n}\n\npublic class OrderOrderLineViewModel {\n public Order Order => null; // Stop object cycling\n}\n\n $.Variants.productBase.variants.productBase.variants"
},
{
"answer_id": 74516761,
"author": "NineBerry",
"author_id": 101087,
"author_profile": "https://Stackoverflow.com/users/101087",
"pm_score": 1,
"selected": false,
"text": "ProductVariant ProductSize ProductColor ProductSize ProductColor ProductVariant ProductVariant BaseProduct productVariant ProductSize ProductColor ProductSize ProductColor ProductVariant productBase ProductVariant"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3345721/"
] |
74,516,642
|
<p>I need help, please be kind I'm a beginner.
I have a nested dict like this:</p>
<pre><code>dict_ = {
"timestamp": "2022-11-18T10: 10: 49.301Z",
"name" : "example",
"person":{
"birthyear": "2002"
"birthname": "Examply"
},
"order":{
"orderId": "1234"
"ordername": "onetwothreefour"
}
}
</code></pre>
<p>How do I get a new dict like:</p>
<pre><code>new_dict = {"timestamp": "2022-11-18T10: 10: 49.301Z", "birthyear": "2002", "birthname": "Examply", "orderId": "1234"}
</code></pre>
<p>I tried the normal things I could google.
But I only found solutions like getting the values without the keys back or it only works for flatten dicts.
Last thing I tried:</p>
<pre><code>new_dict = {key: msg[key] for key in msg.keys() & {'timestamp', 'birthyear', 'birthname', 'orderId'}
</code></pre>
<p>This do not work for the nested dict.
May someone has an easy option for it.</p>
|
[
{
"answer_id": 74516758,
"author": "sommmen",
"author_id": 4122889,
"author_profile": "https://Stackoverflow.com/users/4122889",
"pm_score": 0,
"selected": false,
"text": "Variants foreach(var x in baseProduct.SelectMany(c => c.Variants) { x.ProductBase = null } public class Order {\n public List<OrderLine> OrderLines {get;set}\n}\n\npublic class OrderLine {\n public Order Order {get;set}\n}\n\n// Gets mapped to the following viewmodels:\n\npublic class OrderViewModel {\n public List<OrderOrderLineViewModel > OrderLines {get;set}\n}\n\npublic class OrderOrderLineViewModel {\n public Order Order => null; // Stop object cycling\n}\n\n $.Variants.productBase.variants.productBase.variants"
},
{
"answer_id": 74516761,
"author": "NineBerry",
"author_id": 101087,
"author_profile": "https://Stackoverflow.com/users/101087",
"pm_score": 1,
"selected": false,
"text": "ProductVariant ProductSize ProductColor ProductSize ProductColor ProductVariant ProductVariant BaseProduct productVariant ProductSize ProductColor ProductSize ProductColor ProductVariant productBase ProductVariant"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17581870/"
] |
74,516,647
|
<p>Fairly new to SAS/SQL, and have a query, I've not been able to solve. I apologies if the details of my problems are a bit vague, but due to my job I can't be too detailed about the actual data, or show the actual code I have.</p>
<p>I have a table that's a combination of sales data and backlog/catalogue type data. Within the sales data is a variable that informs which group the sale belongs to. Below is a table that illustrates my data and my intent, i.e creating the Group variable that states which group the sale belongs to. Is there a way within SAS to match the catalogue_code to the group columns and return a new variable that is the column header of the matched column (ideally without the underscore).</p>
<p>Hope that's enough info for someone to point me in the right direction.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>catalogue_code</th>
<th>Group_A</th>
<th>Group_B</th>
<th>Group_C</th>
<th>Group</th>
</tr>
</thead>
<tbody>
<tr>
<td>B01235</td>
<td>B01234</td>
<td>B01235</td>
<td>B01236</td>
<td>Group B</td>
</tr>
<tr>
<td>B01234</td>
<td>B01234</td>
<td>B01235</td>
<td>B01236</td>
<td>Group A</td>
</tr>
<tr>
<td>B01235</td>
<td>B01234</td>
<td>B01235</td>
<td>B01236</td>
<td>Group B</td>
</tr>
<tr>
<td>B01236</td>
<td>B01234</td>
<td>B01235</td>
<td>B01236</td>
<td>Group C</td>
</tr>
<tr>
<td>B01235</td>
<td>B01234</td>
<td>B01235</td>
<td>B01236</td>
<td>Group B</td>
</tr>
</tbody>
</table>
</div>
|
[
{
"answer_id": 74516758,
"author": "sommmen",
"author_id": 4122889,
"author_profile": "https://Stackoverflow.com/users/4122889",
"pm_score": 0,
"selected": false,
"text": "Variants foreach(var x in baseProduct.SelectMany(c => c.Variants) { x.ProductBase = null } public class Order {\n public List<OrderLine> OrderLines {get;set}\n}\n\npublic class OrderLine {\n public Order Order {get;set}\n}\n\n// Gets mapped to the following viewmodels:\n\npublic class OrderViewModel {\n public List<OrderOrderLineViewModel > OrderLines {get;set}\n}\n\npublic class OrderOrderLineViewModel {\n public Order Order => null; // Stop object cycling\n}\n\n $.Variants.productBase.variants.productBase.variants"
},
{
"answer_id": 74516761,
"author": "NineBerry",
"author_id": 101087,
"author_profile": "https://Stackoverflow.com/users/101087",
"pm_score": 1,
"selected": false,
"text": "ProductVariant ProductSize ProductColor ProductSize ProductColor ProductVariant ProductVariant BaseProduct productVariant ProductSize ProductColor ProductSize ProductColor ProductVariant productBase ProductVariant"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20561080/"
] |
74,516,660
|
<p>I am getting an application crash of my app when I am using mic in my case Microsoft Teams on the background and trying to record an audio inside of my app.</p>
<blockquote>
<p>Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio', reason: 'required condition is false: IsFormatSampleRateAndChannelCountValid(format)'</p>
</blockquote>
<p>Please refer to the code below:</p>
<pre><code>func startRecording() {
// Clear all previous session data and cancel task
if recognitionTask != nil {
recognitionTask?.cancel()
recognitionTask = nil
}
// Create instance of audio session to record voice
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSession.Category.record, mode: AVAudioSession.Mode.measurement, options: AVAudioSession.CategoryOptions.defaultToSpeaker)
try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
} catch {
print("audioSession properties weren't set because of an error.")
}
self.recognitionRequest = SFSpeechAudioBufferRecognitionRequest()
let inputNode = audioEngine.inputNode
guard let recognitionRequest = recognitionRequest else {
fatalError("Unable to create an SFSpeechAudioBufferRecognitionRequest object")
}
recognitionRequest.shouldReportPartialResults = true
self.recognitionTask = speechRecognizer?.recognitionTask(with: recognitionRequest, resultHandler: { (result, error) in
var isFinal = false
if result != nil {
self.textField.text = result?.bestTranscription.formattedString
isFinal = (result?.isFinal)!
}
if error != nil || isFinal {
self.audioEngine.stop()
inputNode.removeTap(onBus: 0)
self.recognitionRequest = nil
self.recognitionTask = nil
self.micButton.isEnabled = true
}
})
let recordingFormat = inputNode.outputFormat(forBus: 0)
inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, when) in
self.recognitionRequest?.append(buffer)
}
self.audioEngine.prepare()
do {
try self.audioEngine.start()
} catch {
print("audioEngine couldn't start because of an error.")
}
self.textField.text = ""
}
</code></pre>
<p>I am pretty sure that the problem is somewhere here, but not sure how to fix it.</p>
<pre><code>let recordingFormat = inputNode.outputFormat(forBus: 0)
inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, when) in
self.recognitionRequest?.append(buffer)
}
</code></pre>
|
[
{
"answer_id": 74516758,
"author": "sommmen",
"author_id": 4122889,
"author_profile": "https://Stackoverflow.com/users/4122889",
"pm_score": 0,
"selected": false,
"text": "Variants foreach(var x in baseProduct.SelectMany(c => c.Variants) { x.ProductBase = null } public class Order {\n public List<OrderLine> OrderLines {get;set}\n}\n\npublic class OrderLine {\n public Order Order {get;set}\n}\n\n// Gets mapped to the following viewmodels:\n\npublic class OrderViewModel {\n public List<OrderOrderLineViewModel > OrderLines {get;set}\n}\n\npublic class OrderOrderLineViewModel {\n public Order Order => null; // Stop object cycling\n}\n\n $.Variants.productBase.variants.productBase.variants"
},
{
"answer_id": 74516761,
"author": "NineBerry",
"author_id": 101087,
"author_profile": "https://Stackoverflow.com/users/101087",
"pm_score": 1,
"selected": false,
"text": "ProductVariant ProductSize ProductColor ProductSize ProductColor ProductVariant ProductVariant BaseProduct productVariant ProductSize ProductColor ProductSize ProductColor ProductVariant productBase ProductVariant"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11714895/"
] |
74,516,740
|
<p>I need to create pathed copy of the class, where calls to one module method are replaced to another module method calls:</p>
<pre><code>module Foo
def self.check
"foo"
end
end
module Bar
def self.check
"bar"
end
end
class Bark
def call
puts Foo.check
end
end
Bark.new.call => "foo"
Meouw = Bark.dup
...
???
Meouw.new.call => "bar"
</code></pre>
<p>Any ideas how would i achieve that?</p>
|
[
{
"answer_id": 74516758,
"author": "sommmen",
"author_id": 4122889,
"author_profile": "https://Stackoverflow.com/users/4122889",
"pm_score": 0,
"selected": false,
"text": "Variants foreach(var x in baseProduct.SelectMany(c => c.Variants) { x.ProductBase = null } public class Order {\n public List<OrderLine> OrderLines {get;set}\n}\n\npublic class OrderLine {\n public Order Order {get;set}\n}\n\n// Gets mapped to the following viewmodels:\n\npublic class OrderViewModel {\n public List<OrderOrderLineViewModel > OrderLines {get;set}\n}\n\npublic class OrderOrderLineViewModel {\n public Order Order => null; // Stop object cycling\n}\n\n $.Variants.productBase.variants.productBase.variants"
},
{
"answer_id": 74516761,
"author": "NineBerry",
"author_id": 101087,
"author_profile": "https://Stackoverflow.com/users/101087",
"pm_score": 1,
"selected": false,
"text": "ProductVariant ProductSize ProductColor ProductSize ProductColor ProductVariant ProductVariant BaseProduct productVariant ProductSize ProductColor ProductSize ProductColor ProductVariant productBase ProductVariant"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/471407/"
] |
74,516,750
|
<p>I try to create a mock test with monkeypatch. I have a typical service-repository class.</p>
<p>repository_class.py</p>
<pre><code>find_by_id(id):
con.select(....);
</code></pre>
<p>service_class.py</p>
<pre><code>get_details(id):
some pre-process...
item = repository_class.find_by_id(id)
post-process...
return result
</code></pre>
<p>then I try to create a mock test with mocking repository method under service:</p>
<pre><code>def test_bid_on_brand_keyword(monkeypatch):
mock_data = "abc"
monkeypatch.setattr(repository_class, 'find_by_id', mock_data)
ans = service_class.get_details(id)
assert ans is not None
</code></pre>
<p>This doesn’t work. It tries to call real repository method. Any suggestion?</p>
|
[
{
"answer_id": 74516758,
"author": "sommmen",
"author_id": 4122889,
"author_profile": "https://Stackoverflow.com/users/4122889",
"pm_score": 0,
"selected": false,
"text": "Variants foreach(var x in baseProduct.SelectMany(c => c.Variants) { x.ProductBase = null } public class Order {\n public List<OrderLine> OrderLines {get;set}\n}\n\npublic class OrderLine {\n public Order Order {get;set}\n}\n\n// Gets mapped to the following viewmodels:\n\npublic class OrderViewModel {\n public List<OrderOrderLineViewModel > OrderLines {get;set}\n}\n\npublic class OrderOrderLineViewModel {\n public Order Order => null; // Stop object cycling\n}\n\n $.Variants.productBase.variants.productBase.variants"
},
{
"answer_id": 74516761,
"author": "NineBerry",
"author_id": 101087,
"author_profile": "https://Stackoverflow.com/users/101087",
"pm_score": 1,
"selected": false,
"text": "ProductVariant ProductSize ProductColor ProductSize ProductColor ProductVariant ProductVariant BaseProduct productVariant ProductSize ProductColor ProductSize ProductColor ProductVariant productBase ProductVariant"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10912170/"
] |
74,516,782
|
<p>I have a .srt file with text like this:</p>
<p>19<br>
00:01:05,100 --> 00:01:08,820<br>
countries such as Spain. Another factor to</p>
<p>20<br>
00:01:08,820 --> 00:01:11,850<br>
consider is the southern tip of Spain's coast</p>
<p>21<br>
00:01:11,850 --> 00:01:15,060<br>
being so close to northern Africa could have<br></p>
<p><br></p>
<p>I've found this code which works pretty well at cleaning the information but this code leaves in the initial numbers (these can be from one digit to four digits)</p>
<p>the result:</p>
<p>19countries such as Spain. Another factor to 20consider is the southern tip of Spain's coast 21being so close to northern Africa could have</p>
<p>Any idea how to remove the digits?</p>
<p>This is my code:</p>
<pre><code> <script>
document.querySelector('#files').addEventListener('change', (e) => {
let files = e.target.files,
i = 0,
reader = new FileReader;
reader.onload = (e) => {
//console.log(files[i].name, e.target.result);
var fileName = files[i].name;
var text = e.target.result;
text = text.replace(/WEBVTT[\r\n]/,"");
text = text.replace(/NOTE duration:.*[\r\n]/,"");
text = text.replace(/NOTE language:.*[\r\n]/,"");
text = text.replace(/NOTE Confidence:.+\d/g,"");
text = text.replace(/NOTE recognizability.+\d/g,"");
text = text.replace(/[\r\n].+-.+-.+-.+-.+/g,"");
text = text.replace(/[\r\n].+ --> .+[\r\n]/g,"");
text = text.replace(/.[\r\n]. --> .+[\r\n]/g,"");
text = text.replace(/[\n](.)/g," $1");
text = text.replace(/[\r\n]+/g,"");
text = text.replace(/^ /,"");
var heading = document.createElement('h3');
document.body.appendChild(heading);
heading.innerHTML = "Transcript for '" + files[i].name + "'";
var copyButton = document.createElement('button');
document.body.appendChild(copyButton);
copyButton.onclick = function() {copyToClip(text,fileName); };
copyButton.innerHTML = "Copy transcript";
copyButton.className = "copyButton";
var div = document.createElement('div');
document.body.appendChild(div);
div.className = "cleanVTTText";
div.innerHTML = text;
//console.log(files[i].name, text);
console.log(files[i].name);
if (i++ < files.length - 1) {
reader.readAsText(files[i]);
} else {
console.log('done');
}
};
reader.readAsText(files[i]);
}, false);
function copyToClip(str,fileName) {
function listener(e) {
e.clipboardData.setData("text/html", str);
e.clipboardData.setData("text/plain", str);
e.preventDefault();
}
document.addEventListener("copy", listener);
document.execCommand("copy");
document.removeEventListener("copy", listener);
alert("Copied transcript to clipboard:\n'"+fileName+"'");
};
</script>
</code></pre>
|
[
{
"answer_id": 74516758,
"author": "sommmen",
"author_id": 4122889,
"author_profile": "https://Stackoverflow.com/users/4122889",
"pm_score": 0,
"selected": false,
"text": "Variants foreach(var x in baseProduct.SelectMany(c => c.Variants) { x.ProductBase = null } public class Order {\n public List<OrderLine> OrderLines {get;set}\n}\n\npublic class OrderLine {\n public Order Order {get;set}\n}\n\n// Gets mapped to the following viewmodels:\n\npublic class OrderViewModel {\n public List<OrderOrderLineViewModel > OrderLines {get;set}\n}\n\npublic class OrderOrderLineViewModel {\n public Order Order => null; // Stop object cycling\n}\n\n $.Variants.productBase.variants.productBase.variants"
},
{
"answer_id": 74516761,
"author": "NineBerry",
"author_id": 101087,
"author_profile": "https://Stackoverflow.com/users/101087",
"pm_score": 1,
"selected": false,
"text": "ProductVariant ProductSize ProductColor ProductSize ProductColor ProductVariant ProductVariant BaseProduct productVariant ProductSize ProductColor ProductSize ProductColor ProductVariant productBase ProductVariant"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20561227/"
] |
74,516,787
|
<p>I'm trying to fetch a list of users from a backend API. It all works perfectly unless that once I log the <code>getAllUsers()</code> method in the <code>ngOnInit</code> I get the data, but when I log the variable containing the list of users I get undefined.</p>
<p>Here is my code:</p>
<pre><code>users:User[];
constructor(private userService:UserService) { }
ngOnInit(): void {
this.getAllUsers();
console.log(this.users); // ==> shows undefined
}
getAllUsers() {
this.userService.getAll().subscribe({
next:(data) => {
console.log(data); // ==> shows the result
this.users=data
}
})
}
</code></pre>
<p>Can anyone explain the difference between them? And how can I access the response outside the subscribe method? I'm still new to angular though! thanks in advance!</p>
|
[
{
"answer_id": 74516758,
"author": "sommmen",
"author_id": 4122889,
"author_profile": "https://Stackoverflow.com/users/4122889",
"pm_score": 0,
"selected": false,
"text": "Variants foreach(var x in baseProduct.SelectMany(c => c.Variants) { x.ProductBase = null } public class Order {\n public List<OrderLine> OrderLines {get;set}\n}\n\npublic class OrderLine {\n public Order Order {get;set}\n}\n\n// Gets mapped to the following viewmodels:\n\npublic class OrderViewModel {\n public List<OrderOrderLineViewModel > OrderLines {get;set}\n}\n\npublic class OrderOrderLineViewModel {\n public Order Order => null; // Stop object cycling\n}\n\n $.Variants.productBase.variants.productBase.variants"
},
{
"answer_id": 74516761,
"author": "NineBerry",
"author_id": 101087,
"author_profile": "https://Stackoverflow.com/users/101087",
"pm_score": 1,
"selected": false,
"text": "ProductVariant ProductSize ProductColor ProductSize ProductColor ProductVariant ProductVariant BaseProduct productVariant ProductSize ProductColor ProductSize ProductColor ProductVariant productBase ProductVariant"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20498616/"
] |
74,516,789
|
<p>I'm trying to make it so that properties are easily adjustable using a .ini file.</p>
<p>The problem currently is that currently these properties are defined using the "&global-define". With this the properties are not easily adjustable.</p>
<p>I want to put all of these variables inside of a settings file, and import that settings file inside of the procedure. I was thinking about using a settings.ini file for this.</p>
<p>I hope I can further clarify what I'm trying to achieve down below.</p>
<p>settings.ini</p>
<pre><code>port = 19995
</code></pre>
<p>procedure.p</p>
<pre><code>import settings.ini .
define variable iPort as integer no-undo .
iPort = port .
</code></pre>
<p>Let me know if more explanation is needed.</p>
<p>Thanks in advance</p>
<p>I looked for a solution on the internet but was unable to find one.</p>
<p>A solution I tried was reading the file and based on the propertyName I would assign a variable, however this seems very inefficient when dealing with a high amount of variables. Example shown below:</p>
<pre><code>input from value("settings.ini") .
repeat:
import unformatted vLine.
iIndex = index(vLine, "=") .
cPropertyName = trim (substring (vLine, 1, iIndex - 1)) .
cPropertyValue = trim (substring (vLine, iIndex + 1)) .
case cPropertyName:
when "port" then
if cPropertyValue <> "" then iPort = cPropertyValue .
else iPort = "" .
end case.
end.
input CLOSE.
</code></pre>
<p>Another solution I found was:
<a href="https://community.progress.com/s/article/is-it-possible-to-set-custom-variables-in-an-ini-file-to-use-with-abl-code" rel="nofollow noreferrer">https://community.progress.com/s/article/is-it-possible-to-set-custom-variables-in-an-ini-file-to-use-with-abl-code</a></p>
<p>But as stated in the comments this solution only works for windows.</p>
<p>I now have a new solution which makes use of a temp-table:
procedure.p</p>
<pre><code>define temp-table ttSettings no-undo
field port as integer .
temp-table ttSettings:read-json ("file", "settings.json").
find first ttSettings .
message ttSettings.port view-as alert-box.
</code></pre>
<p>settings.json</p>
<pre><code>{
"port": 19995
}
</code></pre>
|
[
{
"answer_id": 74521666,
"author": "nwahmaet",
"author_id": 18177,
"author_profile": "https://Stackoverflow.com/users/18177",
"pm_score": 2,
"selected": false,
"text": "block-level on error undo, throw.\n\ndefine temp-table ttIniSetting no-undo\n field Section as character\n field KeyName as character\n field KeyValue as character\n index idx1 as primary unique Section KeyName.\n \ndefine variable cLine as character.\ndefine variable cSection as character.\ndefine variable iPos as integer.\n \ninput from value('/path/to/file.ini').\n\nrepeat:\n import unformatted cLine.\n cLine = trim(cLine).\n \n if cLine begins '#' \n or cLine begins ';' \n or cLine eq ''\n then\n next.\n \n if cLine matches '[*]' then\n do:\n cSection = substring(cLine, 2, r-index(cLine, ']') - 2).\n next.\n end. \n \n iPos = index(cLine, '=').\n \n create ttIniSetting.\n ttIniSetting.Section = cSection.\n ttIniSetting.KeyName = substring(cLine, 1, iPos - 1).\n ttIniSetting.KeyValue = substring(cLine, iPos + 1).\n \nend. \n"
},
{
"answer_id": 74530038,
"author": "Jensd",
"author_id": 2189922,
"author_profile": "https://Stackoverflow.com/users/2189922",
"pm_score": 0,
"selected": false,
"text": "= DEFINE TEMP-TABLE ttSetting NO-UNDO \n FIELD settingKey AS CHARACTER \n FIELD settingValue AS CHARACTER.\n \nINPUT FROM VALUE(\"c:/temp/settings.ini\").\nREPEAT :\n CREATE ttSetting.\n IMPORT DELIMITER \"=\" ttSetting.\n ASSIGN \n ttSetting.settingKey = TRIM(ttSetting.settingKey)\n ttSetting.settingValue = TRIM(ttSetting.settingValue).\nEND.\nINPUT CLOSE.\n\nFOR EACH ttSetting:\n DISPLAY ttSetting.\nEND.\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18725072/"
] |
74,516,803
|
<p>I have to implement a method named <em>groupBy</em> which has the following signature:
<code>groupBy : (a -> b) -> List a -> List ( b, List a )</code>.</p>
<p>The method takes as input a function and a list of items and returns a list of tuples in the form (b, List a), i.e. it returns some kind of dictionary in which the <strong>key</strong> is the value <strong>b</strong> of the function applied to an item <strong>a</strong> in the input list, and the <strong>value</strong> is an array of items for which the function applied on has the same value. The function given as a parameter is the <em>criteria</em> by which the elements are <em>grouped by</em>. The following examples should make it more clear.</p>
<p>It should return the following results for the give tests:</p>
<ul>
<li><code>groupBy .x [ { x = 1 } ] --> [(1, [{x = 1}])]</code></li>
<li><code>groupBy (modBy 10) [ 11, 12, 21, 22 ] --> [(1, [11, 21]), (2, [12, 22])]</code></li>
<li><code>groupBy identity [] --> []</code>.</li>
</ul>
<p>I'm not sure what the 'identity' input means, but I suppose that it is an input for which the method should return the same array which was given as the second parameter.</p>
<p>I've tried the following code and I almost managed to get the result, but I'm stuck and I have no ideas of how I should continue:</p>
<pre><code>groupBy : (a -> b) -> List a -> List ( b, List a )
groupBy criteria list =
let
unique lst =
List.foldl
(\a uniques ->
if List.member a uniques then
uniques
else
uniques ++ [a]
)
[]
lst
keys =
list
|> List.map criteria
|> unique
pairs =
List.map2 Tuple.pair (List.map criteria list) list
filtered_list =
List.filterMap (\x -> criteria x == keys)
group kl lst =
case kl of
[] -> []
k::ks ->
(k, []):: (result els)
in
[]
-- Debug.todo "Implement groupBy in Util.elm"
</code></pre>
<p>If I run the following code in <strong>elm repl</strong>:
<code>List.map2 Tuple.pair (List.map (modBy 10) [ 11, 12, 21, 22 ]) [ 11, 12, 21, 22 ]</code>, then I get the result:
<code>[(1,11),(2,12),(1,21),(2,22)]</code></p>
<p>The <strong>unique</strong> function returns a list of unique elements (basically a set) given a list which contains duplicates.
The <strong>pairs</strong> function creates tuples of (<strong>b</strong>, <strong>a</strong>) form, but I'm trying to get to the form (<strong>b</strong>, List <strong>a</strong>).
The other two functions don't work, they're just attempts for trying to get to the final form.</p>
<p><a href="https://meta.stackoverflow.com/q/334822">[How do I ask and answer homework questions?]</a></p>
|
[
{
"answer_id": 74520166,
"author": "Catalin Goga",
"author_id": 13059249,
"author_profile": "https://Stackoverflow.com/users/13059249",
"pm_score": 1,
"selected": false,
"text": "groupBy : (a -> b) -> List a -> List ( b, List a )\ngroupBy criteria list =\n let\n unique lst = \n List.foldl\n (\\a uniques ->\n if List.member a uniques then\n uniques\n else\n uniques ++ [a]\n )\n [] \n lst\n keys = \n list\n |> List.map criteria\n |> unique\n \n group kl lst =\n case kl of\n [] -> []\n k::ks ->\n (k, List.filter (\\x -> criteria x == k) lst) :: group ks lst\n in\n group keys list\n"
},
{
"answer_id": 74528315,
"author": "pdamoc",
"author_id": 626515,
"author_profile": "https://Stackoverflow.com/users/626515",
"pm_score": 3,
"selected": true,
"text": "list-extra gatherEqualsBy (a -> b) -> List a -> List ( b, List a )"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13059249/"
] |
74,516,817
|
<p>Bicep can be used to create a role assignment as follows:</p>
<pre><code>resource RoleAssignment 'Microsoft.Authorization/roleAssignments@2020-10-01-preview' = {
name: guid(managementGroup().id, RoleDefinitionId, principalId)
properties: {
roleDefinitionId: roleDefinition.id
principalId: principalId
principalType: principalType
}
}
</code></pre>
<p>Where the principal type is 'ServicePrincipal', it seems the application id from the Enterprise Application page of the Azure portal is required:</p>
<p><a href="https://i.stack.imgur.com/XSmKo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XSmKo.png" alt="enter image description here" /></a></p>
<p>Does anyone know how to acquire this programatically? If it's not possible using bicep then perhaps PowerShell?</p>
|
[
{
"answer_id": 74517294,
"author": "Imran",
"author_id": 18229970,
"author_profile": "https://Stackoverflow.com/users/18229970",
"pm_score": 2,
"selected": true,
"text": "Application ID (Get-AzADServicePrincipal -DisplayName AppName).AppId\n ClientApp (Get-AzADServicePrincipal -DisplayName ClientApp).AppId\n"
},
{
"answer_id": 74522903,
"author": "Ezequiel Santos",
"author_id": 10572045,
"author_profile": "https://Stackoverflow.com/users/10572045",
"pm_score": 0,
"selected": false,
"text": "resource workflows_la 'Microsoft.Logic/workflows@2017-07-01' = {\n name: 'la-${env_id}-test'\n location: location\n identity: {\n type: 'SystemAssigned'\n }\n\noutput logicapp_managed_identity string = workflows_la.identity.principalId\n resource roleAssignmentlogicApp 'Microsoft.Authorization/roleAssignments@2020-04-01-preview' = {\n scope: Storage\n name: guid(Storage.id, managed_identity_logic_app, roleDefinitionResourceId)\n properties: {\n roleDefinitionId: roleDefinitionResourceId\n principalId: managed_identity_logic_app\n }\n}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41169/"
] |
74,516,830
|
<p>I am new to the react (Jest) tests and I wanted to start practice but for some reason I get an error that there are no tests found.</p>
<p>package.json:</p>
<pre><code>{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"socket.io-client": "^4.5.2",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --watchAll",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
</code></pre>
<p>my test</p>
<pre><code>import {render, screen, cleanup} from '@testing-library/react';
import Home from '../src/Home.js';
test('test', () => {
expect(true).toBe(true);
})
</code></pre>
<p>the test is located in another folder called <em>testing</em> inside the src folder (where the original jsx file is). I am trying to run it with npm test but it never finds any tests. The main file is Home.js and the test file is called Home.test.js</p>
|
[
{
"answer_id": 74517220,
"author": "Ryan Le",
"author_id": 5122615,
"author_profile": "https://Stackoverflow.com/users/5122615",
"pm_score": 2,
"selected": true,
"text": ".js __tests__ .test.js .spec.js .test.js .spec.js __tests__ src"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20045530/"
] |
74,516,842
|
<p>I currently have my userInfo stored in a state</p>
<pre><code>const [users, setUsers] = useState([])
</code></pre>
<p>Please, how do I pass the userId into the axios URL to be able to fetch the posts of a specific user. see what I did below. I know I am getting it wrong but please help me.</p>
<p><strong>Dashboard Component</strong></p>
<pre><code>const Dashboard = () => {
const getPost = () => {
axios.get(`/api/getpost/${users._id}`, //I want to fetch the userID on this URL. That measns it is to replace ${users._id}
{
withCredentials: 'true',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then((response) => {
setUposts(response.data)
})
}
useEffect(() => {
getPost()
}, [])
return (
//something here
)
}
</code></pre>
<p><strong>UserSchema</strong>
This is my userSchema</p>
<pre><code>const userSchema = new Schema({
username: {
type: String,
required: true
},
roles: {
User: {
type: Number,
default: 2001
},
Mentor: Number,
Admin: Number
},
password: {
type: String,
required: true
},
userID: {
type: String,
required: true
},
Profile: {
type: mongoose.Schema.Types.ObjectId,
ref: "profile",
},
refreshToken: String
});
const User = mongoose.model('user', userSchema);
module.exports = User;
</code></pre>
<p><strong>API TO GET USER POST</strong>
This is how I find the user by their id from the database and populate</p>
<pre><code>router.get('/getpost/:id/', (req, res) => {
const id = req.params.id;
// const profID = req.params.prof_id;
Userpost.find({User:id}).populate('User', {password: 0}).populate('Profile').exec((err,docs) => {
if(err) throw(err);
res.json(docs);
})
});
</code></pre>
<p><strong>HOW I setUsers</strong>
The code below show how I did set the User in state.</p>
<pre><code> const getUser = () => {
axios.get('/api/users', {
withCredentials: 'true',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then((response) => {
setUsers(response.data)
})
};
useEffect(() => {
getUser()
}, [])
</code></pre>
|
[
{
"answer_id": 74517203,
"author": "Thaiyalnayaki",
"author_id": 15431167,
"author_profile": "https://Stackoverflow.com/users/15431167",
"pm_score": 0,
"selected": false,
"text": "/api/getpost/${users[0]._id}"
},
{
"answer_id": 74517368,
"author": "Daniel",
"author_id": 14698690,
"author_profile": "https://Stackoverflow.com/users/14698690",
"pm_score": 2,
"selected": true,
"text": "const getUser = () => {\n axios.get('/api/users', {\n withCredentials: 'true',\n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }\n })\n .then((response) => {\n let user = response.data\n })\n };\n useEffect(() => {\n getUser()\n }, [])\n"
},
{
"answer_id": 74517821,
"author": "KARAN DOSHI",
"author_id": 19615397,
"author_profile": "https://Stackoverflow.com/users/19615397",
"pm_score": 1,
"selected": false,
"text": "<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js\"></script>\nconst Dashboard = () => {\n\nconst getPost = (userId) => { \n\n axios.get(`/api/getpost/${userId}`, \n {\n withCredentials: 'true',\n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }\n })\n .then((response) => {\n setUposts(response.data)\n })\n }\n useEffect(() => {\n getPost(users[0].userId);\n }, [])\n\n\nreturn (\n//something here\n\n)\n}"
},
{
"answer_id": 74542940,
"author": "SwiftDev",
"author_id": 20234989,
"author_profile": "https://Stackoverflow.com/users/20234989",
"pm_score": 0,
"selected": false,
"text": "const getUserPost = () => {\n axios.get('/api/users', {\n withCredentials: 'true',\n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }\n })\n .then((response) => {\n let user = response.data\n\n axios.get(`/api/getpost/` + user[0]._id, {\n withCredentials: 'true',\n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }\n })\n .then((response) => {\n setUposts(response.data)\n })\n })\n\n };\n useEffect(() => {\n getUserPost()\n }, [])\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20234989/"
] |
74,516,845
|
<p>Let's say I have the following options structure</p>
<pre class="lang-cs prettyprint-override"><code>using System.ComponentModel.DataAnnotations;
public record AzureOption
{
public AzureGraphOption? Graph { get; init; }
}
public record AzureGraphOption
{
public AzureGraphSecretOption? Secret { get; init; }
}
public record AzureGraphSecretOption
{
[Required] public string TenantId { get; init; }
[Required] public string ClientId { get; init; }
[Required] public string ClientSecret { get; init; }
}
</code></pre>
<p>And an extension class:</p>
<pre class="lang-cs prettyprint-override"><code>using Azure.Core;
using Azure.Identity;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.Graph;
public static class AzureServiceExtensions
{
// Add Azure services so we can query the Microsoft Graph and resolve membership for automatic group assignment
public static IServiceCollection AddAzureServices(this IServiceCollection services)
{
services.AddAzureOptions();
// Add a Azure Token Credentials based on "static" credentials
// Requires a working Azure app and approvals for several permissions.
// The app does not have to be operating on behalf of the user.
services.AddScoped<TokenCredential>(provider =>
{
var azureOption = provider.GetRequiredService<IOptionsMonitor<AzureOption>>().CurrentValue;
return new ClientSecretCredential(
azureOption.Graph?.Secret?.TenantId,
azureOption.Graph?.Secret?.ClientId,
azureOption.Graph?.Secret?.ClientSecret,
new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
});
});
// Add the Microsoft Graph Service, based on the Azure Token
services.AddScoped(provider => new GraphServiceClient(provider.GetService<TokenCredential>(),
new[] { "https://graph.microsoft.com/.default" }));
return services;
}
public static IServiceCollection AddAzureOptions(this IServiceCollection services)
{
services.AddOptions<AzureOption>()
.BindConfiguration("Azure")
.ValidateDataAnnotations()
.ValidateOnStart();
return services;
}
}
</code></pre>
<p>And a small utility extension class:</p>
<pre class="lang-cs prettyprint-override"><code>using Microsoft.Extensions.Configuration;
public static class ServiceCollectionExtensions
{
public static IConfigurationBuilder AddSecretConfig(this IConfigurationBuilder config)
{
config.AddJsonFile("appsettings.Secret.json", true, true);
return config;
}
}
</code></pre>
<p>We can also bootstrap a little ASP.NET Core app for testing, if you will:</p>
<pre class="lang-cs prettyprint-override"><code>using WebApplication = Microsoft.AspNetCore.Builder.WebApplication;
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddSecretConfig();
builder.Services
.AddAzureServices();
var app = builder.Build();
app.Run();
</code></pre>
<p>I also have a small structure of secret file stored as <code>appsettings.Secret.json</code> in web root:</p>
<pre class="lang-json prettyprint-override"><code>{
"Azure": {
"Graph": {
"Secret": {
"TenantId": "30cbfa3f-a625-436a-90ff-e90c3fe8bb8e",
"ClientId": "37c72790-ee45-4090-a749-c3ff61c43df8",
"ClientSecret": "qqBGA~5QYza42ABjeWx4o-kAQPJKAGD38wVXCR7Y"
}
}
}
}
</code></pre>
<p>It all went good and well, until I decided to delete the secrets:</p>
<pre class="lang-json prettyprint-override"><code>{
"Azure": {
"Graph": {
"Secret": {
}
}
}
}
</code></pre>
<p>However, the app still runs, and does not validate for the fields of <code>Azure:Graph:Secret</code>, because it is now <code>null</code> instead. Thus the <code>Required</code> validations attached on the fields never runs. If you have added a wrong property in <code>Azure:Graph:Secret</code>, this will happen too:</p>
<pre class="lang-cs prettyprint-override"><code>var azureOption = provider.GetRequiredService<IOptionsMonitor<AzureOption>>().CurrentValue;
var tenant = azureOption.Graph.Secret.TenantId; // What???! it is null???!
</code></pre>
<p>Of course, this is not desirable. I wanted to have this run dynamically:</p>
<pre><code>var azureOption = provider.GetRequiredService<IOptionsMonitor<AzureOption>>().CurrentValue;
var tenant = azureOption.Graph.Secret.TenantId; // Throws an exception `Required value is not set` instead, while I don't have to handle nullable
</code></pre>
<p>One can always choose to add the nested options to match:</p>
<pre class="lang-cs prettyprint-override"><code> public static IServiceCollection AddAzureOptions(this IServiceCollection services)
{
services.AddOptions<AzureOption>()
.BindConfiguration("Azure")
.ValidateDataAnnotations()
.ValidateOnStart();
services.AddOptions<AzureGraphSecretOption>()
.BindConfiguration("Azure:Graph:Secret")
.ValidateDataAnnotations()
.ValidateOnStart();
return services;
}
</code></pre>
<p>But doing so is very tedious especially when you have tons of options.</p>
|
[
{
"answer_id": 74518495,
"author": "Chernyshev Ivan",
"author_id": 20557670,
"author_profile": "https://Stackoverflow.com/users/20557670",
"pm_score": 1,
"selected": false,
"text": "AzureOption AzureOption MyRecursiveValidationAttribute : ValidationAttribute public class MyRecursiveValidationAttribute : ValidationAttribute\n{\n public override bool IsValid(object? value)\n {\n var isValid = true;\n\n if (value == null)\n { return isValid; }\n\n isValid = Validator.TryValidateObject(value, new ValidationContext(value), null);\n\n return isValid;\n }\n}\n public record AzureOption\n{\n [MyRecursiveValidation]\n public AzureGraphOption? Graph { get; init; }\n}\n\npublic record AzureGraphOption\n{\n [MyRecursiveValidation]\n public AzureGraphSecretOption? Secret { get; init; }\n}\n\npublic record AzureGraphSecretOption\n{\n [Required] public string TenantId { get; init; }\n [Required] public string ClientId { get; init; }\n [Required] public string ClientSecret { get; init; }\n}\n"
},
{
"answer_id": 74519120,
"author": "Steve Fan",
"author_id": 3289081,
"author_profile": "https://Stackoverflow.com/users/3289081",
"pm_score": 0,
"selected": false,
"text": "using System.ComponentModel.DataAnnotations;\nusing System.Collections.Immutable;\n\npublic class ValidateObjectAttribute : ValidationAttribute\n{\n protected override ValidationResult IsValid(object? value, ValidationContext validationContext)\n {\n if (value == null)\n {\n var nullable = validationContext.ObjectType\n .GetMember(validationContext.MemberName!)\n .FirstOrDefault()?.CustomAttributes.Any(x => x.AttributeType.Name == \"NullableAttribute\") ?? false;\n return nullable ? ValidationResult.Success! : new ValidationResult($\"{validationContext.DisplayName} is null\");\n }\n\n var results = new List<ValidationResult>();\n Validator.TryValidateObject(value, new ValidationContext(value, null, null), results, true);\n\n if (results.Count > 0)\n {\n var compositeResults = new CompositeValidationResult($@\"Validation for \"\"{validationContext.DisplayName}\"\" failed!\");\n results.ForEach(compositeResults.AddResult);\n return compositeResults;\n }\n\n return ValidationResult.Success!;\n\n }\n}\n\npublic class CompositeValidationResult : ValidationResult\n{\n public IImmutableList<ValidationResult> Results { get; private set; } = ImmutableList<ValidationResult>.Empty;\n\n public CompositeValidationResult(string errorMessage) : base(errorMessage) { }\n public CompositeValidationResult(string errorMessage, IEnumerable<string> memberNames) : base(errorMessage, memberNames) { }\n protected CompositeValidationResult(ValidationResult validationResult) : base(validationResult) { }\n\n public void AddResult(ValidationResult validationResult) => Results = Results.Add(validationResult);\n}\n using System.ComponentModel.DataAnnotations;\n\npublic record GiteaOption\n{\n [Required] public required string BaseUrl { get; init; }\n [ValidateObject]\n public GiteaSecretOption? Secret { get; init; } \n}\n\npublic record GiteaSecretOption\n{ \n [Required] public required string AccessToken { get; init; }\n}\n Secret"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3289081/"
] |
74,516,883
|
<p>I am new at FLutter and I want to try to make authorization but I don't know how to do it properly.</p>
<p>I have multiple screens with inputs</p>
<p>First screen: Choose country in textFormField => Second screen: type name, email in textFormFields => Third screen: type and confirm password in textFormFields</p>
<p>And when I press sign up button, I should send country, name, email and password to a server.</p>
<p>But where to store values of previous screens. Should I just transfer all data from one screen to another using navigator, or there is a better solution?</p>
<p>I know in React exists redux or mobX(state manager) but do we have something similar in flutter?</p>
|
[
{
"answer_id": 74518495,
"author": "Chernyshev Ivan",
"author_id": 20557670,
"author_profile": "https://Stackoverflow.com/users/20557670",
"pm_score": 1,
"selected": false,
"text": "AzureOption AzureOption MyRecursiveValidationAttribute : ValidationAttribute public class MyRecursiveValidationAttribute : ValidationAttribute\n{\n public override bool IsValid(object? value)\n {\n var isValid = true;\n\n if (value == null)\n { return isValid; }\n\n isValid = Validator.TryValidateObject(value, new ValidationContext(value), null);\n\n return isValid;\n }\n}\n public record AzureOption\n{\n [MyRecursiveValidation]\n public AzureGraphOption? Graph { get; init; }\n}\n\npublic record AzureGraphOption\n{\n [MyRecursiveValidation]\n public AzureGraphSecretOption? Secret { get; init; }\n}\n\npublic record AzureGraphSecretOption\n{\n [Required] public string TenantId { get; init; }\n [Required] public string ClientId { get; init; }\n [Required] public string ClientSecret { get; init; }\n}\n"
},
{
"answer_id": 74519120,
"author": "Steve Fan",
"author_id": 3289081,
"author_profile": "https://Stackoverflow.com/users/3289081",
"pm_score": 0,
"selected": false,
"text": "using System.ComponentModel.DataAnnotations;\nusing System.Collections.Immutable;\n\npublic class ValidateObjectAttribute : ValidationAttribute\n{\n protected override ValidationResult IsValid(object? value, ValidationContext validationContext)\n {\n if (value == null)\n {\n var nullable = validationContext.ObjectType\n .GetMember(validationContext.MemberName!)\n .FirstOrDefault()?.CustomAttributes.Any(x => x.AttributeType.Name == \"NullableAttribute\") ?? false;\n return nullable ? ValidationResult.Success! : new ValidationResult($\"{validationContext.DisplayName} is null\");\n }\n\n var results = new List<ValidationResult>();\n Validator.TryValidateObject(value, new ValidationContext(value, null, null), results, true);\n\n if (results.Count > 0)\n {\n var compositeResults = new CompositeValidationResult($@\"Validation for \"\"{validationContext.DisplayName}\"\" failed!\");\n results.ForEach(compositeResults.AddResult);\n return compositeResults;\n }\n\n return ValidationResult.Success!;\n\n }\n}\n\npublic class CompositeValidationResult : ValidationResult\n{\n public IImmutableList<ValidationResult> Results { get; private set; } = ImmutableList<ValidationResult>.Empty;\n\n public CompositeValidationResult(string errorMessage) : base(errorMessage) { }\n public CompositeValidationResult(string errorMessage, IEnumerable<string> memberNames) : base(errorMessage, memberNames) { }\n protected CompositeValidationResult(ValidationResult validationResult) : base(validationResult) { }\n\n public void AddResult(ValidationResult validationResult) => Results = Results.Add(validationResult);\n}\n using System.ComponentModel.DataAnnotations;\n\npublic record GiteaOption\n{\n [Required] public required string BaseUrl { get; init; }\n [ValidateObject]\n public GiteaSecretOption? Secret { get; init; } \n}\n\npublic record GiteaSecretOption\n{ \n [Required] public required string AccessToken { get; init; }\n}\n Secret"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20478292/"
] |
74,516,895
|
<p>I want to change the color of the first p element, in the example I presented first-child would work as I understand but, in the project I am working there are actually more elements, and more could be added, therefore I would like to avoid ever using it. I need to only change the first element of type p in a given div.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.test p:first-of-type{
background-color:red
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div class="test">
<p>hello</p>
<p>hello</p>
<div>
<p>hello</p>
</div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74518495,
"author": "Chernyshev Ivan",
"author_id": 20557670,
"author_profile": "https://Stackoverflow.com/users/20557670",
"pm_score": 1,
"selected": false,
"text": "AzureOption AzureOption MyRecursiveValidationAttribute : ValidationAttribute public class MyRecursiveValidationAttribute : ValidationAttribute\n{\n public override bool IsValid(object? value)\n {\n var isValid = true;\n\n if (value == null)\n { return isValid; }\n\n isValid = Validator.TryValidateObject(value, new ValidationContext(value), null);\n\n return isValid;\n }\n}\n public record AzureOption\n{\n [MyRecursiveValidation]\n public AzureGraphOption? Graph { get; init; }\n}\n\npublic record AzureGraphOption\n{\n [MyRecursiveValidation]\n public AzureGraphSecretOption? Secret { get; init; }\n}\n\npublic record AzureGraphSecretOption\n{\n [Required] public string TenantId { get; init; }\n [Required] public string ClientId { get; init; }\n [Required] public string ClientSecret { get; init; }\n}\n"
},
{
"answer_id": 74519120,
"author": "Steve Fan",
"author_id": 3289081,
"author_profile": "https://Stackoverflow.com/users/3289081",
"pm_score": 0,
"selected": false,
"text": "using System.ComponentModel.DataAnnotations;\nusing System.Collections.Immutable;\n\npublic class ValidateObjectAttribute : ValidationAttribute\n{\n protected override ValidationResult IsValid(object? value, ValidationContext validationContext)\n {\n if (value == null)\n {\n var nullable = validationContext.ObjectType\n .GetMember(validationContext.MemberName!)\n .FirstOrDefault()?.CustomAttributes.Any(x => x.AttributeType.Name == \"NullableAttribute\") ?? false;\n return nullable ? ValidationResult.Success! : new ValidationResult($\"{validationContext.DisplayName} is null\");\n }\n\n var results = new List<ValidationResult>();\n Validator.TryValidateObject(value, new ValidationContext(value, null, null), results, true);\n\n if (results.Count > 0)\n {\n var compositeResults = new CompositeValidationResult($@\"Validation for \"\"{validationContext.DisplayName}\"\" failed!\");\n results.ForEach(compositeResults.AddResult);\n return compositeResults;\n }\n\n return ValidationResult.Success!;\n\n }\n}\n\npublic class CompositeValidationResult : ValidationResult\n{\n public IImmutableList<ValidationResult> Results { get; private set; } = ImmutableList<ValidationResult>.Empty;\n\n public CompositeValidationResult(string errorMessage) : base(errorMessage) { }\n public CompositeValidationResult(string errorMessage, IEnumerable<string> memberNames) : base(errorMessage, memberNames) { }\n protected CompositeValidationResult(ValidationResult validationResult) : base(validationResult) { }\n\n public void AddResult(ValidationResult validationResult) => Results = Results.Add(validationResult);\n}\n using System.ComponentModel.DataAnnotations;\n\npublic record GiteaOption\n{\n [Required] public required string BaseUrl { get; init; }\n [ValidateObject]\n public GiteaSecretOption? Secret { get; init; } \n}\n\npublic record GiteaSecretOption\n{ \n [Required] public required string AccessToken { get; init; }\n}\n Secret"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18834616/"
] |
74,516,902
|
<p>How to override the property of outline: none in css. In the parent class there is a property outline: none and in child class i dont need that .</p>
|
[
{
"answer_id": 74518495,
"author": "Chernyshev Ivan",
"author_id": 20557670,
"author_profile": "https://Stackoverflow.com/users/20557670",
"pm_score": 1,
"selected": false,
"text": "AzureOption AzureOption MyRecursiveValidationAttribute : ValidationAttribute public class MyRecursiveValidationAttribute : ValidationAttribute\n{\n public override bool IsValid(object? value)\n {\n var isValid = true;\n\n if (value == null)\n { return isValid; }\n\n isValid = Validator.TryValidateObject(value, new ValidationContext(value), null);\n\n return isValid;\n }\n}\n public record AzureOption\n{\n [MyRecursiveValidation]\n public AzureGraphOption? Graph { get; init; }\n}\n\npublic record AzureGraphOption\n{\n [MyRecursiveValidation]\n public AzureGraphSecretOption? Secret { get; init; }\n}\n\npublic record AzureGraphSecretOption\n{\n [Required] public string TenantId { get; init; }\n [Required] public string ClientId { get; init; }\n [Required] public string ClientSecret { get; init; }\n}\n"
},
{
"answer_id": 74519120,
"author": "Steve Fan",
"author_id": 3289081,
"author_profile": "https://Stackoverflow.com/users/3289081",
"pm_score": 0,
"selected": false,
"text": "using System.ComponentModel.DataAnnotations;\nusing System.Collections.Immutable;\n\npublic class ValidateObjectAttribute : ValidationAttribute\n{\n protected override ValidationResult IsValid(object? value, ValidationContext validationContext)\n {\n if (value == null)\n {\n var nullable = validationContext.ObjectType\n .GetMember(validationContext.MemberName!)\n .FirstOrDefault()?.CustomAttributes.Any(x => x.AttributeType.Name == \"NullableAttribute\") ?? false;\n return nullable ? ValidationResult.Success! : new ValidationResult($\"{validationContext.DisplayName} is null\");\n }\n\n var results = new List<ValidationResult>();\n Validator.TryValidateObject(value, new ValidationContext(value, null, null), results, true);\n\n if (results.Count > 0)\n {\n var compositeResults = new CompositeValidationResult($@\"Validation for \"\"{validationContext.DisplayName}\"\" failed!\");\n results.ForEach(compositeResults.AddResult);\n return compositeResults;\n }\n\n return ValidationResult.Success!;\n\n }\n}\n\npublic class CompositeValidationResult : ValidationResult\n{\n public IImmutableList<ValidationResult> Results { get; private set; } = ImmutableList<ValidationResult>.Empty;\n\n public CompositeValidationResult(string errorMessage) : base(errorMessage) { }\n public CompositeValidationResult(string errorMessage, IEnumerable<string> memberNames) : base(errorMessage, memberNames) { }\n protected CompositeValidationResult(ValidationResult validationResult) : base(validationResult) { }\n\n public void AddResult(ValidationResult validationResult) => Results = Results.Add(validationResult);\n}\n using System.ComponentModel.DataAnnotations;\n\npublic record GiteaOption\n{\n [Required] public required string BaseUrl { get; init; }\n [ValidateObject]\n public GiteaSecretOption? Secret { get; init; } \n}\n\npublic record GiteaSecretOption\n{ \n [Required] public required string AccessToken { get; init; }\n}\n Secret"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20528893/"
] |
74,516,912
|
<p>I have to run a one-line batch command in my Python script.</p>
<p>Currently, I am saving my command in a <code>.bat</code> file and executing the <code>.bat</code> file using the <code>subprocess</code>. But I want to omit the <code>.bat</code> file and directly include the command in my <code>python</code> script. Because I might need to use different bat files for different use cases. I would prefer to use one dynamic python script than save multiple <code>.bat</code> files.</p>
<p>bat command:</p>
<p><code>"C:\Program Files (x86)\temp\FL.B5.exe" /s /a "C:\Users\kuk\Downloads\B5+Typ B.2.asc" /o "C:\Users\kuk\Download\B5+Typ B.2.docx"</code></p>
<p>Python script was:</p>
<pre><code>import subprocess as sp
sp.call([r"C:\Users\kuk\Downloads\test.bat"])
</code></pre>
<p><strong>What I want is:</strong></p>
<pre><code>import subprocess
exe = r"C:\Program Files (x86)\temp\FL.B5.exe"
input = r"C:\Users\kuk\Downloads\B5+Typ B.2.asc"
output = r"C:\Users\kuk\Downloads\B5+Typ B.2.docx"
cmd = '{} /s /a {} /o {}'.format(soft,var1,var2)
subprocess.call(cmd)
</code></pre>
<p>I don't know what is wrong, but unable to execute the script.</p>
<p>Any help would be appreciated!!</p>
|
[
{
"answer_id": 74518495,
"author": "Chernyshev Ivan",
"author_id": 20557670,
"author_profile": "https://Stackoverflow.com/users/20557670",
"pm_score": 1,
"selected": false,
"text": "AzureOption AzureOption MyRecursiveValidationAttribute : ValidationAttribute public class MyRecursiveValidationAttribute : ValidationAttribute\n{\n public override bool IsValid(object? value)\n {\n var isValid = true;\n\n if (value == null)\n { return isValid; }\n\n isValid = Validator.TryValidateObject(value, new ValidationContext(value), null);\n\n return isValid;\n }\n}\n public record AzureOption\n{\n [MyRecursiveValidation]\n public AzureGraphOption? Graph { get; init; }\n}\n\npublic record AzureGraphOption\n{\n [MyRecursiveValidation]\n public AzureGraphSecretOption? Secret { get; init; }\n}\n\npublic record AzureGraphSecretOption\n{\n [Required] public string TenantId { get; init; }\n [Required] public string ClientId { get; init; }\n [Required] public string ClientSecret { get; init; }\n}\n"
},
{
"answer_id": 74519120,
"author": "Steve Fan",
"author_id": 3289081,
"author_profile": "https://Stackoverflow.com/users/3289081",
"pm_score": 0,
"selected": false,
"text": "using System.ComponentModel.DataAnnotations;\nusing System.Collections.Immutable;\n\npublic class ValidateObjectAttribute : ValidationAttribute\n{\n protected override ValidationResult IsValid(object? value, ValidationContext validationContext)\n {\n if (value == null)\n {\n var nullable = validationContext.ObjectType\n .GetMember(validationContext.MemberName!)\n .FirstOrDefault()?.CustomAttributes.Any(x => x.AttributeType.Name == \"NullableAttribute\") ?? false;\n return nullable ? ValidationResult.Success! : new ValidationResult($\"{validationContext.DisplayName} is null\");\n }\n\n var results = new List<ValidationResult>();\n Validator.TryValidateObject(value, new ValidationContext(value, null, null), results, true);\n\n if (results.Count > 0)\n {\n var compositeResults = new CompositeValidationResult($@\"Validation for \"\"{validationContext.DisplayName}\"\" failed!\");\n results.ForEach(compositeResults.AddResult);\n return compositeResults;\n }\n\n return ValidationResult.Success!;\n\n }\n}\n\npublic class CompositeValidationResult : ValidationResult\n{\n public IImmutableList<ValidationResult> Results { get; private set; } = ImmutableList<ValidationResult>.Empty;\n\n public CompositeValidationResult(string errorMessage) : base(errorMessage) { }\n public CompositeValidationResult(string errorMessage, IEnumerable<string> memberNames) : base(errorMessage, memberNames) { }\n protected CompositeValidationResult(ValidationResult validationResult) : base(validationResult) { }\n\n public void AddResult(ValidationResult validationResult) => Results = Results.Add(validationResult);\n}\n using System.ComponentModel.DataAnnotations;\n\npublic record GiteaOption\n{\n [Required] public required string BaseUrl { get; init; }\n [ValidateObject]\n public GiteaSecretOption? Secret { get; init; } \n}\n\npublic record GiteaSecretOption\n{ \n [Required] public required string AccessToken { get; init; }\n}\n Secret"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20233252/"
] |
74,516,951
|
<p>I'm following a guide in which <code>api routes</code> are built like so:</p>
<p>1 create <code>server/api/route.js</code> file:</p>
<pre><code>export default defineEventHandler((event) => {
return {
message: `hello api route`
}
})
</code></pre>
<p>2 use api route in component like so:</p>
<pre><code><script setup>
const { data: message } = await useFetch('/api/route')
</script>
<template>
<div>
<p>api data {{ message }}</p>
</div>
</template>
</code></pre>
<p>This works but when I try to add a <code>query parameter</code> in <code>1.</code>:</p>
<pre><code>export default defineEventHandler((event) => {
const { name } = useQuery(event)
return {
message: `hello api name parameter ${name}`
}
})
</code></pre>
<p>and call it in a component <code>2.</code>:</p>
<pre><code><script setup>
const { data: message } = await useFetch('/api/route?name=mario')
</script>
<template>
<div>
<p>api data {{ message }}</p>
</div>
</template>
</code></pre>
<p>the <code>message</code> property is empty. It seems that <code>useQuery(event)</code> produces an empty variable. Any idea why this is not working?</p>
|
[
{
"answer_id": 74518495,
"author": "Chernyshev Ivan",
"author_id": 20557670,
"author_profile": "https://Stackoverflow.com/users/20557670",
"pm_score": 1,
"selected": false,
"text": "AzureOption AzureOption MyRecursiveValidationAttribute : ValidationAttribute public class MyRecursiveValidationAttribute : ValidationAttribute\n{\n public override bool IsValid(object? value)\n {\n var isValid = true;\n\n if (value == null)\n { return isValid; }\n\n isValid = Validator.TryValidateObject(value, new ValidationContext(value), null);\n\n return isValid;\n }\n}\n public record AzureOption\n{\n [MyRecursiveValidation]\n public AzureGraphOption? Graph { get; init; }\n}\n\npublic record AzureGraphOption\n{\n [MyRecursiveValidation]\n public AzureGraphSecretOption? Secret { get; init; }\n}\n\npublic record AzureGraphSecretOption\n{\n [Required] public string TenantId { get; init; }\n [Required] public string ClientId { get; init; }\n [Required] public string ClientSecret { get; init; }\n}\n"
},
{
"answer_id": 74519120,
"author": "Steve Fan",
"author_id": 3289081,
"author_profile": "https://Stackoverflow.com/users/3289081",
"pm_score": 0,
"selected": false,
"text": "using System.ComponentModel.DataAnnotations;\nusing System.Collections.Immutable;\n\npublic class ValidateObjectAttribute : ValidationAttribute\n{\n protected override ValidationResult IsValid(object? value, ValidationContext validationContext)\n {\n if (value == null)\n {\n var nullable = validationContext.ObjectType\n .GetMember(validationContext.MemberName!)\n .FirstOrDefault()?.CustomAttributes.Any(x => x.AttributeType.Name == \"NullableAttribute\") ?? false;\n return nullable ? ValidationResult.Success! : new ValidationResult($\"{validationContext.DisplayName} is null\");\n }\n\n var results = new List<ValidationResult>();\n Validator.TryValidateObject(value, new ValidationContext(value, null, null), results, true);\n\n if (results.Count > 0)\n {\n var compositeResults = new CompositeValidationResult($@\"Validation for \"\"{validationContext.DisplayName}\"\" failed!\");\n results.ForEach(compositeResults.AddResult);\n return compositeResults;\n }\n\n return ValidationResult.Success!;\n\n }\n}\n\npublic class CompositeValidationResult : ValidationResult\n{\n public IImmutableList<ValidationResult> Results { get; private set; } = ImmutableList<ValidationResult>.Empty;\n\n public CompositeValidationResult(string errorMessage) : base(errorMessage) { }\n public CompositeValidationResult(string errorMessage, IEnumerable<string> memberNames) : base(errorMessage, memberNames) { }\n protected CompositeValidationResult(ValidationResult validationResult) : base(validationResult) { }\n\n public void AddResult(ValidationResult validationResult) => Results = Results.Add(validationResult);\n}\n using System.ComponentModel.DataAnnotations;\n\npublic record GiteaOption\n{\n [Required] public required string BaseUrl { get; init; }\n [ValidateObject]\n public GiteaSecretOption? Secret { get; init; } \n}\n\npublic record GiteaSecretOption\n{ \n [Required] public required string AccessToken { get; init; }\n}\n Secret"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7826511/"
] |
74,516,996
|
<p>I want to set multi type for one field of my schema</p>
<p>like this:</p>
<pre><code>@Schema({ validateBeforeSave: true, _id: false })
class example1 {
a: string;
b: number;
}
@Schema({ validateBeforeSave: true, _id: false })
class example2 {
a: string;
b: number;
}
@Schema({ collection: 'user', validateBeforeSave: true, timestamps: true })
export class User extends Document {
@Prop({ type: example1 | example2 })
firstProp: string;
@Prop({ type: example1[] | example2[] })
secondProp: example1[] | example2[];
}
</code></pre>
<p>I want property with two type and an array with two or more type and i want to that mongoDB validate my schema</p>
|
[
{
"answer_id": 74518495,
"author": "Chernyshev Ivan",
"author_id": 20557670,
"author_profile": "https://Stackoverflow.com/users/20557670",
"pm_score": 1,
"selected": false,
"text": "AzureOption AzureOption MyRecursiveValidationAttribute : ValidationAttribute public class MyRecursiveValidationAttribute : ValidationAttribute\n{\n public override bool IsValid(object? value)\n {\n var isValid = true;\n\n if (value == null)\n { return isValid; }\n\n isValid = Validator.TryValidateObject(value, new ValidationContext(value), null);\n\n return isValid;\n }\n}\n public record AzureOption\n{\n [MyRecursiveValidation]\n public AzureGraphOption? Graph { get; init; }\n}\n\npublic record AzureGraphOption\n{\n [MyRecursiveValidation]\n public AzureGraphSecretOption? Secret { get; init; }\n}\n\npublic record AzureGraphSecretOption\n{\n [Required] public string TenantId { get; init; }\n [Required] public string ClientId { get; init; }\n [Required] public string ClientSecret { get; init; }\n}\n"
},
{
"answer_id": 74519120,
"author": "Steve Fan",
"author_id": 3289081,
"author_profile": "https://Stackoverflow.com/users/3289081",
"pm_score": 0,
"selected": false,
"text": "using System.ComponentModel.DataAnnotations;\nusing System.Collections.Immutable;\n\npublic class ValidateObjectAttribute : ValidationAttribute\n{\n protected override ValidationResult IsValid(object? value, ValidationContext validationContext)\n {\n if (value == null)\n {\n var nullable = validationContext.ObjectType\n .GetMember(validationContext.MemberName!)\n .FirstOrDefault()?.CustomAttributes.Any(x => x.AttributeType.Name == \"NullableAttribute\") ?? false;\n return nullable ? ValidationResult.Success! : new ValidationResult($\"{validationContext.DisplayName} is null\");\n }\n\n var results = new List<ValidationResult>();\n Validator.TryValidateObject(value, new ValidationContext(value, null, null), results, true);\n\n if (results.Count > 0)\n {\n var compositeResults = new CompositeValidationResult($@\"Validation for \"\"{validationContext.DisplayName}\"\" failed!\");\n results.ForEach(compositeResults.AddResult);\n return compositeResults;\n }\n\n return ValidationResult.Success!;\n\n }\n}\n\npublic class CompositeValidationResult : ValidationResult\n{\n public IImmutableList<ValidationResult> Results { get; private set; } = ImmutableList<ValidationResult>.Empty;\n\n public CompositeValidationResult(string errorMessage) : base(errorMessage) { }\n public CompositeValidationResult(string errorMessage, IEnumerable<string> memberNames) : base(errorMessage, memberNames) { }\n protected CompositeValidationResult(ValidationResult validationResult) : base(validationResult) { }\n\n public void AddResult(ValidationResult validationResult) => Results = Results.Add(validationResult);\n}\n using System.ComponentModel.DataAnnotations;\n\npublic record GiteaOption\n{\n [Required] public required string BaseUrl { get; init; }\n [ValidateObject]\n public GiteaSecretOption? Secret { get; init; } \n}\n\npublic record GiteaSecretOption\n{ \n [Required] public required string AccessToken { get; init; }\n}\n Secret"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74516996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17658482/"
] |
74,517,051
|
<p>I want to add eye to password field in flutter project</p>
<p>this is my code:</p>
<pre><code>TextFormField(
decoration: const InputDecoration(
label: Text('PASSWORD'),
),
keyboardType: TextInputType.visiblePassword,
obscureText: true,
validator: (val) {
if (val!.length < 6) {
return "Please enter at least 6 characters";
}
return null;
},
onSaved: (val) => data['password'] = val!,
),
</code></pre>
|
[
{
"answer_id": 74517113,
"author": "Idriss",
"author_id": 3293320,
"author_profile": "https://Stackoverflow.com/users/3293320",
"pm_score": 0,
"selected": false,
"text": "decoration: InputDecoration(\n suffixIcon: IconButton(\n onPressed: showHideText(),\n icon: Icon(Icons.yourIcon),\n ),\n),\n"
},
{
"answer_id": 74517193,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 1,
"selected": false,
"text": "class CustomInput extends StatefulWidget {\n final String? label;\n final TextInputType? keyboardType;\n final String? Function(String?)? validator;\n final Function(String?)? onSaved;\n final bool obscureText;\n const CustomInput(\n {Key? key,\n this.label,\n this.keyboardType,\n this.validator,\n this.onSaved,\n this.obscureText = false})\n : super(key: key);\n\n @override\n State<CustomInput> createState() => _CustomInputState();\n}\n\nclass _CustomInputState extends State<CustomInput> {\n bool showPassword = false;\n @override\n Widget build(BuildContext context) {\n return TextFormField(\n decoration: InputDecoration(\n label: Text(widget.label ?? ''),\n suffixIcon: InkWell(\n onTap: () {\n setState(() {\n showPassword = !showPassword;\n });\n },\n child: Icon(showPassword\n ? Icons.remove_red_eye\n : Icons.remove_red_eye_outlined),\n )),\n keyboardType: widget.keyboardType,\n obscureText: showPassword ? false : widget.obscureText,\n validator: widget.validator,\n onSaved: widget.onSaved,\n );\n }\n}\n CustomInput(\n label: 'PASSWORD',\n keyboardType: TextInputType.visiblePassword,\n onSaved: (val) => data['password'] = val!,\n validator: (val) {\n if (val!.length < 6) {\n return \"Please enter at least 6 characters\";\n }\n return null;\n },\n obscureText: true,\n)\n"
},
{
"answer_id": 74518278,
"author": "Arijeet",
"author_id": 15387120,
"author_profile": "https://Stackoverflow.com/users/15387120",
"pm_score": 0,
"selected": false,
"text": "bool hidePassword=true; TextFormField obscureText TextFormField(\n autovalidateMode: AutovalidateMode.onUserInteraction,\n obscureText: hidePassword,\n decoration: InputDecoration(\n prefixIcon: const Icon(\n Icons.password,\n ),\n suffixIcon: IconButton(\n onPressed: () {\n setState(() {\n hidePassword = !hidePassword;\n });\n },\n icon: (hidePassword == true)\n ? const Icon(Icons.visibility_off)\n : const Icon(\n Icons.visibility,\n ),\n ),\n border: const OutlineInputBorder(\n borderRadius: BorderRadius.all(\n Radius.circular(20),\n ),\n ),\n hintText: 'Enter your password.',\n ),\n validator: validatePassword,\n ),\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17410263/"
] |
74,517,079
|
<p>It's been 3 months I learn ReactJS + TypeScript. My question is about to use react-hook-form (v7) for editing a form. I want to use my custom component that I created and found how to do it by myself !</p>
<p><em>Here is a part of my form provider with react-hook-form</em></p>
<pre><code>import { FormProvider, useForm } from 'react-hook-form';
import { useNavigate, useParams } from 'react-router-dom';
import InputText from 'components/commons/form/InputText';
import { supabase } from 'configs/supabase';
const EditEducation: React.FC = () => {
const { educationId } = useParams();
const [education, setEducation] = useState<education>();
const getEducation = async (educationId: string | undefined) => {
try {
const { data, error } = await supabase
.from('tables1')
.select('data1, data2')
.eq('id', educationId)
.single();
if (error) {
seterror(error.message);
}
if (data) {
return data;
}
} catch (error: any) {
alert(error.message);
}
};
useEffect(() => {
getEducation(educationId).then((data) => {
setEducation(data);
});
// eslint-disable-next-line
}, [educationId]);
const methods = useForm();
const onSubmit = async (formData: any) => {
const updateData = {
data1 = formData.data1,
data2 = formData.data2
};
try {
setSaving(true);
const { error } = await supabase.from('educations').update(updateData);
if (error) {
seterror(error.message);
}
if (!error) {
navigate('/experiences/education');
}
setSaving(false);
} catch (error: any) {
seterror(error.message);
}
};
return (
...
<FormProvider {...methods}>
<form className="p-4" onSubmit={methods.handleSubmit(onSubmit)}>
<InputText
id="data1"
label="Data1"
placeholder="Ex: data1"
defaultValue={education?.data1}
options={{ required: 'This field is required' }}
/>
<Button type="submit">{saving ? 'Saving' : 'Save'}</Button>
</form>
</FormProvider>
...
)
};
</code></pre>
<p><em>Here is my custom component :</em></p>
<pre><code>import React, { useEffect } from 'react';
import { useFormContext } from 'react-hook-form';
interface InputProps {
id: string;
label: string;
placeholder?: string;
defaultValue?: string;
}
const InputText: React.FC<InputProps> = ({
id,
label,
placeholder,
defaultValue,
options,
...rest
}: InputProps) => {
const {
register,
setValue,
formState: { errors }
} = useFormContext();
useEffect(() => {
if (defaultValue) setValue(id, defaultValue, { shouldDirty: true });
}, [defaultValue, setValue, id]);
return (
<div className="">
<label htmlFor={id} className="">
{label}
</label>
<input
type="text"
placeholder={placeholder}
className=""
id={id}
defaultValue={defaultValue}
{...register(id, options)}
{...rest}
/>
{errors[id] && (
<p className="">
<span className="">*</span> {errors[id]?.message}
</p>
)}
</div>
);
};
export default InputText;
</code></pre>
<p>As you can see, I had use a formContext because I want to deconstruct my code into smaller components.</p>
<p>Now I'm having some doubts if I correctly code, specialy when I use ut editing forms : if set my default value via "defaultValue" prop, I have to submit (error show) then clique inside the input to change the state in order to clean the error in the input component.</p>
<p>This is why I have add the useEffect hook to clean the input validation error and it's working. What do you think about this ? Is there a better way to manage it (I think Yup it's a cleaner way to set the validation schema) ?</p>
<p>Thanks in advance and sorry for my rusty English. Great day to all and hope my code will help people.</p>
<p>Use <FormProvider {...methods}> and it's working but I do not know if it's a good way to do it.</p>
<p><strong>Edit</strong> : In reality, I have to double submit to get my data so I guess it's not the correct way, any sugestions ?</p>
<p><strong>Edit2</strong> : I have found a "solution" : if I have a defaultValue in my props, I do in my component :</p>
<pre><code> useEffect(() => {
if (defaultValue) setValue(id, defaultValue, { shouldDirty: true });
}, [defaultValue, setValue, id]);
</code></pre>
<p>I do not think it is the better solution ...</p>
|
[
{
"answer_id": 74517113,
"author": "Idriss",
"author_id": 3293320,
"author_profile": "https://Stackoverflow.com/users/3293320",
"pm_score": 0,
"selected": false,
"text": "decoration: InputDecoration(\n suffixIcon: IconButton(\n onPressed: showHideText(),\n icon: Icon(Icons.yourIcon),\n ),\n),\n"
},
{
"answer_id": 74517193,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 1,
"selected": false,
"text": "class CustomInput extends StatefulWidget {\n final String? label;\n final TextInputType? keyboardType;\n final String? Function(String?)? validator;\n final Function(String?)? onSaved;\n final bool obscureText;\n const CustomInput(\n {Key? key,\n this.label,\n this.keyboardType,\n this.validator,\n this.onSaved,\n this.obscureText = false})\n : super(key: key);\n\n @override\n State<CustomInput> createState() => _CustomInputState();\n}\n\nclass _CustomInputState extends State<CustomInput> {\n bool showPassword = false;\n @override\n Widget build(BuildContext context) {\n return TextFormField(\n decoration: InputDecoration(\n label: Text(widget.label ?? ''),\n suffixIcon: InkWell(\n onTap: () {\n setState(() {\n showPassword = !showPassword;\n });\n },\n child: Icon(showPassword\n ? Icons.remove_red_eye\n : Icons.remove_red_eye_outlined),\n )),\n keyboardType: widget.keyboardType,\n obscureText: showPassword ? false : widget.obscureText,\n validator: widget.validator,\n onSaved: widget.onSaved,\n );\n }\n}\n CustomInput(\n label: 'PASSWORD',\n keyboardType: TextInputType.visiblePassword,\n onSaved: (val) => data['password'] = val!,\n validator: (val) {\n if (val!.length < 6) {\n return \"Please enter at least 6 characters\";\n }\n return null;\n },\n obscureText: true,\n)\n"
},
{
"answer_id": 74518278,
"author": "Arijeet",
"author_id": 15387120,
"author_profile": "https://Stackoverflow.com/users/15387120",
"pm_score": 0,
"selected": false,
"text": "bool hidePassword=true; TextFormField obscureText TextFormField(\n autovalidateMode: AutovalidateMode.onUserInteraction,\n obscureText: hidePassword,\n decoration: InputDecoration(\n prefixIcon: const Icon(\n Icons.password,\n ),\n suffixIcon: IconButton(\n onPressed: () {\n setState(() {\n hidePassword = !hidePassword;\n });\n },\n icon: (hidePassword == true)\n ? const Icon(Icons.visibility_off)\n : const Icon(\n Icons.visibility,\n ),\n ),\n border: const OutlineInputBorder(\n borderRadius: BorderRadius.all(\n Radius.circular(20),\n ),\n ),\n hintText: 'Enter your password.',\n ),\n validator: validatePassword,\n ),\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6858043/"
] |
74,517,094
|
<p>I am building a project based on STM32CubeProgrammer API. The filepath is is done like this and you have to input the filename in the code manually.</p>
<pre><code> /* Download File + verification */
#ifdef _WIN32
const wchar_t* filePath = L"../test file/filename.hex";
#else
const wchar_t* filePath = L"../api/test file/filename.hex";
#endif
</code></pre>
<p>I want the program to show a list of available .hex files, ask for a corresponding number and then append the correct filename to the filePath. The goal is to ask for minimal input from user and keep it as simple as possible.</p>
<p>filePath should remain as const wchar_t*.</p>
<p>I wasn't able to find anything working on Google and I am not even sure how and what to search.</p>
<p>How can this be done?</p>
|
[
{
"answer_id": 74517471,
"author": "sklott",
"author_id": 11680056,
"author_profile": "https://Stackoverflow.com/users/11680056",
"pm_score": 0,
"selected": false,
"text": "const wchar_t* const wchar_t *file_paths[] = {\n \"some path/filename1.hex\",\n \"some path/filename2.hex\",\n...\n};\n\nconst wchar_t* select_path() {\n for (const wchar_t *path : file_paths) {\n const wchar_t* filename = get_file_name_from_path(path);\n out_file_name(filename);\n }\n return file_paths[input_number()];\n}\n"
},
{
"answer_id": 74517595,
"author": "RTL",
"author_id": 20357707,
"author_profile": "https://Stackoverflow.com/users/20357707",
"pm_score": 1,
"selected": false,
"text": " std::wstring projects[] = { L\"data.hex\", L\"blinky.hex\" };\n int projectNr = 0;\n\n std::wstring file = L\"../test file/\" + projects[projectNr];\n\n\n#ifdef _WIN32\n const wchar_t* filePath = file.c_str();\n#else\n const wchar_t* filePath = L\"../api/test file/\";\n#endif\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20357707/"
] |
74,517,120
|
<p>The function <code>int IsOnMinLevel(Heap H, int i)</code>, returns if the node of index <code>i</code> is on a <code>min level (even level)</code>, in <code>constant time</code></p>
<p>functions provided:</p>
<pre class="lang-c prettyprint-override"><code>typedef struct heap
{
int *array;
int count;
int capacity;
} *Heap;
Heap CreateHeap(int capacity)
{
Heap h=(Heap) malloc(sizeof(struct heap));
h->count=0;
h->capacity=capacity;
h->array=(int *)malloc(sizeof(int)*h->capacity);
if(! h->array) return NULL;
return h;
}
int Parent(Heap h, int i)
{
if(i<=0 || i>=h->count)
return -1;
return ((i-1)/2);
}
int LeftChild(Heap h, int i)
{
int left = 2*i+1;
if(left>=h->count) return -1;
return left;
}
int RightChild(Heap h, int i)
{
int right = 2*i+2;
if(right>=h->count)
return -1;
return right;
}
void ResizeHeap(Heap *h)
{
int i;
int *array_old = (*h)->array;
(*h)->array=(int *)malloc(sizeof(int)*(*h)->capacity*2);
for(i=0; i<(*h)->capacity; i++)
(*h)->array[i]=array_old[i];
(*h)->capacity *=2;
free(array_old);
}
</code></pre>
<p>How do I get <code>level</code> from <code>index</code>? And is there a relation between <code>level</code> and <code>index</code> in a <code>complete binary tree</code>?</p>
|
[
{
"answer_id": 74517663,
"author": "Dancchi",
"author_id": 18064255,
"author_profile": "https://Stackoverflow.com/users/18064255",
"pm_score": 0,
"selected": false,
"text": "i floor(log2(i+1)) + 1 int IsOnMinLevel(Heap H, int i)\n{\n return ((int)(floor(log2(i+1))) % 2) == 0; //cast to int since log2 gives double\n}\n"
},
{
"answer_id": 74517799,
"author": "Nelfeal",
"author_id": 3854570,
"author_profile": "https://Stackoverflow.com/users/3854570",
"pm_score": 1,
"selected": false,
"text": "index: 0 1 2 3 4 5 6 7 8 ...\nlevel: 0 1 1 2 2 2 2 3 3 ...\n 2^k-1 2^k-1 2^(k+1)-1 k i k 2^k-1 <= i < 2^(k+1)-1 2^k <= i+1 < 2^(k+1) k <= log2(i+1) < k+1 k k+1 floor(log2(i+1)) = k floor(log2(i)) i int uint64_log2(uint64_t n)\n{\n #define S(k) if (n >= (UINT64_C(1) << k)) { i += k; n >>= k; }\n int i = -(n == 0); S(32); S(16); S(8); S(4); S(2); S(1); return i;\n #undef S\n}\n int IsOnMinLevel(Heap H, int i)\n{\n return uint64_log2(i+1) % 2 == 0;\n}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18064255/"
] |
74,517,147
|
<pre><code>`tokenizer = AutoTokenizer.from_pretrained('google/byt5-base')
</code></pre>
<p>OSError: Can't load config for 'google/byt5-base'. Make sure that:</p>
<ul>
<li><p>'google/byt5-base' is a correct model identifier listed on 'https://huggingface.co/models'</p>
</li>
<li><p>or 'google/byt5-base' is the correct path to a directory containing a config.json file</p>
</li>
</ul>
<p>Edit:</p>
<p>Also was getting error below while upgrading transformer</p>
<pre><code>WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('
</code></pre>
<p>I refereed <a href="https://huggingface.co/google/byt5-base" rel="nofollow noreferrer">this</a> article and checked correct path in the model repository as well but no luck</p>
<p>Any help highly appreciated! Thanks.</p>
|
[
{
"answer_id": 74517663,
"author": "Dancchi",
"author_id": 18064255,
"author_profile": "https://Stackoverflow.com/users/18064255",
"pm_score": 0,
"selected": false,
"text": "i floor(log2(i+1)) + 1 int IsOnMinLevel(Heap H, int i)\n{\n return ((int)(floor(log2(i+1))) % 2) == 0; //cast to int since log2 gives double\n}\n"
},
{
"answer_id": 74517799,
"author": "Nelfeal",
"author_id": 3854570,
"author_profile": "https://Stackoverflow.com/users/3854570",
"pm_score": 1,
"selected": false,
"text": "index: 0 1 2 3 4 5 6 7 8 ...\nlevel: 0 1 1 2 2 2 2 3 3 ...\n 2^k-1 2^k-1 2^(k+1)-1 k i k 2^k-1 <= i < 2^(k+1)-1 2^k <= i+1 < 2^(k+1) k <= log2(i+1) < k+1 k k+1 floor(log2(i+1)) = k floor(log2(i)) i int uint64_log2(uint64_t n)\n{\n #define S(k) if (n >= (UINT64_C(1) << k)) { i += k; n >>= k; }\n int i = -(n == 0); S(32); S(16); S(8); S(4); S(2); S(1); return i;\n #undef S\n}\n int IsOnMinLevel(Heap H, int i)\n{\n return uint64_log2(i+1) % 2 == 0;\n}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5800969/"
] |
74,517,161
|
<p>I want to get rid of a module in Python and I use the "pip uninstall " command. However, for some reason the module is still importable! I am using VS code on a Mac OS. Here is the screenshot of the code:</p>
<p><a href="https://i.stack.imgur.com/bw2Ki.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bw2Ki.png" alt="enter image description here" /></a></p>
<p>As you can see, the yellow warning says the polars package is not installed (because I already excuted the uninstall command) however in the cell below it, the polars module has been imported succesfully! Can anyone explain what is happening and how can I completely remove the module so it is not importable anymore?</p>
|
[
{
"answer_id": 74517382,
"author": "Ghazouani Ahmed",
"author_id": 18937595,
"author_profile": "https://Stackoverflow.com/users/18937595",
"pm_score": 0,
"selected": false,
"text": "$ python setup.py install --record files.txt\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12014637/"
] |
74,517,187
|
<p>I am working on a project which have to do image predictions using artifical intelligence,
<a href="https://i.stack.imgur.com/NYnbW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NYnbW.png" alt="enter image description here" /></a></p>
<p>this is the image, you can see that the nodes are attached with each other, and first encoding the image and then hidden layer and then decoding layer.</p>
<p>My question is, the real implementation of autoencoder is very difficult to understand, is it possible to do coding of autoencoder nodes like we normaly do in data structures for creating linklist node BST node etc?</p>
<p>I want the code looks easy to understand.</p>
<p>like....</p>
<pre><code>#include <iostream>
using namespace std;
struct node
{
double data[100][100];
struct node *next;
};
class autoencoder
{
struct node *head;
struct node *temp; // to traverse through the whole list
public:
LinkedList()
{
head = NULL;
}
void insert()
{
node *NewNode = new node;
cout << "Enter data :: ";
cin >> NewNode->data[100][100];
NewNode->next = 0;
if (head == 0)
{
head = temp = NewNode;
}
else
{
temp->next = NewNode;
temp = NewNode; // temp is treversing to newnode
}
}
void activation() // some activation function
void sigmoid fucntion // some sigmoid function
}
int main()
{
autoencoder obj;
obj.insertnode()
obj.activation()
obj.sigmoid()
}
</code></pre>
<p>this is sudo code type.
My wquestion is the real autoencoder implementation include so much libraries and other stuff which is not understandable,
is it possible to implement the nodes of autoEncoder like shown in the image?</p>
<p>I have a lot of search but didn't find any solution.
If it is possible please let me know the guidence.
If not please let me noe so that I will waste my time on searching this.</p>
|
[
{
"answer_id": 74517635,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 1,
"selected": false,
"text": "double data[100][100]"
},
{
"answer_id": 74518047,
"author": "Botje",
"author_id": 1548468,
"author_profile": "https://Stackoverflow.com/users/1548468",
"pm_score": 0,
"selected": false,
"text": "struct Node {\n double value;\n double bias = 0;\n std::vector<std::pair<Node*, float>> connections;\n\n double compute() {\n value = bias;\n for (auto&& [node, weight] : connections) {\n value += node->value * weight;\n }\n\n return value;\n }\n};\n using Layer = std::vector<Node>;\n struct Network {\n std::vector<Layer> layers;\n\n void addFCLayer(int size) {\n Layer newLayer(size);\n if (!layers.empty()) {\n Layer& prevLayer = layers.back();\n for (auto& newNode: newLayer) {\n for (auto& prevNode: prevLayer) {\n newNode.connections.emplace_back(&prevNode, rand());\n }\n }\n }\n layers.push_back(std::move(newLayer));\n }\n compute network.layers.back() void forwardProp() {\n for (auto it = ++layers.begin(); it != layers.end(); it++) {\n for (auto& node: *it) {\n node.compute();\n }\n }\n }\n};\n rand()"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16536775/"
] |
74,517,208
|
<p>I have folder hierarchy as:</p>
<pre><code>->Project Folder
-Main.py
->modules Folder
->PowerSupply Folder
- PowerSupply.py
- SerialPort.py
</code></pre>
<p>In <code>Main.py</code> I am importing <code>PowerSupply.py</code> with following command</p>
<p><code>from modules.PowerSupply.PowerSupply import *</code></p>
<p>Then inside of <code>PowerSupply.py</code>, I am importing SerilPort.py with following command</p>
<p><code>from SerialPort import SerialPort</code></p>
<p>So, when I try to run the Main.py, PowerSupply.py throw an error in the line <code>from SerialPort import SerialPort</code>. The error is</p>
<pre><code>"Exception has occurred: ModuleNotFoundError
No module named 'SerialPort'"
</code></pre>
<p>When I modify the <code>PowerSupply.py</code> as<br />
<code>from modules.PowerSupply.SerialPort import SerialPort</code>, it is not throwing error. But it don`t seem like a good way to me. Is there any way to solve this error?</p>
|
[
{
"answer_id": 74517635,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 1,
"selected": false,
"text": "double data[100][100]"
},
{
"answer_id": 74518047,
"author": "Botje",
"author_id": 1548468,
"author_profile": "https://Stackoverflow.com/users/1548468",
"pm_score": 0,
"selected": false,
"text": "struct Node {\n double value;\n double bias = 0;\n std::vector<std::pair<Node*, float>> connections;\n\n double compute() {\n value = bias;\n for (auto&& [node, weight] : connections) {\n value += node->value * weight;\n }\n\n return value;\n }\n};\n using Layer = std::vector<Node>;\n struct Network {\n std::vector<Layer> layers;\n\n void addFCLayer(int size) {\n Layer newLayer(size);\n if (!layers.empty()) {\n Layer& prevLayer = layers.back();\n for (auto& newNode: newLayer) {\n for (auto& prevNode: prevLayer) {\n newNode.connections.emplace_back(&prevNode, rand());\n }\n }\n }\n layers.push_back(std::move(newLayer));\n }\n compute network.layers.back() void forwardProp() {\n for (auto it = ++layers.begin(); it != layers.end(); it++) {\n for (auto& node: *it) {\n node.compute();\n }\n }\n }\n};\n rand()"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11850938/"
] |
74,517,223
|
<p>I have a list of keywords (each in separate cell), for example:</p>
<p>| Keyword A | (cell C1)
| Keyword B | (cell C2)
| Keyword C | (cell C3)</p>
<p>and I have a formula that searches for these keywords across different worksheets and returns the sum of values corresponding to a given keyword:</p>
<pre><code>=SUM(FILTER(INDIRECT("'"& B6 & "'!G1:G600");INDIRECT("'" & B6 & "'!B1:B600")=A6))
</code></pre>
<p>where A6 contains an in-cell dropdown list of these keywords to choose from and B6 contains an in-cell dropdown list of worksheets to work in (let's say for different months).</p>
<p>Example: When 'Keyword A' is found in worksheet 'January' in column B, find the corresponding value to this keyword in column G; then ultimately sum all of these values for a given worksheet and a given keyword.</p>
<p>Depending on what I choose from the in-cell dropdown list, I get the corresponding sum for a given keyword. However, I'd like to get the total sum of all the keyword values added together, but I can`t seem to make it work. Feels like I'd have to use some equivalent of a for loop to iterate through the list and add up the individual sums, but as far as I'm concerned, there's no looping possible in Google Sheets.</p>
<p>I can, obviously, define these sums for each keyword separately and then add these values together, but as I'm working with large datasets with many keywords, this solution is rather unpleasant.</p>
<p>All suggestions are much appreciated!</p>
|
[
{
"answer_id": 74517635,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 1,
"selected": false,
"text": "double data[100][100]"
},
{
"answer_id": 74518047,
"author": "Botje",
"author_id": 1548468,
"author_profile": "https://Stackoverflow.com/users/1548468",
"pm_score": 0,
"selected": false,
"text": "struct Node {\n double value;\n double bias = 0;\n std::vector<std::pair<Node*, float>> connections;\n\n double compute() {\n value = bias;\n for (auto&& [node, weight] : connections) {\n value += node->value * weight;\n }\n\n return value;\n }\n};\n using Layer = std::vector<Node>;\n struct Network {\n std::vector<Layer> layers;\n\n void addFCLayer(int size) {\n Layer newLayer(size);\n if (!layers.empty()) {\n Layer& prevLayer = layers.back();\n for (auto& newNode: newLayer) {\n for (auto& prevNode: prevLayer) {\n newNode.connections.emplace_back(&prevNode, rand());\n }\n }\n }\n layers.push_back(std::move(newLayer));\n }\n compute network.layers.back() void forwardProp() {\n for (auto it = ++layers.begin(); it != layers.end(); it++) {\n for (auto& node: *it) {\n node.compute();\n }\n }\n }\n};\n rand()"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17701542/"
] |
74,517,249
|
<p>I have a question regarding to creating custom input slider the label inside field itself.</p>
<p>The output should be like in following screenshot:</p>
<p><a href="https://i.stack.imgur.com/gE6EJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gE6EJ.png" alt="output" /></a></p>
<p>I have done the input field part, but the label and white color part is missing.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.slider-container .slider {
-webkit-appearance: none;
overflow: hidden;
width: 100%;
height: 50px;
border-radius: 30px;
background: #b5b33c;
outline: none;
opacity: 0.7;
-webkit-transition: 0.2s;
transition: opacity 0.2s;
}
.slider-container .slider:hover {
opacity: 1;
}
.content .slider-container .slider::-webkit-slider-runnable-track {
height: 50px;
-webkit-appearance: none;
color: #13bba4;
}
.slider::-webkit-slider-thumb {
-webkit-appearance: none;
width: 50px;
height: 50px;
border-radius: 50%;
cursor: pointer;
background: #54565a url("https://i.imgur.com/OuvOpHG.png") 50% 50% no-repeat;
}
.slider::-moz-range-thumb {
width: 50px;
height: 50px;
border-radius: 50%;
cursor: pointer;
background: #54565a url("https://i.imgur.com/OuvOpHG.png") 50% 50% no-repeat;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="slider-container">
<input
type="range"
min="1"
max="1000"
value="50"
class="slider"
id="range"
/>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74517576,
"author": "Onur İlyas Tokay",
"author_id": 16571858,
"author_profile": "https://Stackoverflow.com/users/16571858",
"pm_score": -1,
"selected": false,
"text": "<div class=\"slider-container\">\n <input\n type=\"range\"\n min=\"1\"\n max=\"1000\"\n value=\"50\"\n class=\"slider\"\n id=\"range\"\n onchange=\"getRangeValue()\"\n />\n<output id=\"rangeOutput\">50</output>\n</div>\n function getRangeValue() {\ndocument.getElementById(\"rangeOutput\").value = document.getElementById(\"range\").value\n}\n"
},
{
"answer_id": 74518025,
"author": "Kairav Thakar",
"author_id": 20447312,
"author_profile": "https://Stackoverflow.com/users/20447312",
"pm_score": 2,
"selected": true,
"text": "Please check below demo link, where I have perform Javascript and CSS tweaks:\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10489887/"
] |
74,517,267
|
<p>When handling exceptions in FastAPI, is there a way to stop the application after raising an <code>HTTPException</code>?</p>
<p>An example of what I am trying to achieve:</p>
<pre class="lang-py prettyprint-override"><code>@api.route("/")
def index():
try:
do_something()
except Exception as e:
raise HTTPException(status_code=500, detail="Doing something failed!")
sys.exit(1)
if __name__ == "__main__":
uvicorn.run(api)
</code></pre>
<p>Raising the <code>HTTPException</code> alone won't stop my program, and every line of code after the <code>raise</code> won't be executed.</p>
<p>Is there a good way to do something like this, or something similar with the same result?</p>
|
[
{
"answer_id": 74517699,
"author": "kosciej16",
"author_id": 3361462,
"author_profile": "https://Stackoverflow.com/users/3361462",
"pm_score": 0,
"selected": false,
"text": "sys.exit() stop @api.route(\"/\")\ndef stop():\n loop = asyncio.get_event_loop()\n loop.stop()\n"
},
{
"answer_id": 74518128,
"author": "Chris",
"author_id": 17865804,
"author_profile": "https://Stackoverflow.com/users/17865804",
"pm_score": 1,
"selected": false,
"text": "stop stop() async def def shutdown from fastapi import FastAPI, HTTPException, Request\nfrom fastapi.responses import PlainTextResponse\nfrom starlette.exceptions import HTTPException as StarletteHTTPException\nfrom starlette.background import BackgroundTask\nimport asyncio\n\napp = FastAPI()\n\n@app.on_event('shutdown')\ndef shutdown_event():\n print('Shutting down...!')\n \nasync def exit_app():\n loop = asyncio.get_running_loop()\n loop.stop()\n \n@app.exception_handler(StarletteHTTPException)\nasync def http_exception_handler(request, exc):\n task = BackgroundTask(exit_app)\n return PlainTextResponse(str(exc.detail), status_code=exc.status_code, background=task)\n \n@app.get('/{msg}')\ndef main(msg: str):\n if msg == 'hi':\n raise HTTPException(status_code=500, detail='Something went wrong')\n\n return {'msg': msg}\n \nif __name__ == '__main__':\n import uvicorn\n uvicorn.run(app, host='0.0.0.0', port=8000)\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19745277/"
] |
74,517,276
|
<p><a href="https://i.stack.imgur.com/VlT4I.png" rel="nofollow noreferrer">enter image description here</a></p>
<p><a href="https://i.stack.imgur.com/rHEZE.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>Hello, I have encountered a problem. When I use os.listdir, I hope that the effect of picture 1 will appear, but the effect of python is reversed.
I would like to ask how can I get the data and want the effect of picture 1</p>
|
[
{
"answer_id": 74517699,
"author": "kosciej16",
"author_id": 3361462,
"author_profile": "https://Stackoverflow.com/users/3361462",
"pm_score": 0,
"selected": false,
"text": "sys.exit() stop @api.route(\"/\")\ndef stop():\n loop = asyncio.get_event_loop()\n loop.stop()\n"
},
{
"answer_id": 74518128,
"author": "Chris",
"author_id": 17865804,
"author_profile": "https://Stackoverflow.com/users/17865804",
"pm_score": 1,
"selected": false,
"text": "stop stop() async def def shutdown from fastapi import FastAPI, HTTPException, Request\nfrom fastapi.responses import PlainTextResponse\nfrom starlette.exceptions import HTTPException as StarletteHTTPException\nfrom starlette.background import BackgroundTask\nimport asyncio\n\napp = FastAPI()\n\n@app.on_event('shutdown')\ndef shutdown_event():\n print('Shutting down...!')\n \nasync def exit_app():\n loop = asyncio.get_running_loop()\n loop.stop()\n \n@app.exception_handler(StarletteHTTPException)\nasync def http_exception_handler(request, exc):\n task = BackgroundTask(exit_app)\n return PlainTextResponse(str(exc.detail), status_code=exc.status_code, background=task)\n \n@app.get('/{msg}')\ndef main(msg: str):\n if msg == 'hi':\n raise HTTPException(status_code=500, detail='Something went wrong')\n\n return {'msg': msg}\n \nif __name__ == '__main__':\n import uvicorn\n uvicorn.run(app, host='0.0.0.0', port=8000)\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20561573/"
] |
74,517,285
|
<p>I created a new project due to a problem with an existing project.</p>
<p>I'm trying to add a dependency to a new project, but it's different from the gradle I've been doing so far.</p>
<p>I also went to the developer documentation, but it doesn't seem to have been updated for the new gradle yet.</p>
<p>Fortunately the app level gradle seems to be the same.</p>
<hr />
<p><strong>Previous gradle (Project)</strong></p>
<pre><code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = "1.5.21"
def nav_version = "2.4.2"
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.2.2'
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
// safe args
classpath("androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version")
classpath 'com.google.gms:google-services:4.3.10'
// Dagger Hilt
classpath 'com.google.dagger:hilt-android-gradle-plugin:2.41'
}
}
allprojects {
repositories {
google()
mavenCentral()
jcenter() // Warning: this repository is going to shut down soon
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
</code></pre>
<p><strong>Current gradle(project)</strong></p>
<pre><code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
id 'com.android.application' version '7.2.2' apply false
id 'com.android.library' version '7.2.2' apply false
id 'org.jetbrains.kotlin.android' version '1.7.10' apply false
}
task clean(type: Delete) {
delete rootProject.buildDir
}
</code></pre>
|
[
{
"answer_id": 74517699,
"author": "kosciej16",
"author_id": 3361462,
"author_profile": "https://Stackoverflow.com/users/3361462",
"pm_score": 0,
"selected": false,
"text": "sys.exit() stop @api.route(\"/\")\ndef stop():\n loop = asyncio.get_event_loop()\n loop.stop()\n"
},
{
"answer_id": 74518128,
"author": "Chris",
"author_id": 17865804,
"author_profile": "https://Stackoverflow.com/users/17865804",
"pm_score": 1,
"selected": false,
"text": "stop stop() async def def shutdown from fastapi import FastAPI, HTTPException, Request\nfrom fastapi.responses import PlainTextResponse\nfrom starlette.exceptions import HTTPException as StarletteHTTPException\nfrom starlette.background import BackgroundTask\nimport asyncio\n\napp = FastAPI()\n\n@app.on_event('shutdown')\ndef shutdown_event():\n print('Shutting down...!')\n \nasync def exit_app():\n loop = asyncio.get_running_loop()\n loop.stop()\n \n@app.exception_handler(StarletteHTTPException)\nasync def http_exception_handler(request, exc):\n task = BackgroundTask(exit_app)\n return PlainTextResponse(str(exc.detail), status_code=exc.status_code, background=task)\n \n@app.get('/{msg}')\ndef main(msg: str):\n if msg == 'hi':\n raise HTTPException(status_code=500, detail='Something went wrong')\n\n return {'msg': msg}\n \nif __name__ == '__main__':\n import uvicorn\n uvicorn.run(app, host='0.0.0.0', port=8000)\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14415521/"
] |
74,517,319
|
<p>This code block is used to read an excel file and get user data by a given user role. but if the user role does not exist in the excel file, it will return an undefined value. how to de we check that the "user" variable is not undefined or null?</p>
<pre><code> cy.task('getExcelData', Cypress.env('usersFilePath')).then((users) => {
const user = users.find(user => {
return user.userRole === 'userRole';
});
cy.wrap(user).should('not.be.empty');
cy.wrap(user).should('not.be.a',undefined)
cy.wrap(user).should('not.be.a',null)
signIn(user.username, user.password);
});
</code></pre>
<p>cy.wrap(user).should('not.be.empty'); (this part working but not others)</p>
<p>this is the error I got in cypress</p>
<p><a href="https://i.stack.imgur.com/EiqB9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EiqB9.png" alt="enter image description here" /></a></p>
<p>so I want know how do we check if the value is null or undefined using cypress commands</p>
|
[
{
"answer_id": 74521833,
"author": "jjhelguero",
"author_id": 17917809,
"author_profile": "https://Stackoverflow.com/users/17917809",
"pm_score": 1,
"selected": false,
"text": "cy.task('getExcelData', Cypress.env('usersFilePath')).then((users) => {\n const user = users.find(user => {\n if(!user) {\n throw new Error('user is empty, null, or undefined', user)\n }\n\n return user.userRole === 'userRole';\n });\n signIn(user.username, user.password);\n });\n"
},
{
"answer_id": 74524757,
"author": "TesterDick",
"author_id": 18366749,
"author_profile": "https://Stackoverflow.com/users/18366749",
"pm_score": 3,
"selected": true,
"text": "expect(undefined).to.be.an('undefined')\n .a() .an() typeof \"undefined\" cy.wrap(user).should('not.be.a', \"undefined\")\n .a cy.wrap(user).should('not.be', undefined)\n"
},
{
"answer_id": 74525186,
"author": "Blunt",
"author_id": 20473079,
"author_profile": "https://Stackoverflow.com/users/20473079",
"pm_score": 1,
"selected": false,
"text": ".find() .find() undefined cy.task('getExcelData', Cypress.env('usersFilePath')).then((users) => {\n\n /* \n e.g users = [\n { userRole: 'admin', username: '...', password: '...' },\n { userRole: 'userRole', username: '...', password: '...' },\n ]\n */\n\n const user = users.find(user => user.userRole === 'userRole')\n if (!user) {\n throw new Error('user is undefined')\n }\n\n signIn(user.username, user.password);\n})\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13246500/"
] |
74,517,369
|
<p>I have an integration test that requires a small amount of API credits from a third party. The tests are normally <code>.skip</code>ped, but occasionally I wish to run them and spend the credits.</p>
<p>Right now I manually remove the <code>.skip</code>, run:</p>
<pre><code>npx jest -t 'integration tests'
</code></pre>
<p>...then re-add the <code>.skip</code>. However I'm concerned that I'll accidentally commit the removed <code>.skip</code>, and telling colleagues to remove the <code>.skip</code> before they run the tests is a hassle.</p>
<p>Is it possible to override a Jest <code>.skip</code> from the command line? The <a href="https://jestjs.io/docs/cli" rel="nofollow noreferrer">Jest docs</a> don't mention such a thing but there may be some other way.</p>
|
[
{
"answer_id": 74537197,
"author": "jonrsharpe",
"author_id": 3001761,
"author_profile": "https://Stackoverflow.com/users/3001761",
"pm_score": 1,
"selected": false,
"text": "const _it = process.env.RUN_ALL ? it : xit;\n\n_it(\"behaves correctly\", () => { /* ... */ });\n testMatch {\n \"scripts\": {\n \"test\": \"jest --selectProjects some\",\n \"test:all\": \"jest\",\n \"test:other\": \"jest --selectProjects other\"\n }\n}\n"
},
{
"answer_id": 74642043,
"author": "mikemaccana",
"author_id": 123671,
"author_profile": "https://Stackoverflow.com/users/123671",
"pm_score": -1,
"selected": true,
"text": "_it xit it const testOrSkip = process.env.RUN_SKIPPED_TESTS ? test : test.skip;\n\ntestOrSkip(\"behaves correctly\", () => {\n expect(true).toBeTruthy();\n});\n $ npx jest src/backend/runme.test.ts\n\nTest Suites: 1 skipped, 0 of 1 total\nTests: 1 skipped, 1 total\nSnapshots: 0 total\nTime: 3.566 s\nRan all test suites matching /src\\/backend\\/runme.test.ts/i.\n\n$ export RUN_SKIPPED_TESTS='true'\n\n$ npx jest src/backend/runme.test.ts\n\n PASS src/backend/runme.test.ts\n ✓ behaves correctly (3 ms)\n\nTest Suites: 1 passed, 1 total\nTests: 1 passed, 1 total\nSnapshots: 0 total\nTime: 1.951 s\nRan all test suites matching /src\\/backend\\/runme.test.ts/i.\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123671/"
] |
74,517,402
|
<p>I'm new in redux, I'm using react native hooks and redux. my problem is that after opening the articleScreen.js page then clicking the back button and opening the articleScreen.js page again, the data is rendered again so that there is the same data and display the same data repeatedly when clicked on the articleScreen.js page. is there something wrong with my code below?.</p>
<p>=> ArticleScreen.js</p>
<pre><code> const ArticleScreen = () => {
const dispatch = useDispatch();
const data = useSelector((state) => state.articleReducer.data);
const isLoading = useSelector((state) => state.articleReducer.isLoading);
const [loadingMore, setLoadingMore] = useState(false);
const [page, setPage] = useState(1);
const currentPage = useSelector((state) => state.articleReducer.currentPage);
const totalPage = useSelector((state) => state.articleReducer.totalPage);
const nextPage = useSelector((state) => state.articleReducer.nextPage);
useEffect(() => {
dispatch(fetchingArticle({ page: 1 }));
}, [])
const _renderItem = ({ item, index }) => {
return (
<TouchableOpacity
key={`${item.id} ${page}`}
style={{ marginBottom: 16 }}
>
<View style={{ flexDirection: 'row' }}>
<View style={{ flex: 1 }}>
<Text>{item.title}</Text>
</View>
</View>
</TouchableOpacity>
);
};
const handleLoadMoreData = () => {
if (!isLoading) {
setLoadingMore(true)
if (nextPage <= totalPage) {
dispatch(fetchingArticle(nextPage));
} else {
setLoadingMore(false)
}
}
}
return (
<>
<View>
<FlatList
data={data}
renderItem={_renderItem}
keyExtractor={item => `${item.id}`}
onEndReached={handleLoadMoreData}
onEndReachedThreshold={0.01}
ListFooterComponent={
loadingMore && (
<View
style={{
marginVertical: 30,
}}>
<ActivityIndicator
size="large"
color={Colors.onSurface}
/>
</View>
)
}
/>
</View>
</>
);
};
export default ArticleScreen;
</code></pre>
<p>=> store.js</p>
<pre><code>const middleware = applyMiddleware(thunk);
// Root Reducer
const rootReducer = combineReducers({
articleReducer: ArticleReducer,
});
// Redux Store
const store = createStore(
rootReducer,
middleware
)
export default store;
</code></pre>
<p>=> ArticleAction.js</p>
<pre><code>export const fetchArticleRequest = () => ({
type: 'FETCH_ARTICLE_REQUEST',
});
export const fetchArticleSuccess = (data) => ({
type: 'FETCH_ARTICLE_SUCCESS',
payload: data.data
});
export const fetchArticleFailure = (error) => ({
type: 'FETCH_ARTICLE_FAILURE',
payload: error
});
export const fetchingArticle = (page) => {
return async dispatch => {
dispatch(fetchArticleRequest());
return apiRequest.get(URL.articles + '?page=' + page).then((response) => {
dispatch(fetchArticleSuccess(response.data));
})
.catch((error) => {
dispatch(fetchArticleFailure("Request Data Error"))
})
}
}
</code></pre>
<p>=> ArticleReducer.js</p>
<pre><code> const initialState = {
data: [],
error: '',
isLoading: false,
refreshing: false,
currentPage: 1,
totalPage: 1,
nextPage: 0,
totalData: 0
};
const ArticleReducer = (state = initialState, action) => {
switch (action.type) {
case 'FETCH_ARTICLE_REQUEST':
return {
...state,
isLoading: true,
refreshing: true,
};
case 'FETCH_ARTICLE_SUCCESS':
return {
...state,
data: state.data.concat(action.payload.data),
isLoading: false,
refreshing: false,
currentPage: action.payload.current_page,
totalPage: action.payload.last_page,
nextPage: action.payload.current_page + 1,
};
case 'FETCH_ARTICLE_FAILURE':
return {
...state,
error: action.error,
isLoading: false,
refreshing: false,
};
default:
return state;
}
};
export { ArticleReducer };
</code></pre>
|
[
{
"answer_id": 74537197,
"author": "jonrsharpe",
"author_id": 3001761,
"author_profile": "https://Stackoverflow.com/users/3001761",
"pm_score": 1,
"selected": false,
"text": "const _it = process.env.RUN_ALL ? it : xit;\n\n_it(\"behaves correctly\", () => { /* ... */ });\n testMatch {\n \"scripts\": {\n \"test\": \"jest --selectProjects some\",\n \"test:all\": \"jest\",\n \"test:other\": \"jest --selectProjects other\"\n }\n}\n"
},
{
"answer_id": 74642043,
"author": "mikemaccana",
"author_id": 123671,
"author_profile": "https://Stackoverflow.com/users/123671",
"pm_score": -1,
"selected": true,
"text": "_it xit it const testOrSkip = process.env.RUN_SKIPPED_TESTS ? test : test.skip;\n\ntestOrSkip(\"behaves correctly\", () => {\n expect(true).toBeTruthy();\n});\n $ npx jest src/backend/runme.test.ts\n\nTest Suites: 1 skipped, 0 of 1 total\nTests: 1 skipped, 1 total\nSnapshots: 0 total\nTime: 3.566 s\nRan all test suites matching /src\\/backend\\/runme.test.ts/i.\n\n$ export RUN_SKIPPED_TESTS='true'\n\n$ npx jest src/backend/runme.test.ts\n\n PASS src/backend/runme.test.ts\n ✓ behaves correctly (3 ms)\n\nTest Suites: 1 passed, 1 total\nTests: 1 passed, 1 total\nSnapshots: 0 total\nTime: 1.951 s\nRan all test suites matching /src\\/backend\\/runme.test.ts/i.\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7546078/"
] |
74,517,426
|
<p>I am trying to perform. simple get on influxdb using python. The connection works great and I am able to query several values. However, I have one of them which is reported as <code>homeassistant.autogen.°C</code>. When I try to query it, I always get</p>
<pre><code>influxdb.exceptions.InfluxDBClientError: 400: {"error":"error parsing query: found \u00b0, expected identifier at line 1, char 43"}
</code></pre>
<p>The code that is use is:</p>
<pre><code>client = InfluxDBClient(host='192.168.1.x', port=8086, username='user', password='password')
results = client.query(r'SELECT "value" FROM homeassistant.autogen."°C" WHERE entity_id = sensor.x_temperature')
</code></pre>
<p>I already tried to escape and pass it through quotes but nothing seems to work.</p>
<p>I cannot change how the value is inserted in influxdb.</p>
|
[
{
"answer_id": 74537197,
"author": "jonrsharpe",
"author_id": 3001761,
"author_profile": "https://Stackoverflow.com/users/3001761",
"pm_score": 1,
"selected": false,
"text": "const _it = process.env.RUN_ALL ? it : xit;\n\n_it(\"behaves correctly\", () => { /* ... */ });\n testMatch {\n \"scripts\": {\n \"test\": \"jest --selectProjects some\",\n \"test:all\": \"jest\",\n \"test:other\": \"jest --selectProjects other\"\n }\n}\n"
},
{
"answer_id": 74642043,
"author": "mikemaccana",
"author_id": 123671,
"author_profile": "https://Stackoverflow.com/users/123671",
"pm_score": -1,
"selected": true,
"text": "_it xit it const testOrSkip = process.env.RUN_SKIPPED_TESTS ? test : test.skip;\n\ntestOrSkip(\"behaves correctly\", () => {\n expect(true).toBeTruthy();\n});\n $ npx jest src/backend/runme.test.ts\n\nTest Suites: 1 skipped, 0 of 1 total\nTests: 1 skipped, 1 total\nSnapshots: 0 total\nTime: 3.566 s\nRan all test suites matching /src\\/backend\\/runme.test.ts/i.\n\n$ export RUN_SKIPPED_TESTS='true'\n\n$ npx jest src/backend/runme.test.ts\n\n PASS src/backend/runme.test.ts\n ✓ behaves correctly (3 ms)\n\nTest Suites: 1 passed, 1 total\nTests: 1 passed, 1 total\nSnapshots: 0 total\nTime: 1.951 s\nRan all test suites matching /src\\/backend\\/runme.test.ts/i.\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/295525/"
] |
74,517,438
|
<p>My program is supposed to read data forever from provider classes stored in <code>PROVIDERS</code>, defined in the config. Every second, it should check whether the config has changed and if so, stop all tasks, reload the config and and create new tasks.</p>
<p>The below code raises <code>CancelledError</code> because I'm cancelling my tasks. Should I really try/catch each of those to achieve my goals or is there a better pattern?</p>
<pre class="lang-py prettyprint-override"><code>async def main(config_file):
load_config(config_file)
tasks = []
config_task = asyncio.create_task(watch_config(config_file)) # checks every 1s if config changed and raises ConfigChangedSignal if so
tasks.append(config_task)
for asset_name, provider in PROVIDERS.items():
task = asyncio.create_task(provider.read_forever())
tasks.append(task)
try:
await asyncio.gather(*tasks, return_exceptions=False)
except ConfigChangedSignal:
# Restarting
for task in asyncio.tasks.all_tasks():
task.cancel() # raises CancelledError
await main(config_file)
try:
asyncio.run(main(config_file))
except KeyboardInterrupt:
logger.debug("Ctrl-C pressed. Aborting")
</code></pre>
|
[
{
"answer_id": 74521232,
"author": "jsbueno",
"author_id": 108205,
"author_profile": "https://Stackoverflow.com/users/108205",
"pm_score": 3,
"selected": true,
"text": "asyncio.TaskGroup asyncio.gather asyncio.run(main(False)) asyncio.run(main(True)) import asyncio\n\nasync def doit(i, n, cancel=False):\n await asyncio.sleep(n)\n if cancel:\n raise RuntimeError()\n print(i, \"done\")\n\nasync def main(cancel):\n try:\n async with asyncio.TaskGroup() as group:\n tasks = [group.create_task(doit(i, 2)) for i in range(10)]\n group.create_task(doit(42, 1, cancel=cancel))\n group.create_task(doit(11, .5))\n except Exception:\n pass\n await asyncio.sleep(3)\n\n main import asyncio\n...\n\n\nasync def main(config_file):\n while True:\n load_config(config_file)\n try:\n async with asyncio.TaskGroup() as tasks:\n tasks.create_task(watch_config(config_file)) # checks every 1s if config changed and raises ConfigChangedSignal if so\n\n for asset_name, provider in PROVIDERS.items():\n tasks.create_task.create_task(provider.read_forever())\n\n # all tasks are awaited at the end of the with block\n except *ConfigChangedSignal: # <- the new syntax in Python 3.11\n # Restarting is just a matter of re-doing the while-loop\n # ... log.info(\"config changed\")\n pass\n\n # any other exception won't be caught and will error, allowing one\n # to review what went wrong\n \n...\n\n\n \n\nasync def main(config_file):\n while True:\n await inner_main(config_file)\n\nasync def inner_main(config_file):\n load_config(config_file)\n\n # keep the existing body\n ...\n except ConfigChangedSignal:\n # Restarting\n for task in asyncio.tasks.all_tasks():\n task.cancel() # raises CancelledError\n # await main call dropped from here\n\n\n"
},
{
"answer_id": 74540583,
"author": "fancidev",
"author_id": 1465038,
"author_profile": "https://Stackoverflow.com/users/1465038",
"pm_score": 0,
"selected": false,
"text": "async def main(config_file):\n load_config(config_file)\n\n tasks = []\n for asset_name, provider in PROVIDERS.items():\n task = asyncio.create_task(provider.read_forever())\n tasks.append(task)\n\n try:\n await watch_config(config_file)\n except ConfigChangedSignal:\n pass\n\ntry:\n while True:\n asyncio.run(main(config_file))\nexcept KeyboardInterrupt:\n logger.debug(\"Ctrl-C pressed. Aborting\")\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1961574/"
] |
74,517,443
|
<p>I'm relativley new to python
I have a excel file where i can read,Column A "url" and Column B "name".</p>
<p>In the future the columns will have no "column name" so i need it to read from Column A directly and column B and start iterating from cell 1.</p>
<p>I tried using index_col(0) but can't really seem to get the hang of it.
This is a simple download image script.</p>
<pre><code>import requests
import pandas as pd
df = pd.read_excel(r'C:\Users\exdata1.xlsx')
for index, row in df.iterrows():
url = row['url']
file_name = url.split('/')
r = requests.get(url)
file_name=(row['name']+".jpeg")
if r.status_code == 200:
with open(file_name, "wb") as f:
f.write(r.content)
print (file_name)
</code></pre>
<p>I tried this below without any good result.</p>
<pre><code>url = row['index_col(0)'] #0 for excel column "A"
file_name=(row['index_col(1)']+".jpeg") #1 for excel Column "B"
</code></pre>
<p>Apreciate any support!</p>
|
[
{
"answer_id": 74517626,
"author": "abokey",
"author_id": 16120011,
"author_profile": "https://Stackoverflow.com/users/16120011",
"pm_score": 3,
"selected": true,
"text": "header=None pandas.read_excel import requests\nimport pandas as pd\n \ndf = pd.read_excel(r'C:\\Users\\exdata1.xlsx', header=None, names=['url', 'name'])\n\nfor index, row in df.iterrows():\n url = row['url']\n file_name = url.split('/')\n r = requests.get(url) \n file_name=(row['name']+'.jpeg') \n\n if r.status_code == 200:\n with open(file_name, 'wb') as f:\n f.write(r.content)\n print(file_name)\n"
},
{
"answer_id": 74517691,
"author": "Maen",
"author_id": 11104626,
"author_profile": "https://Stackoverflow.com/users/11104626",
"pm_score": 0,
"selected": false,
"text": "Unnamed: 0 df.info df.head() df.rename( columns={\"Unnamed: 0\" :'url', Unnamed: 0: 'name'}, inplace=True )\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17835613/"
] |
74,517,456
|
<p>I have a table with three Columns:
Column A: name of Item,
Column B: Lowest value of series,
Column C: the Highest value of series.
<a href="https://i.stack.imgur.com/TqlMY.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>What I want to achieve is:</p>
<ol>
<li>Generate series of item sequence from lowest number to highest number per row</li>
</ol>
<p>So Apple 7 9 will yield: "Apple_7", "Apple_8", "Apple_9"</p>
<ol start="2">
<li><p>Concatenate/Join such sequence per row into Column D
So</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">Item</th>
<th style="text-align: center;">From</th>
<th style="text-align: center;">Until</th>
<th style="text-align: left;">Result</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">Apple</td>
<td style="text-align: center;">7</td>
<td style="text-align: center;">9</td>
<td style="text-align: left;">"Apple_7, Apple_8, Apple_9"</td>
</tr>
<tr>
<td style="text-align: left;">Berry</td>
<td style="text-align: center;">3</td>
<td style="text-align: center;">8</td>
<td style="text-align: left;">"Berry_3, Berry_4, Berry_5, Berry_6, Berry_7, Berry_8"</td>
</tr>
</tbody>
</table>
</div></li>
<li><p>Doing it all using one Arrayformula, so that new row added can be automatically calculated.</p>
</li>
</ol>
<p>Here is example sheet: <a href="https://docs.google.com/spreadsheets/d/1R5raKmmt5-aOIorAZGHjv_-fdySKWjCMB_FRQwm1vag/edit#gid=0" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/1R5raKmmt5-aOIorAZGHjv_-fdySKWjCMB_FRQwm1vag/edit#gid=0</a></p>
<p>I tried in Column D:</p>
<pre><code>arrayformula(textjoin(", ",true,arrayformula(A3:A&"_"&sequence(1,C3:C-B3:B+1,B3:B,1))))
</code></pre>
<p>Apparently, the sequence function only take value from Column B and join it in first row.</p>
<p>Any help will be appreciated.</p>
|
[
{
"answer_id": 74517626,
"author": "abokey",
"author_id": 16120011,
"author_profile": "https://Stackoverflow.com/users/16120011",
"pm_score": 3,
"selected": true,
"text": "header=None pandas.read_excel import requests\nimport pandas as pd\n \ndf = pd.read_excel(r'C:\\Users\\exdata1.xlsx', header=None, names=['url', 'name'])\n\nfor index, row in df.iterrows():\n url = row['url']\n file_name = url.split('/')\n r = requests.get(url) \n file_name=(row['name']+'.jpeg') \n\n if r.status_code == 200:\n with open(file_name, 'wb') as f:\n f.write(r.content)\n print(file_name)\n"
},
{
"answer_id": 74517691,
"author": "Maen",
"author_id": 11104626,
"author_profile": "https://Stackoverflow.com/users/11104626",
"pm_score": 0,
"selected": false,
"text": "Unnamed: 0 df.info df.head() df.rename( columns={\"Unnamed: 0\" :'url', Unnamed: 0: 'name'}, inplace=True )\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19524055/"
] |
74,517,519
|
<p>I am currently looking into memory allocation in C. The code below should read characters from standard input one by one and write them to string s. First I allocate memory for s using malloc. Initial size: CHUNK_SIZE. The counter variable counts the number of letters entered. After it becomes larger than the current size l of string s, the code should reallocate string s with the new size l + CHUNK_SIZE.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#define CHUNK_SIZE 10
int main(void)
{
int l = CHUNK_SIZE;
// s - is the string where to write letters from stdin
char *s = (char *)malloc(l * sizeof(char));
char *p = s;
// counter for counting entered letters
int counter = 0;
while ((*p++ = getchar()) != '\n') {
counter++;
// reallocate memory if amount of entered letters more than size of s
if (counter > l - 1) {
l += CHUNK_SIZE;
s = (char *)realloc(s, l * sizeof(char));
}
}
*p = '\0';
printf("%s", s);
return 0;
}
</code></pre>
<p>The problem is that it seems that the memory space is being successfully reallocated. But the program does not write the letter to the string after the second reallocation. With CHUNK_SIZE set to 10, only 20 letters are stored.
Entered: <code>This is a string and I like it</code>
Saved to string: <code>This is a string and</code></p>
|
[
{
"answer_id": 74517626,
"author": "abokey",
"author_id": 16120011,
"author_profile": "https://Stackoverflow.com/users/16120011",
"pm_score": 3,
"selected": true,
"text": "header=None pandas.read_excel import requests\nimport pandas as pd\n \ndf = pd.read_excel(r'C:\\Users\\exdata1.xlsx', header=None, names=['url', 'name'])\n\nfor index, row in df.iterrows():\n url = row['url']\n file_name = url.split('/')\n r = requests.get(url) \n file_name=(row['name']+'.jpeg') \n\n if r.status_code == 200:\n with open(file_name, 'wb') as f:\n f.write(r.content)\n print(file_name)\n"
},
{
"answer_id": 74517691,
"author": "Maen",
"author_id": 11104626,
"author_profile": "https://Stackoverflow.com/users/11104626",
"pm_score": 0,
"selected": false,
"text": "Unnamed: 0 df.info df.head() df.rename( columns={\"Unnamed: 0\" :'url', Unnamed: 0: 'name'}, inplace=True )\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6799861/"
] |
74,517,554
|
<p>I'm having an issue with my widget running its <code>FutureBuilder</code> code multiple times with an already resolved <code>Future</code>. Unlike the other questions on SO about this, my <code>build()</code> method isn't being called multiple times.</p>
<p>My future is being called outside of <code>build()</code> in <code>initState()</code> - it's also wrapped in an <code>AsyncMemoizer</code>.</p>
<p>Relevant code:</p>
<pre><code>class _HomeScreenState extends State<HomeScreen> {
late final Future myFuture;
final AsyncMemoizer _memoizer = AsyncMemoizer();
@override
void initState() {
super.initState();
/// provider package
final homeService = context.read<HomeService>();
myFuture = _memoizer.runOnce(homeService.getMyData);
}
@override
Widget build(BuildContext context) {
print("[HOME] BUILDING OUR HOME SCREEN");
return FutureBuilder(
future: myFuture,
builder: ((context, snapshot) {
print("[HOME] BUILDER CALLED WITH SNAPSHOT: $snapshot - connection state: ${snapshot.connectionState}");
</code></pre>
<p>When I run the code, and trigger the bug (a soft keyboard being shown manages to trigger it 50% of the time, but not all the time), my logs are:</p>
<pre><code>I/flutter (29283): [HOME] BUILDING OUR HOME SCREEN
I/flutter (29283): [HOME] BUILDER CALLED WITH SNAPSHOT: AsyncSnapshot<dynamic>(ConnectionState.waiting, null, null, null) - connection state: ConnectionState.waiting
I/flutter (29283): [HOME] BUILDER CALLED WITH SNAPSHOT: AsyncSnapshot<dynamic>(ConnectionState.done, Instance of 'HomeData', null, null) - connection state: ConnectionState.done
...
/// bug triggered
...
I/flutter (29283): [HOME] BUILDER CALLED WITH SNAPSHOT: AsyncSnapshot<dynamic>(ConnectionState.done, Instance of 'HomeData', null, null) - connection state: ConnectionState.done
</code></pre>
<p>The initial call with <code>ConnectionState.waiting</code> is normal, then we get the first build with <code>ConnectionState.done</code>.</p>
<p>After the bug is triggered, I end up with another <code>FutureBuilder</code> resolve <em>without</em> the <code>build()</code> method being called.</p>
<p>Am I missing something here?</p>
<p><strong>Edit with full example</strong></p>
<p>This shows the bug in question - if you click in and out of the TextField, the <code>FutureBuilder</code> is called again.</p>
<p>It seems related to how the keyboard is hidden. If I use the <code>FocusScopeNode</code> method, it will rebuild, whereas if I use <code>FocusManager</code>, it won't, so I'm not sure if this is a bug or not.</p>
<pre class="lang-dart prettyprint-override"><code>import 'package:flutter/material.dart';
void main() async {
runApp(const TestApp());
}
class TestApp extends StatelessWidget {
const TestApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Testapp',
home: Scaffold(
body: TestAppHomeScreen(),
),
);
}
}
class TestAppHomeScreen extends StatefulWidget {
const TestAppHomeScreen({super.key});
@override
State<TestAppHomeScreen> createState() => _TestAppHomeScreenState();
}
class _TestAppHomeScreenState extends State<TestAppHomeScreen> {
late final Future myFuture;
@override
void initState() {
super.initState();
myFuture = Future.delayed(const Duration(milliseconds: 500), () => true);
print("[HOME] HOME SCREEN INIT STATE CALLED: $hashCode");
}
@override
Widget build(BuildContext context) {
print("[HOME] HOME SCREEN BUILD CALLED: $hashCode");
return FutureBuilder(
future: myFuture,
builder: (context, snapshot) {
print("[HOME] HOME SCREEN FUTURE BUILDER CALLED WITH STATE ${snapshot.connectionState}: $hashCode");
if (snapshot.connectionState == ConnectionState.waiting) {
return const Scaffold(
body: Center(
child: CircularProgressIndicator(),
),
);
}
return GestureDetector(
onTapUp: (details) {
// hide the keyboard if it's showing
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus) {
currentFocus.unfocus();
}
// FocusManager.instance.primaryFocus?.unfocus();
},
child: const Scaffold(
body: Center(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 32.0),
child: TextField(),
),
),
),
);
},
);
}
}
</code></pre>
|
[
{
"answer_id": 74558136,
"author": "Abdullatif Eida",
"author_id": 20570798,
"author_profile": "https://Stackoverflow.com/users/20570798",
"pm_score": 0,
"selected": false,
"text": "/// provider package super.initState(); @override\n void initState() {\n /// provider package\n final homeService = context.read<HomeService>();\n myFuture = _memoizer.runOnce(homeService.getMyData);\n super.initState();\n }\n"
},
{
"answer_id": 74560900,
"author": "Sayyid J",
"author_id": 15366030,
"author_profile": "https://Stackoverflow.com/users/15366030",
"pm_score": 0,
"selected": false,
"text": "context FocusScope.of build() build() Widget build(BuildContext context) {\n print(\"[HOME] HOME SCREEN BUILD CALLED: $hashCode\");\n return FutureBuilder(\n future: myFuture,\n builder: (context, snapshot) {\n print(\"[HOME] HOME SCREEN FUTURE BUILDER CALLED WITH STATE ${snapshot.connectionState}: $hashCode\");\n if (snapshot.connectionState == ConnectionState.waiting) {\n return const Scaffold(\n body: Center(\n child: CircularProgressIndicator(),\n ),\n );\n }\n //make StatefulBuilder as parent will prevent it\n return StatefulBuilder(\n builder: (context, setState) {\n return GestureDetector(\n onTapUp: (details) {\n // hide the keyboard if it's showing\n FocusScopeNode currentFocus = FocusScope.of(context);\n if (!currentFocus.hasPrimaryFocus) {\n currentFocus.unfocus();\n }\n // FocusManager.instance.primaryFocus?.unfocus();\n },\n child: const Scaffold(\n body: Center(\n child: Padding(\n padding: EdgeInsets.symmetric(horizontal: 32.0),\n child: TextField(),\n ),\n ),\n ),\n );\n }\n );\n },\n );\n }\n FutureBuilder return LayoutBuilder(\n builder: (context, box) {\n print('Rebuild');\n return FutureBuilder(\n future: myFuture,\n builder: (context, snapshot) {\n print(\"[HOME] HOME SCREEN FUTURE BUILDER CALLED WITH STATE ${snapshot.connectionState}: $hashCode\");\n if (snapshot.connectionState == ConnectionState.waiting) {\n return const Scaffold(\n body: Center(\n child: CircularProgressIndicator(),\n ),\n );\n }\n\n return GestureDetector(\n onTapUp: (details) {\n // hide the keyboard if it's showing\n FocusScopeNode currentFocus = FocusScope.of(context);\n if (!currentFocus.hasPrimaryFocus) {\n currentFocus.unfocus();\n }\n // FocusManager.instance.primaryFocus?.unfocus();\n },\n child: const Scaffold(\n body: Center(\n child: Padding(\n padding: EdgeInsets.symmetric(horizontal: 32.0),\n child: TextField(),\n ),\n ),\n ),\n );\n\n\n },\n );\n }\n );\n build() FutureBuilder"
},
{
"answer_id": 74566571,
"author": "venir",
"author_id": 15831316,
"author_profile": "https://Stackoverflow.com/users/15831316",
"pm_score": 2,
"selected": true,
"text": "print builder FutureBuilder FocusScopeNode currentFocus = FocusScope.of(context);\n .of .of dependOnInheritedWidgetOfExactType Widget Widget InheritedWidget .of build Widget FutureBuilder builder FocusScope.of FocusScope GestureDetector builder InheritedWidget .of context.getElementForInheritedWidgetOfExactType<T>();\n T _FocusMarker extends InheritedWidget FocusNode FutureBuilder builder: (context, snapshot) {\n print(\"[HOME] HOME SCREEN FUTURE BUILDER CALLED WITH STATE ${snapshot.connectionState}: $hashCode\");\n // ...\n return Something();\n}\n Something StatelessWidget Something builder InheritedWidget InheritedWidget didChangeDependencies"
},
{
"answer_id": 74566636,
"author": "CopsOnRoad",
"author_id": 6618622,
"author_profile": "https://Stackoverflow.com/users/6618622",
"pm_score": 1,
"selected": false,
"text": "BuildContext context Widget.build() FocusScope.of(context).unfocus();\n build() builder() context Widget.build() Builder.builder() // Example-1\n@override\nWidget build(BuildContext context) {\n print(\"Widget.build()\");\n\n return Builder(builder: (context2) {\n print('Builder.builder()');\n return GestureDetector(\n onTap: () => FocusScope.of(context).unfocus(), // <-- Using `context`\n child: Scaffold(\n body: Center(\n child: TextField(),\n ),\n ),\n );\n });\n}\n context2 Builder.builder() FocusScope.of(context2).unfocus();\n builder() context2 Builder.builder() // Example-2\n@override\nWidget build(BuildContext context) {\n print(\"Widget.build()\");\n\n return Builder(builder: (context2) {\n print('Builder.builder()');\n return GestureDetector(\n onTap: () => FocusScope.of(context2).unfocus(), // <-- Using `context2`\n child: Scaffold(\n body: Center(\n child: TextField(),\n ),\n ),\n );\n });\n}\n builder: (context, snapshot) { ...}\n builder: (_, snapshot) { }\n build()"
},
{
"answer_id": 74570948,
"author": "Quyen Anh Nguyen",
"author_id": 4399085,
"author_profile": "https://Stackoverflow.com/users/4399085",
"pm_score": 1,
"selected": false,
"text": "context return Builder(builder: (_context) {\n return GestureDetector(\n onTapUp: () {\n // hide the keyboard if it's showing\n final currentFocus = FocusScope.of(_context);\n if (!currentFocus.hasPrimaryFocus) {\n currentFocus.unfocus();\n },\n } ...\n FocusManager.instance.primaryFocus?.unfocus();"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/639441/"
] |
74,517,565
|
<p>I have string like below:</p>
<pre><code>[(.1, apple), (.2, orange), (.3, banana), (.4, jack), (.5, grape), (.6, mango)]
</code></pre>
<p>i need to convert above string to object in python like below:</p>
<p><code>[('.1', 'apple'), ('.2', 'orange'), ('.3', 'banana'), ('.4', 'jack'), ('.5', 'grape'), ('.6', 'mango')]</code></p>
<p>is there any efficient way of converting this either by using regex or any other ways?</p>
<p>Thanks in advance</p>
|
[
{
"answer_id": 74517772,
"author": "Lucas M. Uriarte",
"author_id": 14543462,
"author_profile": "https://Stackoverflow.com/users/14543462",
"pm_score": 3,
"selected": true,
"text": "import re\n\nstring = \"\"\"[(.1, apple), (.2, orange), (.3, banana), (.4, jack), (.5, grape), (.6, mango)]\"\"\"\nvalues = [tuple(ele.split(',')) for ele in re.findall(\".\\d, \\w+\", string)]\n print(values)\n>>> [('.1', ' apple'), ('.2', ' orange'), ('.3', ' banana'), ('.4', ' jack'), ('.5', ' grape'), ('.6', ' mango')]\n"
},
{
"answer_id": 74517934,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 0,
"selected": false,
"text": "ast.literal_eval import ast\nimport re\n\ninp = \"[(.1, apple), (.2, orange), (.3, banana), (.4, jack), (.5, grape), (.6, mango)]\"\ninp = re.sub(r'([A-Za-z]+)', r\"'\\1'\", inp)\nobject = ast.literal_eval(inp)\nprint(object)\n [(0.1, 'apple'), (0.2, 'orange'), (0.3, 'banana'), (0.4, 'jack'), (0.5, 'grape'), (0.6, 'mango')]\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8772160/"
] |
74,517,584
|
<p>I am using Google Cloud run for my applications.
I am storing all my secrets in Google Cloud Secret Manager.</p>
<p>To read secrets I do the following:</p>
<pre><code>from google.cloud import secretmanager
import hashlib
def access_secret_version(secret_id, version_id="latest"):
# Create the Secret Manager client.
client = secretmanager.SecretManagerServiceClient()
# Build the resource name of the secret version.
PROJECT_ID = "xxxxx"
name = f"projects/{PROJECT_ID}/secrets/{secret_id}/versions/{version_id}"
# Access the secret version.
response = client.access_secret_version(name=name)
# Return the decoded payload.
return response.payload.data.decode('UTF-8')
def secret_hash(secret_value):
# return the sha224 hash of the secret value
return hashlib.sha224(bytes(secret_value, "utf-8")).hexdigest()
</code></pre>
<p>To write secrets:</p>
<pre><code>from google.cloud import secretmanager
def create_secret(secret_id):
# Create the Secret Manager client.
client = secretmanager.SecretManagerServiceClient()
# Build the resource name of the parent project.
PROJECT_ID = "xxxx"
parent = f"projects/{PROJECT_ID}"
# Build a dict of settings for the secret
secret = {'replication': {'automatic': {}}}
# Create the secret
response = client.create_secret(secret_id=secret_id, parent=parent, secret=secret)
# Print the new secret name.
print(f'Created secret: {response.name}')
</code></pre>
<p>How can I create secrets with tags in Python?</p>
|
[
{
"answer_id": 74517772,
"author": "Lucas M. Uriarte",
"author_id": 14543462,
"author_profile": "https://Stackoverflow.com/users/14543462",
"pm_score": 3,
"selected": true,
"text": "import re\n\nstring = \"\"\"[(.1, apple), (.2, orange), (.3, banana), (.4, jack), (.5, grape), (.6, mango)]\"\"\"\nvalues = [tuple(ele.split(',')) for ele in re.findall(\".\\d, \\w+\", string)]\n print(values)\n>>> [('.1', ' apple'), ('.2', ' orange'), ('.3', ' banana'), ('.4', ' jack'), ('.5', ' grape'), ('.6', ' mango')]\n"
},
{
"answer_id": 74517934,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 0,
"selected": false,
"text": "ast.literal_eval import ast\nimport re\n\ninp = \"[(.1, apple), (.2, orange), (.3, banana), (.4, jack), (.5, grape), (.6, mango)]\"\ninp = re.sub(r'([A-Za-z]+)', r\"'\\1'\", inp)\nobject = ast.literal_eval(inp)\nprint(object)\n [(0.1, 'apple'), (0.2, 'orange'), (0.3, 'banana'), (0.4, 'jack'), (0.5, 'grape'), (0.6, 'mango')]\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9827719/"
] |
74,517,628
|
<p>Suppose I have the following string:
<code>const test = "This is outside the HTML tag. <title>How to remove an HTML element using JavaScript ?</title>";</code></p>
<p>I'd like to remove the content within all HTML tags in that string. I have tried doing <code>test.replace(/(<([^>]+)>)/gi, '')</code>, but this only removes the HTML tags rather than all the content within it as well. I would expect the outcome to only be 'This is outside the HTML tag.'.</p>
<p>Is it possible to remove HTML tags <strong>and</strong> its contents within a string?</p>
|
[
{
"answer_id": 74517772,
"author": "Lucas M. Uriarte",
"author_id": 14543462,
"author_profile": "https://Stackoverflow.com/users/14543462",
"pm_score": 3,
"selected": true,
"text": "import re\n\nstring = \"\"\"[(.1, apple), (.2, orange), (.3, banana), (.4, jack), (.5, grape), (.6, mango)]\"\"\"\nvalues = [tuple(ele.split(',')) for ele in re.findall(\".\\d, \\w+\", string)]\n print(values)\n>>> [('.1', ' apple'), ('.2', ' orange'), ('.3', ' banana'), ('.4', ' jack'), ('.5', ' grape'), ('.6', ' mango')]\n"
},
{
"answer_id": 74517934,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 0,
"selected": false,
"text": "ast.literal_eval import ast\nimport re\n\ninp = \"[(.1, apple), (.2, orange), (.3, banana), (.4, jack), (.5, grape), (.6, mango)]\"\ninp = re.sub(r'([A-Za-z]+)', r\"'\\1'\", inp)\nobject = ast.literal_eval(inp)\nprint(object)\n [(0.1, 'apple'), (0.2, 'orange'), (0.3, 'banana'), (0.4, 'jack'), (0.5, 'grape'), (0.6, 'mango')]\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3480297/"
] |
74,517,631
|
<p>There is a function that takes the following argument :</p>
<pre><code>int send_message(const char *topic)
</code></pre>
<p>I have a struct :</p>
<pre><code>typedef struct mqtt_topic {
char topic[200];
} mqtt_topic_t;
</code></pre>
<p>and a value that is of the type : <code>mqtt_topic_t *mqtt_topic</code></p>
<p>I am trying to pass <code>mqtt_topic->topic</code> as an argument to the function but it throws an error. How do I convert this data to useful format that I can then use as an argument in my function?</p>
<p>Here is the code snippet :</p>
<pre><code>int mqtt_publish(char message[])
{
int msg_id = 0;
ESP_LOGI(TAG, "MQTT_EVENT_CONNECTED");
mqtt_topic_t *mqtt_topic = get_mqtt_topic();
msg_id = esp_mqtt_client_publish(client,&mqtt_topic->topic, message, 0, 1, 0);
ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);
return msg_id;
}
</code></pre>
<p>Function Prototype :</p>
<pre><code>int esp_mqtt_client_publish(esp_mqtt_client_handle_t client, const char *topic, const char *data, int len, int qos, int retain);
</code></pre>
|
[
{
"answer_id": 74517772,
"author": "Lucas M. Uriarte",
"author_id": 14543462,
"author_profile": "https://Stackoverflow.com/users/14543462",
"pm_score": 3,
"selected": true,
"text": "import re\n\nstring = \"\"\"[(.1, apple), (.2, orange), (.3, banana), (.4, jack), (.5, grape), (.6, mango)]\"\"\"\nvalues = [tuple(ele.split(',')) for ele in re.findall(\".\\d, \\w+\", string)]\n print(values)\n>>> [('.1', ' apple'), ('.2', ' orange'), ('.3', ' banana'), ('.4', ' jack'), ('.5', ' grape'), ('.6', ' mango')]\n"
},
{
"answer_id": 74517934,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 0,
"selected": false,
"text": "ast.literal_eval import ast\nimport re\n\ninp = \"[(.1, apple), (.2, orange), (.3, banana), (.4, jack), (.5, grape), (.6, mango)]\"\ninp = re.sub(r'([A-Za-z]+)', r\"'\\1'\", inp)\nobject = ast.literal_eval(inp)\nprint(object)\n [(0.1, 'apple'), (0.2, 'orange'), (0.3, 'banana'), (0.4, 'jack'), (0.5, 'grape'), (0.6, 'mango')]\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19622689/"
] |
74,517,638
|
<p><strong>Using python AI mnist to recognize my picture, trained accuracy is 97.99%, but accuracy to my img is less than 20%</strong></p>
<p>I'm hoping can use MNIST doing 0~9 number recognition, and trainning accuracy rate reach up to 97% , I thought it will be fine to reconize my pic</p>
<p>but predict/recognize my 2 picture as number 7<br />
predict/recognize my 3 picture as number 6<br />
predict/recognize my 5 picture as number 2</p>
<p>here is the share pic link : <a href="https://imgur.com/a/yDJ8ujc" rel="nofollow noreferrer">https://imgur.com/a/yDJ8ujc</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import keras
from keras.datasets import mnist
import matplotlib.pyplot as plt
import PIL
from PIL import Image
(train_images,train_labels),(test_images,test_labels) = mnist.load_data()
train_images.shape
len(train_labels)
train_labels
test_images.shape
len(test_labels)
test_labels
from keras import models
from keras import layers
network = models.Sequential()
network.add(layers.Dense(512,activation='relu',input_shape=(28*28,)))
network.add(layers.Dense(10,activation='softmax'))
network.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])
train_images = train_images.reshape((60000,28*28))
train_images = train_images.astype('float32')/255
test_images = test_images.reshape((10000,28*28))
test_images = test_images.astype('float32')/255
from keras.utils import to_categorical
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
network.fit(train_images,train_labels,epochs= 3 ,batch_size=128)
test_loss , test_acc = network.evaluate(test_images,test_labels)
print('test_acc:',test_acc)
network.save('m_lenet.h5')
#########
import numpy as np
from keras.models import load_model
import matplotlib.pyplot as plt
from PIL import Image
model = load_model('/content/m_lenet.h5')
picPath = '/content/02_a.png'
img = Image.open(picPath)
reIm = img.resize((28,28),Image.ANTIALIAS)
plt.imshow(reIm)
plt.savefig('/content/result.png')
im1 = np.array(reIm.convert("L"))
im1 = im1.reshape((1,28*28))
im1 = im1.astype('float32')/255
# predict = model.predict_classes(im1)
predict_x=model.predict(im1)
classes_x=np.argmax(predict_x,axis=1)
print ("---------------------------------")
print ('predict as:')
print (predict_x)
print ("")
print ("")
print ('predict number as:')
print (classes_x)
print ("---------------------------------")
print ("Original img : ")</code></pre>
</div>
</div>
</p>
<p>what should I do for this?</p>
<ul>
<li>should I also import my img with ans for AI to trainning?</li>
<li>add more layers?</li>
</ul>
<p>that all the idea I came up, if there is more, just let me know? If that the only two idea to slove, also tell me how to implement <em>(ex:import my img with ans for AI to trainning)</em></p>
<hr />
<p><strong>tried code suggested by expert:</strong></p>
<blockquote>
<p>use data augmentation in dataset in Keras with ImageDataGenerator</p>
</blockquote>
<pre><code>import keras
from keras.datasets import mnist
import matplotlib.pyplot as plt
import PIL
from PIL import Image
(train_images,train_labels),(test_images,test_labels) = mnist.load_data()
train_images.shape
len(train_labels)
train_labels
test_images.shape
len(test_labels)
test_labels
from keras import models
from keras import layers
network = models.Sequential()
network.add(layers.Dense(512,activation='relu',input_shape=(28*28,)))
network.add(layers.Dense(10,activation='softmax'))
network.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])
train_images = train_images.reshape((60000,28*28))
train_images = train_images.astype('float32')/255
test_images = test_images.reshape((10000,28*28))
test_images = test_images.astype('float32')/255
from keras.utils import to_categorical
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
network.fit(train_images,train_labels,epochs= 3 ,batch_size=128)
# Here is image data augmentation example:
from tensorflow.keras.preprocessing.image import ImageDataGenerator
data_generator = ImageDataGenerator(rotation_range=10,
width_shift_range=8,
height_shift_range=8,
brightness_range=[0.6,1.1],
zoom_range=.15,
validation_split=.2,
rescale=1./255)
train_dataset = data_generator.flow(train_images, train_labels, batch_size=32, subset='training')
validation_dataset = data_generator.flow(train_images, train_labels, batch_size=32, subset='validation')
# Now it's time to train model with augmented dataset
network.fit(train_dataset, validation_data=validation_dataset, epochs=30)
test_loss , test_acc = network.evaluate(test_images,test_labels)
print('test_acc:',test_acc)
network.save('m_lenet.h5')
#########
import numpy as np
from keras.models import load_model
import matplotlib.pyplot as plt
from PIL import Image
model = load_model('/content/m_lenet.h5')
picPath = '/content/02_a.png'
img = Image.open(picPath)
reIm = img.resize((28,28),Image.ANTIALIAS)
plt.imshow(reIm)
plt.savefig('/content/result.png')
im1 = np.array(reIm.convert("L"))
im1 = im1.reshape((1,28*28))
im1 = im1.astype('float32')/255
# predict = model.predict_classes(im1)
predict_x=model.predict(im1)
classes_x=np.argmax(predict_x,axis=1)
print ("---------------------------------")
print ('predict as:')
print (predict_x)
print ("")
print ("")
print ('predict number as:')
print (classes_x)
print ("---------------------------------")
print ("Original img : ")
</code></pre>
<p>output:</p>
<pre><code>Epoch 1/3
469/469 [==============================] - 10s 15ms/step - loss: 0.2555 - accuracy: 0.9268
Epoch 2/3
469/469 [==============================] - 5s 10ms/step - loss: 0.1023 - accuracy: 0.9695
Epoch 3/3
469/469 [==============================] - 5s 10ms/step - loss: 0.0678 - accuracy: 0.9796
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-11-476f532516e9> in <module>
51 rescale=1./255)
52
---> 53 train_dataset = data_generator.flow(train_images, train_labels, batch_size=32, subset='training')
54 validation_dataset = data_generator.flow(train_images, train_labels, batch_size=32, subset='validation')
55
1 frames
/usr/local/lib/python3.7/dist-packages/keras/preprocessing/image.py in __init__(self, x, y, image_data_generator, batch_size, shuffle, sample_weight, seed, data_format, save_to_dir, save_prefix, save_format, subset, ignore_class_split, dtype)
675 'Input data in `NumpyArrayIterator` '
676 'should have rank 4. You passed an array '
--> 677 'with shape', self.x.shape)
678 channels_axis = 3 if data_format == 'channels_last' else 1
679 if self.x.shape[channels_axis] not in {1, 3, 4}:
ValueError: ('Input data in `NumpyArrayIterator` should have rank 4. You passed an array with shape', (48000, 784))
</code></pre>
|
[
{
"answer_id": 74518906,
"author": "Ali",
"author_id": 6189090,
"author_profile": "https://Stackoverflow.com/users/6189090",
"pm_score": 2,
"selected": false,
"text": "data augmentation ImageDataGenerator # Here is image data augmentation example:\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\ndata_generator = ImageDataGenerator(rotation_range=10,\n width_shift_range=8,\n height_shift_range=8,\n brightness_range=[0.6,1.1],\n zoom_range=.15,\n validation_split=.2,\n rescale=1./255)\n\ntrain_dataset = data_generator.flow(train_images, train_labels, batch_size=32, subset='training')\nvalidation_dataset = data_generator.flow(train_images, train_labels, batch_size=32, subset='validation')\n\n\n# Now it's time to train model with augmented dataset\nnetwork.fit(train_dataset, validation_data=validation_dataset, epochs=10)\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20396381/"
] |
74,517,666
|
<p>Hello guys I got the following code in my app.js:</p>
<pre><code>function App() {
const [theme, setTheme] = useState('light');
const toggleTheme = () => {
if (theme === 'light') {
setTheme('dark');
} else {
setTheme('light');
}
};
useEffect(() => {
document.body.className = theme;
}, [theme]);
return (
<div className={`App ${theme}`}>
<button onClick={toggleTheme}>Toggle Theme</button>
</code></pre>
<p>And the Following Css in my Form:</p>
<pre><code>.form-container {
width: 600px;
height: 750px;
background-color: rgb(54, 118, 139);
border-radius: 8px;
box-shadow: 0 0 15px 1px rgba(0, 0, 0, 0.4);
display: flex;
flex-direction: column;
}
</code></pre>
<p>So How can I change the background-color of my Form When Dark is toggled and When Light is toggled? Im using react coding</p>
|
[
{
"answer_id": 74517739,
"author": "tstrmn",
"author_id": 15605135,
"author_profile": "https://Stackoverflow.com/users/15605135",
"pm_score": 0,
"selected": false,
"text": "className ...\n <form className={theme === \"light\" ? \"form-container light\" : \"form-container dark\"}>\n...\n .form-container {\n width: 600px;\n height: 750px;\n border-radius: 8px;\n box-shadow: 0 0 15px 1px rgba(0, 0, 0, 0.4);\n display: flex;\n flex-direction: column;\n}\n\n.form-container.light {\n background-color: rgb(54, 118, 139);\n}\n\n.form-container.dark {\n background-color: black;\n}\n"
},
{
"answer_id": 74517854,
"author": "Marc Simon",
"author_id": 19699404,
"author_profile": "https://Stackoverflow.com/users/19699404",
"pm_score": 2,
"selected": true,
"text": "light dark .light {\n --form-bg: #4d4d4d;\n}\n.dark {\n --form-bg: #e1e1e1;\n}\n\n.form-container {\n width: 600px;\n height: 750px;\n background-color: var(--form-bg);\n border-radius: 8px;\n box-shadow: 0 0 15px 1px rgba(0, 0, 0, 0.4);\n display: flex;\n flex-direction: column;\n}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20109764/"
] |
74,517,667
|
<p>I have an issue with push notifications not being received on an iOS device in my Flutter app.</p>
<p>I tried to follow this guide: <a href="https://firebase.flutter.dev/docs/messaging/apple-integration/" rel="nofollow noreferrer">https://firebase.flutter.dev/docs/messaging/apple-integration/</a></p>
<p>Steps I have made to configure my push notifications:</p>
<ol>
<li>Register my APN from developer.apple.com on Firebase Console (Cloud Messaging -> my app)</li>
<li>Used the GoogleServices-Info.plist from firebase</li>
<li>Built the app and uploaded to TestFlight</li>
<li>Asked the user for permission to show notifications on iOS</li>
<li>Copied the fcm token from my app and pasted it into Firebase Console -> Cloud Messaging -> new campaign</li>
<li>Push has not been received by my physical iPhone that has the app installed from TestFlight.</li>
</ol>
<p>I also have made sure I have XCode configured properly and:</p>
<ol>
<li>I have selected Push Notifications and Background Modes (Background fetch, Remote notifications)
<a href="https://i.stack.imgur.com/JFw7K.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JFw7K.png" alt="enter image description here" /></a></li>
<li>I am using the proper bundle identifier (lol)</li>
<li>My App ID has Push Notifications selected
<a href="https://i.stack.imgur.com/vGOyT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vGOyT.png" alt="enter image description here" /></a></li>
<li>My APN key has the Push Notifications Service selected
<a href="https://i.stack.imgur.com/CrfUl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CrfUl.png" alt="enter image description here" /></a></li>
</ol>
<p>Any idea on what I am doing wrong? Anyone experienced a similar issue?</p>
<p>EDIT:
This is my <code>AppDelegate.swift</code> file, maybe it's somewhat helpful in resolving my issue (worth mentioning - I didn't touch it, it's generated by flutter I guess):</p>
<pre class="lang-swift prettyprint-override"><code>import UIKit
import Flutter
import FirebaseMessaging
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
super.application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)
}
}
</code></pre>
<p>Also have received such an email from Apple when submitted a build to Test Flight:
<a href="https://i.stack.imgur.com/ngnje.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ngnje.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74589487,
"author": "mrcendre",
"author_id": 1710188,
"author_profile": "https://Stackoverflow.com/users/1710188",
"pm_score": 2,
"selected": false,
"text": "aps-environment .entitlements development production ~/Library/MobileDevice/Provisioning\\ Profiles aps-environment aps-environment Payload/AppName.app/embedded.mobileprovision"
},
{
"answer_id": 74595817,
"author": "Quyen Anh Nguyen",
"author_id": 4399085,
"author_profile": "https://Stackoverflow.com/users/4399085",
"pm_score": 0,
"selected": false,
"text": "import Firebase FirebaseApp.configure() application await Firebase.initializeApp(); WidgetsFlutterBinding.ensureInitialized(); xcrun simctl push simulator-device-id app-bundle-id notification.apns { \"aps\": { \"alert\": \"APNs demo\", \"sound\": \"default\", \"badge\": 69 } }"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13206091/"
] |
74,517,671
|
<p>I have to write this code where The function must receive a path to a text file which must contain text composed of only English letters and punctuation symbols and a destination file for encrypted data. Punctuation symbols must be left as they are without any modification and the encrypted text must be written to a different file.
Also, I have to validate the inputs.</p>
<p>I've done most of it but in the first part, where I have to ask for a text, the code isn't accepting spaces or punctuation marks, and as I gather it's because of <code>.isalpha</code>, however I couldn't find a way to fix it.</p>
<p>I'm not sure if I have completed the aforementioned requirements, so any type of feedback / constructive criticism is appreciated.</p>
<pre><code> while True: # Validating input text
string = input("Enter the text to be encrypted: ")
if not string.isalpha():
print("Please enter a valid text")
continue
else:
break
while True: # Validating input key
key = input("Enter the key: ")
try:
key = int(key)
except ValueError:
print("Please enter a valid key: ")
continue
break
def caesarcipher(string, key): # Caesar Cipher
encrypted_string = []
new_key = key % 26
for letter in string:
encrypted_string.append(getnewletter(letter, new_key))
return ''.join(encrypted_string)
def getnewletter(letter, key):
new_letter = ord(letter) + key
return chr(new_letter) if new_letter <= 122 else chr(96 + new_letter % 122)
with open('Caesar.txt', 'a') as the_file: # Writing to a text file
the_file.write(caesarcipher(string, key))
print(caesarcipher(string, key))
print('Your text has been encrypted via Caesar-Cipher, the result is in Caesar.txt')
</code></pre>
|
[
{
"answer_id": 74517922,
"author": "JohnyCapo",
"author_id": 19335841,
"author_profile": "https://Stackoverflow.com/users/19335841",
"pm_score": 1,
"selected": true,
"text": "# ____help_function____\ndef check_alpha(m_string):\n list_wanted = ['!', '?', '.', ',']\n\n for letter in m_string:\n if not (letter in list_wanted or letter.isalpha()):\n return False\n\n return True\n\n# ____in your code____\nwhile True:\n string = input(\"Enter the text to be encrypted: \")\n\n if check_aplha(string):\n break\n else:\n print('....')\n"
},
{
"answer_id": 74517926,
"author": "Oghli",
"author_id": 5169186,
"author_profile": "https://Stackoverflow.com/users/5169186",
"pm_score": 1,
"selected": false,
"text": "import string\n\ndef check_valid_input(str):\n for c in str:\n if not c.isalpha() and (c not in string.punctuation):\n return False\n return True and any(c.isalpha() for c in str)\n \n\nwhile True: # Validating input text\n string = input(\"Enter the text to be encrypted: \")\n # checking if contain only alphabet characters and punctuations\n if not check_valid_input(string): \n print(\"Please enter a valid text\")\n continue\n else:\n break\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20111366/"
] |
74,517,696
|
<p>I have a simple problem with my json file.</p>
<p>That json file can describe like this:</p>
<pre><code>{
"motto": "<span class="text-success">IF</span> YOU FAIL, TRY AGAIN"
}
</code></pre>
<p>How to put <code>"</code> inside <code>motto</code> property ? Thanks for advice</p>
|
[
{
"answer_id": 74517922,
"author": "JohnyCapo",
"author_id": 19335841,
"author_profile": "https://Stackoverflow.com/users/19335841",
"pm_score": 1,
"selected": true,
"text": "# ____help_function____\ndef check_alpha(m_string):\n list_wanted = ['!', '?', '.', ',']\n\n for letter in m_string:\n if not (letter in list_wanted or letter.isalpha()):\n return False\n\n return True\n\n# ____in your code____\nwhile True:\n string = input(\"Enter the text to be encrypted: \")\n\n if check_aplha(string):\n break\n else:\n print('....')\n"
},
{
"answer_id": 74517926,
"author": "Oghli",
"author_id": 5169186,
"author_profile": "https://Stackoverflow.com/users/5169186",
"pm_score": 1,
"selected": false,
"text": "import string\n\ndef check_valid_input(str):\n for c in str:\n if not c.isalpha() and (c not in string.punctuation):\n return False\n return True and any(c.isalpha() for c in str)\n \n\nwhile True: # Validating input text\n string = input(\"Enter the text to be encrypted: \")\n # checking if contain only alphabet characters and punctuations\n if not check_valid_input(string): \n print(\"Please enter a valid text\")\n continue\n else:\n break\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12715723/"
] |
74,517,716
|
<p>I have an <code>orders</code> table that has a primary key <code>id</code> column, an <code>order_id</code> column, and a <code>created_date</code> column:</p>
<pre><code>===================================
ORDERS
===================================
id | order_id | created_date
-----------------------------------
1 | 178 | 2022-11-16 09:25:11
2 | 182 | 2022-11-18 08:44:19
3 | 178 | 2022-11-17 11:16:22
4 | 178 | 2022-11-18 14:55:41
5 | 195 | 2022-11-15 09:11:17
6 | 195 | 2022-11-16 21:22:32
7 | 146 | 2022-11-16 16:55:09
8 | 178 | 2022-11-16 04:39:16
9 | 121 | 2022-11-16 01:20:19
</code></pre>
<p>I want to write a query that returns the highest <code>created_date</code> for a specific <code>order_id</code>, so I'm trying to use <code>MAX()</code>. But I would also like to return the <code>id</code> of that highest <code>created_date</code> row. In the example above, let's say that I would like to return the row that fits this criteria for order ID 178:</p>
<pre><code>SELECT MAX(o.created_date),
o.id
FROM orders o
WHERE o.order_id = 178
GROUP BY o.id;
</code></pre>
<p>The problem is that when I write the query like this, I get multiple rows returned. I've tried removing the <code>GROUP BY</code> altogether but aside from that, I cannot wrap my head around what I would need to do to this query to show the following information:</p>
<p><code>4 | 2022-11-18 14:55:41</code></p>
<p>How can I write a PostgreSQL query to show the row with the highest <code>created_date</code> value but also show other information for that row?</p>
|
[
{
"answer_id": 74517858,
"author": "VvdL",
"author_id": 15589010,
"author_profile": "https://Stackoverflow.com/users/15589010",
"pm_score": 1,
"selected": false,
"text": "order_id ROW_NUMBER() ORDER BY WITH ranked_order_ids_by_date AS (\n SELECT \n *, \n ROW_NUMBER() over (PARTITION BY order_id ORDER BY created_date DESC) AS date_rank\n FROM USERS\n)\nSELECT *\nFROM ranked_order_ids_by_date\nWHERE order_id = 178\n AND date_rank = 1\n"
},
{
"answer_id": 74517939,
"author": "Jonas Metzler",
"author_id": 18794826,
"author_profile": "https://Stackoverflow.com/users/18794826",
"pm_score": 1,
"selected": false,
"text": "LIMIT SELECT id, order_id, created_date\nFROM orders\nWHERE order_id = 178\nORDER BY created_date DESC\nLIMIT 1;\n FETCH FIRST 1 ROW WITH TIES SELECT id, order_id, created_date\nFROM orders\nWHERE order_id = 178\nORDER BY created_date DESC\nFETCH FIRST 1 ROW WITH TIES;\n DENSE_RANK WITH o AS\n(\n SELECT orders.*, DENSE_RANK() \n OVER (PARTITION BY order_id ORDER BY created_date DESC) AS sub\n FROM orders\n WHERE order_id = 178\n)\nSELECT id, order_id, created_date\n FROM o\n WHERE sub = 1\n"
},
{
"answer_id": 74517979,
"author": "Jonathan Willcock",
"author_id": 7990032,
"author_profile": "https://Stackoverflow.com/users/7990032",
"pm_score": 3,
"selected": true,
"text": "distinct on order by desc max select distinct on (order_id) id, order_id, created_date\nfrom orders\norder by order_id, created_date desc \n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2664815/"
] |
74,517,720
|
<p>I'm kinda new to reactjs and I got a situation where I will have to change a state and then I will need to access the new state value in the same function. Please have a look at the code below,</p>
<pre><code>import { useState } from "react";
import "./styles.css";
export default function App() {
const [state, setState] = useState(true); // default state true
const CallMe = () => {
setState(false); // state change to false
console.log(state); // expecting false but return true
};
return (
<div className="App">
<button onClick={CallMe}>CallMe</button>
</div>
);
}
</code></pre>
<p>When I click the button for first time, I get true when I'm expecting false. Is there anyway, I can do it these thing in a same function like above?</p>
|
[
{
"answer_id": 74517745,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 1,
"selected": false,
"text": "state useEffect useEffect(() => {\n console.log(state)\n}, [state])\n"
},
{
"answer_id": 74517764,
"author": "Majid M.",
"author_id": 14986372,
"author_profile": "https://Stackoverflow.com/users/14986372",
"pm_score": 0,
"selected": false,
"text": "console.log(state);\n useEffect import { useState } from \"react\";\nimport \"./styles.css\";\n\nexport default function App() {\n const [state, setState] = useState(true); // default state true\n\n useEffect(() => {\n console.log(state)\n }, [state])\n\n const CallMe = () => {\n setState(false); \n };\n\n return (\n <div className=\"App\">\n <button onClick={CallMe}>CallMe</button>\n </div>\n );\n}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13362682/"
] |
74,517,735
|
<p>I have a spring-boot app (that implements Spring security) related to react app in the front.
When I do rest calls (GET, POST, ..), it works fine without any issues.
However, When I try to call Stripe checkout from my react app, I get this error :</p>
<blockquote>
<p>Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at <a href="https://r.stripe.com/0" rel="nofollow noreferrer">https://r.stripe.com/0</a>. (Reason: CORS request did not succeed). Status code: (null)</p>
</blockquote>
<p>Here's my code</p>
<p><strong>SecurityConfig.java</strong></p>
<pre><code>protected void configure(HttpSecurity http) throws Exception {
String[] staticResources = {
"/api/clients/authentication/**",
"/api/repas/**"
};
http = http.cors().and().csrf().disable();
http = http
.exceptionHandling()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and();
http
.authorizeRequests()
.antMatchers(staticResources).permitAll()
.anyRequest().authenticated();
http.addFilterAfter(jwtFilter, ExceptionTranslationFilter.class);
}
</code></pre>
<p><strong>CorsConfiguration.java</strong></p>
<pre><code>Configuration
public class CorsConfiguration
{
@Bean
public WebMvcConfigurer corsConfigurer()
{
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH","OPTIONS")
.allowedOrigins("https://m.stripe.com/6","https://r.stripe.com/0","http://localhost:3000")
.exposedHeaders("*")
.allowedHeaders("*");
}
};
}
</code></pre>
<p>I tried to put "*" in the allowed origins but it didn't work either.
I tried to create a bean in the security config file to enable cors and deleted the cors configuration file (like below)
but then all the calls, even those to my rest APIs have failed.</p>
<pre><code>@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source =
new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
</code></pre>
<p><strong>Update:</strong>
This code in the front is what causes the issue
ProfilPayment.java</p>
<pre><code>export default function ProfilPayment() {
const [clientSecret, setClientSecret] = useState("");
const headers = {
'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*",
'Access-Control-Allow-Methods': "*",
'Authorization': `Bearer ${localStorage.getItem("token")}`
}
const URL_API_HTTP = "http://localhost:8080/api/clients/authentication/create-payment-intent";
async function handlePayment() {
console.log("if it works, this line should be shown");
try {
const response = await axios.post("http://localhost:8080/api/clients/authentication/create-payment-intent",{headers});
const data = response.data;
console.log(data);
console.log(typeof data);
setClientSecret(data);
}catch(error) {
alert(error.message);}
}
return (
<Card sx={{width: 250 ,height: 670, display: "inline" ,float: "left"}} style={{ border: "none", boxShadow: "none" }}>
<CardContent>
<Typography sx={{fontSize: 20, color: "#ef6800"}} color="text.secondary" gutterBottom >
Mode de paiement
</Typography>
<br/>
<Typography sx={{ fontSize: 12}} variant="body2" >
<br />
<br />
<ProfilButton value="Ajouter une carte" onClick={handlePayment}/>
</Typography>
<Typography>
{clientSecret && (
<Elements options={clientSecret} stripe={stripePromise}>
{ <CheckoutForm /> }
</Elements>
)}
</Typography>
</CardContent>
</Card>
);
</code></pre>
<p>}</p>
|
[
{
"answer_id": 74521858,
"author": "soma",
"author_id": 17427213,
"author_profile": "https://Stackoverflow.com/users/17427213",
"pm_score": 0,
"selected": false,
"text": "r.stripe.com"
},
{
"answer_id": 74572361,
"author": "Hamadi95",
"author_id": 19070542,
"author_profile": "https://Stackoverflow.com/users/19070542",
"pm_score": -1,
"selected": true,
"text": "const appearance = {\n theme: 'stripe',\n};\nconst options = {\n clientSecret,\n appearance,\n };\n{ clientSecret && (\n <Elements options={options} stripe={stripePromise}>\n { <CheckoutForm /> }\n </Elements>\n )\n}\n\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19070542/"
] |
74,517,737
|
<p>This is an easy question, but I am new to Rails. Simply put, I want to use a route from another model (Score) in my Prediction controller. Once a new prediction is made, I want to redirect to the new_score_path but I keep getting an error -</p>
<pre><code> undefined local variable or method `new_scores_path' for #<PredictionsController:
</code></pre>
<p>I guess I need to somehow reference the Score model in the Predictions Controller but I am not sure how to do this. Here is my create method</p>
<pre><code> def create
@prediction = Prediction.new(prediction_params)
respond_to do |format|
if @prediction.save
user = User.find(@current_user.id)
user.lastcase = user.lastcase + 1
user.save
@user = user
@patient = Patient.find(@current_user.lastcase)
format.html { redirect_to url: new_scores_path, notice: 'Prediction WAS successfully created.' }
format.json { render :new, status: :created, location: @prediction }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @prediction.errors, status: :unprocessable_entity }
end
end
end
</code></pre>
<p>Many thanks for reading.</p>
<p>EDIT</p>
<p>I tried</p>
<pre><code> new_score_path
</code></pre>
<p>and it simply routed me to predictions (i.e. in the index.html.erb file). This was in the address
bar</p>
<pre><code> http://localhost:3000/predictions?notice=Prediction+WAS+successfully+created.&url=%2Fscores%2Fnew
</code></pre>
|
[
{
"answer_id": 74518263,
"author": "max",
"author_id": 544825,
"author_profile": "https://Stackoverflow.com/users/544825",
"pm_score": 1,
"selected": false,
"text": "routes.rb resources :scores new_score_path new_singular_path"
},
{
"answer_id": 74518947,
"author": "GhostRider",
"author_id": 2576839,
"author_profile": "https://Stackoverflow.com/users/2576839",
"pm_score": 0,
"selected": false,
"text": " redirect_to \"/scores/new\"\n"
},
{
"answer_id": 74554172,
"author": "markets",
"author_id": 3033649,
"author_profile": "https://Stackoverflow.com/users/3033649",
"pm_score": 0,
"selected": false,
"text": "redirect_to redirect_to url: new_scores_path, notice: 'Prediction WAS successfully created.'\n redirect_to new_score_path, notice: 'Prediction WAS successfully created.'\n new_score_path"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2576839/"
] |
74,517,744
|
<p>When iam trying to create lock using powershell Azure automation runbook by using below script</p>
<pre><code>New-AzResourceLock -LockName test -LockLevel CanNotDelete -ResourceGroupName rg -ResourceName resorcename -LockNotes Protection Auto created by Azure Backup -ResourceType Microsoft.Storage/storageAccounts -Force
</code></pre>
<p>error getting: A positional parameter cannot be found that accepts argument 'Auto'<a href="https://i.stack.imgur.com/VLhMk.png" rel="nofollow noreferrer">enter image description here</a> Hope you can help me with a problem trying to execute a script block, Thanks in Advance.</p>
|
[
{
"answer_id": 74518263,
"author": "max",
"author_id": 544825,
"author_profile": "https://Stackoverflow.com/users/544825",
"pm_score": 1,
"selected": false,
"text": "routes.rb resources :scores new_score_path new_singular_path"
},
{
"answer_id": 74518947,
"author": "GhostRider",
"author_id": 2576839,
"author_profile": "https://Stackoverflow.com/users/2576839",
"pm_score": 0,
"selected": false,
"text": " redirect_to \"/scores/new\"\n"
},
{
"answer_id": 74554172,
"author": "markets",
"author_id": 3033649,
"author_profile": "https://Stackoverflow.com/users/3033649",
"pm_score": 0,
"selected": false,
"text": "redirect_to redirect_to url: new_scores_path, notice: 'Prediction WAS successfully created.'\n redirect_to new_score_path, notice: 'Prediction WAS successfully created.'\n new_score_path"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20441802/"
] |
74,517,809
|
<p>I'm trying to run a really simple script on an Ubuntu EC2 machine with Selenium.</p>
<p>I put the next piece of code inside a loop since the script should run in the background forever:</p>
<pre><code>from selenium import webdriver
def play():
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("enable-automation")
chrome_options.add_argument("--disable-infobars")
chrome_options.add_argument("--disable-dev-shm-usage")
try:
driver = webdriver.Chrome(executable_path='/usr/bin/chromedriver', options=chrome_options)
except Exception as e:
with open(f'{os.getcwd()}/error_log.txt', 'a') as f:
f.write(str(datetime.datetime.now()))
f.write(str(e))
</code></pre>
<p>While connected to the instance with ssh, the script runs perfectly, but when disconnected, I get this error:</p>
<pre><code>Message: Service /usr/bin/chromedriver unexpectedly exited. Status code was: 1
</code></pre>
<p>After re-connecting, the script works normally again with no touch.</p>
<p>I'm running the script as follow:</p>
<pre><code>nohup python3 script.py &
</code></pre>
|
[
{
"answer_id": 74518100,
"author": "tedsmitt",
"author_id": 9464037,
"author_profile": "https://Stackoverflow.com/users/9464037",
"pm_score": 0,
"selected": false,
"text": "nohup ./script.py > foo.out 2> foo.err < /dev/null &\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10118150/"
] |
74,517,811
|
<p>Working with external Postgres DB, I have only read permissions, so I have to deal with a poorly designed tables.</p>
<p>I have a table:</p>
<pre><code>CREATE TABLE table (
user_id uuid NOT NULL,
column_a boolean DEFAULT false,
column_b boolean DEFAULT false,
column_c boolean DEFAULT false
);
</code></pre>
<p>The table is designed in such a way that only one of the 3 columns is set to true (or all of them are false).</p>
<p>I need to select the column name which is set to true. Is there an elegant way to achive this?</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>user_id</th>
<th>column_a</th>
<th>column_b</th>
<th>column_c</th>
</tr>
</thead>
<tbody>
<tr>
<td>u1</td>
<td>F</td>
<td>F</td>
<td>F</td>
</tr>
<tr>
<td>u2</td>
<td>F</td>
<td>T</td>
<td>F</td>
</tr>
</tbody>
</table>
</div>
<pre><code>SELECT WHERE user_id = 'u2'
</code></pre>
<p>should return '<strong>column_b</strong>' in this example (because it is the one that is set to true).</p>
<p>Tried different approaches but can't find an elegant way</p>
|
[
{
"answer_id": 74517893,
"author": "szeak",
"author_id": 1597791,
"author_profile": "https://Stackoverflow.com/users/1597791",
"pm_score": 0,
"selected": false,
"text": "SELECT\n CASE WHEN column_a = true\n THEN column_a\n ELSE CASE WHEN column_b = true\n THEN column_b\n ELSE CASE WHEN column_c = true\n THEN column_c ELSE null\n END\n END\n END as RESULT\nFROM table\nWHERE user_id = 'u2'\n"
},
{
"answer_id": 74517896,
"author": "a_horse_with_no_name",
"author_id": 330315,
"author_profile": "https://Stackoverflow.com/users/330315",
"pm_score": 2,
"selected": false,
"text": "select t.user_id, f.col\nfrom the_table t\n left join lateral (\n values \n ('column_a', t.column_a), \n ('column_b', t.column_b), \n ('column_c', t.column_c)\n ) as f(col, value) on f.value\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20561910/"
] |
74,517,895
|
<p>hi I have the following code that works just fine but I do not know how to move the matching name files to the same directory. for example I have 3 files with the same name (xml, jpeg, txt) when I move the xml file I want all the files with the same name to move with it. I was looking in the forum and did not find anything.</p>
<pre><code>import shutil
from pathlib import Path
from xml.etree import ElementTree as ET
def contains_drone(path):
tree = ET.parse(path.as_posix())
root = tree.getroot()
for obj in root.findall('object'):
rank = obj.find('name').text
if rank == 'car':
return True
return False
def move_drone_files(src="D:\\TomProject\\Images\\",
dst="D:\\TomProject\\Done"):
src, dst = Path(src), Path(dst)
for path in src.iterdir():
if path.suffix == '.xml' and contains_drone(path):
print(f'Moving {path.as_posix()} to {dst.as_posix()}')
shutil.move(path, dst)
if __name__ == "__main__":
move_drone_files()
</code></pre>
|
[
{
"answer_id": 74517893,
"author": "szeak",
"author_id": 1597791,
"author_profile": "https://Stackoverflow.com/users/1597791",
"pm_score": 0,
"selected": false,
"text": "SELECT\n CASE WHEN column_a = true\n THEN column_a\n ELSE CASE WHEN column_b = true\n THEN column_b\n ELSE CASE WHEN column_c = true\n THEN column_c ELSE null\n END\n END\n END as RESULT\nFROM table\nWHERE user_id = 'u2'\n"
},
{
"answer_id": 74517896,
"author": "a_horse_with_no_name",
"author_id": 330315,
"author_profile": "https://Stackoverflow.com/users/330315",
"pm_score": 2,
"selected": false,
"text": "select t.user_id, f.col\nfrom the_table t\n left join lateral (\n values \n ('column_a', t.column_a), \n ('column_b', t.column_b), \n ('column_c', t.column_c)\n ) as f(col, value) on f.value\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15691901/"
] |
74,517,945
|
<p>I'm working on a program in which i want to store the distance the user walked since pressing a button. I retrieve the distance via geolocator package and display it on screen which works just fine.</p>
<p>I know there are some distanceBetween-Function for locations, but as far as i noticed, they are just calculating the distance between 2 points and not the actual distance the user walked (For example, if the user starts at one point X, walks over to Point Y and back to X would end in comparing start-and endpoint (X to X), which results in distance: 0, but i want the distance X -> Y -> X.</p>
<p>I added following function that calculated the distance based on longitude/latitude.</p>
<pre><code>double distance(Position start, Position current){
return double.parse((acos(sin(start.latitude)*sin(current.latitude)+cos(start.latitude)*cos(current.latitude)*cos(current.longitude-start.longitude))*6371).toStringAsFixed(2));
}
</code></pre>
<p>I call it every frame and store the distance between the current and last gps position.
Works slowly but fine, except one Problem:
<strong>Somewhen, the double suddenly turns into "NaN", and i can't figure out why.</strong>
It's completely random when this occurs - At the beginning, it was always around 0.6, but it also occurred around 4.5 and 0.2, so i think the problem may be somewhere else.</p>
<p>Can anybody help?</p>
<p>Or does anybody knows a built-in-function that can solve the same problem?</p>
<p>I tried parsing the double to only have 2 decimal spaces (Didn't round it before) because i thought the number might just got too many decimal spaces to be displayed, but error still occured.</p>
<p>I have a second task that is happening at the same time each time stamp, so i thought it was hindering retrieving the GPS, so i tried disabling it, but it didn't change anything.</p>
|
[
{
"answer_id": 74517893,
"author": "szeak",
"author_id": 1597791,
"author_profile": "https://Stackoverflow.com/users/1597791",
"pm_score": 0,
"selected": false,
"text": "SELECT\n CASE WHEN column_a = true\n THEN column_a\n ELSE CASE WHEN column_b = true\n THEN column_b\n ELSE CASE WHEN column_c = true\n THEN column_c ELSE null\n END\n END\n END as RESULT\nFROM table\nWHERE user_id = 'u2'\n"
},
{
"answer_id": 74517896,
"author": "a_horse_with_no_name",
"author_id": 330315,
"author_profile": "https://Stackoverflow.com/users/330315",
"pm_score": 2,
"selected": false,
"text": "select t.user_id, f.col\nfrom the_table t\n left join lateral (\n values \n ('column_a', t.column_a), \n ('column_b', t.column_b), \n ('column_c', t.column_c)\n ) as f(col, value) on f.value\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20561895/"
] |
74,517,953
|
<p>I have this function:</p>
<pre><code>const getXNumberOfDocuments = async function getXNumberOfDocuments(
page,
results_per_page
) {
/*************************************************** */
results_per_page = parseInt(results_per_page);
let x_number_of_documents = await Document.find()
.populate([
{
path: "user",
populate: {
path: "profile",
select: ["profileImageURL"],
},
},
])
.limit(results_per_page)
.skip(results_per_page * page)
.lean();
/*************************************************** */
// I will stop this loop at i=0 by throwing an error
// As you se below
for (let i = 0; i < x_number_of_documents.length; i++) {
console.log(" ~ file: documentsServices.js ~ line 295 ~ i", i);
// #BUG:
// For some reason this changes
// profileImageURL for i=0 and i=1 as well
x_number_of_documents[i].user.profile.profileImageURL =
"THIS SHOULD ONLY BE MODIFIED FOR i=0 BUT IT IS MODIFIED FOR ALL OF THEM!";
// await s3_config.getImageReadSignedUrl(
// x_number_of_documents[i].user.profile.profileImageURL
// );
/*************************************************** */
// I check all documents here
// And I find that profileImageURL was modified in all of them
// Even though I stopped the loop at i=0
for (let j = 0; j < x_number_of_documents.length; j++) {
console.log(
" j,",
j
);
console.log(
" ~ file: documentsServices.js ~ line 299 ~ x_number_of_documents[j].user.profile.profileImageURL",
x_number_of_documents[j].user.profile.profileImageURL
);
console.log(
" "
);
}
/*************************************************** */
throw new Error("STOPPING LOOP AT i=0");
/*************************************************** */
}
return x_number_of_documents;
};
</code></pre>
<p>It usually returns something like this:</p>
<pre><code> const response = [
{
user: {
profile: {
profileImageURL: "https://xxxxxxx.com/xxx.jpeg",
},
},
},
{
user: {
profile: {
profileImageURL: "https://xxxxxxx.com/yyy.jpeg",
},
},
},
{
user: {
profile: {
profileImageURL: "https://xxxxxxx.com/zzz.jpeg",
},
},
},
];
</code></pre>
<p>I am trying to modify <code>profileImageURL</code> in each object:</p>
<pre><code>for (let i = 0; i < x_number_of_documents.length; i++) {
console.log(" ~ file: documentsServices.js ~ line 295 ~ i", i);
x_number_of_documents[i].user.profile.profileImageURL =
"THIS SHOULD ONLY BE MODIFIED FOR i=0 BUT IT IS MODIFIED FOR ALL OF THEM!";
}
</code></pre>
<p>The problem is I find out that when <code>i==0</code>, instead of modifying <code>profileImageURL</code> <strong>ONLY the first object</strong>, it modifies it in <strong>all objects</strong>.</p>
<p>So when I break the loop after <code>i==0</code>, and log all the objects, I see that <code>profileImageURL</code> is the same in all of them:</p>
<pre><code> ~ file: documentsServices.js ~ line 291 ~ x_number_of_documents.length 5
~ file: documentsServices.js ~ line 295 ~ i 0
j, 0
~ file: documentsServices.js ~ line 299 ~ x_number_of_documents[j].user.profile.profileImageURL THIS SHOULD ONLY BE MODIFIED FOR i=0 BUT IT IS MODIFIED FOR ALL OF THEM!
3asba
j, 1
~ file: documentsServices.js ~ line 299 ~ x_number_of_documents[j].user.profile.profileImageURL THIS SHOULD ONLY BE MODIFIED FOR i=0 BUT IT IS MODIFIED FOR ALL OF THEM!
3asba
j, 2
~ file: documentsServices.js ~ line 299 ~ x_number_of_documents[j].user.profile.profileImageURL THIS SHOULD ONLY BE MODIFIED FOR i=0 BUT IT IS MODIFIED FOR ALL OF THEM!
3asba
j, 3
~ file: documentsServices.js ~ line 299 ~ x_number_of_documents[j].user.profile.profileImageURL THIS SHOULD ONLY BE MODIFIED FOR i=0 BUT IT IS MODIFIED FOR ALL OF THEM!
3asba
j, 4
~ file: documentsServices.js ~ line 299 ~ x_number_of_documents[j].user.profile.profileImageURL THIS SHOULD ONLY BE MODIFIED FOR i=0 BUT IT IS MODIFIED FOR ALL OF THEM!
3asba
~ file: documents.js ~ line 204 ~ err Error: STOPPING LOOP AT i=0
</code></pre>
<p>Any idea what's going on?</p>
<hr />
<p>To better explain this, I simplified the snippets above:</p>
<pre><code>x_number_of_documents[0].user.profile.profileImageURL =
"THIS SHOULD ONLY BE MODIFIED FOR i=0 BUT IT IS MODIFIED FOR ALL OF THEM!";
console.log(
" ~ file: documentsServices.js ~ line 308 ~ x_number_of_documents[0].user.profile.profileImageURL",
x_number_of_documents[0].user.profile.profileImageURL
);
console.log(
" ~ file: documentsServices.js ~ line 308 ~ x_number_of_documents[1].user.profile.profileImageURL",
x_number_of_documents[1].user.profile.profileImageURL
);
console.log(
" ~ file: documentsServices.js ~ line 308 ~ x_number_of_documents[2].user.profile.profileImageURL",
x_number_of_documents[2].user.profile.profileImageURL
);
console.log(
" ~ file: documentsServices.js ~ line 308 ~ x_number_of_documents[3].user.profile.profileImageURL",
x_number_of_documents[3].user.profile.profileImageURL
);
console.log(
" ~ file: documentsServices.js ~ line 308 ~ x_number_of_documents[4].user.profile.profileImageURL",
x_number_of_documents[4].user.profile.profileImageURL
);
</code></pre>
<p>So even if I explicitly, changed the first object, this is the result:</p>
<pre><code> ~ file: FILLING profileImageURL for i= 0
~ file: documentsServices.js ~ line 308 ~ x_number_of_documents[0].user.profile.profileImageURL THIS SHOULD ONLY BE MODIFIED FOR i=0 BUT IT IS MODIFIED FOR ALL OF THEM!
~ file: documentsServices.js ~ line 308 ~ x_number_of_documents[1].user.profile.profileImageURL THIS SHOULD ONLY BE MODIFIED FOR i=0 BUT IT IS MODIFIED FOR ALL OF THEM!
~ file: documentsServices.js ~ line 308 ~ x_number_ofdocuments[2].user.profile.profileImageURL THIS SHOULD ONLY BE MODIFIED FOR i=0 BUT IT IS MODIFIED FOR ALL OF THEM!
~ file: documentsServices.js ~ line 308 ~ x_number_of_documents[3].user.profile.profileImageURL THIS SHOULD ONLY BE MODIFIED FOR i=0 BUT IT IS MODIFIED FOR ALL OF THEM!
~ file: documentsServices.js ~ line 308 ~ x_number_of_documents[4].user.profile.profileImageURL THIS SHOULD ONLY BE MODIFIED FOR i=0 BUT IT IS MODIFIED FOR ALL OF THEM!
</code></pre>
<p>So the final result is like this even though I explicitly only modified the first object!</p>
<pre><code>const response = [
{
user: {
profile: {
profileImageURL:
"THIS SHOULD ONLY BE MODIFIED FOR i=0 BUT IT IS MODIFIED FOR ALL OF THEM!",
},
},
},
{
user: {
profile: {
profileImageURL:
"THIS SHOULD ONLY BE MODIFIED FOR i=0 BUT IT IS MODIFIED FOR ALL OF THEM!",
},
},
},
{
user: {
profile: {
profileImageURL:
"THIS SHOULD ONLY BE MODIFIED FOR i=0 BUT IT IS MODIFIED FOR ALL OF THEM!",
},
},
},
];
</code></pre>
<hr />
<p>Strangely enough, if I modify the <code>user</code> instead of <code>x_number_of_documents[0].user.profile.profileImageURL</code>, it modified only the first object:</p>
<pre><code>const response = [
{
user: "THIS SHOULD ONLY BE MODIFIED FOR i=0 BUT IT IS MODIFIED FOR ALL OF THEM!",
},
{
user: {
profile: {
profileImageURL: "https://xxxxxxx.com/yyy.jpeg",
},
},
},
{
user: {
profile: {
profileImageURL: "https://xxxxxxx.com/zzz.jpeg",
},
},
},
];
</code></pre>
<hr />
<p>And if I modify <code>user.profile</code>, I get the same original problem:</p>
<pre><code>const response = [
{
user: {
profile:
"THIS SHOULD ONLY BE MODIFIED FOR i=0 BUT IT IS MODIFIED FOR ALL OF THEM!",
},
},
{
user: {
profile:
"THIS SHOULD ONLY BE MODIFIED FOR i=0 BUT IT IS MODIFIED FOR ALL OF THEM!",
},
},
{
user: {
profile:
"THIS SHOULD ONLY BE MODIFIED FOR i=0 BUT IT IS MODIFIED FOR ALL OF THEM!",
},
},
];
</code></pre>
<p>So this may have something to do with modifying values in embedded documents.</p>
|
[
{
"answer_id": 74517893,
"author": "szeak",
"author_id": 1597791,
"author_profile": "https://Stackoverflow.com/users/1597791",
"pm_score": 0,
"selected": false,
"text": "SELECT\n CASE WHEN column_a = true\n THEN column_a\n ELSE CASE WHEN column_b = true\n THEN column_b\n ELSE CASE WHEN column_c = true\n THEN column_c ELSE null\n END\n END\n END as RESULT\nFROM table\nWHERE user_id = 'u2'\n"
},
{
"answer_id": 74517896,
"author": "a_horse_with_no_name",
"author_id": 330315,
"author_profile": "https://Stackoverflow.com/users/330315",
"pm_score": 2,
"selected": false,
"text": "select t.user_id, f.col\nfrom the_table t\n left join lateral (\n values \n ('column_a', t.column_a), \n ('column_b', t.column_b), \n ('column_c', t.column_c)\n ) as f(col, value) on f.value\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74517953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8965420/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.