qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,363,421 | <p>I have a number of text entries (municipalities) from which I need to remove the s at the end.</p>
<pre><code>Data test;
input city $;
datalines;
arjepogs
askers
Londons
;
run;
data cities;
set test;
if prxmatch("/^(.*?)s$/",city)
then city=prxchange("s/^(.*?)s$/$1/",-1,city);
run;
</code></pre>
<p>Strangely enough, my s's are only removed from my first entry.</p>
<p><a href="https://i.stack.imgur.com/Bjz3W.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Bjz3W.png" alt="enter image description here" /></a></p>
<p>What am I doing wrong?</p>
| [
{
"answer_id": 74363539,
"author": "Tom",
"author_id": 4965549,
"author_profile": "https://Stackoverflow.com/users/4965549",
"pm_score": 3,
"selected": true,
"text": "data have;\n input city $20.;\ndatalines;\narjepogs\nKent\naskers\nLondons\n;\n\ndata want;\n set have;\n length new_city $20 ;\n new_city=prxchange(\"s/^(.*?)s$/$1/\",-1,trim(city));\nrun;\n"
},
{
"answer_id": 74367397,
"author": "gregor",
"author_id": 20198546,
"author_profile": "https://Stackoverflow.com/users/20198546",
"pm_score": 2,
"selected": false,
"text": "data cities;\n set test;\n if substr(city,length(city)) eq \"s\" then\n city=substr(city,1,length(city)-1);\nrun;\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74363421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5428469/"
] |
74,363,423 | <p>My code implemented so far is:</p>
<pre><code>const date = new Date();
const currentTime = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
const getDay = `${date.getDay()} ${date.getMonth()} ${date.getDate()}`;
return (
<Box>
<Typography>{currentTime}</Typography>
<Typography>{getDay}</Typography>
</Box>
);
</code></pre>
<p>But I get</p>
<p>14:6:56</p>
<p>2 10 8</p>
<p>The below image is the format I was looking for.</p>
<p><a href="https://i.stack.imgur.com/uibwQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uibwQ.png" alt="format" /></a></p>
| [
{
"answer_id": 74363539,
"author": "Tom",
"author_id": 4965549,
"author_profile": "https://Stackoverflow.com/users/4965549",
"pm_score": 3,
"selected": true,
"text": "data have;\n input city $20.;\ndatalines;\narjepogs\nKent\naskers\nLondons\n;\n\ndata want;\n set have;\n length new_city $20 ;\n new_city=prxchange(\"s/^(.*?)s$/$1/\",-1,trim(city));\nrun;\n"
},
{
"answer_id": 74367397,
"author": "gregor",
"author_id": 20198546,
"author_profile": "https://Stackoverflow.com/users/20198546",
"pm_score": 2,
"selected": false,
"text": "data cities;\n set test;\n if substr(city,length(city)) eq \"s\" then\n city=substr(city,1,length(city)-1);\nrun;\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74363423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14215598/"
] |
74,363,449 | <p>I have a JSON response here,</p>
<pre class="lang-json prettyprint-override"><code>{
"Items": [
{
"Key": {
"timestamp": "2022-11-06T20",
"value": 100.80
}
},
{
"Key": {
"timestamp": "2022-11-07T08",
"value": 100.90
}
}
]
}
</code></pre>
<p>That I would like to reformat to this:</p>
<pre class="lang-json prettyprint-override"><code>{
"Key": [
{
"timestamp": "2019-01-08T20",
"value": 12.44
},
{
"timestamp": "2018-12-12 16:23:00",
"value": 12.45
}
]
}
</code></pre>
<p>For all responses, the Key must only be on the top once followed by an array of timestamps and values, and remove the Items parent value completely. I have tried doing this and messing around with the implementation, but I keep receiving multiple different errors. Is this the correct idea to do it or is there a better way to implement this?</p>
<pre><code> JObject obj = JObject.Parse(jsonOutput);
JObject newObj = new JObject();
new JProperty("KEY", new JArray(
.Children<JProperty>()
.Select(j => new JObject(
new JProperty("timestamp", j.Value["timestamp"]),
new JProperty("value", j.Value["value"])
)
)
)
);
jsonOutput = newObj.ToString();
</code></pre>
<p>What is the correct way to implement this idea? Thanks!</p>
| [
{
"answer_id": 74363539,
"author": "Tom",
"author_id": 4965549,
"author_profile": "https://Stackoverflow.com/users/4965549",
"pm_score": 3,
"selected": true,
"text": "data have;\n input city $20.;\ndatalines;\narjepogs\nKent\naskers\nLondons\n;\n\ndata want;\n set have;\n length new_city $20 ;\n new_city=prxchange(\"s/^(.*?)s$/$1/\",-1,trim(city));\nrun;\n"
},
{
"answer_id": 74367397,
"author": "gregor",
"author_id": 20198546,
"author_profile": "https://Stackoverflow.com/users/20198546",
"pm_score": 2,
"selected": false,
"text": "data cities;\n set test;\n if substr(city,length(city)) eq \"s\" then\n city=substr(city,1,length(city)-1);\nrun;\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74363449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19685408/"
] |
74,363,466 | <p>I have a table as following:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>a</th>
<th>b</th>
<th>a</th>
<th>b</th>
<th>c</th>
<th>color</th>
</tr>
</thead>
<tbody>
<tr>
<td>123</td>
<td>1</td>
<td>6</td>
<td>7</td>
<td>3</td>
<td>4</td>
<td>blue</td>
</tr>
<tr>
<td>456</td>
<td>2</td>
<td>8</td>
<td>9</td>
<td>7</td>
<td>5</td>
<td>yellow</td>
</tr>
</tbody>
</table>
</div>
<p>As you can see, some of the columns have the same. What I want to do is to stack the columns with the same names on top of each other (make the table longer than wider). I have looked into documentations of stack, melt and pivot but I can't find a similar problem as I have here. Can anyone help me how this can be achieved?</p>
<p>FYI, here is how I need the table to be:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>a</th>
<th>b</th>
<th>c</th>
<th>color</th>
</tr>
</thead>
<tbody>
<tr>
<td>123</td>
<td>1</td>
<td>6</td>
<td>4</td>
<td>blue</td>
</tr>
<tr>
<td>123</td>
<td>7</td>
<td>3</td>
<td>4</td>
<td>blue</td>
</tr>
<tr>
<td>456</td>
<td>2</td>
<td>8</td>
<td>5</td>
<td>yellow</td>
</tr>
<tr>
<td>456</td>
<td>9</td>
<td>7</td>
<td>5</td>
<td>yellow</td>
</tr>
</tbody>
</table>
</div> | [
{
"answer_id": 74363540,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "groupby.cumcount"
},
{
"answer_id": 74363571,
"author": "Naveed",
"author_id": 3494754,
"author_profile": "https://Stackoverflow.com/users/3494754",
"pm_score": 0,
"selected": false,
"text": "# melt to turn wide to long format\ndf2=df.melt(id_vars=['id']) \n\n(df2.assign(seq=df2.groupby(['variable']).cumcount()) # assign a seq to create multiple rows for an id\n .pivot(index=['id','seq'], columns='variable', values='value' ) # pivot\n .reset_index()\n .drop(columns='seq')\n .rename_axis(columns=None)\n).ffill() # fill nan with previous value\n\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74363466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18374702/"
] |
74,363,467 | <p>I am currently making password strength checker and I want to check the length of the password and determine the strength of the password. But I do not know how to check the length of the password so that it is like "between 5 and 10 words" or "between 20 to 30 words"</p>
<pre><code>import React from "react";
import { useState } from "react";
const Password = () => {
const [password, setPassword] = useState("")
const HandleInputChange = (event) => {
setPassword(event.target.value)
}
const letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
const capsLetters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
const numbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
const specialChar = ["!", "@", "#", "$", "%", "^", "&", "*", "(", ")"]
const slicedLetters = letters.slice(...letters)
const slicedCapsLetters = capsLetters.slice(...capsLetters)
const slicedNumbers = numbers.slice(...numbers)
const slicedSpecialChar = specialChar.slice(...specialChar)
const [passwordStrength, setPasswordStrength] = useState()
// I am working with this function
const StrengthCheck = () => {
if(password.includes(slicedLetters || capsLetters)) {
setPasswordStrength("Very Weak")
} else if(password.includes(slicedLetters && slicedNumbers || slicedCapsLetters)) {
setPasswordStrength("Weak")
} else if(password.includes(slicedLetters && slicedNumbers && slicedSpecialChar || slicedCapsLetters)) {
setPasswordStrength("Medium")
} else if(password.includes(slicedLetters && slicedCapsLetters && slicedSpecialChar || slicedNumbers)) {
setPasswordStrength("Strong")
} else if(password.includes(slicedLetters && slicedCapsLetters && slicedNumbers && slicedSpecialChar)) {
setPasswordStrength("Very Strong")
} else {
setPasswordStrength("Invalid Password to Check!")
}
}
return(
<div>
<h1>Password Strength Checker</h1>
<h3>Your Password</h3>
<input type={"text"} value={password} onChange={HandleInputChange}/>
<button onClick={StrengthCheck}>Confirm</button>
<h3>Password display:</h3>
<input type={"password"} value={password}/>
<br/>
<br/>
<hr/>
Your password strength is: <b>{passwordStrength}</b>
</div>
)
}
export default Password
</code></pre>
| [
{
"answer_id": 74363540,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "groupby.cumcount"
},
{
"answer_id": 74363571,
"author": "Naveed",
"author_id": 3494754,
"author_profile": "https://Stackoverflow.com/users/3494754",
"pm_score": 0,
"selected": false,
"text": "# melt to turn wide to long format\ndf2=df.melt(id_vars=['id']) \n\n(df2.assign(seq=df2.groupby(['variable']).cumcount()) # assign a seq to create multiple rows for an id\n .pivot(index=['id','seq'], columns='variable', values='value' ) # pivot\n .reset_index()\n .drop(columns='seq')\n .rename_axis(columns=None)\n).ffill() # fill nan with previous value\n\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74363467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20159329/"
] |
74,363,491 | <p>I have a nested list shaped like
<code>mylist = [[a, b, c, d], [e, f, g, h], [i, j, k, l]]</code>
And i need to split the nested lists so that every two items are grouped together like this:
<code>Nested_list = [[[a, b], [c, d], [[e, f], [g, h]], [[i, j], [k, l]]</code></p>
<p>I tried splitting them by them by usinga for loop that appended them but this doesn't work.</p>
| [
{
"answer_id": 74363609,
"author": "Aymen",
"author_id": 5165980,
"author_profile": "https://Stackoverflow.com/users/5165980",
"pm_score": 2,
"selected": false,
"text": "mylist = [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l']]\n\nnested_list = [ [i[:2], i[2:]] for i in mylist ] \n\nprint(nested_list)\n"
},
{
"answer_id": 74363611,
"author": "Portal",
"author_id": 20160920,
"author_profile": "https://Stackoverflow.com/users/20160920",
"pm_score": 0,
"selected": false,
"text": "mylist = [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l']]\nNested_list = []\nfor x in mylist:\n Nested_list.append(x[:2])\n Nested_list.append(x[2:])\nprint(Nested_list)\n"
},
{
"answer_id": 74363764,
"author": "Salvatore Daniele Bianco",
"author_id": 11728488,
"author_profile": "https://Stackoverflow.com/users/11728488",
"pm_score": 0,
"selected": false,
"text": "import numpy as np\n\nNested_list = np.array(mylist).reshape(-1,2,2)\n"
},
{
"answer_id": 74363780,
"author": "Harez",
"author_id": 20352132,
"author_profile": "https://Stackoverflow.com/users/20352132",
"pm_score": 0,
"selected": false,
"text": "from itertools import * \n\nmy_list = chain.from_iterable(my_list)\ndef grouper(inputs, n):\n iters = [iter(inputs)] * n\n return zip_longest(*iters)\n\nprint(list(grouper(my_list, 2)))\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74363491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,363,494 | <p>I'm trying to make a menu like this picture:</p>
<p><a href="https://i.stack.imgur.com/yN6T0.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yN6T0.jpg" alt="enter image description here" /></a></p>
<p>I did it like this:</p>
<p><a href="https://i.stack.imgur.com/UaLJQ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UaLJQ.jpg" alt="enter image description here" /></a></p>
<p>How can I center the items in the menu with the picture? This is my homework and I couldn't do it even though I tried. Thanks in advance for your help.</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>body {
font-family: Poppins;
background-color: #F5F6F6;
}
.container {
width: 70%;
margin: 0 auto;
}
.top-space {
height: 25px;
}
.navbar ul li {
display: inline;
}
.navbar ul li a {
text-decoration: none;
line-height: 50px;
}
.navbar ul li img {
height: 50px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Poppins">
<link rel="stylesheet" href="./style/reset.css">
<link rel="stylesheet" href="./style/style.css">
</head>
<body>
<div class="container">
<div class="top-space"></div>
<div class="navbar">
<ul>
<li>
<a href=""><img src="./img/logo.png"> </a>
</li>
<li><a href="">adssdaads</a></li>
<li><a href="">adssdaads</a></li>
<li><a href="">adssdaads</a></li>
<li><a href="">adssdaads</a></li>
</ul>
</div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>I'd appreciate it if you could tell me what the code you've written works.</p>
| [
{
"answer_id": 74363609,
"author": "Aymen",
"author_id": 5165980,
"author_profile": "https://Stackoverflow.com/users/5165980",
"pm_score": 2,
"selected": false,
"text": "mylist = [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l']]\n\nnested_list = [ [i[:2], i[2:]] for i in mylist ] \n\nprint(nested_list)\n"
},
{
"answer_id": 74363611,
"author": "Portal",
"author_id": 20160920,
"author_profile": "https://Stackoverflow.com/users/20160920",
"pm_score": 0,
"selected": false,
"text": "mylist = [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l']]\nNested_list = []\nfor x in mylist:\n Nested_list.append(x[:2])\n Nested_list.append(x[2:])\nprint(Nested_list)\n"
},
{
"answer_id": 74363764,
"author": "Salvatore Daniele Bianco",
"author_id": 11728488,
"author_profile": "https://Stackoverflow.com/users/11728488",
"pm_score": 0,
"selected": false,
"text": "import numpy as np\n\nNested_list = np.array(mylist).reshape(-1,2,2)\n"
},
{
"answer_id": 74363780,
"author": "Harez",
"author_id": 20352132,
"author_profile": "https://Stackoverflow.com/users/20352132",
"pm_score": 0,
"selected": false,
"text": "from itertools import * \n\nmy_list = chain.from_iterable(my_list)\ndef grouper(inputs, n):\n iters = [iter(inputs)] * n\n return zip_longest(*iters)\n\nprint(list(grouper(my_list, 2)))\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74363494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18003111/"
] |
74,363,496 | <pre><code> public function doctorToday(Request $request){
$doctors = Appointment::with('doctor')->whereDate('date',date('Y-m-d'))->get();
return $doctors;
</code></pre>
<p>May I know how to implement one more day to the code? I want to get the tommorow's date instead of today's.</p>
| [
{
"answer_id": 74363548,
"author": "Delano van londen",
"author_id": 19923550,
"author_profile": "https://Stackoverflow.com/users/19923550",
"pm_score": 0,
"selected": false,
"text": "public function doctorToday(Request $request){\n $doctors = Appointment::with('doctor')->whereDate('date',date('Y-m-d', strtotime('+1 days')))->get();\n return $doctors;\n"
},
{
"answer_id": 74363582,
"author": "Gert B.",
"author_id": 2911020,
"author_profile": "https://Stackoverflow.com/users/2911020",
"pm_score": 2,
"selected": true,
"text": "date()"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74363496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20381850/"
] |
74,363,532 | <p>I need to extract the year from vote_data and save it into another column to finally sort the dataframe by year. <a href="https://i.stack.imgur.com/LUcJo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LUcJo.png" alt="R dataframe" /></a></p>
<p>Anyone with an idea? If it is possible to sort it without extracting, that would be even better. Already tried sorting, but did not find out how to sort only by year when the cell contains the whole date.</p>
| [
{
"answer_id": 74363670,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "library(dplyr)\nlibrary(lubridate)\ndf1 <- df1 %>% \n mutate(year = year(ymd(vote_date))) %>%\n arrange(year)\n"
},
{
"answer_id": 74363717,
"author": "Laura",
"author_id": 19109145,
"author_profile": "https://Stackoverflow.com/users/19109145",
"pm_score": 1,
"selected": true,
"text": "arrange()"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74363532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20346322/"
] |
74,363,568 | <p>I would like to add 1 to each element of a bash array. Say I have an array:</p>
<pre><code>array1=(5 1 7 9 4)
</code></pre>
<p>What I would like is to do ideally is this:</p>
<pre><code>echo ${array2[@]}
5 6 1 2 7 8 9 10 4 5
</code></pre>
<p>So that each number is followed by its consecutive number. But I wasn't sure if this was possible so failing that I wanted to just generate the array:</p>
<pre><code>echo ${array3[@]}
6 4 2 8 10 5
</code></pre>
<p>I can achieve the former with a for loop:</p>
<pre><code>for i in ${array1[@]}; do array2+=($i `expr $i + 1`); done
</code></pre>
<p>But this is very time-consuming (my array has 20 million elements) so I was just wondering whether there was a more direct way of doing this?</p>
| [
{
"answer_id": 74363670,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "library(dplyr)\nlibrary(lubridate)\ndf1 <- df1 %>% \n mutate(year = year(ymd(vote_date))) %>%\n arrange(year)\n"
},
{
"answer_id": 74363717,
"author": "Laura",
"author_id": 19109145,
"author_profile": "https://Stackoverflow.com/users/19109145",
"pm_score": 1,
"selected": true,
"text": "arrange()"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74363568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18160418/"
] |
74,363,631 | <p>I'm trying to use a ListTile widget inside a ListView that will change depending on some information received elsewhere in the app. In order to practice, I tried to make a little Dartpad example.</p>
<p>The problem is as follows: I have been able to change the booleans and data behind the items, but they don't update within the ListView.builder.</p>
<p>I have ListTile widgets inside the ListView that I want to have four different states as follows: <code>idle</code>, <code>wait</code>, <code>requested</code>, and <code>speaking</code>.</p>
<p>The different states look like this, as an example:
<a href="https://i.stack.imgur.com/Gb8Z9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gb8Z9.png" alt="enter image description here" /></a></p>
<p>I am trying to change the individual state of one of these items, but I haven't been able to get them to properly update within the ListView.</p>
<p>The ListTile code looks like this. Most of this code is responsible for just handling what the UI should look like for each state:</p>
<pre><code>class UserItem extends StatefulWidget {
String name;
UserTileState userTileState;
UserItem(this.name, this.userTileState);
@override
UserItemState createState() => UserItemState();
}
class UserItemState extends State<UserItem> {
String _getCorrectTextState(UserTileState userTileState) {
switch (userTileState) {
case UserTileState.speaking:
return "Currently Speaking";
case UserTileState.requested:
return "Speak Request";
case UserTileState.wait:
return "Wait - Someone Speaking";
case UserTileState.idle:
return "Idle";
}
}
Widget _getCorrectTrailingWidget(UserTileState userTileState) {
switch (userTileState) {
case UserTileState.speaking:
return const CircleAvatar(
backgroundColor: Colors.green,
foregroundColor: Colors.white,
child: Icon(Icons.volume_up));
case UserTileState.requested:
return CircleAvatar(
backgroundColor: Colors.green.shade100,
foregroundColor: Colors.grey[700],
child: const Icon(Icons.volume_up),
);
case UserTileState.wait:
return CircleAvatar(
backgroundColor: Colors.green.shade100,
foregroundColor: Colors.grey[700],
child: const Icon(Icons.volume_off),
);
case UserTileState.idle:
return CircleAvatar(
backgroundColor: Colors.green.shade100,
foregroundColor: Colors.grey[700],
child: const Icon(Icons.volume_off),
);
}
}
void kickUser(String name) {
print("Kick $name");
}
@override
Widget build(BuildContext context) {
return ListTile(
onLongPress: () {
kickUser(widget.name);
},
title: Text(widget.name,
style: TextStyle(
fontWeight: widget.userTileState == UserTileState.speaking ||
widget.userTileState == UserTileState.requested
? FontWeight.bold
: FontWeight.normal)),
subtitle: Text(_getCorrectTextState(widget.userTileState),
style: const TextStyle(fontStyle: FontStyle.italic)),
trailing: _getCorrectTrailingWidget(widget.userTileState));
}
}
enum UserTileState { speaking, requested, idle, wait }
</code></pre>
<p>To try and trigger a change in one of these <code>UserTile</code> items, I wrote a function as follows. This one should make an <code>idle</code> tile become a <code>requested</code> tile.</p>
<pre><code>void userRequest(String name) {
// send a speak request to a tile
int index = users.indexWhere((element) => element.name == name);
users[index].userTileState = UserTileState.requested;
}
</code></pre>
<p>I will then run that <code>userRequest</code> inside my main build function inside a button, as follows:</p>
<pre><code>class MyApp extends StatefulWidget {
@override
MyAppState createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
void userRequest(String name) {
// send a speak request to a tile
int index = users.indexWhere((element) => element.name == name);
users[index].userTileState = UserTileState.requested;
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(children: [
Expanded(
flex: 8,
child: ListView.separated(
separatorBuilder: (context, index) {
return const Divider();
},
itemCount: users.length,
itemBuilder: (context, index) {
return users[index];
})),
Expanded(
flex: 2,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
TextButton(
onPressed: () {
setState(() {
userRequest("Test1");
});
},
child: const Text("Send Request")),
]))
]));
}
}
</code></pre>
<p>When I tap the button to set the value within the first <code>UserTile</code>, nothing happens.</p>
<p>I don't know where to put setState, and the state of the object within the ListView isn't being updated. What is the most simple solution to this problem? Provider? I've used Provider in this same situation and can't get it to work. Is there another simpler solution to this?</p>
<p>How can I change update the state of a specific element within a ListView?</p>
| [
{
"answer_id": 74363786,
"author": "krumpli",
"author_id": 6904430,
"author_profile": "https://Stackoverflow.com/users/6904430",
"pm_score": 0,
"selected": false,
"text": "_getCorrectTextState()"
},
{
"answer_id": 74363856,
"author": "Aks",
"author_id": 14071053,
"author_profile": "https://Stackoverflow.com/users/14071053",
"pm_score": 0,
"selected": false,
"text": "ListView.separated(\n separatorBuilder: (context, index) {\n return const Divider();\n },\n itemCount: users.length,\n itemBuilder: (context, index) {\n return StatefulBuilder(\n builder: ((context, setStateItem){\n\n //return_your_listTile_widget_here\n //use setStateItem (as setState) this will update the state of selected item\n\n setStateItem(() {\n //code for update the listView item \n });\n\n })\n );\n })),\n"
},
{
"answer_id": 74397673,
"author": "Zachary Haslam",
"author_id": 11703954,
"author_profile": "https://Stackoverflow.com/users/11703954",
"pm_score": 2,
"selected": true,
"text": "Provider"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74363631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11703954/"
] |
74,363,699 | <p>I have seen the Page speed for the web <a href="https://pagespeed.web.dev/" rel="nofollow noreferrer">https://pagespeed.web.dev/</a>
I want to calculate the amount of time taken between the user lands on the screen until the app completes processing and rendering the content.
Have tried some analytics tools such as Firebase performance, Posthog, Mixpanel, Google Analytics, and Instabug. But no tool provided the analytics which I am looking for.</p>
| [
{
"answer_id": 74363786,
"author": "krumpli",
"author_id": 6904430,
"author_profile": "https://Stackoverflow.com/users/6904430",
"pm_score": 0,
"selected": false,
"text": "_getCorrectTextState()"
},
{
"answer_id": 74363856,
"author": "Aks",
"author_id": 14071053,
"author_profile": "https://Stackoverflow.com/users/14071053",
"pm_score": 0,
"selected": false,
"text": "ListView.separated(\n separatorBuilder: (context, index) {\n return const Divider();\n },\n itemCount: users.length,\n itemBuilder: (context, index) {\n return StatefulBuilder(\n builder: ((context, setStateItem){\n\n //return_your_listTile_widget_here\n //use setStateItem (as setState) this will update the state of selected item\n\n setStateItem(() {\n //code for update the listView item \n });\n\n })\n );\n })),\n"
},
{
"answer_id": 74397673,
"author": "Zachary Haslam",
"author_id": 11703954,
"author_profile": "https://Stackoverflow.com/users/11703954",
"pm_score": 2,
"selected": true,
"text": "Provider"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74363699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4917736/"
] |
74,363,728 | <p>The following code searches a text file for a name and displays the related number in a tkinter entry box in Python.</p>
<p>so original text file includes:</p>
<pre><code>bob 19
dan 20
shayne 17
</code></pre>
<p>I would like add another nested loop so that if there are two names the same then two numbers are returned to the entry box. Sorry, I am new to Python, have tried but always come up with an error.</p>
<pre><code>bob 18
bob 19
dan 20
shayne 17
</code></pre>
<pre><code>#https://www.youtube.com/watch?v=lR90cp1wQ1I
from tkinter import *
from tkinter import messagebox
race = []
def displayInfo(race, name):
found = False
pos = 0
while pos < len(race) and not found:
if race[pos][0] == name:
found = True
pos+=1
if found:
return race[pos-1][1]
else:
messagebox.showerror(message = "Invalid input, please try again.")
def clickArea():
fin.set(displayInfo(race, name.get()))
def createlist():
raceFile = open ("C:/python/files/number_list.txt", 'r')
for line in raceFile:
racer = line.split()
race.append(racer)
raceFile.close()
return race
root = Tk()
root.title("Read From text File/List GUI")
Label(root, text="Name").grid(row=0, column=0)
name = StringVar()
Entry(root, textvariable=name).grid(row=0, column =1)
Label(root, text="Finish Time").grid(row=2, column=0)
fin=IntVar()
Label(root, textvariable=fin).grid(row=2, column=1)
button = Button(root, text="Finish Time", command=clickArea)
button.grid(row=3, column=0, columnspan=2)
createlist()
print(race)
</code></pre>
| [
{
"answer_id": 74364370,
"author": "chikibamboni",
"author_id": 19427338,
"author_profile": "https://Stackoverflow.com/users/19427338",
"pm_score": 1,
"selected": false,
"text": "name = input('who do you want to find: ') + \" \"\n\n\nwith open(\"number_list.txt\", \"r\") as file:\n A = file.readlines()\n\n\n#remove program entry '\\n' \nfor i in range(len(A)):\n A[i] = A[i].strip()\n\n\n#getting matching names\nB = [] #the court records the names we need\nfor i in A:\n if i.count(name): #truth check\n #this notation is equivalent to the notationsi: if i.count(name) == 1:\n B.append(i)\n\nprint('the following numbers match:')\nfor i in B:\n index_space = i.index(' ') + 1\n print(i[index_space:])\n"
},
{
"answer_id": 74453724,
"author": "acw1668",
"author_id": 5317403,
"author_profile": "https://Stackoverflow.com/users/5317403",
"pm_score": 0,
"selected": false,
"text": "race"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74363728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18059806/"
] |
74,363,737 | <p>Guys I need your help with an issue. I am recently learning how to use React. The question is this: I have three h2 elements, each with a different id attribute. What I am trying to do is create a list consisting of as many "a" elements as there are h2 elements. Each "a" element should have the href attribute pointing to the respective h2 element.</p>
<p>I show you what I have tried to do. With the code I wrote the list remains blank.</p>
<pre><code>import logo from './logo.svg';
import './App.css';
import { Link } from "react-router-dom";
function App() {
const h2 = Array.from(document.getElementsByTagName('h2'));
const list = h2.map(element => {
return (
<li key={element.id}>
<Link to={`${element.id}`}>{element.innerHTML}</Link>
</li>
);
})
return (
<div className="App">
<h2 id="first">First item</h2>
<h2 id="second">Second item</h2>
<h2 id="Third">Third item</h2>
<h4>List of h2:</h4>
<ul>
{list}
</ul>
</div>
);
}
export default App;
</code></pre>
<p>Could you tell me what I should do or the concepts I should go to study?</p>
| [
{
"answer_id": 74363966,
"author": "Mehul Thakkar",
"author_id": 6888239,
"author_profile": "https://Stackoverflow.com/users/6888239",
"pm_score": 2,
"selected": true,
"text": "#"
},
{
"answer_id": 74364148,
"author": "KcH",
"author_id": 11737596,
"author_profile": "https://Stackoverflow.com/users/11737596",
"pm_score": 0,
"selected": false,
"text": "useEffect"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74363737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17664715/"
] |
74,363,756 | <p><strong>Here's the code i wrote to solve the problem:</strong></p>
<pre><code>let isPrime = function(n) {
for (let i = 2; i < n; i++) {
if (n % i === 0) {
return false;
}
}
return true;
};
function nextPrime(num) {
let newNum = num;
for (let i = 0; i < newNum; i++) {
if (!isPrime(newNum)) {
newNum += 1;
} else if (isPrime(newNum)) {
return newNum;
}
}
};
</code></pre>
<p><strong>My plan is:</strong></p>
<pre><code>// increment the num by 1 and check if that new num is prime;
// if not, increment again and check again. Repeat the process untill prime is found.
</code></pre>
<p><strong>Input and (expected output is commented):</strong></p>
<pre><code>console.log(nextPrime(2)); // 3
console.log(nextPrime(3)); // 5
console.log(nextPrime(7)); // 11
console.log(nextPrime(8)); // 11
console.log(nextPrime(20)); // 23
console.log(nextPrime(97)); // 101
</code></pre>
<p><strong>The output i'm getting;</strong></p>
<pre><code>2
3
7
11
23
97
</code></pre>
<p>I'd like to know where exactly my implementation is wrong. Also, i'd like the code to be without fancy methods because i'm new to all this. Thank you!</p>
| [
{
"answer_id": 74363966,
"author": "Mehul Thakkar",
"author_id": 6888239,
"author_profile": "https://Stackoverflow.com/users/6888239",
"pm_score": 2,
"selected": true,
"text": "#"
},
{
"answer_id": 74364148,
"author": "KcH",
"author_id": 11737596,
"author_profile": "https://Stackoverflow.com/users/11737596",
"pm_score": 0,
"selected": false,
"text": "useEffect"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74363756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16400935/"
] |
74,363,811 | <p>I read through a lot of the answers but can't figure out how to execute a command which I currently execute using <code>cron</code> from <code>subprocess</code> or something better?</p>
<pre><code># cron command
00 16 * * 1-5 DISPLAY=:10 /path/to/shell/script.sh > log/file.log 2>&1
</code></pre>
<p>The <code>DISPLAY</code> is <code>Xvfb</code>.</p>
| [
{
"answer_id": 74364132,
"author": "Barmar",
"author_id": 1491895,
"author_profile": "https://Stackoverflow.com/users/1491895",
"pm_score": 1,
"selected": false,
"text": "os.environ"
},
{
"answer_id": 74364230,
"author": "Charles Duffy",
"author_id": 14122,
"author_profile": "https://Stackoverflow.com/users/14122",
"pm_score": 0,
"selected": false,
"text": "env="
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74363811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6387095/"
] |
74,363,818 | <p>I have a column A with service name, and a column B with the state of these services.
I have the same services deployed on multiple hosts but with different states.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Service</th>
<th>state</th>
</tr>
</thead>
<tbody>
<tr>
<td>ServiceA</td>
<td>OK</td>
</tr>
<tr>
<td>ServiceB</td>
<td>NOK</td>
</tr>
<tr>
<td>ServiceA</td>
<td>NOK</td>
</tr>
<tr>
<td>ServiceB</td>
<td>NOK</td>
</tr>
</tbody>
</table>
</div>
<p>I want to display only services where all rows related to this service are NOK--if a serviceX is in the OK state I want to exclude it.</p>
<p>In my example I would like to retrieve only ServiceB, because there is no row where ServiceB is in a different state than NOK in the whole table.</p>
<pre><code>With a :
SELECT service,state,count(*)
FROM table
GROUP BY service,state
</code></pre>
<p>I'm able to retrieve a counter for each different value:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Service</th>
<th>state</th>
<th>count</th>
</tr>
</thead>
<tbody>
<tr>
<td>ServiceA</td>
<td>OK</td>
<td>1</td>
</tr>
<tr>
<td>ServiceB</td>
<td>NOK</td>
<td>2</td>
</tr>
<tr>
<td>ServiceA</td>
<td>NOK</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
<p><code>WHERE state != 'NOK'</code> discards services in the OK state, but it gives a wrong result as serviceA will appear whereas one row is not 'NOK'.</p>
| [
{
"answer_id": 74364132,
"author": "Barmar",
"author_id": 1491895,
"author_profile": "https://Stackoverflow.com/users/1491895",
"pm_score": 1,
"selected": false,
"text": "os.environ"
},
{
"answer_id": 74364230,
"author": "Charles Duffy",
"author_id": 14122,
"author_profile": "https://Stackoverflow.com/users/14122",
"pm_score": 0,
"selected": false,
"text": "env="
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74363818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20451279/"
] |
74,363,831 | <p>I'am very confused to get someone's birthday date by changing Y-m-d to m-d in the date_birth field. How should I do? This is my current code:</p>
<pre><code>$getBirthday = Karyawan::where('date_birth', Carbon::now()->format('m-d'))->get();
</code></pre>
<p>Thanks, I want to get someone's birthday by taking m-d only from date_birth field. Hope u're helping me!</p>
| [
{
"answer_id": 74363894,
"author": "N69S",
"author_id": 4369919,
"author_profile": "https://Stackoverflow.com/users/4369919",
"pm_score": 3,
"selected": true,
"text": "whereRaw"
},
{
"answer_id": 74363959,
"author": "Semih SAHIN",
"author_id": 10542740,
"author_profile": "https://Stackoverflow.com/users/10542740",
"pm_score": 0,
"selected": false,
"text": "$getBirthday = Karyawan::whereDay('date_birth', Carbon::now()->format('d'))\n ->whereMonth('date_birth', Carbon::now()->format('m'))->get();\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74363831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18294688/"
] |
74,363,837 | <p>I'm attempting to declare a function component in React, so that I could use my custom hook for making API calls. I'm getting a <code>rules-of-hooks</code> that my hook <code>useGet</code> cannot be called inside a callback. In my eyes I am declaring a function component, I must be missing something?</p>
<p>Example:</p>
<pre><code>export const MyComponent = () => {
const [data, setData] = useState();
useEffect(() => {
const { getData } = useGet("myUrl");
setData(getData);
}, [getData]);
return (
<div>{data}</div>
);
};
</code></pre>
| [
{
"answer_id": 74363916,
"author": "Simon Löfquist",
"author_id": 19748662,
"author_profile": "https://Stackoverflow.com/users/19748662",
"pm_score": 1,
"selected": false,
"text": "const {getData} = useGet(\"myUrl\");"
},
{
"answer_id": 74364069,
"author": "soanks",
"author_id": 16454139,
"author_profile": "https://Stackoverflow.com/users/16454139",
"pm_score": 3,
"selected": true,
"text": "const { getData } = useGet(\"myUrl\");\n\nuseEffect(() => { \n setData(getData);\n }, [getData]);\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74363837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4942596/"
] |
74,363,886 | <p>I have the following peace of code:</p>
<pre class="lang-kotlin prettyprint-override"><code>class JiraCredentials(applicationContext: Context)
{
private val preferences = applicationContext.getSharedPreferences(
"jira",
ComponentActivity.MODE_PRIVATE
)
private val username_key = "username"
var username: String
get () = preferences.getString (username_key, "").toString()
set (value) {
val editor = preferences.edit()
editor.putString (username_key, value)
editor.commit ()
}
private val password_key = "password"
var password: String
get () = preferences.getString (password_key, "").toString()
set (value) {
val editor = preferences.edit()
editor.putString (password_key, value)
editor.commit ()
}
}
</code></pre>
<p>As you can see the "username" part is almost the same as the "password" part. Other languages (Scheme, Rust) have <a href="https://en.wikipedia.org/wiki/Hygienic_macro" rel="nofollow noreferrer">"hygienic macros"</a> to handle this. What is the idiomatic way to handle this in Kotlin?</p>
| [
{
"answer_id": 74364113,
"author": "Sweeper",
"author_id": 5133585,
"author_profile": "https://Stackoverflow.com/users/5133585",
"pm_score": 3,
"selected": true,
"text": "class PreferenceDelegate(\n val key: String,\n val preferences: SharedPreferences\n) {\n operator fun getValue(self: Any?, property: KProperty<*>) =\n preferences.getString(key, \"\").toString()\n\n operator fun setValue(self: Any?, property: KProperty<*>, value: String) {\n val editor = preferences.edit()\n editor.putString(key, value)\n editor.commit()\n }\n}\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74363886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/402322/"
] |
74,363,889 | <p>React Hook useEffect has a missing dependency.</p>
<p>Line 92:4: React Hook useEffect has a missing dependency: 'getMoviesData'. Either include it or remove the dependency array react-hooks/exhaustive-deps</p>
<p>Can someone tell me how to fix this error? I'm sure it's something very simple but any help would be greatly appreciated!</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function App() {
// * MOVIE API *
//State
const [movies, setMovies] = useState([])
const [topMovies, setTopMovies] = useState([])
const [kidsMovies, setKidsMovies] = useState([])
const [setKidsTv] = useState([])
//kidsTv
const [setTvShows] = useState([])
//TvShows
const [kidsTvSeries, setKidsTvSeries] = useState([])
//API URL
const url = 'https://api.themoviedb.org/3/discover/movie?api_key=&with_genres=28/';
const tvUrl = 'https://api.themoviedb.org/3/tv/popular?api_key=8&language=en-US&page=1';
const kidsMovieURL = 'https://api.themoviedb.org/3/discover/movie?api_key=8&certification_country=US&certification.lte=G&with_genres=16&include_adult=false&sort_by=popularity.desc';
const kidsTvURL = 'https://api.themoviedb.org/3/tv/popular?api_key=8&language=en-US&page=1&with_genres=16&include_adult=false&sort_by=popularity.desc';
const topPicks = 'https://api.themoviedb.org/3/movie/top_rated?api_key=&language=en-US&page=1';
const kidsSeries = 'https://api.themoviedb.org/3/discover/tv?api_key=1f7c961ae4f02a23e0968d449c15bc98&with_genres=10762'
//Async function to fetch API
async function getMoviesData (url, tvUrl, topPicks, kidsMovieURL, kidsTvUrl, kidsSeries) {
await fetch(url).then(res => res.json()).then(data => setMovies(data.results))
await fetch(topPicks).then(res => res.json()).then(data => setTopMovies(data.results))
await fetch(tvUrl).then(res => res.json()).then(data => setTvShows(data.results))
await fetch(kidsMovieURL).then(res => res.json()).then(data => setKidsMovies(data.results))
await fetch(kidsTvUrl).then(res => res.json()).then(data => setKidsTv(data.results))
await fetch(kidsSeries).then(res => res.json()).then(data => setKidsTvSeries(data.results))
}
//Use Effect
useEffect(() => {
getMoviesData(url, tvUrl, topPicks, kidsMovieURL, kidsTvURL, kidsSeries);
}, [])
return (
<div className='app'>
<div className="header">
<Header Home={Home} Movies={Movies} Kids={Kids} Music={lazyMusic} movies={movies} topMovies={topMovies} kidsMovies={kidsMovies} kidsTvSeries={kidsTvSeries} />
</div>
<div className="music-player">
<MusicPlayer />
</div>
</div>
)
}
export default App</code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74363921,
"author": "Dulaj Ariyaratne",
"author_id": 13368318,
"author_profile": "https://Stackoverflow.com/users/13368318",
"pm_score": 1,
"selected": false,
"text": "useCallback"
},
{
"answer_id": 74363996,
"author": "Ali Nauman",
"author_id": 9917250,
"author_profile": "https://Stackoverflow.com/users/9917250",
"pm_score": 2,
"selected": true,
"text": "useEffect"
},
{
"answer_id": 74364001,
"author": "Zhminko Roman",
"author_id": 20051277,
"author_profile": "https://Stackoverflow.com/users/20051277",
"pm_score": -1,
"selected": false,
"text": "const getMoviesData = useCallback(() => { /* your code */ }, []);\n"
},
{
"answer_id": 74364035,
"author": "Anh Le Hoang",
"author_id": 16315750,
"author_profile": "https://Stackoverflow.com/users/16315750",
"pm_score": 0,
"selected": false,
"text": "getMoviesData func"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74363889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20165435/"
] |
74,363,899 | <p>I am working with a data frame which has date in the first row as given below:</p>
<p><a href="https://i.stack.imgur.com/JPb1h.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JPb1h.png" alt="enter image description here" /></a></p>
<p>However, when I input them these dates get converted to numbers as shown below:</p>
<p><a href="https://i.stack.imgur.com/gAKiF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gAKiF.png" alt="enter image description here" /></a></p>
<p>I would like this to be dates in the same format as in the image above.</p>
<pre><code>> library(readxl)
> Book1 <- read_excel("C:/X/X/X/Book1.xlsx",skip=1)
> View(Book1)
</code></pre>
<p>The data frame is given below:</p>
<pre><code>structure(list(ds = c("ABC", "ABX", "ABZ"), `44866` = c(0, 0,
0), `44896` = c(0, 0, 0), `44927` = c(0, 0, 0), `44958` = c(0,
0, 0), `44986` = c(0, 0, 0), `45017` = c(0, 0, 0)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -3L))
</code></pre>
<p>Can someone share work around on this?</p>
| [
{
"answer_id": 74363921,
"author": "Dulaj Ariyaratne",
"author_id": 13368318,
"author_profile": "https://Stackoverflow.com/users/13368318",
"pm_score": 1,
"selected": false,
"text": "useCallback"
},
{
"answer_id": 74363996,
"author": "Ali Nauman",
"author_id": 9917250,
"author_profile": "https://Stackoverflow.com/users/9917250",
"pm_score": 2,
"selected": true,
"text": "useEffect"
},
{
"answer_id": 74364001,
"author": "Zhminko Roman",
"author_id": 20051277,
"author_profile": "https://Stackoverflow.com/users/20051277",
"pm_score": -1,
"selected": false,
"text": "const getMoviesData = useCallback(() => { /* your code */ }, []);\n"
},
{
"answer_id": 74364035,
"author": "Anh Le Hoang",
"author_id": 16315750,
"author_profile": "https://Stackoverflow.com/users/16315750",
"pm_score": 0,
"selected": false,
"text": "getMoviesData func"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74363899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20203146/"
] |
74,363,907 | <p>I am developing a telegram bot in the Python programming language using the telebot library (pyTelegramBotApi). At the moment when I'm making buttons, I decided to use InlineKeyboardMarkup. The following questions arise, how to get the name of this button by clicking on the button. I need to get the index of an item in the list by the name I need to get from the button name.</p>
<pre><code>@bot.callback_query_handler(func=lambda call: True)
def callback_query(call):
if call.data == 'SUBCATEGORIES_BTN':
sub_id = names.index(???) # Here I have to insert the name from the button name
</code></pre>
| [
{
"answer_id": 74363921,
"author": "Dulaj Ariyaratne",
"author_id": 13368318,
"author_profile": "https://Stackoverflow.com/users/13368318",
"pm_score": 1,
"selected": false,
"text": "useCallback"
},
{
"answer_id": 74363996,
"author": "Ali Nauman",
"author_id": 9917250,
"author_profile": "https://Stackoverflow.com/users/9917250",
"pm_score": 2,
"selected": true,
"text": "useEffect"
},
{
"answer_id": 74364001,
"author": "Zhminko Roman",
"author_id": 20051277,
"author_profile": "https://Stackoverflow.com/users/20051277",
"pm_score": -1,
"selected": false,
"text": "const getMoviesData = useCallback(() => { /* your code */ }, []);\n"
},
{
"answer_id": 74364035,
"author": "Anh Le Hoang",
"author_id": 16315750,
"author_profile": "https://Stackoverflow.com/users/16315750",
"pm_score": 0,
"selected": false,
"text": "getMoviesData func"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74363907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20451464/"
] |
74,363,926 | <p>I am using the following button snip:</p>
<pre><code> Widget _formTextButton(onPressed, buttonText) => TextButton(
style: TextButton.styleFrom(
foregroundColor: Colors.white,
backgroundColor: Colors.blue,
padding: const EdgeInsets.all(16.0),
textStyle: const TextStyle(fontSize: 20),
),
onPressed: onPressed,
child: Text(buttonText),
);
</code></pre>
<p>I need to be able to control the size of the button, is there any way to do that?
I tried to put it inside a SizedBox but I could not get it to work!</p>
| [
{
"answer_id": 74363921,
"author": "Dulaj Ariyaratne",
"author_id": 13368318,
"author_profile": "https://Stackoverflow.com/users/13368318",
"pm_score": 1,
"selected": false,
"text": "useCallback"
},
{
"answer_id": 74363996,
"author": "Ali Nauman",
"author_id": 9917250,
"author_profile": "https://Stackoverflow.com/users/9917250",
"pm_score": 2,
"selected": true,
"text": "useEffect"
},
{
"answer_id": 74364001,
"author": "Zhminko Roman",
"author_id": 20051277,
"author_profile": "https://Stackoverflow.com/users/20051277",
"pm_score": -1,
"selected": false,
"text": "const getMoviesData = useCallback(() => { /* your code */ }, []);\n"
},
{
"answer_id": 74364035,
"author": "Anh Le Hoang",
"author_id": 16315750,
"author_profile": "https://Stackoverflow.com/users/16315750",
"pm_score": 0,
"selected": false,
"text": "getMoviesData func"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74363926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17281101/"
] |
74,363,957 | <p>So I'm building registration page type of thing in android studio kotlin and in it password length has to be over 8 symbols and it must contain at least one number otherwise it should not let me press register button</p>
<p>I managed to make it so that jts necessary for password lenght to be over 8 symbols but I cant seem to add the requirement of it containing number. I have tried to use contain(Int) but it gives me an error. I'd greatly appreciate the help. Thanks in advance</p>
| [
{
"answer_id": 74364193,
"author": "Xəyal Şərifli",
"author_id": 20432696,
"author_profile": "https://Stackoverflow.com/users/20432696",
"pm_score": 1,
"selected": false,
"text": " if (password.contains(\"[0-9]\".toRegex())) {\n //Write code here\n }\n"
},
{
"answer_id": 74365719,
"author": "cactustictacs",
"author_id": 13598222,
"author_profile": "https://Stackoverflow.com/users/13598222",
"pm_score": 0,
"selected": false,
"text": "kotlin.text"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74363957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20263059/"
] |
74,363,965 | <p>I'm designing a simple image-guessing game where the user is shown an image of a flag and then must guess the name of the flag. I have the images set to show up randomly using a random number generator in javascript, however, I do not know how to assign a name to each flag so that I can compare it with the user input.</p>
<p>Here is my code. How would I go about adding value to my images so I can compare them with the user input?</p>
<pre><code>index.html:
<script language="javascript">
document.write("<div id = flagImage><img src = " + link[random_num] + " alt = Flag width = 250px></div>");
</script>
main.js:
random_num = (Math.round((Math.random() * 10) + 1));
link = new Array;
link[1] = "../assets/flagImages/ad.png";
link[2] = "../assets/flagImages/ae.png";
link[3] = "../assets/flagImages/af.png";
link[4] = "../assets/flagImages/ag.png";
link[5] = "../assets/flagImages/ai.png";
link[6] = "../assets/flagImages/al.png";
link[7] = "../assets/flagImages/am.png";
link[8] = "../assets/flagImages/ao.png";
link[9] = "../assets/flagImages/aq.png";
link[10] = "../assets/flagImages/ar.png";`
</code></pre>
| [
{
"answer_id": 74364014,
"author": "Ben Aston",
"author_id": 38522,
"author_profile": "https://Stackoverflow.com/users/38522",
"pm_score": 0,
"selected": false,
"text": "const countries = [{ \n name: 'United Kingdom', \n flagImagePath: '../assets/flagImages/uk.png'\n}, { \n name: 'United States', \n flagImagePath: '../assets/flagImages/us.png'\n}]\n"
},
{
"answer_id": 74364072,
"author": "Peje Joestar",
"author_id": 14024895,
"author_profile": "https://Stackoverflow.com/users/14024895",
"pm_score": 1,
"selected": false,
"text": "let objectName = {name:\"NameCountry\", link:\"https...\"}\n\nconsole.log(objectName.name) //it'll return \"NameCountry\"\nconsole.log(objectName.link) //it'll return \"https...\""
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74363965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20451594/"
] |
74,363,972 | <p>I'm practicing ViewPager in JetPack compose which is experimental right now.</p>
<p>I was able to successfully make a basic view pager, but when trying to add an indicator, I get an error:
<code>Cannot access 'ColumnScopeInstance': it is internal in 'androidx.compose.foundation.layout'</code></p>
<p>Indicator code; (<em>please keep in keep I already imported it</em>)
<a href="https://i.stack.imgur.com/Wig9w.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Wig9w.jpg" alt="enter image description here" /></a></p>
<p>I tried looking for answers, I found a similar problem problem <a href="https://stackoverflow.com/questions/74001640/cannot-access-rowscopeinstance-it-is-internal-in-androidx-compose-foundation">here on stackOverFlow</a>, but I don't understand.</p>
<p>I also found out that I could only use <code>horizontalAlignment = Alignment.CenterHorizontally</code> in a column.</p>
<p>To ask bluntly, How do I position ViewPager Indicator Center Horizontally.</p>
<p>And I followed the procedure on the official document for pager indicator, I don't know what I'm missing.</p>
<p>I'm highly open to Ideas. Thanks to you in Advance.
\If you details is needed I'm more than happy to provide.</p>
| [
{
"answer_id": 74364497,
"author": "Mohammad Derakhshan",
"author_id": 9470643,
"author_profile": "https://Stackoverflow.com/users/9470643",
"pm_score": 3,
"selected": true,
"text": "Box(contentAlignment = Alignment.Center) {....}\n"
},
{
"answer_id": 74364562,
"author": "Thracian",
"author_id": 5457853,
"author_profile": "https://Stackoverflow.com/users/5457853",
"pm_score": 2,
"selected": false,
"text": "contentAlignment = Alignment.Center/TopCenter/BottomCenter"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74363972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15976878/"
] |
74,363,978 | <p>I'm trying to switch to MariaDB from mysql 8. I downloaded latest MariaDb 10.10.1 RC version, trying to import backup created from mysql using mysqldump and I get the following error
<code>Unknown collation 'utf8mb4_0900_as_cs'</code></p>
<p>What is the equivalent collation in MariaDB. Since this question has been closed due to similar question already answered. Similar question is about <code>utf8mb4_0900_ai_ci</code> which is different than what asked here and there is no answer about the collation that I asked. So I would please don't close it again</p>
| [
{
"answer_id": 74370921,
"author": "danblack",
"author_id": 10195153,
"author_profile": "https://Stackoverflow.com/users/10195153",
"pm_score": 3,
"selected": true,
"text": "uca1400_as_cs"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74363978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1173307/"
] |
74,363,992 | <p>How to ignore a field in a Quarkus Rest Client request body? I see in the dependency tree, this is listed:</p>
<pre><code>io.quarkus:quarkus-resteasy-reactive-jsonb:jar:2.7.5.Final:compile
</code></pre>
<p>And using <code>@JsonIgnore</code> or <code>JsonProperty(access = JsonProperty.Access.WRITE_ONLY)</code> from <code>com.fasterxml.jackson.annotation</code> is not working.</p>
<p>I guess it is because <code>MessageBodyWriter</code> is using Jsonb providers, not Jackson.</p>
| [
{
"answer_id": 74363993,
"author": "WesternGun",
"author_id": 4537090,
"author_profile": "https://Stackoverflow.com/users/4537090",
"pm_score": 0,
"selected": false,
"text": "\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\n\nimport javax.json.bind.Jsonb;\nimport javax.json.bind.JsonbBuilder;\nimport javax.json.bind.JsonbConfig;\nimport javax.json.bind.config.PropertyVisibilityStrategy;\nimport javax.ws.rs.ext.ContextResolver;\n\npublic class EventJsonbCustomizer implements ContextResolver<Jsonb> {\n\n @Override\n public Jsonb getContext(Class<?> type) {\n JsonbConfig jsonbConfig = new JsonbConfig()\n .withPropertyVisibilityStrategy(new PropertyVisibilityStrategy() {\n @Override\n public boolean isVisible(Field field) {\n return !field.getDeclaringClass().equals(Event.class) ||\n !field.getName().equals(\"package\"); // if is this class and this field, return false; else true\n }\n\n @Override\n public boolean isVisible(Method method) {\n return false; // always false\n }\n });\n return JsonbBuilder.newBuilder().withConfig(jsonbConfig).build();\n }\n}\n"
},
{
"answer_id": 74375636,
"author": "geoand",
"author_id": 2504224,
"author_profile": "https://Stackoverflow.com/users/2504224",
"pm_score": 2,
"selected": true,
"text": "quarkus-resteasy-reactive-jsonb"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74363992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4537090/"
] |
74,364,047 | <p>Suppose I have a simple dataframe like this one:</p>
<pre><code>mydata <- data.frame(Name = c(rep("A",4),rep("B",3),rep("C",2),rep("D",2),"E"),
Value = c(5,2,3,6,1,3,8,13,3,5,3,3)
</code></pre>
<p>I want to find which is the minimum <code>Value</code> that is shared by all <code>Name</code> (in this example, 3). So far I've created a column with the minimum <code>Value</code> for each <code>Name</code> with:</p>
<pre><code>mydata$min <- ave(mydata$Value, mydata$Name, FUN = min)
</code></pre>
<p>but it's not the result I am looking for. I think I can group the <code>Name</code> with a combination of <code>unique()</code> and <code>mutate()</code> (from <code>dplyr</code>) but I am not sure.</p>
| [
{
"answer_id": 74363993,
"author": "WesternGun",
"author_id": 4537090,
"author_profile": "https://Stackoverflow.com/users/4537090",
"pm_score": 0,
"selected": false,
"text": "\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\n\nimport javax.json.bind.Jsonb;\nimport javax.json.bind.JsonbBuilder;\nimport javax.json.bind.JsonbConfig;\nimport javax.json.bind.config.PropertyVisibilityStrategy;\nimport javax.ws.rs.ext.ContextResolver;\n\npublic class EventJsonbCustomizer implements ContextResolver<Jsonb> {\n\n @Override\n public Jsonb getContext(Class<?> type) {\n JsonbConfig jsonbConfig = new JsonbConfig()\n .withPropertyVisibilityStrategy(new PropertyVisibilityStrategy() {\n @Override\n public boolean isVisible(Field field) {\n return !field.getDeclaringClass().equals(Event.class) ||\n !field.getName().equals(\"package\"); // if is this class and this field, return false; else true\n }\n\n @Override\n public boolean isVisible(Method method) {\n return false; // always false\n }\n });\n return JsonbBuilder.newBuilder().withConfig(jsonbConfig).build();\n }\n}\n"
},
{
"answer_id": 74375636,
"author": "geoand",
"author_id": 2504224,
"author_profile": "https://Stackoverflow.com/users/2504224",
"pm_score": 2,
"selected": true,
"text": "quarkus-resteasy-reactive-jsonb"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11068947/"
] |
74,364,061 | <p>Once I run the below code, I get the following error:</p>
<pre><code> Line 19:5: React Hook useEffect has missing dependencies: 'departureDate', 'from', and 'to'. Either include them or remove the dependency array react-hooks/exhaustive-deps
</code></pre>
<p>This is my Code</p>
<pre><code>import axios from 'axios';
import { useEffect, useState } from 'react';
import {Link, useParams} from 'react-router-dom'
function DisplayFlights() {
const {from,to,departureDate} = useParams()
const [flightData,setFlightData] = useState([])
const [isLoading,setLoading]=useState(true)
useEffect(()=>{
axios.get('http://localhost:8081/flightnews/flights?from='+from+'&to='+to
+'&departureDate='+departureDate).then(res=>{
setFlightData(res.data);
setLoading(false);
})
},[])
return (
<div>
<h2>Flights:</h2>
<table>
<thead>
<tr>
<th>Airlines</th>
<th>Departure City</th>
<th>Arrival City</th>
<th>Departure Date and Time</th>
</tr>
</thead>
<tbody>
{!isLoading?flightData.map(flight=><RowCreator item={flight}/>):""}
</tbody>
</table>
</div>
);
}
function RowCreator(props){
var flight = props.item;
return <tr>
<td>{flight.operatingAirlines}</td>
<td>{flight.departureCity}</td>
<td>{flight.arrivalCity}</td>
<td>{flight.estimatedDepartureTime}</td>
<td><Link to={'/passengerDetails/'+flight.id}>Select</Link></td>
</tr>
}
export default DisplayFlights;
</code></pre>
<p>I tried to call useParams inside the callBack like that I could have all of the dependencies but I can't do that because is not a function .</p>
<p>Thanks for helping me</p>
| [
{
"answer_id": 74364073,
"author": "twharmon",
"author_id": 5808504,
"author_profile": "https://Stackoverflow.com/users/5808504",
"pm_score": 0,
"selected": false,
"text": "from"
},
{
"answer_id": 74364553,
"author": "arp",
"author_id": 10841628,
"author_profile": "https://Stackoverflow.com/users/10841628",
"pm_score": -1,
"selected": false,
"text": "const fetchNews=useCallback((from, to, departureDate)=>{\n axios.get('http://localhost:8081/flightnews/flights?from='+from+'&to='+to\n+'&departureDate='+departureDate).then(res=>{\n setFlightData(res.data);\n setLoading(false);\n})\n},[])\n\nuseEffect(()=>{\n fetchNews(from, to, departureDate)\n},[fetchNews,from, to, departureDate])\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18176483/"
] |
74,364,090 | <p>How can I check if any date is between two dates?
For instance I want to check if current date is between 15 December and 15 January.</p>
<p>This can be any year so my current date could be 15 December 2023 and it should return true. If it's 14 of December or 16 January any year it should return false. 31 December should return true.</p>
<p>This is what I tried:</p>
<pre><code>let now = currentDateProvider()
dateFormatter.dateFormat = "yyyy-MM-dd"
let year = Calendar.current.component(.year, from: now)
guard let start = dateFormatter.date(from: "\(year)-01-01"),
let end = dateFormatter.date(from: "\(year)-01-07") else {
return false
}
if start <= now && now <= end {
return true
}
guard let start = dateFormatter.date(from: "\(year)-12-01"),
let end = dateFormatter.date(from: "\(year)-12-31") else {
return false
}
let value = start <= now && now <= end
return value
</code></pre>
<p>But it seams a bit buggy because if my time zone is UTC +2 then the end date gives me 30 December 22:00:00 because UTC + 2 is 31 December 00:00 - 2 hours it gives you 30 December instead of 31.</p>
<p>Ideally I would like to not have to separate checks for dates and just have one inclusive check between 15-december and 15 January rather than check 15-december - 31 December and 1 janury to 7 - January.</p>
| [
{
"answer_id": 74364681,
"author": "vadian",
"author_id": 5044042,
"author_profile": "https://Stackoverflow.com/users/5044042",
"pm_score": 0,
"selected": false,
"text": "let currentDate = Date.now\nlet year = Calendar.current.component(.year, from: currentDate)\nlet startComponents = DateComponents(year: year, month: 12, day: 15)\nlet startDate = Calendar.current.date(from: startComponents)!\nlet endDate = Calendar.current.date(byAdding: DateComponents(month: 1, day: 1), to: startDate)!\n\nif currentDate >= startDate && currentDate < endDate {\n print(\"isValid\")\n}\n"
},
{
"answer_id": 74364692,
"author": "Allan Garcia",
"author_id": 1636456,
"author_profile": "https://Stackoverflow.com/users/1636456",
"pm_score": -1,
"selected": false,
"text": "import Foundation\n\nlet f = ISO8601DateFormatter()\nf.formatOptions = .withFullDate\nf.timeZone = TimeZone(abbreviation: \"PST\")\n\nfunc thisDate(_ date: Date, isBetweenthisMonth initialMonth: Int, andDay initialDay: Int, andThisOtherMonth finalMonth: Int, andThisOtherDay finalDay: Int) -> Bool {\n var isBetween = false\n \n let year = Calendar.current.component(.year, from: date)\n \n let initialYear = year\n var finalYear = year\n \n if finalMonth < initialMonth {\n finalYear += finalYear\n }\n \n let initialFakeData = f.date(from: \"\\(initialYear)-\\(initialMonth)-\\(initialDay)\")!\n let finalFakeData = f.date(from: \"\\(finalYear)-\\(finalMonth)-\\(finalDay)\")!\n \n if (date > initialFakeData && date < finalFakeData) {\n isBetween = true\n }\n \n return isBetween\n}\n\n\n// Some test cases to pass\nlet date = f.date(from: \"2022-11-01\")!\n\nprint(thisDate(date, isBetweenthisMonth: 12, andDay: 02, andThisOtherMonth: 02, andThisOtherDay: 23) == false ? \"False\" : \"Something wrong.\")\nprint(thisDate(date, isBetweenthisMonth: 10, andDay: 02, andThisOtherMonth: 01, andThisOtherDay: 15) == true ? \"True\" : \"Something wrong.\")\n\nlet date2 = f.date(from: \"2022-12-31\")!\n\nprint(thisDate(date2, isBetweenthisMonth: 12, andDay: 30, andThisOtherMonth: 01, andThisOtherDay: 01) == true ? \"True\" : \"Something wrong.\")\nprint(thisDate(date2, isBetweenthisMonth: 01, andDay: 01, andThisOtherMonth: 01, andThisOtherDay: 15) == false ? \"False\" : \"Something wrong.\")\n\nlet date_now = f.date(from: f.string(from: Date()))!\n\nprint(thisDate(date_now, isBetweenthisMonth: 11, andDay: 08, andThisOtherMonth: 11, andThisOtherDay: 10) == true ? \"True\" : \"Something wrong.\")\nprint(thisDate(date_now, isBetweenthisMonth: 12, andDay: 01, andThisOtherMonth: 02, andThisOtherDay: 01) == false ? \"False\" : \"Something wrong.\")\n"
},
{
"answer_id": 74366023,
"author": "Joakim Danielson",
"author_id": 9223839,
"author_profile": "https://Stackoverflow.com/users/9223839",
"pm_score": 1,
"selected": false,
"text": "let components = Calendar.current.dateComponents([.month, .day], from: date)\nlet inPeriod = (components.month! == 12 && components.day! >= 15) || (components.month! == 1 && components.day! <= 15)\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1898829/"
] |
74,364,115 | <p>Please I'm new to react and I'm trying to set a value on session storage the get it on another page. The problem is, I'm forced to refresh the page to get the updated value stored in the session storage.</p>
<p>I tried setting this way :</p>
<pre><code>sessionStorage.setItem("annee", JSON.stringify(annees));
sessionStorage.setItem("commune", JSON.stringify(communes));
</code></pre>
<p>And getting this other way :</p>
<pre><code>{JSON.parse(sessionStorage.getItem("commune")).ctd_name_commune}
{JSON.parse(sessionStorage.getItem("annee")).ctd_annee_libelle}
</code></pre>
| [
{
"answer_id": 74364681,
"author": "vadian",
"author_id": 5044042,
"author_profile": "https://Stackoverflow.com/users/5044042",
"pm_score": 0,
"selected": false,
"text": "let currentDate = Date.now\nlet year = Calendar.current.component(.year, from: currentDate)\nlet startComponents = DateComponents(year: year, month: 12, day: 15)\nlet startDate = Calendar.current.date(from: startComponents)!\nlet endDate = Calendar.current.date(byAdding: DateComponents(month: 1, day: 1), to: startDate)!\n\nif currentDate >= startDate && currentDate < endDate {\n print(\"isValid\")\n}\n"
},
{
"answer_id": 74364692,
"author": "Allan Garcia",
"author_id": 1636456,
"author_profile": "https://Stackoverflow.com/users/1636456",
"pm_score": -1,
"selected": false,
"text": "import Foundation\n\nlet f = ISO8601DateFormatter()\nf.formatOptions = .withFullDate\nf.timeZone = TimeZone(abbreviation: \"PST\")\n\nfunc thisDate(_ date: Date, isBetweenthisMonth initialMonth: Int, andDay initialDay: Int, andThisOtherMonth finalMonth: Int, andThisOtherDay finalDay: Int) -> Bool {\n var isBetween = false\n \n let year = Calendar.current.component(.year, from: date)\n \n let initialYear = year\n var finalYear = year\n \n if finalMonth < initialMonth {\n finalYear += finalYear\n }\n \n let initialFakeData = f.date(from: \"\\(initialYear)-\\(initialMonth)-\\(initialDay)\")!\n let finalFakeData = f.date(from: \"\\(finalYear)-\\(finalMonth)-\\(finalDay)\")!\n \n if (date > initialFakeData && date < finalFakeData) {\n isBetween = true\n }\n \n return isBetween\n}\n\n\n// Some test cases to pass\nlet date = f.date(from: \"2022-11-01\")!\n\nprint(thisDate(date, isBetweenthisMonth: 12, andDay: 02, andThisOtherMonth: 02, andThisOtherDay: 23) == false ? \"False\" : \"Something wrong.\")\nprint(thisDate(date, isBetweenthisMonth: 10, andDay: 02, andThisOtherMonth: 01, andThisOtherDay: 15) == true ? \"True\" : \"Something wrong.\")\n\nlet date2 = f.date(from: \"2022-12-31\")!\n\nprint(thisDate(date2, isBetweenthisMonth: 12, andDay: 30, andThisOtherMonth: 01, andThisOtherDay: 01) == true ? \"True\" : \"Something wrong.\")\nprint(thisDate(date2, isBetweenthisMonth: 01, andDay: 01, andThisOtherMonth: 01, andThisOtherDay: 15) == false ? \"False\" : \"Something wrong.\")\n\nlet date_now = f.date(from: f.string(from: Date()))!\n\nprint(thisDate(date_now, isBetweenthisMonth: 11, andDay: 08, andThisOtherMonth: 11, andThisOtherDay: 10) == true ? \"True\" : \"Something wrong.\")\nprint(thisDate(date_now, isBetweenthisMonth: 12, andDay: 01, andThisOtherMonth: 02, andThisOtherDay: 01) == false ? \"False\" : \"Something wrong.\")\n"
},
{
"answer_id": 74366023,
"author": "Joakim Danielson",
"author_id": 9223839,
"author_profile": "https://Stackoverflow.com/users/9223839",
"pm_score": 1,
"selected": false,
"text": "let components = Calendar.current.dateComponents([.month, .day], from: date)\nlet inPeriod = (components.month! == 12 && components.day! >= 15) || (components.month! == 1 && components.day! <= 15)\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15384145/"
] |
74,364,118 | <p>I have this mechanism of checking the logged-in user role in a blade page so that I can give him/ her the selected pages but I find after a user has logged in and stayed idle for a long time and when he is back and wants to continue in the page he is getting an error</p>
<p><em>ErrorException
Trying to get property 'id' of non-object (View: /var/www/html/poss_v1/resources/views/dashboard/student/index.blade.php)</em></p>
<p>and my code is here below</p>
<pre><code><?PHP
$user = Auth::user();
$user_id = $user->id; //----here is the problem it is missing the id when the session has ended--//
$role_user = App\Models\RoleUser::where('user_id', $user_id)->first();
$role_name = App\Models\Role::where('id', $role_user->role_id)->first();
$role = $role_name->name;
?>
</code></pre>
| [
{
"answer_id": 74365412,
"author": "SillasSoares",
"author_id": 3498511,
"author_profile": "https://Stackoverflow.com/users/3498511",
"pm_score": 0,
"selected": false,
"text": "Auth::check()"
},
{
"answer_id": 74366331,
"author": "Engr Talha",
"author_id": 12135529,
"author_profile": "https://Stackoverflow.com/users/12135529",
"pm_score": 1,
"selected": false,
"text": "@php\nif(Auth::check()){\n$user = Auth::user(); \n$user_id = $user->id;\n$role_user = App\\Models\\RoleUser::where('user_id', $user_id)->first();\n$role_name = App\\Models\\Role::where('id', $role_user->role_id)->first();\n$role = $role_name->name;\n}\n@endphp\n"
},
{
"answer_id": 74369887,
"author": "Khayam Khan",
"author_id": 10739750,
"author_profile": "https://Stackoverflow.com/users/10739750",
"pm_score": 2,
"selected": true,
"text": "@php\n if(Auth::check()){\n $role_user_id = App\\Models\\RoleUser::where('user_id', auth()->id())->first()->role_id;\n $role = App\\Models\\Role::where('id', $role_user_id)->first()->name;\n }\n@endphp\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11966370/"
] |
74,364,127 | <p>I try to used TRUNC in SQL Oracle but doens't work . I make a mistake ?</p>
<p>select
TRUNC(cal.DAY_DATE - BIRTHDATE)/ 365 AS EMP_AGE,</p>
<p>from dual</p>
| [
{
"answer_id": 74365412,
"author": "SillasSoares",
"author_id": 3498511,
"author_profile": "https://Stackoverflow.com/users/3498511",
"pm_score": 0,
"selected": false,
"text": "Auth::check()"
},
{
"answer_id": 74366331,
"author": "Engr Talha",
"author_id": 12135529,
"author_profile": "https://Stackoverflow.com/users/12135529",
"pm_score": 1,
"selected": false,
"text": "@php\nif(Auth::check()){\n$user = Auth::user(); \n$user_id = $user->id;\n$role_user = App\\Models\\RoleUser::where('user_id', $user_id)->first();\n$role_name = App\\Models\\Role::where('id', $role_user->role_id)->first();\n$role = $role_name->name;\n}\n@endphp\n"
},
{
"answer_id": 74369887,
"author": "Khayam Khan",
"author_id": 10739750,
"author_profile": "https://Stackoverflow.com/users/10739750",
"pm_score": 2,
"selected": true,
"text": "@php\n if(Auth::check()){\n $role_user_id = App\\Models\\RoleUser::where('user_id', auth()->id())->first()->role_id;\n $role = App\\Models\\Role::where('id', $role_user_id)->first()->name;\n }\n@endphp\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15476415/"
] |
74,364,146 | <p>I am trying to write an Ageing Report on SQL Server which shows the total amount of overdue invoices (later on I will have to deduct Credit Notes) that fall in the different columns depending on how many days the have been overdued. I.e (>0), (0-30), (31-60), (61-90), etc.</p>
<p>This is the part of the query I have written so far mostly looking at old post in this forum but it's giving me a lot of duplicates even for Accounts where there is not due balance.</p>
<p>Any idea what I am doing wrong?</p>
<blockquote>
<pre><code>SELECT O.cardcode AS [Account],
O.cardname AS [Name],
O.u_creditlimit AS [Credit Limit],
O.u_onhold AS [On Hold],
O.balance,
Isnull(CASE
WHEN Datediff(day, INV.docduedate, Getdate()) >= 0 AND Datediff(day, INV.docduedate, Getdate()) < 30
THEN (
SELECT Sum(doctotal)
FROM oinv
WHERE cardcode = INV.cardcode)
END, 0) AS [0 to 30 Days],
Isnull(CASE
WHEN Datediff(day, INV.docduedate, Getdate()) >= 31 AND Datediff(day, INV.docduedate, Getdate()) < 60
THEN (
SELECT Sum(doctotal)
FROM oinv
WHERE cardcode = INV.cardcode)
END, 0) AS [31 to 60 Days],
Isnull(CASE
WHEN Datediff(day, INV.docduedate, Getdate()) >= 61 AND Datediff(day, INV.docduedate, Getdate()) < 90
THEN (
SELECT Sum(doctotal)
FROM oinv
WHERE cardcode = INV.cardcode)
END, 0) AS [61 to 90 Days],
Isnull(CASE
WHEN Datediff(day, INV.docduedate, Getdate()) >= 91 AND Datediff(day, INV.docduedate, Getdate()) < 120
THEN (
SELECT Sum(doctotal)
FROM oinv
WHERE cardcode = INV.cardcode)
END, 0) AS [91 to 120 Days],
Isnull(CASE
WHEN Datediff(day, INV.docduedate, Getdate()) >= 121
THEN(
SELECT Sum(doctotal)
FROM oinv
WHERE cardcode = INV.cardcode)
END, 0) AS [121+ Days]
FROM ocrd O
INNER JOIN oinv INV
ON O.cardcode = INV.cardcode
WHERE territory = 3
AND INV.docstatus = 'O'
</code></pre>
<p>Thank you very much.</p>
</blockquote>
| [
{
"answer_id": 74364547,
"author": "John Cappelletti",
"author_id": 1570000,
"author_profile": "https://Stackoverflow.com/users/1570000",
"pm_score": 2,
"selected": true,
"text": " Select O.cardcode\n ,O.cardname \n ,[Credit Limit] = max(O.u_creditlimit)\n ,[On Hold] = max(O.u_onhold)\n ,[0 to 30 Days] = sum( case when DPD between 0 and 30 then doctotal else 0 end)\n ,[31 to 60 Days] = sum( case when DPD between 31 and 60 then doctotal else 0 end)\n ,[61 to 90 Days] = sum( case when DPD between 61 and 90 then doctotal else 0 end)\n ,[91 to 120 Days] = sum( case when DPD between 91 and 120 then doctotal else 0 end)\n ,[121+ Days ] = sum( case when DPD >=121 then doctotal else 0 end)\n From ocrd O\n Join oinv INV on O.cardcode = INV.cardcode\n Cross Apply (values ( Datediff(day, INV.docduedate, Getdate()) ) ) P(DPD)\n Where territory = 3\n and INV.docstatus = 'O' \n and DPD >= 0\n Group By O.cardcode\n ,O.cardname \n"
},
{
"answer_id": 74364803,
"author": "Patrick Hurst",
"author_id": 18522514,
"author_profile": "https://Stackoverflow.com/users/18522514",
"pm_score": 0,
"selected": false,
"text": "DECLARE @table TABLE (RecordID INT IDENTITY, CardCode INT, CardName NVARCHAR(100), u_CreditLimit DECIMAL(10,2), u_onhold DECIMAL(10,2), balance DECIMAL(10,2))\nINSERT INTO @table (CardCode, CardName, u_CreditLimit, u_onhold, balance) VALUES (1, 'John Smith', 10000, 0, 200),\n(1, 'John Smith', 10000, 0, 400),\n(1, 'John Smith', 10000, 0, 200)\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20449468/"
] |
74,364,188 | <p>I have a nested dictionary with three layers, the bottom layer being a mixture of dictionaries and values and want to convert it into a dataframe with keys from the last layer as column names and keys from the first layer as ids.</p>
<pre><code>dict = {"id1": {"att_1": 1,
"att_2": {"att2_1": "value1",
"att2_2": "value2"}},
"id2": {"att_1": 2,
"att_2": {"att2_1": "value3",
"att2_2": "value4"}}
}
</code></pre>
<p>I tried around a little bit with the 'pandas.DataFrame.from_dict()' function:</p>
<pre><code>pd.DataFrame.from_dict({(i): x_dict[i][j] for i in x_dict.keys() for j in x_dict[i].keys()}, orient='index')
</code></pre>
<p>However, the output I am getting lost all the values from the second layer(att1):</p>
<pre><code> att2_1 att2_2
id1 value1 value2
id2 value3 value4
</code></pre>
<p>Is there a better way to approach this or how could I fix my current attempt?</p>
| [
{
"answer_id": 74364547,
"author": "John Cappelletti",
"author_id": 1570000,
"author_profile": "https://Stackoverflow.com/users/1570000",
"pm_score": 2,
"selected": true,
"text": " Select O.cardcode\n ,O.cardname \n ,[Credit Limit] = max(O.u_creditlimit)\n ,[On Hold] = max(O.u_onhold)\n ,[0 to 30 Days] = sum( case when DPD between 0 and 30 then doctotal else 0 end)\n ,[31 to 60 Days] = sum( case when DPD between 31 and 60 then doctotal else 0 end)\n ,[61 to 90 Days] = sum( case when DPD between 61 and 90 then doctotal else 0 end)\n ,[91 to 120 Days] = sum( case when DPD between 91 and 120 then doctotal else 0 end)\n ,[121+ Days ] = sum( case when DPD >=121 then doctotal else 0 end)\n From ocrd O\n Join oinv INV on O.cardcode = INV.cardcode\n Cross Apply (values ( Datediff(day, INV.docduedate, Getdate()) ) ) P(DPD)\n Where territory = 3\n and INV.docstatus = 'O' \n and DPD >= 0\n Group By O.cardcode\n ,O.cardname \n"
},
{
"answer_id": 74364803,
"author": "Patrick Hurst",
"author_id": 18522514,
"author_profile": "https://Stackoverflow.com/users/18522514",
"pm_score": 0,
"selected": false,
"text": "DECLARE @table TABLE (RecordID INT IDENTITY, CardCode INT, CardName NVARCHAR(100), u_CreditLimit DECIMAL(10,2), u_onhold DECIMAL(10,2), balance DECIMAL(10,2))\nINSERT INTO @table (CardCode, CardName, u_CreditLimit, u_onhold, balance) VALUES (1, 'John Smith', 10000, 0, 200),\n(1, 'John Smith', 10000, 0, 400),\n(1, 'John Smith', 10000, 0, 200)\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20451623/"
] |
74,364,214 | <p>I just wanted to make a proof of concept that based on the person's search text and the option they select from the dropdown it will redirect them to the search engine of their choice.</p>
<pre><code>const options = [
{ value: 'http://www.google.com/search?q=', label: 'Google' },
{ value: 'http://search.yahoo.com/search?p=', label: 'Yahoo' },
{ value: 'https://www.bing.com/search?q=', label: 'Bing' },
{ value: 'https://duckduckgo.com/?q=', label: 'DuckDuckGo' }
]
//const [selection, setSearch] = useState("");
const doSearch = event => {
event.preventDefault();
var sf=document.searchform;
var submitto = sf.sengines[sf.sengines.selectedIndex].value + (sf.searchterms.value);
console.log("log: " + submitto);
window.location.href = submitto;
//window.location.replace(submitto)
return null;
}
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>Search:</p>
<form name="searchform" onSubmit={doSearch}>
<Select id="sengines" options={options}/>
For:
<input type="text" name='searchTerms'/>
<input type="submit" name="SearchSubmit" value="Search"></input>
</form>
</header>
</div>
);
}
</code></pre>
<p>When I hit search it throws an error saying that the selectedIndex is undefined. Is there a syntax mistake I am making that I am unaware of?</p>
| [
{
"answer_id": 74364547,
"author": "John Cappelletti",
"author_id": 1570000,
"author_profile": "https://Stackoverflow.com/users/1570000",
"pm_score": 2,
"selected": true,
"text": " Select O.cardcode\n ,O.cardname \n ,[Credit Limit] = max(O.u_creditlimit)\n ,[On Hold] = max(O.u_onhold)\n ,[0 to 30 Days] = sum( case when DPD between 0 and 30 then doctotal else 0 end)\n ,[31 to 60 Days] = sum( case when DPD between 31 and 60 then doctotal else 0 end)\n ,[61 to 90 Days] = sum( case when DPD between 61 and 90 then doctotal else 0 end)\n ,[91 to 120 Days] = sum( case when DPD between 91 and 120 then doctotal else 0 end)\n ,[121+ Days ] = sum( case when DPD >=121 then doctotal else 0 end)\n From ocrd O\n Join oinv INV on O.cardcode = INV.cardcode\n Cross Apply (values ( Datediff(day, INV.docduedate, Getdate()) ) ) P(DPD)\n Where territory = 3\n and INV.docstatus = 'O' \n and DPD >= 0\n Group By O.cardcode\n ,O.cardname \n"
},
{
"answer_id": 74364803,
"author": "Patrick Hurst",
"author_id": 18522514,
"author_profile": "https://Stackoverflow.com/users/18522514",
"pm_score": 0,
"selected": false,
"text": "DECLARE @table TABLE (RecordID INT IDENTITY, CardCode INT, CardName NVARCHAR(100), u_CreditLimit DECIMAL(10,2), u_onhold DECIMAL(10,2), balance DECIMAL(10,2))\nINSERT INTO @table (CardCode, CardName, u_CreditLimit, u_onhold, balance) VALUES (1, 'John Smith', 10000, 0, 200),\n(1, 'John Smith', 10000, 0, 400),\n(1, 'John Smith', 10000, 0, 200)\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20153976/"
] |
74,364,216 | <p><strong>Objective:</strong>
I'm working with a service. The objective is to create a service that will serve as a creation for confirmation dialog and will return whether confirm or cancel was clicked in the popup.</p>
<p><strong>Code:</strong></p>
<blockquote>
<p>product.component.html</p>
</blockquote>
<pre><code><button class="edit-button" (click)="confirmFeatureProductDialog(data)">Confirm</button>
</code></pre>
<blockquote>
<p>product.component.ts</p>
</blockquote>
<pre><code> confirmFeatureProductDialog(product){
let message = "Do you want to set this product?";
let result;
this._popupDialogService.confirmationPopup(message).subscribe(
(res)=>{
console.log("Running")
result = res;
if(result){
this.featureProduct(product._id);
}
}
);
}
</code></pre>
<blockquote>
<p>popupDialog.service.ts</p>
</blockquote>
<pre><code>import { Injectable } from "@angular/core";
import { Observable, Subject } from "rxjs";
import Swal from 'sweetalert2'
Injectable();
export class PopupDialogService {
public mySubject = new Subject<boolean>();
confirmationPopup(textDetail?): Observable<any> {
Swal.fire({
title: 'Are you sure?',
text: textDetail,
icon: 'success',
showConfirmButton: true,
showCancelButton: true,
}).then((result) => {
if (result.value) {
this.mySubject.next(true);
return;
}
Swal.close();
});
return this.mySubject.asObservable();
}
}
</code></pre>
<p><strong>Result & Issue:</strong></p>
<p>When I run this the first time everything seems to be <strong>working fine</strong>.</p>
<p>When I click on the button the <strong>2nd time</strong> after clicking either cancel or confirm the response from the <code>product.component.ts</code> is <strong>duplicated twice</strong> i.e the console.log from the subscribe response is repeated twice and console.log shows <code>"Running" "Running"</code>.</p>
<p>When I click the button third time (once the dialog closes after clicking confirm/cancel) the response is repeated thrice and console shows <code>"Running"</code> 3 times.</p>
<p><strong>Things I've tried so far:</strong></p>
<p>Add the service to app.module.ts provider instead of product.module.ts providers. Doesn't change anything.</p>
<p>Checked if the service's constructor is called multiple times on 2nd and onwards execution. It doesn't execute multiple times. <strong>Only the subscription response is executed multiple times.</strong></p>
<p><strong>Summary:</strong></p>
<p>Running subscription on a function returning observable from service. First time the response of the subscription is okay however when the function is re-opened the 2nd time it throws the response twice, after closing and re-running the function gives the response thrice and so on.</p>
| [
{
"answer_id": 74364387,
"author": "Parth M. Dave",
"author_id": 12119351,
"author_profile": "https://Stackoverflow.com/users/12119351",
"pm_score": -1,
"selected": false,
"text": "this._popupDialogService.confirmationPopup(message)"
},
{
"answer_id": 74364408,
"author": "Luca Angrisani",
"author_id": 13240452,
"author_profile": "https://Stackoverflow.com/users/13240452",
"pm_score": -1,
"selected": false,
"text": "sub: Subscription;\nconfirmFeatureProductDialog(product){\n let message = \"Do you want to set this product?\";\n let result; \n this.sub = this._popupDialogService.confirmationPopup(message).subscribe(\n (res)=>{\n console.log(\"Running\")\n result = res;\n if(result){\n this.featureProduct(product._id);\n }\n this.subs.unsubscribe();\n }\n );\n}\n"
},
{
"answer_id": 74365498,
"author": "Mr. Stash",
"author_id": 13625800,
"author_profile": "https://Stackoverflow.com/users/13625800",
"pm_score": 0,
"selected": false,
"text": "// component code\n\nngOnInit() {\n let result;\n this._popupDialogService.mySubject.subscribe(\n (res)=>{\n console.log(\"Running\")\n result = res;\n if(result){\n this.featureProduct(product._id);\n }\n }\n );\n}\n\nconfirmFeatureProductDialog(product){\n let message = \"Do you want to set this product?\";\n this._popupDialogService.confirmationPopup(message)\n}\n\n// Service code\n\nconfirmationPopup(textDetail?) {\n Swal.fire({\n title: 'Are you sure?',\n text: textDetail,\n icon: 'success',\n showConfirmButton: true,\n showCancelButton: true,\n }).then((result) => {\n if (result.value) {\n console.log(result)\n this.mySubject.next(true);\n return;\n }\n Swal.close();\n });\n}\n"
},
{
"answer_id": 74369118,
"author": "paranaaan",
"author_id": 11634381,
"author_profile": "https://Stackoverflow.com/users/11634381",
"pm_score": 0,
"selected": false,
"text": "Subscription"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3573145/"
] |
74,364,219 | <p>I would like to create a container component in my application. I don't know if this is possible or if it's a good idea at all. I would be so very comfortable.</p>
<pre><code>From this:
export default function App(){
return(
<div className={styles.CardsContainer}>
<CardPrice price={700}/>
<CardPrice price={3000}/>
<CardPrice price={5000}/>
</div>
)
}
I want to do it:
export default function App(){
return(
<CardsContainer>
<CardPrice price={700}/>
<CardPrice price={3000}/>
<CardPrice price={5000}/>
</CardsContainer>
)
}
I do this in CardsContainer:
export default function CardsContainer(){
return(
<div className={styles.CardsContainer}>
</div>
)
}
</code></pre>
<p>Obviously it doesn't work) But I don't know how to wrap properly.
I don't want to put components with CardPrice in a CardContainer component. I want to wrap in App component</p>
| [
{
"answer_id": 74364265,
"author": "Luis Paulo",
"author_id": 19730992,
"author_profile": "https://Stackoverflow.com/users/19730992",
"pm_score": 2,
"selected": true,
"text": "export default function CardsContainer({children}){\n return(\n <div className={styles.CardsContainer}>\n {children}\n </div>\n )\n}\n"
},
{
"answer_id": 74364320,
"author": "arp",
"author_id": 10841628,
"author_profile": "https://Stackoverflow.com/users/10841628",
"pm_score": 0,
"selected": false,
"text": "export default function CardsContainer({children}){\nreturn(\n <div className={styles.CardsContainer}>\n {children}\n </div>\n)\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20023944/"
] |
74,364,266 | <p>I got a list which contains approx. 10.000 strings and I want to use a regex pattern to detect this in this list. When I use re.compile it takes a lot of time to only apply one regex pattern. Is there any way with Python to make it faster?</p>
<p>Here my code:</p>
<pre><code>
import re
list_of_strings = ["I like to eat meat", "I don't like to eat meat", "I like to eat fish", "I don't like to eat fish"]
outcome = [x for x in list_of_strings if len(re.compile(r"I like to eat (.*?)").findall(x)) != 0]
Out[6]: ['I like to eat meat', 'I like to eat fish']
</code></pre>
<p>Here I have just 4 strings to demonstrate the case. In reality the code should handle 10.000 strings.</p>
<p>I could also use multiple processing to solve this issue but maybe there is also another solution with pytorch, pyspark or other Frameworks existing.</p>
<p>[Edit]
Thanks for all answers. I should have mentioned that every string is an article. So, it is not just one sentence to be handled from regex.</p>
<p>I also want to say that the regex here ist not that problem. So this is not a topic to be discussed.</p>
| [
{
"answer_id": 74364327,
"author": "0x0fba",
"author_id": 20339407,
"author_profile": "https://Stackoverflow.com/users/20339407",
"pm_score": 1,
"selected": false,
"text": "re.compile"
},
{
"answer_id": 74364529,
"author": "user99999",
"author_id": 20070120,
"author_profile": "https://Stackoverflow.com/users/20070120",
"pm_score": 1,
"selected": true,
"text": "new_list = []\nfor item in list_of_strings:\n if 'I like to eat' in item:\n new_list.append(item)\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13527251/"
] |
74,364,267 | <p>I have a json file I am trying to read via a <code>StreamReader</code>. The json is in the same directory as my code. However, any method for loading the file (<code>GetFullPath()</code>, <code>GetDirectoryName()</code>, etc) is always looking in the <code>\bin\Debug\netcoreapp3.1</code> directory, where it obviously is not. I have tried all the different versions</p>
<p>I think that has more to do with an issue with netcoreapp than anything else. How do I get it to just load the file in the same directory?</p>
| [
{
"answer_id": 74364327,
"author": "0x0fba",
"author_id": 20339407,
"author_profile": "https://Stackoverflow.com/users/20339407",
"pm_score": 1,
"selected": false,
"text": "re.compile"
},
{
"answer_id": 74364529,
"author": "user99999",
"author_id": 20070120,
"author_profile": "https://Stackoverflow.com/users/20070120",
"pm_score": 1,
"selected": true,
"text": "new_list = []\nfor item in list_of_strings:\n if 'I like to eat' in item:\n new_list.append(item)\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/285409/"
] |
74,364,281 | <p>So i'm making this app, that captures an image, and that image is used further to extract text from it. I found this code, to access the camera and capture image (in a fragment):</p>
<pre><code>class HomeFragment : Fragment() {
private var _binding: FragmentHomeBinding? = null
private val binding get() = _binding!!
private val CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1888
var button: Button? = null
var imageView: ImageView? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentHomeBinding.inflate(inflater, container, false)
val root: View = binding.root
button!!.setOnClickListener {
fun onClick(view: View?) {
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(
intent,
CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE
)
}
}
return root
}
fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
val bmp = data.extras!!["data"] as Bitmap?
val stream = ByteArrayOutputStream()
bmp!!.compress(Bitmap.CompressFormat.PNG, 100, stream)
val byteArray: ByteArray = stream.toByteArray()
// convert byte array to Bitmap
val bitmap = BitmapFactory.decodeByteArray(
byteArray, 0,
byteArray.size
)
imageView!!.setImageBitmap(bitmap)
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
</code></pre>
<p>But there is an "accidental override" error with onActivityResult() method, and i don't know how to fix that: <a href="https://i.stack.imgur.com/rR7zz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rR7zz.png" alt="error message" /></a></p>
<p>I've tried adding this to MainActivity class, hoping for the best:</p>
<pre><code>override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
}
</code></pre>
<p>But it doesn't seem to help. I am a total beginner, but i've got to make this app real quick, so will be grateful for any advice or explanation.</p>
<p>upd: I've also tried adding keyword override, but i get error "onActivityResult() overrides nothing"</p>
| [
{
"answer_id": 74373361,
"author": "Asaf",
"author_id": 15505732,
"author_profile": "https://Stackoverflow.com/users/15505732",
"pm_score": 1,
"selected": false,
"text": "onActivityResult"
},
{
"answer_id": 74376785,
"author": "David Wasser",
"author_id": 769265,
"author_profile": "https://Stackoverflow.com/users/769265",
"pm_score": 0,
"selected": false,
"text": "OnActivityResult()"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20451667/"
] |
74,364,288 | <p>I have the following array:</p>
<pre><code>const foodMenu = [
{id: 1, name: 'pasta', nutritionalInfo: ['ve', 'veg', 'gf']},
{id: 2, name: 'pizza', nutritionalInfo: ['gf', 'veg']},
{id: 3, name: 'applePie', nutritionalInfo: ['nuts']}
]
</code></pre>
<p>I want to display a count on my page of how many of each nutritional info there is. For example, it will look like:</p>
<p>Ve: 1
Gluten free: 2,
Veg: 2,
Nuts: 1</p>
<p>I am not sure of the cleanest way of getting all the data from the nested <code>nutritionalInfo</code> array and counting it?</p>
<p>I have tried mapping over them to add to a new <code>nutritionalInfoCount</code> array but I am getting a too many rerenders warning:</p>
<pre><code> {foodMenu.map((foodMenu) => (
foodMenu.nutritionalInfo.forEach((nutritionalInfo) => (
setNutritionalInfoCount([nutritionalInfoCount, nutritionalInfo])
))
))
}
</code></pre>
<p>Can anyone please help with a way to solve this?</p>
| [
{
"answer_id": 74364489,
"author": "Mr. Polywhirl",
"author_id": 1762224,
"author_profile": "https://Stackoverflow.com/users/1762224",
"pm_score": 0,
"selected": false,
"text": "const descriptors = {\n ve: 'Vegan',\n veg: 'Vegetarian',\n gf: 'Gluten Free',\n nuts: 'Nuts',\n};\n\nconst foodMenu = [\n { id: 1, name: 'pasta', nutritionalInfo: ['ve', 'veg', 'gf'] }, \n { id: 2, name: 'pizza', nutritionalInfo: ['gf', 'veg'] }, \n { id: 3, name: 'applePie', nutritionalInfo: ['nuts'] },\n];\n\nconst calcFrequency = (items, subKey) =>\n items.reduce((outer, item) =>\n item[subKey].reduce((inner, key) => {\n inner[key] = (inner[key] ?? 0) + 1;\n return inner;\n }, outer), {});\n\nconst printFrequency = (frequency) => {\n console.log(Object.entries(frequency)\n .sort(([k1], [k2]) => descriptors[k1].localeCompare(descriptors[k2]))\n .map(([key, count]) => `${descriptors[key]}: ${count}`)\n .join(', '));\n}\n\nprintFrequency(calcFrequency(foodMenu, 'nutritionalInfo'));"
},
{
"answer_id": 74364502,
"author": "sumowrestler",
"author_id": 4504046,
"author_profile": "https://Stackoverflow.com/users/4504046",
"pm_score": 3,
"selected": true,
"text": "const foodMenu = [\n {id: 1, name: 'pasta', nutritionalInfo: ['ve', 'veg', 'gf']}, \n {id: 2, name: 'pizza', nutritionalInfo: ['gf', 'veg']}, \n {id: 3, name: 'applePie', nutritionalInfo: ['nuts']}\n]\n\nconst nutritionalInfoCount = {};\nfoodMenu.forEach(({nutritionalInfo}) => {\n nutritionalInfo.forEach(nutrient => {\n if (nutrient in nutritionalInfoCount) {\n nutritionalInfoCount[nutrient] += 1;\n } else {\n nutritionalInfoCount[nutrient] = 1;\n }\n });\n});\n"
},
{
"answer_id": 74364595,
"author": "Ilê Caian",
"author_id": 19330762,
"author_profile": "https://Stackoverflow.com/users/19330762",
"pm_score": -1,
"selected": false,
"text": ".reduce()"
},
{
"answer_id": 74364754,
"author": "Keith",
"author_id": 6870228,
"author_profile": "https://Stackoverflow.com/users/6870228",
"pm_score": 1,
"selected": false,
"text": "Array.reduce"
},
{
"answer_id": 74364836,
"author": "Harsh Srivastava",
"author_id": 9099045,
"author_profile": "https://Stackoverflow.com/users/9099045",
"pm_score": 0,
"selected": false,
"text": " export default function App() {\n const foodMenu = [\n { id: 1, name: \"pasta\", nutritionalInfo: [\"ve\", \"veg\", \"gf\"] },\n { id: 2, name: \"pizza\", nutritionalInfo: [\"gf\", \"veg\"] },\n { id: 3, name: \"applePie\", nutritionalInfo: [\"nuts\"] }\n ];\n const nutrientContent = {};\n foodMenu.forEach((foodMenu) => {\n foodMenu.nutritionalInfo.forEach(\n (nutritionalInfo) =>\n (nutrientContent[nutritionalInfo] =\n nutritionalInfo in nutrientContent\n ? nutrientContent[nutritionalInfo] + 1\n : 1)\n );\n });\n return (\n <div className=\"App\">\n {Object.keys(nutrientContent).map(\n (val) => val + \":\" + nutrientContent[val] + \", \"\n )}\n </div>\n );\n}\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12145038/"
] |
74,364,301 | <pre><code> crsr.execute("SELECT * FROM tblmob")
res = crsr.fetchall()
for i in res:
nopol = i [2]
print(nopol)
</code></pre>
<p>and the ouput is row formating like this without the bullet</p>
<ul>
<li>B 9020 BCS</li>
<li>B 9243 BQB</li>
<li>B 9244 BQB</li>
<li>B 9307 KXR</li>
<li>B 9552 UXT</li>
<li>B 9730 BCK</li>
<li>B 9733 CXS</li>
<li>B 9746 WRU</li>
<li>B 9782 FXR</li>
</ul>
<p>how can i get only one data from mylist
i want get only B 9552 UXT
please help me thanks</p>
<p>i have tried many time but is always fails</p>
| [
{
"answer_id": 74364489,
"author": "Mr. Polywhirl",
"author_id": 1762224,
"author_profile": "https://Stackoverflow.com/users/1762224",
"pm_score": 0,
"selected": false,
"text": "const descriptors = {\n ve: 'Vegan',\n veg: 'Vegetarian',\n gf: 'Gluten Free',\n nuts: 'Nuts',\n};\n\nconst foodMenu = [\n { id: 1, name: 'pasta', nutritionalInfo: ['ve', 'veg', 'gf'] }, \n { id: 2, name: 'pizza', nutritionalInfo: ['gf', 'veg'] }, \n { id: 3, name: 'applePie', nutritionalInfo: ['nuts'] },\n];\n\nconst calcFrequency = (items, subKey) =>\n items.reduce((outer, item) =>\n item[subKey].reduce((inner, key) => {\n inner[key] = (inner[key] ?? 0) + 1;\n return inner;\n }, outer), {});\n\nconst printFrequency = (frequency) => {\n console.log(Object.entries(frequency)\n .sort(([k1], [k2]) => descriptors[k1].localeCompare(descriptors[k2]))\n .map(([key, count]) => `${descriptors[key]}: ${count}`)\n .join(', '));\n}\n\nprintFrequency(calcFrequency(foodMenu, 'nutritionalInfo'));"
},
{
"answer_id": 74364502,
"author": "sumowrestler",
"author_id": 4504046,
"author_profile": "https://Stackoverflow.com/users/4504046",
"pm_score": 3,
"selected": true,
"text": "const foodMenu = [\n {id: 1, name: 'pasta', nutritionalInfo: ['ve', 'veg', 'gf']}, \n {id: 2, name: 'pizza', nutritionalInfo: ['gf', 'veg']}, \n {id: 3, name: 'applePie', nutritionalInfo: ['nuts']}\n]\n\nconst nutritionalInfoCount = {};\nfoodMenu.forEach(({nutritionalInfo}) => {\n nutritionalInfo.forEach(nutrient => {\n if (nutrient in nutritionalInfoCount) {\n nutritionalInfoCount[nutrient] += 1;\n } else {\n nutritionalInfoCount[nutrient] = 1;\n }\n });\n});\n"
},
{
"answer_id": 74364595,
"author": "Ilê Caian",
"author_id": 19330762,
"author_profile": "https://Stackoverflow.com/users/19330762",
"pm_score": -1,
"selected": false,
"text": ".reduce()"
},
{
"answer_id": 74364754,
"author": "Keith",
"author_id": 6870228,
"author_profile": "https://Stackoverflow.com/users/6870228",
"pm_score": 1,
"selected": false,
"text": "Array.reduce"
},
{
"answer_id": 74364836,
"author": "Harsh Srivastava",
"author_id": 9099045,
"author_profile": "https://Stackoverflow.com/users/9099045",
"pm_score": 0,
"selected": false,
"text": " export default function App() {\n const foodMenu = [\n { id: 1, name: \"pasta\", nutritionalInfo: [\"ve\", \"veg\", \"gf\"] },\n { id: 2, name: \"pizza\", nutritionalInfo: [\"gf\", \"veg\"] },\n { id: 3, name: \"applePie\", nutritionalInfo: [\"nuts\"] }\n ];\n const nutrientContent = {};\n foodMenu.forEach((foodMenu) => {\n foodMenu.nutritionalInfo.forEach(\n (nutritionalInfo) =>\n (nutrientContent[nutritionalInfo] =\n nutritionalInfo in nutrientContent\n ? nutrientContent[nutritionalInfo] + 1\n : 1)\n );\n });\n return (\n <div className=\"App\">\n {Object.keys(nutrientContent).map(\n (val) => val + \":\" + nutrientContent[val] + \", \"\n )}\n </div>\n );\n}\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5111917/"
] |
74,364,315 | <p>I am working on a mathematics project with a persistent need of extracting a canonical "basis" out of a type, so I defined the following type class.</p>
<pre class="lang-hs prettyprint-override"><code>class Basis a where
getBasis :: Int -> [a]
</code></pre>
<p>And I want to use this basis in a separate function:</p>
<pre class="lang-hs prettyprint-override"><code>foo :: (Basis a) => Int -> (a -> b) -> IO ()
foo n f = do
let theBasis = getBasis n
undefined
-- Do some stuff with the basis using the function f.
-- theBasis should have type [a].
</code></pre>
<p>However this fails to type check, yielding an error of the form <code>Could not deduce (Basis a0) arising from the use of 'getBasis' from the context: Basis a</code>.</p>
<p>I tried to help the typechecker by explicitly writing the expected type:</p>
<pre class="lang-hs prettyprint-override"><code>foo n f = do
let theBasis = (getBasis n) :: [a]
undefined
</code></pre>
<p>But the error persists, and moving the type annotation to different terms in that line does not fix the error.</p>
<p>How can I tell the typechecker that I want the type of <code>getBasis n</code> to be the same <code>a</code> appearing in the signature of <code>foo</code>?</p>
| [
{
"answer_id": 74364479,
"author": "lsmor",
"author_id": 9271266,
"author_profile": "https://Stackoverflow.com/users/9271266",
"pm_score": 0,
"selected": false,
"text": "ScopedTypeVariables"
},
{
"answer_id": 74364485,
"author": "Fyodor Soikin",
"author_id": 180286,
"author_profile": "https://Stackoverflow.com/users/180286",
"pm_score": 2,
"selected": false,
"text": "theBasis"
},
{
"answer_id": 74364488,
"author": "Cubic",
"author_id": 938694,
"author_profile": "https://Stackoverflow.com/users/938694",
"pm_score": 4,
"selected": true,
"text": "a"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9302269/"
] |
74,364,316 | <p>I am trying to create unit test for configuration class for connection class. Here is my config class for connection:</p>
<pre><code>@Configuration
public class JmsMessageGatewayConnectionConfig {
@Bean
public JmsMessageGatewayConnection jmsMessageGatewayConnection (final JmsMessageGatewayProperties jmsConfig) throws JMSException {
return new JmsMessageGatewayConnection(jmsConfig, cachingConnectionFactory(jmsConfig));
}
private CachingConnectionFactory cachingConnectionFactory(final JmsMessageGatewayProperties jmsConfig) {
CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory();
cachingConnectionFactory.setTargetConnectionFactory(jmsConnectionFactory(jmsConfig));
cachingConnectionFactory.resetConnection();
return cachingConnectionFactory;
}
private JmsConnectionFactory jmsConnectionFactory(final JmsMessageGatewayProperties jmsConfig) {
JmsConnectionFactory jmsConnectionFactory =
new JmsConnectionFactory(jmsConfig.getUsername(), jmsConfig.getPassword(), jmsConfig.getRemoteUri());
jmsConnectionFactory.setReceiveLocalOnly(true);
return jmsConnectionFactory;
}
@Bean
@ConfigurationProperties(prefix = "jms")
public JmsMessageGatewayProperties messageGatewayProperties() {
return new JmsMessageGatewayProperties();
}
}
</code></pre>
<p>And here is JmsMessageGatewayProperties class:</p>
<pre><code>public class JmsMessageGatewayProperties {
private String remoteUri;
private String username;
private String password;
private boolean messagePersistent;
private Integer forceDetachedRetryLimit = 1;
public String getRemoteUri() {
return remoteUri;
}
public void setRemoteUri(final String remoteUri) {
this.remoteUri = remoteUri;
}
public String getUsername() {
return username;
}
public void setUsername(final String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(final String password) {
this.password = password;
}
public boolean isMessagePersistent() {
return messagePersistent;
}
public void setMessagePersistent(final boolean messagePersistent) {
this.messagePersistent = messagePersistent;
}
public Integer getForceDetachedRetryLimit() {
return forceDetachedRetryLimit;
}
public void setForceDetachedRetryLimit(final Integer forceDetachedRetryLimit) {
this.forceDetachedRetryLimit = forceDetachedRetryLimit;
}
}
</code></pre>
<p>And here is my test class:</p>
<pre><code>@RunWith(SpringRunner.class)
@ContextConfiguration(classes = { JmsMessageGatewayConnectionConfig.class})
@TestPropertySource(locations = "classpath:camel.properties")
public class JmsMessageGatewayConnectionConfigTest {
@Autowired
private JmsMessageGatewayConnection jmsMessageGatewayConnection;
@Test
public void jmsMessageGatewayConnectionConfigTest() {
Assert.assertNotNull(jmsMessageGatewayConnection);
}
}
</code></pre>
<p>Test fails with <code>Invalid URI: cannot be null or empty</code>. I think I understand that properties in <code>jmsConfig</code> are null via checking it in debug mode. I did update my camel.properties to have the properties like this:</p>
<pre><code>jms.remoteUri=vm://localhost:61616
jms.username=username
jms.password=password
</code></pre>
<p>I am not sure what I am missing here. Why are the properties inside of JmsMessageGatewayProperties null even though it has the object?</p>
| [
{
"answer_id": 74364479,
"author": "lsmor",
"author_id": 9271266,
"author_profile": "https://Stackoverflow.com/users/9271266",
"pm_score": 0,
"selected": false,
"text": "ScopedTypeVariables"
},
{
"answer_id": 74364485,
"author": "Fyodor Soikin",
"author_id": 180286,
"author_profile": "https://Stackoverflow.com/users/180286",
"pm_score": 2,
"selected": false,
"text": "theBasis"
},
{
"answer_id": 74364488,
"author": "Cubic",
"author_id": 938694,
"author_profile": "https://Stackoverflow.com/users/938694",
"pm_score": 4,
"selected": true,
"text": "a"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7259705/"
] |
74,364,334 | <p>I need to change a variable each time the function is called.
My function counts the number of time this function has been called:</p>
<pre><code>def score_chart():
num_of_charts=+ 1
return num_of_charts
</code></pre>
<p>At the beginning <code>num_of_charts</code> equals 0. Then I call the function and re-save <code>num_of_charts</code> to be equal 1.
But if I call it second time, the result is still 1, while I m expecting to get 2.</p>
<pre><code>num_of_charts = 0
num_of_charts = score_chart()
print (num_of_charts)
num_of_charts = score_chart()
print(num_of_charts)
1
1
</code></pre>
<p>Could you please help</p>
| [
{
"answer_id": 74364385,
"author": "Barmar",
"author_id": 1491895,
"author_profile": "https://Stackoverflow.com/users/1491895",
"pm_score": 1,
"selected": false,
"text": "def score_chart(num):\n return num + 1\n\nnum_of_charts = 0\nnum_of_charts = score_chart(num_of_charts)\nprint(num_of_charts)\nnum_of_charts = score_chart(num_of_charts)\nprint(num_of_charts)\n"
},
{
"answer_id": 74364410,
"author": "BokiX",
"author_id": 16843389,
"author_profile": "https://Stackoverflow.com/users/16843389",
"pm_score": 0,
"selected": false,
"text": "def score_chart():\n global num_of_charts\n num_of_charts += 1\n"
},
{
"answer_id": 74365341,
"author": "user19077881",
"author_id": 19077881,
"author_profile": "https://Stackoverflow.com/users/19077881",
"pm_score": 1,
"selected": false,
"text": "def call_counter(func):\n def keeper():\n keeper.calls += 1\n return func()\n keeper.calls = 0\n return keeper\n\n@call_counter\ndef score_chart():\n pass # function could do anything required\n\nfor i in range(4):\n score_chart()\nprint(score_chart.calls) \n"
},
{
"answer_id": 74365394,
"author": "Claudio",
"author_id": 7711283,
"author_profile": "https://Stackoverflow.com/users/7711283",
"pm_score": 1,
"selected": true,
"text": "def score_chart():\n num_of_charts=+ 1\n return num_of_charts\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18775708/"
] |
74,364,357 | <p>I have a data.table <code>x</code> with approx. 2M rows and 2 columns: <code>entry</code> and <code>code</code>. <code>entry</code> contains character values that <em>might</em> be repeated elsewhere in <code>entry</code> in lowered form. Also, all-lower entries exist, that do not have a non-lowered form. Each row in <code>x</code> has a unique code in column <code>code</code>. I've created a reproducible example with only 6 rows.</p>
<pre><code>library(data.table)
x <- data.table(entry = c("Aaa", "Bbb", "Ccc", "aaa", "bbb", "ddd"),
code = c(1, 2, 3, 4, 5, 6))
x
entry code
1: Aaa 1
2: Bbb 2
3: Ccc 3
4: aaa 4
5: bbb 5
6: ddd 6
</code></pre>
<p>As you can see, <code>Aaa</code> and <code>Bbb</code> also come with their lowered "counterparts" <code>aaa</code> and <code>bbb</code>. <code>Ccc</code> does not have a lowered form and <code>ddd</code> does not have a non-lowered form.</p>
<p>I now want to assign a new column <code>low_code</code> which holds the code for the lowered counterpart if there is one. If not, the code should remain the same. This is what my goal would look like in this example:</p>
<pre><code> entry code low_code
1: Aaa 1 4
2: Bbb 2 5
3: Ccc 3 3
4: aaa 4 4
5: bbb 5 5
6: ddd 6 6
</code></pre>
<p>As you can see, the codes for <code>aaa</code> and <code>bbb</code> get assigned for <code>Aaa</code> and <code>Bbb</code>. For <code>Ccc</code>, there is no lowered version, so the code remains the same.</p>
<p>What I have done so far is this (and this works):</p>
<pre><code>x$low_code <- sapply(x$entry, USE.NAMES = F, FUN = function (e) {
low_e <- tolower(e)
ret <- x[x$entry == low_e,][["code"]]
if (length(ret) == 0) { # If no low entry is found...
ret <- x[x$entry == e,][["code"]] # ...return original code
}
stopifnot(length(ret) %in% c(0, 1)) # Too many return values (should never happen)
ret
})
</code></pre>
<p>However, it is extremely slow for my original data.table with more than 2 million rows. I suspect this is due to the indexing for every single entry (<code>e</code> in the code above).</p>
<p>I would be <em>very</em> surprised if there isn't a considerably faster option (maybe leveraging data.table syntax) but I am out of ideas. Any help is much appreciated - if you have the time, please also explain your solution with a few words so I can learn from it. As always, I hope that I didn't overlook any answers solving a similar problem. Thank you so much!</p>
| [
{
"answer_id": 74364578,
"author": "sindri_baldur",
"author_id": 4552295,
"author_profile": "https://Stackoverflow.com/users/4552295",
"pm_score": 3,
"selected": true,
"text": "rows = grep(\"^[A-Z]\", x$entry)\nx[(rows), lentry := tolower(entry)]\nx[(rows), low_code := x[(-rows)][.SD, on = .(entry = lentry), x.code]]\nrm(rows)\nx[, lentry := NULL]\nx[is.na(low_code), low_code := code]\n\n# entry code low_code\n# <char> <num> <num>\n# 1: Aaa 1 4\n# 2: Bbb 2 5\n# 3: Ccc 3 3\n# 4: aaa 4 4\n# 5: bbb 5 5\n# 6: ddd 6 6\n"
},
{
"answer_id": 74364613,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 2,
"selected": false,
"text": "library(data.table)\nx <- data.table(entry = c(\"Aaa\", \"Bbb\", \"Ccc\", \"aaa\", \"bbb\", \"ddd\"), code = c(1, 2, 3, 4, 5, 6))\nx[, low_entry := tolower(entry)\n ][entry == low_entry, low_entry := NA]\nx[x, low_code := i.code, on = .(low_entry == entry)\n ][, low_entry := NULL\n ][, low_code := fcoalesce(low_code, code)]\nx\n# entry code low_code\n# <char> <num> <num>\n# 1: Aaa 1 4\n# 2: Bbb 2 5\n# 3: Ccc 3 3\n# 4: aaa 4 4\n# 5: bbb 5 5\n# 6: ddd 6 6\n"
},
{
"answer_id": 74364673,
"author": "zx8754",
"author_id": 680068,
"author_profile": "https://Stackoverflow.com/users/680068",
"pm_score": 1,
"selected": false,
"text": "merge(x[, .(rn = 1:.N, entry_low = tolower(entry), entry, code) ],\n x[ tolower(entry) == entry, .(entry_low = entry, code_low = code)], \n by = \"entry_low\", all.x = TRUE\n )[ is.na(code_low), code_low := code \n ][ order(rn), .(entry, code, code_low)]\n# entry code code_low\n# 1: Aaa 1 4\n# 2: Bbb 2 5\n# 3: Ccc 3 3\n# 4: aaa 4 4\n# 5: bbb 5 5\n# 6: ddd 6 6\n"
},
{
"answer_id": 74365990,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 1,
"selected": false,
"text": "tolower"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2433233/"
] |
74,364,362 | <p>It is possible to make ONLY the first character set to uppercase with css? (e.g: :first-char selector)</p>
<p>in short: if the <strong>text start with a number, do not apply the conversion (capitalize)</strong> afterwards</p>
<pre><code>table.evenOdd tr td::first-letter{
text-transform:capitalize;
}
</code></pre>
<p>the table</p>
<pre><code><table class="evenOdd">
<tr>
<td style="width: 50%">question 1</td>
<td><b>100 mm</b></td>
</tr>
<tr>
<td>question 2</td>
<td><b>Success</b></td>
</tr>
<tr>
<td>question 3</td>
<td><b>42 kilometer</b></td>
</tr>
</table>
</code></pre>
<p>and the result is <br />
Question 1 | 100 <strong>M</strong>m -- nok i want mm<br />
Question 2 | <strong>S</strong>uccess -- ok<br />
Question 3 | 42 <strong>K</strong>ilometer -- nok i want kilometer<br /></p>
| [
{
"answer_id": 74364433,
"author": "cameronErasmus",
"author_id": 19525398,
"author_profile": "https://Stackoverflow.com/users/19525398",
"pm_score": 0,
"selected": false,
"text": "span::first-letter {\n text-transform: uppercase;\n}\n"
},
{
"answer_id": 74364498,
"author": "Anh Le Hoang",
"author_id": 16315750,
"author_profile": "https://Stackoverflow.com/users/16315750",
"pm_score": 0,
"selected": false,
"text": ".uppercase {\n display: inline-block; \n text-transform: lowercase;\n}\n\n.uppercase:first-letter {\n text-transform: uppercase\n}"
},
{
"answer_id": 74364512,
"author": "DBS",
"author_id": 1650337,
"author_profile": "https://Stackoverflow.com/users/1650337",
"pm_score": 2,
"selected": false,
"text": "::first-letter"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7461847/"
] |
74,364,455 | <p><a href="https://i.stack.imgur.com/D5asK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/D5asK.png" alt="enter image description here" /></a></p>
<p><strong>html page</strong></p>
<pre class="lang-html prettyprint-override"><code> <div class="card pos-card col-6">
<div class="card-body">
<!--Import All Product-->
<div>
<div
class="row"
id="allProduct"
style="
position: relative;
overflow: scroll;
width: 620px;
height: 520px;
"
></div>
</div>
</div>
</div>
</code></pre>
<p><strong>js file</strong></p>
<pre class="lang-js prettyprint-override"><code>const fetchItem = () => {
connection.query(
"SELECT * FROM `products`",
function (error, results, fields) {
if (error) throw error;
let item = results;
for (let i = 0; i < item.length; i++) {
let product =
'<div class="col-md-3 itemId" id="btn_add_item' +
`${item[i].pId}` +
'" tabindex="1" onclick="openQtyModal(' +
` ${item[i].pId}` +
')">';
product +=
' <div id="' +
`${item[i].pId}` +
'" class="card img-card productItem' +
i +
'" >';
product +=
'<img class="card-img-top img-fluid" src="./assets/images/product/' +
`${item[i].pImage}` +
'" width = "40px" height="40px" alt="Card image cap">';
product += '<div class="card-body">';
product +=
'<p class="card-text text-center">' + `${item[i].pName}` + "</p>";
product +=
' <p class="card-text text-center">' + `${format_currency}` + "</p>";
product += " </div>";
product += " </div>";
product += " </div>";
$("#allProduct").append(product);
}
}
);
};
</code></pre>
<p>Here I attached a picture . It has some items with pics it heights and widths are not same. just I want to set it as same sizes wth images and whole item square.. please help me to solve it. above I mentioned the code..</p>
| [
{
"answer_id": 74365054,
"author": "Arleigh Hix",
"author_id": 6127393,
"author_profile": "https://Stackoverflow.com/users/6127393",
"pm_score": 1,
"selected": false,
"text": ".h-100"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20355754/"
] |
74,364,465 | <p>Using flask, I'm trying to send a file to the user on clicking a button in UI using send_from_directory function. It used to work fine. I wanted to change the repo and since changing it, I'm no more able to download the file. On looking at the supervisor log, I see this:</p>
<pre><code>[9617] [ERROR] Error handling request
Traceback (most recent call last):
File "path_to_file/venv/lib/python3.4/site-packages/gunicorn/workers/sync.py", line 182, in handle_request
resp.write_file(respiter)
File "path_to_file/venv/lib/python3.4/site-packages/gunicorn/http/wsgi.py", line 385, in write_file
if not self.sendfile(respiter):
File "path_to_file/venv/lib/python3.4/site-packages/gunicorn/http/wsgi.py", line 375, in sendfile
self.sock.sendfile(respiter.filelike, count=nbytes)
AttributeError: 'socket' object has no attribute 'sendfile'
</code></pre>
<p>In the same repo, this works fine locally. But when trying in remote server using the gunicorn + supervisor + nginx setup, I get the above error message. I do get 200 Ok response in the application log file. Spent a lot of time trying to fix but without success.</p>
<p>Also, the notable difference between the working app between the previous repo and the non-working current repo is the python version. Previous: python2.7, Current: python3.4</p>
| [
{
"answer_id": 74365054,
"author": "Arleigh Hix",
"author_id": 6127393,
"author_profile": "https://Stackoverflow.com/users/6127393",
"pm_score": 1,
"selected": false,
"text": ".h-100"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5304538/"
] |
74,364,470 | <p>If we look at <a href="https://docs.python.org/3/library/contextlib.html#single-use-reusable-and-reentrant-context-managers" rel="nofollow noreferrer">python docs</a> it states:</p>
<blockquote>
<p>Most context managers are written in a way that means they can only be used effectively in a with statement once. These single use context managers must be created afresh each time they’re used - attempting to use them a second time will trigger an exception or otherwise not work correctly.</p>
<p>This common limitation means that it is generally advisable to create context managers directly in the header of the with statement where they are used (as shown in all of the usage examples above).</p>
</blockquote>
<p>Yet, <a href="https://docs.python.org/3/library/contextlib.html#using-a-context-manager-as-a-function-decorator" rel="nofollow noreferrer">the example most commonly shared for creating context managers inside classes is</a>:</p>
<pre class="lang-py prettyprint-override"><code>
from contextlib import ContextDecorator
import logging
logging.basicConfig(level=logging.INFO)
class track_entry_and_exit(ContextDecorator):
def __init__(self, name):
self.name = name
def __enter__(self):
logging.info('Entering: %s', self.name)
def __exit__(self, exc_type, exc, exc_tb):
logging.info('Exiting: %s', self.name)
</code></pre>
<p>But, when I instantiate this class, I can pass it several times to a with statement:</p>
<pre class="lang-py prettyprint-override"><code>In [8]: test_context = track_entry_and_exit('test')
In [9]: with test_context:
...: pass
...:
INFO:root:Entering: test
INFO:root:Exiting: test
In [10]: with test_context:
...: pass
...:
INFO:root:Entering: test
INFO:root:Exiting: test
</code></pre>
<p>How can I create a class that fails on the second call to the with statement?</p>
| [
{
"answer_id": 74365050,
"author": "S.B",
"author_id": 13944524,
"author_profile": "https://Stackoverflow.com/users/13944524",
"pm_score": 1,
"selected": false,
"text": "from functools import wraps\n\n\nclass MultipleCallToCM(Exception):\n pass\n\n\ndef single_use(cls):\n if not (\"__enter__\" in vars(cls) and \"__exit__\" in vars(cls)):\n raise TypeError(f\"{cls} is not a Context Manager.\")\n\n org_new = cls.__new__\n @wraps(org_new)\n def new(clss, *args, **kwargs):\n instance = org_new(clss)\n instance._called = False\n return instance\n cls.__new__ = new\n\n org_enter = cls.__enter__\n @wraps(org_enter)\n def enter(self):\n if self._called:\n raise MultipleCallToCM(\"You can't call this CM twice!\")\n self._called = True\n return org_enter(self)\n\n cls.__enter__ = enter\n return cls\n\n\n@single_use\nclass CM:\n def __enter__(self):\n print(\"Enter to the CM\")\n\n def __exit__(self, exc_type, exc_value, exc_tb):\n print(\"Exit from the CM\")\n\n\nwith CM():\n print(\"Inside.\")\nprint(\"-----------------------------------\")\nwith CM():\n print(\"Inside.\")\nprint(\"-----------------------------------\")\ncm = CM()\nwith cm:\n print(\"Inside.\")\nprint(\"-----------------------------------\")\nwith cm:\n print(\"Inside.\")\n"
},
{
"answer_id": 74365868,
"author": "mkrieger1",
"author_id": 4621513,
"author_profile": "https://Stackoverflow.com/users/4621513",
"pm_score": 0,
"selected": false,
"text": ">>> from contextlib import contextmanager\n>>> @contextmanager\n... def track_entry_and_exit(name):\n... print('Entering', name)\n... yield\n... print('Exiting', name)\n... \n>>> c = track_entry_and_exit('test')\n>>> with c:\n... pass\n... \nEntering test\nExiting test\n>>> with c:\n... pass\n... \nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"/usr/lib/python3.9/contextlib.py\", line 115, in __enter__\n del self.args, self.kwds, self.func\nAttributeError: args\n"
},
{
"answer_id": 74368081,
"author": "KonstantinTogoi",
"author_id": 2896441,
"author_profile": "https://Stackoverflow.com/users/2896441",
"pm_score": 0,
"selected": false,
"text": "class Iterable:\n \"\"\"Iterable that can be iterated only once.\"\"\"\n\n def __init__(self, name):\n self.name = name\n self.it = iter([self])\n\n def __iter__(self):\n # code to acquire resource\n print('enter')\n yield next(self.it)\n print('exit')\n # code to release resource\n\n def __repr__(self):\n return f'{self.__class__.__name__}({self.name})'\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4263284/"
] |
74,364,487 | <p>in order to programmatically retrive some <strong>AppTraces</strong> and <strong>AppExceptions</strong> info from an Azure <strong>Application Insights</strong> Logs resource, we followed the instructions included in the following article advicing to adopt the new <strong>Azure Monitor Query</strong> client library for .NET to fulfill the purpose.</p>
<p><a href="https://learn.microsoft.com/it-it/dotnet/api/overview/azure/Monitor.Query-readme?view=azure-dotnet" rel="nofollow noreferrer">https://learn.microsoft.com/it-it/dotnet/api/overview/azure/Monitor.Query-readme?view=azure-dotnet</a></p>
<p>Strictly following the above article instructions (and using the <strong>DefaultAzureCredential</strong> object to authenticate), we managed to get the client library's <strong>LogsQueryClient</strong> object working fine in the local version of the developed web api (ASP .NET Core 6.0). And so, locally we are eable to fetch the logs info we need.
But once we published the web api on the Cloud (under the same Azure subscription of the Application Insights target resource) we started to get the following error:</p>
<ul>
<li><strong>Message</strong>: The provided credentials have insufficient access to perform the requested operation</li>
<li><strong>Status</strong>: 403 (Forbidden)</li>
<li><strong>ErrorCode</strong>: InsufficientAccessError</li>
</ul>
<p><strong>N.B.</strong>
Surprisingly we didn't find any thread explaining, step by step how to fix the problem with specific reference to the new Azure Monitor Query client library.</p>
<p>To fix the issue, we tried replacing the class <strong>DefaultAzureCredential</strong> with the class <strong>ClientSecretCredential</strong> generating and assigning it a new client secret.</p>
<p>Here are the details concerning the steps we followed to implement the ClientSecretCredentials.
In particular, we have:</p>
<ol>
<li>Setup a new <strong>Azure AD Application</strong>.</li>
<li>Assigned it the required permissions ==> <strong>Data.Read</strong> (Read Log Analytics data - Granted from Admin).</li>
<li>Assinged to the Registered App (AAD Application) the <strong>Reader Role</strong> from the Application Insights Resource's Access control (IAM) section of the Azure Portal.</li>
<li>Created a new <strong>client secret</strong> for the AAD Application.</li>
<li>Created a new Azure <strong>Web API</strong>, on witch we Installed the <strong>Azure Monitor Query</strong> client library for .NET.</li>
<li>To retrive Logs data, we programmatically istantiated a new <strong>Azure.Identity.ClientSecretCredential</strong> object, assigning it the right tenantId, the client (application) ID of the AAD Application and the client secret previously generated for the App Registration.</li>
<li>In the Program.cs file of the web api we created a singleton instance of the class <strong>LogsQueryClient</strong> assigning it the above <strong>ClientSecretCredential</strong> object.</li>
<li>And finally we invoked the <strong>QueryWorkspaceAsync</strong> method of the class LogsQueryClient, passing it the <strong>WorkSpaceId</strong> of the Application Insights Resource (whom logs have to be read) and the query to retrive.</li>
</ol>
<p>Unfortunately, replacing the class DefaultAzureCredential with ClientSecretCredential didn't work and the error message keeps to be the same.</p>
<p><strong>N.B.</strong></p>
<ul>
<li>The <strong>AAD User Type</strong> of the user who: developed and released the web api, registered the new Azure AD Application and granted it the necessary permissions is "<strong>Member</strong>".</li>
<li>The above user, refers to the same tenant id as the resources he managed in the above steps (Web Api, AAD Application etc).</li>
<li>During the release process of the web api, a new API Management service was specifically created by the same user releasing the app.</li>
</ul>
<p>Here are the code snippets:</p>
<p><strong>Program.cs</strong></p>
<pre><code>builder.Services.AddAzureClients(builder =>
{
static LogsQueryClient func(LogsQueryClientOptions options)
{
options.Retry.Mode = Azure.Core.RetryMode.Exponential;
options.Retry.MaxRetries = 5;
var csc = new ClientSecretCredential(tenantId, clientId, clientSecret);
return new LogsQueryClient(csc, options);
}
builder.AddClient<LogsQueryClient, LogsQueryClientOptions>(func);
var credentials = new ClientSecretCredential(tenantId, clientId, clientSecret);
builder.UseCredential(credentials);
});
</code></pre>
<p><strong>Controller.cs</strong> (get <strong>logsQueryClient</strong> through dependency injection)</p>
<pre><code>Response<LogsQueryResult> response = await logsQueryClient.QueryWorkspaceAsync(workSpaceId, query);
</code></pre>
| [
{
"answer_id": 74365050,
"author": "S.B",
"author_id": 13944524,
"author_profile": "https://Stackoverflow.com/users/13944524",
"pm_score": 1,
"selected": false,
"text": "from functools import wraps\n\n\nclass MultipleCallToCM(Exception):\n pass\n\n\ndef single_use(cls):\n if not (\"__enter__\" in vars(cls) and \"__exit__\" in vars(cls)):\n raise TypeError(f\"{cls} is not a Context Manager.\")\n\n org_new = cls.__new__\n @wraps(org_new)\n def new(clss, *args, **kwargs):\n instance = org_new(clss)\n instance._called = False\n return instance\n cls.__new__ = new\n\n org_enter = cls.__enter__\n @wraps(org_enter)\n def enter(self):\n if self._called:\n raise MultipleCallToCM(\"You can't call this CM twice!\")\n self._called = True\n return org_enter(self)\n\n cls.__enter__ = enter\n return cls\n\n\n@single_use\nclass CM:\n def __enter__(self):\n print(\"Enter to the CM\")\n\n def __exit__(self, exc_type, exc_value, exc_tb):\n print(\"Exit from the CM\")\n\n\nwith CM():\n print(\"Inside.\")\nprint(\"-----------------------------------\")\nwith CM():\n print(\"Inside.\")\nprint(\"-----------------------------------\")\ncm = CM()\nwith cm:\n print(\"Inside.\")\nprint(\"-----------------------------------\")\nwith cm:\n print(\"Inside.\")\n"
},
{
"answer_id": 74365868,
"author": "mkrieger1",
"author_id": 4621513,
"author_profile": "https://Stackoverflow.com/users/4621513",
"pm_score": 0,
"selected": false,
"text": ">>> from contextlib import contextmanager\n>>> @contextmanager\n... def track_entry_and_exit(name):\n... print('Entering', name)\n... yield\n... print('Exiting', name)\n... \n>>> c = track_entry_and_exit('test')\n>>> with c:\n... pass\n... \nEntering test\nExiting test\n>>> with c:\n... pass\n... \nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"/usr/lib/python3.9/contextlib.py\", line 115, in __enter__\n del self.args, self.kwds, self.func\nAttributeError: args\n"
},
{
"answer_id": 74368081,
"author": "KonstantinTogoi",
"author_id": 2896441,
"author_profile": "https://Stackoverflow.com/users/2896441",
"pm_score": 0,
"selected": false,
"text": "class Iterable:\n \"\"\"Iterable that can be iterated only once.\"\"\"\n\n def __init__(self, name):\n self.name = name\n self.it = iter([self])\n\n def __iter__(self):\n # code to acquire resource\n print('enter')\n yield next(self.it)\n print('exit')\n # code to release resource\n\n def __repr__(self):\n return f'{self.__class__.__name__}({self.name})'\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10734697/"
] |
74,364,507 | <p>I have two Nginx servers acting as reverse proxies for nodejs servers running on ports 5000 and 5001.
The one that is running on port 5000 is for normal form upload
The other one that is running on port 5001 is for uploading images
On the client side, what I've done is after filling out the form (title, description, and image) by the user, the image is uploaded to the image server first and the imageURL, title, and description are uploaded to the normal web server then.</p>
<p><strong>The Problem</strong></p>
<p>When the client fills out the form and clicks on upload if the image upload works then upload to the normal server fails or if normal server upload works then upload to the image server fails.
<em>The error is the following one:</em> (This could for either of them)</p>
<blockquote>
<p>Access to XMLHttpRequest at 'https://myserver.com/imagev2api/profile-upload-single' from origin 'https://blogs.vercel.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.</p>
</blockquote>
<p><strong>Note:</strong> I've used <code>app.use(cors())</code> on both servers (image and normal server)</p>
<p><strong>Here's both nginx server configurations</strong></p>
<p><strong>Image Server</strong></p>
<pre><code>upstream imageserver.com {
server 127.0.0.1:5001;
keepalive 600;
}
server {
server_name imageserver.com;
error_log /var/www/log/imagserver.com.error;
access_log /var/www/log/imagserver.com.access;
location / {
proxy_pass http://imageserver.com;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
# fastcgi_split_path_info ^(.+\.php)(/.+)$;
}
listen 443 ssl http2; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/linoxcloud.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/linoxcloud.com/privkey.pem; # managed by Certbot
ssl_protocols TLSv1.2 TLSv1.3 SSLv2 SSLv3;
ssl_session_cache shared:SSL:5m;
ssl_session_timeout 10m;
ssl_session_tickets off;
}
server {
if ($host = imageserver.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80;
server_name imageserver.com;
}
</code></pre>
<p>Normal Server</p>
<pre><code>upstream normalserver.com {
server 127.0.0.1:5000;
keepalive 600;
}
server {
server_name normalserver.com;
error_log /var/www/log/normalserver.com.error;
access_log /var/www/log/normalserver.com.access;
location / {
proxy_pass http://normalserver.com;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
listen 443 ssl http2; # managed by Certbot
ssl_certificate ...; # managed by Certbot
ssl_certificate_key ...; # managed by Certbot
ssl_protocols TLSv1.2 TLSv1.3 SSLv2 SSLv3;
ssl_session_cache shared:SSL:5m;
ssl_session_timeout 10m;
ssl_session_tickets off;
}
server {
if ($host = normalserver.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80;
server_name normalserver.com;
}
</code></pre>
<p>I've been trying to overcome this problem for some period of time by trying literally everything.
Reference: <a href="https://stackoverflow.com/questions/47230317/two-nginx-servers-one-passing-cors-issue">Two NGINX servers one passing CORS issue</a> (but this doesn't provide any insights into what the problem and solution is)</p>
<p>Any possible fixes, please?</p>
| [
{
"answer_id": 74365050,
"author": "S.B",
"author_id": 13944524,
"author_profile": "https://Stackoverflow.com/users/13944524",
"pm_score": 1,
"selected": false,
"text": "from functools import wraps\n\n\nclass MultipleCallToCM(Exception):\n pass\n\n\ndef single_use(cls):\n if not (\"__enter__\" in vars(cls) and \"__exit__\" in vars(cls)):\n raise TypeError(f\"{cls} is not a Context Manager.\")\n\n org_new = cls.__new__\n @wraps(org_new)\n def new(clss, *args, **kwargs):\n instance = org_new(clss)\n instance._called = False\n return instance\n cls.__new__ = new\n\n org_enter = cls.__enter__\n @wraps(org_enter)\n def enter(self):\n if self._called:\n raise MultipleCallToCM(\"You can't call this CM twice!\")\n self._called = True\n return org_enter(self)\n\n cls.__enter__ = enter\n return cls\n\n\n@single_use\nclass CM:\n def __enter__(self):\n print(\"Enter to the CM\")\n\n def __exit__(self, exc_type, exc_value, exc_tb):\n print(\"Exit from the CM\")\n\n\nwith CM():\n print(\"Inside.\")\nprint(\"-----------------------------------\")\nwith CM():\n print(\"Inside.\")\nprint(\"-----------------------------------\")\ncm = CM()\nwith cm:\n print(\"Inside.\")\nprint(\"-----------------------------------\")\nwith cm:\n print(\"Inside.\")\n"
},
{
"answer_id": 74365868,
"author": "mkrieger1",
"author_id": 4621513,
"author_profile": "https://Stackoverflow.com/users/4621513",
"pm_score": 0,
"selected": false,
"text": ">>> from contextlib import contextmanager\n>>> @contextmanager\n... def track_entry_and_exit(name):\n... print('Entering', name)\n... yield\n... print('Exiting', name)\n... \n>>> c = track_entry_and_exit('test')\n>>> with c:\n... pass\n... \nEntering test\nExiting test\n>>> with c:\n... pass\n... \nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"/usr/lib/python3.9/contextlib.py\", line 115, in __enter__\n del self.args, self.kwds, self.func\nAttributeError: args\n"
},
{
"answer_id": 74368081,
"author": "KonstantinTogoi",
"author_id": 2896441,
"author_profile": "https://Stackoverflow.com/users/2896441",
"pm_score": 0,
"selected": false,
"text": "class Iterable:\n \"\"\"Iterable that can be iterated only once.\"\"\"\n\n def __init__(self, name):\n self.name = name\n self.it = iter([self])\n\n def __iter__(self):\n # code to acquire resource\n print('enter')\n yield next(self.it)\n print('exit')\n # code to release resource\n\n def __repr__(self):\n return f'{self.__class__.__name__}({self.name})'\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18832663/"
] |
74,364,551 | <p>I'm getting a response from an API and decoding the response like this:</p>
<pre><code>struct MyStuff: Codable {
let name: String
let quantity: Int
let location: String
}
</code></pre>
<p>And I have instance an Entity to map <code>MyStuff</code>:</p>
<pre><code>@objc(Stuff)
public class Stuff: NSManagedObject {
}
extension Stuff {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Stuff> {
return NSFetchRequest<Stuff>(entityName: "Stuff")
}
@NSManaged public var name: String?
@NSManaged public var quantity: Int64
@NSManaged public var location: String?
}
</code></pre>
<p>My question is, when I have the response of type MyStuff there is a way to loop thru the keys and map the values to core data?</p>
<p>for example:</p>
<pre><code>let myStuff = MyStuff(name: "table", quantity: 1, location: "kitchen")
let myStuff = MyStuff(name: "table", quantity: 1, location: "kitchen")
for chidren in Mirror(reflecting: myStuff).children {
print(chidren.label)
print(chidren.value)
/*
insert values to core data
*/
}
</code></pre>
<p>I'll really appreciate your help</p>
| [
{
"answer_id": 74365004,
"author": "vadian",
"author_id": 5044042,
"author_profile": "https://Stackoverflow.com/users/5044042",
"pm_score": 3,
"selected": true,
"text": "Decodable"
},
{
"answer_id": 74365142,
"author": "SPatel",
"author_id": 6630644,
"author_profile": "https://Stackoverflow.com/users/6630644",
"pm_score": 0,
"selected": false,
"text": "struct MyStuff: Codable {\n let name: String\n let quantity: Int\n let location: String\n}\n \nextension Encodable {\n func toString() -> String? {\n if let config = try? JSONEncoder().encode(self) {\n return String(data: config, encoding: .utf8)\n }\n return .none\n }\n}\n \nextension Decodable {\n static func map(JSONString: String) -> Self? {\n try? JSONDecoder().decode(Self.self, from: JSONString.data(using: .utf8) ?? .init())\n }\n}\n \n \n@objc(Stuff)\npublic class Stuff: NSManagedObject {\n}\n \n// Entity with single field (no field base query support)\nextension Stuff {\n @nonobjc public class func fetchRequest() -> NSFetchRequest<Stuff> {\n return NSFetchRequest<Stuff>(entityName: \"Stuff\")\n }\n @NSManaged public var myStuffRawJSON: String?\n \n func mapToMyStuff() -> MyStuff? {\n MyStuff.map(JSONString: myStuffRawJSON ?? \"\")\n }\n}\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2924482/"
] |
74,364,558 | <p>I have a pandas dataframe in the following format.</p>
<pre><code>| id | name | last_name | address | x | y | x_list | y_list|
| -- | ------- | --------- | ------- | ------- | - | --------- | ----- |
| 1 | 'John' | 'Smith' | 'add_1' | 'one' | 1 | ['one'] | [1] |
| 2 | 'Tom' | 'Davis' | 'add_2' | 'two' | 2 | ['two'] | [2] |
| 3 | 'John' | 'Smith' | 'add_1' | 'three' | 3 | ['three'] | [3] |
| 4 | 'Tom' | 'Davis' | 'add_2' | 'four' | 4 | ['four'] | [4] |
| 5 | 'Susan' | 'Jones' | 'add_1' | 'one' | 1 | ['one'] | [1] |
</code></pre>
<p>I have no idea how to approach this problem. I need this output:</p>
<pre><code>| id | name | last_name | address | x_list | y_list |
| -- | ------- | ---------- | ------- | ---------------- | ------ |
| 1 | 'John' | 'Smith' | 'add_1' | ['one', 'three'] | [1, 3] |
| 2 | 'Tom' | 'Davis' | 'add_2' | ['two', 'four'] | [2, 4] |
| 3 | 'Susan' | 'Jones' | 'add_1' | ['one'] | [1] |
</code></pre>
<p>Basically, I need to return a new DataFrame, or modify the existing one so the columns with <strong>the same name, last_name, and address</strong> have their x_list and y_list merged. Can anyone help me how to do this in pandas? This needs to be done on a dataframe of about 58 000 rows.</p>
| [
{
"answer_id": 74365004,
"author": "vadian",
"author_id": 5044042,
"author_profile": "https://Stackoverflow.com/users/5044042",
"pm_score": 3,
"selected": true,
"text": "Decodable"
},
{
"answer_id": 74365142,
"author": "SPatel",
"author_id": 6630644,
"author_profile": "https://Stackoverflow.com/users/6630644",
"pm_score": 0,
"selected": false,
"text": "struct MyStuff: Codable {\n let name: String\n let quantity: Int\n let location: String\n}\n \nextension Encodable {\n func toString() -> String? {\n if let config = try? JSONEncoder().encode(self) {\n return String(data: config, encoding: .utf8)\n }\n return .none\n }\n}\n \nextension Decodable {\n static func map(JSONString: String) -> Self? {\n try? JSONDecoder().decode(Self.self, from: JSONString.data(using: .utf8) ?? .init())\n }\n}\n \n \n@objc(Stuff)\npublic class Stuff: NSManagedObject {\n}\n \n// Entity with single field (no field base query support)\nextension Stuff {\n @nonobjc public class func fetchRequest() -> NSFetchRequest<Stuff> {\n return NSFetchRequest<Stuff>(entityName: \"Stuff\")\n }\n @NSManaged public var myStuffRawJSON: String?\n \n func mapToMyStuff() -> MyStuff? {\n MyStuff.map(JSONString: myStuffRawJSON ?? \"\")\n }\n}\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20451022/"
] |
74,364,569 | <p>I am trying to refactor my api into a minimal api. Previously I've been using ControllerBase.HttpContext to get the user like this:</p>
<pre><code>var emial = HttpContext.User.FindFirstValue(ClaimTypes.Email);
</code></pre>
<p>The method that I want to use for my endpoint mapping should be something like this:</p>
<pre><code>public static void MapSurveyEndpoints(this WebApplication app) {
app.MapPost("/api/Surveys", AddSurveysAsync);
}
public static async Task<Survey> AddSurveysAsync(ISurveyRepository repo, Survey survey) {
var email = ...; //get current user email
survey.UserEmail = email;
return await repo.AddSurveysAsync(survey);
}
</code></pre>
<p>What would be another approach for getting the user without using controller?</p>
| [
{
"answer_id": 74364615,
"author": "Daniel A. White",
"author_id": 23528,
"author_profile": "https://Stackoverflow.com/users/23528",
"pm_score": 2,
"selected": false,
"text": "HttpContext"
},
{
"answer_id": 74366192,
"author": "Guru Stron",
"author_id": 2501279,
"author_profile": "https://Stackoverflow.com/users/2501279",
"pm_score": 3,
"selected": true,
"text": "HttpContext"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11317067/"
] |
74,364,593 | <pre><code>function message()
{
if (isset($_SESSION['message'])) {
if ($_SESSION['message'] == "signup_err_password") {
echo " <div class='alert alert-danger' role='alert'>
please enter the password in correct form !!!
</div>";
unset($_SESSION['message']);
} elseif ($_SESSION['message'] == "loginErr") {
echo " <div class='alert alert-danger' role='alert'>
The email or the password is incorrect !!!
</div>";
unset($_SESSION['message']);
} elseif ($_SESSION['message'] == "usedEmail") {
echo " <div class='alert alert-danger' role='alert'>
This email is already used !!!
</div>";
unset($_SESSION['message']);
} elseif ($_SESSION['message'] == "wentWrong") {
echo " <div class='alert alert-danger' role='alert'>
Something went wrong !!!
</div>";
unset($_SESSION['message']);
} elseif ($_SESSION['message'] == "empty_err") {
echo " <div class='alert alert-danger' role='alert'>
please don't leave anything empty !!!
</div>";
unset($_SESSION['message']);
} elseif ($_SESSION['message'] == "signup_err_email") {
echo " <div class='alert alert-danger' role='alert'>
please enter the email in the correct form !!!
</div>";
unset($_SESSION['message']);
}
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/n6FCB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n6FCB.png" alt="enter image description here" /></a></p>
<p>This kind of error is displayed were ever i use this message function
the same message is displayed wen eve i tried to import the message function in the program</p>
| [
{
"answer_id": 74365046,
"author": "Roman",
"author_id": 3895734,
"author_profile": "https://Stackoverflow.com/users/3895734",
"pm_score": -1,
"selected": false,
"text": "<?php\n\nfunction message()\n{\n $messageMap = [\n \"signup_err_password\" => \"lease enter the password in correct form !!!\",\n \"loginErr\" => \"The email or the password is incorrect !!!\",\n \"usedEmail\" => \"This email is already used !!!\",\n \"wentWrong\" => \"Something went wrong !!!\",\n \"empty_err\" => \"please don't leave anything empty !!!\",\n \"signup_err_email\" => \"please enter the email in the correct form !!!\"\n ];\n \n if (array_key_exists('message', $_SESSION)) {\n if(array_key_exists((string)$_SESSION['message'], $messageMap)) {\n printf(\"<div class='alert alert-danger' role='alert'>%s</div>\", $messageMap[$_SESSION['message']]);\n unset($_SESSION['message']);\n }\n }\n}\n"
},
{
"answer_id": 74365123,
"author": "Vlad",
"author_id": 20382571,
"author_profile": "https://Stackoverflow.com/users/20382571",
"pm_score": -1,
"selected": false,
"text": "if (isset($_SESSION['message']))\n"
},
{
"answer_id": 74365275,
"author": "manju nath",
"author_id": 20439964,
"author_profile": "https://Stackoverflow.com/users/20439964",
"pm_score": -1,
"selected": false,
"text": "<?php session_start();\n//for checking this session\n$_SESSION['message']=\"wentWrong\";\n\nfunction message($message)\n{\n $res=\"\";$msg=\"\";\n switch($message)\n {\n case \"signup_err_password\":\n $msg=\"please enter the password in correct form !!!\"; \n break;\n case \"loginErr\":\n $msg=\" The email or the password is incorrect !!!\"; \n break;\n case \"usedEmail\":\n $msg=\"This email is already used !!!\"; \n break;\n case \"wentWrong\":\n $msg=\" Something went wrong !!!\"; \n break;\n case \"empty_err\":\n $msg=\"please don't leave anything empty !!!\"; \n break;\n case \"signup_err_email\":\n $msg=\"please enter the email in the correct form !!!\"; \n break;\n default:\n $msg=\"\";\n break;\n }\n $res=\"<div class='alert alert-danger' role='alert'>\".$msg.\"</div>\";\n return $res; \n}\n$msg = message($_SESSION['message']);\necho $msg;\n?>\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20451953/"
] |
74,364,606 | <p>From <a href="https://stackoverflow.com/questions/11659134">this question</a>, given that I don't want to specify any context, hence, passing <code>null</code> to <code>thisArg</code> in <code>call()</code>.</p>
<p>What would be the difference between line 2 and line 3 in the following code? Is there any benefit from doing one over the other?</p>
<pre class="lang-js prettyprint-override"><code>function sum(a,b) { return a + b; }
var result1 = sum.call(null,3,4); // 7
var result2 = sum(3,4); // 7
</code></pre>
<p>Similarly for <code>apply()</code>:</p>
<pre class="lang-js prettyprint-override"><code>var arr = [1,2,4];
var result3 = Math.max.apply(null, arr); // 4
var result4 = Math.max(...arr); // 4
</code></pre>
| [
{
"answer_id": 74365046,
"author": "Roman",
"author_id": 3895734,
"author_profile": "https://Stackoverflow.com/users/3895734",
"pm_score": -1,
"selected": false,
"text": "<?php\n\nfunction message()\n{\n $messageMap = [\n \"signup_err_password\" => \"lease enter the password in correct form !!!\",\n \"loginErr\" => \"The email or the password is incorrect !!!\",\n \"usedEmail\" => \"This email is already used !!!\",\n \"wentWrong\" => \"Something went wrong !!!\",\n \"empty_err\" => \"please don't leave anything empty !!!\",\n \"signup_err_email\" => \"please enter the email in the correct form !!!\"\n ];\n \n if (array_key_exists('message', $_SESSION)) {\n if(array_key_exists((string)$_SESSION['message'], $messageMap)) {\n printf(\"<div class='alert alert-danger' role='alert'>%s</div>\", $messageMap[$_SESSION['message']]);\n unset($_SESSION['message']);\n }\n }\n}\n"
},
{
"answer_id": 74365123,
"author": "Vlad",
"author_id": 20382571,
"author_profile": "https://Stackoverflow.com/users/20382571",
"pm_score": -1,
"selected": false,
"text": "if (isset($_SESSION['message']))\n"
},
{
"answer_id": 74365275,
"author": "manju nath",
"author_id": 20439964,
"author_profile": "https://Stackoverflow.com/users/20439964",
"pm_score": -1,
"selected": false,
"text": "<?php session_start();\n//for checking this session\n$_SESSION['message']=\"wentWrong\";\n\nfunction message($message)\n{\n $res=\"\";$msg=\"\";\n switch($message)\n {\n case \"signup_err_password\":\n $msg=\"please enter the password in correct form !!!\"; \n break;\n case \"loginErr\":\n $msg=\" The email or the password is incorrect !!!\"; \n break;\n case \"usedEmail\":\n $msg=\"This email is already used !!!\"; \n break;\n case \"wentWrong\":\n $msg=\" Something went wrong !!!\"; \n break;\n case \"empty_err\":\n $msg=\"please don't leave anything empty !!!\"; \n break;\n case \"signup_err_email\":\n $msg=\"please enter the email in the correct form !!!\"; \n break;\n default:\n $msg=\"\";\n break;\n }\n $res=\"<div class='alert alert-danger' role='alert'>\".$msg.\"</div>\";\n return $res; \n}\n$msg = message($_SESSION['message']);\necho $msg;\n?>\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10666066/"
] |
74,364,607 | <p>I have Embedded Qt applicaiton runing on my HMI screen.
I am trying to execute some commands to execute in cmd.
I am calling this c++ function simply from QML.
Everytime I call it it hangs on process.start().
Do anyone have any experience for such issue? please help.
I have ceated a simple function to print out date and it still hangs at process.start() regardless what cmd I execute.</p>
<pre><code>cmd.sprintf("date +%%F' '%%X");
qDebug() << "cmd: " << cmd;
process.start("sh", QStringList()<<"-c"<<cmd);
process.waitForFinished(1000);
dtval = process.readAllStandardOutput();
process.close();
</code></pre>
<p>I am using Qt 5.9 on Ubuntu 18.04.6LTS platform.</p>
| [
{
"answer_id": 74365046,
"author": "Roman",
"author_id": 3895734,
"author_profile": "https://Stackoverflow.com/users/3895734",
"pm_score": -1,
"selected": false,
"text": "<?php\n\nfunction message()\n{\n $messageMap = [\n \"signup_err_password\" => \"lease enter the password in correct form !!!\",\n \"loginErr\" => \"The email or the password is incorrect !!!\",\n \"usedEmail\" => \"This email is already used !!!\",\n \"wentWrong\" => \"Something went wrong !!!\",\n \"empty_err\" => \"please don't leave anything empty !!!\",\n \"signup_err_email\" => \"please enter the email in the correct form !!!\"\n ];\n \n if (array_key_exists('message', $_SESSION)) {\n if(array_key_exists((string)$_SESSION['message'], $messageMap)) {\n printf(\"<div class='alert alert-danger' role='alert'>%s</div>\", $messageMap[$_SESSION['message']]);\n unset($_SESSION['message']);\n }\n }\n}\n"
},
{
"answer_id": 74365123,
"author": "Vlad",
"author_id": 20382571,
"author_profile": "https://Stackoverflow.com/users/20382571",
"pm_score": -1,
"selected": false,
"text": "if (isset($_SESSION['message']))\n"
},
{
"answer_id": 74365275,
"author": "manju nath",
"author_id": 20439964,
"author_profile": "https://Stackoverflow.com/users/20439964",
"pm_score": -1,
"selected": false,
"text": "<?php session_start();\n//for checking this session\n$_SESSION['message']=\"wentWrong\";\n\nfunction message($message)\n{\n $res=\"\";$msg=\"\";\n switch($message)\n {\n case \"signup_err_password\":\n $msg=\"please enter the password in correct form !!!\"; \n break;\n case \"loginErr\":\n $msg=\" The email or the password is incorrect !!!\"; \n break;\n case \"usedEmail\":\n $msg=\"This email is already used !!!\"; \n break;\n case \"wentWrong\":\n $msg=\" Something went wrong !!!\"; \n break;\n case \"empty_err\":\n $msg=\"please don't leave anything empty !!!\"; \n break;\n case \"signup_err_email\":\n $msg=\"please enter the email in the correct form !!!\"; \n break;\n default:\n $msg=\"\";\n break;\n }\n $res=\"<div class='alert alert-danger' role='alert'>\".$msg.\"</div>\";\n return $res; \n}\n$msg = message($_SESSION['message']);\necho $msg;\n?>\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6200195/"
] |
74,364,631 | <p>I have the following query with high execution time, where current indexes are created on individual columns ENTER_TIME and EXIT_TIME and location_id is primary_key on both the tables.</p>
<p>Database server: Oracle Database 19c Standard Edition 2</p>
<p>Version : 19.11.0.0.0</p>
<pre><code>SELECT
trp.location,
trp.enter_time,
trp.exit_time
SUM(TIMEDIFF(trp.enter_time,trp.exit_time)) AS stay_time
FROM
trip_route_point trp
INNER JOIN
location l ON trp.location_id = l.location_id
WHERE
trp.enter_time BETWEEN '20221010070000' AND '20221108070000'
AND trp.exit_time IS NOT NULL
AND trp.exit_time >= trp.enter_time
GROUP BY
trp.location_id
HAVING
SUM(TIMEDIFF(trp.enter_time, trp.exit_time)) > 0
ORDER BY
stay_time DESC
</code></pre>
<p>Query performance is at 3 secs with 2.5 million rows in the <code>trip_route_point</code> table.</p>
<p>I suspect <code>trp.exit_time >= trp.enter_time</code> condition is not making use of the indexes.</p>
<p>From the execution plan I can see the query requires full table scan.</p>
<p>Please advise the best indexes to use to improve the query performance</p>
| [
{
"answer_id": 74365046,
"author": "Roman",
"author_id": 3895734,
"author_profile": "https://Stackoverflow.com/users/3895734",
"pm_score": -1,
"selected": false,
"text": "<?php\n\nfunction message()\n{\n $messageMap = [\n \"signup_err_password\" => \"lease enter the password in correct form !!!\",\n \"loginErr\" => \"The email or the password is incorrect !!!\",\n \"usedEmail\" => \"This email is already used !!!\",\n \"wentWrong\" => \"Something went wrong !!!\",\n \"empty_err\" => \"please don't leave anything empty !!!\",\n \"signup_err_email\" => \"please enter the email in the correct form !!!\"\n ];\n \n if (array_key_exists('message', $_SESSION)) {\n if(array_key_exists((string)$_SESSION['message'], $messageMap)) {\n printf(\"<div class='alert alert-danger' role='alert'>%s</div>\", $messageMap[$_SESSION['message']]);\n unset($_SESSION['message']);\n }\n }\n}\n"
},
{
"answer_id": 74365123,
"author": "Vlad",
"author_id": 20382571,
"author_profile": "https://Stackoverflow.com/users/20382571",
"pm_score": -1,
"selected": false,
"text": "if (isset($_SESSION['message']))\n"
},
{
"answer_id": 74365275,
"author": "manju nath",
"author_id": 20439964,
"author_profile": "https://Stackoverflow.com/users/20439964",
"pm_score": -1,
"selected": false,
"text": "<?php session_start();\n//for checking this session\n$_SESSION['message']=\"wentWrong\";\n\nfunction message($message)\n{\n $res=\"\";$msg=\"\";\n switch($message)\n {\n case \"signup_err_password\":\n $msg=\"please enter the password in correct form !!!\"; \n break;\n case \"loginErr\":\n $msg=\" The email or the password is incorrect !!!\"; \n break;\n case \"usedEmail\":\n $msg=\"This email is already used !!!\"; \n break;\n case \"wentWrong\":\n $msg=\" Something went wrong !!!\"; \n break;\n case \"empty_err\":\n $msg=\"please don't leave anything empty !!!\"; \n break;\n case \"signup_err_email\":\n $msg=\"please enter the email in the correct form !!!\"; \n break;\n default:\n $msg=\"\";\n break;\n }\n $res=\"<div class='alert alert-danger' role='alert'>\".$msg.\"</div>\";\n return $res; \n}\n$msg = message($_SESSION['message']);\necho $msg;\n?>\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4562784/"
] |
74,364,637 | <p>I'm working through some self guided coding curriculum and currently doing a small project building a holy grail layout with flexbox. Here is my codepen <a href="https://codepen.io/clayco/pen/KKeNjrm" rel="nofollow noreferrer">https://codepen.io/clayco/pen/KKeNjrm</a></p>
<p>Currently, all of the cards are displayed under the sidebar when they should be to the right of it.</p>
<p>I'm guessing it has something to do with the flex direction of the body being set to column, but I've tried changing the flex directions around and it doesn't help the problem.</p>
<p>Anyways, here's my code.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
margin: 0;
min-height: 100vh;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.header {
height: 72px;
background: darkmagenta;
color: white;
font-size: 32px;
font-weight: 900;
align-items: center;
display: flex;
text-indent: 16px;
}
.footer {
height: 72px;
background: #eee;
color: darkmagenta;
display: flex;
align-items: center;
justify-content: center;
}
.sidebar {
width: 300px;
background: royalblue;
display: flex;
min-width: 300px;
height: calc( 100vh - 72px);
flex-direction: column;
gap: 50px;
}
.container {
display: flex;
flex-grow: 1;
}
.card {
border: 1px solid #eee;
box-shadow: 2px 4px 16px rgba(0, 0, 0, .06);
border-radius: 4px;
flex: 1 1 250px;
}
.cards {
padding: 32px;
display: flex;
flex-wrap: wrap;
flex-direction: row-reverse;
gap: 50px;
width: 1000px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
MY AWESOME WEBSITE
</div>
<div class="container">
<div class="sidebar">
<ul>
<li><a href="#">⭐ - link one</a></li>
<li><a href="#">♂️ - link two</a></li>
<li><a href="#">️ - link three</a></li>
<li><a href="#"> - link four</a></li>
</ul>
</div>
</div>
<div class="cards">
<div class="card">Lorem ipsum dolor sit amet consectetur adipisicing elit. Tempora, eveniet? Dolorem dignissimos maiores non delectus possimus dolor nulla repudiandae vitae provident quae, obcaecati ipsam unde impedit corrupti veritatis minima porro?</div>
<div class="card">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quasi quaerat qui iure ipsam maiores velit tempora, deleniti nesciunt fuga suscipit alias vero rem, corporis officia totam saepe excepturi odit ea.</div>
<div class="card">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Nobis illo ex quas, commodi eligendi aliquam ut, dolor, atque aliquid iure nulla. Laudantium optio accusantium quaerat fugiat, natus officia esse autem?</div>
<div class="card">Lorem ipsum dolor sit amet consectetur adipisicing elit. Necessitatibus nihil impedit eius amet adipisci dolorum vel nostrum sit excepturi corporis tenetur cum, dolore incidunt blanditiis. Unde earum minima laboriosam eos!</div>
<div class="card">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Nobis illo ex quas, commodi eligendi aliquam ut, dolor, atque aliquid iure nulla. Laudantium optio accusantium quaerat fugiat, natus officia esse autem?</div>
<div class="card">Lorem ipsum dolor sit amet consectetur adipisicing elit. Necessitatibus nihil impedit eius amet adipisci dolorum vel nostrum sit excepturi corporis tenetur cum, dolore incidunt blanditiis. Unde earum minima laboriosam eos!</div>
</div>
<div class="footer">
The Odin Project ❤️
</div></code></pre>
</div>
</div>
</p>
<p>Thanks so much</p>
| [
{
"answer_id": 74365046,
"author": "Roman",
"author_id": 3895734,
"author_profile": "https://Stackoverflow.com/users/3895734",
"pm_score": -1,
"selected": false,
"text": "<?php\n\nfunction message()\n{\n $messageMap = [\n \"signup_err_password\" => \"lease enter the password in correct form !!!\",\n \"loginErr\" => \"The email or the password is incorrect !!!\",\n \"usedEmail\" => \"This email is already used !!!\",\n \"wentWrong\" => \"Something went wrong !!!\",\n \"empty_err\" => \"please don't leave anything empty !!!\",\n \"signup_err_email\" => \"please enter the email in the correct form !!!\"\n ];\n \n if (array_key_exists('message', $_SESSION)) {\n if(array_key_exists((string)$_SESSION['message'], $messageMap)) {\n printf(\"<div class='alert alert-danger' role='alert'>%s</div>\", $messageMap[$_SESSION['message']]);\n unset($_SESSION['message']);\n }\n }\n}\n"
},
{
"answer_id": 74365123,
"author": "Vlad",
"author_id": 20382571,
"author_profile": "https://Stackoverflow.com/users/20382571",
"pm_score": -1,
"selected": false,
"text": "if (isset($_SESSION['message']))\n"
},
{
"answer_id": 74365275,
"author": "manju nath",
"author_id": 20439964,
"author_profile": "https://Stackoverflow.com/users/20439964",
"pm_score": -1,
"selected": false,
"text": "<?php session_start();\n//for checking this session\n$_SESSION['message']=\"wentWrong\";\n\nfunction message($message)\n{\n $res=\"\";$msg=\"\";\n switch($message)\n {\n case \"signup_err_password\":\n $msg=\"please enter the password in correct form !!!\"; \n break;\n case \"loginErr\":\n $msg=\" The email or the password is incorrect !!!\"; \n break;\n case \"usedEmail\":\n $msg=\"This email is already used !!!\"; \n break;\n case \"wentWrong\":\n $msg=\" Something went wrong !!!\"; \n break;\n case \"empty_err\":\n $msg=\"please don't leave anything empty !!!\"; \n break;\n case \"signup_err_email\":\n $msg=\"please enter the email in the correct form !!!\"; \n break;\n default:\n $msg=\"\";\n break;\n }\n $res=\"<div class='alert alert-danger' role='alert'>\".$msg.\"</div>\";\n return $res; \n}\n$msg = message($_SESSION['message']);\necho $msg;\n?>\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20451920/"
] |
74,364,652 | <p>I'm trying to remove some strings from filenames i have in a directory using bash. I've tried the following with no success.</p>
<p><code>rename --version</code></p>
<p><code>rename from util-linux 2.23.2</code></p>
<p><code>rename -v 's/[.].*//' *</code></p>
<p><code>rename -v 's/\.vesta-01:2,//' *</code></p>
<p>Original File Name(s):</p>
<p>1667874526.M308257P1693.vesta-01:2,</p>
<p>1667883117.M371701P32232.vesta-01:2,</p>
<p>Desired File Name(s):</p>
<p>1667874526</p>
<p>1667883117</p>
| [
{
"answer_id": 74364969,
"author": "j_b",
"author_id": 16482938,
"author_profile": "https://Stackoverflow.com/users/16482938",
"pm_score": 0,
"selected": false,
"text": "mv"
},
{
"answer_id": 74364989,
"author": "choroba",
"author_id": 1030675,
"author_profile": "https://Stackoverflow.com/users/1030675",
"pm_score": 2,
"selected": false,
"text": "rename"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10161051/"
] |
74,364,666 | <p>I have a Redmine project that is a container for subprojects. This top level project does not have issues (Issue tracking is not enabled in the project settings).</p>
<p>I am trying to figure out a way for the Python api to detect this. Right now, when my code (which is scanning for issue counts) is going through the projects, it gets to this one and errors out.</p>
<p>redminelib.exceptions.ForbiddenError: Requested resource is forbidden</p>
<p>What project property can I use to determine if the Issues are enabled? I tried project.issues._total_count but that always seems to evaluate to "None" for all projects (even ones with issues). I think that gets filled in later when you run an issue query. But I cannot run an issue query without failing and exiting the script.</p>
<p>I just want to have some logic to skip over these Issue disabled projects.</p>
<pre><code>redmine = Redmine('https://redmine.server/redmine', key='1234567890987654321', requests={'verify': False})
projects = redmine.project.all()
for project in projects:
issues = redmine.issue.filter(project_id=project.identifier, status_id='*')
issueCount = 0
for issue in issues:
issueCount = issueCount + 1
print( 'Project ' + project.identifier + ' has ' + str(issueCount) + ' issues' )
</code></pre>
| [
{
"answer_id": 74364969,
"author": "j_b",
"author_id": 16482938,
"author_profile": "https://Stackoverflow.com/users/16482938",
"pm_score": 0,
"selected": false,
"text": "mv"
},
{
"answer_id": 74364989,
"author": "choroba",
"author_id": 1030675,
"author_profile": "https://Stackoverflow.com/users/1030675",
"pm_score": 2,
"selected": false,
"text": "rename"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2019315/"
] |
74,364,675 | <p>I'm sowewhat new to rx and currently I am using it to schedule a cron job which is continuously polling a server via grpc (found that solution a time ago here on Stackoverflow).</p>
<p>The polling function with rx:</p>
<pre><code>Observable.Interval(Timespan)
.Select(l => Observable.FromAsync(() => Job(m_CTS.Token)))
.Concat()
.Catch((Exception ex) => OnErrorFunc(ex))
.Subscribe(m_CTS.Token);`
</code></pre>
<p>The error function which handles the occurring error:</p>
<pre><code>private IObservable<System.Reactive.Unit> OnError(Exception aException)
{
LOG.Error("CronJob failed " + Job.Method+ " " + aException.Message );
return Observable.Empty<System.Reactive.Unit>();
}
</code></pre>
<p>When the task fails e.g. the server is not available, an exception is thrown. Rx catches the error with the error function, but doesn't continue to schedule/fire the task.</p>
<p>Apparently the empty observable is not sufficient for the sequence to continue.</p>
<p>I already tried to return an</p>
<pre><code>Observable.FromAsync(() => Job(m_CTS.Token))
</code></pre>
<p>but this doesn't work either.</p>
<p>What is the correct return type to get the sequence going? Or maybe my approach is wrong? Is <code>.Retry</code> the better option?</p>
<p>To elimnate confusion here the whole class:</p>
<pre><code>public class CronJob : ICronJob
{
private CancellationTokenSource m_CTS;
private static readonly ILog LOG = LogManager.GetLogger( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType );
public Func<CancellationToken,Task> Job{ get; private set; }
public Func<Exception,IObservable< System.Reactive.Unit>> OnErrorFunc { get; set; }
public TimeSpan Timespan;
public bool Running { get; private set; } = false;
public CronJob(Func<CancellationToken,Task> aJob, TimeSpan aTimeSpan, Func<Exception,IObservable<System.Reactive.Unit>> aOnErrorFunc = null)
{
Job= aJob;
Timespan = aTimeSpan;
OnErrorFunc = aOnErrorFunc ?? OnError;
m_CTS = new CancellationTokenSource();
}
public void StartInstantly()
{
StartTask();
Observable.Interval(Timespan)
.StartWith(-1L)
.Select(l => Observable.FromAsync(() => Job(m_CTS.Token)))
.Concat()
.Catch((Exception ex) => OnErrorFunc(ex))
.Subscribe(m_CTS.Token);
}
private void StartTask()
{
if (Running)
throw new Exception("Task allready started");
m_CTS = new CancellationTokenSource();
Running = true;
}
public void StartAfterTimeSpan()
{
StartTask();
Observable.Interval(Timespan)
.Select(l => Observable.FromAsync(() => Job(m_CTS.Token)))
.Concat()
.Catch((Exception ex) => OnErrorFunc(ex))
.Subscribe(m_CTS.Token);
}
public void Stop()
{
m_CTS.Cancel();
Running = false;
}
public void SetTask(Func<CancellationToken,Task> aJob)
{
if(Running)
Stop();
Job= aJob;
}
private IObservable<System.Reactive.Unit> OnError(Exception aException)
{
LOG.Error("CronJob failed " + Job.Method+ " " + aException.Message );
// return Observable.Empty<System.Reactive.Unit>();
return Observable.Empty<System.Reactive.Unit>();
}
}
</code></pre>
| [
{
"answer_id": 74364969,
"author": "j_b",
"author_id": 16482938,
"author_profile": "https://Stackoverflow.com/users/16482938",
"pm_score": 0,
"selected": false,
"text": "mv"
},
{
"answer_id": 74364989,
"author": "choroba",
"author_id": 1030675,
"author_profile": "https://Stackoverflow.com/users/1030675",
"pm_score": 2,
"selected": false,
"text": "rename"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11957956/"
] |
74,364,693 | <p>I have following string in text file:</p>
<pre><code>^25555555~BIG^20200629^20022222^20200629^55555555^^^DI^00~CUR^ZZ^USD
</code></pre>
<p>and want to fetch string between <code>BIG^</code> and <code>^00</code> i.e.
<code>20200629^20022222^20200629^25523652^^^DI</code>. I tried to use following command but it is not working, may be because of special character caret <code>^</code>.</p>
<pre class="lang-bash prettyprint-override"><code>echo "^25555555~BIG^20200629^20022222^20200629^25523652^^^DI^00~CUR^ZZ^USD" | grep -o -P '(?<=BIG^).*(?=^00)'
</code></pre>
<p>I tried removing caret from search and it is working but need to include caret in my search:</p>
<pre class="lang-bash prettyprint-override"><code>echo "^25555555~BIG^20200629^20022222^20200629^55555555^^^DI^00~CUR^ZZ^USD" | grep -o -P '(?<=BIG).*(?=00)'
</code></pre>
<p>above command returns: <code>^20200629^20022222^20200629^55555555^^^DI^</code></p>
<p>How to fetch part of string from string containing special character caret ^ using grep?</p>
| [
{
"answer_id": 74364785,
"author": "WilliamHarding",
"author_id": 19284008,
"author_profile": "https://Stackoverflow.com/users/19284008",
"pm_score": 2,
"selected": false,
"text": "BIG\\^(.*)\\^00"
},
{
"answer_id": 74365478,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 0,
"selected": false,
"text": "grep -oP 'BIG\\^\\K.*?(?=\\^00)'\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16855164/"
] |
74,364,698 | <p>Suppose I have this code:</p>
<pre><code>#!/usr/bin/perl
use warnings;
use strict;
package Guy;
sub new {
my $type = shift;
my %params = @_;
my $self = {};
$self->{'First'} = $params{'First'};
$self->{'Middle'} = $params{'Middle'};
$self->{'Last'} = $params{'Last'};
bless $self, $type;
}
sub printMe
{
printf "-----------------------------------\n";
printf "My type is: \"$self->{type}\"\n"; # Line 18
printf "First :: $self->{First}\n"; # Line 19
printf "Middle :: $self->{Middle}\n"; # Line 20
printf "Last :: $self->{Last}\n"; # Line 21
printf "-----------------------------------\n";
}
package main;
my $dude = Guy->new( 'First' => "John", 'Middle' => "Jacob", 'Last' => "Smith" );
$dude->printMe();
</code></pre>
<p>Output is:</p>
<pre><code>me@ubuntu1$ ./toy01.perl
Global symbol "$self" requires explicit package name (did you forget to declare "my $self"?) at ./toy01.perl line 18.
Global symbol "$self" requires explicit package name (did you forget to declare "my $self"?) at ./toy01.perl line 19.
Global symbol "$self" requires explicit package name (did you forget to declare "my $self"?) at ./toy01.perl line 20.
Global symbol "$self" requires explicit package name (did you forget to declare "my $self"?) at ./toy01.perl line 21.
Execution of ./toy01.perl aborted due to compilation errors.
me@ubuntu1$
</code></pre>
<p>So the problem here is that class method <code>printMe()</code> can't access attributes stored in the <code>$self</code> hash, which is populated in the constructor. I'm so confused as to why.</p>
<p>In the constructor, <code>$self</code> is created as a hash, used to store the attributed passed into the constructor. Is <code>$self</code> created with a local scope when it needs to be global, or something like that? Or do I lack a command at the top of the <code>printMe()</code> method that makes <code>$self</code> visible, or something?</p>
<p>And how to refer to attribute <code>type</code>, which is an attribute that is set in the constructor but not stored in the <code>$self</code> hash? (My <code>$self->{type}</code> call is obviously a desperate attempt to stumble upon the solution here.)<br />
Any advice or feedback is appreciated here, thank you.</p>
| [
{
"answer_id": 74364815,
"author": "choroba",
"author_id": 1030675,
"author_profile": "https://Stackoverflow.com/users/1030675",
"pm_score": 3,
"selected": true,
"text": "sub printMe\n{\n my ($self) = @_;\n ...\n"
},
{
"answer_id": 74375317,
"author": "Dave Cross",
"author_id": 7231,
"author_profile": "https://Stackoverflow.com/users/7231",
"pm_score": 2,
"selected": false,
"text": "sub new {\n ...;\n my $self = {};\n\n # code populating $self\n ...;\n\n bless $self, $type;\n}\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4040743/"
] |
74,364,714 | <p>I want to add a new column names (title_holder) to my dataset (image), based on the column "title". All NAs in the column title should have the value "no" in the new column "title_holder", else the value should be "yes".</p>
<p>Thanks.<a href="https://i.stack.imgur.com/4qaN5.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4qaN5.jpg" alt="enter image description here" /></a></p>
<p>Among others I tried this code among others:</p>
<p><code>age_average <- age %>% mutate(title_holder = case_when (!is.na(title), "no", TRUE ~ "yes")) %>%view()</code></p>
<p>Can someone help me figuring out the correct code?</p>
| [
{
"answer_id": 74364722,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "~"
},
{
"answer_id": 74365030,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 1,
"selected": false,
"text": "ifelse"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20451876/"
] |
74,364,719 | <p>Basically, I want to create a loop that will continue getting string inputs from users until the user types only a "#" on a line.</p>
<p>I am coming from C++ so I am a bit lost in this Python project I have in mind.</p>
| [
{
"answer_id": 74364778,
"author": "Zach J.",
"author_id": 20276330,
"author_profile": "https://Stackoverflow.com/users/20276330",
"pm_score": 1,
"selected": false,
"text": "last_input = ''\nwhile (last_input != '#'):\n last_input = input()\n"
},
{
"answer_id": 74364856,
"author": "ANISH SAJI KUMAR",
"author_id": 12309235,
"author_profile": "https://Stackoverflow.com/users/12309235",
"pm_score": -1,
"selected": false,
"text": "while True:\n s = input()\n if s == \"#\":\n break\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20451866/"
] |
74,364,771 | <p>I am trying to add a file renaming step in my current workflow to make it easier on some of the other users. What I want to do is take the <code>contigs.fasta</code> file from a spades assembly directory and rename it to include the sample name. (i.e <code>foo_de_novo/contigs.fasta</code> to <code>foo_de_novo/foo.fasta</code>)</p>
<p>here is my code... well currently.</p>
<pre><code>configfile: "config.yaml"
import os
def is_file_empty(file_path):
""" Check if file is empty by confirming if its size is 0 bytes"""
# Check if singleton file exist and it is empty from bbrepair output
return os.path.exists(file_path) and os.stat(file_path).st_size == 0
rule all:
input:
expand("{sample}_de_novo/{sample}.fasta", sample = config["names"]),
rule fastp:
input:
r1 = lambda wildcards: config["sample_reads_r1"][wildcards.sample],
r2 = lambda wildcards: config["sample_reads_r2"][wildcards.sample]
output:
r1 = temp("clean/{sample}_r1.trim.fastq.gz"),
r2 = temp("clean/{sample}_r2.trim.fastq.gz")
shell:
"fastp --in1 {input.r1} --in2 {input.r2} --out1 {output.r1} --out2 {output.r2} --trim_front1 20 --trim_front2 20"
rule bbrepair:
input:
r1 = "clean/{sample}_r1.trim.fastq.gz",
r2 = "clean/{sample}_r2.trim.fastq.gz"
output:
r1 = temp("clean/{sample}_r1.fixed.fastq"),
r2 = temp("clean/{sample}_r2.fixed.fastq"),
singles = temp("clean/{sample}.singletons.fastq")
shell:
"repair.sh -Xmx10g in1={input.r1} in2={input.r2} out1={output.r1} out2={output.r2} outs={output.singles}"
rule spades:
input:
r1 = "clean/{sample}_r1.fixed.fastq",
r2 = "clean/{sample}_r2.fixed.fastq",
s = "clean/{sample}.singletons.fastq"
output:
directory("{sample}_de_novo")
run:
isempty = is_file_empty("clean/{sample}.singletons.fastq")
if isempty == "False":
shell("spades.py --careful --phred-offset 33 -1 {input.r1} -2 {input.r2} -s {input.singletons} -o {output}")
else:
shell("spades.py --careful --phred-offset 33 -1 {input.r1} -2 {input.r2} -o {output}")
rule rename_spades:
input:
"{sample}_de_novo/contigs.fasta"
output:
"{sample}_de_novo/{sample}.fasta"
shell:
"cp {input} {output}"
</code></pre>
<p>When I have it written like this I get the <code>MissingInputError</code> and when I change it to this.</p>
<pre><code>rule rename_spades:
input:
"{sample}_de_novo"
output:
"{sample}_de_novo/{sample}.fasta"
shell:
"cp {input} {output}"
</code></pre>
<p>I get the <code>ChildIOException</code></p>
<p>I feel I understand why snakemake is unhappy with both versions. The first one is becasue I don't explicitly output the <code>"{sample}_de_novo/contigs.fasta"</code> file. Its just one of several files spades outputs. And the other error is because it doesn't like how I am asking it to look into the directory. I however am at a loss on how to fix this.</p>
<p>Is there a way to ask snakmake to look into a directory for a file and then perform the task requested?</p>
<p>Thank you,
Sean</p>
<p><em><strong>EDIT File Structure of Spades output</strong></em></p>
<pre><code>Sample_de_novo
|-corrected/
|-K21/
|-K33/
|-K55/
|-K77/
|-misc/
|-mismatch_corrector/
|-tmp/
|-assembly_graph.fastg
|-assembly_graph_with_scaffolds.gfa
|-before_rr.fasta
|-contigs.fasta
|-contigs.paths
|-dataset.info
|-input_dataset.ymal
|-params.txt
|-scaffolds.fasta
|-scaffolds.paths
|spades.log
</code></pre>
| [
{
"answer_id": 74364778,
"author": "Zach J.",
"author_id": 20276330,
"author_profile": "https://Stackoverflow.com/users/20276330",
"pm_score": 1,
"selected": false,
"text": "last_input = ''\nwhile (last_input != '#'):\n last_input = input()\n"
},
{
"answer_id": 74364856,
"author": "ANISH SAJI KUMAR",
"author_id": 12309235,
"author_profile": "https://Stackoverflow.com/users/12309235",
"pm_score": -1,
"selected": false,
"text": "while True:\n s = input()\n if s == \"#\":\n break\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9074333/"
] |
74,364,791 | <p>I tried to run codes in my hyper-terminal (deleted nodemon and then reinstalled it) but at the end I still can NOT get the version of my nodemon, it says:
"C:\Users\azadk\AppData\Roaming\npm/node_modules/node/bin/node: line 1: This: command not found"</p>
<p>Here’s what I tried to do:</p>
<p><a href="https://i.stack.imgur.com/XSLf7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XSLf7.png" alt="enter image description here" /></a></p>
<p>I also tried to set the path of Environment variables to "C:\Program Files\nodejs" but still I can’t get the version.</p>
| [
{
"answer_id": 74364778,
"author": "Zach J.",
"author_id": 20276330,
"author_profile": "https://Stackoverflow.com/users/20276330",
"pm_score": 1,
"selected": false,
"text": "last_input = ''\nwhile (last_input != '#'):\n last_input = input()\n"
},
{
"answer_id": 74364856,
"author": "ANISH SAJI KUMAR",
"author_id": 12309235,
"author_profile": "https://Stackoverflow.com/users/12309235",
"pm_score": -1,
"selected": false,
"text": "while True:\n s = input()\n if s == \"#\":\n break\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19401680/"
] |
74,364,798 | <p>Few weeks ago i changed the primary email of my github account a since than my contribution graph is empty , after that i read that this is due to mismatch of my github account email and my local git email from which i am commiting. I changed the local user.email to the correct one but still my activity doesen't show up. I tried to run a bunch of command with rebase and filter_branch but it made the situation even worse becouse it doubled my commits and i can't fix it. Is there a way to show my activity is there a setting in github which shows activity from all commit authors or a e command which can fix it. Command i tried from this link</p>
<p><a href="https://stackoverflow.com/questions/750172/how-do-i-change-the-author-and-committer-name-email-for-multiple-commits">How do I change the author and committer name/email for multiple commits?</a></p>
| [
{
"answer_id": 74364778,
"author": "Zach J.",
"author_id": 20276330,
"author_profile": "https://Stackoverflow.com/users/20276330",
"pm_score": 1,
"selected": false,
"text": "last_input = ''\nwhile (last_input != '#'):\n last_input = input()\n"
},
{
"answer_id": 74364856,
"author": "ANISH SAJI KUMAR",
"author_id": 12309235,
"author_profile": "https://Stackoverflow.com/users/12309235",
"pm_score": -1,
"selected": false,
"text": "while True:\n s = input()\n if s == \"#\":\n break\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15118061/"
] |
74,364,813 | <p>consider two dataframes</p>
<pre><code>df1 <- data.frame(a=LETTERS[1:6],
b=c("apple", "apple","dog", "red", "red","red"))
df2 <- data.frame(col1=c("apple", "golf", "dog", "red"),
col2=c("fruit", "sport","animal", "color"))
> df1
a b
1 A apple
2 B apple
3 C dog
4 D red
5 E red
6 F red
> df2
col1 col2
1 apple fruit
2 golf sport
3 dog animal
4 red color
</code></pre>
<p>I want to create</p>
<pre><code>> output
a b
1 A fruit
2 B fruit
3 C animal
4 D color
5 E color
6 F color
</code></pre>
<p>I get the output I am looking for using the basic for loop. But is there any neat nice way to get this through pipes of dplyr?</p>
<pre><code>for(i in 1:nrow(df1)){
df1[i,2] <- df2[df2$col1==df1[i,2], 2]
}
</code></pre>
| [
{
"answer_id": 74364826,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 3,
"selected": true,
"text": "library(dplyr)\nleft_join(df1, df2, by = c(\"b\" = \"col1\")) %>%\n select(a, b = col2)\n"
},
{
"answer_id": 74365114,
"author": "Karl Edwards",
"author_id": 20311140,
"author_profile": "https://Stackoverflow.com/users/20311140",
"pm_score": 0,
"selected": false,
"text": "df1$b <- df2[ df2$col1 == df1$b, 'col2' ]\n"
},
{
"answer_id": 74365283,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 1,
"selected": false,
"text": "lapply"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16354132/"
] |
74,364,827 | <p>I am currently trying to implement a login to Shopify over the <a href="https://shopify.dev/api/storefront/2022-10/mutations/customerAccessTokenCreateWithMultipass" rel="nofollow noreferrer">Storefront API</a> via <a href="https://shopify.dev/api/multipass" rel="nofollow noreferrer">Multipass</a>.</p>
<p>However, what it isn't clear to me from the Documentation on that Page, how the "created_at" Field is used. Since it states that this field should be filled with the current timestamp.<br />
But what if the same users logs in a second time via Multipass, should it be filled with the timestamp of the second login.<br />
Or should the original Multipass token be stored somewhere, and reused at a second login, instead of generating a new one?</p>
| [
{
"answer_id": 74366368,
"author": "Fabio Filippi",
"author_id": 343794,
"author_profile": "https://Stackoverflow.com/users/343794",
"pm_score": 2,
"selected": true,
"text": "class Multipass:\n def __init__(self, secret):\n key = SHA256.new(secret.encode('utf-8')).digest()\n self.encryptionKey = key[0:16]\n self.signatureKey = key[16:32]\n\n def generate_token(self, customer_data_hash):\n customer_data_hash['created_at'] = datetime.datetime.utcnow().isoformat()\n cipher_text = self.encrypt(json.dumps(customer_data_hash))\n return urlsafe_b64encode(cipher_text + self.sign(cipher_text))\n\n def generate_url(self, customer_data_hash, url):\n token = self.generate_token(customer_data_hash).decode('utf-8')\n return '{0}/account/login/multipass/{1}'.format(url, token)\n\n def encrypt(self, plain_text):\n plain_text = self.pad(plain_text)\n iv = get_random_bytes(AES.block_size)\n cipher = AES.new(self.encryptionKey, AES.MODE_CBC, iv)\n return iv + cipher.encrypt(plain_text.encode('utf-8'))\n\n def sign(self, secret):\n return HMAC.new(self.signatureKey, secret, SHA256).digest()\n\n @staticmethod\n def pad(s):\n return s + (AES.block_size - len(s) % AES.block_size) * chr(AES.block_size - len(s) % AES.block_size)\n\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14771706/"
] |
74,364,841 | <p>I have a series of signals, sample data looks like this:
<a href="https://i.stack.imgur.com/cWHFN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cWHFN.png" alt="enter image description here" /></a></p>
<p>We can see that there are 5 peaks there. I can assume that there won't be more than 1 pick every 10 samples, usually there is one pick every 20 to 40 samples.</p>
<p>I was trying to fit a polynomial and then use scipy.signal.find_peaks and it kind of works but I have to choose different numbers of spline knots to approximate each series correctly and the number of knots correlates to the number of peaks so I sort of ended up where I begun - but now I'd need only a rough idea about the number of peaks.</p>
<p>Then I tried it by dividing the signal into parts:</p>
<pre><code>window = 10 # the smallest range potentially containing whole peak
parts = np.array_split(data, len(data)//window) # divide data set into parts
lengths = []
d = np.nan
for i in parts:
d = abs(i.max() - i.min())
lengths.append(d) # differences between max and min values in each part
av = sum(lengths)/len(lengths)
for i in lengths:
if i < some_tolerance_fraction*av:
window = window+1 # make part for the next check bigger
break
</code></pre>
<p>The idea was that the difference between min and max values in these parts should be smaller than the height of an actual pick I'm looking for unless the parts are large enough to contain whole peak - then the differences should be similar in each part and the average should also be similar to the actual height of the pick.</p>
<p>But this doesn't work at all and possibly doesn't even make sense - depending on the tolerance it divides window all the time or doesn't divide it at all.</p>
<p>this is the array from the image:</p>
<pre><code>array([254256., 254390., 251546., 250561., 250603., 250128., 251000.,
252612., 253552., 253776., 252843., 251800., 250808., 250569.,
249804., 247755., 247685., 247111., 242320., 242580., 243462.,
240383., 239689., 240730., 239508., 239604., 238544., 240174.,
240806., 240218., 239956., 241325., 241343., 241532., 240696.,
242064., 241830., 237569., 237392., 236353., 234819., 234430.,
233890., 233215., 233745., 232159., 231778., 230307., 228754.,
225823., 225139., 223737., 222078., 221188., 220669., 221944.,
223928., 224996., 223405., 223018., 224966., 226590., 226166.,
226012., 226192., 224900., 224439., 223179., 222375., 221509.,
220734., 219686., 218656., 217792., 215934., 214829., 213673.,
212837., 211604., 210748., 210216., 209974., 209659., 209707.,
210131., 210663., 212113., 213078., 214476., 215087., 216220.,
216831., 217286., 217373., 217030., 216491., 215642., 214249.,
213273., 212148., 210846., 209570., 208202., 207165., 206677.,
205703., 203837., 202620., 201530., 198812., 197654., 196506.,
194163., 193736., 193945., 193785., 193417., 193044., 193768.,
194690., 195739., 198592., 199237., 199932., 200142., 199859.,
199593., 199337., 198403., 197500., 195988., 195114., 194278.,
193837., 193861.])
</code></pre>
| [
{
"answer_id": 74366596,
"author": "Ulises Bussi",
"author_id": 17194418,
"author_profile": "https://Stackoverflow.com/users/17194418",
"pm_score": 1,
"selected": false,
"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\narr = np.array([254256., 254390., 251546., 250561., 250603., 250128., 251000.,\n 252612., 253552., 253776., 252843., 251800., 250808., 250569.,\n 249804., 247755., 247685., 247111., 242320., 242580., 243462.,\n 240383., 239689., 240730., 239508., 239604., 238544., 240174.,\n 240806., 240218., 239956., 241325., 241343., 241532., 240696.,\n 242064., 241830., 237569., 237392., 236353., 234819., 234430.,\n 233890., 233215., 233745., 232159., 231778., 230307., 228754.,\n 225823., 225139., 223737., 222078., 221188., 220669., 221944.,\n 223928., 224996., 223405., 223018., 224966., 226590., 226166.,\n 226012., 226192., 224900., 224439., 223179., 222375., 221509.,\n 220734., 219686., 218656., 217792., 215934., 214829., 213673.,\n 212837., 211604., 210748., 210216., 209974., 209659., 209707.,\n 210131., 210663., 212113., 213078., 214476., 215087., 216220.,\n 216831., 217286., 217373., 217030., 216491., 215642., 214249.,\n 213273., 212148., 210846., 209570., 208202., 207165., 206677.,\n 205703., 203837., 202620., 201530., 198812., 197654., 196506.,\n 194163., 193736., 193945., 193785., 193417., 193044., 193768.,\n 194690., 195739., 198592., 199237., 199932., 200142., 199859.,\n 199593., 199337., 198403., 197500., 195988., 195114., 194278.,\n 193837., 193861.])\n\n\n\ndef moving_average(x, w):\n \"\"\"calculate moving average with window size w\"\"\"\n return np.convolve(x, np.ones(w), 'valid') / w\n\n#moving average with size 5\nn=5\narr_f = moving_average(arr, 5)\n#to show in same plot\narr_f_ext= np.hstack([np.ones(n//2)*arr_f[0],arr_f])\nplt.figure()\nplt.plot(arr,'o')\nplt.plot(arr_f_ext)\n\n\n"
},
{
"answer_id": 74368100,
"author": "user3435121",
"author_id": 3435121,
"author_profile": "https://Stackoverflow.com/users/3435121",
"pm_score": 0,
"selected": false,
"text": "i = 0 # position cursor at beginning\nwhile i <= (len(t)-3):\n if (t[i] - t[i+1]) * (t[i+1] - t[i+2]) >= 0:\n # Same direction: join 2 segments by removing the middlepoint.\n # This test also include the case of an horizontal segment \\\n # formed by the first 2 points. We remove the second.\n del( t[i+1])\n else:\n # different directions. Delete nothing. Move cursor by 1\n i += 1\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15282464/"
] |
74,364,871 | <p>I need to specialized numpy arrays. Assume I have a function:</p>
<pre><code> def gen_array(start, end, n_cols):
</code></pre>
<p>It should behave like this, generating three columns where each column goes from start (inclusive) to end (exclusive):</p>
<pre><code>>>> gen_array(20, 25, 3)
array([[20, 20, 20],
[21, 21, 21],
[22, 22, 22],
[23, 23, 23],
[24, 24, 24]])
</code></pre>
<p>My rather naïve implementation looks like this:</p>
<pre><code>def gen_array(start, end, n_columns):
a = np.arange(start, end).reshape(end-start, 1) # create a column vector from start to end
return np.dot(a, [np.ones(n_columns)]) # replicate across n_columns
</code></pre>
<p>(It's okay, though not required, that the <code>np.dot</code> converts values to floats.)</p>
<p>I'm sure there's a better, more efficient and more numpy-ish way to accomplish the same thing. Suggestions?</p>
<h2>Update</h2>
<p>Buildin on a suggestion by @msi_gerva to use <code>np.tile</code>, my latest best thought is:</p>
<pre><code>def gen_array(start, end, n_cols):
return np.tile(np.arange(start, end).reshape(-1, 1), (1, n_cols))
</code></pre>
<p>... which seems pretty good to me.</p>
| [
{
"answer_id": 74365053,
"author": "ILS",
"author_id": 10017662,
"author_profile": "https://Stackoverflow.com/users/10017662",
"pm_score": 3,
"selected": true,
"text": "numpy.arange"
},
{
"answer_id": 74367685,
"author": "Okapi575",
"author_id": 3373796,
"author_profile": "https://Stackoverflow.com/users/3373796",
"pm_score": 0,
"selected": false,
"text": "np.arange(start, end)[:,None]*np.ones(n_cols)\n"
},
{
"answer_id": 74375906,
"author": "w-m",
"author_id": 463796,
"author_profile": "https://Stackoverflow.com/users/463796",
"pm_score": 0,
"selected": false,
"text": "np.arange(start, end)[:, np.newaxis].repeat(n_cols, axis=1)\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/558639/"
] |
74,364,879 | <p>the program is supposed to ask for another input if the name input already has been entered before by checking if that name exists in the list. but the problem is the elements of the list are tuples how can a fix that?</p>
<pre><code>from datetime import datetime
ToDoList = []
time = datetime.now()
date_format = "%Y/%m/%d %H:%M:%S"
def addNewItems():
global ToDoList
while True:
name = input("Please enter your task name: ")
if name in ToDoList:
print("Task already exists! Select the options again.")
elif name not in ToDoList:
break
while True:
date = input(
"Please enter your task completion date as yyyy/mm/dd HH:MM:SS: ")
date = datetime.strptime(date, date_format)
if date < time:
print("Time entered is in the past! Select the options again")
elif date >= time:
break
task = (name, date)
ToDoList = ToDoList.append(task)
print("Task added successfully!")
ToDoList.sort()
</code></pre>
| [
{
"answer_id": 74365053,
"author": "ILS",
"author_id": 10017662,
"author_profile": "https://Stackoverflow.com/users/10017662",
"pm_score": 3,
"selected": true,
"text": "numpy.arange"
},
{
"answer_id": 74367685,
"author": "Okapi575",
"author_id": 3373796,
"author_profile": "https://Stackoverflow.com/users/3373796",
"pm_score": 0,
"selected": false,
"text": "np.arange(start, end)[:,None]*np.ones(n_cols)\n"
},
{
"answer_id": 74375906,
"author": "w-m",
"author_id": 463796,
"author_profile": "https://Stackoverflow.com/users/463796",
"pm_score": 0,
"selected": false,
"text": "np.arange(start, end)[:, np.newaxis].repeat(n_cols, axis=1)\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,364,924 | <p>I have a table like this:</p>
<pre><code>Id email Active
---------------------
1 aaa 1
2 aaa 1
3 aaa 0
4 aaa 0
</code></pre>
<p>I want to delete duplicate row but if Active have 1/0 value keep 1 value and delete 0 value.</p>
<p>I tried this query</p>
<pre><code>select * FROM tbl_name WHERE Id NOT IN (SELECT Id FROM tbl_name GROUP BY email)
</code></pre>
<p>And I expected this result :</p>
<pre><code>Id email Active
---------------------
1 aaa 1
</code></pre>
<p>OR</p>
<pre><code>Id email Active
---------------------
2 aaa 1
</code></pre>
<p>but actually result was :</p>
<pre><code>Id email Active
---------------------
4 aaa 0
</code></pre>
<p>Thanks in advance.</p>
| [
{
"answer_id": 74365053,
"author": "ILS",
"author_id": 10017662,
"author_profile": "https://Stackoverflow.com/users/10017662",
"pm_score": 3,
"selected": true,
"text": "numpy.arange"
},
{
"answer_id": 74367685,
"author": "Okapi575",
"author_id": 3373796,
"author_profile": "https://Stackoverflow.com/users/3373796",
"pm_score": 0,
"selected": false,
"text": "np.arange(start, end)[:,None]*np.ones(n_cols)\n"
},
{
"answer_id": 74375906,
"author": "w-m",
"author_id": 463796,
"author_profile": "https://Stackoverflow.com/users/463796",
"pm_score": 0,
"selected": false,
"text": "np.arange(start, end)[:, np.newaxis].repeat(n_cols, axis=1)\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20446355/"
] |
74,364,929 | <p>I'm trying to do this by convert the response to json and then find the filed form it.</p>
<p>But I don't know neither how to convert it to json, nor how to traverse the json.</p>
<pre><code>@POST
@Path("/custoemrs")
@Produces({ MediaType.APPLICATION_JSON })
Response createCustomer(Customer customer);
</code></pre>
<p>there would be a id field which I want to extract.</p>
<p>There are too many answers out there, I tried some of them but none is working.</p>
<p>I want to use jackson to process the json file, and I'm using resteasy client.</p>
<p>The response I'm using is javax.ws.rs.core.Response, please kindly base on this to answer</p>
<p>I saw many people said something like</p>
<p><code>EntityUtils.toString(entity)</code></p>
<p>But I can't even resolve the entityutils...</p>
| [
{
"answer_id": 74365053,
"author": "ILS",
"author_id": 10017662,
"author_profile": "https://Stackoverflow.com/users/10017662",
"pm_score": 3,
"selected": true,
"text": "numpy.arange"
},
{
"answer_id": 74367685,
"author": "Okapi575",
"author_id": 3373796,
"author_profile": "https://Stackoverflow.com/users/3373796",
"pm_score": 0,
"selected": false,
"text": "np.arange(start, end)[:,None]*np.ones(n_cols)\n"
},
{
"answer_id": 74375906,
"author": "w-m",
"author_id": 463796,
"author_profile": "https://Stackoverflow.com/users/463796",
"pm_score": 0,
"selected": false,
"text": "np.arange(start, end)[:, np.newaxis].repeat(n_cols, axis=1)\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20410560/"
] |
74,364,934 | <p>When trying to start postgresql</p>
<pre><code>➜ ~ brew services start postgresql
Warning: Use postgresql@14 instead of deprecated postgresql
Bootstrap failed: 5: Input/output error
Try re-running the command as root for richer errors.
Error: Failure while executing; `/bin/launchctl bootstrap gui/501 /Users/josh/Library/LaunchAgents/homebrew.mxcl.postgresql@14.plist` exited with 5.
</code></pre>
<p>Getting "error" as status when running brew services list</p>
<pre><code>➜ ~ brew services list
Name Status User File
postgresql@14 error 256 root ~/Library/LaunchAgents/homebrew.mxcl.postgresql@14.plist
</code></pre>
<p>PSQL was working perfectly fine, shut down my laptop (did not update) and when I turned it on the next day psql was not working. I am on OSX Version 12.6 (Monteray).</p>
| [
{
"answer_id": 74365053,
"author": "ILS",
"author_id": 10017662,
"author_profile": "https://Stackoverflow.com/users/10017662",
"pm_score": 3,
"selected": true,
"text": "numpy.arange"
},
{
"answer_id": 74367685,
"author": "Okapi575",
"author_id": 3373796,
"author_profile": "https://Stackoverflow.com/users/3373796",
"pm_score": 0,
"selected": false,
"text": "np.arange(start, end)[:,None]*np.ones(n_cols)\n"
},
{
"answer_id": 74375906,
"author": "w-m",
"author_id": 463796,
"author_profile": "https://Stackoverflow.com/users/463796",
"pm_score": 0,
"selected": false,
"text": "np.arange(start, end)[:, np.newaxis].repeat(n_cols, axis=1)\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19111700/"
] |
74,364,964 | <p>I have multiple csv files present in hadoop folder. each csv files will have the header present with it. the header will remain the same in each file.</p>
<p>I am writing these csv files with the help of spark dataset like this in java</p>
<p><code>df.write().csv(somePath)</code></p>
<p>I was also thinking of using coalsec(1) but it is not memory efficient in my case</p>
<p>I know that this write will also create some redundant files in a folder. so need to handle that also</p>
<p>I want to merge all these csv files into one big csv files but I don't want to repeat the header in the combined csv files.I just want one line of header on top of data in my csv file</p>
<p>I am working with python to merging these files. I know I can use hadoop getmerge command but it will merge the headers also which are present in each csv files</p>
<p>so I am not able to figure out how should I merge all the csv files without merging the headers</p>
| [
{
"answer_id": 74365281,
"author": "viniciusfelipe",
"author_id": 20452202,
"author_profile": "https://Stackoverflow.com/users/20452202",
"pm_score": 0,
"selected": false,
"text": "# importing libraries\nimport pandas as pd\nimport glob\nimport os\n \n# merging the files\njoined_files = os.path.join(\"/hadoop\", \"*.csv\")\n \n# A list of all joined files is returned\njoined_list = glob.glob(joined_files)\n \n# Finally, the files are joined\ndf = pd.concat(map(pd.read_csv, joined_list), ignore_index=True)\n"
},
{
"answer_id": 74377309,
"author": "OneCricketeer",
"author_id": 2308683,
"author_profile": "https://Stackoverflow.com/users/2308683",
"pm_score": 2,
"selected": true,
"text": "coalesce(1)"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15170477/"
] |
74,364,987 | <p>I was tasked with writing code that would convert strings into their initials via a function. For example, running "Dog" and "Cat" through the function would yield an output of "D. C.". However, another component of the task is that the code must require at least 2 strings to run. This is where I'm getting stuck.</p>
<p>Here's my code which works fine, just missing the "require 2 strings to run" part. Any suggestions for optimizing the code would be helpful as well.</p>
<pre><code>
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
string initials(string&, string&, string&, string&, string&);
int main()
{
string a = "This";
string b = "Is";
string c = "A";
string d = "Test";
string e = "Run";
initials(a, b, c, d, e);
cout << a << ". " << b << ". " << c << ". " << d << ". " <<e;
}
string initials(string& a, string& b, string& c, string& d, string& e) {
a = a[0];
b = b[0];
c = c[0];
d = d[0];
e = e[0];
return a;
return b;
return c;
return d;
return e;
}
</code></pre>
<p>My code only allows for 5 strings to go through the function, but it also has to require at least 2 for the code to run. The output for the provided code yields "T. I. A. T. R.", which is what I wanted. However, the code below also runs fine. How can I force the code to only run if there are at least two strings run through the function?</p>
<pre><code>
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
string initials(string&, string&, string&, string&, string&);
int main()
{
string a = "This";
string b;
string c;
string d;
string e;
initials(a, b, c, d, e);
cout << a << ". " << b << ". " << c << ". " << d << ". " <<e;
}
string initials(string& a, string& b, string& c, string& d, string& e) {
a = a[0];
b = b[0];
c = c[0];
d = d[0];
e = e[0];
return a;
return b;
return c;
return d;
return e;
}
</code></pre>
| [
{
"answer_id": 74365281,
"author": "viniciusfelipe",
"author_id": 20452202,
"author_profile": "https://Stackoverflow.com/users/20452202",
"pm_score": 0,
"selected": false,
"text": "# importing libraries\nimport pandas as pd\nimport glob\nimport os\n \n# merging the files\njoined_files = os.path.join(\"/hadoop\", \"*.csv\")\n \n# A list of all joined files is returned\njoined_list = glob.glob(joined_files)\n \n# Finally, the files are joined\ndf = pd.concat(map(pd.read_csv, joined_list), ignore_index=True)\n"
},
{
"answer_id": 74377309,
"author": "OneCricketeer",
"author_id": 2308683,
"author_profile": "https://Stackoverflow.com/users/2308683",
"pm_score": 2,
"selected": true,
"text": "coalesce(1)"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74364987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20344353/"
] |
74,365,066 | <p>How can I make a program in C# that gets 3 digits from the user and outputs the smallest one? It's gonna be as a Console App.</p>
<p>I tried this and gave me an error (I may be stupid):</p>
<pre><code>if (a<b<c)
{
min=a;
Console.WriteLine("Min: " + min);
</code></pre>
<p>I don't now what else should I do, I'm new to C#.</p>
| [
{
"answer_id": 74365155,
"author": "Austin",
"author_id": 12571241,
"author_profile": "https://Stackoverflow.com/users/12571241",
"pm_score": 2,
"selected": false,
"text": "int min;\n"
},
{
"answer_id": 74365188,
"author": "Sergey",
"author_id": 998737,
"author_profile": "https://Stackoverflow.com/users/998737",
"pm_score": 0,
"selected": false,
"text": "if (a < b && a < c)\n{\n Console.WriteLine(\"Min: \" + a);\n}\nelse if (b < c)\n{\n Console.WriteLine(\"Min: \" + b);\n}\nelse\n{\n Console.WriteLine(\"Min: \" + c);\n}\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74365066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16516830/"
] |
74,365,073 | <p>I am trying to change my source image of UI.Image with script. You can see below that there are two versions with the former (the one commented) working but the latter not. I have tried to change the texture type from Default to Sprite (2D and UI) but it still not working. Can someone explain why?</p>
<pre><code>//var tex = Resources.Load<Texture2D>("candy_110/candy1_green_01");
//GetComponent<Image>().sprite = Sprite.Create(tex, new Rect(0.0f, 0.0f, tex.width, tex.height), new Vector2(0.5f, 0.5f));
GetComponent<Image>().sprite = Resources.Load<Sprite>("candy_110/candy1_green_01");
</code></pre>
<p>Update 1: Because everyone wants to make sure that Resources.Load does not return any error, I post here 2 screenshots of the asset layout and the console.
<a href="https://i.stack.imgur.com/nN4yM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nN4yM.png" alt="Screenshot of assets layout" /></a></p>
<p><a href="https://i.stack.imgur.com/PIfCS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PIfCS.png" alt="Screenshot of console log" /></a></p>
| [
{
"answer_id": 74369587,
"author": "fp Van",
"author_id": 20415202,
"author_profile": "https://Stackoverflow.com/users/20415202",
"pm_score": 0,
"selected": false,
"text": "Resources.Load(\"candy_110/candy1_green_01\")"
},
{
"answer_id": 74375336,
"author": "Andriy Marshalek",
"author_id": 15382343,
"author_profile": "https://Stackoverflow.com/users/15382343",
"pm_score": 1,
"selected": false,
"text": "Sprite Mode"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74365073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9508705/"
] |
74,365,095 | <p>Automating small business reporting from my Quickbooks P&L. I'm trying to get the net income value for the current month from a specific cell in a dataframe, but that cell moves one column to the right every month when I update the csv file.</p>
<p>For example, for the code below, this month I want the value from Nov[0], but next month I'll want the value from Dec[0], even though that column doesn't exist yet.</p>
<p>Is there a graceful way to always select the second right most column, or is this a stupid way to try and get this information?</p>
<pre><code>import numpy as np
import pandas as pd
nov = -810
dec = 14958
total = 8693
d = {'Jan': [50], 'Feb': [70], 'Total':[120]}
df = pd.DataFrame(data=d)
</code></pre>
| [
{
"answer_id": 74369587,
"author": "fp Van",
"author_id": 20415202,
"author_profile": "https://Stackoverflow.com/users/20415202",
"pm_score": 0,
"selected": false,
"text": "Resources.Load(\"candy_110/candy1_green_01\")"
},
{
"answer_id": 74375336,
"author": "Andriy Marshalek",
"author_id": 15382343,
"author_profile": "https://Stackoverflow.com/users/15382343",
"pm_score": 1,
"selected": false,
"text": "Sprite Mode"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74365095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19453328/"
] |
74,365,103 | <p>I have a small code created in python and from an api I would like to go through all the
<code>code = url.json()["data"][0]["name"]</code></p>
<p>But I do not know how to do it</p>
<p>this is my little code:</p>
<pre><code>import requests
swf = input("write: ")
url = requests.get(f"https://apihabbo.com/api/furnis?hotel=es&name={swf}")
code = url.json()["data"][0]["name"]
print(code)
</code></pre>
<p>Can someone help me, thank you very much in advance!</p>
<p>this is the url:
<a href="https://apihabbo.com/api/furnis?hotel=es&name=ducha" rel="nofollow noreferrer">https://apihabbo.com/api/furnis?hotel=es&name=ducha</a></p>
<p>I have tried with this code, but no success</p>
<pre><code>response = requests.get("https://apihabbo.com/api/furnis?hotel=es&name=Gorro%20con%20Pomp%C3%B3n")
data = response.json()
for i in data['data'][0]['code']:
print("{}".format(i['code']))
</code></pre>
| [
{
"answer_id": 74365170,
"author": "Barmar",
"author_id": 1491895,
"author_profile": "https://Stackoverflow.com/users/1491895",
"pm_score": 1,
"selected": false,
"text": "data['data'][0]['code']"
},
{
"answer_id": 74365184,
"author": "Liam Pieri",
"author_id": 1325202,
"author_profile": "https://Stackoverflow.com/users/1325202",
"pm_score": 0,
"selected": false,
"text": "response = requests.get(\"https://apihabbo.com/api/furnis?hotel=es&name=Gorro%20con%20Pomp%C3%B3n\")\n\ndata = response.json()\nfor i in data['data']:\n print(\"{}\".format(i['code']))\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74365103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20452313/"
] |
74,365,112 | <p>my React Webapp has some strange behaivior, I have implemented a global edit mode, which can be activated and deactivated, the state variable which controls this gets passed by a ContextProvider. When activated, a button gets inserted into the DOM, which can open up a form.</p>
<pre><code>{edit ?
<button
onClick={setShowLinkForm(true)}
className="btn card w-36 h-36 bg-base-100 hover:bg-slate-700 shadow-xl items-center justify-center p-4 glassmorphism cursor-pointer"
>
<svg className="w-12" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6">
<path stroke-linecap="round" stroke-linejoin="round" d="M12 9v6m3-3H9m12 0a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</button>
: "" }
</code></pre>
<p>Now the strange thing is, when the button gets inserted, it triggers the onClick event automatically, is there any workaround besides controlling the activation and deactivation with CSS?</p>
<p>Edit: People suggest i need to call the function "setShowLinkForm" in a callback, i did that it now looks like this:</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>onClick={() => {
setShowLinkForm(true);
}}</code></pre>
</div>
</div>
</p>
<p>Now it gets even stranger, the event still gets triggered on insertion and as long as "edit" is true, which means the button is inserted it somehow blocks the state of "showLinkForm" which gets changed by "setShowLinkForm". If edit is false and the Button is removed, the state "showLinkForm" is changeable again.</p>
| [
{
"answer_id": 74365160,
"author": "sumowrestler",
"author_id": 4504046,
"author_profile": "https://Stackoverflow.com/users/4504046",
"pm_score": 1,
"selected": false,
"text": "onClick"
},
{
"answer_id": 74365252,
"author": "IamAAARIANME",
"author_id": 15921653,
"author_profile": "https://Stackoverflow.com/users/15921653",
"pm_score": 0,
"selected": false,
"text": "<button\n onClick={() => {\n yourFunc(true);\n }}>\n Click me to run onclick\n</button>\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74365112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9212944/"
] |
74,365,129 | <p>When I try to run <code>!pip install google-cloud-vision</code> and <code>from google.cloud import vision</code>on google colab</p>
<p>I get the following error:</p>
<blockquote>
<p>ContextualVersionConflict (protobuf 3.17.3 (/usr/local/lib/python3.7/dist-packages), Requirement.parse('protobuf!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5,<5.0.0dev,>=3.19.5'), {'google-cloud-vision'})</p>
</blockquote>
<p>I try several ways, it is not working</p>
<ol>
<li>use !ls to check the protobuf in the colab path, it shows "protobuf-4.21.9.dist-info"</li>
<li>try to !pip install protobuf ==4.21.1</li>
<li>!gitclone the whole package of protobuf from github under the colab path of /content</li>
</ol>
<p>I wonder if i am putting into a wrong route, or is there any thing else i can try to solve this problem.</p>
| [
{
"answer_id": 74365160,
"author": "sumowrestler",
"author_id": 4504046,
"author_profile": "https://Stackoverflow.com/users/4504046",
"pm_score": 1,
"selected": false,
"text": "onClick"
},
{
"answer_id": 74365252,
"author": "IamAAARIANME",
"author_id": 15921653,
"author_profile": "https://Stackoverflow.com/users/15921653",
"pm_score": 0,
"selected": false,
"text": "<button\n onClick={() => {\n yourFunc(true);\n }}>\n Click me to run onclick\n</button>\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74365129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20452149/"
] |
74,365,144 | <p>I am practicing React now and I have a task that I am not sure how to do
The main idea is to filter tasks in todos list when you type user ID
I created another button and when you type user's id it will show exact user's tasks
I did filter tasks as well just for practice, but don't know how to filter user's tasks when you type his id</p>
<p>upd: the problem seems like when you type something in input type becomes string, but I need number</p>
<pre><code>import React from "react"
import {useState, useMemo, useEffect} from "react"
function App() {
const [tasks, setTasks] = useState([])
const [completed, setCompleted] = useState(false)
const [title, setTitle] = useState("")
const [userId, setUserId] = useState(1)
const onToggleFilter = () => {
setCompleted(!completed)
}
const onTitleChange = (event) => {
setTitle(event.target.value)
}
const onUserChange = (event) => {
setUserId(event.target.value)
}
let filteredTask = useMemo(() => {
console.log("Filter by status")
return tasks.filter((task) => task.completed === completed)
}, [tasks, completed])
//console.log("Rerender")
if(title) {
filteredTask = filteredTask.filter((task) => task.title.indexOf(title) >= 0)
}
if(userId) {
filteredTask = filteredTask.filter((item) => item.userId === userId)
}
console.log(userId)
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/todos")
.then(response => response.json())
.then(todos => setTasks(todos))
}, [])
return(
<div className="App">
<h1>Task list</h1>
<div>
<button onClick={onToggleFilter}>
{
completed ? "Show tasks in work" : "Show completed tasks"
}
</button>
<br/>
<br/>
<input onChange={onTitleChange}/>
<input onChange={onUserChange}/>
<br/>
<br/>
{
filteredTask.map((task) => <div key={task.id}>{task.title}</div>)
}
</div>
</div>
)
}
export default App
</code></pre>
| [
{
"answer_id": 74365814,
"author": "twharmon",
"author_id": 5808504,
"author_profile": "https://Stackoverflow.com/users/5808504",
"pm_score": 2,
"selected": true,
"text": "parseInt"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74365144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19501234/"
] |
74,365,266 | <p>I have a model with some fields with a verbose_name. This verbose name is suitable for the admin edit page, but definitively too long for the list page.</p>
<p>How to set the label to be used in the <code>list_display</code> admin page ?</p>
| [
{
"answer_id": 74365388,
"author": "Willem Van Onsem",
"author_id": 67579,
"author_profile": "https://Stackoverflow.com/users/67579",
"pm_score": 1,
"selected": false,
"text": "verbose_name"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74365266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1745291/"
] |
74,365,331 | <p>I am working on a mobile application and I want to create a list of images like in this example\</p>
<p><a href="https://i.stack.imgur.com/jP8TY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jP8TY.png" alt="enter image description here" /></a></p>
<p>I searched about it but didn't know what it was called or how I can do it in react-native (with expo).</p>
<p>is there any library to make this or how can I create it from scratch?</p>
| [
{
"answer_id": 74365899,
"author": "user18309290",
"author_id": 18309290,
"author_profile": "https://Stackoverflow.com/users/18309290",
"pm_score": 3,
"selected": true,
"text": "flexDirection"
},
{
"answer_id": 74366905,
"author": "Michael Bahl",
"author_id": 5905466,
"author_profile": "https://Stackoverflow.com/users/5905466",
"pm_score": 1,
"selected": false,
"text": "import * as React from 'react';\nimport { View } from 'react-native';\n\nconst StackedFloatingChip: React.FC<{ children: JSX.Element[] }> = ({\n children,\n}) => {\n return (\n <View style={{ alignItems: 'center' }}>\n <View style={{ flex: 0 }}>\n {children.map((floatingChip, index) => {\n return (\n <View\n style={{\n flexDirection: 'row',\n position: 'absolute',\n flex: 0,\n left:( (-20 + CHIP_METRICS) * index),\n zIndex: children.length - index\n }}>\n {floatingChip}\n </View>\n );\n })}\n </View>\n </View>\n );\n};\n\nconst FloatingChip: React.FC<{ color: string }> = ({ color = '#ff00ff' }) => {\n return (\n <View\n style={{\n width: CHIP_METRICS,\n height: CHIP_METRICS,\n borderRadius: CHIP_METRICS / 2,\n backgroundColor: color,\n borderWidth: 5,\n borderColor: 'black',\n }}></View>\n );\n};\n\nfunction App() {\n const chips = CHIP_COLORS.map((chipcolor) => (\n <FloatingChip color={chipcolor} />\n ));\n\n return (\n <View style={{ flex: 1, justifyContent: 'center' }}>\n <StackedFloatingChip>{chips}</StackedFloatingChip>\n </View>\n );\n}\n\nconst CHIP_COLORS = ['#ff00ff', '#ff0000', 'orange', 'green'];\nconst CHIP_METRICS = 50;\n\nexport default App;"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74365331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13546478/"
] |
74,365,340 | <p>This is my App.js. I'm trying to add bottom tabs for my app.</p>
<p>`</p>
<pre><code>import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import Home from './components/Home';
import Details from './components/Details';
import Liked from './components/Liked';
import Profile from './components/Profile';
import colors from './assets/colors/colors';
import Entypo from 'react-native-vector-icons/Entypo';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
Entypo.loadFont();
const Stack = createStackNavigator();
const Tab = createBottomTabNavigator();
const TabNavigator = () => {
return (
<Tab.Navigator
screenOptions={{
headerShown: false,
tabBarStyle: styles.tabBar,
tabBarActiveTintColor: colors.orange,
tabBarInactiveTintColor: colors.gray,
}}>
<Tab.Screen name="Home" component={Home}
options={{
tabBarIcon: ({ size, color }) =>
<Entypo name="home" size={size} color={color} />,
}} />
<Tab.Screen name="Liked" component={Liked} options={{
tabBarIcon: ({ size, color }) =>
<Entypo name="home" size={size} color={color} />,
}} />
<Tab.Screen name="Profile" component={Profile} options={{
tabBarIcon: ({ size, color }) =>
<Entypo name="home" size={size} color={color} />,
}} />
</Tab.Navigator>
)
}
const App = () => {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="TabNavigator" component={TabNavigator} />
</Stack.Navigator>
</NavigationContainer>
);
};
const styles = StyleSheet.create({
tabBar: {
position: 'absolute',
backgroundColor: colors.white,
borderTopLeftRadius: 20,
borderTopRightRadius: 20,
},
})
export default App;
</code></pre>
<p>`</p>
<p>This is my dependencies
`</p>
<pre><code>"dependencies": {
"@react-native-masked-view/masked-view": "^0.2.8",
"@react-navigation/bottom-tabs": "^6.4.0",
"@react-navigation/native": "^6.0.13",
"@react-navigation/stack": "^6.3.4",
"react": "18.1.0",
"react-native": "0.70.4",
"react-native-gesture-handler": "^2.8.0",
"react-native-ionicons": "^4.6.5",
"react-native-safe-area-context": "^4.4.1",
"react-native-screens": "^3.18.2",
"react-native-vector-icons": "^9.2.0"
},
</code></pre>
<p>`</p>
<p>This is android build</p>
<p><a href="https://i.stack.imgur.com/tLMeW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tLMeW.png" alt="Bottom tab icons are not showing" /></a></p>
<p>What can I do?</p>
<p>I want to get showed bottom tab icons. I tried other icon packages as well. (eg: feather, MaterialCommunityIcons and Ionicons). I think icon pack works fine. What can I do for this?</p>
| [
{
"answer_id": 74365899,
"author": "user18309290",
"author_id": 18309290,
"author_profile": "https://Stackoverflow.com/users/18309290",
"pm_score": 3,
"selected": true,
"text": "flexDirection"
},
{
"answer_id": 74366905,
"author": "Michael Bahl",
"author_id": 5905466,
"author_profile": "https://Stackoverflow.com/users/5905466",
"pm_score": 1,
"selected": false,
"text": "import * as React from 'react';\nimport { View } from 'react-native';\n\nconst StackedFloatingChip: React.FC<{ children: JSX.Element[] }> = ({\n children,\n}) => {\n return (\n <View style={{ alignItems: 'center' }}>\n <View style={{ flex: 0 }}>\n {children.map((floatingChip, index) => {\n return (\n <View\n style={{\n flexDirection: 'row',\n position: 'absolute',\n flex: 0,\n left:( (-20 + CHIP_METRICS) * index),\n zIndex: children.length - index\n }}>\n {floatingChip}\n </View>\n );\n })}\n </View>\n </View>\n );\n};\n\nconst FloatingChip: React.FC<{ color: string }> = ({ color = '#ff00ff' }) => {\n return (\n <View\n style={{\n width: CHIP_METRICS,\n height: CHIP_METRICS,\n borderRadius: CHIP_METRICS / 2,\n backgroundColor: color,\n borderWidth: 5,\n borderColor: 'black',\n }}></View>\n );\n};\n\nfunction App() {\n const chips = CHIP_COLORS.map((chipcolor) => (\n <FloatingChip color={chipcolor} />\n ));\n\n return (\n <View style={{ flex: 1, justifyContent: 'center' }}>\n <StackedFloatingChip>{chips}</StackedFloatingChip>\n </View>\n );\n}\n\nconst CHIP_COLORS = ['#ff00ff', '#ff0000', 'orange', 'green'];\nconst CHIP_METRICS = 50;\n\nexport default App;"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74365340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12310859/"
] |
74,365,375 | <p>I would like to create a tuple dictionary of a dataframe. Currently, I have a dataframe looking like this:</p>
<hr />
<pre><code>xxxxxxxxx | Period 1 | Period 2 |
Customer | -------- | -------- |
Customer 1| 31 | 222 |
Customer 2| 46 | 187 |
</code></pre>
<hr />
<p>I would like to get a tuple dictionary of this:</p>
<pre><code>tuple_dict =
{('Customer 1', 'Period 1'): 31,
('Customer 2', 'Period 1'): 46,
('Customer 1', 'Period 2'): 222,
('Customer 2', 'Period 2'): 187}
</code></pre>
<p>It is probably posted somewhere already but I can't find it unfortunately. Could somebody help me?</p>
<p>Currently I converted the above looking table to a dictionary with</p>
<pre><code>dict = df.to_dict():
</code></pre>
<p>This created 4 seperate dictionaries (one for each period),</p>
<pre><code>Period 1: {'Customer 1': 31, 'Customer 2': 46}
Period 2: {'Customer 1': 222 ,'Customer 2': 187}
</code></pre>
<p>But I really would like to have tuple dictionaries as described above. Thank you so much for helping!</p>
| [
{
"answer_id": 74365899,
"author": "user18309290",
"author_id": 18309290,
"author_profile": "https://Stackoverflow.com/users/18309290",
"pm_score": 3,
"selected": true,
"text": "flexDirection"
},
{
"answer_id": 74366905,
"author": "Michael Bahl",
"author_id": 5905466,
"author_profile": "https://Stackoverflow.com/users/5905466",
"pm_score": 1,
"selected": false,
"text": "import * as React from 'react';\nimport { View } from 'react-native';\n\nconst StackedFloatingChip: React.FC<{ children: JSX.Element[] }> = ({\n children,\n}) => {\n return (\n <View style={{ alignItems: 'center' }}>\n <View style={{ flex: 0 }}>\n {children.map((floatingChip, index) => {\n return (\n <View\n style={{\n flexDirection: 'row',\n position: 'absolute',\n flex: 0,\n left:( (-20 + CHIP_METRICS) * index),\n zIndex: children.length - index\n }}>\n {floatingChip}\n </View>\n );\n })}\n </View>\n </View>\n );\n};\n\nconst FloatingChip: React.FC<{ color: string }> = ({ color = '#ff00ff' }) => {\n return (\n <View\n style={{\n width: CHIP_METRICS,\n height: CHIP_METRICS,\n borderRadius: CHIP_METRICS / 2,\n backgroundColor: color,\n borderWidth: 5,\n borderColor: 'black',\n }}></View>\n );\n};\n\nfunction App() {\n const chips = CHIP_COLORS.map((chipcolor) => (\n <FloatingChip color={chipcolor} />\n ));\n\n return (\n <View style={{ flex: 1, justifyContent: 'center' }}>\n <StackedFloatingChip>{chips}</StackedFloatingChip>\n </View>\n );\n}\n\nconst CHIP_COLORS = ['#ff00ff', '#ff0000', 'orange', 'green'];\nconst CHIP_METRICS = 50;\n\nexport default App;"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74365375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20110815/"
] |
74,365,381 | <p>I am in Unity 2D and I need to delay the jump, because right now you can just spam jump, which shouldn't happen, it is not good for a platformer. Here is my whole movement script:</p>
<pre><code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
public Vector2 speed = new Vector2(15, 15);
// Update is called once per frame
void Update()
{
float inputX = Input.GetAxis("Horizontal");
float inputY = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(speed.x * inputX, speed.y * inputY, 0);
movement *= Time.deltaTime;
transform.Translate(movement);
}
}
</code></pre>
<p>I lowered the speed from 50 to 15, I expected if you couldn't jump as high you wouldn't be able to spam, couldn't move up as high too quickly, but you could still spam jump.</p>
| [
{
"answer_id": 74365899,
"author": "user18309290",
"author_id": 18309290,
"author_profile": "https://Stackoverflow.com/users/18309290",
"pm_score": 3,
"selected": true,
"text": "flexDirection"
},
{
"answer_id": 74366905,
"author": "Michael Bahl",
"author_id": 5905466,
"author_profile": "https://Stackoverflow.com/users/5905466",
"pm_score": 1,
"selected": false,
"text": "import * as React from 'react';\nimport { View } from 'react-native';\n\nconst StackedFloatingChip: React.FC<{ children: JSX.Element[] }> = ({\n children,\n}) => {\n return (\n <View style={{ alignItems: 'center' }}>\n <View style={{ flex: 0 }}>\n {children.map((floatingChip, index) => {\n return (\n <View\n style={{\n flexDirection: 'row',\n position: 'absolute',\n flex: 0,\n left:( (-20 + CHIP_METRICS) * index),\n zIndex: children.length - index\n }}>\n {floatingChip}\n </View>\n );\n })}\n </View>\n </View>\n );\n};\n\nconst FloatingChip: React.FC<{ color: string }> = ({ color = '#ff00ff' }) => {\n return (\n <View\n style={{\n width: CHIP_METRICS,\n height: CHIP_METRICS,\n borderRadius: CHIP_METRICS / 2,\n backgroundColor: color,\n borderWidth: 5,\n borderColor: 'black',\n }}></View>\n );\n};\n\nfunction App() {\n const chips = CHIP_COLORS.map((chipcolor) => (\n <FloatingChip color={chipcolor} />\n ));\n\n return (\n <View style={{ flex: 1, justifyContent: 'center' }}>\n <StackedFloatingChip>{chips}</StackedFloatingChip>\n </View>\n );\n}\n\nconst CHIP_COLORS = ['#ff00ff', '#ff0000', 'orange', 'green'];\nconst CHIP_METRICS = 50;\n\nexport default App;"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74365381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19097364/"
] |
74,365,399 | <p>I am learning the php code.
I'm in a situation where it has to be done as soon as possible.
Please help me reorganize my xml duplicate data.</p>
<p>original .xml file</p>
<pre><code><products>
<product>
<ID>ID1</ID>
<SKU_parent>SKU1</SKU_parent>
<SKU>MA</SKU>
<price>10</price>
<price-sale>5</price-sale>
<KHO1>10</KHO1>
<KHO2>6</KHO2>
<KHO3>2</KHO3>
</product>
<product>
<ID>ID2</ID>
<SKU_parent>SKU2</SKU_parent>
<SKU>MA2</SKU>
<price>500</price>
<price-sale>200</price-sale>
<KHO1>20</KHO1>
<KHO2>0</KHO2>
<KHO3>0</KHO3>
</product>
<product>
<ID>ID3</ID>
<SKU_parent>SKU2</SKU_parent>
<SKU>MA2</SKU>
<price>500</price>
<price-sale>200</price-sale>
<KHO1>0</KHO1>
<KHO2>30</KHO2>
<KHO3>0</KHO3>
</product>
<product>
<ID>ID2</ID>
<SKU_parent>SKU2</SKU_parent>
<SKU>MA2</SKU>
<price>500</price>
<price-sale>200</price-sale>
<KHO1>0</KHO1>
<KHO2>0</KHO2>
<KHO3>40</KHO3>
</product>
</code></pre>
<p>into something like this:</p>
<pre><code><products>
<product>
<ID>ID1</ID>
<SKU_parent>SKU1</SKU_parent>
<SKU>MA</SKU>
<price>10</price>
<price-sale>5</price-sale>
<KHO1>10</KHO1>
<KHO2>6</KHO2>
<KHO3>2</KHO3>
</product>
<product>
<ID>ID2</ID>
<SKU_parent>SKU2</SKU_parent>
<SKU>MA2</SKU>
<price>500</price>
<price-sale>200</price-sale>
<KHO1>20</KHO1>
<KHO2>30</KHO2>
<KHO3>40</KHO3>
</product>
</code></pre>
<p>I've tried searching on stackoverflow but it doesn't seem to work.
I appreciate it when someone help me with this php code</p>
| [
{
"answer_id": 74365874,
"author": "Valeriu Ciuca",
"author_id": 4527645,
"author_profile": "https://Stackoverflow.com/users/4527645",
"pm_score": 1,
"selected": false,
"text": "SKU_parent"
},
{
"answer_id": 74366116,
"author": "Rob Eyre",
"author_id": 20418616,
"author_profile": "https://Stackoverflow.com/users/20418616",
"pm_score": 0,
"selected": false,
"text": "product->ID"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74365399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14302722/"
] |
74,365,410 | <p>I want to get the duplicates between two lists. Something like this:</p>
<pre><code>list1 = [1,2,3,4,5]
list2 = [1,2,8,4,6]
duplicates = getDuplicates(list1, list2)
print(duplicates) # => = [1,2,4]
</code></pre>
<p>I tried to search for an answer, but I only found how to remove the duplicates.</p>
| [
{
"answer_id": 74365442,
"author": "jsbueno",
"author_id": 108205,
"author_profile": "https://Stackoverflow.com/users/108205",
"pm_score": 0,
"selected": false,
"text": "set1 = set(list1)\nduplicates = [item for item in list2 if item in set1]\n"
},
{
"answer_id": 74365461,
"author": "Michael M.",
"author_id": 13376511,
"author_profile": "https://Stackoverflow.com/users/13376511",
"pm_score": 1,
"selected": false,
"text": "set"
},
{
"answer_id": 74369174,
"author": "Nijat Mursali",
"author_id": 10489887,
"author_profile": "https://Stackoverflow.com/users/10489887",
"pm_score": 0,
"selected": false,
"text": "duplicates = [i for i in list1 if i in list2]\n"
},
{
"answer_id": 74369209,
"author": "Germ",
"author_id": 4646017,
"author_profile": "https://Stackoverflow.com/users/4646017",
"pm_score": 0,
"selected": false,
"text": "list1 = [1, 2, 3, 4, 5]\nlist2 = [1, 2, 8, 4, 6]\nprint (set(list1) & set(list2))\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74365410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20452467/"
] |
74,365,423 | <pre><code>import statistics
def main():
with open('Grades.txt', mode='w') as Grades:
Grade = input("Please enter student grades. " ) #Gets Input from User
Grades.write(str(Grade) + '\n') #Has the student grades written into the Grades text file and has each of them on a new line.
with open('Grades.txt', mode='r') as Grades: #Opens the Grades File in read and then prints Mean, Total, Count, Median, Min, Max, Std, Grades
print(f'{"Mean"}')
for record in Grades:
grade = record.split()
print("Mean of the sample is " %(statistics.mean('grade')))
print(f'{"Total"}')
print(f'{"Count"}')
print(f'{"Median"}')
for record in Grades:
grade = record.split()
print("Median of the sample is " %(statistics.median('grade')))
print(f'{"Min"}')
for record in Grades:
grade = record.split()
print("Minimum of the sample is " %(min('grade')))
print(f'{"Max"}')
for record in Grades:
grade = record.split()
print("Maximum of the sample is " %(max('grade')))
print(f'{"Std"}')
for record in Grades:
grade = record.split()
print("Standard Deviation of the sample is % s " %(statistics.mean('grade')))
for record in Grades: #For the record in Grades Files It takes the grade in the record and splits and prints the Grades
grade = record.split()
print(f'This is the Grades of the students {grade}')
main()
</code></pre>
<p>I'm stuck on this still learning python.
Trying convert the str to int and then get the mean, median, total etc
...................................................................................................</p>
| [
{
"answer_id": 74365442,
"author": "jsbueno",
"author_id": 108205,
"author_profile": "https://Stackoverflow.com/users/108205",
"pm_score": 0,
"selected": false,
"text": "set1 = set(list1)\nduplicates = [item for item in list2 if item in set1]\n"
},
{
"answer_id": 74365461,
"author": "Michael M.",
"author_id": 13376511,
"author_profile": "https://Stackoverflow.com/users/13376511",
"pm_score": 1,
"selected": false,
"text": "set"
},
{
"answer_id": 74369174,
"author": "Nijat Mursali",
"author_id": 10489887,
"author_profile": "https://Stackoverflow.com/users/10489887",
"pm_score": 0,
"selected": false,
"text": "duplicates = [i for i in list1 if i in list2]\n"
},
{
"answer_id": 74369209,
"author": "Germ",
"author_id": 4646017,
"author_profile": "https://Stackoverflow.com/users/4646017",
"pm_score": 0,
"selected": false,
"text": "list1 = [1, 2, 3, 4, 5]\nlist2 = [1, 2, 8, 4, 6]\nprint (set(list1) & set(list2))\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74365423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20452513/"
] |
74,365,441 | <p>Just downloaded and installed SDK Net 7.0.100 and it broke existing applications and they won't load any more in VS 2022 or Rider.</p>
<p>Copied the follwing error:</p>
<pre><code>error : SDK Resolver Failure: "The SDK resolver "Microsoft.DotNet.MSBuildSdkResolver"
failed while attempting to resolve the SDK "Microsoft.NET.Sdk". Exception: "Microsoft.NET.Sdk.WorkloadManifestReader.WorkloadManifestCompositionException: Workload definition 'wasm-tools' in manifest 'microsoft.net.workload.mono.toolchain.net7' [C:\Program Files\dotnet\sdk-manifests\7.0.100\microsoft.net.workload.mono.toolchain.net7\WorkloadManifest.json] conflicts with manifest 'microsoft.net.workload.mono.toolchain' [C:\Program Files\dotnet\sdk-manifests\7.0.100\microsoft.net.workload.mono.toolchain\WorkloadManifest.json]
at Microsoft.NET.Sdk.WorkloadManifestReader.WorkloadResolver.ComposeWorkloadManifests()
at Microsoft.NET.Sdk.WorkloadManifestReader.WorkloadResolver.Create(IWorkloadManifestProvider manifestProvider, String dotnetRootPath, String sdkVersion, String userProfileDir)
at Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver.CachingWorkloadResolver.Resolve(String sdkReferenceName, String dotnetRootPath, String sdkVersion, String userProfileDir)
at Microsoft.DotNet.MSBuildSdkResolver.DotNetMSBuildSdkResolver.Resolve(SdkReference sdkReference, SdkResolverContext context, SdkResultFactory factory)
at Microsoft.Build.BackEnd.SdkResolution.SdkResolverService.TryResolveSdkUsingSpecifiedResolvers(IList`1 resolvers, Int32 submissionId, SdkReference
</code></pre>
| [
{
"answer_id": 74379486,
"author": "nagilson",
"author_id": 20461346,
"author_profile": "https://Stackoverflow.com/users/20461346",
"pm_score": 5,
"selected": false,
"text": "TargetFramework"
},
{
"answer_id": 74450313,
"author": "breadswonders",
"author_id": 5786959,
"author_profile": "https://Stackoverflow.com/users/5786959",
"pm_score": 0,
"selected": false,
"text": "C:\\Program Files\\dotnet\\sdk-manifests\\7.0.100"
},
{
"answer_id": 74666305,
"author": "Sahaj Raj Malla",
"author_id": 11773575,
"author_profile": "https://Stackoverflow.com/users/11773575",
"pm_score": 0,
"selected": false,
"text": "dotnet clean --interactive\n\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74365441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9586015/"
] |
74,365,464 | <p>I'm trying to make a simple hyper casual. I couldn't understand what's wrong with my codes.</p>
<p>My code:</p>
<pre><code>public class CameraFollow : MonoBehaviour
{
public Transform Target;
public Vector3 offset;
void LateUptade()
{
transform.position = Vector3.Lerp(transform.position, Target.position + offset, Time.deltaTime * 2);
}
}
</code></pre>
| [
{
"answer_id": 74365574,
"author": "Voidsay",
"author_id": 19151717,
"author_profile": "https://Stackoverflow.com/users/19151717",
"pm_score": -1,
"selected": false,
"text": "Time.deltaTime"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74365464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9819483/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.