qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,305,797 | <p>The task wants you to have the user enter a month, day and two-digit number for a year in sperate prompts and if the month times the day equals the year to print "this date is magic" but I'm getting an unknown error</p>
<p>What to be expected is: Sample Run (user input shown in bold)
Enter month (numeric):12↵
Enter day:8↵
Enter two digit year:96↵
This date is magic!
Sample Run (user input shown in bold)
Enter month (numeric):10↵
Enter day:2↵
Enter two-digit year:75↵
This date is not magic</p>
<hr />
<ol>
<li>``My code</li>
</ol>
<pre><code>print('Enter a month:')
month=input('Select a month from the year')
print('Enter day:')
day=input('Select a day:')
print('Enter a two digit year:')
year=input('Select a two digit value')
if month*day=year:
print('This date is magic')
else:
print("This date is not magic")
</code></pre>
<p>``</p>
| [
{
"answer_id": 74305867,
"author": "a_horse_with_no_name",
"author_id": 330315,
"author_profile": "https://Stackoverflow.com/users/330315",
"pm_score": 0,
"selected": false,
"text": "select sport, sum(cost)\nfrom \n( \n select 'Basketball' as sport, cost\n from the_table \n where basketball = 1\n union all\n select 'Baseball', cost\n from the_table \n where baseball = 1\n union all\n select 'Golf', cost\n from the_table \n where golf = 1\n) t\ngroup by sport;\n"
},
{
"answer_id": 74305999,
"author": "DannySlor",
"author_id": 19174570,
"author_profile": "https://Stackoverflow.com/users/19174570",
"pm_score": 1,
"selected": false,
"text": "select game\n ,sum(cost*flg) as cost\n \nfrom t \n cross join lateral (\n values \n (basketball, 'basketball')\n ,(baseball, 'baseball')\n ,(golf, 'golf')\n ) t2(flg, game)\ngroup by game\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74305797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20346267/"
] |
74,305,806 | <p>I want to output an array to a range, however I want the range to be made up of several parts. My example code is below with the expected output.</p>
<pre><code>Sub test()
a = Array(1, 2, 3, 4, 5)
Range("A2:B2,D2:F2") = a
End Sub
</code></pre>
<p>Output I Get:</p>
<p>A-B-C-D-E-F</p>
<p>1-2---1-2-3</p>
<p>Output I Want:</p>
<p>A-B-C-D-E-F</p>
<p>1-2---3-4-5</p>
<p>How do I achieve the output I need from the array? As you can see the output skips column C correctly but starts to output the array from the start again and not continue as I expected.</p>
| [
{
"answer_id": 74306229,
"author": "Pᴇʜ",
"author_id": 3219613,
"author_profile": "https://Stackoverflow.com/users/3219613",
"pm_score": 1,
"selected": false,
"text": "Sub test()\n Dim Area1 As Variant\n Area1 = Array(1, 2)\n Range(\"A2:B2\") = Area1\n\n Dim Area2 As Variant\n Area2 = Array(3, 4, 5)\n\n Range(\"D2:F2\") = Area2\nEnd Sub\n"
},
{
"answer_id": 74306365,
"author": "TehDrunkSailor",
"author_id": 13705050,
"author_profile": "https://Stackoverflow.com/users/13705050",
"pm_score": 2,
"selected": true,
"text": "Range"
},
{
"answer_id": 74339284,
"author": "T.M.",
"author_id": 6460297,
"author_profile": "https://Stackoverflow.com/users/6460297",
"pm_score": 0,
"selected": false,
"text": "Sub testSlice()\n'1. Define array values\n Dim arr As Variant\n arr = Array(1, 2, 3, 4, 5)\n'2. Assign sliced array values to each range area\n With Sheet1.Range(\"A2:B2,D2:F2\") ' non contiguous range\n Dim i As Long, col As Long\n For i = 1 To .Areas.Count ' loop through each area\n Dim cols As Long: cols = .Areas(i).Columns.Count\n 'Assign partial array\n .Areas(i) = Slice(arr, col + 1, cols) ' << aux. function\n col = col + cols ' provide for next col\n Next i\n End With\nEnd Sub\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74305806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10358185/"
] |
74,305,841 | <p>My list consists of elements with fiels Type(<code>String</code>), Amount(<code>Double</code>) and Quantity(<code>Integer</code>) and it looks like this:</p>
<pre><code>Type: Type A, Amount : 55.0, Quantity : 0
Type: Type A, Amount : 55.0, Quantity : 5
Type: Type A, Amount : 44.35, Quantity : 6
Type: Type A, Amount : 55.0, Quantity : 0
Type: Type B, Amount : 7.0, Quantity : 1
Type: Type B, Amount : 7.0, Quantity : 1
Type: Type C, Amount : 1613.57, Quantity : 0
Type: Type C, Amount : 1613.57, Quantity : 1
</code></pre>
<p>So i am trying to loop my array to find duplicate, and add the Amount if its duplicate. The outcome would be like this:</p>
<pre><code>Type: Type A, Amount : 209.35.0, Quantity : 11
Type: Type B, Amount : 14.0, Quantity : 2
Type: Type C, Amount : 3227.14, Quantity : 1
</code></pre>
<p>What i have tried is creating another List, add the List to new List, then compare them, but didnt work</p>
<pre><code>List<Type> newList = new ArrayList();
for(int k = 0; k < typeList.size(); k++) {
Type type= new Type();
Double totalAmount = Double.parseDouble("0");
type.setTypeName(typeList.get(k).getTypeName());
type.setAmount(chargeTypeList.get(k).getAmount());
newList.add(k, type);
if(typeList.get(k).getChargeTypeName().equalsIgnoreCase(newList.get(k).getiTypeName())) {
totalAmount += typeList.get(k).getAmount();
}
}
</code></pre>
<p>I don't want to hardcode the value to check for duplicate Type</p>
| [
{
"answer_id": 74306127,
"author": "Marcus Dunn",
"author_id": 12639399,
"author_profile": "https://Stackoverflow.com/users/12639399",
"pm_score": 3,
"selected": false,
"text": "compute"
},
{
"answer_id": 74307145,
"author": "Ashish Patil",
"author_id": 5014221,
"author_profile": "https://Stackoverflow.com/users/5014221",
"pm_score": 1,
"selected": false,
"text": " List<TypeClass> ls = List.of(new TypeClass(\"A\", 12.3, 2), new TypeClass(\"A\", 3.4, 4),\n new TypeClass(\"B\", 12.4, 6), new TypeClass(\"B\", 12.8, 8));\n\n System.out.println(\n ls.stream().collect(HashMap<String, TypeClass>::new, (x, y) -> x.merge(y.getTypeName(), y, (o, p) -> {\n return new TypeClass(y.getTypeName(), o.getAmount() + p.getAmount(),\n o.getQuantity() + p.getQuantity());\n }), (a, b) -> a.putAll(b)));\n"
},
{
"answer_id": 74307498,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 0,
"selected": false,
"text": "groupingBy()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74305841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7592295/"
] |
74,305,846 | <pre><code>lambdaFunction = _lambda.DockerImageFunction(self, f'{client_id}-prefect-lambda-handler',
code=_lambda.DockerImageCode.from_image_asset(
directory="cumulus_devops_cdk/prefect-lambda-handler"
),
)
</code></pre>
<p>I am trying to create a lambda function from a docker image in CDK as shown above. The problem is that my company's CDK runs in a docker image and thus has trouble building a docker image inside of itself.</p>
<p>I know that the docker image works because it succeeded when I manually built and pushed the image to ECR and had CDK pull from that, however I would like to have it get built every time I CDK deploy.</p>
<p>Whenever I try to cdk deploy the stack I get this error</p>
<pre><code>[100%] fail: docker build --tag cdkasset-d4a61d4806d68e3a7b9589a1e161b40523d2a3bc5be6506aaf6bb4b45fd5cc07 . exited with error code 1: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
</code></pre>
<p>How can I successfully build the docker image in cdk and have it deployed to the lambda function?</p>
| [
{
"answer_id": 74306127,
"author": "Marcus Dunn",
"author_id": 12639399,
"author_profile": "https://Stackoverflow.com/users/12639399",
"pm_score": 3,
"selected": false,
"text": "compute"
},
{
"answer_id": 74307145,
"author": "Ashish Patil",
"author_id": 5014221,
"author_profile": "https://Stackoverflow.com/users/5014221",
"pm_score": 1,
"selected": false,
"text": " List<TypeClass> ls = List.of(new TypeClass(\"A\", 12.3, 2), new TypeClass(\"A\", 3.4, 4),\n new TypeClass(\"B\", 12.4, 6), new TypeClass(\"B\", 12.8, 8));\n\n System.out.println(\n ls.stream().collect(HashMap<String, TypeClass>::new, (x, y) -> x.merge(y.getTypeName(), y, (o, p) -> {\n return new TypeClass(y.getTypeName(), o.getAmount() + p.getAmount(),\n o.getQuantity() + p.getQuantity());\n }), (a, b) -> a.putAll(b)));\n"
},
{
"answer_id": 74307498,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 0,
"selected": false,
"text": "groupingBy()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74305846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20409202/"
] |
74,305,847 | <p>I have this simple function that, given a string <code>str</code>, if it is a number then return 'true' and overwrite the reference input <code>num</code>.</p>
<pre><code>template <typename T>
bool toNumber(string str, T& num)
{
bool bRet = false;
if(str.length() > 0U)
{
if (str == "0")
{
num = static_cast<T>(0);
bRet = true;
}
else
{
std::stringstream ss;
ss << str;
ss >> num; // if str is not a number op>> it will assign 0 to num
if (num == static_cast<T>(0))
{
bRet = false;
}
else
{
bRet = true;
}
}
}
else
{
bRet = false;
}
return bRet;
}
</code></pre>
<p>So I expect that:</p>
<pre><code>int x, y;
toNumber("90", x); // return true and x is 90
toNumber("New York", y); // return false and let y unasigned.
</code></pre>
<p>On my machine, both debug and release configurations works fine, but on the server, only with the debug configuration, in calls like <code>toNumber("New York", y)</code> the 'ss >> num' fails to recognize that <code>str</code> is a string.</p>
<p>I checked the project configuration, but they are the same for both machines (the server is a svn-checkout of my local vs-2015 project).</p>
<p>I have literally no idea on how to solve the problem. Can anyone help me with this?</p>
| [
{
"answer_id": 74305989,
"author": "n. m.",
"author_id": 775806,
"author_profile": "https://Stackoverflow.com/users/775806",
"pm_score": 0,
"selected": false,
"text": "if (num == static_cast<T>(0))"
},
{
"answer_id": 74306250,
"author": "Marek R",
"author_id": 1387438,
"author_profile": "https://Stackoverflow.com/users/1387438",
"pm_score": 2,
"selected": true,
"text": "template <typename T>\nbool toNumber(std::string str, T& num)\n{\n return !!(std::istringstream { std::move(str) } >> num);\n}\n"
},
{
"answer_id": 74306322,
"author": "Remy Lebeau",
"author_id": 65863,
"author_profile": "https://Stackoverflow.com/users/65863",
"pm_score": 3,
"selected": false,
"text": "operator>>"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74305847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14877217/"
] |
74,305,880 | <p>I am trying to use this json data (below) to draw a <a href="https://plotly.com/javascript/3d-point-clustering/" rel="nofollow noreferrer">3D cluster chart</a>), I have no idea how to get the data format the chart required.</p>
<pre><code> [{
"date": "2022-10-23 00:59:48",
"coords": {
"centroid_coordinates": {
"lat": -7.207031,
"lon": 168.596191
},
"a": {
"x": -1256364.723016,
"y": -905736.587501,
"z": -193874.799252
},
"b": {
"x": -386418.720754,
"y": -6642.909578,
"z": 23877.65777
},
"c": {
"x": -129833372.79993,
"y": -66828394.94447,
"z": -28968456.528255
}
}
},
{
"date": "2022-10-23 02:47:50",
"coords": {
"centroid_coordinates": {
"lat": -7.17041,
"lon": 141.584473
},
"a": {
"x": -1255562.609906,
"y": -906938.207607,
"z": -194414.791666
},
"b": {
"x": -386086.589686,
"y": -12494.762637,
"z": 20835.942076
},
"c": {
"x": -129735646.666749,
"y": -66982246.620175,
"z": -29035155.240834
}
}
},
{
"date": "2022-10-23 04:35:53",
"coords": {
"centroid_coordinates": {
"lat": -7.214355,
"lon": 114.528809
},
"a": {
"x": -1254758.115314,
"y": -908137.954559,
"z": -194955.259706
},
"b": {
"x": -385642.162129,
"y": -18344.612851,
"z": 17787.284227
},
"c": {
"x": -129637682.082612,
"y": -67136009.866602,
"z": -29101817.979109
}
}
}]
</code></pre>
<p>I want to use javascript function to integrate each (a.b.c.d)'s xyz data using javascript and put it into the chart, are their any solutions that helps!</p>
<pre><code> var data = [{
x: [-1256364.723016,-386418.720754,-129833372.79993]
y: [-905736.587501,-6642.909578,-66828394.94447]
z: [-193874.799252,23877.65777,-28968456.528255]
}]
</code></pre>
<p>I would be very grateful for any tips or resources, so I can get unstuck on this probably not so difficult task. I should mention I'm fairly new to all of this.</p>
<p>Thank you all in advance!</p>
| [
{
"answer_id": 74306167,
"author": "dileep nandanam",
"author_id": 1547872,
"author_profile": "https://Stackoverflow.com/users/1547872",
"pm_score": 2,
"selected": true,
"text": " const data = initialData.map((perDate) => {\n let coords = perDate.coords\n return({\n x: [coords.a.x, coords.b.x, coords.c.x],\n y: [coords.a.y, coords.b.y, coords.c.y],\n z: [coords.a.z, coords.b.z, coords.c.z]\n })\n })\n"
},
{
"answer_id": 74306668,
"author": "山河以无恙",
"author_id": 20209252,
"author_profile": "https://Stackoverflow.com/users/20209252",
"pm_score": 0,
"selected": false,
"text": "data.map(o => o.coords)\n .map(o => [o.a, o.b, o.c])\n .map(o => {\n return {\n x: o.map(x => x.x),\n y: o.map(y => y.y),\n z: o.map(z => z.z),\n }\n }).forEach(o => console.log(o))\n"
},
{
"answer_id": 74313478,
"author": "Rohìt Jíndal",
"author_id": 4116300,
"author_profile": "https://Stackoverflow.com/users/4116300",
"pm_score": 1,
"selected": false,
"text": "Array.map()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74305880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20409273/"
] |
74,305,892 | <p>I have to write unit tests for a function and this function uses <code>json.NewDecoder.Decode</code></p>
<pre><code>var infos models.RegisterInfos // struct with json fields
err := json.NewDecoder(r.Body).Decode(&infos)
if err != nil {
// do something
}
</code></pre>
<p>How can I simulate an error in a unit test (using the <code>testing</code> package) for <code>json.NewDecoder(r.Body).Decode(&infos)</code> ? I tried looking in the <code>NewDecoder</code> and <code>Decode</code> source code but I couldn't find anything that can generate an error in just a few lines.</p>
| [
{
"answer_id": 74306167,
"author": "dileep nandanam",
"author_id": 1547872,
"author_profile": "https://Stackoverflow.com/users/1547872",
"pm_score": 2,
"selected": true,
"text": " const data = initialData.map((perDate) => {\n let coords = perDate.coords\n return({\n x: [coords.a.x, coords.b.x, coords.c.x],\n y: [coords.a.y, coords.b.y, coords.c.y],\n z: [coords.a.z, coords.b.z, coords.c.z]\n })\n })\n"
},
{
"answer_id": 74306668,
"author": "山河以无恙",
"author_id": 20209252,
"author_profile": "https://Stackoverflow.com/users/20209252",
"pm_score": 0,
"selected": false,
"text": "data.map(o => o.coords)\n .map(o => [o.a, o.b, o.c])\n .map(o => {\n return {\n x: o.map(x => x.x),\n y: o.map(y => y.y),\n z: o.map(z => z.z),\n }\n }).forEach(o => console.log(o))\n"
},
{
"answer_id": 74313478,
"author": "Rohìt Jíndal",
"author_id": 4116300,
"author_profile": "https://Stackoverflow.com/users/4116300",
"pm_score": 1,
"selected": false,
"text": "Array.map()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74305892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11140488/"
] |
74,305,897 | <p>I have a Cassandra cluster with 8 nodes in 2 datacenters respectively 4-4 nodes in DC1 and DC2.</p>
<p>I've created a keyspace:</p>
<pre><code>CREATE KEYSPACE mykeyspace
WITH REPLICATION = {
'class' : 'NetworkTopologyStrategy',
'DC1' : 2,
'DC2' : 2,
};
</code></pre>
<p>As far as I understand, both DC1 and DC2 will have all the data, with other words in case of whole DC1 goes offline, DC2 will capable to serve all data.</p>
<p><strong>Question</strong></p>
<p>Should we say that based on the previous fact both DC1 and DC2 are a "complete" ring in their own? (regarding the whole hash -2^63-1 .. +2^63 will be presented by nodes on DC1 and the same is true for DC2)</p>
<p><strong>Why I am asking this?</strong></p>
<p>My answer would be no, this is still one cluster, so one ring, regardless there are two subset of nodes which are contain all the data. However many image and illustrations represent the nodes in the two datacenters with two "circles" which hints the term two "rings". (obviously not two clusters)</p>
<p>see for example:</p>
<p><a href="https://docs.datastax.com/en/cassandra-oss/2.1/cassandra/dml/architectureClientRequestsMultiDCWrites_c.html" rel="nofollow noreferrer">DataStax: Multiple datacenter write requests</a></p>
<p>PS: If it is possible do not bring to the picture the consistency levels. I understand that the inter node communication workflow depends on if the operation is write or read, and also depends on the consistency level.</p>
<p><strong>A practical question which depends on the answer:</strong></p>
<p>Say in DC1 <code>num_tokens: 256</code> for all nodes and DC2 <code>num_tokens: 32</code> for all nodes. Those numbers will be relative to each other if the 8 node are in one token ring, but in case of DC1 and DC2 are two separate token rings those number (256 and 32) are nothing to do with each other...</p>
| [
{
"answer_id": 74368048,
"author": "Adriano Bonacin",
"author_id": 8527017,
"author_profile": "https://Stackoverflow.com/users/8527017",
"pm_score": 0,
"selected": false,
"text": "DC1\n- rack1\n-- 2 nodes\n- rack2\n-- 2 nodes\n\nDC2\n- rack1\n-- 2 nodes\n- rack2\n-- 2 nodes\n"
},
{
"answer_id": 74381343,
"author": "Adriano Bonacin",
"author_id": 8527017,
"author_profile": "https://Stackoverflow.com/users/8527017",
"pm_score": 1,
"selected": false,
"text": "nodetool ring"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74305897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1157814/"
] |
74,305,900 | <p>I have a table with 2 columns: client and product_name.</p>
<p>I need to number the product_name for each client</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>client</th>
<th>product_name</th>
<th>rank</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>aaa</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>baa</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>cwe</td>
<td>3</td>
</tr>
<tr>
<td>2</td>
<td>te</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>aaa</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>cwq</td>
<td>2</td>
</tr>
</tbody>
</table>
</div>
<p>I created a column</p>
<pre><code>RANKX_column =
RANKX(
FILTER(Query1,Query1[client_id] = EARLIER(Query1[client_id])),
Query1[product_id],,ASC,Dense
)
</code></pre>
<p>but if I apply a filter, the rank is not recalculated.</p>
<p>I tried to rewrite this formula for measure, but it returns an error about the function EARLIER.</p>
| [
{
"answer_id": 74368048,
"author": "Adriano Bonacin",
"author_id": 8527017,
"author_profile": "https://Stackoverflow.com/users/8527017",
"pm_score": 0,
"selected": false,
"text": "DC1\n- rack1\n-- 2 nodes\n- rack2\n-- 2 nodes\n\nDC2\n- rack1\n-- 2 nodes\n- rack2\n-- 2 nodes\n"
},
{
"answer_id": 74381343,
"author": "Adriano Bonacin",
"author_id": 8527017,
"author_profile": "https://Stackoverflow.com/users/8527017",
"pm_score": 1,
"selected": false,
"text": "nodetool ring"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74305900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19044278/"
] |
74,305,902 | <p>I am working with the below df:</p>
<pre><code>first_column<-c(1,2,3,4)
second_column<-c(1,2,"NA",4)
df<-data.frame(first_column,second_column)
df$test=ifelse(df$first_column==df$second_column,0,1)
> df
first_column second_column test
1 1 1 0
2 2 2 0
3 3 NA 1
4 4 4 0
</code></pre>
<p>What I would like to do are 2 things, 1) to remove an entire row if there is NA in second column, how should I do with & without dplyr? 2) If I would like to have an result returning to the first column if the test column shows non-zero, that is, in this case, returning to first column # 3 based on "1" on test column. May I know how should I tackle these 2 things? Many thanks for your help.</p>
| [
{
"answer_id": 74368048,
"author": "Adriano Bonacin",
"author_id": 8527017,
"author_profile": "https://Stackoverflow.com/users/8527017",
"pm_score": 0,
"selected": false,
"text": "DC1\n- rack1\n-- 2 nodes\n- rack2\n-- 2 nodes\n\nDC2\n- rack1\n-- 2 nodes\n- rack2\n-- 2 nodes\n"
},
{
"answer_id": 74381343,
"author": "Adriano Bonacin",
"author_id": 8527017,
"author_profile": "https://Stackoverflow.com/users/8527017",
"pm_score": 1,
"selected": false,
"text": "nodetool ring"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74305902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16601198/"
] |
74,305,921 | <p>i keep getting this after the code runs for a minute or so...</p>
<blockquote>
<p>Traceback (most recent call last): File "rapid7_helper.py", line
233, in
_request() File "rapid7_helper.py", line 31, in _request
resp = requests.post(url=url1, headers=headers, json=third_party_patching_filer, verify=False).json() File
"/usr/local/lib/python3.8/site-packages/requests/models.py", line 898,
in json
return complexjson.loads(self.text, **kwargs) File "/usr/local/lib/python3.8/site-packages/simplejson/<strong>init</strong>.py", line
525, in loads
return _default_decoder.decode(s) File "/usr/local/lib/python3.8/site-packages/simplejson/decoder.py", line
370, in decode
obj, end = self.raw_decode(s) File "/usr/local/lib/python3.8/site-packages/simplejson/decoder.py", line
400, in raw_decode
return self.scan_once(s, idx=_w(s, idx).end()) simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1
(char 0)</p>
</blockquote>
<p>is it possible to assign two different variables for my resp2? I need to be able to filter out "tags" from my rapid7 api as well as getting the next Key</p>
<pre><code>def _request():
third_party_patching_filer = {
"asset": "asset.agentKey IS NOT NULL",
"vulnerability" : "vulnerability.categories NOT IN ['microsoft patch']"}
headers = _headers()
print(headers)
url1 = f"https://us.api.insight.rapid7.com/vm/v4/integration/assets"
resp = requests.post(url=url1, headers=headers, json=third_party_patching_filer, verify=False).json()
jsonData = resp
#print(jsonData)
has_next_cursor = False
nextKey = ""
if "cursor" in jsonData["metadata"]:
has_next_cursor = True
nextKey = jsonData["metadata"]["cursor"]
while has_next_cursor:
url2 = f"https://us.api.insight.rapid7.com/vm/v4/integration/assets?&size=10&cursor={nextKey}"
resp2 = requests.post(url=url2, headers=headers, json=third_party_patching_filer, verify=False).json()
#print(resp2)
#totalResources = resp2["metadata"]["totalResources"]
desktop_support = resp2['data']
cursor = resp2["metadata"]
if "cursor" in cursor:
nextKey = cursor["cursor"]
print(f"next key {nextKey}")
#print(desktop_support)
for data in desktop_support:
for tags in data['tags']:
#print(f"Tags from response{tags}")
if tags["name"] == 'OSSWIN':
print("OSSWIN")
total_critical_vul_osswin = []
total_severe_vul_osswin = []
total_modoer_vuln_osswin = []
critical_vuln_osswin = data['critical_vulnerabilities']
severe_vuln_osswin = data['severe_vulnerabilities']
modoer_vuln_osswin = data['moderate_vulnerabilities']
total_critical_vul_osswin.append(critical_vuln_osswin)
total_severe_vul_osswin.append(severe_vuln_osswin)
total_modoer_vuln_osswin.append(modoer_vuln_osswin)
print(sum(total_critical_vul_osswin))
print(sum(total_severe_vul_osswin))
print(sum(total_modoer_vuln_osswin))
if tags["name"] == 'DESKTOP_SUPPORT':
print("Desktop")
total_critical_vul_desktop = []
total_severe_vul_desktop = []
total_modoer_vuln_desktop = []
critical_vuln_desktop = data['critical_vulnerabilities']
severe_vuln_desktop = data['severe_vulnerabilities']
modoer_vuln_desktop = data['moderate_vulnerabilities']
total_critical_vul_desktop.append(critical_vuln_desktop)
total_severe_vul_desktop.append(severe_vuln_desktop)
total_modoer_vuln_desktop.append(modoer_vuln_desktop)
print(sum(total_critical_vul_desktop))
print(sum(total_severe_vul_desktop))
print(sum(total_modoer_vuln_desktop))
else:
print("Nothing to do here...")
</code></pre>
<p>i believe the errors started when i started doing the more if's (last two), it wouldnt error out when i just get the next cursor. Is there a better way i can turn my if tags["name"] == 'OSSWIN': into a function? im only 5-6 months or so into python, how can i troubleshoot my error?</p>
| [
{
"answer_id": 74305992,
"author": "Steinn Hauser Magnusson",
"author_id": 13819183,
"author_profile": "https://Stackoverflow.com/users/13819183",
"pm_score": 0,
"selected": false,
"text": "req = requests.post(url)\nif req.status_code == 200: # can also use \"req.ok\" to see if it's 2xx\n req.json()\nelse:\n print(f\"Debug! Status code was {req.status_code} with URL: {url}\")\n # ...\n"
},
{
"answer_id": 74305996,
"author": "thesraid",
"author_id": 5003489,
"author_profile": "https://Stackoverflow.com/users/5003489",
"pm_score": 1,
"selected": false,
"text": "print(resp.text)"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74305921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19899245/"
] |
74,305,929 | <p>I have an array of objects like,</p>
<pre><code>customer1 = [
{"key": "name",
"value": "Peter"},
{"key": "age",
"value": 23},
{"key": "address",
"value": "xyz St, abcd"},
{"key": "points",
"value": 234}
]
</code></pre>
<p>and I want to find say age and address from this object, what is the recommended and optimal way to do that? For real application, I might have 20-40 key-value objects in this array, out of which I might want to access 5-10 values.</p>
<p>What I do right now is I loop through this object and use conditions to find and assign values to my variables. but in this approach, I have to write multiple else if expressions (5-10).</p>
<p>For example,</p>
<pre><code>let name: string;
let points: number;
for (var item of customer1) {
if (item.key === "name") {
name = item.value;
} else if (item.key === "points") {
points = item.value;
}};
</code></pre>
| [
{
"answer_id": 74305992,
"author": "Steinn Hauser Magnusson",
"author_id": 13819183,
"author_profile": "https://Stackoverflow.com/users/13819183",
"pm_score": 0,
"selected": false,
"text": "req = requests.post(url)\nif req.status_code == 200: # can also use \"req.ok\" to see if it's 2xx\n req.json()\nelse:\n print(f\"Debug! Status code was {req.status_code} with URL: {url}\")\n # ...\n"
},
{
"answer_id": 74305996,
"author": "thesraid",
"author_id": 5003489,
"author_profile": "https://Stackoverflow.com/users/5003489",
"pm_score": 1,
"selected": false,
"text": "print(resp.text)"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74305929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18455673/"
] |
74,305,944 | <p>I have two tables <code>contacts</code> and <code>calllist</code>. <code>contacts</code> has multiple columns containing phone numbers. <code>calllist</code> has only one column <code>from_number</code> containing phone numbers. I'm trying to get all phone numbers from the column <code>from_number</code> which do not match the phone numbers in the table <code>calllist</code>.</p>
<p>Here is my working but probably very inefficient and slow SQL query:</p>
<pre><code>SELECT from_number AS phone_number, COUNT(from_number) AS number_of_calls
FROM calllist
WHERE from_number NOT IN (
SELECT businessPhone1
FROM contacts
WHERE businessPhone1 IS NOT NULL
)
AND from_number NOT IN (
SELECT businessPhone2
FROM contacts
WHERE businessPhone2 IS NOT NULL
)
AND from_number NOT IN (
SELECT homePhone1
FROM contacts
WHERE homePhone1 IS NOT NULL
)
AND from_number NOT IN (
SELECT homePhone2
FROM contacts
WHERE homePhone2 IS NOT NULL
)
AND from_number NOT IN (
SELECT mobilePhone
FROM contacts
WHERE mobilePhone IS NOT NULL
)
AND (received_at BETWEEN '$startDate' AND DATE_ADD('$endDate', INTERVAL 1 DAY))
GROUP BY phone_number
ORDER BY number_of_calls DESC
LIMIT 10
</code></pre>
<p>How do i rewrite this SQL query to be faster? Any help would be much appreciated.</p>
| [
{
"answer_id": 74305992,
"author": "Steinn Hauser Magnusson",
"author_id": 13819183,
"author_profile": "https://Stackoverflow.com/users/13819183",
"pm_score": 0,
"selected": false,
"text": "req = requests.post(url)\nif req.status_code == 200: # can also use \"req.ok\" to see if it's 2xx\n req.json()\nelse:\n print(f\"Debug! Status code was {req.status_code} with URL: {url}\")\n # ...\n"
},
{
"answer_id": 74305996,
"author": "thesraid",
"author_id": 5003489,
"author_profile": "https://Stackoverflow.com/users/5003489",
"pm_score": 1,
"selected": false,
"text": "print(resp.text)"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74305944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20409284/"
] |
74,305,948 | <p>I am trying to use aggregate assignments within a conditional assignment statement in the lines labelled "PROBLEMATIC LINE" in the following code implementation for a priority encoder module.</p>
<pre><code>library ieee;
use ieee.std_logic_1164.all;
entity SN74LS148 is -- 8 to 3 line priority encoder module
port(EI : in std_logic; -- input enable
input : in std_logic_vector(0 to 7); -- 8 bit input bus
A : out std_logic_vector(2 downto 0); -- 3 output bits
GS, EO : out std_logic -- valid bit, enable output
);
end SN74LS148;
architecture behavioral of SN74LS148 is
signal truth_table : std_logic_vector(2 downto 0);
begin
truth_table <= "HHH" when input = (others => 'H') else -- PROBLEMATIC LINE
"LLL" when input(7) = 'L' else
"LLH" when input(6) = 'L' else
"LHL" when input(5) = 'L' else
"LHH" when input(4) = 'L' else
"HLL" when input(3) = 'L' else
"HLH" when input(2) = 'L' else
"HHL" when input(1) = 'L' else
"HHH" when input(0) = 'L' else
"XXX";
A <= truth_table when EI = 'L' else -- device enabled (active low)
"HHH" when EI = 'H' else -- device disabled (all outputs inactive)
"XXX";
GS <= 'H' when EI = 'H' -- invalid when device disabled
or input = (others => 'H') else -- or none of the lines asserted (PROBLEMATIC LINE)
'L';
EO <= 'L' when EI = 'L' and input = (others => 'H') else -- PROBLEMATIC LINE
'H';
end behavioral;
</code></pre>
<p>I am using the GHDL compiler. The error that I am getting is</p>
<pre><code>encoder8x3.vhd:28:43: 'others' choice not allowed for an aggregate in this context
truth_table <= "HHH" when input = (others => 'H') else
^
encoder8x3.vhd:46:47: 'others' choice not allowed for an aggregate in this context
or input = (others => 'H') else -- or none of the lines asserted
^
encoder8x3.vhd:50:45: 'others' choice not allowed for an aggregate in this context
EO <= 'L' when EI = 'L' and input = (others => 'H') else
^
</code></pre>
<p>I guess I can fix this easily by hardcoding the inputs but what I want to know is why I am getting this error when the size of input has been specified in the port. This is not an ambiguity issue right ?</p>
| [
{
"answer_id": 74305992,
"author": "Steinn Hauser Magnusson",
"author_id": 13819183,
"author_profile": "https://Stackoverflow.com/users/13819183",
"pm_score": 0,
"selected": false,
"text": "req = requests.post(url)\nif req.status_code == 200: # can also use \"req.ok\" to see if it's 2xx\n req.json()\nelse:\n print(f\"Debug! Status code was {req.status_code} with URL: {url}\")\n # ...\n"
},
{
"answer_id": 74305996,
"author": "thesraid",
"author_id": 5003489,
"author_profile": "https://Stackoverflow.com/users/5003489",
"pm_score": 1,
"selected": false,
"text": "print(resp.text)"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74305948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13709317/"
] |
74,305,961 | <p><strong>Issue details</strong></p>
<blockquote>
<ol>
<li>.env value not initialized in the react property <br></li>
<li>siteKey value is always blank</li>
</ol>
</blockquote>
<p><strong>Property in react</strong></p>
<pre><code>const [siteKey] = useState(process.env.REACT_CAPTCHA_SITE_KEY);
</code></pre>
<p><strong>Key in .env</strong></p>
<pre><code>REACT_CAPTCHA_SITE_KEY='some key'
</code></pre>
<p><strong>Html</strong></p>
<pre><code><ReCAPTCHA sitekey={siteKey}/>
</code></pre>
| [
{
"answer_id": 74356005,
"author": "Lakruwan Pathirage",
"author_id": 12383492,
"author_profile": "https://Stackoverflow.com/users/12383492",
"pm_score": 2,
"selected": true,
"text": "UseState"
},
{
"answer_id": 74427793,
"author": "Harsh Patel",
"author_id": 7844349,
"author_profile": "https://Stackoverflow.com/users/7844349",
"pm_score": 2,
"selected": false,
"text": "useState"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74305961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/726802/"
] |
74,305,965 | <p>While trying to add the <code>@typechecked</code> property above all (of the 487) functions, I was experiencing some difficulties with finding the right replace command. I intend to go from:</p>
<pre class="lang-py prettyprint-override"><code> def some_function(
</code></pre>
<p>to:</p>
<pre class="lang-py prettyprint-override"><code> @typechecked
def some_function(
</code></pre>
<p>However, when I do <code>Ctrl+H</code> and replace <code>def </code> with:</p>
<pre><code>@typechecked
def
</code></pre>
<p>The indentation of the def gets lost.</p>
<p>Hence I would like to ask:
<strong>How can I add the property <code>typechecked above all functions in all </code>.py` files in vscode?</strong></p>
| [
{
"answer_id": 74356005,
"author": "Lakruwan Pathirage",
"author_id": 12383492,
"author_profile": "https://Stackoverflow.com/users/12383492",
"pm_score": 2,
"selected": true,
"text": "UseState"
},
{
"answer_id": 74427793,
"author": "Harsh Patel",
"author_id": 7844349,
"author_profile": "https://Stackoverflow.com/users/7844349",
"pm_score": 2,
"selected": false,
"text": "useState"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74305965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7437143/"
] |
74,305,982 | <p>I am trying to make my mobile logo larger on our site. The logo is perfect for desktop, but on mobile it is very small, regardless of theme settings I tweak.</p>
<p><a href="https://i.stack.imgur.com/oOnjG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oOnjG.png" alt="mobile preview of website" /></a></p>
<p>I tried this snippet in additional CSS without luck:</p>
<p>`</p>
<pre><code>/* MOBILE LOGO HEADER */
@media only screen and (max-width: 990px) {#logo-container img {
width: 100%;
height: auto;
}
}
</code></pre>
<p>`</p>
| [
{
"answer_id": 74356005,
"author": "Lakruwan Pathirage",
"author_id": 12383492,
"author_profile": "https://Stackoverflow.com/users/12383492",
"pm_score": 2,
"selected": true,
"text": "UseState"
},
{
"answer_id": 74427793,
"author": "Harsh Patel",
"author_id": 7844349,
"author_profile": "https://Stackoverflow.com/users/7844349",
"pm_score": 2,
"selected": false,
"text": "useState"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74305982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20409510/"
] |
74,306,011 | <p>I have a pipeline with multiple copy activities(23) from parquet to azure sql. I am experiencing low copy throughput (23kb/s) Is there a way to improve this?</p>
<p>Integration runtime is azure and not a self hosted IR.</p>
| [
{
"answer_id": 74356005,
"author": "Lakruwan Pathirage",
"author_id": 12383492,
"author_profile": "https://Stackoverflow.com/users/12383492",
"pm_score": 2,
"selected": true,
"text": "UseState"
},
{
"answer_id": 74427793,
"author": "Harsh Patel",
"author_id": 7844349,
"author_profile": "https://Stackoverflow.com/users/7844349",
"pm_score": 2,
"selected": false,
"text": "useState"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20260433/"
] |
74,306,017 | <p>For a school project I need to create a website. I have table with data in it it has 5 columns and 20 rows. I need to use the pseudo class nth-child to color all even horizontal lines #CFF and all the odd horizontal lines #FFF. Can anyone help me? I tried to use it a couple of times but wouldn't work.</p>
<p>If this works, my assignment is done</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-pricing {
float: left;
width: 70%;
border-width: 1px;
border-style: double;
border-color: #279AF1;
}
tr:nth-child(2) {
background-color: #CFF;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="table-pricing">
<thead>
<tr>
<td><strong>Product Name</strong></td>
<th>Description</th>
<th>Price</th>
<th>Shoe Type</th>
<th>Rating</th>
</tr>
</thead>
<tr>
<td>All shoe</td>
<td>For everyone</td>
<td>150</td>
<td>Soft shoe</td>
<td>8</td>
</tr>
<tr>
<td>Yellow shoe</td>
<td>Best shoe for budget</td>
<td>49</td>
<td>hard shoe</td>
<td>7</td>
<tr>
</tr>
<td>Red shoe</td>
<td>For pros</td>
<td>169</td>
<td>hard shoe</td>
<td>8.5</td>
<tr>
</tr>
<td>Orange shoe</td>
<td>Best shoe for budget</td>
<td>79</td>
<td> exterme hard shoe</td>
<td>6</td>
<tr>
</tr>
<td>Pink shoe</td>
<td>For everyone</td>
<td>45</td>
<td>hard shoe</td>
<td>6</td>
<tr>
</tr>
<tr>
<td>Grey shoe</td>
<td>For everyone</td>
<td>139</td>
<td>soft shoe</td>
<td>9.3</td>
<tr>
</tr>
<tr>
<td>Black shoe</td>
<td>For everyone</td>
<td>45</td>
<td>very soft shoe</td>
<td>6</td>
<tr>
</tr>
<tr>
<td>Aqua shoe</td>
<td>For the family</td>
<td>75</td>
<td>very soft shoe</td>
<td>7</td>
<tr>
</tr>
<tr>
<td>Indigo shoe</td>
<td>For beginners</td>
<td>145</td>
<td>very soft shoe</td>
<td>6</td>
<tr>
</tr>
<tr>
<td>All shoe2</td>
<td>For everyone</td>
<td>69</td>
<td>Soft shoe</td>
<td>8</td>
<tr>
</tr>
<td>Green shoe</td>
<td>Best shoe for budget</td>
<td>49</td>
<td>hard shoe</td>
<td>9</td>
<tr>
</tr>
<td>Fire shoe</td>
<td>For pros</td>
<td>67</td>
<td>hard shoe</td>
<td>8.5</td>
<tr>
</tr>
<td>Brown shoe</td>
<td>Best shoe for budget</td>
<td>34</td>
<td> exterme hard shoe</td>
<td>6</td>
<tr>
</tr>
<td>Pro shoe</td>
<td>For everyone</td>
<td>98</td>
<td>hard shoe</td>
<td>5</td>
</tr>
<tr>
<td>Ultra shoe</td>
<td>For everyone</td>
<td>234</td>
<td>soft shoe</td>
<td>9.3</td>
</tr>
<tr>
<td>Nike shoe</td>
<td>For everyone</td>
<td>54</td>
<td>very soft shoe</td>
<td>8</td>
</tr>
<tr>
<td>Adidas shoe</td>
<td>For the family</td>
<td>78</td>
<td>very soft shoe</td>
<td>4</td>
</tr>
<tr>
<td>Puma shoe</td>
<td>For beginners</td>
<td>98</td>
<td>very soft shoe</td>
<td>6</td>
</tr>
</table></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74356005,
"author": "Lakruwan Pathirage",
"author_id": 12383492,
"author_profile": "https://Stackoverflow.com/users/12383492",
"pm_score": 2,
"selected": true,
"text": "UseState"
},
{
"answer_id": 74427793,
"author": "Harsh Patel",
"author_id": 7844349,
"author_profile": "https://Stackoverflow.com/users/7844349",
"pm_score": 2,
"selected": false,
"text": "useState"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20111693/"
] |
74,306,032 | <p>I have a list made up by these numbers: 3,7,15,31,63.
I need to randomly take one of these numbers, but the one I obtain must be smaller of a Number taken from a cycle (it changes everytime and it is between an interval (10,100).
Can somenone help me please?
P.S. I recently started using python and i don't know a loro about it :)</p>
<p>I don't know how can i do it</p>
| [
{
"answer_id": 74356005,
"author": "Lakruwan Pathirage",
"author_id": 12383492,
"author_profile": "https://Stackoverflow.com/users/12383492",
"pm_score": 2,
"selected": true,
"text": "UseState"
},
{
"answer_id": 74427793,
"author": "Harsh Patel",
"author_id": 7844349,
"author_profile": "https://Stackoverflow.com/users/7844349",
"pm_score": 2,
"selected": false,
"text": "useState"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20409576/"
] |
74,306,039 | <p>In this bottomNavigationBar I am using Column widget right now When I am using Row Then I am getting error How to make Like this ui btn in bottom.</p>
<p><a href="https://i.stack.imgur.com/Ji1by.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ji1by.png" alt="enter image description here" /></a></p>
<p>This is my code.</p>
<pre><code> return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text(
"Support",
style: TextStyle(fontSize: tSize16),
),
leading: Builder(
builder: (BuildContext context) {
return IconButton(
icon: Icon(Icons.arrow_back_ios_rounded),
onPressed: () {
Navigator.pop(context);
},
tooltip: '',
);
},
),
elevation: 0,
backgroundColor: skyBlue,
),
body: Column(
children: [
_bodyChat(),
],
),
bottomNavigationBar: Column(
mainAxisSize: MainAxisSize.min,
children: [
ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(green2Color),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(2.0),
side: BorderSide(color: green2Color, width: 0.0),
),
),
),
onPressed: () {},
child: Padding(
padding: const EdgeInsets.all(15.0),
child: Text(
"Yes! Resolved",
style: TextStyle(fontSize: tSize18, color: Color(0xFFFFFFFF)),
),
),
),
ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(skyBlue),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(2.0),
side: BorderSide(color: skyBlue, width: 0.0),
),
),
),
onPressed: () {},
child: Padding(
padding: const EdgeInsets.all(15.0),
child: Text(
"New Comment",
style: TextStyle(fontSize: tSize18, color: Color(0xFFFFFFFF)),
),
),
)
],
),
);
</code></pre>
| [
{
"answer_id": 74356005,
"author": "Lakruwan Pathirage",
"author_id": 12383492,
"author_profile": "https://Stackoverflow.com/users/12383492",
"pm_score": 2,
"selected": true,
"text": "UseState"
},
{
"answer_id": 74427793,
"author": "Harsh Patel",
"author_id": 7844349,
"author_profile": "https://Stackoverflow.com/users/7844349",
"pm_score": 2,
"selected": false,
"text": "useState"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15610685/"
] |
74,306,050 | <p>Lets say I have this data set:</p>
<pre><code> col1 col2
1 2 1
2 1 1
3 1 2
4 1 2
5 1 2
6 1 1
7 2 1
8 2 2
</code></pre>
<p>How would I go about creating a column that counts the number of times either "1" or "2" appears across the columns, such that it looks like this:</p>
<pre><code> col1 col2 count_1 count_2
1 2 1 1 1
2 1 1 2 0
3 1 2 1 1
4 1 2 1 1
5 1 2 1 1
6 1 1 2 0
7 2 1 1 1
8 2 2 0 2
</code></pre>
| [
{
"answer_id": 74306069,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "rowSums"
},
{
"answer_id": 74306135,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 1,
"selected": false,
"text": "tidyverse"
},
{
"answer_id": 74306436,
"author": "sindri_baldur",
"author_id": 4552295,
"author_profile": "https://Stackoverflow.com/users/4552295",
"pm_score": 0,
"selected": false,
"text": "n = 2L\ninp_col = sprintf(\"col%d\", 1L:2L)\ndf[sprintf(\"count_%d\", 1L:n)] = t(apply(df[inp_col], 1L, tabulate, nbins = n))\n# col1 col2 count_1 count_2\n# 1 2 1 1 1\n# 2 1 1 2 0\n# 3 1 2 1 1\n# 4 1 2 1 1\n# 5 1 2 1 1\n# 6 1 1 2 0\n# 7 2 1 1 1\n# 8 2 2 0 2\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20409556/"
] |
74,306,051 | <p>I am making a "hotkey" for my site but the code I am using is not working.</p>
<p>How it is intended to work is when the user presses <strong>CTRL</strong> and <strong>`</strong> it should display an alert with the message hi. But instead it does nothing and I don't get any console error either.</p>
<p>Here's what I have:</p>
<pre><code>document.addEventListener('keydown', logKey);
function logKey(e) {
if (`${e.code}` == "ControlLeft" && `${e.code}` == "Backquote") {
alert('hi');
}
}
</code></pre>
| [
{
"answer_id": 74306158,
"author": "Felix Ranesberger",
"author_id": 11090915,
"author_profile": "https://Stackoverflow.com/users/11090915",
"pm_score": 1,
"selected": false,
"text": "document.addEventListener('keydown', ({ keyCode, ctrlKey }) => {\n if (ctrlKey && keyCode === 192) {\n alert(\"hi\");\n }\n});\n\n"
},
{
"answer_id": 74306962,
"author": "Oskar Grosser",
"author_id": 13561410,
"author_profile": "https://Stackoverflow.com/users/13561410",
"pm_score": 0,
"selected": false,
"text": "// Keep track of key states\nconst keys = {};\ndocument.addEventListener(\"keydown\", ({ code }) => keys[code] = true);\ndocument.addEventListener(\"keyup\", ({ code }) => keys[code] = false);\n\n// Check for combinations on each keydown event\ndocument.addEventListener(\"keydown\", e => {\n const isCtrl = keys.Control || keys.ControlLeft || keys.ControlRight;\n if (isCtrl && keys.Backquote) {\n console.log(\"Ctrl + Backquote combo detected.\");\n }\n});"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20409231/"
] |
74,306,055 | <p>I have this Panel widget defined:</p>
<pre><code>import panel as pn
demo = pn.widgets.Select(name='Demo', options=datasource)
</code></pre>
<p>How can i force the widget to update, when the datasource is also updated?
I tried with this:</p>
<pre><code>demo.param.update()
</code></pre>
<p>inside the function that also changes the datasource but it does not work. Any suggestions? Thank you.</p>
| [
{
"answer_id": 74392929,
"author": "Kaspacainoombro",
"author_id": 19839411,
"author_profile": "https://Stackoverflow.com/users/19839411",
"pm_score": 1,
"selected": true,
"text": "import panel as pn\ndemo = pn.widgets.Select(name='Demo', options=datasource)\n\n...\n# after changing the datasource do:\ndemo.options = datasource\n"
},
{
"answer_id": 74426486,
"author": "JasonWang711",
"author_id": 11145733,
"author_profile": "https://Stackoverflow.com/users/11145733",
"pm_score": 1,
"selected": false,
"text": "def update_options(event):\n demo.options = event.new\n\ndatasource.param.watch(update_options, 'value')\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19839411/"
] |
74,306,066 | <p>I have an SQLite file containing unique identifiers:</p>
<pre class="lang-none prettyprint-override"><code>+--------------+---------+-------+
| uid | request | print |
+--------------+---------+-------+
| slisn39r | 1 | 1 |
| 91na039d | 1 | 1 |
| 039184ms | 1 | 1 |
| ..(16 mio).. | | | << could be millions of used records
| 3948mass | 0 | 0 | << select first non-requested
+--------------+---------+-------+
</code></pre>
<p>I repeatedly (at intervals of < 300 msec) select the next unused, limit 1:</p>
<pre><code>SELECT uid from uidtable where (request=0 and print=0) limit 1
</code></pre>
<p>When number of used rows is low this is near instant, but at 6 million used, it's in seconds. Given the criteria above (millions of identical values), is it correct to use:</p>
<pre><code>CREATE INDEX if not exists idx_uid on uidtable ("request" ASC, "print" ASC);
</code></pre>
| [
{
"answer_id": 74392929,
"author": "Kaspacainoombro",
"author_id": 19839411,
"author_profile": "https://Stackoverflow.com/users/19839411",
"pm_score": 1,
"selected": true,
"text": "import panel as pn\ndemo = pn.widgets.Select(name='Demo', options=datasource)\n\n...\n# after changing the datasource do:\ndemo.options = datasource\n"
},
{
"answer_id": 74426486,
"author": "JasonWang711",
"author_id": 11145733,
"author_profile": "https://Stackoverflow.com/users/11145733",
"pm_score": 1,
"selected": false,
"text": "def update_options(event):\n demo.options = event.new\n\ndatasource.param.watch(update_options, 'value')\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1818059/"
] |
74,306,082 | <p>I have created following html element.</p>
<p>Here <code>remaining-height</code> class is supposed to be remaining height of <code>container-div</code> which is 100 - 15 = 85px, but because <code>grand-child-div</code> is 200 px, <code>remaining-height</code> div is going beyond <code>container-div</code>.</p>
<p>How can I prevent <code>remaining-height</code> div to be remaining height of <code>container-div</code> which is 100 - 15 = 85px.</p>
<p>Based on comment I am adding one detail. <code>remaining-height</code> will have scroll inside that div as <code>grand-child-div</code> will have more height than <code>remaining-height</code>.</p>
<pre class="lang-html prettyprint-override"><code><div class="container-div" style="height:100px">
<div class="fixed-height">
</div>
<div class="remaining-height">
<div>
<div class="grand-child-div" style="height:200px">
</div>
</div>
</div>
</div>
</code></pre>
<p>Following is css</p>
<pre class="lang-css prettyprint-override"><code>.remaining-height {
flex: 1 1 auto;
display: flex;
flex-flow: column;
background-color: yellow;
}
.fixed-height {
height: 15px;
background-color: green;
}
</code></pre>
<p><a href="https://jsfiddle.net/6cg8kmqh/" rel="nofollow noreferrer">https://jsfiddle.net/6cg8kmqh/</a></p>
| [
{
"answer_id": 74306179,
"author": "andei95",
"author_id": 14721449,
"author_profile": "https://Stackoverflow.com/users/14721449",
"pm_score": -1,
"selected": false,
"text": "height: calc(100% - 15px);"
},
{
"answer_id": 74307166,
"author": "PAB",
"author_id": 10821598,
"author_profile": "https://Stackoverflow.com/users/10821598",
"pm_score": 2,
"selected": true,
"text": "overflow: auto"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9263418/"
] |
74,306,104 | <p>eg . I have data like <code>2008Q1 , 2008Q2 , 2009Q1</code> in a single column.
I want to give output as <code>2008_Q1 ,2008_Q2</code></p>
<pre><code>df['quarter'] = df[:4] + '_' + df[2:]
</code></pre>
<p>I have tried this but it did not work.</p>
| [
{
"answer_id": 74306176,
"author": "LCMa",
"author_id": 11147691,
"author_profile": "https://Stackoverflow.com/users/11147691",
"pm_score": 1,
"selected": false,
"text": "df['quarter'] = df.quarter.apply(lambda x: x[:4] + '_' + x[-2:])\n"
},
{
"answer_id": 74306213,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 2,
"selected": false,
"text": "str.replace"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20409605/"
] |
74,306,129 | <p>I am pretty new to Great Expectations (GX) and very new to Docker, and now I am trying to combine the two. I can get a Docker image to build just fine, but when I try to run a container, it fails. I can get my GX Checkpoint to run from both the GX CLI, as well as from a Python file.</p>
<p>I have tried to run a docker image using both a <a href="https://hub.docker.com/r/ekgf/debian-awscli" rel="nofollow noreferrer">Python base image</a> (and running the Python file from the image), as well as a <a href="https://hub.docker.com/layers/greatexpectations/great_expectations/python-3.7-buster-ge-0.12.0/images/sha256-bc607ad95821817e4ed3f86fb5115596212f952560a24bb6f7c6173ba56b1cde?context=explore" rel="nofollow noreferrer">GX base image</a>.</p>
<p>Something specific to the <a href="https://docs.greatexpectations.io/docs/guides/miscellaneous/how_to_use_the_great_expectation_docker_images/" rel="nofollow noreferrer">GX documentation</a> that I think is important, I will highlight below:</p>
<pre><code>You need to mount the local great_expectations directory into the container at /usr/app/great_expectations, and from there you can run all non-interactive commands, such as running checkpoints and listing items.
</code></pre>
<p>I will break up the two paths below:</p>
<h2>Python Base Image</h2>
<p>The Python Image version of my Dockerfile is basically:</p>
<pre><code>FROM python:3.8-slim
COPY . ./src
RUN pip install -r ./src/requirements.txt
CMD ["python3", "./src/validate_data.py"]
</code></pre>
<p>(where my Python file that works outside of Docker is <code>validate_data.py</code>)</p>
<p>When I run this container, I get the following error:</p>
<pre><code>Error: No great_expectations directory was found here!
- Please check that you are in the correct directory or have specified the correct directory.
- If you have never run Great Expectations in this project, please run `great_expectations init` to get started.
</code></pre>
<h2>GX Base Image</h2>
<p>The GX Image version of my Dockerfile (which is contained in my <code>great_expectations/</code> folder is similar to:</p>
<pre><code>FROM greatexpectations/great_expectations:python-3.7-buster-ge-0.12.0
ADD . /usr/app/great_expectations
COPY . ./src
CMD ["checkpoint", "run", "data_checkpoint"]
</code></pre>
<p>(where my Checkpoint that works from the CLI outside of Docker is <code>data_checkpoint</code>)</p>
<p><strong>Note:</strong> Prior to adding <code>ADD . /usr/app/great_expectations</code> to the Dockerfile, I was getting an identical error to the Python path.</p>
<p>I get the following error:</p>
<pre><code>{'include_rendered_content': ['Unknown field.'], 'checkpoint_store_name': ['Unknown field.']}
Encountered errors during loading data context config. See ValidationError for more details.
</code></pre>
<h1>Things I have tried:</h1>
<h2>Python Base Image</h2>
<p>All the things I have tried:</p>
<ul>
<li>Adding <code>ADD . /usr/app/great_expectations</code> to my Dockerfile</li>
<li>Moving the Dockerfile from within my <code>great_expectations/</code> folder to a level above</li>
<li>Adding <code>great_expectations init</code> to the Dockerfile. (The image doesn't build in this case)</li>
<li>Mounting my local GX directory to <code>/usr/app/great_expectations</code> when I run the container</li>
</ul>
<p>No matter what I have tried, I get the same error.</p>
<h2>GX Base Image</h2>
<p>I found <code>include_rendered_content</code> and <code>checkpoint_store_name</code> in my <code>great_expectations.yml</code> config file. I commented out those lines because I was unsure of their utility, and I got a new error:</p>
<pre><code>You appear to have an invalid config version (3.0). The maximum valid version is 2.
</code></pre>
<p>So, I am guessing the reason I am getting these new errors is because the GX base image was built off of v2 of Great Expectations, and I have been using v3 when building out the GX testing infrastructure on my local.</p>
<p>So, that is really leading me to want to make the Python base image path described above work, but that's the one I have made less progress on solving.</p>
| [
{
"answer_id": 74306176,
"author": "LCMa",
"author_id": 11147691,
"author_profile": "https://Stackoverflow.com/users/11147691",
"pm_score": 1,
"selected": false,
"text": "df['quarter'] = df.quarter.apply(lambda x: x[:4] + '_' + x[-2:])\n"
},
{
"answer_id": 74306213,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 2,
"selected": false,
"text": "str.replace"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5545082/"
] |
74,306,153 | <p>I'm looking into searching a broader range of hidden sizes for my model and encountered a major slowdown in a specific range.</p>
<p>I'm assuming that CUDA may be using different optimisations for different tensor sizes and the one used in this range are just not well supported by my hardware.</p>
<p>Any ideas on how I can get more performance in this range would be greatly appreciate.</p>
<p>This is the code to produce the plot below:</p>
<pre><code>import torch
from torch import nn
import time
from plotly import graph_objs as go
from tqdm import tqdm
def test_speed(hidden_size, n=5, gpu=0):
torch.random.manual_seed(42)
model = torch.nn.LSTM(
2,
hidden_size,
num_layers=3,
batch_first=True,
dropout=0.5,
).cuda(gpu)
x = torch.randn(256, 180, 2).cuda(gpu)
# Warmup
model.forward(x)
output = []
t = time.time()
for i in range(n):
with torch.no_grad():
y = model.forward(x)[0]
output.append(y.mean().item()) # to force syncronization
return (time.time() - t) / n, output
test_range = range(64, 256)
go.Figure(
[
go.Scatter(
x=list(test_range),
y=[test_speed(hidden_size, n=20, gpu=0)[0] for hidden_size in tqdm(test_range)],
name="GPU 0",
),
],
go.Layout(
title="Mean forward pass time vs hidden size",
xaxis_title="Hidden Size",
yaxis_title="Time (s)"
)
)
</code></pre>
<p><a href="https://i.stack.imgur.com/8B0eC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8B0eC.png" alt="" /></a></p>
<p>System:</p>
<p>i9 12th gen
RTX 3080 ti
cuda: 11.8
pytorch: 1.12.1</p>
<p>I've tried reinstalling / updating cuda and torch.
I was expecting a constant relationship between hidden size and forward pass time.</p>
| [
{
"answer_id": 74306176,
"author": "LCMa",
"author_id": 11147691,
"author_profile": "https://Stackoverflow.com/users/11147691",
"pm_score": 1,
"selected": false,
"text": "df['quarter'] = df.quarter.apply(lambda x: x[:4] + '_' + x[-2:])\n"
},
{
"answer_id": 74306213,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 2,
"selected": false,
"text": "str.replace"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9751764/"
] |
74,306,160 | <p>I have a table where i put a button on the final column of some rows. This button is supposed to open a bootstrap modal using jquery through the onclick attribute. It calls a js function which has the jquery method that shows the modal, but is not working.</p>
<p>When I put an alert on the function and comment the jquery method it works. Also, when I call the method to open it outside of any function, it works when I load the page, as it should. So for some reason it only doesn't work when I try to call it from inside a function.</p>
<p>I need to call it from inside the function because I need to pass some values from the specific table row.</p>
<p>Button:</p>
<pre><code><button type="button" class="btn btn-success btn-sm" onclick="iniciar_produccion();">Iniciar Producción</button>
</code></pre>
<p>Jquery:</p>
<pre><code>// This works
$("#modalIniciarProduccion").modal();
function iniciar_produccion() {
// This doesn't work
$("#modalIniciarProduccion").modal();
// alert('working');
}
</code></pre>
<p>Modal:</p>
<pre><code><div id="modalIniciarProduccion" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">&times;</button>
<h4 class="modal-title">Finalizar Proyecto</h4>
</div>
<div class="modal-body">
<form action="marcar_proyecto_como_finalizado.php" id="finalizar" method="post" target="_self">
<div class="input-group">
<label> Fecha en que se entregó </label>
<input type="date" id="fechaEntrega" name="fechaEntrega" class="form-control" required>
<br><br>
</div>
</form>
</div>
<div class="modal-footer">
<input type="submit" form="finalizar" class="btn btn-default pull-right" name="action" value="Subir">
</div>
</div>
</div>
</div>
</code></pre>
<p>Your help is much appreciated</p>
| [
{
"answer_id": 74306176,
"author": "LCMa",
"author_id": 11147691,
"author_profile": "https://Stackoverflow.com/users/11147691",
"pm_score": 1,
"selected": false,
"text": "df['quarter'] = df.quarter.apply(lambda x: x[:4] + '_' + x[-2:])\n"
},
{
"answer_id": 74306213,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 2,
"selected": false,
"text": "str.replace"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13617839/"
] |
74,306,194 | <p>I am trying to find the do a function which is similar to a vlookup in excel but which returns the maximum value and the other values in the same row.
The data frame looks like this:</p>
<p><a href="https://i.stack.imgur.com/cvbZO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cvbZO.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/omrFD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/omrFD.png" alt="enter image description here" /></a></p>
<p>The data frame which I am dealing with are given below:</p>
<pre><code>dput(Book3)
structure(list(Item = c("ABA", "ABB", "ABC", "ABD", "ABE", "ABF"
)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-6L))
dput(Book4)
structure(list(Item = c("ABA", "ABB", "ABC", "ABD", "ABE", "ABF",
"ABA", "ABB", "ABC", "ABD", "ABE", "ABF", "ABA", "ABB", "ABC",
"ABD", "ABE", "ABF"), Max1 = c(12, 68, 27, 17, 74, 76, 78, 93,
94, 98, 46, 90, 5, 58, 67, 64, 34, 97), Additional1 = c(40, 66,
100, 33, 66, 19, 8, 70, 21, 93, 48, 34, 44, 89, 74, 20, 0, 47
), Additional2 = c(39, 31, 85, 58, 0, 2, 57, 28, 31, 32, 15,
22, 93, 41, 57, 81, 95, 46)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -18L))
</code></pre>
<p>The Expected output for this is given below:</p>
<p><a href="https://i.stack.imgur.com/eIfbK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eIfbK.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74306222,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 3,
"selected": true,
"text": "slice_max"
},
{
"answer_id": 74306274,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 1,
"selected": false,
"text": "aggregate"
},
{
"answer_id": 74306282,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "base R"
},
{
"answer_id": 74306615,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 2,
"selected": false,
"text": "ties.method = \"min\""
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20203146/"
] |
74,306,195 | <p>I have created two classes for two animations that pressing a button should turn fullscreen on and off using one animation first and another one after a second press of the button.</p>
<p>CSS
Animate enable fullscreen, animatereverse disable it</p>
<pre><code> #mv {
width: 100%;
height: 57%;
}
.animate {
animation: fullscreen 0.5s;
animation-fill-mode: forwards;
}
@keyframes fullscreen {
from {
height: 57%;
}
to {
height: 100%;
}
}
.animatereverse {
animation: fullscreenreverse 0.5s;
animation-fill-mode: forwards;
}
@keyframes fullscreenreverse {
from {
height: 100%;
}
to {
height: 57%;
}
}
</code></pre>
<p>TS/JS
I used a flag to make the function know if the interface is in fullscreen or not</p>
<pre><code> var fullscreen = false;
//console.log(" fullscreen now false ");
document.getElementById('fllbtn').addEventListener("click", function () {
if(fullscreen == false){
//console.log(" fullscreen is false ");
fullscreen = true;
//console.log(" fullscreen now true ");
document.getElementById("mv").classList.toggle("animate");
}else{
//console.log(" fullscreen is true ");
fullscreen = false;
//console.log(" fullscreen now false ");
document.getElementById("mv").classList.toggle("animatereverse");
}
})
</code></pre>
<p>The problem is as follows:</p>
<p><strong>BEGIN</strong><br />
*non-fullscreen interface<br />
*I press fullscreen button<br />
*animation works, interface becomes fullscreen<br />
*I press fullscreen button<br />
*animation works, interface returns to initial non-fullscreen state<br />
*I press fullscreen button<br />
*animation does not work, does not go fullscreen<br />
*I press the fullscreen button<br />
*animation does not work, does not go to fullscreen<br />
<strong>END</strong></p>
<p>Think of it as a loop, it basically runs twice, jumps twice and repeats like this.</p>
| [
{
"answer_id": 74306222,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 3,
"selected": true,
"text": "slice_max"
},
{
"answer_id": 74306274,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 1,
"selected": false,
"text": "aggregate"
},
{
"answer_id": 74306282,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "base R"
},
{
"answer_id": 74306615,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 2,
"selected": false,
"text": "ties.method = \"min\""
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18700261/"
] |
74,306,257 | <p>I basically have a structure like this:</p>
<pre><code>--OuterWidget
--ListWidget
--ListElementWidget1
--ListElementWidget2
...
--ListElementWidget3
</code></pre>
<p>WHat I wanna do is the following: whenever a user checks a checkbox in ListElementWidget, I want to be notified about that in OuterWidget. Also, whenever I add an element to the list in OuterWidget, I want that to be reflected in ListWidget.
I could do the simple method of passing down a notifier in constructor, but is there a simpler way?</p>
| [
{
"answer_id": 74306222,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 3,
"selected": true,
"text": "slice_max"
},
{
"answer_id": 74306274,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 1,
"selected": false,
"text": "aggregate"
},
{
"answer_id": 74306282,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "base R"
},
{
"answer_id": 74306615,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 2,
"selected": false,
"text": "ties.method = \"min\""
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9593286/"
] |
74,306,260 | <p>i want to make a function that counts the amount of digits once the value is sumed up</p>
<p>lets say i have this array</p>
<pre><code>byte[] array = new byte[] { 200, 100, 200, 250, 150, 100, 200 };
</code></pre>
<p>once this is sumed up you'll have a value of 1200</p>
<p>you can get the amount of digits with these functions</p>
<pre><code>Math.Floor(Math.Log10(1200)+1) // 4
</code></pre>
<p>but if i sum it up and there are too many values in the array i get an integer overflow</p>
<pre><code>public decimal countDigits(byte[] array)
{
decimal count = array[0];
for (int i = 1; i < array.Length; i++)
{
count = Math.Log10(Math.Pow(count, 10)+array[i]);
}
return count;
}
</code></pre>
<p>this does give the correct output i want but this causes a integeroverflow if the count is greater than 28.898879583742193 (log10(decimal.MaxValue))</p>
| [
{
"answer_id": 74306341,
"author": "PMF",
"author_id": 2905768,
"author_profile": "https://Stackoverflow.com/users/2905768",
"pm_score": -1,
"selected": true,
"text": "BigInteger"
},
{
"answer_id": 74306505,
"author": "CSharpie",
"author_id": 1789202,
"author_profile": "https://Stackoverflow.com/users/1789202",
"pm_score": 0,
"selected": false,
"text": "i want to make a function that counts the amount of digits once the value is sumed up"
},
{
"answer_id": 74306745,
"author": "Dmitry Bychenko",
"author_id": 2319407,
"author_profile": "https://Stackoverflow.com/users/2319407",
"pm_score": 1,
"selected": false,
"text": "byte"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16350392/"
] |
74,306,292 | <p>I have two collections, one being Companies and the others being Projects. I am trying to write an aggregation function that first grabs all Companies with the status of "Client", then from there write a pipeline that will return all filtered Companies where the company._id === project.companyId, as an Array of Objects. An example of the shortened Collections are below:</p>
<pre><code>Companies
{
_id: ObjectId('2341908342'),
companyName: "Meta",
address: "123 Facebook Lane",
status: "Client"
}
Projects
{
_id: ObjectId('234123840'),
companyId: '2341908342',
name: "Test Project",
price: 97450,
}
{
_id: ObjectId('23413456'),
companyId: '2341908342',
name: "Test Project 2",
price: 100000,
}
</code></pre>
<p>My desired outcome after the Aggregation:</p>
<pre><code>Companies
{
_id: ObjectId('2341908342'),
companyName: "Meta",
address: "123 Facebook Lane",
projects: [ [Project1], [Project2],
}
</code></pre>
<p>The projects field does not currently exist on the Companies collection, so I imagine we would have to add it. I also begun writing a $match function to filter by clients, but I am not sure if this is correct. I am trying to use $lookup for this but can not figure out the pipeline. Can anyone help me?</p>
<p>Where I'm currently stuck:</p>
<pre><code>try {
const allClientsWithProjects = await companyCollection
.aggregate([
{
$match: {
orgId: {
$in: [new ObjectId(req.user.orgId)],
},
status: { $in: ["Client"] },
},
},
{
$addFields: {
projects: [{}],
},
},
{
$lookup: { from: "projects", (I am stuck here) },
},
])
.toArray()
</code></pre>
<p>Thank you for any help anyone can provide.</p>
<p>UPDATE*</p>
<p>I am seemingly so close I feel like... This is what I have currently, and it is returning everything but Projects is still an empty array.</p>
<pre><code> try {
const allClients = await companyCollection
.aggregate([
{
$match: {
orgId: {
$in: [new ObjectId(req.user.orgId)],
},
status: {
$in: ["Client"],
},
},
},
{
$lookup: {
from: "projects",
let: {
companyId: {
$toString: [req.user.companyId],
},
},
pipeline: [
{
$match: {
$expr: {
$eq: ["$companyId", "$$companyId"],
},
},
},
],
as: "projects",
},
},
])
.toArray()
</code></pre>
<p>All of my company information is being returned correctly for multiple companies, but that projects Array is still []. Any help would be appreciated, and I will still be troubleshooting this.</p>
| [
{
"answer_id": 74306341,
"author": "PMF",
"author_id": 2905768,
"author_profile": "https://Stackoverflow.com/users/2905768",
"pm_score": -1,
"selected": true,
"text": "BigInteger"
},
{
"answer_id": 74306505,
"author": "CSharpie",
"author_id": 1789202,
"author_profile": "https://Stackoverflow.com/users/1789202",
"pm_score": 0,
"selected": false,
"text": "i want to make a function that counts the amount of digits once the value is sumed up"
},
{
"answer_id": 74306745,
"author": "Dmitry Bychenko",
"author_id": 2319407,
"author_profile": "https://Stackoverflow.com/users/2319407",
"pm_score": 1,
"selected": false,
"text": "byte"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20409515/"
] |
74,306,320 | <p>I'd like to write a generic query that will be run on many different tables. It needs to select all columns from any table it runs on, but there is a catch: the select must exclude the columns with data type 'ntext'. Otherwise it's a simple</p>
<pre><code>select * from <tableName>.
</code></pre>
<p>Any ideas?</p>
<p>I was able to create a query that lists all columns in a table that are not 'ntext'. Unfortunately I cannot pass this a parameter to another select, as it returns multiple results.</p>
| [
{
"answer_id": 74306757,
"author": "Patrick Hurst",
"author_id": 18522514,
"author_profile": "https://Stackoverflow.com/users/18522514",
"pm_score": 1,
"selected": false,
"text": "DECLARE c CURSOR FOR \nSELECT 'SELECT '''+sName+'.'+tName+''' AS TableName, ' +STRING_AGG('['+cName+']',', ') + ' FROM ['+sName+'].['+tName+']' AS tSQL\n FROM (\n SELECT c.name AS cName, t.name AS tName, s.name AS sName\n FROM sys.tables t\n INNER JOIN sys.columns c\n ON t.object_id = c.object_id\n INNER JOIN sys.systypes st\n ON c.system_type_id = st.xtype\n INNER JOIN sys.schemas s\n ON t.schema_id = s.schema_id\n WHERE st.name NOT IN ('TEXT', 'NTEXT','IMAGE','BINARY')\n AND (st.name NOT IN ('NVARCHAR','VARCHAR') OR c.max_length < 50)\n ) a\n GROUP BY tName, sName\nDECLARE @tSql NVARCHAR(MAX)\nOPEN c\nFETCH NEXT FROM c INTO @tSql\nWHILE @@FETCH_STATUS <> -1\nBEGIN\n PRINT @tSQL\n EXEC sp_executeSQL @tSQL\n FETCH NEXT FROM c INTO @tSql\nEND\nCLOSE c\nDEALLOCATE c\n"
},
{
"answer_id": 74307086,
"author": "SQLpro",
"author_id": 12659872,
"author_profile": "https://Stackoverflow.com/users/12659872",
"pm_score": -1,
"selected": true,
"text": "DECLARE @TABLE_NAME NVARCHAR(261) = 'dbo.sys_dm_db_missing_index_details'\n ,@SQL NVARCHAR(max) = N'';\nSELECT @SQL = N'SELECT ' + STRING_AGG('[' + CAST(COLUMN_NAME AS NVARCHAR(max)) + ']', ', ') + ' FROM ' + @TABLE_NAME\nFROM INFORMATION_SCHEMA.COLUMNS\nWHERE DATA_TYPE <> 'ntext'\n AND TABLE_SCHEMA = PARSENAME(@TABLE_NAME, 2)\n AND TABLE_NAME = PARSENAME(@TABLE_NAME, 1)\nEXEC (@SQL);\n"
},
{
"answer_id": 74309094,
"author": "Code Novice",
"author_id": 6026385,
"author_profile": "https://Stackoverflow.com/users/6026385",
"pm_score": 0,
"selected": false,
"text": "/* DynamicSelect.sql \n | Desc: This version uses PRINT to spit out the SELECT statements.\n*/\n\nDECLARE @TABLE_NAME NVARCHAR(261) = 'dbo.CT_DogBreed' --'dbo.CT_DogBreed' 'import.CT_DogBreed'\n , @SQL NVARCHAR(max) = N''\n;\n\nSELECT @SQL = CONCAT(@SQL, N'SELECT ', STRING_AGG(QUOTENAME(c.COLUMN_NAME), ', ' ), ' FROM ', c.TABLE_SCHEMA ,'.', c.TABLE_NAME, char(13))\n --CONCAT(N'SELECT ', STRING_AGG(QUOTENAME(c.COLUMN_NAME), ', ' ), ' FROM ', c.TABLE_SCHEMA ,'.', c.TABLE_NAME) AS DynamicSQL\n --, c.TABLE_SCHEMA\n --, c.TABLE_NAME\n --, PARSENAME(@TABLE_NAME, 2) AS SchemaPartFilterOnParameter\n --, PARSENAME(@TABLE_NAME, 1) AS TablePartFilterOnParameter\n\nFROM INFORMATION_SCHEMA.COLUMNS c\nWHERE DATA_TYPE <> 'ntext'\n\n AND 1 = CASE WHEN PARSENAME(@TABLE_NAME, 2) IS NOT NULL /* If TRUE then filter on Schema */\n THEN \n CASE WHEN c.TABLE_SCHEMA = PARSENAME(@TABLE_NAME, 2) THEN 1 ELSE 0 END\n /* Else if False perform no filter on Schema and return 1 for TRUE and not apply Schema Filter - Returns All Schemas */\n ELSE 1 END\n\n AND 1 = CASE WHEN PARSENAME(@TABLE_NAME, 1) IS NOT NULL /* If TRUE then filter on Table */\n THEN \n CASE WHEN c.TABLE_NAME = PARSENAME(@TABLE_NAME, 1) THEN 1 ELSE 0 END\n /* Else if False perform no filter on Table and return 1 for TRUE and not apply Table Filter - Returns All Tables */\n ELSE 1 END\n\nGROUP BY c.TABLE_SCHEMA, c.TABLE_NAME\n\nPRINT @SQL\n\n--EXEC (@SQL);\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14166256/"
] |
74,306,334 | <p>20160116
Suppose this is the data with datatype integer in a column and now I want to convert it like 2016/01/16 or 2016-01-16 and datatype as date. My column name is system and dataframe is df. How can I do that?</p>
<p>I tried using many date format function but It was not good enough to achieve the answer.</p>
| [
{
"answer_id": 74306396,
"author": "Naveed",
"author_id": 3494754,
"author_profile": "https://Stackoverflow.com/users/3494754",
"pm_score": 2,
"selected": false,
"text": "pd.to_datetime(df['dte'], format='%Y%m%d').dt.strftime('%Y/%m/%d')\n"
},
{
"answer_id": 74306397,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 0,
"selected": false,
"text": "str.replace"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20409458/"
] |
74,306,346 | <p>am triying to make a simple tik-tak-toe game using react, but i have some problem in my code.</p>
<p>This is the parent component :</p>
<pre><code>const Wrapper = () => {
const [cases, setCases] = useState(Array(9).fill(null));
const [isX, setIsX] = useState(true);
const handleClick = (i) => {
cases[i] = isX ? 'X' : 'O';
setCases(cases);
setIsX(!isX);
console.log(cases)
}
return (
<div className='ttt-wrapper'>
<div className='ttt-3-cols'>
<Case value={cases[0]} onClick={()=> handleClick(0)}/>
<Case value={cases[1]} onClick={()=> handleClick(1)}/>
<Case value={cases[2]} onClick={()=> handleClick(2)}/>
</div>
<div className='ttt-3-cols'>
<Case value={cases[3]} onClick={()=> handleClick(3)}/>
<Case value={cases[4]} onClick={()=> handleClick(4)}/>
<Case value={cases[5]} onClick={()=> handleClick(5)}/>
</div>
<div className='ttt-3-cols'>
<Case value={cases[6]} onClick={()=> handleClick(6)}/>
<Case value={cases[7]} onClick={()=> handleClick(7)}/>
<Case value={cases[8]} onClick={()=> handleClick(8)}/>
</div>
</div>
)
}
</code></pre>
<p>This is the child component :</p>
<pre><code>const Case = ({ value, handleClick }) => {
console.log(value)
return (
<button className='ttt-case' onClick={handleClick} >
{ value }
</button>
)
}
</code></pre>
<p>How can i use the <code>handleClick</code> function inside so i can use the click ?</p>
| [
{
"answer_id": 74306396,
"author": "Naveed",
"author_id": 3494754,
"author_profile": "https://Stackoverflow.com/users/3494754",
"pm_score": 2,
"selected": false,
"text": "pd.to_datetime(df['dte'], format='%Y%m%d').dt.strftime('%Y/%m/%d')\n"
},
{
"answer_id": 74306397,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 0,
"selected": false,
"text": "str.replace"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18631280/"
] |
74,306,350 | <p>I am trying to to create a rank for each instance of a status occurring, for example</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>Status</th>
<th>From_date</th>
<th>To_date</th>
<th>rank</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Available</td>
<td>2022-01-01</td>
<td>2022-01-02</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>Available</td>
<td>2022-01-02</td>
<td>2022-01-03</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>Unavailable</td>
<td>2022-01-03</td>
<td>2022-01-10</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>Available</td>
<td>2022-01-10</td>
<td>2022-01-20</td>
<td>3</td>
</tr>
</tbody>
</table>
</div>
<p>For each <code>ID</code>, for each instance of a <code>status</code> occurring, by <code>from_date</code> ascending.</p>
<p>I want to do this as i see this as the best way of getting to the final result i want which is</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>Status</th>
<th>From_date</th>
<th>To_date</th>
<th>rank</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Available</td>
<td>2022-01-01</td>
<td>2022-01-03</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>Unavailable</td>
<td>2022-01-03</td>
<td>2022-01-10</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>Available</td>
<td>2022-01-10</td>
<td>2022-01-20</td>
<td>3</td>
</tr>
</tbody>
</table>
</div>
<p>I tried <code>dense_rank(partition by id order by status, from_date</code> but can see now why that wouldnt work. Not sure how to get to this result.</p>
| [
{
"answer_id": 74306396,
"author": "Naveed",
"author_id": 3494754,
"author_profile": "https://Stackoverflow.com/users/3494754",
"pm_score": 2,
"selected": false,
"text": "pd.to_datetime(df['dte'], format='%Y%m%d').dt.strftime('%Y/%m/%d')\n"
},
{
"answer_id": 74306397,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 0,
"selected": false,
"text": "str.replace"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19126433/"
] |
74,306,369 | <p>I make a lot of fetches through the fetch-API in Deno TypeScript. The problem now is that randomly I get the following error (can't be caught by try-catch):</p>
<pre><code>error: Uncaught (in promise) TypeError: error sending request for url (https://www.googleapis.com/calendar/v3/calendars/****@group.calendar.google.com/events/?calendarId=****group.calendar.google.com): http2 error: stream error received: unexpected internal error encountered
const result: Response = await fetch(url, {
^
at async mainFetch (deno:ext/fetch/26_fetch.js:288:14)
at async fetch (deno:ext/fetch/26_fetch.js:505:9)
at async gFetchEvent (file:///home/****/my_script.ts:98:27)
</code></pre>
<p>And I don't have any clue how to fix it. Is this a Deno bug?</p>
<p>I have the following deno version installed:</p>
<pre><code>deno 1.25.2 (release, x86_64-unknown-linux-gnu)
v8 10.6.194.5
typescript 4.7.4
</code></pre>
<p>There is no particular line of code that breaks my program, just after some time (could be minutes, could be days) my program crashes with this error.</p>
<p>It only appears on my Ubuntu 20.04.5 LTS vServer by 1blu with the following hardware specs:</p>
<pre><code>H/W path Device Class Description
=============================================
system Computer
/0 bus Motherboard
/0/0 memory 8GiB System memory
/0/1 processor AMD EPYC 7452 32-Core Processor
/1 veth09bb0e5 network Ethernet interface
/2 veth0ab53b0 network Ethernet interface
/3 veth62387d0 network Ethernet interface
/4 veth7dbc5b2 network Ethernet interface
/5 vethb66edc6 network Ethernet interface
</code></pre>
<p>(output of <code>sudo lshw -short</code>)</p>
<p>The code in my main script:</p>
<pre><code>try {
await main()
} catch (e) {
console.log(new Date(), e.stack)
Deno.writeTextFileSync(`logs/${Date.now()}`, "" + e.stack)
}
</code></pre>
<p>my main function</p>
<pre><code>// this program checks changes in my school schedule and automatically puts them in my google calendar
export default async function main() {
await Kantplaner.init()
while (true) {
// MKDate is just a class that extends Date for more functionallity, nothing special
const start_day = new MKDate(Date.now())
// repeats 14 times for the next 14 days
for (let i = 0; i < 14; i++) {
const date: MKDate = i ? start_day.nextDate(1) : start_day
// get my schedule from my school's site
const vplan: VPlan | null = await Indiware(date)
if (!vplan) continue
// fetch the existing events with google calendar api and check if something in the meantime changed
const calendar = await Kantplaner.list_events(date)
// male one big object containing all indices that were previously built by `await Indiware(date)`
const GrandIndex = { ...vplan.data.KlassenIndex, ...vplan.data.LehrerIndex }
for (const item of calendar.items) {
const stundenNr = "some_string"
const stundenMitDerID = GrandIndex[stundenNr]
// if the event is not in my school's schedule anymore, delete it
if (!stundenMitDerID) {
await Kantplaner.delete_event(item.id)
continue
}
// for every other event check differences and update the corresponding Google event
// `stundenMitDerID` is an array of events with the same id (can happen at my school)
for (let i = 0; i < stundenMitDerID.length; ++i) {
// ... create update (doesn't matter)
const update: Kantplaner.Update = {}
await Kantplaner.update_event(item.id, update)
// remove lesson from index to avoid another creation
GrandIndex[stundenNr].splice(i)
if (GrandIndex[stundenNr].length == 0) delete GrandIndex[stundenNr]
}
}
// create every remainig event
for (const stundenNr in GrandIndex) {
const stundenMitDerID = GrandIndex[stundenNr]
for (let i = 0; i < stundenMitDerID.length; ++i) {
await Kantplaner.create_event({
// event data
})
}
}
}
// wait one minute to reduce unnecessary fetches
await new Promise(r => setTimeout(r, 60_000))
}
}
</code></pre>
<p>All appearances of <code>gFetchEvent</code>:</p>
<pre><code>export async function list_events(date: MKDate, TIME_SHIFT: string): Promise<Calendar> {
const calendar: Calendar | null = await gFetchEvent("/", "GET", {
timeMin: date.format(`yyyy-MM-ddT00:00:00${TIME_SHIFT}`),
timeMax: date.format(`yyyy-MM-ddT23:59:59${TIME_SHIFT}`),
})
if (!calendar) return EMPTY_CALENDAR
let nextPageToken = calendar.nextPageToken
while (nextPageToken) {
const nextPage: Calendar = await gFetchEvent("/", "GET", {
pageToken: nextPageToken,
timeMin: date.format(`yyyy-MM-ddT00:00:00${TIME_SHIFT}`),
timeMax: date.format(`yyyy-MM-ddT23:59:59${TIME_SHIFT}`),
})
calendar.items.push(...nextPage.items)
nextPageToken = nextPage.nextPageToken
}
return calendar
}
export async function create_event(event: Event) {
await gFetchEvent("/", "POST", { calendarId: CALENDAR_ID }, event)
}
export async function update_event(eventId: string, update: Update) {
await gFetchEvent(`/${eventId}`, "PATCH", {
sendUpdates: "none"
}, update)
}
export async function delete_event(eventId: string) {
await gFetchEvent(`/${eventId}`, "DELETE", {
calendarId: CALENDAR_ID,
eventId: eventId,
sendUpdates: "none"
})
}
</code></pre>
<p>The code where I fetch:</p>
<pre><code>async function gFetchEvent(urlPath: string, method: string, params?: { [key: string]: string }, body?: any) {
if (!initiated) return null
const url = new URL(CALENDAR_API_URL + urlPath)
if (params) for (const key of Object.keys(params)) url.searchParams.append(key, params[key])
const result: Response = await fetch(url, {
headers: {
Authorization: "Bearer " + access_token,
Accept: "application/json",
"Content-Type": "application/json"
},
method: method,
body: JSON.stringify(body)
})
await new Promise(f => setTimeout(f, 100))
if (result.ok) {
const text = await result.text()
if (text.length > 1) return JSON.parse(text)
else return {}
} else if (result.status == 403) {
gFetchEvent(urlPath, method, params, body)
return
}
return null
}
</code></pre>
<p>Every function call like <code>list_events</code> or <code>update_event</code> implicitly calls <code>gFetchEvent</code> function (with the different url's and ).</p>
| [
{
"answer_id": 74328650,
"author": "Marcos Casagrande",
"author_id": 1119863,
"author_profile": "https://Stackoverflow.com/users/1119863",
"pm_score": 2,
"selected": true,
"text": "await"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14794107/"
] |
74,306,410 | <p>Say I have strings that look like this:</p>
<pre class="lang-bash prettyprint-override"><code>$ a='/o\\'
$ echo $a
/o\
$ b='\//\\\\/'
$ echo $b
\//\\/
</code></pre>
<p>I'd like a shell script (ideally a one-liner) to replace <code>/</code> occurrences by <code>\</code> and vice-versa.</p>
<p>Suppose the command is called <code>invert</code>, it would yield (in a shell prompt):</p>
<pre class="lang-bash prettyprint-override"><code>$ invert $a
\o/
$ invert $b
/\\//\
</code></pre>
<p>For example using <code>sed</code>, it seems unavoidable to use a temporary character, which is not great, like so:</p>
<pre class="lang-bash prettyprint-override"><code>$ echo $a | sed 's#/#%#g' | sed 's#\\#/#g' | sed 's#%#\\#g'
\o/
$ echo $b | sed 's#/#%#g' | sed 's#\\#/#g' | sed 's#%#\\#g'
/\\//\
</code></pre>
<p>For some context, this is useful for proper printing of <code>git log --graph --all | tac</code> (I like to see newer commits at the bottom).</p>
| [
{
"answer_id": 74306774,
"author": "Luuk",
"author_id": 724039,
"author_profile": "https://Stackoverflow.com/users/724039",
"pm_score": 1,
"selected": false,
"text": "$ echo a/\\\\b\\\\/c | gawk -F \"/\" 'BEGIN{ OFS=\"\\\\\" } { for(i=1;i<=NF;i++) gsub(/\\\\/,\"/\",$i); print $0; }'\na\\/b/\\c\n$ echo a\\\\/b/\\\\c | gawk -F \"/\" 'BEGIN{ OFS=\"\\\\\" } { for(i=1;i<=NF;i++) gsub(/\\\\/,\"/\",$i); print $0; }'\na/\\b\\/c\n$\n"
},
{
"answer_id": 74306869,
"author": "Norman Gray",
"author_id": 375147,
"author_profile": "https://Stackoverflow.com/users/375147",
"pm_score": 3,
"selected": true,
"text": "tr"
},
{
"answer_id": 74307693,
"author": "Benjamin W.",
"author_id": 3266847,
"author_profile": "https://Stackoverflow.com/users/3266847",
"pm_score": 1,
"selected": false,
"text": "/"
},
{
"answer_id": 74313899,
"author": "Daweo",
"author_id": 10785975,
"author_profile": "https://Stackoverflow.com/users/10785975",
"pm_score": 1,
"selected": false,
"text": "AWK"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/931156/"
] |
74,306,417 | <p>I am trying to do some web scrawling through Selenium. However, when I run the code, it does not show the result.</p>
<p>Here is my code:</p>
<pre><code>import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from bs4 import BeautifulSoup
import time
import pandas as pd
driver = webdriver.Chrome()
url = 'https://vimeo.com/510879223'
driver.get(url)
#head > meta:nth-child(14)
#/html/head/meta[8]
title = driver.find_element(By.CSS_SELECTOR,"head > meta:nth-child(14)")
print (title.text)
description = driver.find_element(By.XPATH,"//meta[@property='og:description']").text
print (description)
</code></pre>
<p>Result:</p>
<pre><code>Process finished with exit code 0
</code></pre>
<p>In this case, what should I add or delete? Is it happened because the site that I want to scrape does not support xpath scrape option?</p>
<p>If I do print (title), the result is:</p>
<pre><code><selenium.webdriver.remote.webelement.WebElement (session="6f182a4afb7c1173f1e74f1cd6a40d87", element="e10f1407-3a09-4f3e-96e4-19071cda7d8e")>
</code></pre>
<p>Feel like it has a result but I cannot check the result as text. In this case, what is the best way to fix it? Thank you!</p>
| [
{
"answer_id": 74306774,
"author": "Luuk",
"author_id": 724039,
"author_profile": "https://Stackoverflow.com/users/724039",
"pm_score": 1,
"selected": false,
"text": "$ echo a/\\\\b\\\\/c | gawk -F \"/\" 'BEGIN{ OFS=\"\\\\\" } { for(i=1;i<=NF;i++) gsub(/\\\\/,\"/\",$i); print $0; }'\na\\/b/\\c\n$ echo a\\\\/b/\\\\c | gawk -F \"/\" 'BEGIN{ OFS=\"\\\\\" } { for(i=1;i<=NF;i++) gsub(/\\\\/,\"/\",$i); print $0; }'\na/\\b\\/c\n$\n"
},
{
"answer_id": 74306869,
"author": "Norman Gray",
"author_id": 375147,
"author_profile": "https://Stackoverflow.com/users/375147",
"pm_score": 3,
"selected": true,
"text": "tr"
},
{
"answer_id": 74307693,
"author": "Benjamin W.",
"author_id": 3266847,
"author_profile": "https://Stackoverflow.com/users/3266847",
"pm_score": 1,
"selected": false,
"text": "/"
},
{
"answer_id": 74313899,
"author": "Daweo",
"author_id": 10785975,
"author_profile": "https://Stackoverflow.com/users/10785975",
"pm_score": 1,
"selected": false,
"text": "AWK"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10149771/"
] |
74,306,478 | <p>I have my client's open street map tile server, which identificates client by checking cookie header sent with request. Here is a format:</p>
<p>Header:</p>
<pre><code>Cookie: my_clients_company_cookie=0hPRvPfAK65TLASejXTtb6xjsRcH0D7t
</code></pre>
<p>Request:</p>
<pre><code>https://fleet.my_clients_company.com/tile?z=10&x=610&y=510
</code></pre>
<p>Here is TileSource config I use:</p>
<pre><code>val tileSource: ITileSource
get() = object : OnlineTileSourceBase(
"My Client's Company", // name
3, // min zoom
18, // max zoom
512, // tile size
".png",
arrayOf("https://fleet.my_clients_company.com/tile")
) {
override fun getTileURLString(pMapTileIndex: Long): String =
"$baseUrl?z=${MapTileIndex.getZoom(pMapTileIndex)}&x=${MapTileIndex.getX(pMapTileIndex)}&y=${MapTileIndex.getY(pMapTileIndex)}"
}
</code></pre>
<p>Without sending header, I get 401 Unauthorized error response. I haven't find a way to set headers. Is it possible without forking library?</p>
| [
{
"answer_id": 74306774,
"author": "Luuk",
"author_id": 724039,
"author_profile": "https://Stackoverflow.com/users/724039",
"pm_score": 1,
"selected": false,
"text": "$ echo a/\\\\b\\\\/c | gawk -F \"/\" 'BEGIN{ OFS=\"\\\\\" } { for(i=1;i<=NF;i++) gsub(/\\\\/,\"/\",$i); print $0; }'\na\\/b/\\c\n$ echo a\\\\/b/\\\\c | gawk -F \"/\" 'BEGIN{ OFS=\"\\\\\" } { for(i=1;i<=NF;i++) gsub(/\\\\/,\"/\",$i); print $0; }'\na/\\b\\/c\n$\n"
},
{
"answer_id": 74306869,
"author": "Norman Gray",
"author_id": 375147,
"author_profile": "https://Stackoverflow.com/users/375147",
"pm_score": 3,
"selected": true,
"text": "tr"
},
{
"answer_id": 74307693,
"author": "Benjamin W.",
"author_id": 3266847,
"author_profile": "https://Stackoverflow.com/users/3266847",
"pm_score": 1,
"selected": false,
"text": "/"
},
{
"answer_id": 74313899,
"author": "Daweo",
"author_id": 10785975,
"author_profile": "https://Stackoverflow.com/users/10785975",
"pm_score": 1,
"selected": false,
"text": "AWK"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3400881/"
] |
74,306,506 | <p>I am trying to deploy my <code>deploy.js</code> file, but when I use the script 'deploy' I get a messages about “<strong>Network goerli doesn’t exist</strong>”.</p>
<pre><code>require("@nomicfoundation/hardhat-waffle")
module.exports = {
solidity: {
compilers: [{ version: "0.8.8" }, { version: "0.6.6" }]
},
defaultNetwork: "hardhat",
namedAccounts: {
deployer: {
default: 0 //here this will by default take the first account as deployer
}
},
network: {
goerli: {
url: GOERLI_RPC_URL,
accounts: [PRIVATE_KEY],
chainId: 5,
blockConfirmation: 6
}
}
}
</code></pre>
<p>And this is my configuration for <strong>APIs</strong> and environment:</p>
<pre><code>// Add API key and private key
require("@nomicfoundation/hardhat toolbox")
require("dotenv").config()
require("hardhat-deploy")
/** @type import('hardhat/config').HardhatUserConfig */
/** @type import('hardhat/config').HardhatUserConfig */
const GOERLI_PRIVATE_KEY = “PRIVATE_KEY”; const ETHERSCAN_API_KEY = “API_KEY”;
</code></pre>
<p>Is there any way to help me with this issue?</p>
| [
{
"answer_id": 74306774,
"author": "Luuk",
"author_id": 724039,
"author_profile": "https://Stackoverflow.com/users/724039",
"pm_score": 1,
"selected": false,
"text": "$ echo a/\\\\b\\\\/c | gawk -F \"/\" 'BEGIN{ OFS=\"\\\\\" } { for(i=1;i<=NF;i++) gsub(/\\\\/,\"/\",$i); print $0; }'\na\\/b/\\c\n$ echo a\\\\/b/\\\\c | gawk -F \"/\" 'BEGIN{ OFS=\"\\\\\" } { for(i=1;i<=NF;i++) gsub(/\\\\/,\"/\",$i); print $0; }'\na/\\b\\/c\n$\n"
},
{
"answer_id": 74306869,
"author": "Norman Gray",
"author_id": 375147,
"author_profile": "https://Stackoverflow.com/users/375147",
"pm_score": 3,
"selected": true,
"text": "tr"
},
{
"answer_id": 74307693,
"author": "Benjamin W.",
"author_id": 3266847,
"author_profile": "https://Stackoverflow.com/users/3266847",
"pm_score": 1,
"selected": false,
"text": "/"
},
{
"answer_id": 74313899,
"author": "Daweo",
"author_id": 10785975,
"author_profile": "https://Stackoverflow.com/users/10785975",
"pm_score": 1,
"selected": false,
"text": "AWK"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19649713/"
] |
74,306,532 | <p>I get some data from an endpoint (the origin and endpoint domains are different).
I need to get some information from the custom response header. On the server side, this custom response header was added in the <code>Access-Control-Allow-Headers</code> header.
Applied response headers. Response body is ReadableStream</p>
<pre><code> Some-Header: attachment; filename="some-name.tar"
Access-Control-Allow-Headers: Some-Header
Date: Thu, 03 Nov 2022 17:11:04 GMT
Content-Type: application/octet-stream
Transfer-Encoding: chunked
Connection: keep-alive
X-Request-ID: d331a838-b22b-41c1-a5c9-bf3461129a97
Access-Control-Allow-Origin: *
X-RateLimit-Limit: 50
X-RateLimit-Remaining: 49
X-RateLimit-Reset: 1667495466
X-DNS-Prefetch-Control: off
X-Frame-Options: SAMEORIGIN
Strict-Transport-Security: max-age=15552000; includeSubDomains
X-Download-Options: noopen
Surrogate-Control: no-store
Cache-Control: no-store, no-cache, must-revalidate, proxy-revalidate
Pragma: no-cache
Expires: 0
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
</code></pre>
<p>When I try to get this header on the client side, I get only some default headers.</p>
<pre><code>function fetchData(path, options) {
return fetch(`${API_URL}${path}`, options)
.then(parseResponse(path));
}
const response = yield call(
fetchData,
url,
requestOptions,
);
console.log(response.headers && Array.from(response.headers))
</code></pre>
<p>Did not return "Some-Header"</p>
<pre><code>[
[
"cache-control",
"no-store, no-cache, must-revalidate, proxy-revalidate"
],
[
"content-type",
"application/octet-stream"
],
[
"expires",
"0"
],
[
"pragma",
"no-cache"
]
]
</code></pre>
| [
{
"answer_id": 74306774,
"author": "Luuk",
"author_id": 724039,
"author_profile": "https://Stackoverflow.com/users/724039",
"pm_score": 1,
"selected": false,
"text": "$ echo a/\\\\b\\\\/c | gawk -F \"/\" 'BEGIN{ OFS=\"\\\\\" } { for(i=1;i<=NF;i++) gsub(/\\\\/,\"/\",$i); print $0; }'\na\\/b/\\c\n$ echo a\\\\/b/\\\\c | gawk -F \"/\" 'BEGIN{ OFS=\"\\\\\" } { for(i=1;i<=NF;i++) gsub(/\\\\/,\"/\",$i); print $0; }'\na/\\b\\/c\n$\n"
},
{
"answer_id": 74306869,
"author": "Norman Gray",
"author_id": 375147,
"author_profile": "https://Stackoverflow.com/users/375147",
"pm_score": 3,
"selected": true,
"text": "tr"
},
{
"answer_id": 74307693,
"author": "Benjamin W.",
"author_id": 3266847,
"author_profile": "https://Stackoverflow.com/users/3266847",
"pm_score": 1,
"selected": false,
"text": "/"
},
{
"answer_id": 74313899,
"author": "Daweo",
"author_id": 10785975,
"author_profile": "https://Stackoverflow.com/users/10785975",
"pm_score": 1,
"selected": false,
"text": "AWK"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8807575/"
] |
74,306,539 | <pre><code>EMPTY_VAR=''
MMDDYYYY='6.18.1997'
PIPE_VAR=' | xargs echo "1+" | bc'
echo "$MMDDYYYY" | cut -d "." -f 2${EMPTY_VAR}
>> 18
</code></pre>
<p>Command above would give me correct output, which is 18, but if I try to use PIPE_VAR instead it would give me bunch of errors:</p>
<pre><code>echo "$MMDDYYYY" | cut -d "." -f 2${PIPE_VAR}
cut: '|': No such file or directory
cut: xargs: No such file or directory
cut: echo: No such file or directory
cut: '"1+"': No such file or directory
cut: '|': No such file or directory
cut: bc: No such file or directory
</code></pre>
<p>OR:</p>
<pre><code>echo "$MMDDYYYY" | cut -d "." -f 2"$PIPE_VAR"
cut: invalid field value ‘| xargs echo "1+" | bc’
Try 'cut --help' for more information.
</code></pre>
<p>What I'm really trying to find out is that even possible to combine commands like this?</p>
| [
{
"answer_id": 74307102,
"author": "tjm3772",
"author_id": 19271565,
"author_profile": "https://Stackoverflow.com/users/19271565",
"pm_score": 3,
"selected": true,
"text": "|"
},
{
"answer_id": 74307361,
"author": "glenn jackman",
"author_id": 7552,
"author_profile": "https://Stackoverflow.com/users/7552",
"pm_score": 2,
"selected": false,
"text": "date"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3520643/"
] |
74,306,551 | <p>I am new with Google apps script and trying to learn day by day. I apologize for my basic knowledge. I am trying to split a string in a specific way. Here is the string in an array:</p>
<blockquote>
<p><strong>var</strong> <strong>data</strong> = [call number="7203266298" duration="0" date="1646769239639" type="2"
presentation="1" subscription_id="89148000007344410028"
post_dial_digits=""
subscription_component_name="com.android.phone/com.android.services.telephony.TelephonyConnectionService"
readable_date="Mar 8, 2022 12:53:59 PM" contact_name="(Unknown)"]</p>
</blockquote>
<p>Now I want to split this text in the following format:</p>
<pre><code>var data = [call number="7203266298",
duration="0",
date="1646769239639",
type="2",
presentation="1",
subscription_id="89148000007344410028",
subscription_component_name="com.android.phone/com.android.services.telephony.TelephonyConnectionService",
readable_date="Mar 8, 2022 12:53:59 PM",
contact_name="(Unknown)"]
</code></pre>
<p>I tried to use <code>split()</code> function like this:</p>
<pre><code>data = data.split(" ")
</code></pre>
<p>But the output from this method is not really what I need, it creates unnecessary partitions like this:</p>
<blockquote>
<p>[ , , call, number="+12532250046", duration="0", date="1646851016349",
type="3", presentation="1", subscription_id="89148000007344410028",
post_dial_digits="",
subscription_component_name="com.android.phone/com.android.services.telephony.TelephonyConnectionService",
readable_date="<strong>Mar</strong>, <strong>9</strong>,, <strong>2022</strong>, <strong>11:36:56</strong>, <strong>AM</strong>", contact_name="(Unknown)",
]</p>
</blockquote>
<p>Any guidance would be much appreciated.</p>
| [
{
"answer_id": 74307547,
"author": "Roomi",
"author_id": 12736831,
"author_profile": "https://Stackoverflow.com/users/12736831",
"pm_score": 3,
"selected": true,
"text": "var temp = [call number=\"7203266298\" duration=\"0\" date=\"1646769239639\" type=\"2\" presentation=\"1\" subscription_id=\"89148000007344410028\" post_dial_digits=\"\" subscription_component_name=\"com.android.phone/com.android.services.telephony.TelephonyConnectionService\" readable_date=\"Mar 8, 2022 12:53:59 PM\" contact_name=\"(Unknown)\"];\ntemp = temp.split(\" \");\n\nnewData = [temp[0]+\" \"+temp[1], temp[2],temp[3],temp[4],temp[5],temp[6], temp[7],temp[8],temp[9]+\" \"+temp[10]+\" \"+temp[11]+\" \"+temp[12]+\" \"+temp[13], \ntemp[14]];\n\nLogger.log(newData);\n\nOutput:\n\n[call number=\"7203266298\", duration=\"0\", date=\"1646769239639\", type=\"2\", presentation=\"1\", subscription_id=\"89148000007344410028\", post_dial_digits=\"\", subscription_component_name=\"com.android.phone/com.android.services.telephony.TelephonyConnectionService\", readable_date=\"Mar 8, 2022 12:53:59 PM\", contact_name=\"(Unknown)\"]\n"
},
{
"answer_id": 74308709,
"author": "Daniel",
"author_id": 12306687,
"author_profile": "https://Stackoverflow.com/users/12306687",
"pm_score": 1,
"selected": false,
"text": "function myFunction() {\n\n var data = '[call number=\"7203266298\" duration=\"0\" date=\"1646769239639\" type=\"2\" presentation=\"1\" subscription_id=\"89148000007344410028\" post_dial_digits=\"\" subscription_component_name=\"com.android.phone/com.android.services.telephony.TelephonyConnectionService\" readable_date=\"Mar 8, 2022 12:53:59 PM\" contact_name=\"(Unknown)\"]'\n\n var re = new RegExp('\"(.*?)\"', \"g\") // finds sequences enclosed in quotes \"\"\n\n data = data.slice(1,-1) //removes the [] for a cleaner look if necessary\n \n var values = data.match(re)\n var indexes = data.replace(re, \"/-/\").split(\"/-/\").slice(0, -1)\n\n var output = []\n\n for (i=0; i< indexes.length;i++){\n output.push(indexes[i].trim()+values[i])\n }\n\n console.log(output)\n}\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19456634/"
] |
74,306,565 | <p>Hope someone has some experience with the following issue I have on excel:</p>
<p>Imagine that I'd like to get a value from cell Ai, however I want to consider "i" as input from another cell in the workbook. To make it more concrete, if "i" was a fixed number like 5, then "=A5" operation would work. In my case, I want this number 5 to be dynamic, I wonder if someone know the method.</p>
| [
{
"answer_id": 74306584,
"author": "Scott Craner",
"author_id": 4851590,
"author_profile": "https://Stackoverflow.com/users/4851590",
"pm_score": 2,
"selected": false,
"text": "=INDEX(A:A,Z1)\n"
},
{
"answer_id": 74310019,
"author": "Terio",
"author_id": 4840576,
"author_profile": "https://Stackoverflow.com/users/4840576",
"pm_score": 1,
"selected": false,
"text": "INDIRECT"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10865199/"
] |
74,306,573 | <p>I have a data frame that looks like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Identification</th>
<th>Date (day/month/year)</th>
<th>X</th>
<th>Y</th>
</tr>
</thead>
<tbody>
<tr>
<td>123</td>
<td>01/01/2022</td>
<td>100</td>
<td>abc</td>
</tr>
<tr>
<td>123</td>
<td>02/01/2022</td>
<td>200</td>
<td>acb</td>
</tr>
<tr>
<td>123</td>
<td>03/01/2022</td>
<td>300</td>
<td>ary</td>
</tr>
<tr>
<td>124</td>
<td>01/01/2022</td>
<td>200</td>
<td>abc</td>
</tr>
<tr>
<td>124</td>
<td>02/01/2022</td>
<td>900</td>
<td>abc</td>
</tr>
<tr>
<td>124</td>
<td>03/01/2022</td>
<td>900</td>
<td>abc</td>
</tr>
</tbody>
</table>
</div>
<p>I am trying to create two separate 'change' columns, one for x and y separately, that is keeping a rolling count of how many times a given element is changing over time. I would like my output to look something like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Identification</th>
<th>Date (day/month/year)</th>
<th>X</th>
<th>Y</th>
<th>Change X</th>
<th>Change Y</th>
</tr>
</thead>
<tbody>
<tr>
<td>123</td>
<td>01/01/2022</td>
<td>100</td>
<td>abc</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>123</td>
<td>02/01/2022</td>
<td>200</td>
<td>acb</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>123</td>
<td>03/01/2022</td>
<td>300</td>
<td>ary</td>
<td>2</td>
<td>2</td>
</tr>
<tr>
<td>124</td>
<td>01/01/2022</td>
<td>200</td>
<td>abc</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>124</td>
<td>02/01/2022</td>
<td>900</td>
<td>abc</td>
<td>1</td>
<td>0</td>
</tr>
<tr>
<td>124</td>
<td>03/01/2022</td>
<td>900</td>
<td>abc</td>
<td>0</td>
<td>0</td>
</tr>
</tbody>
</table>
</div>
<p>Any help would be greatly appreciated!</p>
<p>Thanks :)</p>
| [
{
"answer_id": 74307364,
"author": "Nathan Furnal",
"author_id": 9479128,
"author_profile": "https://Stackoverflow.com/users/9479128",
"pm_score": 1,
"selected": false,
"text": "def consec_count(arr):\n total = 0\n out = np.zeros(len(arr), dtype=np.int32)\n acc = arr[0]\n for idx, el in enumerate(arr):\n if el == acc or el == np.nan or el == pd.NA:\n total = 0\n else:\n total += 1\n acc = el\n out[idx] = total\n return out\n\ndf[['Change X', 'Change Y']] = df.groupby('Identification', \n group_keys=False)[['X', 'Y']].transform(\n lambda x : consec_count(x.values))\n"
},
{
"answer_id": 74307972,
"author": "Anoushiravan R",
"author_id": 14314520,
"author_profile": "https://Stackoverflow.com/users/14314520",
"pm_score": 0,
"selected": false,
"text": "from itertools import accumulate\nimport pandas as pd\n\nfor col in df.columns[2:]:\n df[f'Change {col}'] = None\n for id, group in df.groupby('Identification'):\n df.loc[df['Identification'] == id, f'Change {col}'] = \\\n list(accumulate(group.index[:-1], lambda x, y: x + 1 if group.loc[y, col] != group.loc[y + 1, col] else 0, initial=0))\n\ndf\n\n Identification Date(day/month/year) X Y Change X Change Y\n0 123 01/01/2022 100 abc 0 0\n1 123 02/01/2022 200 acb 1 1\n2 123 03/01/2022 300 ary 2 2\n3 124 01/01/2022 200 abc 0 0\n4 124 02/01/2022 900 abc 1 0\n5 124 03/01/2022 900 abc 0 0\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18317477/"
] |
74,306,582 | <p>I have a bunch of Scala objects with def's that do a bunch of processing</p>
<pre><code>Foo\CatProcessing (def processing)
Foo\DogProcessing (def processing)
Foo\BirdProcessing (def processing)
</code></pre>
<p>Then I have a my main def that will call all of the individual Foo\obj defProcessing. Passing in common parameter values and such</p>
<p>I am trying to put all the list of objects into an Array or List, and then do a 'Foreach' to loop through the list passing in the parameter values or such. ie</p>
<pre><code>foreach(object in objList){
object.Processing(parametmers)
}
</code></pre>
<p>Coming from C#, I could do this via binders or the like, so who would I manage this is in Scala?</p>
| [
{
"answer_id": 74307090,
"author": "Tdawg90",
"author_id": 1294182,
"author_profile": "https://Stackoverflow.com/users/1294182",
"pm_score": -1,
"selected": false,
"text": "val test = Map(\"foobar\" -> CatProcessing)\n\ntest.values.foreach(\n (movie) => movie.processing(spark)\n)\n"
},
{
"answer_id": 74307101,
"author": "stefanobaghino",
"author_id": 3314107,
"author_profile": "https://Stackoverflow.com/users/3314107",
"pm_score": 2,
"selected": false,
"text": "for (obj <- objList) {\n obj.processing(parameters) // `object` is a reserved keyword in Scala\n}\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1294182/"
] |
74,306,596 | <p>I have a webpage with some divs displayed. There are some filters used on a webshop to filter specific items. Now I want to display the message "no results" if all divs have <code>display:none</code>.</p>
<p>How could I do that?</p>
<p>I tried some stuff like:</p>
<pre><code>if ($('filters')(':visible').length == 0) {
document.textContent('No results');
}
</code></pre>
<p>but that doesn't work.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const buttons = document.querySelectorAll('.btn');
const composers = document.querySelectorAll('.filterDiv');
buttons.forEach((btn) =>
btn.addEventListener('click', (e) => {
e.target.classList.toggle('active');
filterSelection();
}),
);
function filterSelection() {
const filters = [...document.querySelectorAll('.btn.active')].map(
(el) => el.dataset.filter,
);
composers.forEach(
(c) =>
(c.style.display =
filters.length === 0 || c.matches(`.${filters.join('.')}`) ?
'block' :
'none'),
);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="filters">
<div id="myBtnContainer">
<p>Period</p>
<button data-filter="Barok" class="btn">Barok</button>
<button data-filter="Classic" class="btn">Classic</button>
<button data-filter="Renaissance" class="btn">Renaissance</button>
<button data-filter="Romantic" class="btn">Romantic</button>
</div>
<div id="myBtnContainer">
<p>Composer</p>
<button data-filter="DiLasso" class="btn">De Lassus</button>
<button data-filter="Bach" class="btn">Bach</button>
<button data-filter="Vivaldi" class="btn">Vivaldi</button>
<button data-filter="Schubert" class="btn">Schubert</button>
<button data-filter="Tchaikovsky" class="btn">Tchaikovsky</button>
</div>
</div>
<div class="container" id="myUL">
<div class="filterDiv Renaissance DiLasso">Di Lasso -Lagrime de San Pietro</div>
<div class="filterDiv Renaissance">Sweelinck - Fantasie</div>
<div class="filterDiv Classic">Haydn - The Seasons</div>
<div class="filterDiv Romantic">Wagner - Parsifal</div>
<div class="filterDiv Classic">Mozart - Requiem</div>
<div class="filterDiv Barok Bach">Bach - Magnificat</div>
<div class="filterDiv Classic">Beethoven - Symphony 5</div>
<div class="filterDiv Barok">Händel - Hallelujah</div>
<div class="filterDiv Barok Vivaldi">Vivaldi - The Four Seasons</div>
<div class="filterDiv Renaissance">Obrecht - Factor Orbis</div>
<div class="filterDiv Romantic Schubert">Schubert - Erlkönig</div>
<div class="filterDiv Romantic Tchaikovsky">Tchaikovsky - Swan Lake</div>
<div class="filterDiv Barok Vivaldi">Vivaldi - Rosmira</div>
<div class="filterDiv Classic">Beethoven - Moonlight Sonata</div>
</div></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74306849,
"author": "Nick Vu",
"author_id": 9201587,
"author_profile": "https://Stackoverflow.com/users/9201587",
"pm_score": 3,
"selected": true,
"text": ".filterDiv.hidden"
},
{
"answer_id": 74306854,
"author": "Dean Van Greunen",
"author_id": 6651840,
"author_profile": "https://Stackoverflow.com/users/6651840",
"pm_score": 1,
"selected": false,
"text": "none"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,306,598 | <p>I have a bunch of audio files</p>
<pre><code>('ZOOM0001_LR.WAV',
'ZOOM0001_TR1.WAV',
'ZOOM0001_TR3.WAV',
'ZOOM0002_LR.WAV',
'ZOOM0002_TR1.WAV',
'ZOOM0002_TR3.WAV')
</code></pre>
<p>What I want to do is group Zoom0001_XX files into a list in the list and Zoom0002_XX into the list as well and so forth.</p>
<pre><code>files = list(glob.glob(os.path.join(r'C:\Users\adam\Music\temp_h6','*.wav')))
</code></pre>
<p>I'm not sure if list is teh way to go or should I use Tuples.</p>
<p>End goal is for me to process the files in the list of lists individually as well as mixing the set of 3 (Zoom001_LR, TR1, TR3) files.</p>
<p>Maybe there is a better way to do this?</p>
| [
{
"answer_id": 74306702,
"author": "Tyler Aldrich",
"author_id": 1580425,
"author_profile": "https://Stackoverflow.com/users/1580425",
"pm_score": 2,
"selected": true,
"text": "from collections import defaultdict\n\nfiles = ('ZOOM0001_LR.WAV',\n'ZOOM0001_TR1.WAV',\n'ZOOM0001_TR3.WAV',\n'ZOOM0002_LR.WAV',\n'ZOOM0002_TR1.WAV',\n'ZOOM0002_TR3.WAV')\n\norganized_files = defaultdict(list)\n\nfor filename in files:\n key = filename.split('_')[0]\n organized_files[key].append(filename)\n\n# organized_files is now {'ZOOM0001': ['ZOOM0001_LR.WAV', 'ZOOM0001_TR1.WAV', 'ZOOM0001_TR3.WAV'], 'ZOOM0002': ['ZOOM0002_LR.WAV', 'ZOOM0002_TR1.WAV', 'ZOOM0002_TR3.WAV']}\n\n\nfor file_group in organized_files.values():\n # ['ZOOM0001_LR.WAV', 'ZOOM0001_TR1.WAV', 'ZOOM0001_TR3.WAV']\n print(file_group)\n for f in file_group:\n # do whatever you need to do for each file in this group of \"ZOOM001_*\" files\n ...\n"
},
{
"answer_id": 74306748,
"author": "jprebys",
"author_id": 3268228,
"author_profile": "https://Stackoverflow.com/users/3268228",
"pm_score": 2,
"selected": false,
"text": "from itertools import groupby\n\nfiles = ('ZOOM0001_LR.WAV',\n 'ZOOM0001_TR1.WAV',\n 'ZOOM0001_TR3.WAV',\n 'ZOOM0002_LR.WAV',\n 'ZOOM0002_TR1.WAV',\n 'ZOOM0002_TR3.WAV')\n\nresult = []\nfor _, group in grouby(files, key=lambda name: name[:8]):\n result.append(list(group))\n\nprint(result)\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16718446/"
] |
74,306,649 | <p>This is the code I have:</p>
<pre><code>fn test_function() -> String {
String::from("")
}
fn main() {
test_function();
println!("Hello");
}
</code></pre>
<p>I was expecting rust to complain about test_function return value not being assigned, but it just works.</p>
<p>How are the rules of ownership applied here?</p>
| [
{
"answer_id": 74306727,
"author": "Masklinn",
"author_id": 8182118,
"author_profile": "https://Stackoverflow.com/users/8182118",
"pm_score": 3,
"selected": true,
"text": "#[must_use]"
},
{
"answer_id": 74306743,
"author": "Stephen Jennings",
"author_id": 19818,
"author_profile": "https://Stackoverflow.com/users/19818",
"pm_score": 0,
"selected": false,
"text": "main"
},
{
"answer_id": 74306787,
"author": "shay shalita",
"author_id": 20410041,
"author_profile": "https://Stackoverflow.com/users/20410041",
"pm_score": 2,
"selected": false,
"text": "fn test_function()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/574633/"
] |
74,306,695 | <p>My CSV file has three columns, the first column names, the second column is DOB(YYYYMM-DD) the third column is salary
looks like this kind of</p>
<pre><code>Name,DOB,Salary
Sam,2000-01-05,23000
Tyson,1989-09-11,29000
Lara,2002-11-19,19000
Brian,1990-04-20,21000
Tessa,2000-08-17,15000
</code></pre>
<p>Problem statement- <strong>Read the file and display the data and find their age in the terminal.</strong></p>
<p>Therefore, I want to add a new column called 'Age', It'll print their age accordingly.</p>
<pre><code>Name,DOB,Salary,Age
Sam,2000-01-05,23000,22
Tyson,1989-09-11,29000,51
Lara,2002-11-19,19000,20
Brian,1990-04-20,21000,32
Tessa,2000-08-17,15000,22
</code></pre>
<p>I did something like this.</p>
<pre><code>import csv
import datetime
def getage(now, dob):
years = now.year - dob.year
months = now.month - dob.month
if now.day < dob.day:
months -= 1
while months < 0:
months += 12
years -= 1
return '%sy%smo' % (years, months)
with open('emp_details.csv', 'r') as fin, open('emp_details_out.csv', 'w') as fout:
csv_reader = csv.reader(fin)
csv_writer = csv.writer(fout)
for data in csv_reader:
today = datetime.date.today()
DOB = datetime.datetime.strptime(data["DOB"], "%Y-%m-%d").date()
data["Age"] = getage(today, DOB)
csv_writer.writerow(data)
</code></pre>
<p>Where it shows the error below</p>
<pre><code>DOB = datetime.datetime.strptime(data["DOB"], "%Y-%m-%d").date()
TypeError: list indices must be integers or slices, not str
</code></pre>
<p>I'm new with csv files, That's why i need some help, If This Question looks like inappropriate please consider it. I genuinely need help.</p>
| [
{
"answer_id": 74306848,
"author": "It_is_Chris",
"author_id": 9177877,
"author_profile": "https://Stackoverflow.com/users/9177877",
"pm_score": 1,
"selected": false,
"text": "import pandas as pd\nimport datetime\n\n\ndf = pd.read_csv('some/file/path/file_name.csv') # read your csv using the file's path\ndf['DOB'] = pd.to_datetime(df['DOB']) # convert date to datetime\ndf['Age'] = (datetime.datetime.now() - df['DOB']).dt.days // 365 # calculate the age\ndf.to_csv('/some/file/path/file_name.csv', index=False) # create a csv file or update existing \n\n Name DOB Salary Age\n0 Sam 2000-01-05 23000 22\n1 Tyson 1989-09-11 29000 33\n2 Lara 2002-11-19 19000 19\n3 Brian 1990-04-20 21000 32\n4 Tessa 2000-08-17 15000 22\n"
},
{
"answer_id": 74307529,
"author": "Rabinzel",
"author_id": 15521392,
"author_profile": "https://Stackoverflow.com/users/15521392",
"pm_score": 1,
"selected": true,
"text": "csv.reader"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16230454/"
] |
74,306,703 | <p>I have an API endpoint located on my <code>localhost:8000/</code> port; this endpoint simply returns the following object <code>{"message": "hello"}</code>.</p>
<p>I would like to grab this object using my React JS script. My script is added below.</p>
<pre><code>import React, {useEffect, useState} from "react";
const App = () => {
const [message, setMessage] = useState("");
const getHomePageData = async () => {
const requestOptions = {
method: "GET",
headers: {
"Content-Type": "application/json",
},
};
const response = await fetch("/", requestOptions)
if (!response.ok) {
console.log("Error in fetching the data!");
} else {
console.log("Data fetched correctly!");
}
return await response.json();
};
const data = getHomePageData();
console.log(data);
return(
<center><h1>Hello, world!</h1></center>
);
}
export default App;
</code></pre>
<p>Fetching the data seems to be working, because I'm getting the following log inside the console: <code>Data fetched correctly!</code> thus I think everything is working alright with my backend. However on the next line I get the following error message: <code>Unhandled Promise Rejection: SyntaxError: The string did not match the expected pattern.</code></p>
<p>How can I fix my code to be able to get the <code>.json()</code> data?</p>
| [
{
"answer_id": 74306781,
"author": "Majed Badawi",
"author_id": 7486313,
"author_profile": "https://Stackoverflow.com/users/7486313",
"pm_score": 1,
"selected": false,
"text": "useEffect"
},
{
"answer_id": 74307135,
"author": "Antonin Riche",
"author_id": 7409146,
"author_profile": "https://Stackoverflow.com/users/7409146",
"pm_score": 0,
"selected": false,
"text": "const App = () => {\n const [message, error, state] = usePromise(async () => {\n const query = await fetch(\"/\", {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n })\n return await query.json();\n },\n [] // here the dependencies you use in your promise\n );\n return(\n <center><h1>Hello, world!</h1></center>\n );\n}\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7346393/"
] |
74,306,713 | <p>I would like to sum the energy values for US, China and Japan and label this 'group1'
Then groupby date, country, type and sum the energy values.</p>
<p><strong>Data</strong></p>
<p>We are grouping by date, and type and taking the sum of these specific countries: US, China and Japan - renaming this combination as group1</p>
<pre><code>date country type energy
8/1/2022 US aa 10
8/1/2022 US aa 11
8/1/2022 China bb 50
8/1/2022 Japan bb 20
10/1/2022 Australia bb 5
</code></pre>
<p><strong>Desired</strong></p>
<pre><code>date country type energy
8/1/2022 group1 aa 21
8/1/2022 group1 bb 70
10/1/2022 Australia bb 5
</code></pre>
<p><strong>Doing</strong></p>
<pre><code>df.groupby(['country','date', 'type'], as_index=False).agg({'energy': sum})
</code></pre>
<p>The above script performs the groupby and sum perfectly, but unsure of how to condense certain categories into a group before doing this step.</p>
<p>Any suggestion is appreciated</p>
| [
{
"answer_id": 74306781,
"author": "Majed Badawi",
"author_id": 7486313,
"author_profile": "https://Stackoverflow.com/users/7486313",
"pm_score": 1,
"selected": false,
"text": "useEffect"
},
{
"answer_id": 74307135,
"author": "Antonin Riche",
"author_id": 7409146,
"author_profile": "https://Stackoverflow.com/users/7409146",
"pm_score": 0,
"selected": false,
"text": "const App = () => {\n const [message, error, state] = usePromise(async () => {\n const query = await fetch(\"/\", {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n })\n return await query.json();\n },\n [] // here the dependencies you use in your promise\n );\n return(\n <center><h1>Hello, world!</h1></center>\n );\n}\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5942100/"
] |
74,306,720 | <p>My dataframe-</p>
<pre><code>dfmodtestes
Account Key Name MonthSinceInception False
1 a0 Gu 20 0.5
1 a6 Gu 15 0.4
1 a9 Gu 35 0.9
2 89 Pa 70 0.8
2 01 Ra 08 0.1
</code></pre>
<p>My objective is to keep the account order the same, but based on monthsinceinception all other column orders must be sorted by decending
goal -</p>
<pre><code>dfmodtestes
Account Key Name MonthSinceInception False
1 a9 Gu 35 0.9
1 a6 Gu 20 0.5
1 a0 Gu 15 0.4
2 89 Pa 70 0.8
2 01 Ra 08 0.1
</code></pre>
<p>So as you can observe, Account order is the same but all other variables should change based on MonthsinceInception sort by descending</p>
<p>I attempted</p>
<pre><code>dfmodwhtestes = dfmodwhtestes.sort_values(by = 'MonthsSinceInception', ascending = False)
</code></pre>
<p>But this just sorted the whole dataframe by descending based on month sinceinception, so what happend is account 2(month since inception =70) was in the first row then account 1 was in second row because month since inception is 35.</p>
| [
{
"answer_id": 74308194,
"author": "pwoolvett",
"author_id": 7814595,
"author_profile": "https://Stackoverflow.com/users/7814595",
"pm_score": 0,
"selected": false,
"text": "groupby"
},
{
"answer_id": 74308265,
"author": "Scott Boston",
"author_id": 6361531,
"author_profile": "https://Stackoverflow.com/users/6361531",
"pm_score": 2,
"selected": true,
"text": "sort_values"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18572659/"
] |
74,306,725 | <p>I have a snippet of code that is writing to a memory stream in an asynchronous way (.NET Standard 2.1)</p>
<ul>
<li>Create a list of hot tasks, one per a line</li>
<li>Then await when all of them will be finished</li>
<li>Flush the writer buffer to the memoryStream at the end</li>
</ul>
<p>Code:</p>
<pre><code>await using var memoryStream = new MemoryStream();
await using var writer = new StreamWriter(memoryStream);
var recordTasks = stringRecordsToWrite.Select(r => writer.WriteLineAsync(r));
await Task.WhenAll(recordTasks);
await writer.FlushAsync();
var result = memoryStream.ToArray();
</code></pre>
<p><strong>Questions</strong></p>
<p>There are a couple of questions that bothering me:</p>
<ol>
<li>There were reports that time to time some records had been skipped.
Thus, I wonder, could such implementation be the root cause. I've tried to reproduce the issue locally, but, unfortunately, no success</li>
<li>Also Resharper highlights that 'writer' (within SELECT statement) is a captured variable and disposed in outer scope. Can it be a problem?</li>
</ol>
<p>Or those are false traces, and the implementation is fine, and I should try to found the reason out in other place</p>
<p><strong>P.s</strong> The code snippet that, for attempt to reproduce the issue, but, as result a file about 250 MB size, and still no evidence of the issue
...</p>
<pre><code> internal class Program
{
public static async Task Main(string[] args)
{
var records = new Dictionary<string, IEnumerable<RecordsToWrite>>();
for (var i = 0; i < 200; i++)
{
var recordKey = $"test-{i}";
records.Add(recordKey, default);
var itemRecords = new List<RecordsToWrite>();
for (var x = 0; x < 500; x++)
{
itemRecords.Add(new RecordsToWrite
{
Tracking = $"{recordKey}-Track-Ref-{x}"
});
}
records[recordKey] = itemRecords;
}
var resultAsBytes = new List<byte>();
var randomizer = new Random();
foreach (var kv in records)
{
await using var memoryStream = new MemoryStream();
await using var writer = new StreamWriter(memoryStream);
var recordsToWrite = kv.Value;
var writingRecordsTasks = recordsToWrite.Select(x =>
{
var randomLengthString = randomizer.Next(100, 5000);
return writer.WriteLineAsync($"track-ref-{x.Tracking}, " +
$"now in ticks: {DateTime.UtcNow.Ticks}, " +
$"content: {new string(GetRandomLetter(), randomLengthString)}");
});
await Task.WhenAll(writingRecordsTasks);
await writer.FlushAsync();
resultAsBytes.AddRange(memoryStream.ToArray());
}
var content = Encoding.UTF8.GetString(resultAsBytes.ToArray());
await File.WriteAllLinesAsync("PathToAFile.txt", new[] { content });
Console.ReadLine();
}
public static char GetRandomLetter() => (char)('a' + new Random().Next(0, 26));
}
</code></pre>
| [
{
"answer_id": 74306865,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "MemoryStream"
},
{
"answer_id": 74327137,
"author": "Good Night Nerd Pride",
"author_id": 1025555,
"author_profile": "https://Stackoverflow.com/users/1025555",
"pm_score": 0,
"selected": false,
"text": "static async Task<string> Write(int n) {\n var records = Enumerable\n .Range(0, n)\n .Select(i => string.Join(',', Enumerable.Repeat(i, n)));\n await using var stream = new MemoryStream();\n await using var writer = new StreamWriter(stream);\n \n // Will succeed.\n var tasks = records.Select(r => writer.WriteLineAsync(r));\n \n // Will cause failure. See notes below.\n //var tasks = records.Select(r => Task.Run(() => writer.WriteLine(r)));\n \n await Task.WhenAll(tasks);\n await writer.FlushAsync();\n var bytes = stream.ToArray();\n var str = Encoding.Default.GetString(bytes);\n return str;\n}\n\nconst int N = 14000;\nvar result = await Write(N);\nresult\n .Split(Environment.NewLine)\n .Take(N) // skip last newline\n .ForEach((l, i) => Debug.Assert(\n l == string.Join(',', Enumerable.Repeat(i, N)),\n $\"Line {i} is invalid: '{l[..10]}'\"));\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5188689/"
] |
74,306,733 | <p>I'm very new to python and pandas and I'm working a project for a distance matrix.
I got an API that gets distance data from two points and I 'd like to export to excel or csv.</p>
<p>I'm getting a module "pandas" has no attribute "Dataframe"</p>
<pre><code>import requests
import json
import pandas as pd
origin="Centro Hospitalar Universitário de São João, E. P. E"
destination="Braga"
api="api"
response=requests.get("https://api.distancematrix.ai/maps/api/distancematrix/json? origins="+origin+"&destinations="+destination+"&key="+api+"")
print(response.status_code)
print(response.json())
df=pd.Dataframe.from_dict(response.json())
df.to_excel("filepath")
</code></pre>
<p>I tried capitalizing Dataframe and made sure that I don't have any pd variable or pandas.py file name</p>
| [
{
"answer_id": 74306855,
"author": "svfat",
"author_id": 2419628,
"author_profile": "https://Stackoverflow.com/users/2419628",
"pm_score": 1,
"selected": false,
"text": "df = pd.DataFrame.from_dict(response.json())\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20410015/"
] |
74,306,747 | <p>I'm trying to create a connection between my next/react client with my express/socket.io backend (it is not running as a nextjs custom server). When proxying regular http requests using rewrites in the next.config.js file, it works perfectly fine. However, when I try and connect to the server via websockets (using socket.io) it gives this error in the terminal:</p>
<pre><code>Failed to proxy http://localhost:8000/socket.io?EIO=4&transport=websocket Error: socket hang up
at connResetException (node:internal/errors:705:14)
at Socket.socketOnEnd (node:_http_client:518:23)
at Socket.emit (node:events:525:35)
at endReadableNT (node:internal/streams/readable:1358:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
code: 'ECONNRESET'
}
</code></pre>
<p>Here is my app.js at <code>./backend/app.js</code>:</p>
<pre><code>require("dotenv").config();
const express = require("express");
const cookies = require("cookie-parser");
const cors = require("cors");
const http = require("http");
const { Server } = require("socket.io");
const connect = require("./models/database");
const app = express();
const server = http.createServer(app);
const io = new Server(server);
// Connection to MongoDB database
connect();
// Defining middleware
app.use(express.json());
app.use(cookies());
app.use(cors());
app.use(require("./middleware/logger"));
// Defining api route
app.use("/v1", require("./api/v1"));
// Defining websocket entry point
io.on("connection", require("./api/socket.io-v1"));
// starting server
server.listen(process.env.PORT, () => {
console.log(`[STATUS]: Server started at port ${process.env.PORT}`);
});
</code></pre>
<p>Here is my next.config.js at <code>./frontend/next.config.js</code>:</p>
<pre><code>/** @type {import('next').NextConfig} */
module.exports = () => {
const rewrites = () => {
return [
{
source: "/v1/:path*",
destination: "http://localhost:8000/v1/:path*",
},
{
source: "/socket.io/:path*",
destination: "http://localhost:8000/socket.io/:path*",
},
];
};
return {
rewrites,
};
};
</code></pre>
<p>And lastly the <code>socket</code> instance is defined like this in one of the component files (but importantly outside of the component):</p>
<pre><code>const socket = io("http://localhost:3000", { transports : ['websocket'] });
</code></pre>
<p>Can someone tell me how I would go about proxying the socket connection to the external express server as I've been able to easily proxy requests when simply using create-react-app so I'm sure it's a problem with next.js. Thanks in advance.</p>
| [
{
"answer_id": 74306855,
"author": "svfat",
"author_id": 2419628,
"author_profile": "https://Stackoverflow.com/users/2419628",
"pm_score": 1,
"selected": false,
"text": "df = pd.DataFrame.from_dict(response.json())\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14214036/"
] |
74,306,771 | <p>I have been having a nightmare with getting my dependencies in order in this branch I have been working in. Today I finally got everything working, and my pipelines in GitLab are now passing. For context, the project is a React Native app using Expo.</p>
<p>So since I got everything working in this branch, I merged this into <code>develop</code>. But now, when I try and run <code>yarn</code> in my <code>develop</code> branch, I get the following error:</p>
<pre><code>error selenium-webdriver@4.5.0: The engine "node" is incompatible with this module. Expected version ">= 14.20.0". Got "14.17.4"
error Found incompatible module.
</code></pre>
<p>I previously got this error in my other branch, and did as it said, and upgraded my Node to <code>v14.20.0</code>, but when I did this, it did more damage than good and caused countless TypeScript problems.</p>
<p>I was having some problems with where my modules were being installed, so used <code>nohoist</code> and that seemed to do the trick, and I went back to Node <code>v14.17.4</code> and everything seemed to work. But now after merging that branch into <code>develop</code>, <code>develop</code> no longer works.</p>
<p>Here is my <code>package.json</code>:</p>
<pre><code>{
"name": "oml",
"private": true,
"scripts": {
"start": ": You are in the project root. cd into the relevant package and run yarn start to start that package.",
"prepare": "husky install",
"docs": "yarn workspace @oml/types docs",
"test:commit": "yarn workspaces run test:commit",
"test:ci": "yarn workspaces run test:ci",
"check-code": "yarn workspaces run check-code",
"build:web": "cd apps/trader-portal && expo build:web --non-interactive && rm -rf ../firebase/web-build && mv web-build ../firebase/",
"build:android": "cd apps/trader-portal && expo build:android -t app-bundle --non-interactive --no-wait --release-channel",
"build:ios": "cd apps/trader-portal && expo build:ios --non-interactive --no-wait --release-channel"
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^4.29.3",
"@typescript-eslint/parser": "^4.29.3",
"concurrently": "^6.3.0",
"eslint": "^7.32.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-import": "^2.24.2",
"eslint-plugin-jest": "^24.4.0",
"eslint-plugin-react": "^7.26.0",
"eslint-plugin-react-hooks": "^4.2.0",
"eslint-plugin-react-native": "^3.11.0",
"husky": "^7.0.4",
"open-cli": "^7.0.1",
"prettier": "2.3.2",
"typescript": "4.8.4"
},
"workspaces": {
"packages": [
"./packages/*",
"./apps/**"
],
"nohoist": [
"**/@react-native-community",
"**/@react-native-community/**"
]
}
}
</code></pre>
<p><strong>EDIT</strong></p>
<p>I would like to mention, I have no idea why I am getting this error, as I had never heard of <code>selenium-webdriver</code> until I got this error. I have no direct reference to it anywhere in my project.</p>
| [
{
"answer_id": 74330350,
"author": "Chefk5",
"author_id": 4723551,
"author_profile": "https://Stackoverflow.com/users/4723551",
"pm_score": 2,
"selected": false,
"text": "yarn add \"library name\" --ignore-engines"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17446683/"
] |
74,306,885 | <p>I'm trying to plot data with different colors depending on their classification. The data is in an nx3 array, with the first column the x position, the second column the y position, and the third column an integer defining their categorical value. I can do this by running a for loop over the entire array and plotting each point individually, but I have found that doing so massively slows down everything.</p>
<p>So, this works.</p>
<pre><code>data = np.loadtxt('data.csv', delimiter = ",")
colors = ['r', 'g', 'b']
fig = plt.figure():
for i in data:
plt.scatter(i[0], i[1], color = colors[int(i[2] % 3]))
plt.show()
</code></pre>
<p>This does not work, but I want it to, as something along this line would avoid using a for loop.</p>
<pre><code>data = np.loadtxt('data.csv', delimiter = ",")
colors = ['r', 'g', 'b']
fig = plt.figure():
plt.scatter(data[:,0], data[:,1], color = colors[int(data[:,2]) % 3])
plt.show()
</code></pre>
| [
{
"answer_id": 74330350,
"author": "Chefk5",
"author_id": 4723551,
"author_profile": "https://Stackoverflow.com/users/4723551",
"pm_score": 2,
"selected": false,
"text": "yarn add \"library name\" --ignore-engines"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18237946/"
] |
74,306,995 | <p>I have several columns where I have to replace positions in strings with underscores.</p>
<p>i.e.</p>
<pre><code>11 11_modified
XX4RDGCG9DR XX4RDGCG__R
12 12_modified
XX4RDGCG9DRX XX4RDGCG___X
13 13_modified
XX4RDGCG9DRXY XX4RDGCG____Y
</code></pre>
<p>Notice that I will always just need the first 8-digits, but depending on the column, the number of underscores changes and I only need the last value of a string-value.</p>
<p>11... has 2 underscores at the 9th and 10th position, 12... has 3 underscores at the 9th, 10th, and 11th position, and 13 has 4 underscores at the 9th, 10th, llth, and 12th position.</p>
<p>How would I do this?</p>
| [
{
"answer_id": 74307152,
"author": "Lukasz Szozda",
"author_id": 5070879,
"author_profile": "https://Stackoverflow.com/users/5070879",
"pm_score": 1,
"selected": false,
"text": "CONCAT"
},
{
"answer_id": 74307299,
"author": "Rajat",
"author_id": 9947159,
"author_profile": "https://Stackoverflow.com/users/9947159",
"pm_score": 0,
"selected": false,
"text": "insert( <base_expr>, <pos>, <len>, <insert_expr> )"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13136894/"
] |
74,306,996 | <p>I'm creating a page where I have a list of 16 video's which I want to play at random each time the page loads. That works fine, but it will keep looping the current loaded video and not pick another random video. I did include an event listener when the video ends but it's not really doing anything.</p>
<p>HTML</p>
<pre><code><div class="video-container">
<video playsinline loop id ="intro" autoplay id="intro" muted></video>
</div>
</code></pre>
<p>Javascript</p>
<pre><code>var videos = [
[{type:'mp4', 'src':'./media/1.mp4'}],
[{type:'mp4', 'src':'./media/2.mp4'}],
[{type:'mp4', 'src':'./media/3.mp4'}],
[{type:'mp4', 'src':'./media/4.mp4'}],
[{type:'mp4', 'src':'./media/5.mp4'}],
[{type:'mp4', 'src':'./media/6.mp4'}],
[{type:'mp4', 'src':'./media/7.mp4'}],
[{type:'mp4', 'src':'./media/8.mp4'}],
[{type:'mp4', 'src':'./meida/9.mp4'}],
[{type:'mp4', 'src':'./media/10.mp4'}],
[{type:'mp4', 'src':'./media/11.mp4'}],
[{type:'mp4', 'src':'./media/12.mp4'}],
[{type:'mp4', 'src':'./media/13.mp4'}],
[{type:'mp4', 'src':'./media/14.mp4'}],
[{type:'mp4', 'src':'./media/15.mp4'}],
[{type:'mp4', 'src':'./media/16.mp4'}],
];
var randomitem = videos[Math.floor(Math.random()*videos.length)];
function videoadd(element, src, type) {
var source = document.createElement('source');
source.src = src;
source.type = type;
element.appendChild(source);
}
function newvideo(src) {
var vid = document.getElementById("intro");
videoadd(vid,src ,'video/mp4');
vid.autoplay = true;
vid.load();
}
$(document).ready(function(){
newvideo(randomitem[0].src)
document.getElementById('intro').addEventListener('ended', myHandler,false);
function myHandler(e) {
newvideo(randomitem[0].src)
}
})
</code></pre>
<p>I tried the video end event listener in the html with</p>
<pre><code><script>
document.getElementById('intro').addEventListener('ended', myHandler,false);
function myHandler(e) {
newvideo(randomitem[0].src)
}
</script>
</code></pre>
<p>I tried to implement it into the javascript itself but the function returned (e) is declared but it's value is never read.</p>
| [
{
"answer_id": 74307053,
"author": "jesus marmol",
"author_id": 20102799,
"author_profile": "https://Stackoverflow.com/users/20102799",
"pm_score": -1,
"selected": false,
"text": " var backgroundVideo = document.getElementById('intro');\n backgroundVideo.onended = () => {\n //here you can change the src atribute to change the video and play it again\n}\n\n"
},
{
"answer_id": 74307056,
"author": "HKTE",
"author_id": 12412262,
"author_profile": "https://Stackoverflow.com/users/12412262",
"pm_score": -1,
"selected": false,
"text": "videoElement.addEventListener('ended', () => {\n // Select and play a new random video here\n});\n"
},
{
"answer_id": 74307059,
"author": "Dr. Vortex",
"author_id": 17637456,
"author_profile": "https://Stackoverflow.com/users/17637456",
"pm_score": 0,
"selected": false,
"text": "let i = 0;\nconst randomVideos = videos\nrandomVideos.sort(() => (Math.random() > .5) ? 1 : -1); //shuffle\n\n...\n\nfunction myHandler(e) {\n newvideo(randomVideos[++i][0].src);\n}\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74306996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14358964/"
] |
74,307,054 | <p>I'm trying to create a regex pattern to match account ids following certain rules. This matching will occur within a python script using the re library, but I believe the question is mostly just a regex in general issue.</p>
<p>The account ids adhere to the following rules:</p>
<ol>
<li>Must be exactly 6 characters long</li>
<li>The letters and numbers do <strong>not</strong> have to be unique</li>
</ol>
<p>AND</p>
<ol start="3">
<li>3 uppercase letters followed by 3 numbers</li>
</ol>
<p>OR</p>
<ol start="4">
<li>Up to 6 numbers followed by an amount of letters that bring the length of the id to 6</li>
</ol>
<p>So, the following would be 'valid' account ids:</p>
<pre><code>ABC123
123456
12345A
1234AB
123ABC
12ABCD
1ABCDE
AAA111
</code></pre>
<p>And the following would be 'invalid' account ids</p>
<pre><code>ABCDEF
ABCDE1
ABCD12
AB1234
A12345
ABCDEFG
1234567
1
12
123
1234
12345
</code></pre>
<p>I can match the 3 letters followed by 3 numbers very simply, but I'm having trouble understanding how to write a regex to varyingly match an amount of letters such that if x = number of numbers in string, then y = number of letters in string = 6 - x.</p>
<p>I suspect that using lookaheads might help solve this problem, but I'm still new to regex and don't have an amazing grasp on how to use them correctly.</p>
<p>I have the following regex right now, which uses positive lookaheads to check if the string starts with a number or letter, and applies different matching rules accordingly:</p>
<pre><code>((?=^[0-9])[0-9]{1,6}[A-Z]{0,5}$)|((?=^[A-Z])[A-Z]{3}[0-9]{3}$)
</code></pre>
<p>This works to match the 'valid' account ids listed above, however it also matches the following strings which should be invalid:</p>
<ul>
<li>1</li>
<li>12</li>
<li>123</li>
<li>1234</li>
<li>12345</li>
</ul>
<p>How can I change the first capturing group <code>((?=^[0-9])[0-9]{1,6}[A-Z]{0,5}$)</code> to know how many letters to match based on how many numbers begin the string, if that's possible?</p>
| [
{
"answer_id": 74307053,
"author": "jesus marmol",
"author_id": 20102799,
"author_profile": "https://Stackoverflow.com/users/20102799",
"pm_score": -1,
"selected": false,
"text": " var backgroundVideo = document.getElementById('intro');\n backgroundVideo.onended = () => {\n //here you can change the src atribute to change the video and play it again\n}\n\n"
},
{
"answer_id": 74307056,
"author": "HKTE",
"author_id": 12412262,
"author_profile": "https://Stackoverflow.com/users/12412262",
"pm_score": -1,
"selected": false,
"text": "videoElement.addEventListener('ended', () => {\n // Select and play a new random video here\n});\n"
},
{
"answer_id": 74307059,
"author": "Dr. Vortex",
"author_id": 17637456,
"author_profile": "https://Stackoverflow.com/users/17637456",
"pm_score": 0,
"selected": false,
"text": "let i = 0;\nconst randomVideos = videos\nrandomVideos.sort(() => (Math.random() > .5) ? 1 : -1); //shuffle\n\n...\n\nfunction myHandler(e) {\n newvideo(randomVideos[++i][0].src);\n}\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20277369/"
] |
74,307,105 | <p>I have an Oracle SQL view with an ID, TIME_STAMP, LOCATION and a "COMMAND" variable which is used to describe "Time IN", "Time Requested" and "Time Out" as an integer 1, 2, 3, respectively, such as:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>Time</th>
<th>Command</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>00:20:00</td>
<td>1</td>
<td>51</td>
</tr>
<tr>
<td>2</td>
<td>00:22:00</td>
<td>1</td>
<td>52</td>
</tr>
<tr>
<td>1</td>
<td>00:30:00</td>
<td>2</td>
<td>51</td>
</tr>
<tr>
<td>1</td>
<td>00:32:00</td>
<td>3</td>
<td>51</td>
</tr>
<tr>
<td>2</td>
<td>00:40:00</td>
<td>2</td>
<td>52</td>
</tr>
<tr>
<td>2</td>
<td>00:43:00</td>
<td>3</td>
<td>52</td>
</tr>
<tr>
<td>1</td>
<td>00:50:00</td>
<td>1</td>
<td>52</td>
</tr>
<tr>
<td>1</td>
<td>00:52:00</td>
<td>2</td>
<td>52</td>
</tr>
<tr>
<td>3</td>
<td>01:10:00</td>
<td>1</td>
<td>53</td>
</tr>
<tr>
<td>1</td>
<td>01:22:00</td>
<td>3</td>
<td>52</td>
</tr>
<tr>
<td>3</td>
<td>01:40:00</td>
<td>2</td>
<td>53</td>
</tr>
<tr>
<td>3</td>
<td>01:52:00</td>
<td>3</td>
<td>53</td>
</tr>
</tbody>
</table>
</div>
<p>I would like to group the IDs of Time IN, REQ, and OUT into one row, for each ID visit to each location, to get the result:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>Time IN</th>
<th>Time REQ</th>
<th>Time OUT</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>00:20:00</td>
<td>00:30:00</td>
<td>00:32:00</td>
<td>51</td>
</tr>
<tr>
<td>2</td>
<td>00:22:00</td>
<td>00:40:00</td>
<td>00:43:00</td>
<td>52</td>
</tr>
<tr>
<td>1</td>
<td>00:50:00</td>
<td>00:52:00</td>
<td>01:22:00</td>
<td>53</td>
</tr>
<tr>
<td>3</td>
<td>01:10:00</td>
<td>01:40:00</td>
<td>01:52:00</td>
<td>52</td>
</tr>
</tbody>
</table>
</div><hr />
<p>I achieved this by searching where command = 1 (all IN instances) and then using a SELECT in the SELECT statement</p>
<pre><code>SELECT
O.ID AS "ID",
O.TIME AS "TIMEIN",
(SELECT
MIN(TIME)
FROM VIEW I
WHERE O.LOCATION = I.LOCATION AND COMMAND = ('2') AND O.ID = I.ID AND O.TIME < I.TIME)
AS "TIMEREQ",
(SELECT
MIN(TIME)
FROM VIEW I
WHERE O.LOCATION = I.LOCATION AND COMMAND = ('3') AND O.ID = I.ID AND O.TIME < I.TIME)
AS "TIMEOUT",
O.LOCATION AS "LOCATION"
FROM VIEW O
WHERE
LOCATION IN ('52','53','54') AND COMMAND IN ('1')
ORDER BY TIME DESC
</code></pre>
<p>The results of this takes ~11s for 12,000 rows.</p>
<p>When I then tried to JOIN a table to this, which just contains:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>Comment</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Hello, World!</td>
</tr>
<tr>
<td>2</td>
<td>Test comment</td>
</tr>
</tbody>
</table>
</div>
<p>The view never loads, tried up to ~50s, but either way this is too slow and I'm expecting incorrect.</p>
<p>I've tried to use a different approach by using a SELECT statement within the JOIN statement to see if the performance was any better but I'm struggling to get it to work:</p>
<pre><code>SELECT
P.ID AS "ID",
P.TIME AS "TIMEIN",
TIMECOM2 AS "TIMEREQ",
P.LOCATION AS "LOCATION",
P.COMMAND AS "COMMAND"
FROM VIEW P
LEFT JOIN
(SELECT
MAX(C.ID) AS "REQID",
MIN(C.TIME) AS "TIMECOM2"
FROM VIEW C
WHERE C.COMMAND = 2 AND C.LOCATION IN (52, 53, 54) AND C.ID = '2253')
ON (P.ID = REQID) AND TIMECOM2 > P.TIME
WHERE
P.ID = '2253' AND
P.LOCATION IN (52, 53, 54) AND
P.COMMAND = 1
ORDER BY P.TIME, TIMECOM2
</code></pre>
<p>I tried many different approaches in the above, but that was the last attempt, and note I only tried with TIMEREQ and picked a specific ID to try to get it to work in the first instance. I think my issue lies in not being able to use VIEW P in the SELECT statement, such as P.TIME > C.TIME in the WHERE statement. I am getting such results:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>TIMEIN</th>
<th>TIMEREQ</th>
</tr>
</thead>
<tbody>
<tr>
<td>2253</td>
<td>31-OCT-22 22:20:15</td>
<td>31-OCT-22 22:40:11</td>
</tr>
<tr>
<td>2253</td>
<td>01-NOV-22 09:40:19</td>
<td>(null)</td>
</tr>
<tr>
<td>2253</td>
<td>01-NOV-22 11:04:59</td>
<td>(null)</td>
</tr>
<tr>
<td>2253</td>
<td>01-NOV-22 18:21:19</td>
<td>(null)</td>
</tr>
<tr>
<td>2253</td>
<td>01-NOV-22 19:20:38</td>
<td>(null)</td>
</tr>
</tbody>
</table>
</div>
<p>Which I don't understand - I can get it to show the MIN or MAX date in each row, or the MIN or MAX in the first row, or all others..</p>
<p>Also, could anyone explain why SELECT statements within SELECT statements are slow, or am I missing something? Obviously I don't know if JOIN is any faster as I failed to get it to work.</p>
| [
{
"answer_id": 74307053,
"author": "jesus marmol",
"author_id": 20102799,
"author_profile": "https://Stackoverflow.com/users/20102799",
"pm_score": -1,
"selected": false,
"text": " var backgroundVideo = document.getElementById('intro');\n backgroundVideo.onended = () => {\n //here you can change the src atribute to change the video and play it again\n}\n\n"
},
{
"answer_id": 74307056,
"author": "HKTE",
"author_id": 12412262,
"author_profile": "https://Stackoverflow.com/users/12412262",
"pm_score": -1,
"selected": false,
"text": "videoElement.addEventListener('ended', () => {\n // Select and play a new random video here\n});\n"
},
{
"answer_id": 74307059,
"author": "Dr. Vortex",
"author_id": 17637456,
"author_profile": "https://Stackoverflow.com/users/17637456",
"pm_score": 0,
"selected": false,
"text": "let i = 0;\nconst randomVideos = videos\nrandomVideos.sort(() => (Math.random() > .5) ? 1 : -1); //shuffle\n\n...\n\nfunction myHandler(e) {\n newvideo(randomVideos[++i][0].src);\n}\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20409599/"
] |
74,307,106 | <p>Data is a list of lists, ig. <code>[[1, 0], [0, 1], [1, 1]]</code></p>
<p>I have these two lines which get an average of <code>val[0]</code> in a list data based on if <code>val[1]</code> is <code>0</code></p>
<pre class="lang-py prettyprint-override"><code>l = [val[0] for val in data if val[1] == 0]
return sum(l)/len(l)
</code></pre>
<p><strong>Is there a way to calculate the sum while doing the list comprehension?</strong></p>
| [
{
"answer_id": 74314284,
"author": "S.B",
"author_id": 13944524,
"author_profile": "https://Stackoverflow.com/users/13944524",
"pm_score": 2,
"selected": true,
"text": "data = [[1, 0], [0, 1], [1, 1], [4, 0]]\n\nlst = []\ntotal = 0\nfor v1, v2 in data:\n if v2 == 0:\n total += v1\n lst.append(v1)\n"
},
{
"answer_id": 74314397,
"author": "HiFile.app - best file manager",
"author_id": 2757925,
"author_profile": "https://Stackoverflow.com/users/2757925",
"pm_score": 0,
"selected": false,
"text": "sum"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17171910/"
] |
74,307,131 | <p>Let's say I have the following data frame:</p>
<pre><code>"\n mark has \n no name",
"\n john walks his \n dog",
"mary is fun \n",
"tim is \n old"
</code></pre>
<pre class="lang-py prettyprint-override"><code>data = [
"\n mark has \n no name",
"\n john walks his \n dog",
"mary is fun \n",
"tim is \n old"
]
df = pd.DataFrame(data, columns=['Sentences'])
</code></pre>
<p>How can I write a function, ideally a lambda, as I have not much practice with it, that will replace the first <code>\n</code> and last <code>\n</code> only in each of the above, so the output is:</p>
<pre><code>"mark has \n no name",
"john walks his \n dog",
"mary is fun",
"tim is \n old"
</code></pre>
<p>Ideally, I would like the output to be a separate column on the data frame, as opposed to replacing what is there.</p>
<p>I have seen formulas that deal with a global replacement, but I need something a bit more specific.</p>
| [
{
"answer_id": 74307567,
"author": "Otto",
"author_id": 11476513,
"author_profile": "https://Stackoverflow.com/users/11476513",
"pm_score": -1,
"selected": true,
"text": "\\n"
},
{
"answer_id": 74307779,
"author": "pwoolvett",
"author_id": 7814595,
"author_profile": "https://Stackoverflow.com/users/7814595",
"pm_score": -1,
"selected": false,
"text": "df['fixed'] = df.Sentences.str.strip(\"\\n\")\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20410046/"
] |
74,307,132 | <p>In the below dictionary, how would I print the highest overall score?</p>
<pre><code>scores = {
'Monday': [21, 23, 24, 19],
'Tuesday': [16, 15, 12, 19],
'Wednesday': [23, 22, 23],
'Thursday': [18, 20, 26, 24],
'Friday': [17, 22],
'Saturday': [22, 24],
'Sunday': [21, 21, 28, 25]
}
</code></pre>
<p>I am very new to python and I didn't even know where to start with this.</p>
| [
{
"answer_id": 74307224,
"author": "ThePyGuy",
"author_id": 9136348,
"author_profile": "https://Stackoverflow.com/users/9136348",
"pm_score": 1,
"selected": false,
"text": "max"
},
{
"answer_id": 74307229,
"author": "Sachin Paryani",
"author_id": 3107773,
"author_profile": "https://Stackoverflow.com/users/3107773",
"pm_score": 0,
"selected": false,
"text": "print(max([max(scores[day]) for day in scores]))\n"
},
{
"answer_id": 74307528,
"author": "CryptoFool",
"author_id": 7631480,
"author_profile": "https://Stackoverflow.com/users/7631480",
"pm_score": 0,
"selected": false,
"text": "from pprint import pprint\n\nscores = {\n 'Monday': [21, 23, 24, 19],\n 'Tuesday': [16, 15, 12, 19],\n 'Wednesday': [23, 22, 23],\n 'Thursday': [18, 20, 26, 24],\n 'Friday': [17, 22],\n 'Saturday': [22, 24],\n 'Sunday': [21, 21, 28, 25]\n}\n\nscores = {k: {'scores': v, 'total': sum(v), 'max': max(v), 'min': min(v)} for k, v in scores.items()}\npprint(scores)\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20410319/"
] |
74,307,140 | <p>I am trying to pull the second closest date for each as of date in a data set. Below is some example data</p>
<pre><code>asOfDate maturityDate value
0 2022-09-01 2022-10-01 57.273
1 2022-09-01 2022-11-01 55.861
2 2022-09-01 2022-12-01 59.231
3 2022-09-01 2023-01-01 59.305
4 2022-09-01 2023-02-01 58.081
5 2022-09-01 2023-03-01 51.198
6 2022-09-01 2023-04-01 44.532
7 2022-09-01 2023-05-01 38.955
8 2022-09-01 2023-06-01 37.901
9 2022-09-01 2023-07-01 40.461
10 2022-09-01 2023-08-01 40.126
11 2022-09-01 2023-09-01 40.221
12 2022-09-01 2023-10-01 40.455
13 2022-09-01 2023-11-01 41.652
14 2022-09-01 2023-12-01 42.450
15 2022-09-01 2024-01-01 45.057
16 2022-09-01 2024-02-01 42.459
17 2022-09-01 2024-03-01 37.544
18 2022-09-01 2024-04-01 29.901
19 2022-09-01 2024-05-01 25.300
20 2022-09-01 2024-06-01 22.360
21 2022-09-01 2024-07-01 22.544
22 2022-09-01 2024-08-01 23.931
</code></pre>
<p>I have a list of asOfDates with several maturity dates going out. I currently am using this code to pull the maturityDate and value that is the smallest (or rolling front month) for each asOfDate.</p>
<pre><code>df_final[df_final['maturityDate']==df_final.groupby(['asOfDate'])['maturityDate'].transform(min)]
</code></pre>
<p>The above works perfectly for my needs, but now I would like to, instead of getting the smallest date, receive the second smallest for each as of date. I have attempted to get this second smallest, but I received an error that states, "error: Can only compare identically-labeled Series objects". Below is what I have tried that does output the dates I want, but when I try to reindex the data frame I get the error.</p>
<pre><code>df_final.groupby(['asOfDate'])['maturityDate'].nsmallest(2).groupby(['asOfDate']).last().reset_index()
df_final[df_final['maturityDate']==df_final.groupby(['asOfDate'])['maturityDate'].nsmallest(2).groupby(['asOfDate']).last().reset_index()]
</code></pre>
<p>The first one above outputs the below, which is the desired results along with the values any ideas here?</p>
<pre><code>asOfDate maturityDate
0 2022-09-01 2022-11-01
1 2022-09-02 2022-11-01
2 2022-09-05 2022-11-01
3 2022-09-06 2022-11-01
4 2022-09-07 2022-11-01
5 2022-09-08 2022-11-01
6 2022-09-09 2022-11-01
7 2022-09-12 2022-11-01
8 2022-09-13 2022-11-01
9 2022-09-14 2022-11-01
10 2022-09-15 2022-11-01
11 2022-09-16 2022-12-01
12 2022-09-19 2022-12-01
13 2022-09-20 2022-12-01
14 2022-09-21 2022-12-01
15 2022-09-22 2022-12-01
16 2022-09-23 2022-12-01
17 2022-09-26 2022-12-01
18 2022-09-27 2022-12-01
19 2022-09-28 2022-12-01
20 2022-09-29 2022-12-01
21 2022-09-30 2022-12-01
22 2022-10-03 2022-12-01
23 2022-10-04 2022-12-01
24 2022-10-05 2022-12-01
25 2022-10-06 2022-12-01
26 2022-10-07 2022-12-01
27 2022-10-10 2022-12-01
28 2022-10-11 2022-12-01
29 2022-10-12 2022-12-01
</code></pre>
| [
{
"answer_id": 74308092,
"author": "BERA",
"author_id": 6936582,
"author_profile": "https://Stackoverflow.com/users/6936582",
"pm_score": 3,
"selected": true,
"text": "import pandas as pd\ncolumns = [\"asOfDate\", \"maturityDate\", \"value\"]\ndata = [\n[\"2022-09-01\", \"2022-10-01\", 57.273]\n,[\"2022-09-01\", \"2022-11-01\", 55.861]\n,[\"2022-09-01\", \"2022-12-01\", 59.231]\n,[\"2022-09-01\", \"2023-01-01\", 59.305]\n,[\"2022-09-01\", \"2023-02-01\", 58.081]\n,[\"2022-09-01\", \"2023-03-01\", 51.198]\n,[\"2022-09-01\", \"2023-04-01\", 44.532]\n,[\"2022-09-01\", \"2023-05-01\", 38.955]\n,[\"2022-09-01\", \"2023-06-01\", 37.901]\n,[\"2022-09-01\", \"2023-07-01\", 40.461]\n,[\"2022-09-01\", \"2023-08-01\", 40.126]\n,[\"2022-09-01\", \"2023-09-01\", 40.221]\n,[\"2022-09-01\", \"2023-10-01\", 40.455]\n,[\"2022-09-01\", \"2023-11-01\", 41.652]\n,[\"2022-09-01\", \"2023-12-01\", 42.450]\n,[\"2022-09-01\", \"2024-01-01\", 45.057]\n,[\"2022-09-01\", \"2024-02-01\", 42.459]\n,[\"2022-09-01\", \"2024-03-01\", 37.544]\n,[\"2022-09-01\", \"2024-04-01\", 29.901]\n,[\"2022-09-01\", \"2024-05-01\", 25.300]\n,[\"2022-09-01\", \"2024-06-01\", 22.360]\n,[\"2022-09-01\", \"2024-07-01\", 22.544]\n,[\"2022-09-01\", \"2024-08-01\", 23.931]\n]\n\ndf = pd.DataFrame.from_records(data=data, columns=columns)\n\nfor col in [\"asOfDate\", \"maturityDate\"]:\n df[col] = pd.to_datetime(df[col])\n\ndf.sort_values([\"asOfDate\",\"maturityDate\"]).groupby(\"asOfDate\").agg({\"maturityDate\":lambda x: x.shift(-1).values[0]})\n"
},
{
"answer_id": 74317542,
"author": "ARE",
"author_id": 19613669,
"author_profile": "https://Stackoverflow.com/users/19613669",
"pm_score": 0,
"selected": false,
"text": "df_final.groupby(['asOfDate']).apply(lambda grp: grp.nsmallest(2,'maturityDate')).drop(columns='asOfDate').reset_index().groupby(['asOfDate']).last().reset_index()\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19613669/"
] |
74,307,141 | <p>I want to create this peace of UI</p>
<p><a href="https://i.stack.imgur.com/j6bJC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j6bJC.png" alt="enter image description here" /></a></p>
<p>The problem is in the <strong>Red Row</strong> that contains the <em><strong>Title</strong></em> and the <em><strong>Date</strong></em>. I want this <strong>Row</strong> to take the full width of it' parent widget so I can add a space between these two <strong>Text</strong> widgets...and that is what I'v done so far.</p>
<pre><code>Container(
color: Colors.yellow,
margin: const EdgeInsets.symmetric(vertical: 6),
child: Container(
color: Colors.green,
child: Row(
children: [
Container(
decoration: BoxDecoration(
border: Border.all(width: 1, color: AppColors.tertiary),
borderRadius: BorderRadius.circular(240),
),
child: Image.asset(image, width: 48, height: 48),
),
const SizedBox(width: 6),
Container(
color: Colors.blue,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
color: Colors.red,
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
title,
style: Theme.of(context).textTheme.subtitle1?.copyWith(color: Theme.of(context).colorScheme.primary),
),
Text(
date,
style: Theme.of(context).textTheme.bodyText2?.copyWith(color: AppColors.tertiary),
),
],
),
),
const SizedBox(height: 3),
Text(
value.toString(),
style: Theme.of(context).textTheme.bodyText2?.copyWith(color: AppColors.tertiary),
),
],
),
),
],
),
),
);
</code></pre>
<p>I tried to wrap this <strong>Row</strong> with a <strong>Extended</strong> widget and and a <strong>SizedBox.expand()</strong> but it did not work.</p>
| [
{
"answer_id": 74307271,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 2,
"selected": true,
"text": "Container"
},
{
"answer_id": 74307297,
"author": "Fabián Bardecio",
"author_id": 12204458,
"author_profile": "https://Stackoverflow.com/users/12204458",
"pm_score": 0,
"selected": false,
"text": "Row(\n mainAxisSize: MainAxisSize.max,\n children: [\n Container(\n decoration: BoxDecoration(\n border: Border.all(width: 1, color: Colors.black12),\n borderRadius: BorderRadius.circular(240),\n ),\n child: Text('image'),\n ),\n const SizedBox(width: 6),\n Expanded(\n child: Container(\n color: Colors.blue,\n child: Column(\n crossAxisAlignment: CrossAxisAlignment.start,\n children: [\n Container(\n color: Colors.red,\n child: Row(\n mainAxisSize: MainAxisSize.max,\n mainAxisAlignment: MainAxisAlignment.spaceBetween,\n children: [\n Text(\n 'title',\n style: Theme.of(context).textTheme.subtitle1?.copyWith(\n color: Theme.of(context).colorScheme.primary),\n ),\n Text(\n 'date',\n style: Theme.of(context)\n .textTheme\n .bodyText2\n ?.copyWith(color: Colors.black12),\n ),\n ],\n ),\n ),\n const SizedBox(height: 3),\n Text(\n 'value',\n style: Theme.of(context)\n .textTheme\n .bodyText2\n ?.copyWith(color: Colors.black12),\n ),\n ],\n ),\n ),\n ),\n ],\n ),\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18440430/"
] |
74,307,171 | <p>I know that by default, pip uses PyPI to look for packages. I would like to know if there are other domains other than PypI that pip uses.</p>
| [
{
"answer_id": 74307271,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 2,
"selected": true,
"text": "Container"
},
{
"answer_id": 74307297,
"author": "Fabián Bardecio",
"author_id": 12204458,
"author_profile": "https://Stackoverflow.com/users/12204458",
"pm_score": 0,
"selected": false,
"text": "Row(\n mainAxisSize: MainAxisSize.max,\n children: [\n Container(\n decoration: BoxDecoration(\n border: Border.all(width: 1, color: Colors.black12),\n borderRadius: BorderRadius.circular(240),\n ),\n child: Text('image'),\n ),\n const SizedBox(width: 6),\n Expanded(\n child: Container(\n color: Colors.blue,\n child: Column(\n crossAxisAlignment: CrossAxisAlignment.start,\n children: [\n Container(\n color: Colors.red,\n child: Row(\n mainAxisSize: MainAxisSize.max,\n mainAxisAlignment: MainAxisAlignment.spaceBetween,\n children: [\n Text(\n 'title',\n style: Theme.of(context).textTheme.subtitle1?.copyWith(\n color: Theme.of(context).colorScheme.primary),\n ),\n Text(\n 'date',\n style: Theme.of(context)\n .textTheme\n .bodyText2\n ?.copyWith(color: Colors.black12),\n ),\n ],\n ),\n ),\n const SizedBox(height: 3),\n Text(\n 'value',\n style: Theme.of(context)\n .textTheme\n .bodyText2\n ?.copyWith(color: Colors.black12),\n ),\n ],\n ),\n ),\n ),\n ],\n ),\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3468590/"
] |
74,307,186 | <p>I'm new to python seeking your help. I would like to create a string combination of <strong>postive, Negative, floats, Upper case, Lower case elements</strong></p>
<p>Example: Like random combination.</p>
<pre class="lang-none prettyprint-override"><code>As-1jP0.7M -->output
</code></pre>
<p>Explanation</p>
<pre class="lang-none prettyprint-override"><code>A - caps A
s- small S
-1 - Negative 1
j- small j
0.7 - float 0.7
M- caps M
</code></pre>
<p>My ranges</p>
<pre class="lang-none prettyprint-override"><code>Caps - A - Z
small- a -z
positive - 0 to 9
Negatives - -1 to -9
float - 0.1 to 0.9
</code></pre>
<p>I know I'm asking too much but by doing some basic researcg I got idea how to generate combination of <code>Alphanumeric</code> numbers like.</p>
<pre><code>import random, string
x = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(10))
print(x)
</code></pre>
<p>This ok...But, I'm completely clueless how to add <code>Negative</code> & <code>float</code> types along with <code>alphanumerics</code>..Any suggestions how to achieve it. Like we have any some shorcuts like <code>string.floatdigits</code>? or <code>string.negatives</code>? I've searched for similar syntax but, But I 'havent found anything</p>
| [
{
"answer_id": 74307271,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 2,
"selected": true,
"text": "Container"
},
{
"answer_id": 74307297,
"author": "Fabián Bardecio",
"author_id": 12204458,
"author_profile": "https://Stackoverflow.com/users/12204458",
"pm_score": 0,
"selected": false,
"text": "Row(\n mainAxisSize: MainAxisSize.max,\n children: [\n Container(\n decoration: BoxDecoration(\n border: Border.all(width: 1, color: Colors.black12),\n borderRadius: BorderRadius.circular(240),\n ),\n child: Text('image'),\n ),\n const SizedBox(width: 6),\n Expanded(\n child: Container(\n color: Colors.blue,\n child: Column(\n crossAxisAlignment: CrossAxisAlignment.start,\n children: [\n Container(\n color: Colors.red,\n child: Row(\n mainAxisSize: MainAxisSize.max,\n mainAxisAlignment: MainAxisAlignment.spaceBetween,\n children: [\n Text(\n 'title',\n style: Theme.of(context).textTheme.subtitle1?.copyWith(\n color: Theme.of(context).colorScheme.primary),\n ),\n Text(\n 'date',\n style: Theme.of(context)\n .textTheme\n .bodyText2\n ?.copyWith(color: Colors.black12),\n ),\n ],\n ),\n ),\n const SizedBox(height: 3),\n Text(\n 'value',\n style: Theme.of(context)\n .textTheme\n .bodyText2\n ?.copyWith(color: Colors.black12),\n ),\n ],\n ),\n ),\n ),\n ],\n ),\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20410203/"
] |
74,307,217 | <p>Example string:</p>
<pre><code>This is an EXAMPLE SENTENCE, just do give YOU AN Example on Monday, BUT NOT FOR Friday.
</code></pre>
<p>Expected output:</p>
<pre><code>This is an Example Sentence, just do give You An Example on Monday, But Not For Friday.
</code></pre>
<p>I've tried Propper, but this changes every first letter from every word to uppercase.</p>
| [
{
"answer_id": 74307418,
"author": "ztiaa",
"author_id": 17887301,
"author_profile": "https://Stackoverflow.com/users/17887301",
"pm_score": 3,
"selected": true,
"text": "=ARRAYFORMULA(LAMBDA(word,JOIN(\" \",IF(EXACT(UPPER(word),word),PROPER(word),word)))(SPLIT(A1,\" \")))\n"
},
{
"answer_id": 74307462,
"author": "Osm",
"author_id": 19529694,
"author_profile": "https://Stackoverflow.com/users/19529694",
"pm_score": 2,
"selected": false,
"text": "Byrow()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3392296/"
] |
74,307,236 | <p>I was reading about how <a href="https://stackoverflow.com/questions/35321744/python-function-as-class-attribute-becomes-a-bound-method">functions become bound methods when being set as class atrributes</a>. I then observed that this is not the case for functions that are wrapped by <code>functools.partial</code>. What is the explanation for this?</p>
<p>Simple example:</p>
<pre class="lang-py prettyprint-override"><code>from functools import partial
def func1():
print("foo")
func1_partial = partial(func1)
class A:
f = func1
g = func1_partial
a = A()
a.f() # TypeError: func1() takes 0 positional arguments but 1 was given
a.g() # prints "foo"
</code></pre>
<p>I kind of expected them both to behave in the same way.</p>
| [
{
"answer_id": 74307318,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 2,
"selected": false,
"text": "function"
},
{
"answer_id": 74307329,
"author": "Silvio Mayolo",
"author_id": 2288659,
"author_profile": "https://Stackoverflow.com/users/2288659",
"pm_score": 4,
"selected": true,
"text": "__get__"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17647337/"
] |
74,307,312 | <p>I write the code but when i click on the button he don't go up to the header as he have to do</p>
<pre><code>(function() {
'use-strict'
function checkScroll() {
let scrolled = window.pageYOffset;
let coords = document.documentElement.clientHeight;
if (scrolled > coords) {
goTopBtn.classList.add('up_show');
}
if (scrolled < coords) {
goTopBtn.classList.remove('up_show');
}
}
function downToUp() {
if (window.pageXOffset > 0) {
window.scrollBy(0, -80);
setTimeout(downToUp, 0);
}
}
let goTopBtn = document.querySelector(".down_to_up");
window.addEventListener('scroll', checkScroll);
goTopBtn.addEventListener('click', downToUp);
})();
</code></pre>
<p>idk what i have to do</p>
| [
{
"answer_id": 74307318,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 2,
"selected": false,
"text": "function"
},
{
"answer_id": 74307329,
"author": "Silvio Mayolo",
"author_id": 2288659,
"author_profile": "https://Stackoverflow.com/users/2288659",
"pm_score": 4,
"selected": true,
"text": "__get__"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20406911/"
] |
74,307,321 | <p>I'm new to JavaScript and I've been struggling with this problem for a while now. How can I use a variable from a JS file in another HTML file. I have a index.js file where my function is defined. It pulls data from Firebase and I want to use it in another HTML file where it has a script portion.</p>
<p>Index.js file:</p>
<pre><code>async function readProjectNames() {
const q = query(collection(db, "Projects"));
var ProjectNames = [];
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
ProjectNames.push(doc.data().Name);
});
document.getElementById("Projects").innerHTML = ProjectNames;
}
readProjectNames();
</code></pre>
<p>my HTML file:</p>
<pre><code> <!-- Add hours form -->
<form name="AddHoursForm">
<b> Select Project: </b>
<select id="ProjectList">
<option> --Choose Project-- </option>
</select>
<b> Select Engineer: </b>
<select id="EngineerList">
<option> --Choose Engineer-- </option>
</select>
<label for="HoursWorked"><b>Hours Worked: </b></label>
<input id="HoursWorked" type="text">
<button class="AddHourBtn">Add Hours</button><br><br><br><br>
</form>
<script>
//Populate Project List Drop-Down
var ProjectNames = [];
ProjectNames = document.getElementById("Projects");
console.log(ProjectNames);
for (var i = 0; i < ProjectNames.length; i++) {
var Plist = document.createElement("option");
var POpt = ProjectNames[i];
Plist.textContent = POpt;
Plist.value = POpt;
PSelect.appendChild(Plist);
}
</script>
</code></pre>
<p>How do I use ProjectNames array in my HTML file to populate my drop-down list? I can display the text using ID in HTML but I'm not able to use it in my script as a variable to populate my dropdown list. Any help would be appreciated. Thank you</p>
| [
{
"answer_id": 74307318,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 2,
"selected": false,
"text": "function"
},
{
"answer_id": 74307329,
"author": "Silvio Mayolo",
"author_id": 2288659,
"author_profile": "https://Stackoverflow.com/users/2288659",
"pm_score": 4,
"selected": true,
"text": "__get__"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20302542/"
] |
74,307,322 | <p>I have a dataframe that looks like the following:</p>
<pre><code> Examples Type
1 example1 a
2 example1 b
3 example1 c
4 example1 c
5 example2 c
</code></pre>
<p>In a matrix, where rows and columns correspond to each example, I want to calculate the intersection of types between examples.</p>
<pre><code>my_mat <- matrix(0, nrow=length(unique(df$Examples)), ncol=length(unique(df$Examples)))
rownames(my_mat) <- unique(df$Examples)
colnames(my_mat) <- unique(df$Examples)
</code></pre>
<p>The code I currently have is a double for-loop, which is significantly slower at larger scales.</p>
<pre><code>get_intersection <- function(example1, example2) {
return(length(dplyr::intersect(example1, example2)))
}
for (i in 1:nrow(my_mat)) {
curr_row <- rownames(my_mat)[i]
for (j in 1:ncol(my_mat)) {
curr_col <- colnames(my_mat)[j]
my_mat[i, j] <- get_intersection(df$Type[which(df$Examples %in% curr_row)],
df$Type[which(df$Examples %in% curr_col)])
}
}
</code></pre>
<p>How can I use the "apply" methods to accelerate the population of this matrix?</p>
<h2>Data</h2>
<pre><code>df <- structure(list(Examples = c("example1", "example1", "example1",
"example1", "example2"), Type = c("a", "b", "c", "c", "c")), class = "data.frame", row.names = c(NA,
-5L))
</code></pre>
| [
{
"answer_id": 74307682,
"author": "jay.sf",
"author_id": 6574038,
"author_profile": "https://Stackoverflow.com/users/6574038",
"pm_score": 2,
"selected": false,
"text": "outer"
},
{
"answer_id": 74307864,
"author": "br00t",
"author_id": 4028717,
"author_profile": "https://Stackoverflow.com/users/4028717",
"pm_score": 1,
"selected": false,
"text": "df <- data.frame(Examples = c('example1', 'example1', 'example1', 'example1', 'example2'), \n Type = c('a', 'b', 'c', 'c', 'c'), \n stringsAsFactors = FALSE)\nexamples <- unique(df$Examples)\nmy_mat <- matrix(0, nrow = length(examples), ncol = length(examples)) \nrownames(my_mat) <- examples \ncolnames(my_mat) <- examples\nperms <- gtools::permutations(v = examples, \n n = length(examples), \n r = 2, \n repeats.allowed = TRUE)\napply(perms, 1, function(x) {\n result <- intersect(df[ df$Examples == x[ 1 ], 'Type' ], \n df[ df$Examples == x[ 2 ], 'Type' ]) |>\n length()\n my_mat[ x[ 1 ], x[ 2 ] ] <<- result\n}) |> invisible()\nprint(df)\nprint(my_mat)\n"
},
{
"answer_id": 74308010,
"author": "Gregor Thomas",
"author_id": 903061,
"author_profile": "https://Stackoverflow.com/users/903061",
"pm_score": 2,
"selected": false,
"text": "library(dplyr) \nlibrary(tidyr)\ndfw = df %>%\n unique %>% \n mutate(n = 1) %>%\n pivot_wider(names_from = Type, values_from = n, values_fill = 0) %>%\n as.data.frame\n\nrow.names(dfw) = dfw$Examples\ndfm = as.matrix(dfw[-1])\nresult = dfm %*% t(dfm)\nresult\n# example1 example2\n# example1 3 1\n# example2 1 1\n"
},
{
"answer_id": 74308245,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 1,
"selected": false,
"text": "tcrossprod"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2657817/"
] |
74,307,336 | <p>I'm trying to scrape a list of products of products on the following page: <a href="https://www.beermerchants.com/browse/brewery/cantillon" rel="nofollow noreferrer">https://www.beermerchants.com/browse/brewery/cantillon</a> , however I only want to print products that are in stock. I've been able to scrape the full list of products with the following code, however how can I modify this so that this is only true for products that are in stock?</p>
<pre><code>import ssl
import requests
import sys
import time
import smtplib
from email.message import EmailMessage
import hashlib
from urllib.request import urlopen
from datetime import datetime
import json
import random
import requests
from itertools import cycle
import pandas as pd
from bs4 import BeautifulSoup
from selenium import webdriver
from urllib3.exceptions import InsecureRequestWarning
from requests_html import HTMLSession
session = HTMLSession()
# Suppress only the single warning from urllib3 needed.
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
user_agent_list = [
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.1 Safari/605.1.15',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:77.0) Gecko/20100101 Firefox/77.0',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36',
]
for i in range(1,4):
#Pick a random user agent
user_agent = random.choice(user_agent_list)
#Set the headers
headers = {'User-Agent': user_agent}
url = 'https://www.beermerchants.com/browse/brewery/cantillon'
response = requests.get(url,headers=headers)
soup = BeautifulSoup(response.text,features="html.parser")
link = []
for product in soup.find_all('a', href=True, class_="product-item-link"):
link.append(product['href'])
print(link)
</code></pre>
<p>Thanks in advance!!!</p>
| [
{
"answer_id": 74307682,
"author": "jay.sf",
"author_id": 6574038,
"author_profile": "https://Stackoverflow.com/users/6574038",
"pm_score": 2,
"selected": false,
"text": "outer"
},
{
"answer_id": 74307864,
"author": "br00t",
"author_id": 4028717,
"author_profile": "https://Stackoverflow.com/users/4028717",
"pm_score": 1,
"selected": false,
"text": "df <- data.frame(Examples = c('example1', 'example1', 'example1', 'example1', 'example2'), \n Type = c('a', 'b', 'c', 'c', 'c'), \n stringsAsFactors = FALSE)\nexamples <- unique(df$Examples)\nmy_mat <- matrix(0, nrow = length(examples), ncol = length(examples)) \nrownames(my_mat) <- examples \ncolnames(my_mat) <- examples\nperms <- gtools::permutations(v = examples, \n n = length(examples), \n r = 2, \n repeats.allowed = TRUE)\napply(perms, 1, function(x) {\n result <- intersect(df[ df$Examples == x[ 1 ], 'Type' ], \n df[ df$Examples == x[ 2 ], 'Type' ]) |>\n length()\n my_mat[ x[ 1 ], x[ 2 ] ] <<- result\n}) |> invisible()\nprint(df)\nprint(my_mat)\n"
},
{
"answer_id": 74308010,
"author": "Gregor Thomas",
"author_id": 903061,
"author_profile": "https://Stackoverflow.com/users/903061",
"pm_score": 2,
"selected": false,
"text": "library(dplyr) \nlibrary(tidyr)\ndfw = df %>%\n unique %>% \n mutate(n = 1) %>%\n pivot_wider(names_from = Type, values_from = n, values_fill = 0) %>%\n as.data.frame\n\nrow.names(dfw) = dfw$Examples\ndfm = as.matrix(dfw[-1])\nresult = dfm %*% t(dfm)\nresult\n# example1 example2\n# example1 3 1\n# example2 1 1\n"
},
{
"answer_id": 74308245,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 1,
"selected": false,
"text": "tcrossprod"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16344097/"
] |
74,307,384 | <p>I am trying to collapse a dataset based on conditions and groupings from another dataset.
My current dataframe looks like this</p>
<p>For every 'RollNo' in every 'congress' I want a new variable indicating if the two senators in the same state voted together (1,0) and are in the same party (1,0)</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>congress</th>
<th>sen</th>
<th>RollNo</th>
<th>state</th>
<th>Vote</th>
<th>Party</th>
</tr>
</thead>
<tbody>
<tr>
<td>106</td>
<td>Jay</td>
<td>1</td>
<td>Ark</td>
<td>1</td>
<td>Rep</td>
</tr>
<tr>
<td>106</td>
<td>Mary</td>
<td>1</td>
<td>Ark</td>
<td>1</td>
<td>Dem</td>
</tr>
<tr>
<td>106</td>
<td>Bill</td>
<td>2</td>
<td>Ten</td>
<td>2</td>
<td>Dem</td>
</tr>
<tr>
<td>106</td>
<td>Kevin</td>
<td>2</td>
<td>Ten</td>
<td>1</td>
<td>Dem</td>
</tr>
<tr>
<td>108</td>
<td>Sue</td>
<td>1</td>
<td>Ore</td>
<td>2</td>
<td>Rep</td>
</tr>
<tr>
<td>108</td>
<td>Sally</td>
<td>1</td>
<td>Ore</td>
<td>2</td>
<td>Rep</td>
</tr>
<tr>
<td>108</td>
<td>Lisa</td>
<td>3</td>
<td>SDak</td>
<td>1</td>
<td>Rep</td>
</tr>
<tr>
<td>108</td>
<td>Penny</td>
<td>3</td>
<td>SDak</td>
<td>2</td>
<td>Rep</td>
</tr>
<tr>
<td>109</td>
<td>Jay</td>
<td>1</td>
<td>Mich</td>
<td>1</td>
<td>Dem</td>
</tr>
<tr>
<td>109</td>
<td>Mary</td>
<td>1</td>
<td>Mich</td>
<td>9</td>
<td>Rep</td>
</tr>
<tr>
<td>109</td>
<td>Rudy</td>
<td>5</td>
<td>Cal</td>
<td>1</td>
<td>Dem</td>
</tr>
<tr>
<td>109</td>
<td>Niles</td>
<td>5</td>
<td>Cal</td>
<td>1</td>
<td>Dem</td>
</tr>
</tbody>
</table>
</div>
<p>The new dataframe should look like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>congress</th>
<th>RollNo</th>
<th>state</th>
<th>Pair_Vote</th>
<th>Pair_Party</th>
</tr>
</thead>
<tbody>
<tr>
<td>106</td>
<td>1</td>
<td>Ark</td>
<td>1</td>
<td>0</td>
</tr>
<tr>
<td>106</td>
<td>2</td>
<td>Ten</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td>108</td>
<td>1</td>
<td>Ore</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>108</td>
<td>3</td>
<td>SDak</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td>109</td>
<td>1</td>
<td>Mich</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>109</td>
<td>5</td>
<td>Cal</td>
<td>1</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
<p>I have tried the code below, tweaked it several times. My my dataset returns with the same observation and two new columns empty vectors for my new variables.</p>
<pre><code>library(dplyr)
dataframe['Pair_Vote'] <- NA
dataframe['Pair_Party'] <- NA
newdata <- dataframe %>% group_by(congress, RollNo, state) %>%
mutate(Pair_Vote - case_when(any(Vote == Vote) ~ 1, FALSE ~ 0))
</code></pre>
<p>I'm at a loss.</p>
<pre><code></code></pre>
| [
{
"answer_id": 74307442,
"author": "Gregor Thomas",
"author_id": 903061,
"author_profile": "https://Stackoverflow.com/users/903061",
"pm_score": 4,
"selected": true,
"text": "mutate"
},
{
"answer_id": 74307517,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "across"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2268517/"
] |
74,307,396 | <p>I would like to write a pipeline to migrate some data from datastore and export it into a csv.
For that reason I was thinking about doing:</p>
<ul>
<li>read from datastore</li>
<li>convert entities into a python dictionary (not sure about the correctness)</li>
<li>write to big query</li>
<li>export from big query into csv</li>
</ul>
<p>I wrote this code but I'm not sure if my idea is correct and also I'm not sure what I exactly need to write in the last step. Instead there's any direct way to get a csv from Datastore?</p>
<pre><code>from google.cloud import datastore
from google.cloud.datastore import query as datastore_query
from apache_beam.io.gcp.datastore.v1.datastoreio import ReadFromDatastore
import apache_beam as beam
from apache_beam.io.BigQueryDisposition import CREATE_IF_NEEDED
from apache_beam.io.BigQueryDisposition import WRITE_TRUNCATE
def proto_to_dict(proto_obj):
key_list = proto_obj.DESCRIPTOR.fields_by_name.keys()
d = {}
for key in key_list:
d[key] = getattr(proto_obj, key)
return d
p = beam.Pipeline(options=pipeline_options)
ds_client = datastore.Client(project=project)
query = ds_client.query(kind=kind)
query = datastore_query._pb_from_query(query)
input = p | 'ReadFromDatastore' >> ReadFromDatastore(project=project, query=query)
pipeline = (
input
| 'convert to dict' >> beam.Pardo(proto_to_dict())
| 'write to big query' >> beam.io.WriteToBigQuery(
table_spec,
schema=table_schema,
write_disposition=beam.io.BigQueryDisposition.WRITE_TRUNCATE, create_disposition=beam.io.BigQueryDisposition.CREATE_IF_NEEDED)
| 'export big query as csv' >> #i need to add the correct code
)
output = pipeline |beam.Map(print)
</code></pre>
| [
{
"answer_id": 74307442,
"author": "Gregor Thomas",
"author_id": 903061,
"author_profile": "https://Stackoverflow.com/users/903061",
"pm_score": 4,
"selected": true,
"text": "mutate"
},
{
"answer_id": 74307517,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "across"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18222906/"
] |
74,307,402 | <p>When an app goes into the background, iOS automatically takes screenshots to use in the app carousel.
I'm trying to find where automatic screenshots are stored.</p>
<p>I found several possible options, but nothing.</p>
<blockquote>
<p>/Library/Caches/Snapshots/$(BUNDLE_IDENTIFIER)/
/var/mobile/Containers/Data/Application/$APP_ID/Library/Caches/Snapshots/</p>
</blockquote>
| [
{
"answer_id": 74307691,
"author": "Vova Kotsiubenko",
"author_id": 9664739,
"author_profile": "https://Stackoverflow.com/users/9664739",
"pm_score": 2,
"selected": false,
"text": "/Library/Developer/CoreSimulator/Devices/{DEVICE_ID}/data/Containers/Data/Application/{APP_ID}/Library/SplashBoard/Snapshots/sceneID:{BUNDLE_ID}-default\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9664739/"
] |
74,307,403 | <p>I have stored the image path into the column NewImage(varchar) and when I want to display that image from my Images folder its showing a white box with red cross on the picture box.</p>
<p><a href="https://i.stack.imgur.com/X18Ah.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/X18Ah.png" alt="Storing image path into NewImage column" /></a></p>
<p><a href="https://i.stack.imgur.com/FwzVe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FwzVe.png" alt="Storing images in Images directory" /></a></p>
<p>This is the code where i try to retrieve the image from my Images directory and its not working</p>
<pre><code>private void Quiz_Load(object sender, EventArgs e)
{
if (pictureBox1.Image != null)
{
pictureBox1.Image.Dispose();
pictureBox1.Image = null;
}
string constr = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT NewImage FROM tblQuestion WHERE QuestionId =1", conn))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
conn.Open();
sda.Fill(dt);
pictureBox1.ImageLocation = (@"\Images");
pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;
conn.Close();
}
}
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/Tyscs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Tyscs.png" alt="Output:" /></a></p>
| [
{
"answer_id": 74307691,
"author": "Vova Kotsiubenko",
"author_id": 9664739,
"author_profile": "https://Stackoverflow.com/users/9664739",
"pm_score": 2,
"selected": false,
"text": "/Library/Developer/CoreSimulator/Devices/{DEVICE_ID}/data/Containers/Data/Application/{APP_ID}/Library/SplashBoard/Snapshots/sceneID:{BUNDLE_ID}-default\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13250509/"
] |
74,307,407 | <p>I'm using the mutate method to find strings in a column (<code>Name</code> in the example)and replace them with a corrected string in R, which works well both on partial and full strings.</p>
<p>Method:</p>
<pre><code>df <- data.frame(Name = c("Jim","Bob","Sue","Sally","Jimmm","Boob","Suezi","Sallyyyy","Jim","Bob","Sue","Sally"),
Period = c("P1","P1","P1","P1","P2","P2","P2","P2","P3","P3","P3","P3"),
Value = c(150, 200, 325, 120, 760,245,46,244,200, 325, 120, 760))
df <- df %>%
mutate(Name = case_when(
str_detect(Name, "Jim") ~ "Jim",
str_detect(Name, "Sue") ~ "Sue",
TRUE ~ Name)) %>%
mutate(across(Name, str_replace, "Sallyyyy", "Sally"))
</code></pre>
<p>In my real application I realized I should probably maintain the original column for reference and and create a new column with the corrections.</p>
<p>I tried simply adding a new column the standard way in r, as below:</p>
<pre><code>df$test <- df %>%
mutate(Name = case_when(
str_detect(Name, "Jim") ~ "Jim",
TRUE ~ Name)) %>%
mutate(across(Name, str_replace, "Sallyyyy", "Sally"))
</code></pre>
<p>but instead of just creating a new column called <code>test</code>, in this case it creates a copy of the entire dataframe.</p>
<p>Is there a method within the mutate function that will allow me to create a new column with the correction as opposed to replacing it in the original column?</p>
| [
{
"answer_id": 74307691,
"author": "Vova Kotsiubenko",
"author_id": 9664739,
"author_profile": "https://Stackoverflow.com/users/9664739",
"pm_score": 2,
"selected": false,
"text": "/Library/Developer/CoreSimulator/Devices/{DEVICE_ID}/data/Containers/Data/Application/{APP_ID}/Library/SplashBoard/Snapshots/sceneID:{BUNDLE_ID}-default\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11370582/"
] |
74,307,524 | <p>I noticed that when I use the <code>fake.word()</code> function with locale set to <code>'pl_PL'</code> it sometimes generates a swear word which is not ideal for me. Is there an easy way to force Faker to stop outputting swear words, preferably without having to list all of the swear words myself?</p>
| [
{
"answer_id": 74307691,
"author": "Vova Kotsiubenko",
"author_id": 9664739,
"author_profile": "https://Stackoverflow.com/users/9664739",
"pm_score": 2,
"selected": false,
"text": "/Library/Developer/CoreSimulator/Devices/{DEVICE_ID}/data/Containers/Data/Application/{APP_ID}/Library/SplashBoard/Snapshots/sceneID:{BUNDLE_ID}-default\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14677742/"
] |
74,307,540 | <p>Thanks lot for all support...</p>
<p>I need to write one formula and Drag down to get the sum of the power 2.</p>
<p>=POWER(B2,2)+POWER(B3,2)+POWER(B4,2)+POWER(B5,2)</p>
<p><a href="https://i.stack.imgur.com/w8M4a.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/w8M4a.png" alt="Sum of Power" /></a></p>
<p>I need to get the Sum of Power 2, For that need to write formula in cell C2 and Need to Drag till C5 .</p>
<p>Because I have more than 100 cell to drag this same Formula</p>
<p>Because if I type Manually it very critical to add one by one.</p>
<p><a href="https://docs.google.com/spreadsheets/d/1HpWP5fRC42JA1LvrCxnqsa7sIN64KfjlTkk-UjXvhhM/edit?usp=sharing" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/1HpWP5fRC42JA1LvrCxnqsa7sIN64KfjlTkk-UjXvhhM/edit?usp=sharing</a></p>
<p>Best regard
Indika</p>
| [
{
"answer_id": 74307619,
"author": "Mario Greco",
"author_id": 14184946,
"author_profile": "https://Stackoverflow.com/users/14184946",
"pm_score": 0,
"selected": false,
"text": "for the first cell(E2) = POWER(B2,2)\nfor the second cell(E3) = POWER(B3,2)+E2\ncell E4 = POWER(B4,2)+E3\n"
},
{
"answer_id": 74307633,
"author": "Scott Craner",
"author_id": 4851590,
"author_profile": "https://Stackoverflow.com/users/4851590",
"pm_score": 2,
"selected": true,
"text": "=SUMPRODUCT(B$2:B2^2)\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18131328/"
] |
74,307,555 | <p>I'm cleaning my product database and I need to substrate text between a "#" and the space after this character to show an example:</p>
<p>ALMINE #6186 3 WAY EM/BRD --> I need to move the # 6186 at the end of the string.</p>
<p>JOY #197 BD LG GLOW RED --> Here I need to do the same.</p>
<p>Then I need to create a formula to subtract that one an put it at the end I was thinking into look for the space after the # but i can't.</p>
<p>Ill appreciate if you could help me with this.</p>
<p>Ty,</p>
<p>I subtract the character from #-1 to start then in that way I will have the title but ill need to create another formula to extract from the # to the space after the # space because the ID's length change.</p>
| [
{
"answer_id": 74307619,
"author": "Mario Greco",
"author_id": 14184946,
"author_profile": "https://Stackoverflow.com/users/14184946",
"pm_score": 0,
"selected": false,
"text": "for the first cell(E2) = POWER(B2,2)\nfor the second cell(E3) = POWER(B3,2)+E2\ncell E4 = POWER(B4,2)+E3\n"
},
{
"answer_id": 74307633,
"author": "Scott Craner",
"author_id": 4851590,
"author_profile": "https://Stackoverflow.com/users/4851590",
"pm_score": 2,
"selected": true,
"text": "=SUMPRODUCT(B$2:B2^2)\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20410575/"
] |
74,307,591 | <p>What needs to be done in this task:</p>
<p>Determine the amount of couples of neighbouring elements in which both of the numbers are multiple of 7 and also determine a minimal sum of the elements of such couples.</p>
<p>In the actual task I need to read a file, but here I put elements in the list by myself.</p>
<pre><code>a = [7, 14, 2, 6, 5, 7, 7]
counter = 0
minSum = 1000000000000000000000 # This is what this question is all about
for i in range(len(a)):
if a[i] % 7 == 0 and a[i + 1] % 7 == 0:
counter += 1
if (a[i] + a[i + 1]) < minSum:
minSum = a[i] + a[i + 1]
print(counter, minSum)
</code></pre>
<p>So my question is basically this: <strong>is there a more elegant way of searching a minimal sum of elements, I mean without setting a giant number to the variable?</strong></p>
| [
{
"answer_id": 74307638,
"author": "juanpa.arrivillaga",
"author_id": 5014455,
"author_profile": "https://Stackoverflow.com/users/5014455",
"pm_score": 3,
"selected": true,
"text": "float('inf')"
},
{
"answer_id": 74307701,
"author": "kaya3",
"author_id": 12299000,
"author_profile": "https://Stackoverflow.com/users/12299000",
"pm_score": 0,
"selected": false,
"text": "min"
},
{
"answer_id": 74307709,
"author": "Woodford",
"author_id": 8451814,
"author_profile": "https://Stackoverflow.com/users/8451814",
"pm_score": 0,
"selected": false,
"text": "itertools.pairwise"
},
{
"answer_id": 74308782,
"author": "wjandrea",
"author_id": 4518341,
"author_profile": "https://Stackoverflow.com/users/4518341",
"pm_score": 0,
"selected": false,
"text": "None"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19712456/"
] |
74,307,594 | <p>I need to provide a report of accounts that are disabled, but still have security groups in their account so I can purge them. Can you help me with this? In my file, it doesnt show groups Name. I only get Microsoft.ActiveDirectory.Management.ADPropertyValueCollection</p>
<pre><code>$path = "c:\temp\DisabledUsers_ContainGroups ($(Get-Date -Format "yyyy-MM-dd")).xlsx"
$date = Get-Date -Format yyyy-MM-dd
Get-ADUser -Filter ({enabled -eq $false -and memberof -like '*'}) -properties Name, Samaccountname, memberof | select Name, Samaccountname, memberof | Export-excel -Path $path -WorksheetName $date -AutoSize -AutoFilter -TableStyle Medium2
</code></pre>
| [
{
"answer_id": 74307638,
"author": "juanpa.arrivillaga",
"author_id": 5014455,
"author_profile": "https://Stackoverflow.com/users/5014455",
"pm_score": 3,
"selected": true,
"text": "float('inf')"
},
{
"answer_id": 74307701,
"author": "kaya3",
"author_id": 12299000,
"author_profile": "https://Stackoverflow.com/users/12299000",
"pm_score": 0,
"selected": false,
"text": "min"
},
{
"answer_id": 74307709,
"author": "Woodford",
"author_id": 8451814,
"author_profile": "https://Stackoverflow.com/users/8451814",
"pm_score": 0,
"selected": false,
"text": "itertools.pairwise"
},
{
"answer_id": 74308782,
"author": "wjandrea",
"author_id": 4518341,
"author_profile": "https://Stackoverflow.com/users/4518341",
"pm_score": 0,
"selected": false,
"text": "None"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17163818/"
] |
74,307,595 | <p>I am creating a template for a custom post type called "Projects" and trying to display a list of all categories assigned to a single post.</p>
<pre><code><div class="blog-information left full-width">
<div class="wrapper">
<div class="project-content">
<div class="eck-projects-single-start">
<a href="/project" style="text-align: left;" class="eck-projects-back-link">< Back to Projects</a>
<h2 class="project-title"><?php echo get_the_title(); ?></h2>
<p class="eck-projects-single-subtitle"><?php echo $fields['subtitle']; ?></p>
<div class="eck-projects-single-categories">
<?php echo get_the_category_list( ' \ ' ); ?>
</div>
</div>
<div class="eck-projects-single-content">
<?php echo get_the_content(); ?>
</div>
</div>
</div>
</code></pre>
<p>What shows up on the single post is just an empty div; no categories are coming in from the get_the_category_list function.</p>
<p>I tried changing this line:
<code><?php echo get_the_category_list( ' \ ' ); ?></code>
to this:</p>
<pre><code> $args = array(
'taxonomy' => 'ecprojects',
'orderby' => 'name',
'order' => 'ASC'
);
$cats = get_categories($args);
foreach($cats as $cat) {
?>
<a href="<?php echo get_category_link( $cat->term_id ) ?>">
<?php echo $cat->name; ?>
</a>
<?php
}
?>
</code></pre>
<p>(ecprojects being the name of the custom post type), but got the same result.</p>
| [
{
"answer_id": 74307638,
"author": "juanpa.arrivillaga",
"author_id": 5014455,
"author_profile": "https://Stackoverflow.com/users/5014455",
"pm_score": 3,
"selected": true,
"text": "float('inf')"
},
{
"answer_id": 74307701,
"author": "kaya3",
"author_id": 12299000,
"author_profile": "https://Stackoverflow.com/users/12299000",
"pm_score": 0,
"selected": false,
"text": "min"
},
{
"answer_id": 74307709,
"author": "Woodford",
"author_id": 8451814,
"author_profile": "https://Stackoverflow.com/users/8451814",
"pm_score": 0,
"selected": false,
"text": "itertools.pairwise"
},
{
"answer_id": 74308782,
"author": "wjandrea",
"author_id": 4518341,
"author_profile": "https://Stackoverflow.com/users/4518341",
"pm_score": 0,
"selected": false,
"text": "None"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17163918/"
] |
74,307,610 | <p>Plus one- leetcode problem</p>
<p>Problem:</p>
<blockquote>
<p>You are given a large integer represented as an integer array digits,
where each digits[i] is the ith digit of the integer. The digits are
ordered from most significant to least significant in left-to-right
order. The large integer does not contain any leading 0's.</p>
</blockquote>
<p>Increment the large integer by one and return the resulting array of digits.</p>
<p>Example 1:</p>
<pre><code>Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].
</code></pre>
<p>Example 2:</p>
<pre><code>Input: digits = [9]
Output: [1,0]
Explanation: The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].
</code></pre>
<p>Constraints:</p>
<ul>
<li>1 <= digits.length <= 100</li>
<li>0 <= digits[i] <= 9</li>
<li>digits does not contain any leading 0's.</li>
</ul>
<p>My solution:</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>// [9] becomes [1,0]
var plusOne = function(digits) {
let len = digits.length;
//count array backwards
for(let i = len-1; i >= 0; i--) {
// if the currently indexed value is 9, we will zero it (line 14)
// we will also check if the previous entry is 9 via recursion (line 19)
// if it is not 9, we increment it by 1 and return 'digits' (lines 22, 23)
// if there is no previous entry we prepend one and return 'digits' (lines 16, 17)
if(digits[i] == 9) {
digits[i] = 0;
if(!digits[i - 1]){
digits.unshift(1);
return digits;
} else {
plusOne(digits.slice(0, i-1));
}
} else {
digits[i] = digits[i] + 1;
return digits;
}
}
};
let array = [9,9,9];
console.log(plusOne(array));
// This code breaks on input:
// [9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9]</code></pre>
</div>
</div>
</p>
<p>The difficulty with this problem is with 9's, which naturally increment the place value of its more significant neighbor.</p>
<p>I address this problem with recursion. (As you can read in the code comments).</p>
<p>The problem is that I am getting a 'Time limit exceeded' error on Leetcode on the following input:</p>
<p><code>[9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9]</code>.</p>
<p>Though it appears to pass all other test cases.</p>
<p>Is this a stack size issue? Is there a way to optimize the space complexity of the above code?</p>
<p>Thank you very much.</p>
<p>I have no idea how to reduce the time/space complexity of the problem as I am new to recursion.</p>
| [
{
"answer_id": 74307638,
"author": "juanpa.arrivillaga",
"author_id": 5014455,
"author_profile": "https://Stackoverflow.com/users/5014455",
"pm_score": 3,
"selected": true,
"text": "float('inf')"
},
{
"answer_id": 74307701,
"author": "kaya3",
"author_id": 12299000,
"author_profile": "https://Stackoverflow.com/users/12299000",
"pm_score": 0,
"selected": false,
"text": "min"
},
{
"answer_id": 74307709,
"author": "Woodford",
"author_id": 8451814,
"author_profile": "https://Stackoverflow.com/users/8451814",
"pm_score": 0,
"selected": false,
"text": "itertools.pairwise"
},
{
"answer_id": 74308782,
"author": "wjandrea",
"author_id": 4518341,
"author_profile": "https://Stackoverflow.com/users/4518341",
"pm_score": 0,
"selected": false,
"text": "None"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19590865/"
] |
74,307,623 | <p>My data are as follows:</p>
<pre><code>group observation
A red
A blue
A green
B red
B red
B green
C blue
C red
C green
</code></pre>
<p>I would like to subset groups that have at least one of each observation. My desired output is as follows:</p>
<pre><code>group observation
A red
A blue
A green
C blue
C red
C green
</code></pre>
| [
{
"answer_id": 74307639,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 4,
"selected": true,
"text": "all"
},
{
"answer_id": 74308256,
"author": "M--",
"author_id": 6461462,
"author_profile": "https://Stackoverflow.com/users/6461462",
"pm_score": 2,
"selected": false,
"text": "df1[with(df1, ave(observation, group, \n FUN = function(x) length(unique(x))) >= length(unique(observation))),]\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17083131/"
] |
74,307,655 | <p>My question is how can I send the input value to the parent component by clicking on the button? Because now if I type something in the input it shanges the value instantly, I want it to do after I click on the button.</p>
<p>Currently I am using that method:</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 FormInput = ({setIpAddress}) => {
return (
<div className="formInput">
<form className="form_container" onSubmit={e => {e.preventDefault();}}>
<input type="text" id="input" onChange={(e) => setIpAddress(e.target.value)} required={true} placeholder="Search for any IP address or domain"/>
<button type="submit" className="input_btn">
<img src={arrow} alt="arrow"/>
</button>
</form>
</div>
);
};
export default FormInput</code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74307700,
"author": "Sean",
"author_id": 11726149,
"author_profile": "https://Stackoverflow.com/users/11726149",
"pm_score": 3,
"selected": true,
"text": "onClick"
},
{
"answer_id": 74307863,
"author": "Surge",
"author_id": 19358225,
"author_profile": "https://Stackoverflow.com/users/19358225",
"pm_score": 0,
"selected": false,
"text": "function App() {\n const [ipAddress, setIpAddress] = useState(\"\");\n\n const url = `${BASE_URL}apiKey=${process.env.REACT_APP_API_KEY}&ipAddress=${ipAddress}`;\n\n useEffect(() => {\n const getData = async () => {\n axios.get(url).then((respone) => {\n setIpAddress(respone.data.ip)\n ... \n \n getData();\n }, [url]);\n\n return (\n <div className=\"App\">\n <SearchSection setIpAddress={setIpAddress} />\n </div>\n );\n}"
},
{
"answer_id": 74307969,
"author": "Surge",
"author_id": 19358225,
"author_profile": "https://Stackoverflow.com/users/19358225",
"pm_score": 0,
"selected": false,
"text": "const SearchSection = ({setIpAddress}) => {\n return (\n <div className=\"search_container\">\n <h1 className=\"search_heading\">IP Address Tracker</h1> \n \n <FormInput setIpAddress={setIpAddress}/>\n </div>\n );\n};"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19358225/"
] |
74,307,687 | <p>I am trying to run a command from the command line which I derived from a variable and it is not working. If I copy the output of the variable and run it from the command line it works, just not from within Powershell script</p>
<pre><code>$psexec = "c:\sysinternalsSuite\psexec.exe"
$computer = "localhost"
$port = 5482
$urlacl_cmd = "$psexec \\$computer netsh http add urlacl url=http://+:$port/ user=everyone"
# tried both of the lines below; neither worked
invoke-command -scriptblock{$urlacl_cmd}
& $urlacl_cmd
</code></pre>
<p>output from the above results in this:</p>
<p>`</p>
<pre><code>c:\sysinternalsSuite\psexec.exe \\localhost netsh http add urlacl url=http://+:5484/ user=everyone
& : The term 'c:\sysinternalsSuite\psexec.exe \\localhost netsh http add urlacl url=http://+:5484/ user=everyone' is not recognized as the name of a cmdlet, function, script
file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Temp\add-websocket.ps1:11 char:3
+ & $urlacl_cmd
+ ~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (c:\sysinternals.../ user=everyone:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
</code></pre>
<p>`</p>
<p>If I just copy the output and past it in the Powershell prompt it works
<code>c:\sysinternalsSuite\psexec.exe \\localhost netsh http add urlacl url=http://+:5484/ user=everyone</code></p>
| [
{
"answer_id": 74329558,
"author": "js2010",
"author_id": 6654942,
"author_profile": "https://Stackoverflow.com/users/6654942",
"pm_score": 1,
"selected": true,
"text": "set-content -path file -value hi\n$cmd = 'findstr'\n$myargs = '/n','hi','file' # line number\n& $cmd $myargs\n\n1:hi\n"
},
{
"answer_id": 74406991,
"author": "user16242546",
"author_id": 16242546,
"author_profile": "https://Stackoverflow.com/users/16242546",
"pm_score": 1,
"selected": false,
"text": "param (\n[String]$computer = $env:COMPUTERNAME,\n[Parameter(mandatory=$true,Position=0)][int]$port,\n$user = \"everyone\"\n)\n\n$psexec = \"c:\\sysinternalsSuite\\psexec.exe\"\n$urlacl_cmd = \"netsh http add urlacl url=http://+:$port/ user=$user\"\n\n& $psexec \\\\$computer netsh http add urlacl url=http://+:$port/ user=$user\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16242546/"
] |
74,307,697 | <p>I have the multiple rows of strings that look like the following:</p>
<pre><code>irm-eap-edp-refined-nonprod
irm-eap-edp-reporting-prod
irm-eap-edp-development-nonprod
</code></pre>
<p>I need to extract the nonprod or prod string from each, it will always be after the 4th hyphen and the last substring of the entire string.</p>
<p>What's a simple regex for this situation?</p>
| [
{
"answer_id": 74307846,
"author": "Ted Lyngmo",
"author_id": 7582247,
"author_profile": "https://Stackoverflow.com/users/7582247",
"pm_score": 0,
"selected": false,
"text": "[^-]+-"
},
{
"answer_id": 74307850,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 1,
"selected": false,
"text": "-"
},
{
"answer_id": 74307910,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 0,
"selected": false,
"text": "prod"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17928364/"
] |
74,307,724 | <p>I am trying to ask the player to write a sentence. If the sentence has no spaces, it will return as so. Otherwise, i want all the spaces to be replaced with underscores.</p>
<pre><code>sentence = input("Enter de sentence: ")
def replace():
if sentence.count(" ")>0:
sentence[1 : sentence.index(" ")] +"_"+ sentence[sentence.index(" ")+1 : len(sentence)]
else:
return replace()
print(replace)
print(replace)
</code></pre>
<p>no matter what i enter after "Enter de sentence:" is asked, i get this returned:</p>
<p><function replace at 0x7fecbc2b2280></p>
<p>I have tried looking up some of the refences for some of the code and tried to change some of the variables, but to no avail.</p>
| [
{
"answer_id": 74307766,
"author": "azro",
"author_id": 7212686,
"author_profile": "https://Stackoverflow.com/users/7212686",
"pm_score": 1,
"selected": false,
"text": "def replace(content):\n if content.count(\" \") > 0:\n content = content.replace(\" \", \"_\")\n return content\n\nsentence = input(\"Enter de sentence: \")\nprint(replace(sentence))\n"
},
{
"answer_id": 74308440,
"author": "lroth",
"author_id": 11032782,
"author_profile": "https://Stackoverflow.com/users/11032782",
"pm_score": 0,
"selected": false,
"text": ".split()"
},
{
"answer_id": 74308666,
"author": "Arifa Chan",
"author_id": 19574157,
"author_profile": "https://Stackoverflow.com/users/19574157",
"pm_score": 0,
"selected": false,
"text": "replace()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20410728/"
] |
74,307,739 | <p>I have two Models, (<code>Doctor</code> & <code>Patient</code>), the <code>Doctor</code> model is the <em>parent</em> model, How can I make the <code>Service_doctor</code> field an instance of the <code>Doctor</code>'s model so that I can get the <code>Doctor</code>'s name into the <code>Patient</code>'s model using <strong>for loop</strong> in the HTML Template. This is what am trying to mean;</p>
<p><strong>models.py</strong></p>
<pre class="lang-py prettyprint-override"><code>class Doctor(models.Model):
Doctor_Name = models.CharField(max_length=200)
def __str__(self):
return self.Doctor_Name
class Patient(models.Model):
Name = models.CharField(max_length=200)
Telephone = models.CharField(max_length=100, unique=True)
Service_doctor = models.ForeignKey(Doctor, on_delete=CASCADE)
def __str__(self):
return self.Doctor_Name
</code></pre>
<p><strong>views.py</strong></p>
<pre><code>def Newpatient(request):
if request.method == 'POST':
Name = request.POST.get('Name')
Telephone = request.POST.get('Telephone')
Service_doctor = request.POST.get('Service_doctor')
formdata = Patient(Name=Name, Telephone=Telephone, Service_doctor=Service_doctor)
formdata.save()
return render(request, 'Adm.html')
</code></pre>
<p>Any help is appreciated.</p>
| [
{
"answer_id": 74307766,
"author": "azro",
"author_id": 7212686,
"author_profile": "https://Stackoverflow.com/users/7212686",
"pm_score": 1,
"selected": false,
"text": "def replace(content):\n if content.count(\" \") > 0:\n content = content.replace(\" \", \"_\")\n return content\n\nsentence = input(\"Enter de sentence: \")\nprint(replace(sentence))\n"
},
{
"answer_id": 74308440,
"author": "lroth",
"author_id": 11032782,
"author_profile": "https://Stackoverflow.com/users/11032782",
"pm_score": 0,
"selected": false,
"text": ".split()"
},
{
"answer_id": 74308666,
"author": "Arifa Chan",
"author_id": 19574157,
"author_profile": "https://Stackoverflow.com/users/19574157",
"pm_score": 0,
"selected": false,
"text": "replace()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18211511/"
] |
74,307,747 | <p>I have a nested dictionary containing both the title and the number of pages of a book. I want to write a function that gets as first argument the dictionary to search in and as second one a page number (as string). The function will then search through the dictionary and print all the titles of book which have the same number of pages as in the second argument.</p>
<p>Here's an example of my dictionary:</p>
<pre><code>text = {
1: {
1: {"ch.name": "The Boy Who Lived", "pages": "146"},
2: {"ch.name": "The Vanishing Glass", "pages": "126"},
},
2: {
1: {"ch.name": "The Worst Birthday", "pages": "129"},
2: {"ch.name": "Dobby's Warning", "pages": "125"},
},
}
</code></pre>
<p>I have tried the following:</p>
<pre><code>def Name(text,pages):
pages=pages
for key1, value1 in text.items():
for key2, value2 in value1.items():
output = key1,key2,value2['ch.name'],value2['pages']
output
if pages is pages:
print(f"{value2['ch.name']}")
Name(text, '125')
</code></pre>
<p>The result is:</p>
<pre><code>The Boy Who Lived
The Vanishing Glass
The Worst Birthday
Dobby's Warning
</code></pre>
<p>However, the result had to the following, because it is the only book with exactly 125 pages:</p>
<pre><code>Dobby's Warning
</code></pre>
| [
{
"answer_id": 74307766,
"author": "azro",
"author_id": 7212686,
"author_profile": "https://Stackoverflow.com/users/7212686",
"pm_score": 1,
"selected": false,
"text": "def replace(content):\n if content.count(\" \") > 0:\n content = content.replace(\" \", \"_\")\n return content\n\nsentence = input(\"Enter de sentence: \")\nprint(replace(sentence))\n"
},
{
"answer_id": 74308440,
"author": "lroth",
"author_id": 11032782,
"author_profile": "https://Stackoverflow.com/users/11032782",
"pm_score": 0,
"selected": false,
"text": ".split()"
},
{
"answer_id": 74308666,
"author": "Arifa Chan",
"author_id": 19574157,
"author_profile": "https://Stackoverflow.com/users/19574157",
"pm_score": 0,
"selected": false,
"text": "replace()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18980860/"
] |
74,307,750 | <p>i want to change the background-color of all list elements of the unordered list with the id buttons.</p>
<p>If i click on a button, all buttons change their color, but then i get this ugly error:</p>
<blockquote>
<p>main.js:135 Uncaught TypeError: Cannot set properties of undefined (setting 'backgroundColor')
at buttonClicked (main.js:135:48)
at HTMLLIElement. (main.js:65:72)</p>
</blockquote>
<p>Where is the problem?</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 buttons = document.querySelector("#buttons").querySelectorAll("li");
for ( let elements of buttons ) {
elements.addEventListener( "click", function( event ) {buttonClicked( event )} );
}
function buttonClicked( event ) {
let buttons = document.querySelector("#buttons").querySelectorAll("li");
for ( let element in buttons ) {
buttons[element].style.backgroundColor = "black";
}
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#buttons li {
list-style-type: none;
border-radius: 5px;
background-color: rgba( 0, 57, 116, 0.5 );
color: rgba( 255, 255, 255, 1);
padding: 20px;
margin: 10px;
}
#buttons li:hover {
background-color: rgba( 0, 57, 116, 0.8 );
cursor: pointer;
}
#buttons li:active {
color: rgba( 150, 150, 150, 1);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="buttons">
<li id="round-view">Drag and drop</li>
<li id="demo-view">Demo mode</li>
<li id="home-view">View home</li>
<li id="casing-view">Show/Hide Casing</li>
</ul></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74307766,
"author": "azro",
"author_id": 7212686,
"author_profile": "https://Stackoverflow.com/users/7212686",
"pm_score": 1,
"selected": false,
"text": "def replace(content):\n if content.count(\" \") > 0:\n content = content.replace(\" \", \"_\")\n return content\n\nsentence = input(\"Enter de sentence: \")\nprint(replace(sentence))\n"
},
{
"answer_id": 74308440,
"author": "lroth",
"author_id": 11032782,
"author_profile": "https://Stackoverflow.com/users/11032782",
"pm_score": 0,
"selected": false,
"text": ".split()"
},
{
"answer_id": 74308666,
"author": "Arifa Chan",
"author_id": 19574157,
"author_profile": "https://Stackoverflow.com/users/19574157",
"pm_score": 0,
"selected": false,
"text": "replace()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19799489/"
] |
74,307,756 | <p>I have a simple xhr.open/xhr.send to my node.js app and can't figure out why it isn't working. Both are running on the same server.</p>
<p>When I use curl to my node.js app, it returns as expected.</p>
<p>Javascript</p>
<pre><code>var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:2121/ingredients");
xhr.send();
console.log(xhr.responseText);
</code></pre>
<p>Node.js</p>
<pre><code>const express = require('express')
const app = express()
const ingredients = [
{
"id": "1",
"item": "Butter"
}
];
app.get('/ingredients', (req, res) =>{
res.send(ingredients);
});
app.listen(2121);
</code></pre>
<p>I tried reducing my problem to its simplest form. I've been reading about CORS ad-nauseum and still can't get this to work.</p>
<p>I tried setting "Access-Control-Allow-Origin", "*" and "Access-Control-Allow-Headers", "X-Requested-With" (and many other trial-and-errors) in my node script to no avail. I'm hoping someone has a simple solution to this. I'm not an expert in either technology.</p>
| [
{
"answer_id": 74307829,
"author": "Rodolfo BocaneGra",
"author_id": 7623144,
"author_profile": "https://Stackoverflow.com/users/7623144",
"pm_score": 0,
"selected": false,
"text": "console.log()"
},
{
"answer_id": 74324580,
"author": "musca999",
"author_id": 4403891,
"author_profile": "https://Stackoverflow.com/users/4403891",
"pm_score": -1,
"selected": false,
"text": "var xhr = new XMLHttpRequest();\nxhr.onreadystatechange = function() {\n if (xhr.readyState == XMLHttpRequest.DONE) {\n console.log(xhr.responseText);\n }\n}\nxhr.open(\"GET\", \"https://<ip of host...not localhost>:2121\");\nxhr.send() \n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4403891/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.