qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,284,777 | <p>As <code>def xxx() -> str:</code>, code highlight whill be display error when I use <code>-></code></p>
<p><a href="https://i.stack.imgur.com/e52jt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e52jt.png" alt="enter image description here" /></a></p>
<p>It's not a bug of the theme</p>
<p>If it can be solved by setting rules, can you help me solve it? Or a bug?</p>
| [
{
"answer_id": 74284853,
"author": "MAYUR SANCHETI",
"author_id": 12238257,
"author_profile": "https://Stackoverflow.com/users/12238257",
"pm_score": -1,
"selected": false,
"text": " data: tableData,\n columns: columnData,\n pageLength: 4,\n pagingType: \"first_last_numbers\"\n"
},
{
"answer_id": 74317563,
"author": "Yassine",
"author_id": 3311971,
"author_profile": "https://Stackoverflow.com/users/3311971",
"pm_score": 0,
"selected": false,
"text": "var table = $(id_table).DataTable();\nvar numPage= table.page();\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74284777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20394230/"
] |
74,284,780 | <p><strong>(, , , ) = (′ + ′)( + ′)′ + ′(′ + ′) + ′</strong></p>
<p>like this combined expression where SOP and POS are both available how can I know which are sop & which are pos?</p>
<p>I am trying to find the sop & pos from this combined expression but I can't. We know <strong>(′ + ′)( + ′)</strong> it's a pos function and it's a <strong>′A + ′</strong> sop function. But I can't understand how to find from combined expressions where both sop pos are available.</p>
| [
{
"answer_id": 74284853,
"author": "MAYUR SANCHETI",
"author_id": 12238257,
"author_profile": "https://Stackoverflow.com/users/12238257",
"pm_score": -1,
"selected": false,
"text": " data: tableData,\n columns: columnData,\n pageLength: 4,\n pagingType: \"first_last_numbers\"\n"
},
{
"answer_id": 74317563,
"author": "Yassine",
"author_id": 3311971,
"author_profile": "https://Stackoverflow.com/users/3311971",
"pm_score": 0,
"selected": false,
"text": "var table = $(id_table).DataTable();\nvar numPage= table.page();\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74284780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17333680/"
] |
74,284,785 | <p>I trid the following sample code in my pc</p>
<pre><code> from bs4 import BeautifulSoup
from lxml import etree, html
import requests
URL = "https://en.wikipedia.org/wiki/Nike,_Inc."
HEADERS = ({'User-Agent':
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 \
(KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36',\
'Accept-Language': 'en-US, en;q=0.5'})
webpage = requests.get(URL, headers=HEADERS)
soup = BeautifulSoup(webpage.content, "html.parser")
dom = etree.HTML(str(soup))
print(dom.xpath('//*[@id="firstHeading"]')[0].text)
</code></pre>
<p>But print out is empty
I checked about content dom text but it is None
On the other hand I checked about result as xpath using html.tostring()
So content is exsiting...</p>
<p>Actually, it is just sample so I would like to control the following codes,</p>
<pre><code> import pytest
from bs4 import BeautifulSoup
from lxml import etree, html
import requests
from urllib import request as rs
def test_scraping():
URL = "https://news.yahoo.co.jp/search?p=岸田文雄&ei=utf-8&categories=business"
HEADERS = ({'User-Agent':
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 \
(KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36',\
'Accept-Language': 'en-US, en;q=0.5'})
webpage = requests.get(URL, headers=HEADERS)
soup = BeautifulSoup(webpage.content, "html.parser")
dom = etree.HTML(str(soup))
elements = dom.xpath("//li[@class='viewableWrap newsFeed_item newsFeed_item-normal newsFeed_item-ranking']")
for element in elements:
print(element.tag)
if element.text is not None:
.... <-- not working....
</code></pre>
<p>I can find a tag contet or another tags one using find function
But I would like to control it using another way</p>
<p>So let me know the way if you know it</p>
| [
{
"answer_id": 74284853,
"author": "MAYUR SANCHETI",
"author_id": 12238257,
"author_profile": "https://Stackoverflow.com/users/12238257",
"pm_score": -1,
"selected": false,
"text": " data: tableData,\n columns: columnData,\n pageLength: 4,\n pagingType: \"first_last_numbers\"\n"
},
{
"answer_id": 74317563,
"author": "Yassine",
"author_id": 3311971,
"author_profile": "https://Stackoverflow.com/users/3311971",
"pm_score": 0,
"selected": false,
"text": "var table = $(id_table).DataTable();\nvar numPage= table.page();\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74284785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12758069/"
] |
74,284,823 | <p>how do I check which files are missing from the directory based on a txt of the files I should have?</p>
<p>E.G this is the list of files I should have</p>
<blockquote>
<p>A<br />
B<br />
C<br />
D<br />
E<br />
F<br />
G<br />
H<br />
I</p>
</blockquote>
<p>But in my directory I only have</p>
<blockquote>
<p>A.npy<br />
B.npy<br />
C.npy<br />
D.npy</p>
</blockquote>
<p>So I want to do a script that can produce a result.txt like this:</p>
<blockquote>
<p>A [exists]<br />
B [exists]<br />
C [exists]<br />
D [exists]<br />
E [does not exist]<br />
F [does not exist]<br />
G [does not exist]<br />
H [does not exist]<br />
I [does not exist]</p>
</blockquote>
<p>This is the script I have currently but it doesn't seem to work as it registers all files as "does not exist" :(</p>
<pre><code>import os
import copy
import pandas as pd
import shutil
from pathlib import Path
# read training files.txt
path_to_file = 'xxxxxxxxxxxxxxxxxx/train_files_CS/all_training_CSmaster.txt'
path = 'xxxxxxxxxxx/train_files_CS'
# list of training npy files in directory
lof = []
for (dirpath, dirnames, filenames) in os.walk(path):
lof.append(filenames)
lof = [x[:len(x) - 4] for x in lof[0] if x[0] == 'P']
#print(lof)
# new file to be written into
f = open('check_training.txt', 'w')
existing_files = 0
missing_files = 0
trfiles = []
with open(path_to_file) as file:
for line in file:
#print(line.rstrip())
trfiles.append(line)
for x in trfiles:
if x in lof:
existing_files+=1
f.write(x)
f.write("...[exists] \n")
else:
missing_files+=1
f.write(x)
f.write(" ...[doesn't exist] \n")
f.close()
print("\nthe missing files are:", missing_files,"\n")
print("the existing files are:",existing_files,"\n")
</code></pre>
<p>Any help is appreciated, thank you! :)</p>
| [
{
"answer_id": 74284985,
"author": "ljdyer",
"author_id": 17568469,
"author_profile": "https://Stackoverflow.com/users/17568469",
"pm_score": 2,
"selected": true,
"text": "lof = [x[:len(x) - 4] for x in lof[0] if x[0] == 'P']\n"
},
{
"answer_id": 74284987,
"author": "yeti",
"author_id": 5647853,
"author_profile": "https://Stackoverflow.com/users/5647853",
"pm_score": 0,
"selected": false,
"text": "os.path.isfile"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74284823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15233108/"
] |
74,284,863 | <p>I ordered a 444MHZ remote and receiver with some buttons on it. The remote has rolling code but when I tested I saw that every button has 8 fixed different possibility and repeat it self.</p>
<pre><code> Button1: (Decimal results)
1- 3899572514 / 32bit PulseLength: 251 microseconds Protocol: 1
2- 3899580674 / 32bit PulseLength: 251 microseconds Protocol: 1
3- 3899523362 / 32bit PulseLength: 251 microseconds Protocol: 1
4- 3899531522 / 32bit PulseLength: 251 microseconds Protocol: 1
5- 3899539746 / 32bit PulseLength: 251 microseconds Protocol: 1
6- 3899547906 / 32bit PulseLength: 251 microseconds Protocol: 1
7- 3899556130 / 32bit PulseLength: 251 microseconds Protocol: 1
8- 3899564290 / 32bit PulseLength: 251 microseconds Protocol: 1
</code></pre>
<p>So, I'm tyring to figure out what is the best method for developing the receiver code.
I tought different ideas but I did not like them at all so I want to take your opinions.</p>
<p>My ideas are:</p>
<p>1- I will record all of these possibilities and use them like "if any one of these" method but this is not secure and I don't want to that.</p>
<p>2- I will record all of these possibilities and expecting other then previous lenght. This is also not suitable because it is not secure either. There are 7 different possibilities and if I have multiple device in a room, remotes goes mixed with this method.</p>
<p>3- If I'm gonna put them order and expect only for the next possibility it could work and it will reduce to mixing with other same device. Thats nice but I can not put them in order because when the device misses a push then it will not work at all. Also there are no ways to know the current lenght when the device rebooted.</p>
<p>P.S: Security is not too much needed. It is gonna a home light system but I want to code the receiver to reach (close as) paired devices for in a case having multiple devices in the room.</p>
<p>Any idea or example will be awesome!</p>
| [
{
"answer_id": 74284985,
"author": "ljdyer",
"author_id": 17568469,
"author_profile": "https://Stackoverflow.com/users/17568469",
"pm_score": 2,
"selected": true,
"text": "lof = [x[:len(x) - 4] for x in lof[0] if x[0] == 'P']\n"
},
{
"answer_id": 74284987,
"author": "yeti",
"author_id": 5647853,
"author_profile": "https://Stackoverflow.com/users/5647853",
"pm_score": 0,
"selected": false,
"text": "os.path.isfile"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74284863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6076600/"
] |
74,284,869 | <p>I have singlehandedly tried to find a solution to this problem which I encountered about a week ago and to be honest I have tried different ways to tackle this problem but all efforts proved futile as they led to another problem entirely.</p>
<p>I am trying to implement a feature that increases product quantity if the product size already exists in the cart and the user clicks on the add to cart button, but for some reason when I add an item to the cart and the product size exists it adds a new line rather than update the quantity of the product in the cart.</p>
<p>I have different sizes for each products so let's say I added size 32 of the product with 1qty to the cart and I add size 32 of that same product to the cart again with 3qtys I want it to increment the quantity of the product by 3(which is 4) and not add it to a new line.</p>
<p>This is the page that is handling the cart processing.</p>
<pre><code></code></pre>
<pre><code><?php session_name("grind"); session_start();
ini_set('display_errors',1); ini_set('display_startup_errors',1); error_reporting(E_ALL);
if (isset($_SESSION['cart'])) { $checker=array_column($_SESSION['cart'],'size','item_id');
//I know the if(in_array) is not working which is why it executes the else statement that adds the item on a new line but I don't understand why, any explanation with the use of code will be appreciated.
if (in_array($_GET['cart_id'], $checker) && in_array($_POST['size'],$checker)) {
foreach($_SESSION['cart'] as $key => $value){
if($value['item_id']==$_GET['cart_id'] && $value['size']==$_POST['size'] && ($_SESSION['cart'][$key]['quantity'] + $_POST['quantity'] > 5))
//checking if the item_id in the cart is the same as the one in the url using the $_GET variable, check if the product size in the cart is equal to the one that just got added to the cart and if the sum of the cart quantity and the quantity that just got added is greater than 5(if the quantity is > than 5 set the cart quantity of that product size to 5).
{
$_SESSION['cart'][$_POST['size']]['quantity'] = 5;
echo "<script>
alert('only 5 items available for this product');
window.location.href='grind.php';
</script>";
}
//else if the following is true, increment the quantity by the number of quantity added to the cart e.g if 2 is item quantity in the session and the user adds 4 the updated quantity will be 6.
else if($value['item_id']==$_GET['cart_id'] && $value['size']==$_POST['size'] && ($_SESSION['cart'][$key]['quantity'] + $_POST['quantity'] <= 5)){
$_SESSION['cart'][$key]['quantity'] +=$_POST['quantity'];
echo
"<script>
alert('quantity updated');
window.location.href='grind.php';
</script>";
}
}
}
else{
$count=count($_SESSION['cart']);
$_SESSION['cart'][$count]=array('item_id' => $_GET['cart_id'], 'item_name'=>$_GET['cart_name'],'item_picture'=>$_GET['cart_picture'], 'item_price'=>$_GET['cart_price'],'size'=>$_POST['size'], 'quantity'=>$_POST['quantity']);
echo "<script>alert('product added');
window.location.href='grind.php';
</script>";
}
}
else{ $_SESSION['cart'][0]=array('item_id'=>$_GET['cart_id'], 'item_name'=>$_GET['cart_name'], 'item_picture'=>$_GET['cart_picture'],'item_price'=>$_GET['cart_price'],'size'=>$_POST['size'], 'quantity'=>$_POST['quantity']); echo "<script>alert('product added'); window.location.href='grind.php'; </script>";
}
?>
</code></pre>
<pre><code></code></pre>
| [
{
"answer_id": 74298429,
"author": "Asis",
"author_id": 15935039,
"author_profile": "https://Stackoverflow.com/users/15935039",
"pm_score": 0,
"selected": false,
"text": "<?php\n\nsession_name(\"grind\");\nsession_start();\n\nini_set('display_errors', 1);\nini_set('display_startup_errors', 1);\nerror_reporting(E_ALL);\n\n\nif (isset($_SESSION['cart'])) {\n //Check if the item with same size has already been added to the cart\n $itemWithSameSizeIsInCart = false;\n foreach ($_SESSION['cart'] as $key => $value) {\n if ($value['item_id'] == $_GET['cart_id'] && $value['size'] == $_POST['size']) {\n $itemWithSameSizeIsInCart = $key;\n break;\n }\n }\n\n //If item is in cart and size is the same do this and return\n if ($itemWithSameSizeIsInCart !== false) {\n $workingItem = $_SESSION['cart'][$itemWithSameSizeIsInCart];\n\n //Add posted quantity to item\n $workingItem['quantity'] = $workingItem['quantity'] += $_POST['quantity'];\n $alertMsg = \"alert('product added');\";\n\n //Check if quantity is greater than 5\n if ($workingItem['quantity'] > 5) {\n $workingItem['quantity'] = 5;\n $alertMsg = \"alert('only 5 items available for this product');\";\n }\n\n echo \"<script>$alertMsg window.location.href='grind.php'; </script>\";\n return;\n }\n\n //Default behaviour if item not in cart, add item to cart\n $count = count($_SESSION['cart']);\n $_SESSION['cart'][$count] = array(\n 'item_id' => $_GET['cart_id'],\n 'item_name' => $_GET['cart_name'],\n 'item_picture' => $_GET['cart_picture'],\n 'item_price' => $_GET['cart_price'],\n 'size' => $_POST['size'],\n 'quantity' => $_POST['quantity']\n );\n echo \"<script>alert('product added'); window.location.href='grind.php'; </script>\";\n} else {\n $_SESSION['cart'][0] = array(\n 'item_id' => $_GET['cart_id'],\n 'item_name' => $_GET['cart_name'],\n 'item_picture' => $_GET['cart_picture'],\n 'item_price' => $_GET['cart_price'],\n 'size' => $_POST['size'],\n 'quantity' => $_POST['quantity']\n );\n echo \"<script>alert('product added'); window.location.href='grind.php'; </script>\";\n}\n"
},
{
"answer_id": 74324540,
"author": "krimo jay",
"author_id": 10785584,
"author_profile": "https://Stackoverflow.com/users/10785584",
"pm_score": 2,
"selected": true,
"text": "$checker=array_column($_SESSION['cart'],'size','item_id'); "
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74284869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10785584/"
] |
74,284,906 | <p>I need to capitalize the first letter of each line inside a div<br />
In the example below the result should be:</p>
<pre><code>Lorem ipsum
Dolor sit
Amet
</code></pre>
<p>So each <code>\n and first letter</code> should be replaced by <code>\n and capital letter</code></p>
<p>Please help me abut the regex part of my code</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$('button').on('click', function(){
let str = $('#wrap').text();
let result = str.replace(/\n a-z/, /\n A-Z/); // how to write this?
$('#wrap').text(result);
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrap{white-space:pre-wrap;}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='wrap' id='wrap'>
lorem ipsum
dolor sit
amet
</div>
<button>CLICK</button></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74298429,
"author": "Asis",
"author_id": 15935039,
"author_profile": "https://Stackoverflow.com/users/15935039",
"pm_score": 0,
"selected": false,
"text": "<?php\n\nsession_name(\"grind\");\nsession_start();\n\nini_set('display_errors', 1);\nini_set('display_startup_errors', 1);\nerror_reporting(E_ALL);\n\n\nif (isset($_SESSION['cart'])) {\n //Check if the item with same size has already been added to the cart\n $itemWithSameSizeIsInCart = false;\n foreach ($_SESSION['cart'] as $key => $value) {\n if ($value['item_id'] == $_GET['cart_id'] && $value['size'] == $_POST['size']) {\n $itemWithSameSizeIsInCart = $key;\n break;\n }\n }\n\n //If item is in cart and size is the same do this and return\n if ($itemWithSameSizeIsInCart !== false) {\n $workingItem = $_SESSION['cart'][$itemWithSameSizeIsInCart];\n\n //Add posted quantity to item\n $workingItem['quantity'] = $workingItem['quantity'] += $_POST['quantity'];\n $alertMsg = \"alert('product added');\";\n\n //Check if quantity is greater than 5\n if ($workingItem['quantity'] > 5) {\n $workingItem['quantity'] = 5;\n $alertMsg = \"alert('only 5 items available for this product');\";\n }\n\n echo \"<script>$alertMsg window.location.href='grind.php'; </script>\";\n return;\n }\n\n //Default behaviour if item not in cart, add item to cart\n $count = count($_SESSION['cart']);\n $_SESSION['cart'][$count] = array(\n 'item_id' => $_GET['cart_id'],\n 'item_name' => $_GET['cart_name'],\n 'item_picture' => $_GET['cart_picture'],\n 'item_price' => $_GET['cart_price'],\n 'size' => $_POST['size'],\n 'quantity' => $_POST['quantity']\n );\n echo \"<script>alert('product added'); window.location.href='grind.php'; </script>\";\n} else {\n $_SESSION['cart'][0] = array(\n 'item_id' => $_GET['cart_id'],\n 'item_name' => $_GET['cart_name'],\n 'item_picture' => $_GET['cart_picture'],\n 'item_price' => $_GET['cart_price'],\n 'size' => $_POST['size'],\n 'quantity' => $_POST['quantity']\n );\n echo \"<script>alert('product added'); window.location.href='grind.php'; </script>\";\n}\n"
},
{
"answer_id": 74324540,
"author": "krimo jay",
"author_id": 10785584,
"author_profile": "https://Stackoverflow.com/users/10785584",
"pm_score": 2,
"selected": true,
"text": "$checker=array_column($_SESSION['cart'],'size','item_id'); "
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74284906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10983537/"
] |
74,284,931 | <p>I want to count all the unique characters in a given string. So for string "abcaabbd" the length should be 4.</p>
<p>My solution:</p>
<pre><code> public static void unique(String s){
int max = 0;
HashSet<Character> set = new HashSet<Character>();
for(int i = 0; i < s.length(); i++){
set.add(s.charAt(i));
}
max = set.size();
System.out.println(max);
}
</code></pre>
<p>which works fine but I was thinking if there is any way to reduct the time complexity of the operation.</p>
| [
{
"answer_id": 74285658,
"author": "cooleck",
"author_id": 10371918,
"author_profile": "https://Stackoverflow.com/users/10371918",
"pm_score": 2,
"selected": false,
"text": "HashSet"
},
{
"answer_id": 74318318,
"author": "lzl",
"author_id": 20312513,
"author_profile": "https://Stackoverflow.com/users/20312513",
"pm_score": 0,
"selected": false,
"text": "public static int unique(String s) {\n boolean[] seen = new boolean[256];\n for (int i = 0; i < s.length(); i++) {\n seen[s.charAt(i)] = true;\n }\n int count = 0;\n for (int i = 0; i < seen.length; i++) {\n if (seen[i]) {\n count++;\n }\n }\n return count;\n}\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74284931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19231322/"
] |
74,284,933 | <p>Our CVE tracker is flagging <code>odata-client-core</code> (version 4.8.0) for the presence of dependency <code>woodstox-core</code> (version 6.2.4) affected by <a href="https://github.com/advisories/GHSA-fv22-xp26-mm9w" rel="nofollow noreferrer">CVE-2022-40153</a>.</p>
<p>The relevant dependency tree is below:-</p>
<pre><code>+- org.apache.olingo:odata-client-core:jar:4.8.0:compile
[INFO] | +- org.apache.olingo:odata-client-api:jar:4.8.0:compile
[INFO] | | \- org.apache.olingo:odata-commons-api:jar:4.8.0:compile
[INFO] | +- org.apache.olingo:odata-commons-core:jar:4.8.0:compile
[INFO] | +- commons-codec:commons-codec:jar:1.15:compile
[INFO] | +- org.apache.httpcomponents:httpclient:jar:4.5.13:compile
[INFO] | | \- org.apache.httpcomponents:httpcore:jar:4.4.15:compile
[INFO] | +- org.slf4j:slf4j-api:jar:1.7.32:compile
[INFO] | +- com.fasterxml.jackson.core:jackson-core:jar:2.12.6:compile
[INFO] | +- com.fasterxml.jackson.core:jackson-annotations:jar:2.12.6:compile
[INFO] | +- com.fasterxml.jackson.dataformat:jackson-dataformat-xml:jar:2.12.6:compile
[INFO] | | +- com.fasterxml.jackson.module:jackson-module-jaxb-annotations:jar:2.12.6:compile
[INFO] | | +- org.codehaus.woodstox:stax2-api:jar:4.2.1:compile
[INFO] | | \- com.fasterxml.woodstox:woodstox-core:jar:6.2.4:compile
</code></pre>
<p>The issue is fixed in <code>woodstox-core</code> 6.4.0. The latest version of <code>odata-client-core</code> (version 4.9.0) is still using the vulnerable <code>woodstox-core</code> version.</p>
<ol>
<li>Is there any plan of upgrading the version of <code>woodstox-core</code>? If
yes, which version is expected to have the fix?</li>
<li>Is someone aware if the <code>woodstox-core</code> 6.4.0 is compatible with <code>odata-client-core</code>
4.8.0 or 4.9.0 version so that I can exclude <code>woodstox-core</code> 6.2.0 in my pom and add <code>woodstox-core</code> 6.4.0?</li>
</ol>
| [
{
"answer_id": 74285658,
"author": "cooleck",
"author_id": 10371918,
"author_profile": "https://Stackoverflow.com/users/10371918",
"pm_score": 2,
"selected": false,
"text": "HashSet"
},
{
"answer_id": 74318318,
"author": "lzl",
"author_id": 20312513,
"author_profile": "https://Stackoverflow.com/users/20312513",
"pm_score": 0,
"selected": false,
"text": "public static int unique(String s) {\n boolean[] seen = new boolean[256];\n for (int i = 0; i < s.length(); i++) {\n seen[s.charAt(i)] = true;\n }\n int count = 0;\n for (int i = 0; i < seen.length; i++) {\n if (seen[i]) {\n count++;\n }\n }\n return count;\n}\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74284933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/785523/"
] |
74,284,943 | <p>This route handle three request at a time but upon massive traffic this method fail. Is there any method to handle massive traffic</p>
<pre><code>
@app.route('/v1.1/userRegistor', methods=['POST', 'GET'])
def job():
count = 0
data = request.get_json()
numbers = data['number']
if count == 0:
api_url = f'https://app.simplywhatsapp.com/api/send.php?number={numbers}&type=text&message=Your OTP is %20{valuepi1}&instance_id=instance1&access_token=access_token1'
r = requests.get(api_url).text
count += 1
return str(count)
if count == 1:
api1_url = f'https://app.simplywhatsapp.com/api/send.php?number={numbers}&type=text&message=Your OTP is %20{value}&instance_id=instance2&access_token=access_token2'
r = requests.get(api1_url).text
count += 1
return str(count)
if count == 2:
api2_url = f'https://app.simplywhatsapp.com/api/send.php?number={numbers}&type=text&message=Your OTP is %20{value}&instance_id=instance3&access_token=access_token3'
r = requests.get(api2_url).text
count = 0
return str(count)
</code></pre>
| [
{
"answer_id": 74285658,
"author": "cooleck",
"author_id": 10371918,
"author_profile": "https://Stackoverflow.com/users/10371918",
"pm_score": 2,
"selected": false,
"text": "HashSet"
},
{
"answer_id": 74318318,
"author": "lzl",
"author_id": 20312513,
"author_profile": "https://Stackoverflow.com/users/20312513",
"pm_score": 0,
"selected": false,
"text": "public static int unique(String s) {\n boolean[] seen = new boolean[256];\n for (int i = 0; i < s.length(); i++) {\n seen[s.charAt(i)] = true;\n }\n int count = 0;\n for (int i = 0; i < seen.length; i++) {\n if (seen[i]) {\n count++;\n }\n }\n return count;\n}\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74284943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20394458/"
] |
74,284,982 | <p>i have the below posted list and it contais lists, so it is a list of lists, and i have a webservice that returns <code>return jsonify(resultsDict)</code>. the problem i am facing is when i run the App i recieve either of the error messages posted below.
as shown in the code below, i tried to set <code>dtype=np.float64</code> and <code>dtype=object</code>, but each of them generates an error associated to it as shown below in the code.
please let me know how to fix it</p>
<p><strong>attempt_1</strong></p>
<pre><code>resultsDict={
"extras": {
"pvTreatment":np.array(pvTreatment,dtype=np.float64).tolist(),
...
...
...
}
}
**error associated**:
ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (7,) + inhomogeneous part.
</code></pre>
<p><strong>attempt_2</strong></p>
<pre><code>resultsDict = {
"extras": {
"pvTreatment":np.array(pvTreatment,dtype=object).tolist(),
...
...
...
}
}
**error associated**:
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type float32 is not JSON serializable
</code></pre>
| [
{
"answer_id": 74285658,
"author": "cooleck",
"author_id": 10371918,
"author_profile": "https://Stackoverflow.com/users/10371918",
"pm_score": 2,
"selected": false,
"text": "HashSet"
},
{
"answer_id": 74318318,
"author": "lzl",
"author_id": 20312513,
"author_profile": "https://Stackoverflow.com/users/20312513",
"pm_score": 0,
"selected": false,
"text": "public static int unique(String s) {\n boolean[] seen = new boolean[256];\n for (int i = 0; i < s.length(); i++) {\n seen[s.charAt(i)] = true;\n }\n int count = 0;\n for (int i = 0; i < seen.length; i++) {\n if (seen[i]) {\n count++;\n }\n }\n return count;\n}\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74284982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1652954/"
] |
74,284,984 | <p>This is the code:</p>
<pre><code>CREATE PROCEDURE print_string(IN input_string VARCHAR(255))
BEGIN
DECLARE num_chars INT DEFAULT 0;
IF input_string IS NULL THEN
SET num_chars = 0;
ELSE
SET num_chars = CHAR_LENGTH(input_string);
END IF;
SELECT UPPER(input_string), num_chars;
END;
</code></pre>
<p>I get error:</p>
<pre class="lang-none prettyprint-override"><code>PLS-00103: Encountered the symbol "IN" when expecting one of the following: <an identifier> <a double-quoted delimited-identifier>
current delete exists prior
Errors: check compiler log
</code></pre>
<p>How do I fix: <code>current delete exists prior</code>?</p>
| [
{
"answer_id": 74286920,
"author": "Griffin",
"author_id": 18280576,
"author_profile": "https://Stackoverflow.com/users/18280576",
"pm_score": 1,
"selected": false,
"text": "CREATE OR REPLACE PROCEDURE print_string(input_string IN VARCHAR2) \nIS\nBEGIN\n"
},
{
"answer_id": 74287137,
"author": "Alex Poole",
"author_id": 266304,
"author_profile": "https://Stackoverflow.com/users/266304",
"pm_score": 2,
"selected": false,
"text": "(input_string IN ..."
},
{
"answer_id": 74287394,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 2,
"selected": false,
"text": "CREATE PROCEDURE print_string(\n input_string IN VARCHAR2\n)\nIS\nBEGIN\n DBMS_OUTPUT.PUT_LINE(UPPER(input_string) || ', ' || COALESCE(LENGTH(input_string), 0));\nEND;\n/\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74284984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20394548/"
] |
74,284,991 | <p>For some reason the React Router Link is significantly changing my css. Is there a way I can remove any styling impact from the Link?</p>
<p>Without Link:</p>
<p><a href="https://i.stack.imgur.com/ZoVEq.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZoVEq.jpg" alt="enter image description here" /></a></p>
<p>With Link:
<a href="https://i.stack.imgur.com/84qRS.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/84qRS.jpg" alt="enter image description here" /></a></p>
<p>This is the code for the Link. It has no style features.</p>
<pre><code>```
<Link to={`/link/${item.id}`}>
```
</code></pre>
<p>style={{textDecoration: 'none'}}</p>
| [
{
"answer_id": 74286920,
"author": "Griffin",
"author_id": 18280576,
"author_profile": "https://Stackoverflow.com/users/18280576",
"pm_score": 1,
"selected": false,
"text": "CREATE OR REPLACE PROCEDURE print_string(input_string IN VARCHAR2) \nIS\nBEGIN\n"
},
{
"answer_id": 74287137,
"author": "Alex Poole",
"author_id": 266304,
"author_profile": "https://Stackoverflow.com/users/266304",
"pm_score": 2,
"selected": false,
"text": "(input_string IN ..."
},
{
"answer_id": 74287394,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 2,
"selected": false,
"text": "CREATE PROCEDURE print_string(\n input_string IN VARCHAR2\n)\nIS\nBEGIN\n DBMS_OUTPUT.PUT_LINE(UPPER(input_string) || ', ' || COALESCE(LENGTH(input_string), 0));\nEND;\n/\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74284991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19518162/"
] |
74,284,994 | <p>I have a word document with some paragraphs and address details within it. I used textract to extract the sentences of this document line by line into a list. What i want to do is to detect the complete address chunk as one whole sentence string. The address template is not fixed and can or cannot have all the details some times, how can i achieve that ?</p>
<p>the input document looks like -</p>
<pre><code>some paragraph1
Employee’s address: Mr. A John Doe
9 hackers way
a state in US
2192
Telephone: 1411567323
Telefax: -
E-mail: someemail@gmail.com
some paragraph 2
next page
some paragraph 3
</code></pre>
<p>what i want the complete address chunk to be detected is -</p>
<pre><code>Employee’s address: Mr. A John Doe
9 hackers way
a state in US
2192
Telephone: 1411567323
Telefax: -
E-mail: someemail@gmail.com
</code></pre>
| [
{
"answer_id": 74286920,
"author": "Griffin",
"author_id": 18280576,
"author_profile": "https://Stackoverflow.com/users/18280576",
"pm_score": 1,
"selected": false,
"text": "CREATE OR REPLACE PROCEDURE print_string(input_string IN VARCHAR2) \nIS\nBEGIN\n"
},
{
"answer_id": 74287137,
"author": "Alex Poole",
"author_id": 266304,
"author_profile": "https://Stackoverflow.com/users/266304",
"pm_score": 2,
"selected": false,
"text": "(input_string IN ..."
},
{
"answer_id": 74287394,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 2,
"selected": false,
"text": "CREATE PROCEDURE print_string(\n input_string IN VARCHAR2\n)\nIS\nBEGIN\n DBMS_OUTPUT.PUT_LINE(UPPER(input_string) || ', ' || COALESCE(LENGTH(input_string), 0));\nEND;\n/\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74284994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2614378/"
] |
74,285,003 | <p>I used <code>Container</code> this caused all my grid items to be in columns not rows how can I fix it ?</p>
<p><a href="https://i.stack.imgur.com/9BjOA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9BjOA.png" alt="enter image description here" /></a></p>
<p><a href="https://codesandbox.io/s/determined-dijkstra-lqjfyq?file=/src/App.js" rel="nofollow noreferrer">link for project</a></p>
| [
{
"answer_id": 74286920,
"author": "Griffin",
"author_id": 18280576,
"author_profile": "https://Stackoverflow.com/users/18280576",
"pm_score": 1,
"selected": false,
"text": "CREATE OR REPLACE PROCEDURE print_string(input_string IN VARCHAR2) \nIS\nBEGIN\n"
},
{
"answer_id": 74287137,
"author": "Alex Poole",
"author_id": 266304,
"author_profile": "https://Stackoverflow.com/users/266304",
"pm_score": 2,
"selected": false,
"text": "(input_string IN ..."
},
{
"answer_id": 74287394,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 2,
"selected": false,
"text": "CREATE PROCEDURE print_string(\n input_string IN VARCHAR2\n)\nIS\nBEGIN\n DBMS_OUTPUT.PUT_LINE(UPPER(input_string) || ', ' || COALESCE(LENGTH(input_string), 0));\nEND;\n/\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11199128/"
] |
74,285,007 | <p>The below given code in my response which I need to display in Listview builder, now I need the data of <strong>name</strong> which in inside <strong>result</strong>, how do i fetch it and display it in text?</p>
<pre><code>{
"message": "sucess",
"error": false,
"code": 200,
"result": [
{
"id": 1,
"name": "Lab Report"
},
{
"id": 2,
"name": "News"
},
{
"id": 3,
"name": "X-ray"
},
{
"id": 8,
"name": "Blood Test"
}
],
"status": 200
}
</code></pre>
<p>And below is my model class of the response now I want the data which is inside of result and need to display in Listview builder</p>
<pre><code>import 'dart:convert';
PostFromJson postFromJsonFromJson(String str) => PostFromJson.fromJson(json.decode(str));
String postFromJsonToJson(PostFromJson data) => json.encode(data.toJson());
class PostFromJson {
PostFromJson({
this.message,
this.error,
this.code,
required this.result,
this.status,
});
String? message;
bool? error;
int? code;
List<Result> result;
int? status;
factory PostFromJson.fromJson(Map<String, dynamic> json) => PostFromJson(
message: json["message"],
error: json["error"],
code: json["code"],
result: List<Result>.from(json["result"].map((x) => Result.fromJson(x))),
status: json["status"],
);
Map<String, dynamic> toJson() => {
"message": message,
"error": error,
"code": code,
"result": List<dynamic>.from(result.map((x) => x.toJson())),
"status": status,
};
}
class Result {
Result({
this.id,
this.name,
});
int? id;
String? name;
factory Result.fromJson(Map<String, dynamic> json) => Result(
id: json["id"],
name: json["name"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
};
}
</code></pre>
| [
{
"answer_id": 74286920,
"author": "Griffin",
"author_id": 18280576,
"author_profile": "https://Stackoverflow.com/users/18280576",
"pm_score": 1,
"selected": false,
"text": "CREATE OR REPLACE PROCEDURE print_string(input_string IN VARCHAR2) \nIS\nBEGIN\n"
},
{
"answer_id": 74287137,
"author": "Alex Poole",
"author_id": 266304,
"author_profile": "https://Stackoverflow.com/users/266304",
"pm_score": 2,
"selected": false,
"text": "(input_string IN ..."
},
{
"answer_id": 74287394,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 2,
"selected": false,
"text": "CREATE PROCEDURE print_string(\n input_string IN VARCHAR2\n)\nIS\nBEGIN\n DBMS_OUTPUT.PUT_LINE(UPPER(input_string) || ', ' || COALESCE(LENGTH(input_string), 0));\nEND;\n/\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19717967/"
] |
74,285,012 | <p>Not using VBA but just simple excel, can anyone help me find a solution to this problem? Would greatly appreciate it!</p>
<p>I have a list of Names in <strong>Sheet 1</strong> like below</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>-</th>
<th>A</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>sp_abc_<strong>Rick</strong></td>
</tr>
<tr>
<td>2</td>
<td>sp_abc_<strong>Jabba_the</strong></td>
</tr>
<tr>
<td>3</td>
<td>sp_abc_<strong>Dany</strong></td>
</tr>
<tr>
<td>4</td>
<td>sp_random_<strong>Rick</strong></td>
</tr>
<tr>
<td>5</td>
<td>sp_random_<strong>Jabba_the</strong></td>
</tr>
<tr>
<td>6</td>
<td>sp_random_<strong>Dany</strong></td>
</tr>
<tr>
<td>7</td>
<td>sp_constant</td>
</tr>
<tr>
<td>8</td>
<td>sp_ripley_art_<strong>Dany</strong></td>
</tr>
<tr>
<td>9</td>
<td>sp_ripley_art_<strong>Jabba_the</strong></td>
</tr>
<tr>
<td>10</td>
<td>sp_wakeup</td>
</tr>
</tbody>
</table>
</div>
<p>I have a list of Mapping Table in <strong>Sheet 2</strong> like below</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>-</th>
<th>A</th>
<th>B</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td><strong>Rick</strong></td>
<td><strong>Morty</strong></td>
</tr>
<tr>
<td>2</td>
<td><strong>Jabba_the</strong></td>
<td><strong>Hutt</strong></td>
</tr>
<tr>
<td>3</td>
<td><strong>Dany</strong></td>
<td><strong>Dragon</strong></td>
</tr>
</tbody>
</table>
</div>
<p>I wish to have a result in <strong>Sheet 1</strong>, in <strong>column B</strong>, like below</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>-</th>
<th>A</th>
<th>B</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>sp_abc_<strong>Rick</strong></td>
<td>sp_abc_<strong>Morty</strong></td>
</tr>
<tr>
<td>2</td>
<td>sp_abc_<strong>Jabba_the</strong></td>
<td>sp_abc_<strong>Hutt</strong></td>
</tr>
<tr>
<td>3</td>
<td>sp_abc_<strong>Dany</strong></td>
<td>sp_abc_<strong>Dragon</strong></td>
</tr>
<tr>
<td>4</td>
<td>sp_random_<strong>Rick</strong></td>
<td>sp_random_<strong>Morty</strong></td>
</tr>
<tr>
<td>5</td>
<td>sp_random_<strong>Jabba_the</strong></td>
<td>sp_random_<strong>Hutt</strong></td>
</tr>
<tr>
<td>6</td>
<td>sp_random_<strong>Dany</strong></td>
<td>sp_random_<strong>Dragon</strong></td>
</tr>
<tr>
<td>7</td>
<td>sp_constant</td>
<td>sp_constant</td>
</tr>
<tr>
<td>8</td>
<td>sp_ripley_art_<strong>Dany</strong></td>
<td>sp_ripley_art_<strong>Dragon</strong></td>
</tr>
<tr>
<td>9</td>
<td>sp_ripley_art_<strong>Jabba_the</strong></td>
<td>sp_ripley_art_<strong>Hutt</strong></td>
</tr>
<tr>
<td>10</td>
<td>sp_wakeup</td>
<td>sp_wakeup</td>
</tr>
</tbody>
</table>
</div>
<p>To give you a context of the number of rows. Sheet 1 will be bigger with more than 1000 rows. Sheet 2 (Mapping Table) is constant set of rows. Currently it is about 100 rows.</p>
| [
{
"answer_id": 74286300,
"author": "Mayukh Bhattacharya",
"author_id": 8162520,
"author_profile": "https://Stackoverflow.com/users/8162520",
"pm_score": 3,
"selected": true,
"text": "LOOKUP()"
},
{
"answer_id": 74286861,
"author": "Aung",
"author_id": 6249219,
"author_profile": "https://Stackoverflow.com/users/6249219",
"pm_score": 1,
"selected": false,
"text": "=IFERROR(CONCAT(MID(A1,1,MATCH(1,(CODE(MID(A1,ROW($Z$1:$Z$255),1))<90)*(CODE(MID(A1,ROW($Z$1:$Z$255),1))>=65),FALSE)-1),INDIRECT(CONCAT(\"sheet2!b\", MATCH(MID(A1, MATCH(1,(CODE(MID(A1,ROW($Z$1:$Z$255),1))<90)*(CODE(MID(A1,ROW($Z$1:$Z$255),1))>=65),FALSE), LEN(A1)), Sheet2!$A$1:Sheet2!$A$300, 0)))),A1)\n"
},
{
"answer_id": 74287776,
"author": "JvdV",
"author_id": 9758194,
"author_profile": "https://Stackoverflow.com/users/9758194",
"pm_score": 1,
"selected": false,
"text": "B1"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11337371/"
] |
74,285,041 | <p>I'm trying to change the value in <code>userInfo</code> with <code>userArray</code>. I tried to change the first value of dictionary by writing <code>Object.values(userInfo)[0] = userArray[0]</code> but it didn't work. Is there another way to change values in a dictionary?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let userInfo = {'John': money(),'Mary': money(),'Bob': money()}
console.log('Before Dictionary:',userInfo)
let total = 0
let userArray = Object.values(userInfo); //To get dictionary values into array
userArray.forEach(doubleMoney) //Multiply array values by 2
function money(){
randomMoney = Math.floor(Math.random() * 1000000);
return randomMoney
}
function doubleMoney(element,index,array){
array[index] = element * 2
}
Object.values(userInfo)[0] = userArray[0] //Change the first value of dict to first value of array
console.log('Mutiplied array: ',userArray)
console.log('After Dictionary: ',userInfo);</code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74286300,
"author": "Mayukh Bhattacharya",
"author_id": 8162520,
"author_profile": "https://Stackoverflow.com/users/8162520",
"pm_score": 3,
"selected": true,
"text": "LOOKUP()"
},
{
"answer_id": 74286861,
"author": "Aung",
"author_id": 6249219,
"author_profile": "https://Stackoverflow.com/users/6249219",
"pm_score": 1,
"selected": false,
"text": "=IFERROR(CONCAT(MID(A1,1,MATCH(1,(CODE(MID(A1,ROW($Z$1:$Z$255),1))<90)*(CODE(MID(A1,ROW($Z$1:$Z$255),1))>=65),FALSE)-1),INDIRECT(CONCAT(\"sheet2!b\", MATCH(MID(A1, MATCH(1,(CODE(MID(A1,ROW($Z$1:$Z$255),1))<90)*(CODE(MID(A1,ROW($Z$1:$Z$255),1))>=65),FALSE), LEN(A1)), Sheet2!$A$1:Sheet2!$A$300, 0)))),A1)\n"
},
{
"answer_id": 74287776,
"author": "JvdV",
"author_id": 9758194,
"author_profile": "https://Stackoverflow.com/users/9758194",
"pm_score": 1,
"selected": false,
"text": "B1"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19553954/"
] |
74,285,043 | <p>I'm trying to switch every odd index character with the nearest even index character to it in a string.</p>
<pre class="lang-java prettyprint-override"><code>public class A3_Q1 {
public static void main(String... args) {
System.out.print("Enter the messgae you want to be coded: ");
Scanner in = new Scanner(System.in);
String msg = in.nextLine();
in.close();
msg = msg.trim();
char msg1[] = msg.toCharArray();
int index = 0;
while (index<msg.length()) {
msg1[index] = msg1[++index];
index++;
}
System.out.print(msg1);
}
}
</code></pre>
<p>I tried searching and asking more experienced friends what's wrong but we don't know bare with us all compsci freshmen</p>
| [
{
"answer_id": 74285137,
"author": "oleg.cherednik",
"author_id": 3461397,
"author_profile": "https://Stackoverflow.com/users/3461397",
"pm_score": -1,
"selected": false,
"text": "public static void main(String... args) {\n // Best practice: one instruction per one line\n System.out.print(\"Enter the message you want to be coded: \");\n\n // When using System.in you should not close the Scanner\n Scanner scan = new Scanner(System.in);\n String message = scan.nextLine().trim();\n // Best practice: move encoding logic to the separate method\n String convertedMessage = convert(message);\n System.out.println(convertedMessage);\n}\n\npublic static String convert(String str) {\n // String is immutable, so we have to use StringBuilder to build a new string\n StringBuilder buf = new StringBuilder();\n\n // does not matter what to use, I prefer for...loop\n for (int i = 0; i < str.length(); i++) {\n // do not forget to check case for the last index\n if (i == str.length() - 1 || i % 2 != 0)\n buf.append(str.charAt(i));\n else\n // here we have odd and not last index (just use the next one)\n buf.append(str.charAt(i + 1));\n }\n\n return buf.toString();\n}\n"
},
{
"answer_id": 74285570,
"author": "GAVD",
"author_id": 4983082,
"author_profile": "https://Stackoverflow.com/users/4983082",
"pm_score": 1,
"selected": false,
"text": "msg.length() -1"
},
{
"answer_id": 74285757,
"author": "rheza 555",
"author_id": 19229048,
"author_profile": "https://Stackoverflow.com/users/19229048",
"pm_score": -1,
"selected": false,
"text": "while (index<msg.length()) {\n msg1[index] = msg1[++index];\n index++;\n }\n"
},
{
"answer_id": 74285833,
"author": "Stefan Warminski",
"author_id": 7707631,
"author_profile": "https://Stackoverflow.com/users/7707631",
"pm_score": 0,
"selected": false,
"text": "++index"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20394394/"
] |
74,285,055 | <p>I have a function that gets <code>$homes</code> and <code>$member_id</code> as parameters. <code>$homes</code> is an array, <code>$member_id</code> is an integer.</p>
<pre><code>$homes = array( 'home13', 'home21', 'home34', 'home44' );
$member_id = 5;
</code></pre>
<p>How do I insert/update into the following DB?</p>
<p><a href="https://i.stack.imgur.com/aQWb1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aQWb1.png" alt="enter image description here" /></a></p>
<p>in the format:</p>
<pre><code>id home_name member_id
1 home13 5
2 home21 5
2 home34 5
2 home44 5
</code></pre>
<p>The function I used:</p>
<pre><code>public function store($homes, $member_id) {
foreach( $homes as $home ) {
$data[] = [ 'member_id' => $member_id, 'home_name' => $home ];
}
Home::insert( $data );
}
</code></pre>
<p>which works fine while inserting. However, I need to update all records for a given <code>$member_id</code> if the member_id already exists.</p>
<p>For example, if the <code>$member_id</code> is 5 and <code>$homes</code> is now <code>array( 'home54' )</code>, all other <code>home_name</code> that are previously stored for the <code>$member_id</code> 5 should be deleted. so that the following would only remain.</p>
<pre><code>id home_name member_id
1 home54 5
</code></pre>
| [
{
"answer_id": 74285132,
"author": "Harshana",
"author_id": 6952359,
"author_profile": "https://Stackoverflow.com/users/6952359",
"pm_score": 3,
"selected": true,
"text": "upsert()"
},
{
"answer_id": 74285539,
"author": "Leena Patel",
"author_id": 3348994,
"author_profile": "https://Stackoverflow.com/users/3348994",
"pm_score": 0,
"selected": false,
"text": "updateOrCreate"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5844795/"
] |
74,285,073 | <p>C++. I'm tring to get records from a file and store a sorted copy to a different file.</p>
<p>When I call the void sort(Student A[], int count) function with sort(newStudent, Student::getnStudents()); the program will crash if the second argument is over 3 (no errors/warnings).</p>
<p>After sort is called, some entries will have their classList[0] be complete gibberish symbols. Not sure why. I used const for the overloaded <. Commenting out sort has the program run as expected.</p>
<p><a href="https://i.stack.imgur.com/4W5Ks.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4W5Ks.png" alt="enter image description here" /></a></p>
<pre><code>#include <iostream>
#include <fstream> //for input output files
using namespace std;
#include "student.h"
#include "student.cpp"
// Inputs students from a text file using "lname fname n (list of n classes)" and sorts them to a seperate text file.
// Includes statistics about classes and the number of students taking each class.
//==================================================
void sort(Student A[], int count) { // Sort function // <- PROBLEM
for (int i=1; i<count; i++) {
for (int j=i; (j>0) && (A[j] < A[j-1]); j--) {
swap(A[j],A[j-1]);
}
}
}
//==================================================
int main(int argc, char *argv[]) {
if (argc != 4) {
cout << "Usage: " << argv[0] << " (input) (output) (# of elements)" << endl;
exit(1);
}
// Variables from argv. input/output location and max elements for Student
string inputFile = argv[1];
string outputFile = argv[2];
int maxStudents = atoi(argv[3]);
// Array to calculate class statistics
int numberClasses[6] = {0};
string classNames[6] = {"CSC121", "CSC127", "CSC275", "CSC375", "CSC377", "CSC381"};
// Array that is a copy of numberClasses
int numberClasses2[6];
// Most and least common classes
string mostCommon;
string leastCommon;
// Average number of classes per student
float avgClasses = 0.0;
// Student array
Student *newStudent;
newStudent = new Student[maxStudents];
//==================================================
ifstream inStream;
inStream.open(inputFile);
for (int i=0; i<maxStudents; i++) {
inStream>>newStudent[i];
}
inStream.close();
//==================================================
ofstream outStream;
outStream.open(outputFile);
for(int i=0; i<Student::getnStudents(); i++) { // TEST BEFORE
cout<<newStudent[i]<<endl;
}
sort(newStudent, Student::getnStudents()); // <- THIS IS THE PROBLEM
cout<<endl;
for(int i=0; i<Student::getnStudents(); i++) { // TEST AFTER
cout<<newStudent[i]<<endl;
}
for(int i=0; i<Student::getnStudents(); i++) {
outStream<<newStudent[i]<<endl;
}
outStream.close();
//==================================================
// Go through student array and their class list to increase the corresponding numberClasses array. EX: numberClasses[0] = classNames[0].
for(int i=0; i<Student::getnStudents(); i++) {
for (int j=0; j<newStudent[i].getnclasses(); j++) {
for (int k=0; k<6; k++) {
if (newStudent[i].getclassList(j) == classNames[k]) {numberClasses[k]++;}
}
}
}
// loop to print statistics of number of students taking each class
for (int i=0; i<6; i++) {
cout<<endl<<"Number of students taking "<<classNames[i]<<": "<<numberClasses[i];
}
//==================================================
for (int i=0; i<6; i++) {
numberClasses2[i] = numberClasses[i];
}
// Sort numberClasses2
for (int i=0; i<6; i++) {
for (int j=i; (j>0) && (numberClasses2[j] < numberClasses2[j-1]); j--) {
swap(numberClasses2[j],numberClasses2[j-1]);
}
}
// Compare numberClasses2 to numberClasses
for (int i=0; i<6; i++) {
if (numberClasses2[6-1] == numberClasses[i]) {
mostCommon = classNames[i];
}
if (numberClasses2[0] == numberClasses[i]) {
leastCommon = classNames[i];
}
}
// Calculate average classes taken per student
for (int i=0; i<Student::getnStudents(); i++) {
avgClasses += newStudent[i].getnclasses();
}
avgClasses = avgClasses/Student::getnStudents();
//==================================================
// Print rest of statistics
cout<<endl<<"Most common course: "<<mostCommon;
cout<<endl<<"Least common course: "<<leastCommon;
cout<<endl<<"Average number of courses taken, per student: "<<avgClasses;
return 0;
}
</code></pre>
<pre><code>#ifndef STUDENT_H
#define STUDENT_H
class Student {
public:
Student(); // Constructor
~Student(); // Destructor
// Accessors
string getclassList(int idx) { return classList[idx]; }
static int getnStudents(){return nStudents;}
int getnclasses(){return nclasses;}
// Overloaded I/O stream operators
friend istream& operator>> (istream&, Student&);
friend ostream& operator<< (ostream&, const Student&);
// Overloaded compare
friend bool operator < (const Student& S1, const Student& S2);
private:
string lname; // Person's last name
string fname; // Person's first name
int nclasses; // Number of courses enrolled in
string *classList; // An array of strings for names of courses enrolled in
// Static variables for # of students
static int nStudents;
};
int Student::nStudents = 0;
#endif
</code></pre>
<pre><code>#include "student.h"
using namespace std;
// Destructor
Student::~Student() {
delete[] classList;
classList = NULL;
}
// Default constructor
Student::Student() : fname("First"), lname("Last") {
classList = new string[6];
}
//==================================================
// Overloaded input
istream& operator >> (istream& inputStream, Student& S){
inputStream >> S.lname;
inputStream >> S.fname;
inputStream >> S.nclasses;
for (int i=0; i<S.nclasses; i++) {
inputStream >> S.classList[i];
}
if (S.nclasses>0) {Student::nStudents++;}
return inputStream;
}
// Overloaded output
ostream& operator<< (ostream& outputStream, const Student& S){
outputStream<<S.lname<<" "<<S.fname<<" "<<S.nclasses;
for (int i=0; i<S.nclasses; i++) {
outputStream<<" "<<S.classList[i];
}
return outputStream;
}
//==================================================
// Overloaded compare
bool operator < (const Student& S1, const Student& S2) {
if (S1.lname == S2.lname) {
return (S1.fname <= S2.fname);
}
return (S1.lname < S2.lname);
}
</code></pre>
<p>I've tried changing the sort function. Changing the overloaded < compare. Making lname public and comparing lname of two Student Arrays in the sort function without an overloaded <. This used to work, but then I changed something and now I can't figure out what else to do to fix it.</p>
| [
{
"answer_id": 74285132,
"author": "Harshana",
"author_id": 6952359,
"author_profile": "https://Stackoverflow.com/users/6952359",
"pm_score": 3,
"selected": true,
"text": "upsert()"
},
{
"answer_id": 74285539,
"author": "Leena Patel",
"author_id": 3348994,
"author_profile": "https://Stackoverflow.com/users/3348994",
"pm_score": 0,
"selected": false,
"text": "updateOrCreate"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20394511/"
] |
74,285,089 | <p>I'm trying to make lights in Unity for my house.</p>
<p>I've got 14 lights in my house, however, there is a small problem. This is because the lights are dimmed in some parts of the house and not in others. I have checked that all of the light components are the same (they are), and sometimes I get this flickering thing? I have wondered if it is because something isn't done correctly, like baking the house or whatnot.</p>
<p>Here is the light component:</p>
<p><a href="https://i.stack.imgur.com/x591M.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/x591M.png" alt="light component" /></a></p>
<p>Here is what the lights look like (they are red because I thought it would be easier to see):</p>
<p><a href="https://i.stack.imgur.com/2Ng5Y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2Ng5Y.png" alt="What the lights look like" /></a></p>
<p>As you can see, the lights just stop working as shown by the line</p>
<p>If anyone can help me that would be great!</p>
<p>Edit:
Rendering in Quality:</p>
<p><a href="https://i.stack.imgur.com/FoNhu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FoNhu.png" alt="Rendering quality" /></a></p>
| [
{
"answer_id": 74285132,
"author": "Harshana",
"author_id": 6952359,
"author_profile": "https://Stackoverflow.com/users/6952359",
"pm_score": 3,
"selected": true,
"text": "upsert()"
},
{
"answer_id": 74285539,
"author": "Leena Patel",
"author_id": 3348994,
"author_profile": "https://Stackoverflow.com/users/3348994",
"pm_score": 0,
"selected": false,
"text": "updateOrCreate"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19203149/"
] |
74,285,095 | <p>My <strong>input table</strong> looks like below</p>
<p><a href="https://i.stack.imgur.com/ubLbg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ubLbg.png" alt="enter image description here" /></a></p>
<p>From this table, I have to take each base_id and find out the parent hierarchy. My <strong>output table</strong> should be like below</p>
<p><a href="https://i.stack.imgur.com/lMTyg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lMTyg.png" alt="enter image description here" /></a></p>
<p>Here, for each base_id, the parent (parent_1), grand parent (parent_2)...(parent_n) Has to be calculated. Note that different base_id can have different hierarchy depth and the maximum level of depth is unknown.</p>
<p>I've written a script for this that I'm attaching below. It's working but the problem with my code is - I'm running a for loop for each base_id to find out its hierarchy. This is not very optimized since the no of base_ids can be 1 million plus. And God knows how much time it will take to run against Million+ ids.</p>
<pre><code>from pyspark.sql.types import StructType, StructField, StringType, IntegerType
import pyspark.sql.functions as F
from functools import reduce
from pyspark.sql import DataFrame
data2 = [('479', None),
('977', '666'),
('666', '479'),
('555', '678'),
('678', '977'),
]
schema = StructType([
StructField("base_id", StringType(), True),
StructField("parent_id", StringType(), True)
])
base_df = spark.createDataFrame(data=data2, schema=schema)
base_df.show()
def id_parent_relation():
itself_df = (
base_df
.filter(F.col("parent_id").isNull())
.selectExpr(
"base_id",
"base_id as parent_id",
"'itself' as retion_type"
)
)
related_df = base_df.filter(F.col("parent_id").isNotNull())
df_list = []
id_list = related_df.select("base_id").rdd.flatMap(lambda x: x).collect()
# print(id_list)
for base_id in id_list:
checker = True
iteration = 1
new_df = related_df.filter(F.col("base_id") == base_id)
while checker:
if iteration == 1:
new_df = new_df.withColumn("relationship_type", F.lit("parent_1"))
else:
new_df = (
new_df
.withColumnRenamed("base_id", "base_id_new")
.withColumnRenamed("parent_id", "parent_id_new")
)
new_df = (
new_df
.join(
related_df,
on=(related_df["base_id"] == new_df["parent_id_new"]),
how="left"
)
.select(
F.lit(base_id).alias("base_id"),
F.col("parent_id").alias("parent_id"),
)
.withColumn("relationship_type", F.lit("parent_{}".format(iteration)))
)
if new_df.filter(F.col("parent_id").isNotNull()).rdd.isEmpty():
checker = False
else:
iteration += 1
df_list.append(new_df)
union_df = reduce(DataFrame.unionAll, df_list)
union_df.show()
if __name__ == "__main__":
id_parent_relation()
</code></pre>
<p>I was hoping to somehow avoid the <strong>loops</strong> so that the script can be run for million records.</p>
<p>Please help me in this and thanks in advance!!!</p>
| [
{
"answer_id": 74287171,
"author": "botchniaque",
"author_id": 1680826,
"author_profile": "https://Stackoverflow.com/users/1680826",
"pm_score": 0,
"selected": false,
"text": "log(max_depth)"
},
{
"answer_id": 74288084,
"author": "chateaur",
"author_id": 7505894,
"author_profile": "https://Stackoverflow.com/users/7505894",
"pm_score": 1,
"selected": false,
"text": "# Data from original post\ndf0 = base_df.alias(\"df0\")\n\n# Keep tracks of joins number\ni = 1\n# Performs join as many times as necessary\nwhile (df0.filter(~F.isnull(F.col(\"df\" + str(i - 1) + \".parent_id\"))).count() > 0):\n # Create new alias\n df = base_df.alias(\"df\" + str(i))\n # Join\n df0 = df0.join(df, F.col(\"df\" + str(i - 1) + \".parent_id\") == F.col(\"df\" + str(i) + \".base_id\"), \"left\")\n i += 1\n\n# Delete singletons (479 in exemple)\ndf0 = df0.where(~F.isnull(F.col(\"df0.parent_id\")))\n\n# Create stack expression\nstack_expr = \"\"\nfor col in range(1, i):\n stack_expr += f\" df0.base_id, df{col}.base_id, 'parent_{col}',\"\n\n# Remove last ,\nstack_expr = stack_expr[:-1]\n\n# Stack to display columns as rows\ndf0.selectExpr(\"stack(\" + str(i) + \", \" + stack_expr + \") as (base_id, parent_id, relation_type)\") \\\n .where(\"parent_id is not null\") \\\n .show()\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11097152/"
] |
74,285,118 | <p>For instance, there is a piece of text</p>
<pre><code>[task,line:111] first
second
[demo,line:222] first
[test,line:333] first
[task,line:444] first
second
third
[task,line:555] first
</code></pre>
<p>I only want the lines with [task] and next lines until another [*] appears. Like below</p>
<pre><code>[task,line:111] first
second
[task,line:444] first
second
third
[task,line:555] first
</code></pre>
<p>How can I use awk or other tool in shell script to acomplish it?
I just know I can use</p>
<pre><code>awk '/regex/{print $0>"'$output'"}' $file
</code></pre>
<p>to get lines with [task] and redirect them to another file.Please help me with this.</p>
| [
{
"answer_id": 74285139,
"author": "anubhava",
"author_id": 548225,
"author_profile": "https://Stackoverflow.com/users/548225",
"pm_score": 1,
"selected": false,
"text": "awk"
},
{
"answer_id": 74285515,
"author": "tshiono",
"author_id": 8572380,
"author_profile": "https://Stackoverflow.com/users/8572380",
"pm_score": 3,
"selected": true,
"text": "awk '\n /^\\[/ { # the line starts with \"[\"\n if ($1 ~ /^\\[task/) f = 1 # set flag for \"[task\" line\n else f = 0 # otherwise reset the flag\n }\n f {print} # if flag is set, print the line\n' input_file > output_file\n"
},
{
"answer_id": 74286373,
"author": "Daweo",
"author_id": 10785975,
"author_profile": "https://Stackoverflow.com/users/10785975",
"pm_score": 1,
"selected": false,
"text": "AWK"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20394585/"
] |
74,285,162 | <p>I am trying to add a new select field to the page properties sidebar, but I am having trouble getting it to save the value.</p>
<p>This is what I have at the moment:</p>
<pre><code><?php
function addMyMeta() {
add_meta_box( 'my_custom_metabox', 'My Meta', 'setMyMeta', 'page', 'side', 'default' );
}
add_action( 'add_meta_boxes', 'addMyMeta' );
function setMyMeta() {
global $page;
$value = get_post_meta( $page->ID, 'my_custom_metabox', true );
?>
<fieldset>
<select name="my_custom_metabox" id="my_custom_metabox" autocomplete="off">
<option value="">Default</option>
<option value="my-value" <?php if($value == 'my-value') {echo ' selected ';}; ?>>My Value</option>
</select>
</fieldset>
<?php
}
function saveMyMeta( $page_id, $page ) {
if ( !isset( $_POST['my_custom_metabox'] ) ) {
update_post_meta( $page->ID, 'my_custom_metabox', $_POST['my_custom_metabox'] );
}
}
add_action( 'save_post', 'saveMyMeta', 1, 2 );
?>
</code></pre>
| [
{
"answer_id": 74285139,
"author": "anubhava",
"author_id": 548225,
"author_profile": "https://Stackoverflow.com/users/548225",
"pm_score": 1,
"selected": false,
"text": "awk"
},
{
"answer_id": 74285515,
"author": "tshiono",
"author_id": 8572380,
"author_profile": "https://Stackoverflow.com/users/8572380",
"pm_score": 3,
"selected": true,
"text": "awk '\n /^\\[/ { # the line starts with \"[\"\n if ($1 ~ /^\\[task/) f = 1 # set flag for \"[task\" line\n else f = 0 # otherwise reset the flag\n }\n f {print} # if flag is set, print the line\n' input_file > output_file\n"
},
{
"answer_id": 74286373,
"author": "Daweo",
"author_id": 10785975,
"author_profile": "https://Stackoverflow.com/users/10785975",
"pm_score": 1,
"selected": false,
"text": "AWK"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5369794/"
] |
74,285,167 | <p>This is my Code `</p>
<pre><code>from attr import attr
import requests
from bs4 import BeautifulSoup
import csv
datas = []
key = 'sepatu'
jenis = 'teplek'
url = 'https://website.com/search/?term={}+{}'.format(key,jenis)
headers = {
'user-agent' : 'Mozilla/5.0 (X11; Linux x86_64; rv:106.0) Gecko/20100101 Firefox/106.0'
}
req = requests.get(url, headers=headers)
soup = BeautifulSoup (req.text, 'html.parser')
sepatu = soup.find_all('div', 'element_1')
for it in sepatu:
harga = it.find('div','element').__str__
datas.append([harga])
hasil = ['Harga']
write = csv.writer(open('result/{}_{}.csv'.format(key,jenis), 'w', newline=''))
write.writerow (hasil)
for d in datas: write.writerow(d)
</code></pre>
<p>this is Output from this code</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Column A</th>
</tr>
</thead>
<tbody>
<tr>
<td><bound method Tag.<strong>unicode</strong> of Rp 88.000 </div>></td>
</tr>
<tr>
<td><bound method Tag.<strong>unicode</strong> of Rp 200.000 ></td>
</tr>
</tbody>
</table>
<p>how to turn that output to this output</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Column A</th>
</tr>
</thead>
<tbody>
<tr>
<td>Rp 88.000</td>
</tr>
<tr>
<td>Rp 200.000</td>
</tr>
</tbody>
</table>
</div>
<p>i was try
<code>harga = it.find('div','element').__str__</code> to <code>harga = it.find('div','element').text</code> but i got error <code>AttributeError: 'NoneType' object has no attribute 'text'</code></p>
<p>i try to learn web scraping python selenium but i got block by output into text and i expecting i want all the output into text</p>
| [
{
"answer_id": 74287343,
"author": "Eugeny Okulik",
"author_id": 12023661,
"author_profile": "https://Stackoverflow.com/users/12023661",
"pm_score": 0,
"selected": false,
"text": "element_1"
},
{
"answer_id": 74289890,
"author": "indrarasendriya",
"author_id": 19976898,
"author_profile": "https://Stackoverflow.com/users/19976898",
"pm_score": 2,
"selected": true,
"text": "harga = soup.find(\"div\", {\"class\": \"db gM ei b hE be f16-360-o ff vb uT ellipsis-1\"}).text\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20040434/"
] |
74,285,172 | <p>This is probably super simple but I just cannot figure out how to google for that.</p>
<p>What I have is:</p>
<pre><code>data class Post(val id: String)
val ids = listOf("1", "5", "19")
val posts = listOf<Post>(post1, post2, post3 etc)
</code></pre>
<p>now I want to filter posts list with the ids list.
This is how I filter one id:</p>
<pre><code>val output = posts.filter{ it.id == ids[0]}
</code></pre>
<p>but how do I filter for all the items in "ids" list?</p>
| [
{
"answer_id": 74285392,
"author": "Lucas.K",
"author_id": 19115089,
"author_profile": "https://Stackoverflow.com/users/19115089",
"pm_score": 2,
"selected": false,
"text": "val output = posts.filter { post -> ids.any { id -> id == post.id } }\n"
},
{
"answer_id": 74286220,
"author": "deHaar",
"author_id": 1712135,
"author_profile": "https://Stackoverflow.com/users/1712135",
"pm_score": 2,
"selected": false,
"text": "Post"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7735807/"
] |
74,285,175 | <pre><code>`import numpy as np
import matplotlib.pyplot as plt
import scipy
c=299792458 #speed of light in nanometers per second
h=6.62607015e-34 #plank's constant in m^2 kg per s
kB=1.380649e-23 #Boltzmann's constant in m^2 kg per s^2 K
π=np.pi
def F(λ,n):
return ((2*π*h*c**2)/λ**5)*(1/(np.exp((h*c)/(λ*kB*n))-1))
def integrand0(λ):
return F(λ,10800)
T=np.linspace(3000,12000,46)
import scipy.integrate as integrate
for n in T:
def integrand(λ):
return F(λ,n)
mU=-2.5*(np.log10(integrate.quad(integrand,325e-9,395e-9))-np.log10(integrate.quad(integrand0,325e-9,395e-9)))
print('T=',n,'mU=',mU[0])
print(mU[0])
</code></pre>
<p>I'm able to see what the different values of mU are for the different n, and checked this with other code, but when I try to print mU[0] outside of the for loop, I just get a scalar (the final value) instead of a list, how do I make sure the different values get binned into the elements of an array?</p>
| [
{
"answer_id": 74285392,
"author": "Lucas.K",
"author_id": 19115089,
"author_profile": "https://Stackoverflow.com/users/19115089",
"pm_score": 2,
"selected": false,
"text": "val output = posts.filter { post -> ids.any { id -> id == post.id } }\n"
},
{
"answer_id": 74286220,
"author": "deHaar",
"author_id": 1712135,
"author_profile": "https://Stackoverflow.com/users/1712135",
"pm_score": 2,
"selected": false,
"text": "Post"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20376109/"
] |
74,285,192 | <p>Not sure if this is the right place to ask this:</p>
<p>How do programs written in c++ run on other computers if you don't write them specifically to do that? I saw something about not just sending the .exe, but also sending other things with it?</p>
<p>Is there a high level programming language that is as fast or nearly as fast (in run speed) as c++ while also being platform independent?</p>
<p>See above.</p>
| [
{
"answer_id": 74285392,
"author": "Lucas.K",
"author_id": 19115089,
"author_profile": "https://Stackoverflow.com/users/19115089",
"pm_score": 2,
"selected": false,
"text": "val output = posts.filter { post -> ids.any { id -> id == post.id } }\n"
},
{
"answer_id": 74286220,
"author": "deHaar",
"author_id": 1712135,
"author_profile": "https://Stackoverflow.com/users/1712135",
"pm_score": 2,
"selected": false,
"text": "Post"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20394729/"
] |
74,285,210 | <p>i wanted to ask that if in SQL I can do like JOIN ON CASE WHEN, is there a way to do this in Pandas?</p>
<pre><code>disease = [
{"City":"CH","Case_Recorded":5300,"Recovered":2839,"Deaths":2461},
{"City":"NY","Case_Recorded":1311,"Recovered":521,"Deaths":790},
{"City":"TX","Case_Recorded":1991,"Recovered":1413,"Deaths":578},
{"City":"AT","Case_Recorded":3381,"Recovered":3112,"Deaths":269},
{"City":"TX","Case_Recorded":3991,"Recovered":2810,"Deaths":1311},
{"City":"LA","Case_Recorded":2647,"Recovered":2344,"Deaths":303},
{"City":"LA","Case_Recorded":4410,"Recovered":3344,"Deaths":1066}
]
region = {"North": ["AT"], "West":["TX","LA"]}
</code></pre>
<p>So what i have is 2 dummy dict and i have already converted it to become dataframe, first is the name of the cities with the case,and I'm trying to figure out which region the cities belongs to.</p>
<pre><code>Region|City
North|AT
West|TX
West|LA
None|NY
None|CH
</code></pre>
<p>So what i thought in SQL was using left on case when, and if the result is null when join with North region then join with West region.
But if there are 15 or 30 region in some country, it'd be problems i think</p>
| [
{
"answer_id": 74285377,
"author": "humphrey chan",
"author_id": 14206510,
"author_profile": "https://Stackoverflow.com/users/14206510",
"pm_score": 0,
"selected": false,
"text": "disease = [\n{\"City\":\"CH\",\"Case_Recorded\":5300,\"Recovered\":2839,\"Deaths\":2461},\n{\"City\":\"NY\",\"Case_Recorded\":1311,\"Recovered\":521,\"Deaths\":790},\n{\"City\":\"TX\",\"Case_Recorded\":1991,\"Recovered\":1413,\"Deaths\":578},\n{\"City\":\"AT\",\"Case_Recorded\":3381,\"Recovered\":3112,\"Deaths\":269},\n{\"City\":\"TX\",\"Case_Recorded\":3991,\"Recovered\":2810,\"Deaths\":1311},\n{\"City\":\"LA\",\"Case_Recorded\":2647,\"Recovered\":2344,\"Deaths\":303},\n{\"City\":\"LA\",\"Case_Recorded\":4410,\"Recovered\":3344,\"Deaths\":1066}\n]\n\nregion = [\n{'City':'AT','Region':\"North\"},\n{'City':'TX','Region':\"West\"},\n{'City':'LA','Region':\"West\"}\n]\n\ndf = pd.DataFrame(disease)\ndf_reg = pd.DataFrame(region)\n\ndf.merge( df_reg , on = 'City' , how = 'left' )\n"
},
{
"answer_id": 74285402,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 2,
"selected": true,
"text": "#get City without duplicates\ndf1 = pd.DataFrame(disease)[['City']].drop_duplicates()\n\n#create DataFrame from region dictionary\nregion = {\"North\": [\"AT\"], \"West\":[\"TX\",\"LA\"]}\ndf2 = pd.DataFrame([(k, x) for k, v in region.items() for x in v], \n columns=['Region','City'])\n\n#append not matched cities to df2\nout = pd.concat([df2, df1[~df1['City'].isin(df2['City'])]])\nprint (out)\n Region City\n0 North AT\n1 West TX\n2 West LA\n0 NaN CH\n1 NaN NY\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7859524/"
] |
74,285,213 | <p>For instance in this website: <a href="https://rads.stackoverflow.com/amzn/click/com/B07FFH8F9V" rel="nofollow noreferrer" rel="nofollow noreferrer">https://www.amazon.com/Lexani-LXUHP-207-All-Season-Radial-Tire-245/dp/B07FFH8F9V/</a></p>
<p>So I say "inspect" and I find the element that I'm interested:</p>
<pre><code><span id="productTitle" class="a-size-large product-title-word-break"> Lexani LXUHP-207 Performance Radial Tire - 245/45R18 100W </span>
</code></pre>
<p>Here's the deal, I want to copy the <strong>entire</strong> thing. Not just the "Lexani LXUHP-207 Performance Radial Tire - 245/45R18 100W" text title of the product. Can someone tell me how can I do this in beatifulsoup or rvest?</p>
<p>I am learning Python and R and I tried to dig it in but couldn't get a raw result.</p>
| [
{
"answer_id": 74285377,
"author": "humphrey chan",
"author_id": 14206510,
"author_profile": "https://Stackoverflow.com/users/14206510",
"pm_score": 0,
"selected": false,
"text": "disease = [\n{\"City\":\"CH\",\"Case_Recorded\":5300,\"Recovered\":2839,\"Deaths\":2461},\n{\"City\":\"NY\",\"Case_Recorded\":1311,\"Recovered\":521,\"Deaths\":790},\n{\"City\":\"TX\",\"Case_Recorded\":1991,\"Recovered\":1413,\"Deaths\":578},\n{\"City\":\"AT\",\"Case_Recorded\":3381,\"Recovered\":3112,\"Deaths\":269},\n{\"City\":\"TX\",\"Case_Recorded\":3991,\"Recovered\":2810,\"Deaths\":1311},\n{\"City\":\"LA\",\"Case_Recorded\":2647,\"Recovered\":2344,\"Deaths\":303},\n{\"City\":\"LA\",\"Case_Recorded\":4410,\"Recovered\":3344,\"Deaths\":1066}\n]\n\nregion = [\n{'City':'AT','Region':\"North\"},\n{'City':'TX','Region':\"West\"},\n{'City':'LA','Region':\"West\"}\n]\n\ndf = pd.DataFrame(disease)\ndf_reg = pd.DataFrame(region)\n\ndf.merge( df_reg , on = 'City' , how = 'left' )\n"
},
{
"answer_id": 74285402,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 2,
"selected": true,
"text": "#get City without duplicates\ndf1 = pd.DataFrame(disease)[['City']].drop_duplicates()\n\n#create DataFrame from region dictionary\nregion = {\"North\": [\"AT\"], \"West\":[\"TX\",\"LA\"]}\ndf2 = pd.DataFrame([(k, x) for k, v in region.items() for x in v], \n columns=['Region','City'])\n\n#append not matched cities to df2\nout = pd.concat([df2, df1[~df1['City'].isin(df2['City'])]])\nprint (out)\n Region City\n0 North AT\n1 West TX\n2 West LA\n0 NaN CH\n1 NaN NY\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17137428/"
] |
74,285,221 | <p>How can i make the table responsive with fixed header? means it scrolls when reaches maximum viewpoint. Well, i don't want to scroll the whole page on reaching max viewpoint instead i want table to be scrolled. Also fixed header is important. I tried with box-sizing: border-box; and overflow-x:scroll;but it didn't worked , help me to create a responsive table. Thanks.</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>table{
border-collapse: separate;
border-spacing: 0;
width: 100%;
box-sizing: border-box;
}
thead,tbody{
box-sizing: border-box;
overflow: auto;
}
th,td{
padding: 6px 15px;
}
th{
background: #42444e;
color: #fff;
text-align: left;
position: static;
top: 50px;
}
tbody tr td img{
flex-wrap: wrap;
pointer-events: none;
-moz-user-select: none;
-webkit-user-select: none;
user-select: none;
width: 30px;
height: 30px;
float: none;
display:block;
object-fit: fill;
border-radius: 10%;
}
tr:first-child th:first-child {
border-top-left-radius: 6px;
}
tr:first-child th:last-child {
border-top-right-radius: 6px;
}
td{
border-right: 1px solid #c6c9cc;
border-bottom: 1px solid #c6c9cc;
}
td:first-child {
border-left: 1px solid #c6c9cc;
}
tr:nth-child(even) td {
background: #eaeaed;
}
tr:last-child td:first-child {
border-bottom-left-radius: 6px;
}
tr:last-child td:last-child {
border-bottom-right-radius: 6px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
<thead>
<tr>
<th>Image</th>
<th>ID</th>
<th>Date</th>
<th>Name</th>
<th>Email</th>
<th>Phone no.</th>
<th>Role</th>
</tr>
</thead>
<tbody>
<tr>
<td><img src="img/4.jpeg"></td>
<td>1</td>
<td>445445564</td>
<td>Umann goswami</td>
<td>Umanngoswami@gmail.com</td>
<td>9999672450</td>
<td>Admin</td>
</tr>
<tr>
<td><img src="img/4.jpeg"></td>
<td>1</td>
<td>445445564</td>
<td>Umann goswami</td>
<td>Umanngoswami@gmail.com</td>
<td>9999672450</td>
<td>Admin</td>
</tr>
<tr>
<td><img src="img/4.jpeg"></td>
<td>1</td>
<td>445445564</td>
<td>Umann goswami</td>
<td>Umanngoswami@gmail.com</td>
<td>9999672450</td>
<td>Admin</td>
</tr>
<tr>
<td><img src="img/4.jpeg"></td>
<td>1</td>
<td>445445564</td>
<td>Umann goswami</td>
<td>Umanngoswami@gmail.com</td>
<td>9999672450</td>
<td>Admin</td>
</tr>
</thead>
</table></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74285744,
"author": "MAYUR SANCHETI",
"author_id": 12238257,
"author_profile": "https://Stackoverflow.com/users/12238257",
"pm_score": 1,
"selected": false,
"text": " .fixTable {\n overflow-y: auto;\n height: 110px;\n }\n .fixTable thead th {\n position: sticky;\n top: 0;\n }\n table {\n border-collapse: collapse; \n width: 100%;\n }\n th,\n td {\n padding: 8px 15px;\n border: 2px solid #529432;\n }\n th {\n background: #060606;\n }\n ::-webkit-scrollbar {\n -webkit-appearance: none;\n }\n ::-webkit-scrollbar:vertical {\n width: 12px;\n }\n ::-webkit-scrollbar:horizontal {\n height: 12px;\n }\n ::-webkit-scrollbar-thumb {\n background-color: rgba(0, 0, 0, .5);\n border-radius: 10px;\n border: 2px solid #ffffff;\n }\n ::-webkit-scrollbar-track {\n border-radius: 10px;\n background-color: #ffffff;\n }"
},
{
"answer_id": 74287900,
"author": "MrPatel2021",
"author_id": 19671394,
"author_profile": "https://Stackoverflow.com/users/19671394",
"pm_score": 1,
"selected": true,
"text": "codepan"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19171988/"
] |
74,285,222 | <p>hi guys im currently learning c and i have to pass a struct between multiple files for my project in uni . no matter what i do i keep getting errors when i try to pass a struct to a function. i have tired moving the function between being a global variable in main.c and i have tried putting it in a .h file, but i cannot figure it out, i keep hitting the same error messages when i try to gcc it . im having no problems using it in my main file but passing my variable to my functions in external files is where its getting errors i i will include my files that are relevant and my error messages when i gcc it. any help will be much appreciated cheers .</p>
<p>main.c</p>
<pre><code>int main( int argc, char *argv[] ) {
const int bufferSize=10;
int const nBuffer = 50;
char iptName [nBuffer];
empInfo* info;
info = (empInfo*)malloc(bufferSize * sizeof (empInfo));
if (info == NULL){
printf("*malloc* array not allocated\n");
}
printf("malloc worked");
nameFinderPrinter(iptName,info,bufferSize);
return;
}
</code></pre>
<p>fileFunctions.c</p>
<pre><code>void nameFinderPrinter(char name[],empInfo* info, int size) {
bool nameTF;
for (int i = 0; i < size; i++){
if (strcmp(name, info[i].names )== 0);
printf("%s age is %d wage is %f\n", info[i].names, info[i].ages, info[i].wages);
nameTF=true;
}
if(nameTF ==false){
printf("%s could not be found\n",name);}
return;
}
</code></pre>
<p>struct.h</p>
<pre><code>typedef struct employeeInfo
{
char names[50];
int ages;
float wages;
} empInfo;
</code></pre>
<p>error message on gcc</p>
<pre><code> In file included from main.c:7:
struct.h:1:17: error: redefinition of 'struct employeeInfo'
1 | typedef struct employeeInfo
| ^~~~~~~~~~~~
In file included from fileFunctions.h:7,
from main.c:6:
struct.h:1:17: note: originally defined here
1 | typedef struct employeeInfo
| ^~~~~~~~~~~~
struct.h:6:3: error: conflicting types for 'empInfo'; have 'struct employeeInfo'
6 | } empInfo;
| ^~~~~~~
struct.h:6:3: note: previous declaration of 'empInfo' with type 'empInfo' {aka 'struct employeeInfo'}
6 | } empInfo;
| ^~~~~~~
main.c: In function 'main':
main.c:86:29: warning: passing argument 2 of 'nameFinderPrinter' from incompatible pointer type [-Wincompatible-pointer-types]
86 | nameFinderPrinter(iptName,info,bufferSize);
| ^~~~
| |
| empInfo * {aka struct employeeInfo *}
fileFunctions.h:11:45: note: expected 'empInfo *' {aka 'struct employeeInfo *'} but argument is of type 'empInfo *' {aka 'struct employeeInfo *'}
11 | void nameFinderPrinter(char name[],empInfo* info, int size);
</code></pre>
<p>i have tried using pointers to 'info[10]' and rewriting how i pass it to the function in every way i can think of only way that works is to send the internal information of the struct bit by bit like 'info[i].name' i have attempted to make info a global variable and accessing it in the function globally. i am sorry if its messy i am still getting used to how to properly present my code on here and in general</p>
| [
{
"answer_id": 74287029,
"author": "Tenobaal",
"author_id": 18861247,
"author_profile": "https://Stackoverflow.com/users/18861247",
"pm_score": 2,
"selected": true,
"text": "#ifndef INCLUDE_STRUCT_H\n#define INCLUDE_STRUCT_H\ntypedef struct employeeInfo \n{\n char names[50]; \n int ages;\n float wages; \n} empInfo; \n#endif\n"
},
{
"answer_id": 74294902,
"author": "tutomiko",
"author_id": 20401171,
"author_profile": "https://Stackoverflow.com/users/20401171",
"pm_score": 0,
"selected": false,
"text": "#pragma once"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18014747/"
] |
74,285,229 | <p>From several servers I would like to add keys like doc:1 and then doc:2 etc.</p>
<p>Now in order that the different servers do not try to add to, say, doc:2 at the same time, I thought there is some mechanism like "add to doc:{index}" and the index gets automatically bumped.</p>
<p>Is there some way to make that work?</p>
| [
{
"answer_id": 74287029,
"author": "Tenobaal",
"author_id": 18861247,
"author_profile": "https://Stackoverflow.com/users/18861247",
"pm_score": 2,
"selected": true,
"text": "#ifndef INCLUDE_STRUCT_H\n#define INCLUDE_STRUCT_H\ntypedef struct employeeInfo \n{\n char names[50]; \n int ages;\n float wages; \n} empInfo; \n#endif\n"
},
{
"answer_id": 74294902,
"author": "tutomiko",
"author_id": 20401171,
"author_profile": "https://Stackoverflow.com/users/20401171",
"pm_score": 0,
"selected": false,
"text": "#pragma once"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2386605/"
] |
74,285,234 | <p>I have a set of records in a table, with some records having invalid date. I wanted to ignore those invalid records and do a check with rest of the records. I framed a query like below but I don't find it working.</p>
<pre><code>select * from tbl_name i
where is_date(i.dob) and i.dob::date > CURRENT_DATE;
</code></pre>
<p>I got to know that sql doesn't short circuit so it also consider invalid record and end up in date/time out of range. Please help me alter this query in a way i could eliminate invalid dates and do date comparison on valid dates only.</p>
| [
{
"answer_id": 74286651,
"author": "a_horse_with_no_name",
"author_id": 330315,
"author_profile": "https://Stackoverflow.com/users/330315",
"pm_score": 2,
"selected": false,
"text": "from (select ...) where ..."
},
{
"answer_id": 74291444,
"author": "Adrian Klaver",
"author_id": 7070613,
"author_profile": "https://Stackoverflow.com/users/7070613",
"pm_score": 0,
"selected": false,
"text": "WHERE"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7203487/"
] |
74,285,243 | <p>when I hit the delete method in postman I need to disable the data in MongoDB instead of completely delete. how to do that?</p>
<pre><code> router.delete("/admin/delete_profile/:id", async (req, res) => {
try {
await SomeModel.findByIdAndDelete(req.params.id.trim());
return send(res, RESPONSE.SUCCESS);
} catch (err) {
// res.status(404).send(err.message);
return send(res, RESPONSE.UNKNOWN_ERROR);
}
});
</code></pre>
<p>schema.js</p>
<pre><code>const { json } = require("body-parser");
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const SomeModelSchema = new Schema({
first_name: {
type: String,
required: true,
},
last_name: {
type: String,
required: true,
},
image: {
data: Buffer,
type: String,
required: true,
},
});
module.exports = mongoose.model("SomeModel", SomeModelSchema);
</code></pre>
| [
{
"answer_id": 74286651,
"author": "a_horse_with_no_name",
"author_id": 330315,
"author_profile": "https://Stackoverflow.com/users/330315",
"pm_score": 2,
"selected": false,
"text": "from (select ...) where ..."
},
{
"answer_id": 74291444,
"author": "Adrian Klaver",
"author_id": 7070613,
"author_profile": "https://Stackoverflow.com/users/7070613",
"pm_score": 0,
"selected": false,
"text": "WHERE"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14003858/"
] |
74,285,260 | <p>I have a user in the partner model that I was able to create via rust language.
Now, I have to link a user's ID from the res.partner model to the entry in the pos (Point of sale) model where the partner ID is a manyToOne field.</p>
<p>I'm using the xmlrpc crate to make the XMLRPC call to odoo to save the data. Here's what I have till now:</p>
<pre><code>se std::collections::btree_map::IntoValues;
use std::collections::BTreeMap;
use std::error::Error;
use std::{collections::HashMap, env};
use xmlrpc::http::{build_headers, check_response};
use xmlrpc::{Request, Transport, Value};
//Somewhere in a function below
let mut body = BTreeMap::new();
let mut partner_id_vec = BTreeMap::new();
// trying to create that manyToMany field for saving to odoo.
partner_id_vec.insert("3".to_string(), Value::Int(625));
// Creating the final struct for sending to the XMLRPC call, this works
body.insert("partner_id".to_string(), Value::Struct(partner_id_vec));
body.insert("amount_paid".to_string(), Value::Double(2000.00));
body.insert("amount_return".to_string(), Value::Double(0.00));
body.insert("amount_tax".to_string(), Value::Double(0.00));
body.insert("amount_total".to_string(), Value::Double(2000.00));
body.insert("name".to_string(), Value::from("jane doe"));
let order_val_str = Value::Array(vec![Value::Struct(body)]);
println!("order_val_str: {:?}", order_val_str);
let save_request = Request::new("execute_kw")
.arg("db name")
.arg(request_result.unwrap())
.arg("My API key".to_string())
.arg("pos.order")
.arg("create")
.arg(order_val_str);
println!("save_request: {:?}", save_request);
let result = save_request.call_url("https://my.odoo.com/xmlrpc/2/object");
</code></pre>
<p>Any help will be appreciated!</p>
| [
{
"answer_id": 74286651,
"author": "a_horse_with_no_name",
"author_id": 330315,
"author_profile": "https://Stackoverflow.com/users/330315",
"pm_score": 2,
"selected": false,
"text": "from (select ...) where ..."
},
{
"answer_id": 74291444,
"author": "Adrian Klaver",
"author_id": 7070613,
"author_profile": "https://Stackoverflow.com/users/7070613",
"pm_score": 0,
"selected": false,
"text": "WHERE"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11249646/"
] |
74,285,310 | <p>I need a Google Sheet function that will return the position of the last instance of a particular character. Basically, FIND, but starting on the right.</p>
<p>For example, for the data set below, I need to return the position of the last dash.</p>
<pre><code>ABC-DEF-GHI = 8
ABCD-EF-GH-IJK = 11
AB-C-DE-FGH-I-JK = 14
</code></pre>
<p>Thanks!</p>
<p>I don't know where to start. MID might work, but the file names are of different lengths and different formats. The files just generally end with - ***.png, and I need the asterisk. The string I need is also of variable length and can contain spaces (the string is the name of the student).</p>
| [
{
"answer_id": 74286651,
"author": "a_horse_with_no_name",
"author_id": 330315,
"author_profile": "https://Stackoverflow.com/users/330315",
"pm_score": 2,
"selected": false,
"text": "from (select ...) where ..."
},
{
"answer_id": 74291444,
"author": "Adrian Klaver",
"author_id": 7070613,
"author_profile": "https://Stackoverflow.com/users/7070613",
"pm_score": 0,
"selected": false,
"text": "WHERE"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20394777/"
] |
74,285,330 | <p>You know how you can create a new type by wrapping an existing type just because you want to avoid the <a href="https://doc.rust-lang.org/std/marker/trait.Copy.html" rel="nofollow noreferrer">Copy trait</a>?! For example, you have <code>bool</code> and you want a new type MyBool, you do <code>struct MyBool(bool);</code> and then you can use that to avoid the Copy trait.</p>
<p>What I want to know is how do you do it(create a new type, that is) for an array type? eg. for the type of <code>a</code> in <code>let a = [0; 4];</code> which is <code>[{integer}; 4]</code>, array of four integer elements. And can you do it for an array of a specific type X and of a specific len Y ? or, only for an array of type T (think generics) and with/without(?) a specific array length embedded in the new type ?</p>
<p>So, for <code>bool</code>, the following code doesn't show any warnings/errors(even if you run <code>cargo clippy</code> on it):</p>
<pre class="lang-rust prettyprint-override"><code>#![deny(clippy::all, clippy::pedantic, clippy::nursery, warnings, future_incompatible,
nonstandard_style, non_ascii_idents, clippy::restriction, rust_2018_compatibility,
rust_2021_compatibility, unused)]
#![allow(clippy::print_stdout, clippy::use_debug, clippy::missing_docs_in_private_items)]
#![allow(clippy::blanket_clippy_restriction_lints)] //workaround clippy
// might want to deny later:
//#![allow(clippy::default_numeric_fallback)] // might want to deny later!
//#![allow(clippy::dbg_macro)]
fn main() {
let mut has_spawned:bool=false;
//...
let handler=std::thread::spawn(move || {
println!("Before {has_spawned}!"); // false
has_spawned=true;
println!("Set {has_spawned}!"); // true
});
#[allow(clippy::unwrap_used)]
handler.join().unwrap();
println!("Current {has_spawned}!"); // false
}
</code></pre>
<p>But I want it to show me errors, thus, I use a new type for <code>bool</code>, <code>MyBool</code>:</p>
<pre class="lang-rust prettyprint-override"><code>#![deny(clippy::all, clippy::pedantic, clippy::nursery, warnings, future_incompatible,
nonstandard_style, non_ascii_idents, clippy::restriction, rust_2018_compatibility,
rust_2021_compatibility, unused)]
#![allow(clippy::print_stdout, clippy::use_debug, clippy::missing_docs_in_private_items)]
#![allow(clippy::blanket_clippy_restriction_lints)] //workaround clippy
#[derive(Debug)]
struct MyBool(bool);
fn main() {
let mut my_has_spawned:MyBool=MyBool(false);
//...
let handler=std::thread::spawn(move || {
println!("Before {my_has_spawned:?}!"); //MyBool(false)
//my_has_spawned=MyBool(true);
my_has_spawned.0=true;
println!("Set {my_has_spawned:?}!"); // MyBool(true)
});
#[allow(clippy::unwrap_used)]
handler.join().unwrap();
println!("Current {my_has_spawned:#?}!"); // value borrowed here after move, XXX: this is what
// I wanted!
}
</code></pre>
<p>and now it shows me exactly what I want to see:</p>
<pre class="lang-rust prettyprint-override"><code>error[E0382]: borrow of moved value: `my_has_spawned`
--> /home/user/sandbox/rust/copy_trait/gotcha1/copy_trait_thread_newtype/src/main.rs:20:24
|
10 | let mut my_has_spawned:MyBool=MyBool(false);
| ------------------ move occurs because `my_has_spawned` has type `MyBool`, which does not implement the `Copy` trait
11 | //...
12 | let handler=std::thread::spawn(move || {
| ------- value moved into closure here
13 | println!("Before {my_has_spawned:?}!"); //MyBool(false)
| -------------- variable moved due to use in closure
...
20 | println!("Current {my_has_spawned:#?}!"); // value borrowed here after move, XXX: this is what
| -------------------^^^^^^^^^^^^^^-------
| | |
| | value borrowed here after move
| in this macro invocation (#1)
|
::: /usr/lib/rust/1.64.0/lib/rustlib/src/rust/library/std/src/macros.rs:101:1
|
101 | macro_rules! println {
| -------------------- in this expansion of `println!` (#1)
...
106 | $crate::io::_print($crate::format_args_nl!($($arg)*));
| --------------------------------- in this macro invocation (#2)
|
::: /usr/lib/rust/1.64.0/lib/rustlib/src/rust/library/core/src/macros/mod.rs:906:5
|
906 | macro_rules! format_args_nl {
| --------------------------- in this expansion of `$crate::format_args_nl!` (#2)
For more information about this error, try `rustc --explain E0382`.
error: could not compile `copy_trait_thread_newtype` due to previous error
</code></pre>
<p>Similarly to the above, I want to use the new type for this array program that yields no warnings or errors(even through <code>cargo clippy</code>):</p>
<pre class="lang-rust prettyprint-override"><code>#![deny(clippy::all, clippy::pedantic, clippy::nursery, warnings, future_incompatible,
nonstandard_style, non_ascii_idents, clippy::restriction, rust_2018_compatibility,
rust_2021_compatibility, unused)]
#![allow(clippy::print_stdout, clippy::use_debug, clippy::missing_docs_in_private_items)]
#![allow(clippy::blanket_clippy_restriction_lints)] //workaround clippy
// might want to deny later:
#![allow(clippy::default_numeric_fallback)] // might want to deny later!
#![allow(clippy::dbg_macro)]
//src: https://users.rust-lang.org/t/rust-book-suggestion-add-a-section-regarding-copy-vs-move/1549/2
fn foo(mut x: [i32; 4]) {
println!("x(before) = {:?}", x);
x = [1, 2, 3, 4];
println!("x(after) = {:?}", x);
}
//src: https://stackoverflow.com/a/58119924/19999437
fn print_type_of<T>(_: &T) {
//println!("{}", std::any::type_name::<T>());
println!("{}", core::any::type_name::<T>());
}
//struct MyArray(array); //TODO: how?
fn main() {
let a = [0; 4];
//a.something();//method not found in `[{integer}; 4]`
//a=1;//so this is an array
//dbg!(a);
println!("{:#?}", print_type_of(&a)); // i32
foo(a); //sneakily copied! thanks Copy trait!
println!("a = {:?}", a);//unchanged, doh! but since it was just copied above, can use it here
//without errors!
}
</code></pre>
<p>output of that is:</p>
<pre><code>[i32; 4]
()
x(before) = [0, 0, 0, 0]
x(after) = [1, 2, 3, 4]
a = [0, 0, 0, 0]
</code></pre>
<p>So you see, I want a new type in order to avoid the copying of <code>a</code> when <code>foo(a);</code> is called, so that the computer/compiler can keep track of when I would introduce such easy bugs in my code, by error-ing instead, which happens only when <code>a</code> is moved(instead of just copied) when <code>foo(a);</code> is called.</p>
<p>Side note: do you think that this clippy lint <a href="https://github.com/rust-lang/rust-clippy/issues/9061" rel="nofollow noreferrer">https://github.com/rust-lang/rust-clippy/issues/9061</a> if implemented would be able to warn/err for me in such cases? That would be cool!</p>
<p>Personally I dislike the Copy trait for the only reason that it bypasses the borrow checker and thus allows you to write code that introduces subtle bugs. ie. you can keep using the stale value of the "moved"(copied) variable and the compiler won't complain.</p>
<p>Even if there are better ways to do what I want, please also do answer the title question: how I can wrap the array type in my own new type?</p>
| [
{
"answer_id": 74287216,
"author": "Ferdinand Keller",
"author_id": 13223443,
"author_profile": "https://Stackoverflow.com/users/13223443",
"pm_score": 0,
"selected": false,
"text": "Copy"
},
{
"answer_id": 74289317,
"author": "Jmb",
"author_id": 5397009,
"author_profile": "https://Stackoverflow.com/users/5397009",
"pm_score": 3,
"selected": true,
"text": "bool"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19999437/"
] |
74,285,344 | <p>I have a struct like this -</p>
<pre><code>pub struct A {
pub f: &str,
}
</code></pre>
<p>When I later try to assign a &str value to the struct using this -</p>
<pre><code>fn use(&self, t: &str){
let a = A {
f: self.t,
};
}
</code></pre>
<p>I get an error saying -</p>
<pre><code>pub f: &str,
| ^ expected named lifetime parameter
</code></pre>
<p>I then changed my struct to use named lifetime parameters -</p>
<pre><code>pub struct A<'i> {
pub f: &'i str,
}
</code></pre>
<p>But it now gives error -</p>
<pre><code>implicit elided lifetime not allowed here
note: assuming a `'static` lifetime...
help: indicate the anonymous lifetime
</code></pre>
<p>Can someone explain the second error and how can I fix it?</p>
| [
{
"answer_id": 74287216,
"author": "Ferdinand Keller",
"author_id": 13223443,
"author_profile": "https://Stackoverflow.com/users/13223443",
"pm_score": 0,
"selected": false,
"text": "Copy"
},
{
"answer_id": 74289317,
"author": "Jmb",
"author_id": 5397009,
"author_profile": "https://Stackoverflow.com/users/5397009",
"pm_score": 3,
"selected": true,
"text": "bool"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3621735/"
] |
74,285,353 | <p>So I am trying to move a div to the right inside flexbox.</p>
<p>I dont want to change justify-content to anything else, but I am trying to move the middle div to the right. However if I use margin and move it then the space around the whole parent div is also affected. Is it possible to move the middle div to the right without affecting the space of the whole div?</p>
<p>So far this solution kind of works- but the items will overlay on each other on smaller screen so this is not responsive at all:</p>
<pre><code>.item2 {
margin-left: 100px;
margin-right: -100px;
border: 1px solid red;
}
</code></pre>
<p>But it doesnt seem very elegant. Is there a way to do it with flexbox only?</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>.main {
display: flex;
flex-direction: row;
justify-content: space-around;
align-items: center;
}
.item1 {
border: 1px solid red;
}
.item2 {
margin-left: 100px;
margin-right: -100px;
border: 1px solid red;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main">
<div class="item1">
Item 1
</div>
<div class="item2">
Item 2
</div>
<div class="item1">
Item 3
</div>
</div></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74287216,
"author": "Ferdinand Keller",
"author_id": 13223443,
"author_profile": "https://Stackoverflow.com/users/13223443",
"pm_score": 0,
"selected": false,
"text": "Copy"
},
{
"answer_id": 74289317,
"author": "Jmb",
"author_id": 5397009,
"author_profile": "https://Stackoverflow.com/users/5397009",
"pm_score": 3,
"selected": true,
"text": "bool"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6653602/"
] |
74,285,354 | <p><br />
is there a way to achieve a PayPal like 'decimal-first' entry in Xamarin Forms?</p>
<p><a href="https://i.stack.imgur.com/xmBSz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xmBSz.png" alt="example from PayPal" /></a></p>
<p>I hope the screenshot is self explanatory. I basically want an instantaneous division of the input by 100. For an input of e.g. 3,85 I want it shown as<br />
0,03<br />
0,38<br />
3,85<br />
Is there a good way to implement this in Xamarin Forms?<br />
Tanks in advance</p>
| [
{
"answer_id": 74287216,
"author": "Ferdinand Keller",
"author_id": 13223443,
"author_profile": "https://Stackoverflow.com/users/13223443",
"pm_score": 0,
"selected": false,
"text": "Copy"
},
{
"answer_id": 74289317,
"author": "Jmb",
"author_id": 5397009,
"author_profile": "https://Stackoverflow.com/users/5397009",
"pm_score": 3,
"selected": true,
"text": "bool"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13998670/"
] |
74,285,435 | <p>Warning: Undefined array key 5081 in /customers/c/c/a/bhcjobs.com/httpd.www/wp-includes/nav-menu-template.php on line 210</p>
<p><a href="https://i.stack.imgur.com/20Ihr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/20Ihr.png" alt="Screenshot" /></a></p>
<pre><code> // Set up the $menu_item variables.
_wp_menu_item_classes_by_context( $menu_items );
$sorted_menu_items = array();
$menu_items_tree = array();
$menu_items_with_children = array();
foreach ( (array) $menu_items as $menu_item ) {
$sorted_menu_items[ $menu_item->menu_order ] = $menu_item;
$menu_items_tree[ $menu_item->ID ] = $menu_item->menu_item_parent;
if ( $menu_item->menu_item_parent ) {
$menu_items_with_children[ $menu_item->menu_item_parent ] = 1;
}
// Calculate the depth of each menu item with children
foreach ( $menu_items_with_children as $menu_item_key => &$menu_item_depth ) {
$menu_item_parent = $menu_items_tree[ $menu_item_key ];
while ( $menu_item_parent ) {
$menu_item_depth = $menu_item_depth + 1;
$menu_item_parent = $menu_items_tree[ $menu_item_parent ];
}
}
}
</code></pre>
<p>Please help to fix this</p>
<p>I need help to fix this issue</p>
| [
{
"answer_id": 74287216,
"author": "Ferdinand Keller",
"author_id": 13223443,
"author_profile": "https://Stackoverflow.com/users/13223443",
"pm_score": 0,
"selected": false,
"text": "Copy"
},
{
"answer_id": 74289317,
"author": "Jmb",
"author_id": 5397009,
"author_profile": "https://Stackoverflow.com/users/5397009",
"pm_score": 3,
"selected": true,
"text": "bool"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20394864/"
] |
74,285,465 | <p>I have a class which has a private property.</p>
<pre><code>import {Socket} from 'socket.io-client';
export class SocketService {
private socket: Socket;
public initializeSocket() {
if(this.socket) { return; }
this.socket = // get a new Socket
this.socket.on('connect', () => this.processConnect() );
}
private processConnect() {
...
}
}
</code></pre>
<p>When write unit test for method <code>initializeSocket()</code>, how to validate that the <code>on</code> is called? Any suggestion would be appreciated!</p>
| [
{
"answer_id": 74298525,
"author": "Dmytro Demyanenko",
"author_id": 20265473,
"author_profile": "https://Stackoverflow.com/users/20265473",
"pm_score": 1,
"selected": false,
"text": "private processConnect()"
},
{
"answer_id": 74312367,
"author": "Kerwen",
"author_id": 7352168,
"author_profile": "https://Stackoverflow.com/users/7352168",
"pm_score": 0,
"selected": false,
"text": "it('test socket on',()=>{\n service['socket'] = tempSocket; // have to initialize it temply as spyOn need a object\n spyOn(service['socket'], 'on');\n service['socket'] = undefined;\n\n service.initializeSocket();\n\n expect(service['socket'].on).toHaveBeenCalled();\n}\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7352168/"
] |
74,285,547 | <p>I created this <code>fetch</code> function in my React app:</p>
<pre><code> const getStatus = () => {
const fetchData = async () => {
const response = await fetch(`http://localhost:3000`);
const result = response.status;
console.log(result);
return result;
};
return fetchData();
};
</code></pre>
<p>I want then use this function like:</p>
<pre><code>getStatus() === 200 ? 'Do something' : 'Don't do something'
</code></pre>
<p>But now when I call function <code>getStatus()</code> it returns <code>undefined</code>?</p>
<p>How do I directly return something from <code>getStatus()</code> function, which I can use for e.g. a ternary operator?</p>
| [
{
"answer_id": 74298525,
"author": "Dmytro Demyanenko",
"author_id": 20265473,
"author_profile": "https://Stackoverflow.com/users/20265473",
"pm_score": 1,
"selected": false,
"text": "private processConnect()"
},
{
"answer_id": 74312367,
"author": "Kerwen",
"author_id": 7352168,
"author_profile": "https://Stackoverflow.com/users/7352168",
"pm_score": 0,
"selected": false,
"text": "it('test socket on',()=>{\n service['socket'] = tempSocket; // have to initialize it temply as spyOn need a object\n spyOn(service['socket'], 'on');\n service['socket'] = undefined;\n\n service.initializeSocket();\n\n expect(service['socket'].on).toHaveBeenCalled();\n}\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4822666/"
] |
74,285,555 | <p>I am making an e-store. I have the uid of logged-in user. I am trying to make a condition that if the logged in user uid is not equal to admin uid, then I do not want that user to go on the admin page. The useEffect runs infinite.</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> const navigate = useNavigate();
const user = localStorage.getItem("uid");
useEffect(() => {
if (user === 'at64ZIYgqaawRyCAkH6xMYBRNwS2') {
navigate('/admin')
}
else {
navigate('/home')
}
})</code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74285605,
"author": "Anh Lee",
"author_id": 13516576,
"author_profile": "https://Stackoverflow.com/users/13516576",
"pm_score": 0,
"selected": false,
"text": "useEffect(() => {\n\n//Todo\n\n}, [])\n"
},
{
"answer_id": 74286062,
"author": "N.SH",
"author_id": 11814486,
"author_profile": "https://Stackoverflow.com/users/11814486",
"pm_score": 0,
"selected": false,
"text": "useEffect(() => {\n\n if (user === 'at64ZIYgqaawRyCAkH6xMYBRNwS2') {\n navigate('/admin')\n }\n else {\n navigate('/home')\n }\n }, []) // this [] is dependencies array\n"
},
{
"answer_id": 74286201,
"author": "Drystan",
"author_id": 20182014,
"author_profile": "https://Stackoverflow.com/users/20182014",
"pm_score": 1,
"selected": false,
"text": "uid"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19100072/"
] |
74,285,655 | <p>I have method looks like:</p>
<pre><code>public Optional<UserDTO> getUser(String id) {
if (userRepository.findById(Integer.valueOf(id)).isPresent()) {
return userRepository.findById(Integer.parseInt(id))
.map(this::map);
}
throw new UserNotFoundException("User wasn't found");
}
</code></pre>
<p>But I want to make it with try{} catch(){} blocks, I've tried to make it like this:</p>
<pre><code>
public Optional<UserDTO> getUser(String id) {
try {
userRepository.findById(Integer.valueOf(id)).isPresent();
return userRepository.findById(Integer.parseInt(id))
.map(this::map);
} catch (UserNotFoundException userNotFoundException){
var message = "User wasn't found";
System.out.println(message);
}
}
</code></pre>
<p>but it had't thrown an exception in the case of wrong id and shown a mistake with an absence of return block.</p>
<p>Could you help me to find the possible solution?</p>
| [
{
"answer_id": 74285605,
"author": "Anh Lee",
"author_id": 13516576,
"author_profile": "https://Stackoverflow.com/users/13516576",
"pm_score": 0,
"selected": false,
"text": "useEffect(() => {\n\n//Todo\n\n}, [])\n"
},
{
"answer_id": 74286062,
"author": "N.SH",
"author_id": 11814486,
"author_profile": "https://Stackoverflow.com/users/11814486",
"pm_score": 0,
"selected": false,
"text": "useEffect(() => {\n\n if (user === 'at64ZIYgqaawRyCAkH6xMYBRNwS2') {\n navigate('/admin')\n }\n else {\n navigate('/home')\n }\n }, []) // this [] is dependencies array\n"
},
{
"answer_id": 74286201,
"author": "Drystan",
"author_id": 20182014,
"author_profile": "https://Stackoverflow.com/users/20182014",
"pm_score": 1,
"selected": false,
"text": "uid"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20388221/"
] |
74,285,667 | <p>I want to send a file along with json data to my end point, something like this:</p>
<pre><code>curl --location --request POST 'abc.com/upload'
--header 'Authorization: Bearer '
--header 'Content-Type: application/json'
--data-raw '{
"user": {"email":"abx@xyz.com"},
"options": {"process":"order_lines","selection":"price","tolerance":"loose","target":"transport_orders"},
"import-file": "/path/to/file.csv"
}'
</code></pre>
<p>I want to achieve something like this, how can I do this?</p>
| [
{
"answer_id": 74285815,
"author": "yeti",
"author_id": 5647853,
"author_profile": "https://Stackoverflow.com/users/5647853",
"pm_score": -1,
"selected": false,
"text": "<path-to-json-file>"
},
{
"answer_id": 74325926,
"author": "Misunderstood",
"author_id": 3813605,
"author_profile": "https://Stackoverflow.com/users/3813605",
"pm_score": 0,
"selected": false,
"text": "Content-Type: application/x-www-form-urlencoded"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4464531/"
] |
74,285,676 | <p>I have learned we can sum all(or filtered) columns like <code>price</code> from <a href="https://stackoverflow.com/q/8616343/10844937">this question</a>.</p>
<pre><code>ItemPrice.objects.aggregate(Sum('price'))
</code></pre>
<p>But is it possible for Django to sum non-numeric field's <strong>length</strong>, such as <code>CharField</code> or <code>JSONField</code>? A pseudocode is like following.</p>
<pre><code>User.objects.aggregate(Sum(len('username')))
</code></pre>
| [
{
"answer_id": 74285717,
"author": "ramwin",
"author_id": 3601654,
"author_profile": "https://Stackoverflow.com/users/3601654",
"pm_score": 3,
"selected": true,
"text": "from django.db.models.functions import Length\nfrom django.db.models import Sum\nUser.objects.annotate(l=Length(\"username\")).aggregate(Sum(\"l\"))\n"
},
{
"answer_id": 74285739,
"author": "Jack",
"author_id": 7307291,
"author_profile": "https://Stackoverflow.com/users/7307291",
"pm_score": 0,
"selected": false,
"text": "from django.db.models.functions import Length User.objects.aggregate(Sum(Length('username')))"
},
{
"answer_id": 74311271,
"author": "haojie",
"author_id": 10844937,
"author_profile": "https://Stackoverflow.com/users/10844937",
"pm_score": 0,
"selected": false,
"text": "Count"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10844937/"
] |
74,285,682 | <p>for each <code>claimNumbers</code> I want to generate the below expected output from the sample input shared below.</p>
<p>Input payload:</p>
<pre><code>{
"contactUpdateData": [
{
"claimNumbers": [
"12345",
"12346"
],
"channel": "Agent",
"updateData": {
"customer": {
"customerType": "individual",
"address": {
"Line1": "abc"
}
},
"contactpeople": [
{
"contactPersonType": "nominee"
}
],
"reportingfields": {
"schemetype": "pws"
}
}
}
]
}
</code></pre>
<p>Output Payload:</p>
<pre><code>{
"contactUpdateData":[
{
"cNumbers":"12345",
"channel":"Agent",
"updateData":{
"customer":{
"customerType":"abcde",
"address":{
"Line1":"abc"
}
},
"contactpeople":[
{
"contactPersonType":"nominee"
}
],
"reportingfields":{
"schemetype":"pws"
}
}
},
{
"claimNumbers":"12346",
"channel":"Agent",
"updateData":{
"customer":{
"customerType":"individual",
"address":{
"Line1":"abc"
}
},
"contactpeople":[
{
"contactPersonType":"nominee"
}
],
"reportingfields":{
"schemetype":"pws"
}
}
}
]
}
</code></pre>
<p>I want to understand how we can achieve in Mule 4 using foreach and DataWeave.</p>
| [
{
"answer_id": 74285717,
"author": "ramwin",
"author_id": 3601654,
"author_profile": "https://Stackoverflow.com/users/3601654",
"pm_score": 3,
"selected": true,
"text": "from django.db.models.functions import Length\nfrom django.db.models import Sum\nUser.objects.annotate(l=Length(\"username\")).aggregate(Sum(\"l\"))\n"
},
{
"answer_id": 74285739,
"author": "Jack",
"author_id": 7307291,
"author_profile": "https://Stackoverflow.com/users/7307291",
"pm_score": 0,
"selected": false,
"text": "from django.db.models.functions import Length User.objects.aggregate(Sum(Length('username')))"
},
{
"answer_id": 74311271,
"author": "haojie",
"author_id": 10844937,
"author_profile": "https://Stackoverflow.com/users/10844937",
"pm_score": 0,
"selected": false,
"text": "Count"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20395040/"
] |
74,285,683 | <pre><code>class Customer(models.Model):
pass
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='orders')
total_amount = models.DecimalField()
</code></pre>
<p>As you can see, a customer can have many orders.
What I want to know, how much amount one customer has spent so far.</p>
<pre><code>qs = Customer.objects.get(pk=OuterRef('customer').orders.all().aggregate(total=Sum('total_amount))
Order.objects.annotate(customer_total=Subquery(qs.values('total')[:1]))
</code></pre>
<p>But I am getting error</p>
<blockquote>
<p>ValueError: This queryset contains a reference to an outer query and may only be used in a subquery.</p>
</blockquote>
<p>My question is, can we Subquery a <strong>parent Model</strong> ? or i am doing something wrong ?</p>
| [
{
"answer_id": 74285717,
"author": "ramwin",
"author_id": 3601654,
"author_profile": "https://Stackoverflow.com/users/3601654",
"pm_score": 3,
"selected": true,
"text": "from django.db.models.functions import Length\nfrom django.db.models import Sum\nUser.objects.annotate(l=Length(\"username\")).aggregate(Sum(\"l\"))\n"
},
{
"answer_id": 74285739,
"author": "Jack",
"author_id": 7307291,
"author_profile": "https://Stackoverflow.com/users/7307291",
"pm_score": 0,
"selected": false,
"text": "from django.db.models.functions import Length User.objects.aggregate(Sum(Length('username')))"
},
{
"answer_id": 74311271,
"author": "haojie",
"author_id": 10844937,
"author_profile": "https://Stackoverflow.com/users/10844937",
"pm_score": 0,
"selected": false,
"text": "Count"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/967031/"
] |
74,285,693 | <p>powershell get-wmiobject wildcards - Batch File</p>
<p>I´m struggling with on batch file here.. The idea is to get the version of the applications installed on a remote pc, but instead of writing the full application name ( that can be a bit different from client to client) i want to use a Wildcard for it..</p>
<p>Unfortunantly GET-WmiObject operator, does not work the the parameter ( -like) as SQL..</p>
<p>The powershell command below works like i want , but when i add it the the batch file, it does not work...</p>
<p>Power Shell command that work :</p>
<pre><code>[tag:Get-WmiObject -ComputerName ##PCNAMEHERE## -Query "Select * From Win32_Product Where name Like 'McAfee%'" | select Name, Version]
</code></pre>
<p>Line on the batch program</p>
<pre><code>\[tag:get specific app with Wildcards !!!!! Need corrections !!!
Powershell.exe Get-WmiObject -ComputerName %CN% -Query Select \* From Win32_Product Where name Like ''McAfee%'' | select Name, Version \>\>%LOG%\]
</code></pre>
<p>Error that i get on the batch execution... Already try to play with " and ' but without success ...</p>
<p>Get-WmiObject : A positional parameter cannot be found that accepts argument '*'.
At line:1 char:1</p>
<ul>
<li>Get-WmiObject -ComputerName W1865C28 -Query Select * From Win32_Produ ...</li>
<li>
<pre><code> + CategoryInfo : InvalidArgument: (:) [Get-WmiObject], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.GetWmiObjectCommand
</code></pre>
</li>
</ul>
| [
{
"answer_id": 74288730,
"author": "js2010",
"author_id": 6654942,
"author_profile": "https://Stackoverflow.com/users/6654942",
"pm_score": 0,
"selected": false,
"text": "Powershell.exe \"Get-WmiObject -ComputerName %CN% Win32_Product | Where name -Like *mcafee* | select Name, Version >> %LOG%\"\n"
},
{
"answer_id": 74293844,
"author": "Toni",
"author_id": 19895159,
"author_profile": "https://Stackoverflow.com/users/19895159",
"pm_score": 1,
"selected": false,
"text": "-command"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20394137/"
] |
74,285,738 | <p>I have an array which contains 10 objects, called <code>emailThreads</code>.</p>
<p>I am trying to display these objects with next and previous button but its not working as expected.</p>
<pre><code> <Controls>
<Button onClick={previousEmail}>Previous Email</Button>
<SubjectDetails>
<Subject>SUBJECT</Subject>
<SubjectTitle>{emailThreads[emailIndex].subject}</SubjectTitle>
<SentAtDetails>Sent At {emailThreads[emailIndex].deliveredAt}</SentAtDetails>
</SubjectDetails>
<Button onClick={nextEmail}>Next Email</Button>
</Controls>
</code></pre>
<p>this is code for <code>previousEmail</code> and <code>nextEmail</code></p>
<pre><code> const [emailIndex, setEmailIndex] = useState(0);
const previousEmail = () => {
setEmailIndex((prevIndex) => {
prevIndex !== 0 ? prevIndex - 1 : prevIndex;
});
};
const nextEmail = () => {
setEmailIndex((prevIndex) => {
prevIndex !== emailThreads.length ? prevIndex + 1 : prevIndex;
});
};
</code></pre>
<p>when I click on the next email,</p>
<pre><code>TypeError: Cannot read properties of undefined (reading 'subject')
</code></pre>
<p>any help would be wonderful, thank you</p>
| [
{
"answer_id": 74288730,
"author": "js2010",
"author_id": 6654942,
"author_profile": "https://Stackoverflow.com/users/6654942",
"pm_score": 0,
"selected": false,
"text": "Powershell.exe \"Get-WmiObject -ComputerName %CN% Win32_Product | Where name -Like *mcafee* | select Name, Version >> %LOG%\"\n"
},
{
"answer_id": 74293844,
"author": "Toni",
"author_id": 19895159,
"author_profile": "https://Stackoverflow.com/users/19895159",
"pm_score": 1,
"selected": false,
"text": "-command"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4952770/"
] |
74,285,762 | <p>I have the following html table:</p>
<p><a href="https://i.stack.imgur.com/g8nWZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/g8nWZ.png" alt="enter image description here" /></a></p>
<p>Based on current day, only columns corresponding the particular day should be displayed.</p>
<p>For example, if today is Monday, except columns corresponding to Monday all others should be hidden:</p>
<p><a href="https://i.stack.imgur.com/tifbj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tifbj.png" alt="enter image description here" /></a></p>
<p>What I have tried is to employ the following js code to get the day of week and hide unhide a div (<a href="http://jsfiddle.net/L021zstr/" rel="nofollow noreferrer">jsfiddle</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>function injectDay() {
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',
'Friday', 'Saturday'];
var date = new Date();
document.querySelector('.dayContainer').innerHTML = days[date.getDay()];
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.table-responsive{
height:180px; width:50%;
overflow-y: auto;
border:2px solid #444;
}.table-responsive:hover{border-color:red;}
table{width:100%;}
td{padding:24px; background:#eee;}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><body onload="injectDay()">
<div>
<h3 class="dayContainer"></h3>
<table>
<tr>
<td>Time</td>
<td>Sunday</td>
<td>Monday</td>
<td>Tuesday</td>
<td>Wednesday</td>
<td>Thursday</td>
<td>Friday</td>
<td>Saturday</td>
<td>Sunday</td>
<td>Monday</td>
</tr>
<tr>
<td>8to9</td>
<td>df</td>
<td>rer</td>
<td>jkhj</td>
<td>er</td>
<td>dfdf</td>
<td>thh</td>
<td>trttt</td>
<td>dffs</td>
<td>dfd</td>
</tr>
<tr>
<td>9to10</td>
<td>fdf</td>
<td>jjj</td>
<td>hj</td>
<td>re</td>
<td>ffee</td>
<td>ffgs</td>
<td>juff</td>
<td>gfdd</td>
<td>hjj</td>
</tr>
<tr>
<td>10to11</td>
<td>fdf</td>
<td>gffg</td>
<td>gh</td>
<td>jjjj</td>
<td>fdf</td>
<td>kgfg</td>
<td>fdff</td>
<td>rrtt</td>
<td>ghfd</td>
</tr>
<tr>
<td>11to12</td>
<td>fdf</td>
<td>gg</td>
<td>gh</td>
<td>gfgf</td>
<td>fdf</td>
<td>trrr</td>
<td>rtrw</td>
<td>fdf</td>
<td>fdf</td>
</tr>
</table>
</div>
</body></code></pre>
</div>
</div>
</p>
<p>But I don't know how to hide/unhide columns of the table of interest.</p>
| [
{
"answer_id": 74288730,
"author": "js2010",
"author_id": 6654942,
"author_profile": "https://Stackoverflow.com/users/6654942",
"pm_score": 0,
"selected": false,
"text": "Powershell.exe \"Get-WmiObject -ComputerName %CN% Win32_Product | Where name -Like *mcafee* | select Name, Version >> %LOG%\"\n"
},
{
"answer_id": 74293844,
"author": "Toni",
"author_id": 19895159,
"author_profile": "https://Stackoverflow.com/users/19895159",
"pm_score": 1,
"selected": false,
"text": "-command"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19011139/"
] |
74,285,776 | <p>In an exercise I'm supposed to have a program that asks for multiple inputs and the program should delete the largest and smallest n numbers.</p>
<p>My attempt:</p>
<pre><code>
def outliers(lst, n):
new = sorted(lst)
for i in range(0, n):
del new[i]
del new[len(new) - i - 1]
return new
def main():
lst = []
n = int(input("Enter a non-zero number: "))
while n != 0:
lst.append(n)
n = int(input("Enter a non-zero number: "))
print(f"the list without the 2 outliers are: {outliers(lst, 2)}")
main()
</code></pre>
<p>Bug:</p>
<pre><code>Enter a non-zero number: 1
Enter a non-zero number: 2
Enter a non-zero number: 5
Enter a non-zero number: 8
Enter a non-zero number: 9
Enter a non-zero number: 0
the list without the 2 outliers are: [8]
Process finished with exit code 0
</code></pre>
<p>The program should return a list [5]. I tried to run parts of the program, i know the error must be that for loop that I'm using. But it seems correct to me. Can someone tell me why it's not working the way it should?</p>
| [
{
"answer_id": 74285819,
"author": "niu2x",
"author_id": 14563089,
"author_profile": "https://Stackoverflow.com/users/14563089",
"pm_score": 1,
"selected": false,
"text": "def outliers(lst, n):\n\n new = sorted(lst)\n\n for i in range(0, n):\n del new[0]\n del new[len(new) - 1]\n\n return new\n"
},
{
"answer_id": 74285827,
"author": "azro",
"author_id": 7212686,
"author_profile": "https://Stackoverflow.com/users/7212686",
"pm_score": 2,
"selected": false,
"text": "def outliers(lst, n):\n return sorted(lst)[n:-n]\n\n\nprint(outliers([1, 2, 5, 8, 9], 2)) # [5]\nprint(outliers([1, 2, 5, 8, 9], 1)) # [2, 5, 8]\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9305280/"
] |
74,285,864 | <p>I'm struggling with an array issue. I have a React frontend posting an array to a node API for a MySQL INSERT query. The data from frontend consists of an array with 1 object and 6 elements. One of these elements is an array itself.</p>
<pre><code>[
{
subjectID: '2',
studentList: [ [Object], [Object] ],
subjectTitle: 'Physics',
subjectLevel: 'IGCSE Level',
syllabusCode: '0625',
subjectGroup: 'Humanities'
}
]
</code></pre>
<p>The <code>studentList</code> array:</p>
<pre><code>[ { studentID: '244' }, { studentID: '245' } ]
</code></pre>
<p>What I'm trying to achieve is a new array with objects unique to each studentID, so I can run a forEach over it just before . End result looking something like this:</p>
<pre><code>[
{
subjectID: "2",
studentID: "244",
subjectTitle: "Physics",
subjectLevel: "IGCSE Level",
syllabusCode: "0625",
subjectGroup: "Humanities",
},
{
subjectID: "2",
studentID: "245",
subjectTitle: "Physics",
subjectLevel: "IGCSE Level",
syllabusCode: "0625",
subjectGroup: "Humanities",
},
];
</code></pre>
<p>I'm not sure at which point splice will come into it...</p>
<p>Please let me know if I can supply any other code. I'd appreciate any guidance/assistance! (Been coding for about 2 months now)</p>
| [
{
"answer_id": 74285936,
"author": "Moein Moeinnia",
"author_id": 18318552,
"author_profile": "https://Stackoverflow.com/users/18318552",
"pm_score": 2,
"selected": false,
"text": "let parentArr = [\n {\n subjectID: '2',\n studentList: [ [Object], [Object] ],\n subjectTitle: 'Physics',\n subjectLevel: 'IGCSE Level',\n syllabusCode: '0625',\n subjectGroup: 'Humanities'\n }\n]\n\n\nlet newArr = [] ;\nparentArr.forEach((parent)=>{\n parent.studentList.forEach((child)=>{\n newArr.push({\n subjectID: parent.subjectID,\n studentID: child.studentID,\n subjectTitle: parent.subjectTitle,\n subjectLevel: parent.subjectLevel,\n syllabusCode: parent.syllabusCode,\n subjectGroup: parent.subjectGroup,\n })\n })\n})"
},
{
"answer_id": 74286119,
"author": "Syed Arsalan Hussain",
"author_id": 14733216,
"author_profile": "https://Stackoverflow.com/users/14733216",
"pm_score": 2,
"selected": true,
"text": "const arr = [\n {\n subjectID: '2',\n studentList: [ {\"name\":\"xyz\",\"studentID\":2},\n {\"name\":\"abc\",\"studentID\":3} ],\n subjectTitle: 'Physics',\n subjectLevel: 'IGCSE Level',\n syllabusCode: '0625',\n subjectGroup: 'Humanities'\n }\n]\nvar arr1 = []\n\nfor (var parent = 0;parent< arr.length;parent++){\n for (var children = 0; children< arr[parent].studentList.length; children++){\n arr1.push(\n {\n subjectID: arr[parent].subjectID,\n studentID: arr[parent].studentList[children].studentID,// Here studentID is assumed as a key of student ID you need to replace it with your key\n subjectTitle: arr[parent].subjectTitle,\n subjectLevel: arr[parent].subjectLevel,\n syllabusCode: arr[parent].syllabusCode,\n subjectGroup: arr[parent].subjectGroup,\n }\n ) \n \n}\n}\nconsole.log(arr1)\n// Now you can insert the arr1 into SQL"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19525398/"
] |
74,285,872 | <p>I have a DB table with a <code>report_url</code> column. As soon as a backend done with filling and storing a report it fills that column with S3 link. If the report was not yet stored, the column value is NULL by default. I also have Pyramid API where an endpoint is declared returning Response with body of report content. So, whenever the user makes request, according controller will be fired to get the report link and download the file and return it to user. However, if report is not done yet (<code>report_url</code> is NULL), I need to inform the user somehow. In this case front-end should receive HTTP status 400, but I have not figured out if this fits best. Or maybe 503 fits better here?</p>
| [
{
"answer_id": 74290061,
"author": "Matthias",
"author_id": 5272567,
"author_profile": "https://Stackoverflow.com/users/5272567",
"pm_score": 3,
"selected": true,
"text": "{\"report_url\": null}"
},
{
"answer_id": 74294005,
"author": "Stephen Ostermiller",
"author_id": 1145388,
"author_profile": "https://Stackoverflow.com/users/1145388",
"pm_score": 1,
"selected": false,
"text": "202 - Accepted"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8168415/"
] |
74,285,906 | <p>i have a Question about an KQL Query.
I would like to restrict the Query only of the Work Days from Monday to Friday.</p>
<p>How can i build this in KQL Query?</p>
<p>Thanks a lot.</p>
<p>A short Edit:</p>
<p>How can i build this in a existing Query with a Timestamp "timestamp between (datetime(06:00) .. datetime(15:00))" ??</p>
<p>For Example here the Code:</p>
<pre><code>availabilityResults
| where timestamp between (datetime(06:00) .. datetime(15:00))
| where true
| where name == "warmup" and true
| extend percentage = toint(success) * 100
| render timechart
</code></pre>
<p>And now i would like only have an Result when is an Work Day</p>
<p>Best Regards,
Phil</p>
| [
{
"answer_id": 74290061,
"author": "Matthias",
"author_id": 5272567,
"author_profile": "https://Stackoverflow.com/users/5272567",
"pm_score": 3,
"selected": true,
"text": "{\"report_url\": null}"
},
{
"answer_id": 74294005,
"author": "Stephen Ostermiller",
"author_id": 1145388,
"author_profile": "https://Stackoverflow.com/users/1145388",
"pm_score": 1,
"selected": false,
"text": "202 - Accepted"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18864394/"
] |
74,285,911 | <p>I have such state in my React project:</p>
<pre><code> const [information, setInformation] = React.useState([
{
Email: "",
TellNo: "",
Username: "",
NationalityType: "",
pIDCheck: "",
VerificationCode: "",
Password: "",
},
]);
</code></pre>
<p>I want to update "TellNo" value when input values changes. I tried many approaches like this:</p>
<pre><code> onChange={(e) =>
setInformation((prev) => [{...prev, TellNo: e.target.value }])
}
</code></pre>
<p>but as you can see. it will add an additional object. how can I change my <code>TellNo</code> without adding an object</p>
| [
{
"answer_id": 74290061,
"author": "Matthias",
"author_id": 5272567,
"author_profile": "https://Stackoverflow.com/users/5272567",
"pm_score": 3,
"selected": true,
"text": "{\"report_url\": null}"
},
{
"answer_id": 74294005,
"author": "Stephen Ostermiller",
"author_id": 1145388,
"author_profile": "https://Stackoverflow.com/users/1145388",
"pm_score": 1,
"selected": false,
"text": "202 - Accepted"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20395245/"
] |
74,285,917 | <p>We are testing calling Native code from a simple Flutter app with a camera.</p>
<p>However, an error occurs at the point where we call availableCameras(), which has nothing to do with our native integration code.</p>
<pre><code>MissingPluginException (MissingPluginException(No implementation found for method availableCameras on channel plugins.flutter.io/camera_android))
</code></pre>
<pre><code>DartPluginRegistrant.ensureInitialized();
WidgetsFlutterBinding.ensureInitialized();
var cameras = await availableCameras();
</code></pre>
<p>We lowered the version of camera but it did not improve.
Of course we did <code>flutter clean</code> and <code>flutter pub get</code> each time, and also restarted Visual Studio Code and Android Studio.</p>
<p>pubspec.yaml</p>
<pre><code>dependencies:
flutter:
sdk: flutter
camera: ^0.10.0+4
# camera: 0.9.7+1
path_provider: ^2.0.11
path: ^1.8.2
# dependency_overrides:
# camera_android: 0.9.7+1
# camera_avfoundation: 0.9.7+1
</code></pre>
<p>We were testing it to call Native code from Flutter. This problem did not occur before we tried it. So we think it is a possible cause. We suspected a duplicate channel name and changed it to include our domain name, but this did not improve things.</p>
<pre><code>class AppInfo {
static const MethodChannel _channel = MethodChannel('appInfo');
static Future<String?> get appVersion async {
final String? version = await _channel.invokeMethod('getAppVersion');
return version;
}
}
</code></pre>
<p>MainActivity.kt</p>
<pre><code>package com.xxx.xxxx
import android.content.pm.PackageManager
import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import kotlinx.coroutines.ExperimentalCoroutinesApi
class MainActivity : FlutterActivity() {
private val CHANNEL = "appInfo"
@OptIn(ExperimentalCoroutinesApi::class)
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
MethodChannel(
flutterEngine.dartExecutor.binaryMessenger,
CHANNEL
).setMethodCallHandler { call, result ->
if (call.method == "getAppVersion") {
try {
val pInfo =
applicationContext.packageManager.getPackageInfo(context.packageName, 0)
var version = pInfo.versionName
result.success("${pInfo.versionName}");
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
result.notImplemented()
}
} else {
result.notImplemented()
}
}
}
}
</code></pre>
<p>The iOS version does not have this problem.</p>
<p>AppDelegate.swift</p>
<pre><code>import UIKit
import Flutter
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
let controller: FlutterViewController = window?.rootViewController as! FlutterViewController
let helloMethodChannel = FlutterMethodChannel(name: "appInfo",binaryMessenger: controller as! FlutterBinaryMessenger)
helloMethodChannel.setMethodCallHandler({
(call:FlutterMethodCall,result:FlutterResult) -> Void in
switch call.method{
case "getAppVersion":
result(Bundle.main.object(forInfoDictionaryKey:"CFBundleShortVersionString") as? String)
default:
result("iOS" + UIDevice.current.systemVersion)
}
})
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
</code></pre>
<p>What else can we try?</p>
<p>flutter doctor -v</p>
<pre><code>[✓] Flutter (Channel stable, 3.3.6, on macOS 12.6 21G115 darwin-x64, locale en-JP)
• Flutter version 3.3.6 on channel stable at /Users/ganessa/fvm/versions/stable
• Upstream repository https://github.com/flutter/flutter.git
• Framework revision 6928314d50 (7 days ago), 2022-10-25 16:34:41 -0400
• Engine revision 3ad69d7be3
• Dart version 2.18.2
• DevTools version 2.15.0
[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
• Android SDK at /Users/ganessa/src/android-sdks
• Platform android-33, build-tools 33.0.0
• Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 11.0.12+0-b1504.28-7817840)
• All Android licenses accepted.
[✓] Xcode - develop for iOS and macOS (Xcode 13.4.1)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Build 13F100
• CocoaPods version 1.11.2
[✓] Chrome - develop for the web
• Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
[✓] Android Studio (version 2021.2)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin can be installed from:
https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build 11.0.12+0-b1504.28-7817840)
[✓] VS Code (version 1.72.2)
• VS Code at /Applications/Visual Studio Code.app/Contents
• Flutter extension version 3.52.0
[✓] Connected device (4 available)
• SHV43 (mobile) • XXXXXXXXXXXXXXX • android-arm64 • Android 9 (API 28)
• iPhone SE2 MS (mobile) • XXXXXXXX-XXXXXXXXXXXXXXXX • ios • iOS 15.6.1 19G82
• macOS (desktop) • macos • darwin-x64 • macOS 12.6 21G115 darwin-x64
• Chrome (web) • chrome • web-javascript • Google Chrome 107.0.5304.87
[✓] HTTP Host Availability
• All required HTTP hosts are available
• No issues found!
</code></pre>
| [
{
"answer_id": 74290061,
"author": "Matthias",
"author_id": 5272567,
"author_profile": "https://Stackoverflow.com/users/5272567",
"pm_score": 3,
"selected": true,
"text": "{\"report_url\": null}"
},
{
"answer_id": 74294005,
"author": "Stephen Ostermiller",
"author_id": 1145388,
"author_profile": "https://Stackoverflow.com/users/1145388",
"pm_score": 1,
"selected": false,
"text": "202 - Accepted"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5528270/"
] |
74,285,929 | <pre><code>student_heights = input("Input a list of student heights ").split()
for n in range(0, len(student_heights)):
student_heights[n] = int(student_heights[n])
total_height = 0
for height in total_height:
total_height += height
print(total_height)
number_of_students = 0
for student in number_of_students:
number_of_students += student
print(number_of_students)
avg_height = round(total_height / number_of_students)
print(avg_height)
</code></pre>
<p>i tried to make an avg height calculator but something isnt working</p>
| [
{
"answer_id": 74286039,
"author": "yeti",
"author_id": 5647853,
"author_profile": "https://Stackoverflow.com/users/5647853",
"pm_score": 1,
"selected": false,
"text": "int"
},
{
"answer_id": 74286091,
"author": "EmileCoetzee",
"author_id": 20366196,
"author_profile": "https://Stackoverflow.com/users/20366196",
"pm_score": 1,
"selected": false,
"text": "student_heights = input(\"Input a list of student heights \").split()\nfor n in range(0, len(student_heights)):\nstudent_heights[n] = int(student_heights[n])\n\ntotal_height = 0\nfor n in range(0, len(student_heights)):\ntotal_height += student_heights[n]\nprint(total_height)\n\nnumber_of_students = 0\nfor n in range(0, len(student_heights)):\nnumber_of_students += 1\nprint(number_of_students)\n\navg_height = round(total_height / number_of_students)\nprint(avg_height)\n"
},
{
"answer_id": 74286131,
"author": "GAVD",
"author_id": 4983082,
"author_profile": "https://Stackoverflow.com/users/4983082",
"pm_score": 0,
"selected": false,
"text": "int"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19964325/"
] |
74,285,941 | <p>While running a Compose codelab (basics), I encountered these sentences:</p>
<blockquote>
<p>Instead of using remember you can use rememberSaveable. This will save
each state surviving configuration changes (such as rotations) and
process death. ... Run, rotate, change to dark mode or kill the
process. The onboarding screen is not shown unless you have previously
exited the app.</p>
</blockquote>
<p>My initial reaction to "process death" was that the author was referring to how Android will arbitrarily just kill an app process when it needs resources. I do not believe this is something a User can make happen, as opposed to exiting an app.</p>
<p>Then the author says "Run, rotate or kill the process" which makes me think there does exist a way for a User to kill the process without exiting the app. Is there a way to kill an app process using some gesture or recipe other than swiping to exit the app, or using force close from the Settings app?</p>
<p>A good answer to my question would allow me to either test my code using the supposed kill process mechanism or inform the author that the codelab documentation is a little loose and might be tightened up.</p>
| [
{
"answer_id": 74321627,
"author": "Ian G. Clifton",
"author_id": 417513,
"author_profile": "https://Stackoverflow.com/users/417513",
"pm_score": 3,
"selected": true,
"text": "adb shell am force-stop com.example.myapp"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91443/"
] |
74,285,949 | <p>I'm creating a simple webpage tool for language education that randomly selects a question from a javascript array const, but the longer questions are cut off, especially for mobile. How can I get a line break for these longer text questions? I've tried adding breaks inside the array, and I've tried adding css line breaks for the input and divs, but nothing works.</p>
<pre><code> <style>
.button {
background-color: #094997;
border-radius: 12px;
border: none;
color: white;
padding: 12px 20px;
text-align: center;
text-decoration: none;
font-size: 24px;
width: 200px;
}
input
{
font-size:22px;
padding: 50px 50px;
text-align: center;
width: 200px;
height: 250px;
}
.questionsdiv {
text-align: center;
}
</style>
<div class="questionsdiv">
<input type="text" "randomquestion"="" id="randomquestion">
<br><br>
<button class="button" onclick="findquestion();" type="randomquestion">Random Question</button>
</div>
<script>
const question = ["How old are you?","Where do you go on Saturdays?","Do you have any brothers or sisters?","How many books do you own?","Who is your favorite music artist lately?","Do you like Jazz music?","Have you ever traveled outside of Japan?","Do you want to live in the countryside or in the city when you are older and have a family?",];
function findquestion() {
let randomIndex = Math.floor(Math.random() * question.length);
document.getElementById("randomquestion").setAttribute("value", question[randomIndex]);
}
</script>
</code></pre>
| [
{
"answer_id": 74286143,
"author": "dante velli",
"author_id": 19338216,
"author_profile": "https://Stackoverflow.com/users/19338216",
"pm_score": 2,
"selected": true,
"text": "input"
},
{
"answer_id": 74286187,
"author": "matdv",
"author_id": 20240620,
"author_profile": "https://Stackoverflow.com/users/20240620",
"pm_score": 0,
"selected": false,
"text": " <div type=\"text\" \"randomquestion\"=\"\" id=\"randomquestion\"></div>\n\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20395167/"
] |
74,285,954 | <p>Assuming I'm writing a method that takes in <code>Map<String, List<Integer>></code> as shown below, and a String <code>name</code> to filter. My return type is <code>Stream<Integer></code> how do I convert from a <code>Stream<List<Integer>></code> to <code>Stream<Integer></code>?</p>
<pre><code>Map<String, List<Integer>> person = Map.of(
"John", List.of(54, 18),
"Alex", List.of(28), "Tom",
List.of(78, 42)
);
</code></pre>
<p>My current implementation returns a <code>Stream<List<Integer>></code>. Realistically, I would iterate through the list to retrieve all Integers in the list.</p>
<p>Code implementation:</p>
<pre><code>return table.entrySet().stream()
.filter(map -> map.getKey().equals(name))
.map(map -> map.getValue());
</code></pre>
| [
{
"answer_id": 74286143,
"author": "dante velli",
"author_id": 19338216,
"author_profile": "https://Stackoverflow.com/users/19338216",
"pm_score": 2,
"selected": true,
"text": "input"
},
{
"answer_id": 74286187,
"author": "matdv",
"author_id": 20240620,
"author_profile": "https://Stackoverflow.com/users/20240620",
"pm_score": 0,
"selected": false,
"text": " <div type=\"text\" \"randomquestion\"=\"\" id=\"randomquestion\"></div>\n\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9203056/"
] |
74,285,990 | <p>How to select rows which contains digits in dataframe.
I am using this.</p>
<pre><code>s = set([1,2,3,4,5,6,7,8,9,0])
df["text"].apply(lambda x:any(i in list(x) for i in s))
</code></pre>
<p>Trying to get separate the sentences with digits.</p>
| [
{
"answer_id": 74286010,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 2,
"selected": false,
"text": "Series.str.contains"
},
{
"answer_id": 74286047,
"author": "Hu gePanic",
"author_id": 12189751,
"author_profile": "https://Stackoverflow.com/users/12189751",
"pm_score": 1,
"selected": false,
"text": "import pandas as pd\ns1 = pd.Series(['one', 'one1', '1', ''])\ns1.str.isnumeric()\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74285990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20367291/"
] |
74,286,002 | <p>I am not able to sort out the Error 148 in GAMS Studio 39.3 for my problem.</p>
<p>148 Dimension different - The symbol is referenced with more/less indices as declared</p>
<p>following is the details:</p>
<pre><code>Sets
EV 'EV unit'/ev1*ev1/
Asev1 'set ev index for values of sch' /1*2/
taev 'set of arrival'/taev1*taev1/
tdev 'set of departure'/tdev1*tdev1/
t ’time periods’ /t1*t2/
w ’scenarios’ /w1*w2/;
SCALAR
Pev ’EV power traded in the Energy market’/7.8/;
PARAMETER
Asev 'alphasch(ev) values of alphasch'
/1 0
2 1/;
PARAMETER
weigth(w) ’weight of scenarios’
/w1 0.05
w2 0.05/;
POSITIVE VARIABLES
As(ev,t,w) 'EV scheduling in time period t';
EQUATION
Pev1 'power output of EV'
Pev1(t,w).. Pev=e=sum(ev,Pev(ev,t,w)*Asev('ev,t,w'));
</code></pre>
<p>I am not sure where i am making mistake however i am getting Error 148.
Error 148 Dimension different - The symbol is referenced with more/less
**** indices as declared</p>
<p>Note: I got $148 error under w)*</p>
| [
{
"answer_id": 74286010,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 2,
"selected": false,
"text": "Series.str.contains"
},
{
"answer_id": 74286047,
"author": "Hu gePanic",
"author_id": 12189751,
"author_profile": "https://Stackoverflow.com/users/12189751",
"pm_score": 1,
"selected": false,
"text": "import pandas as pd\ns1 = pd.Series(['one', 'one1', '1', ''])\ns1.str.isnumeric()\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16371138/"
] |
74,286,031 | <p>I want to loop over a list of variables nad output the variable name and value. E.g., say I have <code>x=1</code> and <code>y=2</code>, then I want an output</p>
<pre><code>x is 1
y is 2
</code></pre>
<p>I suspect I need to use Symbols for this. Here is my approach, but it isn't working:</p>
<pre><code>function t(x,y)
for i in [x,y]
println("$(Symbol(i)) is $(eval(i))") # outputs "1 is 1" and "2 is 2"
end
end
t(1, 2)
</code></pre>
<p>Is there a way to achieve this? I guess a Dictionary would work, but would be interested to see if Symbols can also be used here.</p>
| [
{
"answer_id": 74286709,
"author": "daycaster",
"author_id": 3800865,
"author_profile": "https://Stackoverflow.com/users/3800865",
"pm_score": 2,
"selected": false,
"text": "x = 1\ny = 2\n\nfunction t(a, b)\n for i in [a, b]\n println(\"$(i) is $(eval(i))\") \n end\nend\n\nt(:x, :y)\n"
},
{
"answer_id": 74287358,
"author": "Nils Gudat",
"author_id": 2499892,
"author_profile": "https://Stackoverflow.com/users/2499892",
"pm_score": 4,
"selected": true,
"text": "NamedTuple"
},
{
"answer_id": 74291271,
"author": "Przemyslaw Szufel",
"author_id": 9957710,
"author_profile": "https://Stackoverflow.com/users/9957710",
"pm_score": 2,
"selected": false,
"text": "varinfo"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19500571/"
] |
74,286,046 | <p>want to add a background image to my drawer. I want to fix my background image over Drawer width</p>
<pre><code> Drawer(
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topRight: Radius.circular(40),
bottomRight: Radius.circular(40),
topLeft: Radius.circular(40),
bottomLeft: Radius.circular(40),
),
),
child: Stack(children: <Widget>[
Image.asset(
"assets/images/menu.png",
width: double.infinity,
fit: BoxFit.cover,
),
</code></pre>
| [
{
"answer_id": 74286709,
"author": "daycaster",
"author_id": 3800865,
"author_profile": "https://Stackoverflow.com/users/3800865",
"pm_score": 2,
"selected": false,
"text": "x = 1\ny = 2\n\nfunction t(a, b)\n for i in [a, b]\n println(\"$(i) is $(eval(i))\") \n end\nend\n\nt(:x, :y)\n"
},
{
"answer_id": 74287358,
"author": "Nils Gudat",
"author_id": 2499892,
"author_profile": "https://Stackoverflow.com/users/2499892",
"pm_score": 4,
"selected": true,
"text": "NamedTuple"
},
{
"answer_id": 74291271,
"author": "Przemyslaw Szufel",
"author_id": 9957710,
"author_profile": "https://Stackoverflow.com/users/9957710",
"pm_score": 2,
"selected": false,
"text": "varinfo"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20378705/"
] |
74,286,053 | <p>I am new to regex. I have read various tutorials, still I have failed to run my simple codes.</p>
<p>My files are organized such as <code>"c1c2c4_aa_1"</code>, <code>"c1c2c3_aa_2"</code>, <code>"c1c2c8_aa_3"</code>, <code>"c1c3c4_aa_4"</code>, ... <code>"c1c2c4_bb_41"</code>, <code>"c1c8c9_cc_58"</code>, <code>"c1c3c11_aa_19"</code></p>
<p>I want to find all those ones that includes <code>"aa"</code> (such as <code>"c1c2c3_aa_3"</code>) and convert them to <code>"c1c2c4_zz_3"</code></p>
<p>So I want the last number and the first string before "_" remains fixed, but change the "aa" in the middle.</p>
<p>"c1", "c2", "c3" are some conditions.
Also, the last numbers are quite random, so I do not know them to define them.</p>
<p>I am interested in using regex.</p>
<p>I tried this:</p>
<pre><code>con_list1 = ["c1", "c2", ... "c8"]
con_list2 = ["c1", "c2", ... "c11"]
con_list3 = ["c1", "c2", ... "c10"]
for con1 in con_list1:
for con2 in con_list2:
for con3 in con_list3:
if(os.path.exists("./" + con1 + con2 + con3 + "_aa(.*)")):
os.rename("./" + con1 + con2 + con3 + "_aa(.*)", "./" + con1 + con2 + con3 + "_zz(.*)")
</code></pre>
<p>I want the last number corresponding to the file that I rename remains fixed:</p>
<p>"c1c2c3_aa_3" -> "c1c2c3_zz_3"
"c1c2c3_aa_13" -> "c1c2c3_zz_13"</p>
<p>I am also interested in using regex and (.*) in the right way.</p>
<p>However, the above code seems not working.</p>
<p>I appreciate to help to implement this code.</p>
| [
{
"answer_id": 74286189,
"author": "David Lador",
"author_id": 17701030,
"author_profile": "https://Stackoverflow.com/users/17701030",
"pm_score": 1,
"selected": false,
"text": "con_list1 = [\"c1c2c4_aa_1\", \"c1c2c3_aa_2\", \"c1c2c8_aa_3\", \"c1c3c4_aa_4\"]"
},
{
"answer_id": 74286243,
"author": "Nero",
"author_id": 19995417,
"author_profile": "https://Stackoverflow.com/users/19995417",
"pm_score": 0,
"selected": false,
"text": "names = re.findall(r'\\\"[a-z0-9]+\\_aa\\_[0-9]+\\\"', files_names_list.text, flags=re.I))\n"
},
{
"answer_id": 74286456,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 0,
"selected": false,
"text": "import os, re\n\ncon_list1 = [\"c1\", \"c2\", \"c3\",\"c4\",\"c5\",\"c6\",\"c7\",\"c8\"]\ncon_list2 = [\"c1\", \"c2\", \"c3\",\"c4\",\"c5\",\"c6\",\"c7\",\"c8\", \"c9\",\"c10\", \"c11\"]\ncon_list3 = [\"c1\", \"c2\", \"c3\",\"c4\",\"c5\",\"c6\",\"c7\",\"c8\", \"c9\",\"c10\"]\nregex = re.compile(f'^((?:{\"|\".join(map(re.escape, con_list1))})(?:{\"|\".join(map(re.escape, con_list2))})(?:{\"|\".join(map(re.escape, con_list3))}))_aa_')\n\nrootdir = \"YOUR_ROOT_DIR\"\nfor root, dirs, files in os.walk(rootdir):\n for file in files:\n if regex.search(file):\n os.rename(file, regex.sub(r'\\g<1>_zz_', file))\n"
},
{
"answer_id": 74286467,
"author": "tshiono",
"author_id": 8572380,
"author_profile": "https://Stackoverflow.com/users/8572380",
"pm_score": 0,
"selected": false,
"text": "import os, re\nfor f in os.listdir('.'):\n m = re.match(r'((?:c\\d{1,2}){3})_aa_(\\d{1,2})$', f)\n if m:\n newname = m.group(1) + '_zz_' + m.group(2)\n os.rename(f, newname)\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2178942/"
] |
74,286,074 | <p>I am getting this error, Where as U is number and returning the number too.</p>
<pre><code>Type 'number' is not assignable to type 'U'.
</code></pre>
<pre><code>function foo<T extends string, U extends number>(a: T): U {
return +a; // error in this line
}
foo<string, number>('12')
</code></pre>
| [
{
"answer_id": 74286189,
"author": "David Lador",
"author_id": 17701030,
"author_profile": "https://Stackoverflow.com/users/17701030",
"pm_score": 1,
"selected": false,
"text": "con_list1 = [\"c1c2c4_aa_1\", \"c1c2c3_aa_2\", \"c1c2c8_aa_3\", \"c1c3c4_aa_4\"]"
},
{
"answer_id": 74286243,
"author": "Nero",
"author_id": 19995417,
"author_profile": "https://Stackoverflow.com/users/19995417",
"pm_score": 0,
"selected": false,
"text": "names = re.findall(r'\\\"[a-z0-9]+\\_aa\\_[0-9]+\\\"', files_names_list.text, flags=re.I))\n"
},
{
"answer_id": 74286456,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 0,
"selected": false,
"text": "import os, re\n\ncon_list1 = [\"c1\", \"c2\", \"c3\",\"c4\",\"c5\",\"c6\",\"c7\",\"c8\"]\ncon_list2 = [\"c1\", \"c2\", \"c3\",\"c4\",\"c5\",\"c6\",\"c7\",\"c8\", \"c9\",\"c10\", \"c11\"]\ncon_list3 = [\"c1\", \"c2\", \"c3\",\"c4\",\"c5\",\"c6\",\"c7\",\"c8\", \"c9\",\"c10\"]\nregex = re.compile(f'^((?:{\"|\".join(map(re.escape, con_list1))})(?:{\"|\".join(map(re.escape, con_list2))})(?:{\"|\".join(map(re.escape, con_list3))}))_aa_')\n\nrootdir = \"YOUR_ROOT_DIR\"\nfor root, dirs, files in os.walk(rootdir):\n for file in files:\n if regex.search(file):\n os.rename(file, regex.sub(r'\\g<1>_zz_', file))\n"
},
{
"answer_id": 74286467,
"author": "tshiono",
"author_id": 8572380,
"author_profile": "https://Stackoverflow.com/users/8572380",
"pm_score": 0,
"selected": false,
"text": "import os, re\nfor f in os.listdir('.'):\n m = re.match(r'((?:c\\d{1,2}){3})_aa_(\\d{1,2})$', f)\n if m:\n newname = m.group(1) + '_zz_' + m.group(2)\n os.rename(f, newname)\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10842900/"
] |
74,286,092 | <p>I'm trying to write a macro that removes rows with the condition that the string in the cells in column A contains "<em>--</em>" or "<em>-4</em>" or "" (empty). I'd do it with a normal filter, but that gives me max 2 conditions.</p>
<pre><code>Sub Delete_Rows()
Dim cell As Range
For Each cell In Range("A:A")
If cell.Value = "*--*" Or cell.Value = "*-4*" Then
cell.EntireRow.Delete
End If
Next cell
End Sub
</code></pre>
<p>What am I doing wrong?</p>
| [
{
"answer_id": 74286210,
"author": "thestarwarsnerd",
"author_id": 18931013,
"author_profile": "https://Stackoverflow.com/users/18931013",
"pm_score": 0,
"selected": false,
"text": "Like"
},
{
"answer_id": 74286301,
"author": "FaneDuru",
"author_id": 2233308,
"author_profile": "https://Stackoverflow.com/users/2233308",
"pm_score": 3,
"selected": true,
"text": "Union"
},
{
"answer_id": 74286323,
"author": "FunThomas",
"author_id": 7599798,
"author_profile": "https://Stackoverflow.com/users/7599798",
"pm_score": 1,
"selected": false,
"text": "="
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16685655/"
] |
74,286,095 | <p>I want to remove the id field from datacopy list. but when I do it, also data list is updated. I want to remove the id field only from datacopy list. how to do that?</p>
<pre><code>void main() {
List<Map<String, dynamic>> data = [
{
'id': '1',
'domain': '00extreme.com',
'TDL': 'com',
'status': 'parked',
'adult': 'No',
'keywords': '[ 00 ] [ extreme ]'
},
{
'id': '2',
'domain': '00hrs.com',
'TDL': 'com',
'status': 'parked',
'adult': 'No',
'keywords': '[ 00 ] [ hrs ]'
},
{
'id': '3',
'domain': '00k3.com',
'TDL': 'com',
'status': 'parked',
'adult': 'No',
'keywords': '[ 00 ] [ k ] [ 3 ]'
},
{
'id': '4',
'domain': '00I.net',
'TDL': 'net',
'status': 'parked',
'adult': 'No',
'keywords': '[ 00I.net ]'
},
{
'id': '5',
'domain': '02text.com',
'TDL': 'com',
'status': 'parked',
'adult': 'No',
'keywords': '[ 02 ] [ text ]'
},
{
'id': '6',
'domain': '0zzy.com',
'TDL': 'com',
'status': 'parked',
'adult': 'No',
'keywords': '[ 0 ] [ zz ] [ y ]'
},
{
'id': '7',
'domain': '100facial.com',
'TDL': 'com',
'status': 'parked',
'adult': 'Yes',
'keywords': '[ 100 ] [ facial ]'
},
{
'id': '8',
'domain': '1000fotosgratis.com',
'TDL': 'com',
'status': 'parked',
'adult': 'No',
'keywords': '[ 1000 ] [ fotos ] [ gratis ]'
},
{
'id': '9',
'domain': '1000petstores.com',
'TDL': 'com',
'status': 'parked',
'adult': 'No',
'keywords': '[ 1000 ] [ pet ] [ stores ]'
},
{
'id': '10',
'domain': '1000toys.com',
'TDL': 'com',
'status': 'parked',
'adult': 'No',
'keywords': '[ 100 ] [ toys ]'
},
];
List<Map<String, dynamic>> datacopy =[];
datacopy = [...data];
removeItem(String key) {
datacopy.map((element) {
var m = element;
m.remove(key);
return m;
}).toList();
}
removeItem('id');
print(data);
print(datacopy);
}
</code></pre>
<p>I want to remove the id field from datacopy list. but when I do it, also data list is updated. I want to remove the id field only from datacopy list. how to do that?</p>
| [
{
"answer_id": 74286198,
"author": "My Car",
"author_id": 16124033,
"author_profile": "https://Stackoverflow.com/users/16124033",
"pm_score": 0,
"selected": false,
"text": "void main() {\nList<Map<String, dynamic>> data = [\n {\n 'id': '1',\n 'domain': '00extreme.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 00 ] [ extreme ]'\n },\n {\n 'id': '2',\n 'domain': '00hrs.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 00 ] [ hrs ]'\n },\n {\n 'id': '3',\n 'domain': '00k3.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 00 ] [ k ] [ 3 ]'\n },\n {\n 'id': '4',\n 'domain': '00I.net',\n 'TDL': 'net',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 00I.net ]'\n },\n {\n 'id': '5',\n 'domain': '02text.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 02 ] [ text ]'\n },\n {\n 'id': '6',\n 'domain': '0zzy.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 0 ] [ zz ] [ y ]'\n },\n {\n 'id': '7',\n 'domain': '100facial.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'Yes',\n 'keywords': '[ 100 ] [ facial ]'\n },\n {\n 'id': '8',\n 'domain': '1000fotosgratis.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 1000 ] [ fotos ] [ gratis ]'\n },\n {\n 'id': '9',\n 'domain': '1000petstores.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 1000 ] [ pet ] [ stores ]'\n },\n {\n 'id': '10',\n 'domain': '1000toys.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 100 ] [ toys ]'\n },\n\n];\n List<Map<String, dynamic>> datacopy =[];\n addData() {\n datacopy.addAll(data);\n }\n addData();\n\n removeItem(String key) {\n datacopy.map((element) {\n var m = element;\n m.remove(key);\n return m;\n }).toList();\n \n }\n removeItem('id');\n print(data);\n print(datacopy);\n}\n"
},
{
"answer_id": 74286202,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 2,
"selected": true,
"text": " datacopy.addAll(data.map((e) => Map.from(e)));\n\n for (final item in datacopy) {\n item.remove(\"id\");\n }\n print(data);\n print(\"NA\\n\");\n print(datacopy);\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14242531/"
] |
74,286,098 | <p>When I fetch the data from database it is giving an error , the error is not correct but it means that you are getting huge data .</p>
<p>here is the data that want to fecth it ;</p>
<p><a href="https://i.stack.imgur.com/fPJnT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fPJnT.png" alt="enter image description here" /></a></p>
<p>here is the model of this data :</p>
<pre><code>class DropdownListModel {
int? id;
String? name;
DropdownListModel({this.id, this.name});
DropdownListModel.fromJson(Map<String, dynamic> json) {
id = json['Id'];
name = json['Name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['Id'] = id;
data['Name'] = name;
return data;
}
}
</code></pre>
<p>I tried to fetch it but cause of the huge data it gives renderflex error.</p>
<p><a href="https://i.stack.imgur.com/ALzlk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ALzlk.png" alt="enter image description here" /></a></p>
<p>The code UI :</p>
<pre><code> CustomDropDown(
width: 375,
focusNode: FocusNode(),
icon: const Icon(
Icons.keyboard_arrow_down_outlined,
size: 30,
),
hintText: "Choose Airport",
items:
airports!.map<DropdownMenuItem<String>>((e) {
return DropdownMenuItem<String>(
value: e.name,
child: Text(
e.name!,
textAlign: TextAlign.left,
),
);
}).toList(),
onChanged: (value) {
setState(() {
int index = airports!
.indexWhere((e) => e.name == value);
destinationAirportId =
int.parse(airports![index].id.toString());
debugPrint(
"destinationAirportId : " + destinationAirportId.toString());
});
},
)
</code></pre>
<p>Custom dropdown :</p>
<pre><code>import 'package:hrsm/core/app_export.dart';
import 'package:flutter/material.dart';
class CustomDropDown extends StatelessWidget {
CustomDropDown({
super.key,
this.alignment,
this.width,
this.margin,
this.focusNode,
this.icon,
this.hintText,
this.prefix,
this.prefixConstraints,
this.items,
this.onChanged,
});
Alignment? alignment;
double? width;
EdgeInsetsGeometry? margin;
FocusNode? focusNode;
Widget? icon;
String? hintText;
Widget? prefix;
BoxConstraints? prefixConstraints;
List<DropdownMenuItem<dynamic>>? items;
Function(dynamic)? onChanged;
@override
Widget build(BuildContext context) {
return _buildDropDownWidget();
}
_buildDropDownWidget() {
return Container(
width: width,
margin: margin,
child: DropdownButtonFormField(
focusNode: focusNode,
icon: icon,
style: TextStyle(
color: ColorConstant.black900,
fontSize: getFontSize(
14,
),
fontFamily: 'Poppins',
fontWeight: FontWeight.w400,
height: 1.00,
),
decoration: InputDecoration(
hintText: hintText,
hintStyle: TextStyle(
fontSize: getFontSize(
14.0,
),
color: ColorConstant.black900,
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(
getHorizontalSize(
12.00,
),
),
borderSide: BorderSide(
color: ColorConstant.bluegray50,
width: 1,
),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(
getHorizontalSize(
12.00,
),
),
borderSide: BorderSide(
color: ColorConstant.bluegray50,
width: 1,
),
),
disabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(
getHorizontalSize(
12.00,
),
),
borderSide: BorderSide(
color: ColorConstant.bluegray50,
width: 1,
),
),
),
items: items,
onChanged: onChanged,
),
);
</code></pre>
<p>}
}</p>
| [
{
"answer_id": 74286198,
"author": "My Car",
"author_id": 16124033,
"author_profile": "https://Stackoverflow.com/users/16124033",
"pm_score": 0,
"selected": false,
"text": "void main() {\nList<Map<String, dynamic>> data = [\n {\n 'id': '1',\n 'domain': '00extreme.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 00 ] [ extreme ]'\n },\n {\n 'id': '2',\n 'domain': '00hrs.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 00 ] [ hrs ]'\n },\n {\n 'id': '3',\n 'domain': '00k3.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 00 ] [ k ] [ 3 ]'\n },\n {\n 'id': '4',\n 'domain': '00I.net',\n 'TDL': 'net',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 00I.net ]'\n },\n {\n 'id': '5',\n 'domain': '02text.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 02 ] [ text ]'\n },\n {\n 'id': '6',\n 'domain': '0zzy.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 0 ] [ zz ] [ y ]'\n },\n {\n 'id': '7',\n 'domain': '100facial.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'Yes',\n 'keywords': '[ 100 ] [ facial ]'\n },\n {\n 'id': '8',\n 'domain': '1000fotosgratis.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 1000 ] [ fotos ] [ gratis ]'\n },\n {\n 'id': '9',\n 'domain': '1000petstores.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 1000 ] [ pet ] [ stores ]'\n },\n {\n 'id': '10',\n 'domain': '1000toys.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 100 ] [ toys ]'\n },\n\n];\n List<Map<String, dynamic>> datacopy =[];\n addData() {\n datacopy.addAll(data);\n }\n addData();\n\n removeItem(String key) {\n datacopy.map((element) {\n var m = element;\n m.remove(key);\n return m;\n }).toList();\n \n }\n removeItem('id');\n print(data);\n print(datacopy);\n}\n"
},
{
"answer_id": 74286202,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 2,
"selected": true,
"text": " datacopy.addAll(data.map((e) => Map.from(e)));\n\n for (final item in datacopy) {\n item.remove(\"id\");\n }\n print(data);\n print(\"NA\\n\");\n print(datacopy);\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20376640/"
] |
74,286,105 | <h2>The context</h2>
<p>I'm creating a very simple game with html canvas (inside a next.js app). In this canvas I draw a few rectangles with some gap in between. If you know coloring pixels the game I bascially recreating this.
This is what it looks like so far:</p>
<p><a href="https://i.stack.imgur.com/Ylk4e.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ylk4e.png" alt="enter image description here" /></a></p>
<p>I also implemented a zoom feature and drag feature. The logic for it I found on google.
But here is how the update function looks like:</p>
<pre><code>update = (ctx) => {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
ctx.translate(window.innerWidth / 2, window.innerHeight / 2);
ctx.scale(this.cameraZoom, this.cameraZoom);
ctx.translate(
-window.innerWidth / 2 + this.cameraOffset.x,
-window.innerHeight / 2 + this.cameraOffset.y
);
ctx.clearRect(0, 0, window.width, window.height);
this.drawTiles(ctx);
};
</code></pre>
<p><code>this.cameraZoom</code> just changes on mousewheel and the <code>this.cameraOffset</code> changes on mousemove and starts with <code>cameraOffset = { x: window.innerWidth / 2, y: window.innerHeight / 2 };</code> . This works fine, I can zoom in and drag the canvas around.
The problem I have is when I click the squares - the wrong rectangles get filled after dragging</p>
<h2>The Problem</h2>
<p>Before the zoom and drag feature I implemented a logic, so I can click on the canvas and the correct rectangle will be filled with a color. That works fine. Then I implemented zooming, and I adjusted that logic until I made it work. But now I have to readjust it further because after dragging the "coordinates" aren't correct anymore, but I can't figure out a correct formula. Here is what I have so far (this function sits on every <code>tile</code> or <code>rect</code> I draw:</p>
<pre><code>setPaintingColor = (game) => {
const minX = (this.x - game.gap) * game.cameraZoom;
const maxX = (this.x + this.width - game.gap) * game.cameraZoom;
const minY = (this.y - game.gap) * game.cameraZoom;
const maxY = (this.y + this.height - game.gap) * game.cameraZoom;
if (!game.mouse.down) {
return;
}
if (
game.mouse.x >= minX &&
game.mouse.x <= maxX &&
game.mouse.y >= minY &&
game.mouse.y <= maxY
) {
this.color = "yellow";
}
};
</code></pre>
<p>So this sets the fill color of the rect and then the game update loop constantly calls draw of each rect (which fills the rect with the set color <code>this.color</code>.</p>
<h2>The question</h2>
<p>So now I want to find out a logic that works after dragging and zooming. When I drag the canvas and then try to click rects, nothing get painted.</p>
<p>I played around with the <code>this.cameraOffset.x + y</code> values adding it, subtracting it etc, the closest I got was, when i clicked a tile, the tile to the left got painted but it wasn't logical to me at all.</p>
<p>So what I also tried is I calculate the distance I have moved after dragging (I set <code>this.dragStart</code> and <code>this.dragEnd</code> at the game object. Then adding it to the <code>setPaintingColor</code> function like that:</p>
<pre><code>const distanceMovedX = game.dragStart.x - game.dragEnd.x;
const distanceMovedY = game.dragStart.y - game.dragEnd.y;
const minX = (this.x - game.gap + distanceMovedX) * game.cameraZoom;
const maxX =
(this.x + this.width - game.gap + distanceMovedX) * game.cameraZoom;
const minY = (this.y - game.gap + distanceMovedY) * game.cameraZoom;
const maxY =
(this.y + this.height - game.gap + distanceMovedY) * game.cameraZoom;
</code></pre>
<p>Now when I drag and then click rects, about 6 - 8 tiles to the right where i clicked the rects get painted.</p>
<p><strong>Does anybody know which logic I need to make it work again?</strong></p>
<p>Thank you very much!</p>
| [
{
"answer_id": 74286198,
"author": "My Car",
"author_id": 16124033,
"author_profile": "https://Stackoverflow.com/users/16124033",
"pm_score": 0,
"selected": false,
"text": "void main() {\nList<Map<String, dynamic>> data = [\n {\n 'id': '1',\n 'domain': '00extreme.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 00 ] [ extreme ]'\n },\n {\n 'id': '2',\n 'domain': '00hrs.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 00 ] [ hrs ]'\n },\n {\n 'id': '3',\n 'domain': '00k3.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 00 ] [ k ] [ 3 ]'\n },\n {\n 'id': '4',\n 'domain': '00I.net',\n 'TDL': 'net',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 00I.net ]'\n },\n {\n 'id': '5',\n 'domain': '02text.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 02 ] [ text ]'\n },\n {\n 'id': '6',\n 'domain': '0zzy.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 0 ] [ zz ] [ y ]'\n },\n {\n 'id': '7',\n 'domain': '100facial.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'Yes',\n 'keywords': '[ 100 ] [ facial ]'\n },\n {\n 'id': '8',\n 'domain': '1000fotosgratis.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 1000 ] [ fotos ] [ gratis ]'\n },\n {\n 'id': '9',\n 'domain': '1000petstores.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 1000 ] [ pet ] [ stores ]'\n },\n {\n 'id': '10',\n 'domain': '1000toys.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 100 ] [ toys ]'\n },\n\n];\n List<Map<String, dynamic>> datacopy =[];\n addData() {\n datacopy.addAll(data);\n }\n addData();\n\n removeItem(String key) {\n datacopy.map((element) {\n var m = element;\n m.remove(key);\n return m;\n }).toList();\n \n }\n removeItem('id');\n print(data);\n print(datacopy);\n}\n"
},
{
"answer_id": 74286202,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 2,
"selected": true,
"text": " datacopy.addAll(data.map((e) => Map.from(e)));\n\n for (final item in datacopy) {\n item.remove(\"id\");\n }\n print(data);\n print(\"NA\\n\");\n print(datacopy);\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8502436/"
] |
74,286,112 | <p>there's a question. I need to generate random numbers with ranges and each range has a fixed probability like this:</p>
<pre><code>100 - 500 (75%)
501 - 5000 (20%)
10001 - 50000 (4%)
50001 - 100000 (1%)
</code></pre>
<p>I have no idea how should i do...</p>
<pre><code>function getRandomAmount() {
const probabilities = [0.75, 0.2, 0.04, 0.01];
const items = []
// 100 - 5000 75%
// 5001 - 10000 20%
// 10001 - 50000 4%
// 50001 - 100000 1%
}
</code></pre>
| [
{
"answer_id": 74286198,
"author": "My Car",
"author_id": 16124033,
"author_profile": "https://Stackoverflow.com/users/16124033",
"pm_score": 0,
"selected": false,
"text": "void main() {\nList<Map<String, dynamic>> data = [\n {\n 'id': '1',\n 'domain': '00extreme.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 00 ] [ extreme ]'\n },\n {\n 'id': '2',\n 'domain': '00hrs.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 00 ] [ hrs ]'\n },\n {\n 'id': '3',\n 'domain': '00k3.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 00 ] [ k ] [ 3 ]'\n },\n {\n 'id': '4',\n 'domain': '00I.net',\n 'TDL': 'net',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 00I.net ]'\n },\n {\n 'id': '5',\n 'domain': '02text.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 02 ] [ text ]'\n },\n {\n 'id': '6',\n 'domain': '0zzy.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 0 ] [ zz ] [ y ]'\n },\n {\n 'id': '7',\n 'domain': '100facial.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'Yes',\n 'keywords': '[ 100 ] [ facial ]'\n },\n {\n 'id': '8',\n 'domain': '1000fotosgratis.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 1000 ] [ fotos ] [ gratis ]'\n },\n {\n 'id': '9',\n 'domain': '1000petstores.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 1000 ] [ pet ] [ stores ]'\n },\n {\n 'id': '10',\n 'domain': '1000toys.com',\n 'TDL': 'com',\n 'status': 'parked',\n 'adult': 'No',\n 'keywords': '[ 100 ] [ toys ]'\n },\n\n];\n List<Map<String, dynamic>> datacopy =[];\n addData() {\n datacopy.addAll(data);\n }\n addData();\n\n removeItem(String key) {\n datacopy.map((element) {\n var m = element;\n m.remove(key);\n return m;\n }).toList();\n \n }\n removeItem('id');\n print(data);\n print(datacopy);\n}\n"
},
{
"answer_id": 74286202,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 2,
"selected": true,
"text": " datacopy.addAll(data.map((e) => Map.from(e)));\n\n for (final item in datacopy) {\n item.remove(\"id\");\n }\n print(data);\n print(\"NA\\n\");\n print(datacopy);\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19507132/"
] |
74,286,113 | <p>I am trying to build a "unique" zipcode list based on the data from geojson.
The goal is to grep one whole line per zip code. There are multiple entries per zipcode possible, all i care is about grabbing one per Zip.</p>
<p>ive prepared a "unique" zip code file to pass as grep to run as a "filter" against the list.
However, this still returns multiple results per zip code.
When limiting the results with -m 1 then i only get the very first match.</p>
<p>How can i filter one entry per line from the "big file"?</p>
<p>The input (example)</p>
<pre><code>9417 TG
9423 TA
9431 HK
9883 TB
9965 TN
</code></pre>
<p>The command:
<code>grep -f infile.txt bigfile.txt</code></p>
<p>the output:</p>
<pre><code>9417 TG Spier Drenthe NLD Netherlands 52.8178 6.4592 ;
9423 TA Hoogersmilde Drenthe NLD Netherlands 52.9098 6.3685 ;
9417 TG Spier Drenthe NLD Netherlands 52.8178 6.4658 ;
9423 TA Hoogersmilde Drenthe NLD Netherlands 52.9066 6.3802 ;
9431 HK Westerbork Drenthe NLD Netherlands 52.8613 6.6029 ;
9431 HK Oosterwolde Friesland NLD Netherlands 52.9851 6.2986 ;
9883 TB Zuurdijk Groningen NLD Netherlands 53.3147 6.3558 ;
9965 TN Zuurdijk Groningen NLD Netherlands 53.3506 6.3691 ;
9965 TN Leens Groningen NLD Netherlands 53.3523 6.37 ;
9883 TB Oldehove Groningen NLD Netherlands 53.3108 6.3632 ;
</code></pre>
<p>As you can see, there are two entries for <code>9423 TA</code> and <code>9965 TN</code></p>
<p>How can I crunch that down to one entry per list?</p>
<p>Thank you kindly for your help!</p>
| [
{
"answer_id": 74286585,
"author": "anubhava",
"author_id": 548225,
"author_profile": "https://Stackoverflow.com/users/548225",
"pm_score": 3,
"selected": true,
"text": "awk"
},
{
"answer_id": 74287494,
"author": "Daweo",
"author_id": 10785975,
"author_profile": "https://Stackoverflow.com/users/10785975",
"pm_score": 2,
"selected": false,
"text": "AWK"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1883409/"
] |
74,286,116 | <p>I am making a simple tic tac toe game in order to practice the module pattern and factory pattern. i have implemented event listeners on the fields to mark x and o. but i need the x's and o's to also go inside the board array in order to compare with the winning combinations array.</p>
<p>i need to ultimately be able to find the winner after.</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>//player factory function
const createPlayer = (name,marker) => {
return {name,marker}
}
//gameboard object
const gameBoard = (() => {
//create board array
let board = []
for (i=0; i<9; i++) {
board.push("")
}
//add event listeners on each field that will mark field and change player's turn state
const fields = document.querySelectorAll(".field")
const nextTurn = document.querySelector(".message")
let turn = 0
fields.forEach((field) => {
field.addEventListener('click',handleClick,{once:true})
function handleClick() {
if(turn %= 2) {
field.innerHTML = "O"
field.classList.toggle("marker")
nextTurn.innerHTML= "Player X's turn"}
else {
field.innerHTML = "X"
field.classList.toggle("marker")
nextTurn.innerHTML= "Player O's turn"}
turn ++
}
})
//restart game
const restart = document.getElementById("restart-button")
restart.addEventListener("click",clicke)
function clicke() {
const fields = document.querySelectorAll(".field").innerHTML=""
}
return {
board,
}
})()
// game object
const game = (() => {
//declare players
const playerOne = createPlayer("player x", "x")
const playerTwo = createPlayer("player o", "o")
//starting point
let activePlayer = playerOne
let winnerDeclared = false
let remainingSpots = 9
//selectors
let playerName = document.querySelector('.message') //alert next turn
//winning conditons
const winningConditons = [
[0,1,2]
[3,4,5]
[6,7,8]
[0,3,8]
[1,4,7]
[2,5,8]
[0,4,8]
[2,4,6]
];
//check for winner
function checkWinner() {
}
function declareTie(){
playerName.innerHTML = "Its a tie!"
}
}
)()</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.gameboard{
display: grid;
grid-template-columns: repeat(3,1fr);
grid-gap: 5px;
}
.field{
width: 150px;
height: 150px;
background-color: #ededee;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="container">
<div class="header">
<div class="header-text">
Tic-Tac-Toe
</div>
</div>
<div class="body-container">
<div class="message">Player X's turn</div>
<div class="gameboard">
<div class="field"></div>
<div class="field"></div>
<div class="field"></div>
<div class="field"></div>
<div class="field"></div>
<div class="field"></div>
<div class="field"></div>
<div class="field"></div>
<div class="field"></div>
</div>
<div class="center">
<button id="restart-button">Restart</button>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74286530,
"author": "rajniszp",
"author_id": 15452072,
"author_profile": "https://Stackoverflow.com/users/15452072",
"pm_score": 0,
"selected": false,
"text": "//player factory function\nconst createPlayer = (name,marker) => {\n return {name,marker}\n}\n\n//gameboard object\nconst gameBoard = (() => {\n //create board array\n let board = []\n for (i=0; i<9; i++) {\n board.push(\"\")\n }\n\n\n //add event listeners on each field that will mark field and change player's turn state\n const fields = document.querySelectorAll(\".field\") \n const nextTurn = document.querySelector(\".message\")\n\n \n let turn = 0\n \n fields.forEach((field) => {\n field.addEventListener('click',handleClick,{once:true})\n\n function handleClick() {\n \n if(turn %= 2) {\n field.innerHTML = \"O\"\n field.classList.toggle(\"marker\")\n nextTurn.innerHTML= \"Player X's turn\"\n }\n else {\n field.innerHTML = \"X\"\n field.classList.toggle(\"marker\")\n nextTurn.innerHTML= \"Player O's turn\"\n }\n game.checkWinner(); // <- check winner after every move\n turn++;\n \n\n }\n \n })\n\n //restart game\n const restart = document.getElementById(\"restart-button\")\n\n restart.addEventListener(\"click\",clicke)\n\n function clicke() {\n console.log('you had a mistake here - you need to iterate the fields', document.querySelectorAll(\".field\"));\n const fields = document.querySelectorAll(\".field\").forEach(field => \n {\n field.innerHTML=\"\";\n // you also need to add the event listeners again where needed - field.addEventListener('click', ...)\n }\n );\n }\n\n \n \n\n return {\n board, \n }\n})()\n\n// game object\nconst game = (() => {\n\n //declare players\n const playerOne = createPlayer(\"player x\", \"x\")\n const playerTwo = createPlayer(\"player o\", \"o\")\n\n //starting point\n let activePlayer = playerOne\n let winnerDeclared = false\n let remainingSpots = 9\n\n //selectors\n let playerName = document.querySelector('.message') //alert next turn\n\n //winning conditons\n const winningConditons = [\n [0,1,2], // <- you forgot the commas here!\n [3,4,5],\n [6,7,8],\n [0,3,8],\n [1,4,7],\n [2,5,8],\n [0,4,8],\n [2,4,6]\n ];\n\n //check for winner\n function checkWinner() {\n console.log('do stuff here');\n }\n\n function declareTie(){\n playerName.innerHTML = \"Its a tie!\"\n }\n\n return { // <- you need to \"export\" a function to be able to use it\n checkWinner\n }\n}\n)()"
},
{
"answer_id": 74287200,
"author": "Asraf",
"author_id": 20361860,
"author_profile": "https://Stackoverflow.com/users/20361860",
"pm_score": 2,
"selected": true,
"text": "checkPlayerMeetsConditions()"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19120987/"
] |
74,286,136 | <p>I am currently trying to create a very simple app that displays a recipe and a network diagram.</p>
<p>I have gotten most of the way there, but I am receiving the following error:
Uncaught ReferenceError: Bokeh is not defined
at HTMLDocument.fn (?description=blueberry+pancakes:29:5)</p>
<p>I have tried implementing the solutions at the following locations:<br>
<a href="https://stackoverflow.com/questions/33486522/python-flask-app-with-interactive-bokeh-plots">Python Flask App with Interactive Bokeh plots</a><br>
<a href="https://stackoverflow.com/questions/33450773/embedding-a-bokeh-plot-in-flask">Embedding a bokeh plot in Flask</a><br>
<a href="https://stackoverflow.com/questions/35298029/embedding-bokeh-plot-and-datatable-in-flask">Embedding bokeh plot and datatable in flask</a><br>
<a href="https://stackoverflow.com/questions/67095144/bokeh-plot-not-visible-in-flask-application">Bokeh plot not visible in flask application</a><br></p>
<p>but nothing is really changing.</p>
<p>Below is my <em>current</em> version of index.html.</p>
<pre><code><html>
<head>
<title>Recipes</title>
<style>
.row {
display: flex;
}
.column {
flex: 50%;
}
</style>
<script scr="https://cdn.pydata.org/bokeh/release/bokeh-3.0.0.min.js"></script>
<script scr="https://cdn.pydata.org/bokeh/release/bokeh-widgets-3.0.0.min.js"></script>
<script scr="https://cdn.pydata.org/bokeh/release/bokeh-tables-3.0.0.min.js"></script>
<script scr="https://cdn.pydata.org/bokeh/release/bokeh-gl-3.0.0.min.js"></script>
<link
href="https://cdn.pydata.org/bokeh/release/bokeh-0.13.0.min.css"
rel="stylesheet" type="text/css">
<link
href="https://cdn.pydata.org/bokeh/release/bokeh-widgets-0.13.0.min.css"
rel="stylesheet" type="text/css">
<link
href="https://cdn.pydata.org/bokeh/release/bokeh-tables-0.13.0.min.css"
rel="stylesheet" type="text/css">
{{script | safe}}
</head>
<!-- <header>
{{ script|safe }}
</header> -->
<body>
<form action="" method="get">
Recipe Description: <input type="text" name="description">
<label for="diets">Choose a Diet:</label>
<select id="diets" name="diet_plan" size="2" multiple>
<option value="Vegan">Vegan</option>
<option value="Vegetarian">Vegetarian</option>
<option value="Nut-Free">Nut-Free</option>
<option value="Gluten-Free">Gluten-Free</option>
</select><br><br>
<input type="submit" value="Generate a recipe">
</form>
<h1>{{description}}</h1>
<h2>{{diet_plan}}</h2>
<div class="row">
<div class="column">
<h2>Ingredients</h2>
<ul>
{%for i in range(0, len)%}
<li>{{ingredients[i]}}</li>
{%endfor%}
</ul>
</div>
<div class="column">
<h2>Instructions</h2>
<ul>
{%for i in range(0, len)%}
<li>{{instructions[i]}}</li>
{%endfor%}
</ul>
</div>
</div>
<h1>{{div}}</h1>
<div>
{{div|safe }}
</div>
</body>
</html>
</code></pre>
<p>And here is the main portion of main.py.</p>
<pre><code>from flask import Flask
from flask import request, render_template, send_file
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
from bokeh.io import output_file, show
from bokeh.models import (BoxZoomTool, Circle, HoverTool, MultiLine, Plot, Range1d, ResetTool)
from bokeh.palettes import Spectral4
from bokeh.plotting import from_networkx, save
from bokeh.embed import components
from bokeh.resources import CDN
from io import BytesIO
import re
app = Flask(__name__)
@app.route("/")
def index():
description = request.args.get("description", "")
# diet_plan = request.form.getlist("diets", "")
diet_plan = request.args.get("diet_plan", "")
if description:
recipe, steps = get_ai_recipe()
ingredients = recipe["ingredient"] + " (" + recipe["qty"] + ")"
instructions = steps["instruction"]
script, div = generate_graph(recipe)
else:
recipe = None
steps = None
ingredients = pd.DataFrame({"ingredient" : []})
instructions = pd.DataFrame({"instruction" : []})
script, div = ("", "")
return render_template("index.html",
len = len(ingredients),
ingredients = ingredients,
instructions = instructions,
description = description,
diet_plan = diet_plan,
script = script,
div = div,
resources = CDN.render())
</code></pre>
<p>I didn't include the get_ai_recipe() or generate_graph() functions to save some space, but basically get_ai_recipe() returns 2 pandas dataframes, and generate_graph() returns a script and a div from components.</p>
<pre><code>script, div = components(plot)
return script, div
</code></pre>
<p>So the "plot" in that code is an actual "Plot" class from bokeh.models. Pretty much every online example I saw when trying to debug this uses figure() instead of Plot(). I'm not sure if that has anything to do with my issue, but if it does, I would appreciate help in figuring out how to convert the Plot to a figure.</p>
<p>Additionally, I am <em>very</em> new to flask and html (this is my very first interaction with them, really), so I'm not sure what all of the scripts/links in the head section are doing. I also do not know if those are the most recent versions of those links. I used the original version from the examples online and then updated them as far as I could, but I'm not sure if they go any further. Some examples used all of those, and some used just one. I assume this is where my issue lies, but I am not sure.</p>
<p>The code is definitely generating the div, as I have it printed as a title on the page, but it's unable to find bokeh.</p>
<p>I would appreciate any help.
Thanks!</p>
| [
{
"answer_id": 74286530,
"author": "rajniszp",
"author_id": 15452072,
"author_profile": "https://Stackoverflow.com/users/15452072",
"pm_score": 0,
"selected": false,
"text": "//player factory function\nconst createPlayer = (name,marker) => {\n return {name,marker}\n}\n\n//gameboard object\nconst gameBoard = (() => {\n //create board array\n let board = []\n for (i=0; i<9; i++) {\n board.push(\"\")\n }\n\n\n //add event listeners on each field that will mark field and change player's turn state\n const fields = document.querySelectorAll(\".field\") \n const nextTurn = document.querySelector(\".message\")\n\n \n let turn = 0\n \n fields.forEach((field) => {\n field.addEventListener('click',handleClick,{once:true})\n\n function handleClick() {\n \n if(turn %= 2) {\n field.innerHTML = \"O\"\n field.classList.toggle(\"marker\")\n nextTurn.innerHTML= \"Player X's turn\"\n }\n else {\n field.innerHTML = \"X\"\n field.classList.toggle(\"marker\")\n nextTurn.innerHTML= \"Player O's turn\"\n }\n game.checkWinner(); // <- check winner after every move\n turn++;\n \n\n }\n \n })\n\n //restart game\n const restart = document.getElementById(\"restart-button\")\n\n restart.addEventListener(\"click\",clicke)\n\n function clicke() {\n console.log('you had a mistake here - you need to iterate the fields', document.querySelectorAll(\".field\"));\n const fields = document.querySelectorAll(\".field\").forEach(field => \n {\n field.innerHTML=\"\";\n // you also need to add the event listeners again where needed - field.addEventListener('click', ...)\n }\n );\n }\n\n \n \n\n return {\n board, \n }\n})()\n\n// game object\nconst game = (() => {\n\n //declare players\n const playerOne = createPlayer(\"player x\", \"x\")\n const playerTwo = createPlayer(\"player o\", \"o\")\n\n //starting point\n let activePlayer = playerOne\n let winnerDeclared = false\n let remainingSpots = 9\n\n //selectors\n let playerName = document.querySelector('.message') //alert next turn\n\n //winning conditons\n const winningConditons = [\n [0,1,2], // <- you forgot the commas here!\n [3,4,5],\n [6,7,8],\n [0,3,8],\n [1,4,7],\n [2,5,8],\n [0,4,8],\n [2,4,6]\n ];\n\n //check for winner\n function checkWinner() {\n console.log('do stuff here');\n }\n\n function declareTie(){\n playerName.innerHTML = \"Its a tie!\"\n }\n\n return { // <- you need to \"export\" a function to be able to use it\n checkWinner\n }\n}\n)()"
},
{
"answer_id": 74287200,
"author": "Asraf",
"author_id": 20361860,
"author_profile": "https://Stackoverflow.com/users/20361860",
"pm_score": 2,
"selected": true,
"text": "checkPlayerMeetsConditions()"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9313545/"
] |
74,286,147 | <p>Hello i have the csv file below, imported with pandas <code>data = pd.read_csv("1.csv")</code>:</p>
<pre><code>x1,x2,xb,y
−2,1,1,1
</code></pre>
<p>I need to convert the negative number (-2) to integer with <code>int()</code>, but i get <code>ValueError</code>:</p>
<pre><code>print(data.iloc[1-1]['x1'])
> -2 # str
print(int(data.iloc[1-1]['x1']))
> ValueError: invalid literal for int() with base 10: '−2`
</code></pre>
<p>I haven't the error when try to convert positive number:</p>
<pre><code>print(data.iloc[1-1]['x2'])
> 1 # str
print(int(data.iloc[1-1]['x2']))
> 1 # int
</code></pre>
| [
{
"answer_id": 74286302,
"author": "Csaba",
"author_id": 12259123,
"author_profile": "https://Stackoverflow.com/users/12259123",
"pm_score": 1,
"selected": false,
"text": "print(int(data.iloc[1-1]['x1'].replace(\"−\", \"-\")))\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16974071/"
] |
74,286,149 | <p>Let's say I have a React component somewhat like this:</p>
<pre><code>function App() {
const [step, setStep] = useState(0);
const [someValue, setSomeValue] = useState("xyz");
const var1 = "abc";
const var2 = "def";
function StepZero() {
return <div>
<p>{someValue}</p>
<input type="text" id="fname" name="fname" />
<h1>{var1} {var2}</h1>
<Button onClick={() => setSomeValue("123")}>Click</Button>
</div>;
}
function StepOne() {
return <div>
<h1>{someValue}</h1>
<Button onClick={() => setSomeValue("456")}>Click</Button>
<h2>{var1}</h2>
<h3>{var2}</h3>
</div>;
}
return (
<div>
{step === 0 ? (
<StepZero />
) : (
<StepOne />
)}
</div>
);
}
</code></pre>
<p>What happens here is, once someValue gets set, the whole StepZero gets re-rendered and the input lost. Really any user interaction gets reset, e.g. an accordion that got opened.
What resolves this is putting StepZero and StepOne directly into the return function, or putting them outside the App component and then passing all the variables in the params like:</p>
<pre><code>{ var1, var2, someValue, setSomeValue }
</code></pre>
<p>Is there a better way to do this that I can separate the two steps into components while still being able to access the states and variables/constants, without state changes re-rendering the components every time, or without having to pass all the required variables as parameters?</p>
<p><em>Note this example app isn't meant to do anything functionally useful</em></p>
| [
{
"answer_id": 74286403,
"author": "Azzam Michel",
"author_id": 14568922,
"author_profile": "https://Stackoverflow.com/users/14568922",
"pm_score": 1,
"selected": false,
"text": " const [step, setStep] = useState(0);\n const [someValue, setSomeValue] = useState(\"xyz\");\n const var1 = useRef(\"abc\");\n const var2 = useRef(\"def\");\n"
},
{
"answer_id": 74286433,
"author": "Anees Hikmat Abu Hmiad",
"author_id": 3288123,
"author_profile": "https://Stackoverflow.com/users/3288123",
"pm_score": 0,
"selected": false,
"text": "function StepZero(props) {\n return <div>\n <p>{props.someValue}</p>\n <input type=\"text\" id=\"fname\" name=\"fname\" />\n <h1>{var1} {var2}</h1>\n <Button onClick={() => props.setSomeValue(\"123\")}>Click</Button>\n </div>;\n }\n \n function StepOne(props) {\n return <div>\n <h1>{props.someValue}</h1>\n <Button onClick={() => props.setSomeValue(\"456\")}>Click</Button>\n <h2>{var1}</h2>\n <h3>{var2}</h3>\n </div>;\n }\n\nfunction App() {\n const [step, setStep] = useState(0);\n const [someValue, setSomeValue] = useState(\"xyz\");\n const var1 = \"abc\";\n const var2 = \"def\";\n \n return (\n <div>\n {step === 0 ? (\n <StepZero {youProps}/>\n ) : (\n <StepOne {youProps}/>\n )}\n </div>\n );\n }\n"
},
{
"answer_id": 74286499,
"author": "JohnS",
"author_id": 19941941,
"author_profile": "https://Stackoverflow.com/users/19941941",
"pm_score": 0,
"selected": false,
"text": "function StepZero({val,var1,var2,callback}) {\n return <div>\n <p>{val}</p>\n <input type=\"text\" id=\"fname\" name=\"fname\" />\n <h1>{var1} {var2}</h1>\n <Button onClick={() => callback(\"123\")}>Click</Button>\n </div>;\n }\n\nfunction App() {\n const [step, setStep] = useState(0);\n const [someValue, setSomeValue] = useState(\"xyz\");\n const var1 = \"abc\";\n const var2 = \"def\";\n return (\n <div> \n <StepZero val={someValue} var1={var1} var2={var2} callback={setSomeValue} /> \n </div>\n );\n}\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2964875/"
] |
74,286,152 | <p>I wanted to create a python function which should read each
character of a text file and then count and display
the occurrence of alphabets E and T individually (including
small cases e and t too).</p>
<pre><code>def test():
f = open("poem.txt",'r')
count = 0
count1 =0
try:
line = f.readlines()
for i in line:
for x in line:
if (i[x] in 'Ee'):
count+=1
else:
if (i[x] in 'Tt'):
count1+=1
print("E or e",count)
print("T or t",count1)
except EOFError:
f.close()
test()
</code></pre>
<p>This is what I tried</p>
<p>And it gave :</p>
<pre><code>File "/Users/ansusinha/Desktop/Tution/Untitled15.py", line 23, in test
if (i[x] in 'Ee'):
TypeError: string indices must be integers
</code></pre>
<p>What am I missing here?</p>
| [
{
"answer_id": 74286298,
"author": "Claudio",
"author_id": 7711283,
"author_profile": "https://Stackoverflow.com/users/7711283",
"pm_score": 2,
"selected": false,
"text": ".count()"
},
{
"answer_id": 74286356,
"author": "Eveheeero",
"author_id": 16761173,
"author_profile": "https://Stackoverflow.com/users/16761173",
"pm_score": 2,
"selected": true,
"text": "def test():\n f = open(\"poem.txt\",'r')\n count = 0\n count1 =0\n try:\n lines = f.readlines()\n for line in lines:\n for char_in_line in line:\n if (char_in_line in 'Ee'):\n count+=1\n elif (char_in_line in 'Tt'):\n count1+=1\n print(\"E or e\",count)\n print(\"T or t\",count1)\n except EOFError:\n f.close()\ntest()\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16779642/"
] |
74,286,159 | <p>I would like to know how i can refactor my code using a Map Data Structure and Lambdas.</p>
<p>Here is my method:</p>
<pre><code>private void validateUserFields(User user) {
if(user.getName() == null){
throw new RuntimeException("The user's name cannot be null");
}
if(user.getLastName() == null){
throw new RuntimeException("The user's lastName cannot be null");
}
if(user.getDni() == null){
throw new RuntimeException("The user's dni cannot be null");
}
if(user.getVehicle() == null){
throw new RuntimeException("The user's vehicle cannot be null");
}
}
</code></pre>
<p>I expect a elegant an a simple way to refactor my code.</p>
| [
{
"answer_id": 74286503,
"author": "Teddy Tsai",
"author_id": 16959486,
"author_profile": "https://Stackoverflow.com/users/16959486",
"pm_score": 0,
"selected": false,
"text": "public class App {\n public static HashMap<String, Predicate<User>> VALIDATION_FUNCTIONS = new HashMap<>();\n\n static {\n VALIDATION_FUNCTIONS.put(\"NAME\", user -> user.getName() != null);\n VALIDATION_FUNCTIONS.put(\"MOREFIELDS\", user -> user.getMorefields() != null);\n }\n\n public static void main(String[] args) {\n validateUserFields(new User());\n }\n\n private static void validateUserFields(User user) {\n VALIDATION_FUNCTIONS.forEach((field,function) -> {\n if (!function.test(user))\n throw new RuntimeException(field + \" is null\");\n });\n }\n\n @Getter\n @NoArgsConstructor\n static class User {\n private String name;\n private String morefields;\n }\n}\n"
},
{
"answer_id": 74286887,
"author": "Bohemian",
"author_id": 256196,
"author_profile": "https://Stackoverflow.com/users/256196",
"pm_score": 2,
"selected": true,
"text": "private static Map<String, Function<User, ?>> VALIDATIONS = Map.of(\n \"name\", User::getName,\n \"lastName\", User::getLastName,\n \"dni\", User::getDni,\n \"vehicle\", User::getVehicle\n);\n\nprivate void validateUserFields(User user) {\n VALIDATIONS.entrySet().stream()\n .filter(entry -> entry.getValue().apply(user) == null)\n .map(Map.Entry::getKey)\n .map(field -> String.format(\"The user's %s cannot be null\", field))\n .map(RuntimeException::new)\n .findFirst()\n .ifPresent(e -> {\n throw e;\n });\n}\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20395420/"
] |
74,286,161 | <p>I am currently using nodejs to build a form that retrieves revenue based on input of the weight and parcel type.</p>
<p>Users in the form are able to select the weight and type (both are dropdown with options select) and will be directed to the next page that will display the revenue. However, the users are able to add rows (up to 5 times) so there can be 5 different weight and 5 different parcel types. Using HTML and Javascript, I have created the table to add new row upon clicking "Add new".</p>
<p>I am currently able to retrieve revenue based on a single row entry. I am unable to retrieve the revenue based on more rows (up to 5). The revenue must be sum up together if there are more than 1 row.</p>
<p>Here are my codes:</p>
<p>Upon retrieving information from MySQL, these are my current code:</p>
<pre><code>
var getsql2 =`SELECT Revenue FROM revenuecard where weight = '${weight}' and type = '${parceltype}';
con1.query(getsql2, function (err, data, fields) {
if (err) throw err;
console.log(data);
var revenue = JSON.stringify(revenue);
//trim the revenue and remove the brackets
revenue = parseFloat(revenue);
//data returns the output of the revenue
</code></pre>
<p>In HTML to display the price</p>
<pre><code>
<label style="text-align:right; padding-right:25px;" id="revenue" class="revenue"> <%= revenue %> </label>
</code></pre>
<p>I am able to retrieve and display the revenue based on the 1 weight and type. However, when I add new row and have another row of weight and type, I am unable to retrieve the data. I want to add both revenue up. E.g. if There are 3 rows, the revenue calculated from 1st row will add with 2nd and 3rd row based on the different weight and type selected for each row. Is there a way to approach this?</p>
| [
{
"answer_id": 74286503,
"author": "Teddy Tsai",
"author_id": 16959486,
"author_profile": "https://Stackoverflow.com/users/16959486",
"pm_score": 0,
"selected": false,
"text": "public class App {\n public static HashMap<String, Predicate<User>> VALIDATION_FUNCTIONS = new HashMap<>();\n\n static {\n VALIDATION_FUNCTIONS.put(\"NAME\", user -> user.getName() != null);\n VALIDATION_FUNCTIONS.put(\"MOREFIELDS\", user -> user.getMorefields() != null);\n }\n\n public static void main(String[] args) {\n validateUserFields(new User());\n }\n\n private static void validateUserFields(User user) {\n VALIDATION_FUNCTIONS.forEach((field,function) -> {\n if (!function.test(user))\n throw new RuntimeException(field + \" is null\");\n });\n }\n\n @Getter\n @NoArgsConstructor\n static class User {\n private String name;\n private String morefields;\n }\n}\n"
},
{
"answer_id": 74286887,
"author": "Bohemian",
"author_id": 256196,
"author_profile": "https://Stackoverflow.com/users/256196",
"pm_score": 2,
"selected": true,
"text": "private static Map<String, Function<User, ?>> VALIDATIONS = Map.of(\n \"name\", User::getName,\n \"lastName\", User::getLastName,\n \"dni\", User::getDni,\n \"vehicle\", User::getVehicle\n);\n\nprivate void validateUserFields(User user) {\n VALIDATIONS.entrySet().stream()\n .filter(entry -> entry.getValue().apply(user) == null)\n .map(Map.Entry::getKey)\n .map(field -> String.format(\"The user's %s cannot be null\", field))\n .map(RuntimeException::new)\n .findFirst()\n .ifPresent(e -> {\n throw e;\n });\n}\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5172172/"
] |
74,286,171 | <p>I would like to write a function that takes multiple dataframes that have the same structure, does specific transformations and saves the transformations inplace.</p>
<p><strong>Dummy dataframes</strong></p>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({"Full name" : ["John Doe","Deep Smith","Julia Carter","Kate Newton","Sandy Thompson"],
"Monthly Sales" : [25,30,35,40,45]})
df2 = pd.DataFrame({"Full name" : ["Alicia Williams","Kriten John","Jessica Adams","Isaac Newton","Whitney Gordon"],
"Monthly Sales" : [35,20,50,15,40]})
</code></pre>
<p><strong>Transformative function</strong></p>
<p>I don't want to return the dataframe, but rather save those transformations in place.</p>
<pre class="lang-py prettyprint-override"><code>def tidy_dfs(dfs):
for df in dfs:
# Drop first row
df = df.iloc[1: , :]
# Replace spaces in columns
df.columns = [c.replace(' ', '_') for c in df]
# change cols to lower
df.columns = [c.lower() for c in df]
return df
</code></pre>
<p>saving <code>df,df2 = tidy_dfs([df,df2])</code> of course won't work as we're outside the loop.</p>
<p><strong>Results</strong>
What would be a way to call this function and save the transformation inplace?</p>
<pre class="lang-py prettyprint-override"><code>tidy_dfs([df,df2])
</code></pre>
| [
{
"answer_id": 74286211,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 2,
"selected": true,
"text": "out"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6334265/"
] |
74,286,191 | <p>The goal is to match two arrays by id. I need to check if <code>stopId</code> is in both <code>info</code> and <code>times</code> arrays and combine matching arrays.</p>
<p>What should be the proper check to find out if id matches? I've attached an example, I was trying to implement using <code>includes</code>.</p>
<p>Could you please give me an advise?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>const info = [
{
stopId: 1,
name: "N1"
},
{
stopId: 2,
name: "N2"
},
{
stopId: 3,
name: "N3"
}
]
const times = [
{
stopId: 1,
time: "T1"
},
{
stopId: 3,
time: "T2"
}
]
// Expected
// [
// {
// stopId: 1,
// name: "123",
// time: "T1"
// },
// {
// stopId: 2,
// name: "123"
// },
// {
// stopId: 3,
// name: "123",
// time: "T2"
// }
// ]
const res = () => {
const final = [];
info.forEach((item) => {
if (times.includes(item.stopId)) { // How to check if stopId matches
final.push({ })
}
})
}
console.log(res())</code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74286211,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 2,
"selected": true,
"text": "out"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9886585/"
] |
74,286,200 | <p>I am coming to you today,
I tried to make an html generator from a json file in javascript.
The problem being that arrived at a certain moment the children "appendChild" to the previous element instead of "appendChild" to the parent</p>
<p>here is my code :</p>
<pre class="lang-js prettyprint-override"><code>$(document).ready(function(){
$.getJSON('THE JSON FILE FROM URL', function(data){
const components = data.htmlComponents.tableSuiviCommandes.components;
createHtmlFromJson(components)
}).fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
function createHtmlFromJson(json, parent){
json.forEach(jsonElement => {
// log("jsonElemement", jsonElement)
createdElement = document.createElement(jsonElement.balise);
if(jsonElement.content) createdElement.innerHTML = jsonElement.content;
jsonElement.attributes?.forEach(element => {
createdElement.setAttribute(element.name, element.content);
});
if(!parent){
document.body.appendChild(createdElement);
}else {
parent.appendChild(createdElement);
}
jsonElement.childs?.forEach(element => {
let theParent = createdElement;
if(element != typeof Array) element = [element];
createHtmlFromJson(element, theParent);
});
});
}
function log(name, value){
console.log("----------");
console.log(name);
console.log(value);
console.log("----------")
}
});
</code></pre>
<p>the json file :</p>
<pre class="lang-json prettyprint-override"><code>{
"htmlComponents": {
"tableSuiviCommandes": {
"components": [
{
"balise": "div",
"attributes": [
{
"name": "class",
"content": "containerTable"
}
],
"childs": [
{
"balise": "table",
"childs": [
{
"balise": "thead",
"childs": [
{
"balise": "tr",
"childs": [
{
"balise": "th",
"content": "Id"
},
{
"balise": "th",
"content": "Statut"
},
{
"balise": "th",
"content": "Voir la demande"
},
{
"balise": "th",
"content": "Objet"
},
{
"balise": "th",
"content": "Projet/Application"
},
{
"balise": "th",
"content": "Demandeur(s)"
},
{
"balise": "th",
"content": "Site"
},
{
"balise": "th",
"content": "Expression de besoin"
},
{
"balise": "th",
"content": "Référence interne"
},
{
"balise": "th",
"content": "CDC retenu"
},
{
"balise": "th",
"content": "N°Cotation"
},
{
"balise": "th",
"content": "N°Devis"
},
{
"balise": "th",
"content": "Date devis"
},
{
"balise": "th",
"content": "N°DEMAP"
},
{
"balise": "th",
"content": "N°CMD"
},
{
"balise": "th",
"content": "N°GAFI"
},
{
"balise": "th",
"content": "Date prévisionnelle de livraison"
},
{
"balise": "th",
"content": "Date de livraison"
},
{
"balise": "th",
"content": "Commentaire"
}
]
}
]
},
{
"balise": "tbody",
"attributes": [
{
"name": "id",
"content": "tableauSuivi"
}
]
}
]
}
]
}
]
}
}
}
</code></pre>
<p>the html generate :</p>
<p><a href="https://i.stack.imgur.com/lalWZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lalWZ.png" alt="enter image description here" /></a></p>
<p>I tried with the debbuger to make step by step, but I really don't understand why theParent is not really the parent so that the children are children of the previous element</p>
| [
{
"answer_id": 74286211,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 2,
"selected": true,
"text": "out"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20395393/"
] |
74,286,213 | <p>I have dataset whose Label is 0 or 1.</p>
<p>I want to divide my data into test and train sets.For this, I used the
<code>train_test_split</code> method from sklearn at first,
But I want to select the test data in such a way that 10% of them are from class 0 and 90% are from class 1.</p>
<p>How can I do this?</p>
| [
{
"answer_id": 74286329,
"author": "Dan Nagle",
"author_id": 2202018,
"author_profile": "https://Stackoverflow.com/users/2202018",
"pm_score": 2,
"selected": false,
"text": "stratify"
},
{
"answer_id": 74286489,
"author": "JArmunia",
"author_id": 8480652,
"author_profile": "https://Stackoverflow.com/users/8480652",
"pm_score": 0,
"selected": false,
"text": "df_0 = df.loc[df.class == 0]\ndf_1 = df.loc[df.class == 1]\n\ntest_0, train_0 = train_test_split(df_0, 0.1)\ntest_1, train_1 = train_test_split(df_1, 0.9)\n\ntest = pd.concat((test_0, test_1), \n axis = 1, \n ignore_index = True).sample(1) # sample(1) is to shuffle the df\ntrain = pd.concat((train_0, train_1), \n axis = 1, \n ignore_index = True).sample(1)\n\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13356545/"
] |
74,286,233 | <p>First of all, I'm a new user of Symfony</p>
<p>And actually I'm customing my form EasyAdmin with some fields and I have an issue with this one :</p>
<p><code>ChoiceField::new('villa')->setChoices($villasChoices)->allowMultipleChoices()</code></p>
<p>I get this error because of the allowMultipleChoices() func :</p>
<p><code>Unable to transform value for property path "villa": Expected an array.</code></p>
<p>My field is actually a collection type, That's why I have this error, there is my entity</p>
<pre><code> #[ORM\OneToMany(mappedBy: 'Name', targetEntity: Villa::class)]
private Collection $Villa;
public function __construct()
{
$this->Villa = new ArrayCollection();
}
/**
* @return Collection<int, Villa>
*/
public function getVilla(): Collection
{
return $this->Villa;
}
</code></pre>
<p>How can I remplace Collection type by Array ?</p>
| [
{
"answer_id": 74286329,
"author": "Dan Nagle",
"author_id": 2202018,
"author_profile": "https://Stackoverflow.com/users/2202018",
"pm_score": 2,
"selected": false,
"text": "stratify"
},
{
"answer_id": 74286489,
"author": "JArmunia",
"author_id": 8480652,
"author_profile": "https://Stackoverflow.com/users/8480652",
"pm_score": 0,
"selected": false,
"text": "df_0 = df.loc[df.class == 0]\ndf_1 = df.loc[df.class == 1]\n\ntest_0, train_0 = train_test_split(df_0, 0.1)\ntest_1, train_1 = train_test_split(df_1, 0.9)\n\ntest = pd.concat((test_0, test_1), \n axis = 1, \n ignore_index = True).sample(1) # sample(1) is to shuffle the df\ntrain = pd.concat((train_0, train_1), \n axis = 1, \n ignore_index = True).sample(1)\n\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18629039/"
] |
74,286,240 | <p>I have the follow List(<strong>InputData</strong>), and I would like to group by <strong>Vendor</strong> then by <strong>Type</strong> and Summarize by <strong>NumberInvoice</strong> and Concatenate by <strong>Month</strong> <a href="https://i.stack.imgur.com/wdiiv.png" rel="nofollow noreferrer">as you see the Input Data</a>
and this is <a href="https://i.stack.imgur.com/tEaBa.png" rel="nofollow noreferrer">the output</a></p>
<pre><code>private static void Main()
{
var InputData= new List<Invoice>()
{
new Invoice{ Vendor = "Microsoft", NumberInvoice= 10, Type= "PC", Month = 1 },
new Invoice{ Vendor = "Microsoft", NumberInvoice= 10, Type= "PC", Month = 2 },
new Invoice{ Vendor = "Microsoft", NumberInvoice= 10, Type= "Surface", Month = 1 },
new Invoice{ Vendor = "Microsoft", NumberInvoice= 20, Type= "PC", Month = 1 },
new Invoice{ Vendor = "Microsoft", NumberInvoice= 20, Type= "PC", Month = 2 },
new Invoice{ Vendor = "Microsoft", NumberInvoice= 30, Type= "Surface", Month = 1 },
new Invoice{ Vendor = "IBM", NumberInvoice= 50, Type= "Network", Month = 5 },
new Invoice{ Vendor = "IBM", NumberInvoice= 60, Type= "Graphic Card", Month = 6 }
};
}
public class Invoice
{
public string Vendor { get; set; }
public int NumberInvoice{ get; set; }
public string Type{ get; set; }
public int Month { get; set; }
}
</code></pre>
<p>I did this so far, but it is not working as my output result.
If I comment the follow line, it will show my result but without Summarizing.</p>
<pre><code>//NumberInvoice = Enumerable.Sum((decimal)key.NumberInvoice)
</code></pre>
<p>The Code:</p>
<pre><code>var result = InputData
.GroupBy(
x => new {
x.Vendor,
x.Type,
x.NumberInvoice
}, // key selector
x => x.Month, // element selector
(key, month) => new Invoice
{
Vendor = key.Vendor,
Type = key.Type,
month = string.Join(",", month),
NumberInvoice = Enumerable.Sum((decimal)key.NumberInvoice)
})
.ToList();
</code></pre>
<p><strong>Update (Explain):</strong>
I need to Group by Columns, and concatenate 1 column, and do the Sum for 1 Column.</p>
<ol>
<li>Group by : 1st by <strong>Vendor</strong> then by <strong>Type</strong></li>
<li>Concatenate by: <strong>Month</strong></li>
<li>Sum by :<strong>NumberInvoice</strong></li>
</ol>
<p>So the result in above example is:
<a href="https://i.stack.imgur.com/jo97U.png" rel="nofollow noreferrer">This the output</a></p>
| [
{
"answer_id": 74301308,
"author": "jdweng",
"author_id": 5015238,
"author_profile": "https://Stackoverflow.com/users/5015238",
"pm_score": 1,
"selected": true,
"text": " var result = InputData\n .OrderBy(x => x.Month)\n .GroupBy(x => x.Month)\n .SelectMany(x => x.GroupBy(y => new {y.Vendor, y.Type, y.NumberInvoice})\n .Select(y => new { Vendor = y.Key.Vendor, Type = y.Key.Type, month = x.Key, numberInvoices = y.Count()}).ToList()).ToList();\n"
},
{
"answer_id": 74302920,
"author": "sgmoore",
"author_id": 125759,
"author_profile": "https://Stackoverflow.com/users/125759",
"pm_score": 1,
"selected": false,
"text": "var result = InputData\n // Group by Vendor and Type\n .GroupBy(x => new { x.Vendor, x.Type, })\n .Select(g => new // Invoice\n {\n Vendor = g.Key.Vendor,\n Type = g.Key.Type,\n\n // Select all the distinct months in the group and concatenate them\n Month = String.Join(\",\", g.Select(a => a.Month).OrderBy(a => a).Distinct()),\n\n // Sum all the NumberInvoices in the group\n NumberInvoice = g.Sum(a => a.NumberInvoice),\n });\n\n \n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19239295/"
] |
74,286,244 | <p>I am having troubles changing the color of a specific element in a SVG on hover. I need to do that in JS and not CSS.</p>
<p>The element as a class "col_05" and I would need that on hover on that element, the fill color change to yellow.</p>
<p>On mouseout then the fill color should be back to the original.</p>
<p>Here is a jsfiddle</p>
<p><a href="https://jsfiddle.net/y7qr6xse/2/" rel="nofollow noreferrer">https://jsfiddle.net/y7qr6xse/2/</a></p>
<p>What I tried</p>
<pre><code><svg id="Ebene_1" data-name="Ebene 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 117.28 114.89">
<rect class="col_05" x="3" y="3" width="110" height="110" style="fill: #e5211e;"/>
<script>
col_05.addEventListener('mouseover', function handleMouseOver() {
col_05.style.fill = 'yellow';
});
</script>
</svg>
</code></pre>
| [
{
"answer_id": 74301308,
"author": "jdweng",
"author_id": 5015238,
"author_profile": "https://Stackoverflow.com/users/5015238",
"pm_score": 1,
"selected": true,
"text": " var result = InputData\n .OrderBy(x => x.Month)\n .GroupBy(x => x.Month)\n .SelectMany(x => x.GroupBy(y => new {y.Vendor, y.Type, y.NumberInvoice})\n .Select(y => new { Vendor = y.Key.Vendor, Type = y.Key.Type, month = x.Key, numberInvoices = y.Count()}).ToList()).ToList();\n"
},
{
"answer_id": 74302920,
"author": "sgmoore",
"author_id": 125759,
"author_profile": "https://Stackoverflow.com/users/125759",
"pm_score": 1,
"selected": false,
"text": "var result = InputData\n // Group by Vendor and Type\n .GroupBy(x => new { x.Vendor, x.Type, })\n .Select(g => new // Invoice\n {\n Vendor = g.Key.Vendor,\n Type = g.Key.Type,\n\n // Select all the distinct months in the group and concatenate them\n Month = String.Join(\",\", g.Select(a => a.Month).OrderBy(a => a).Distinct()),\n\n // Sum all the NumberInvoices in the group\n NumberInvoice = g.Sum(a => a.NumberInvoice),\n });\n\n \n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20386191/"
] |
74,286,259 | <p>As a minimal example, say I have a tensor of the form:</p>
<pre><code>[[ 1. 0. 3. ]
[ 7. 5. 6. ]
[ 0. 0. 0. ]
[ 0. 11. 1. ]
[ 0. 0. 0. ]
[ 0. 0. 0. ]
[13. 14. 16.5]]
</code></pre>
<p>Is there a way (natively in tensorflow) to impute the fully zeroed rows such their values are assigned to be equal to the last non-fully zeroed row? I.e. ->:</p>
<pre><code>[[ 1. 0. 3. ]
[ 7. 5. 6. ]
[ 7. 5. 6. ]
[ 0. 11. 1. ]
[ 0. 11. 1. ]
[ 0. 11. 1. ]
[13. 14. 16.5]]
</code></pre>
<p>I thought about using <code>tf.tensor_scatter_nd_update</code> but with no success.</p>
| [
{
"answer_id": 74287592,
"author": "Mohammad Ahmed",
"author_id": 7746219,
"author_profile": "https://Stackoverflow.com/users/7746219",
"pm_score": 1,
"selected": false,
"text": "data = tf.constant([[ 1., 0., 3. ],\n [ 7., 5., 6. ],\n [ 0., 0., 0. ],\n [ 0., 11., 1. ],\n [ 0., 0., 0. ],\n [ 0., 0., 0. ],\n [13., 14., 16.5]])\nrows_length = data.shape[-1]\n"
},
{
"answer_id": 74288480,
"author": "V.M",
"author_id": 8143158,
"author_profile": "https://Stackoverflow.com/users/8143158",
"pm_score": 3,
"selected": true,
"text": "tf.gather(a, indices)"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18704081/"
] |
74,286,276 | <p>I have an array of objects let's say processDetails. I want to convert it into an array of objects where each object has only two fields instead of every other field. How do I go about it?</p>
<pre><code>"processDetails" : [
{
"process": "details",
"stage": "done",
"status": "collected",
"updatedAt" : ISODate("2017-11-04T04:53:54.623Z"),
"updatedBy" : "BuubebcikkMdFo5Np",
"history" : [
{
"status": "pending",
"createdAt" : ISODate("2017-11-04T04:53:54.257Z"),
"createdBy": "BuubebcikkMdFo5Np",
"assignedTo" : "BuubebcikkMdFo5Np"
},
{
"status": "collected",
"notes": null,
"createdAt" : ISODate("2017-11-04T04:53:54.623Z"),
"createdBy": "BuubebcikkMdFo5Np",
"assignedTo": "BuubebcikkMdFo5Np"
}
],
"incomplete": null
}
]
</code></pre>
<pre><code>"processDetails" : [
{
"process": "details",
"stage": "done"
}
]
</code></pre>
| [
{
"answer_id": 74287592,
"author": "Mohammad Ahmed",
"author_id": 7746219,
"author_profile": "https://Stackoverflow.com/users/7746219",
"pm_score": 1,
"selected": false,
"text": "data = tf.constant([[ 1., 0., 3. ],\n [ 7., 5., 6. ],\n [ 0., 0., 0. ],\n [ 0., 11., 1. ],\n [ 0., 0., 0. ],\n [ 0., 0., 0. ],\n [13., 14., 16.5]])\nrows_length = data.shape[-1]\n"
},
{
"answer_id": 74288480,
"author": "V.M",
"author_id": 8143158,
"author_profile": "https://Stackoverflow.com/users/8143158",
"pm_score": 3,
"selected": true,
"text": "tf.gather(a, indices)"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8112870/"
] |
74,286,280 | <p>i am having difficulties combining/mergin 6 replicate dataframes into a single long format dataframe. By replicates, I mean two data parameters measured from the same experiment repeated 3 times.</p>
<p>I have made small examples of what the data looks like:</p>
<p>GFP exp 1.</p>
<p>GFP1:</p>
<pre><code> time species a species b species c . . .
1 0.24 -1518 -1566 163 . . .
2 0.72 -1408 -1533 43 . . .
3 0.96 -1460 -1573 -133 . . .
4 1.20 -1462 -1505 -398 . . .
</code></pre>
<p>(and GFP2 & GFP3 with same format but different values)</p>
<p>OD exp 1.
OD1:</p>
<pre><code> time species a species b species c . . .
1 0.24 -0.03 -0.03 -0.01 . . .
2 0.72 -0.03 -0.03 0.00 . . .
3 0.96 -0.05 -0.04 -0.01 . . .
4 1.20 -0.04 -0.03 0.00 . . .
</code></pre>
<p>(and then OD2 & OD3 with same format but different values)</p>
<p>This means i have 6 seperate datasets, with same amount of columns and rows but with different data values. What i would like to end up with is one long format dataframe that looks like this, preferably with an experiment id added:</p>
<pre><code> time experiment media od gfp
1 0.24 1 species a -0.03 -1518
2 0.24 2 species a -0.02 -1519
3 0.24 3 species a -0.02 -1242
4 0.72 1 species a -0.03 -1408
5 0.72 2 species a -0.04 -1470
6 0.72 3 species a -0.04 -1228
7 0.96 1 species a -0.05 -1460
8 0.96 2 species a -0.06 -1478
9 0.96 3 species a -0.05 -1214
10 1.20 1 species a -0.04 -1462
11 1.20 2 species a -0.05 -1402
12 1.20 3 species a -0.06 -1227
</code></pre>
<p>I hope everything makes sense, if not i will be happy to elaborate. Thanks in advance.</p>
| [
{
"answer_id": 74286565,
"author": "Marc in the box",
"author_id": 1199289,
"author_profile": "https://Stackoverflow.com/users/1199289",
"pm_score": 2,
"selected": true,
"text": "od <- read.table(text = \"time species_a species_b species_c\n0.24 -0.03 -0.03 -0.01\n0.72 -0.03 -0.03 0.00\n0.96 -0.05 -0.04 -0.01\n1.20 -0.04 -0.03 0.00\", \n header = TRUE, sep = \"\", check.names = F)\nod\n\n\ngfp <- read.table(text = \"time species_a species_b species_c\n 0.24 -1518 -1566 163\n 0.72 -1408 -1533 43\n 0.96 -1460 -1573 -133\n 1.20 -1462 -1505 -398\", \n header = TRUE, sep = \"\", check.names = F)\ngfp\n\n\nlibrary(reshape2)\nod2 <- melt(data = od, id.vars = \"time\", value.name = \"od\")\ngfp2 <- melt(data = gfp, id.vars = \"time\", value.name = \"gfp\")\n\n(df <- merge(x = od2, y = gfp2, all = TRUE))\n\n# time variable od gfp\n# 1 0.24 species_a -0.03 -1518\n# 2 0.24 species_b -0.03 -1566\n# 3 0.24 species_c -0.01 163\n# 4 0.72 species_a -0.03 -1408\n# 5 0.72 species_b -0.03 -1533\n# 6 0.72 species_c 0.00 43\n# 7 0.96 species_a -0.05 -1460\n# 8 0.96 species_b -0.04 -1573\n# 9 0.96 species_c -0.01 -133\n# 10 1.20 species_a -0.04 -1462\n# 11 1.20 species_b -0.03 -1505\n# 12 1.20 species_c 0.00 -398\n"
},
{
"answer_id": 74286647,
"author": "onyambu",
"author_id": 8380272,
"author_profile": "https://Stackoverflow.com/users/8380272",
"pm_score": 2,
"selected": false,
"text": "lst(od, gfp) %>%\n bind_rows(.id = 'name')%>%\n reshape2::recast(time + variable ~ name, id.var = c('name', 'time'))\n\n time variable gfp od\n1 0.24 species_a -1518 -0.03\n2 0.24 species_b -1566 -0.03\n3 0.24 species_c 163 -0.01\n4 0.72 species_a -1408 -0.03\n5 0.72 species_b -1533 -0.03\n6 0.72 species_c 43 0.00\n7 0.96 species_a -1460 -0.05\n8 0.96 species_b -1573 -0.04\n9 0.96 species_c -133 -0.01\n10 1.20 species_a -1462 -0.04\n11 1.20 species_b -1505 -0.03\n12 1.20 species_c -398 0.00\n"
},
{
"answer_id": 74286977,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 1,
"selected": false,
"text": "library(tidyr)\nlibrary(dplyr) \n\n# note use of `.id` arg to create “replicate number” column\nGFP <- bind_rows(GFP1, GFP2, GFP3, .id = \"rep\") %>%\n pivot_longer(\n starts_with(\"species\"),\n names_to = \"media\",\n values_to = \"gfp\"\n )\n\nOD <- bind_rows(OD1, OD2, OD3, .id = \"rep\") %>%\n pivot_longer(\n starts_with(\"species\"),\n names_to = \"media\",\n values_to = \"od\"\n )\n\nfull_join(GFP, OD)\n# Joining, by = c(\"rep\", \"time\", \"media\")\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20137846/"
] |
74,286,319 | <p>for practicing with reusable components in Jetpack Compose, I started a little exercise.
See picture below.</p>
<p><a href="https://i.stack.imgur.com/a4YQr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/a4YQr.png" alt="enter image description here" /></a></p>
<p>As I imagine the green row, the input row, and the rows between have the same construction.
The first element got the available space, the second takes 50.dp, and the last one got 70.dp.
I tried to seperate the width into variables an pass this vars as modifiers to the single elements in the row. I thought if I need additionally fields, the I can extend it whitout any problem.</p>
<h3>CODE DOESN'T WORK!</h3>
<pre><code>@Composable
fun groundComponent(
modifier: Modifier = Modifier,
spaceBetween: Dp = 0.dp,
color: Color,
content: @Composable () -> Unit
) {
Surface(
color = color
) {
Row(
modifier = modifier,
horizontalArrangement = Arrangement.spacedBy(spaceBetween)
) {
content()
}
}
}
@Composable
fun inputSection() {
val firstRowWidth = 1F
val secondRowWidth = 70.dp
val thirdRowWidth = 50.dp
Text("Add Ingredient")
groundComponent(color = Color.Green){
Text( text="Ingredient", modifier = Modifier.weight(firstRowWidth ))
Text( text="Amount", modifier = Modifier.widthIn(secondRowWidth ))
Text( text="Unit", modifier = Modifier.widthIn(thirdRowWidth ))
}
groundComponent{
Text( text="Sugar", modifier = Modifier.weight(firstRowWidth ))
Text( text="500", modifier = Modifier.widthIn(secondRowWidth ))
Text( text="gr", modifier = Modifier.widthIn(thirdRowWidth ))
}
groundComponent{
Text( text="Carrot", modifier = Modifier.weight(firstRowWidth ))
Text( text="1.5", modifier = Modifier.widthIn(secondRowWidth ))
Text( text="kg", modifier = Modifier.widthIn(thirdRowWidth ))
}
groundComponent{
TextField(
value = "newIngredient",
onValueChange = {},
modifier = Modifier.weight(firstRowWidth ))
TextField(
value = "newAmount",
onValueChange = {},
modifier = Modifier.widthIn(secondRowWidth )
)
TextField(
value = "newUnit",
onValueChange = {},
modifier = Modifier.widthIn(thirdRowWidth )
)
}
Button(onClick={}){Text("add")}
}
</code></pre>
<p>I got several errors with the .weight modifier.
So how is the right aproach to solve such a situation.</p>
<p>Thanks!</p>
| [
{
"answer_id": 74286507,
"author": "Thracian",
"author_id": 5457853,
"author_profile": "https://Stackoverflow.com/users/5457853",
"pm_score": 4,
"selected": true,
"text": "@Composable\nfun GroundComponent(\n modifier: Modifier = Modifier,\n spaceBetween: Dp = 0.dp,\n color: Color=Color.Unspecified,\n content: @Composable RowScope.() -> Unit\n) {\n Surface(\n color = color\n ) {\n\n // Can't call content here because it has RowScope as receiver\n// content()\n Row(\n modifier = modifier,\n horizontalArrangement = Arrangement.spacedBy(spaceBetween)\n ) {\n content()\n }\n }\n}\n"
},
{
"answer_id": 74334178,
"author": "Pferdesalbe",
"author_id": 16096509,
"author_profile": "https://Stackoverflow.com/users/16096509",
"pm_score": 1,
"selected": false,
"text": "@Composable\nfun InputRowGroundComponent(\n modifier: Modifier = Modifier,\n spaceBetweenElements: Dp = 0.dp,\n color: Color,\n content: @Composable RowScope.() -> Unit\n) {\n Surface(\n color = color\n ) {\n Row(\n modifier = modifier,\n horizontalArrangement = Arrangement.spacedBy(spaceBetweenElements),\n verticalAlignment = Alignment.CenterVertically\n ) {\n content()\n }\n }\n}\n\n@Composable\nfun OverviewHeader(\n modifier: Modifier = Modifier,\n text: String\n) {\n Text(\n modifier = modifier,\n text = text,\n maxLines = 1,\n overflow = TextOverflow.Ellipsis,\n textAlign = TextAlign.Center\n )\n}\n\n@Composable\nfun OverviewContent(\n modifier: Modifier = Modifier,\n text: String\n) {\n Text(\n modifier = modifier,\n text = text,\n maxLines = 2,\n overflow = TextOverflow.Ellipsis,\n )\n}\n\n@Preview(showBackground = true, widthDp = 460)\n@Composable\nfun testPrev() {\n val rowWeights = listOf(6F,3F,2F)\n val rowSpacing = 8.dp\n val indentation = 10.dp\n Column(\n modifier = Modifier.padding(8.dp),\n verticalArrangement = Arrangement.spacedBy(rowSpacing)\n ) {\n InputRowGroundComponent(\n modifier = Modifier.heightIn(45.dp),\n spaceBetweenElements = rowSpacing,\n color = Color.Green\n ) {\n OverviewHeader(text = \"Ingredient\", modifier = Modifier.weight(rowWeights[0]))\n OverviewHeader(text = \"Amount\", modifier = Modifier.weight(rowWeights[1]))\n OverviewHeader(text = \"Unit\", modifier = Modifier.weight(rowWeights[2]))\n }\n InputRowGroundComponent(\n modifier = Modifier.heightIn(30.dp),\n spaceBetweenElements = rowSpacing,\n color = Color.Unspecified\n ) {\n OverviewContent(text = \"Sugar\", modifier = Modifier.weight(rowWeights[0]).padding(start=indentation))\n OverviewContent(text = \"500\", modifier = Modifier.weight(rowWeights[1]).padding(start=indentation))\n OverviewContent(text = \"gr\", modifier = Modifier.weight(rowWeights[2]).padding(start=indentation))\n }\n InputRowGroundComponent(\n modifier = Modifier.heightIn(30.dp),\n spaceBetweenElements = rowSpacing,\n color = Color.Unspecified\n ) {\n OverviewContent(text = \"Carrot\", modifier = Modifier.weight(rowWeights[0]).padding(start=indentation))\n OverviewContent(text = \"1.5\", modifier = Modifier.weight(rowWeights[1]).padding(start=indentation))\n OverviewContent(text = \"kg\", modifier = Modifier.weight(rowWeights[2]).padding(start=indentation))\n }\n InputRowGroundComponent(\n spaceBetweenElements = rowSpacing,\n color = Color.Unspecified\n ) {\n TextField(value = \"\", onValueChange = {}, modifier = Modifier.weight(rowWeights[0]))\n TextField(value = \"\", onValueChange = {}, modifier = Modifier.weight(rowWeights[1]))\n TextField(value = \"\", onValueChange = {}, modifier = Modifier.weight(rowWeights[2]))\n }\n Button(\n modifier = Modifier.fillMaxWidth(),\n onClick = { /*Todo*/ },\n content = {\n Row(\n verticalAlignment = Alignment.CenterVertically\n ) {\n Icon(\n imageVector = Icons.Filled.Add,\n contentDescription = \"Add Ingredient\"\n )\n Text(\n text = \"Add\"\n )\n }\n }\n )\n }\n}\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16096509/"
] |
74,286,350 | <p>i need output like this:</p>
<pre><code>1 2 3 4 5
2 2 3 4 5
3 3 3 4 5
4 4 4 4 5
5 5 5 5 5
</code></pre>
<p>this is what i can do but it's not right</p>
<pre><code>size=int(input())
for row in range(1,size+1):
for col in range(1,size+1):
print(row,end=' ')
print(col)
</code></pre>
<p>only use forloop</p>
| [
{
"answer_id": 74286406,
"author": "Tom McLean",
"author_id": 14720380,
"author_profile": "https://Stackoverflow.com/users/14720380",
"pm_score": 2,
"selected": false,
"text": "size = int(input())\nfor i in range(1, size+1):\n print(' '.join(str(max(i, j)) for j in range(1, size+1)))\n"
},
{
"answer_id": 74286410,
"author": "ShlomiF",
"author_id": 5024514,
"author_profile": "https://Stackoverflow.com/users/5024514",
"pm_score": 0,
"selected": false,
"text": "size=int(input())\n\nfor i in range(1, size + 1): \n print(' '.join([str(max([i, j])) for j in range(1, size + 1)]))\n \n"
},
{
"answer_id": 74286444,
"author": "Anto",
"author_id": 19617785,
"author_profile": "https://Stackoverflow.com/users/19617785",
"pm_score": 0,
"selected": false,
"text": "num = int(input(\"Input a number : \"))\n\nfor i in range(1, num+1):\n row = \"\"\n for j in range(1, num+1):\n row += \" \" + str(j if j > i else i)\n print(row)\n"
},
{
"answer_id": 74286492,
"author": "T C Molenaar",
"author_id": 8814131,
"author_profile": "https://Stackoverflow.com/users/8814131",
"pm_score": 0,
"selected": false,
"text": "i"
},
{
"answer_id": 74286511,
"author": "mbofos01",
"author_id": 17790231,
"author_profile": "https://Stackoverflow.com/users/17790231",
"pm_score": 0,
"selected": false,
"text": "for row in range(1,size+1):\n cnt = 1\n for col in range(1,size+1):\n if(cnt < row):\n printNum = row\n else:\n printNum = cnt\n cnt = cnt + 1\n if(printNum > 9):\n print(printNum,end=' ')\n else:\n print(printNum,end=' ')\n print(\"\\n\")\n"
},
{
"answer_id": 74286516,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 0,
"selected": false,
"text": "size = input()\nwidth = len(size)\nsize = int(size)+1\nfor i in range(1, size):\n print(*(f'{max(i, j):>{width}}' for j in range(1, size)))\n"
},
{
"answer_id": 74286523,
"author": "PogoSpin",
"author_id": 20395582,
"author_profile": "https://Stackoverflow.com/users/20395582",
"pm_score": 0,
"selected": false,
"text": "size=int(input())\n\nfor col in range(1,size+1):\n for row in range(1,size+1):\n if row <= col:\n print(col, end=' ')\n else:\n print(row, end=' ')\n print()\n"
},
{
"answer_id": 74286838,
"author": "toyota Supra",
"author_id": 4136999,
"author_profile": "https://Stackoverflow.com/users/4136999",
"pm_score": 0,
"selected": false,
"text": "(size := int(input(\"Input a number : \")) + 1)\nfor i in range(1, size):\n print(' '.join(str(max(i, j)) for j in range(1, size)))\n"
},
{
"answer_id": 74287067,
"author": "Alexander",
"author_id": 17829451,
"author_profile": "https://Stackoverflow.com/users/17829451",
"pm_score": 0,
"selected": false,
"text": "square_numbers = lambda val: '1 ' if val == 1 else '\\n'.join([i + str(val)+' ' for i in square_numbers(val-1).split('\\n')] + [(str(val)+' ') * val])\n"
},
{
"answer_id": 74287475,
"author": "ninebee",
"author_id": 20341340,
"author_profile": "https://Stackoverflow.com/users/20341340",
"pm_score": 0,
"selected": false,
"text": " # write a program to traverse every element of the two-dimensional array in Python. \ndt = [ [1, 2, 3, 4, 5], [2, 2, 3, 4, 5], [3, 3, 3, 4, 5 ], [4, 4, 4, 4, 5], [5, 5, 5, 5, 5] ] \n# Use for loop to print the entire elements of the two dimensional array. \nfor x in dt: # outer loop \n for i in x: # inner loop \n print(i, end = \" \") # print the elements \n print()\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20395355/"
] |
74,286,352 | <p>I am creating a library, that is nearly close to its first release, so I would like to upload it to <code>crates.io</code>. Library has a multi-crate design, so I ended with something like:</p>
<pre><code>- CrateA
- CrateProcMacros
- CrateC
- CrateD
- CrateE
- CrateF
- Cargo.toml (handles the workspace)
- Cargo.lock
...
</code></pre>
<p>where <code>CrateA</code> is the parent of the other crates, and has dependencies on another of those local crates, and some of those crates also depends on another ones. I mean, it's the primary crate of the library, the one responsible for exposing the public API of the project, and the unique one that I would like to be published in <code>crates.io</code>.</p>
<p>Reading the <a href="https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html" rel="nofollow noreferrer">cargo docs</a> I am seeing that I won't be able to publish a unique crate to the registry. All will be uploaded and published.</p>
<p>So, what alternatives I have to only publish my <code>CrateA</code> to the registry? Should I change my project's structure, and move to <code>CrateA</code> all the other packages and then try to publish it? Or there's some way to achieve this?</p>
<h3>EDIT</h3>
<p><code>CrateA</code> have direct dependencies on another crates. An those others also depends on another one inside my workspace.</p>
| [
{
"answer_id": 74286419,
"author": "Eveheeero",
"author_id": 16761173,
"author_profile": "https://Stackoverflow.com/users/16761173",
"pm_score": -1,
"selected": false,
"text": "[workspace]\nmembers = [\n \"CrateA\",\n \"CrateB\",\n ...\n]\n"
},
{
"answer_id": 74290158,
"author": "Kevin Reid",
"author_id": 99692,
"author_profile": "https://Stackoverflow.com/users/99692",
"pm_score": 3,
"selected": true,
"text": "CrateA"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14075508/"
] |
74,286,370 | <p>I have a trimmed down version of my code to illustrate the issue.</p>
<p>Here's the compilation error I'm getting:</p>
<pre><code>The method anyMatch(Predicate<? super capture#26-of ?>) in the type Stream<capture#26-of ?> is not applicable for the arguments (Predicate<Map<?,?>>)
</code></pre>
<p><em>My code:</em></p>
<pre><code>private void func(Object o) {
Predicate<Map<?, ?>> pred = m -> true;
if (o instanceof Map && pred.test((Map<?, ?>) o)) {
// ...pred.test is OK
} else if (o instanceof Collection && ((Collection<?>) o).stream().filter(i -> i instanceof Map).anyMatch(pred)) {
// ...anyMatch here gives the above error
}
}
</code></pre>
<p>How would you fix the code to remove the error? Thank you!</p>
| [
{
"answer_id": 74286419,
"author": "Eveheeero",
"author_id": 16761173,
"author_profile": "https://Stackoverflow.com/users/16761173",
"pm_score": -1,
"selected": false,
"text": "[workspace]\nmembers = [\n \"CrateA\",\n \"CrateB\",\n ...\n]\n"
},
{
"answer_id": 74290158,
"author": "Kevin Reid",
"author_id": 99692,
"author_profile": "https://Stackoverflow.com/users/99692",
"pm_score": 3,
"selected": true,
"text": "CrateA"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1589188/"
] |
74,286,394 | <p>im trying to extract a value from my data frame
i have a column ['Desc'] it contains sentences in the folowing format</p>
<blockquote>
<p>_000it_ZZZ$$$-</p>
</blockquote>
<blockquote>
<p>_0780it_ZBZT$$$-</p>
</blockquote>
<blockquote>
<p>_011it_BB$$$-</p>
</blockquote>
<blockquote>
<p>_000it_CCCC$$$-</p>
</blockquote>
<p>I want to extract the string between 'it_' and '$$$'</p>
<p>I have tried this code but does not seem to work</p>
<pre><code># initializing substrings
sub1 = "it_"
sub2 = "$$$"
# getting index of substrings
idx1 = df['DESC'].find(sub1)
idx2 = df['DESC'].find(sub2)
# length of substring 1 is added to
# get string from next character
df['results'] = df['DESC'][idx1 + len(sub1) + 1: idx2]
</code></pre>
<p>I would appreciate your help</p>
| [
{
"answer_id": 74286419,
"author": "Eveheeero",
"author_id": 16761173,
"author_profile": "https://Stackoverflow.com/users/16761173",
"pm_score": -1,
"selected": false,
"text": "[workspace]\nmembers = [\n \"CrateA\",\n \"CrateB\",\n ...\n]\n"
},
{
"answer_id": 74290158,
"author": "Kevin Reid",
"author_id": 99692,
"author_profile": "https://Stackoverflow.com/users/99692",
"pm_score": 3,
"selected": true,
"text": "CrateA"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,286,416 | <p>I tried to update a lot of rows in date format ('DD-MON-YY'). S</p>
<p>So, in cases such 22-FEB-99, I got 22th February 1999, instead of 22th February 2099.</p>
<p>Is there a way to specify the year in such cases?</p>
| [
{
"answer_id": 74286508,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 0,
"selected": false,
"text": "YY"
},
{
"answer_id": 74286932,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 3,
"selected": true,
"text": "DATE"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16561042/"
] |
74,286,420 | <p>Hey guys I have a long table in my Database and i want select all records that have the same id and parent_id.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>parent_id</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>lorem</td>
<td>2</td>
</tr>
</tbody>
</table>
</div>
<p>Second case:</p>
<p>In the second case there are ids and parent_ids in different rows.</p>
<p><a href="https://i.stack.imgur.com/guc8I.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/guc8I.png" alt="enter image description here" /></a></p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 74286508,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 0,
"selected": false,
"text": "YY"
},
{
"answer_id": 74286932,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 3,
"selected": true,
"text": "DATE"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74286420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16846263/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.