qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,377,235 | <p>I am following this tutorial, <a href="https://learn.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/tutorials/how-to-write-csharp-analyzer-code-fix" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/tutorials/how-to-write-csharp-analyzer-code-fix</a></p>
<p>What I really want is to detect if a method in a ASP.Net Web API controller is missing my <code>Custom</code> attribute and give hints to the developer to add it.</p>
<p>In my Analyzer's Initilize method, I have chosen <code>MethodDeclaration</code> as the <code>SyntaxKind</code> like this</p>
<pre><code>context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.MethodDeclaration);
</code></pre>
<p>In the AnalyzeNode method, I want to detect if the method in question already has the <code>Custom</code> attribute added to it.</p>
<pre><code> private void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
var methodDeclaration = (MethodDeclarationSyntax)context.Node;
// make sure the declaration isn't already const:
if (methodDeclaration.AttributeLists.Any(x=> x. ))
{
return;
}
</code></pre>
<p>Not sure what needs to be done in this piece of code to find if <code>Custom</code> attribute is already applied.</p>
<p>Eventually I want my code analyzer to let the user add the missing attribute</p>
<pre><code> [Route("/routex")]
[Custom()]
public async Task<IHttpActionResult> AlreadyHasCustomAttribute()
{
//everything is good, no hint shown to the user
}
[Route("/routey")]
public async Task<IHttpActionResult> DoesNotHaveCustomAttribute()
{
//missing Custom attribute, show hint to the user and add the attribute as a code fix
}
</code></pre>
<p>Please suggest a solution. Thanks.</p>
| [
{
"answer_id": 74394817,
"author": "Jason Malinowski",
"author_id": 972216,
"author_profile": "https://Stackoverflow.com/users/972216",
"pm_score": 2,
"selected": false,
"text": "methodDeclaration.AttributeLists.Any())"
},
{
"answer_id": 74413625,
"author": "Youssef13",
"author_id": 5108631,
"author_profile": "https://Stackoverflow.com/users/5108631",
"pm_score": 0,
"selected": false,
"text": "context.RegisterCompilationStartAction(context =>\n{\n var targetAttribute = context.Compilation.GetTypeByMetadataName(\"FullyQualifiedAttributeName\");\n if (targetAttribute is null)\n {\n // Do whatever you want if the attribute doesn't exist in the first place.\n // Stopping the analysis is probably the best option?\n return;\n }\n\n context.RegisterSymbolAction(context =>\n {\n var methodSymbol = (IMethodSymbol)context.Symbol;\n if (!methodSymbol.GetAttributes().Any(attrData => targetAttribute.Equals(attrData.AttributeClass, SymbolEqualityComparer.Default))\n {\n // attribute is missing.\n // though it doesn't make sense to report a missing attribute for all methods in a compilation, so you'll likely need extra checks based on the logic of your analyzer.\n }\n }, SymbolKind.Method);\n});\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/159910/"
] |
74,377,247 | <p>I'm trying to watch spotify packages on the emulator, but the data sent and received are corrupted. How can I solve this problem?</p>
<p>İmages:</p>
<p><a href="https://i.stack.imgur.com/1cIwd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1cIwd.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/ouDo4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ouDo4.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/OJb1U.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OJb1U.png" alt="enter image description here" /></a></p>
<p>I tried reading the data many times but it always looks like this. I want to see the data properly in JSON form.</p>
| [
{
"answer_id": 74377658,
"author": "Tim Perry",
"author_id": 68051,
"author_profile": "https://Stackoverflow.com/users/68051",
"pm_score": 1,
"selected": false,
"text": "content-type"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20139460/"
] |
74,377,254 | <p>I need to set up a query that will split up a single record into multiple records based on values from multiple columns in a single table.</p>
<p>Right now, a current parcel record would read as:</p>
<pre><code>table.tax_id table.CLASS 1 table.CLASS 2 table.CLASS 3 table.CLASS 4A table.CLASS 4B
03489 0 100 0 0 600
05695 0 0 100 300 0
</code></pre>
<p>I need to generate a sequence number for each record and then split them up according to class, so the above parcels would look like this instead:</p>
<pre><code>table.tax_id table.CLASS table.VALUE table.SEQUENCE
03489 2 100 1
03489 4B 600 2
05695 3 100 1
05695 4A 300 2
</code></pre>
<p>I've tried CASE and IIF statements but couldn't get any of them to work. Any suggestions are very appreciated!</p>
| [
{
"answer_id": 74377658,
"author": "Tim Perry",
"author_id": 68051,
"author_profile": "https://Stackoverflow.com/users/68051",
"pm_score": 1,
"selected": false,
"text": "content-type"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19684094/"
] |
74,377,281 | <p>I'm a beginner in Flutter, I want to use firebase in my flutter app, I run my app on chrome because the emulator does not work, I have configured the <code>build.gradle</code> file, and the <code>pubspec.yaml</code>, when I run my app I have an error saying:</p>
<pre><code>/C:/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core-1.24.0/lib/src/firebase_app.dart:18:25: Error: Member not found: 'FirebaseAppPlatform.verifyExtends'.
FirebaseAppPlatform.verifyExtends(_delegate);
^^^^^^^^^^^^^
Waiting for connection from debug service on Chrome... 154.8s
Failed to compile application.
</code></pre>
| [
{
"answer_id": 74377658,
"author": "Tim Perry",
"author_id": 68051,
"author_profile": "https://Stackoverflow.com/users/68051",
"pm_score": 1,
"selected": false,
"text": "content-type"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20349488/"
] |
74,377,287 | <p>I have a table that stores the date of birth of patients in DateTime format(2022-06-22).</p>
<p>How can I get the age in years for people born in July?</p>
<p>I have tried the below:</p>
<pre><code>select sFirstName,
sLastName,
dDateOfBirth,
DATEDIFF(yy,dDateOfBirth,GETDATE()) as Age,
ifkMedicalAidID
from Patients
where DATEDIFF(month,dDateOfBirth,GETDATE()) between 5 and 5
</code></pre>
<p>Although I get only all the records for July(which is correct) all the ages are 0, I see the problem with the above query but I don't have the SQL knowledge to resolve it...</p>
| [
{
"answer_id": 74377385,
"author": "Kyle",
"author_id": 15321226,
"author_profile": "https://Stackoverflow.com/users/15321226",
"pm_score": -1,
"selected": false,
"text": "select sFirstName,\n sLastName,\n dDateOfBirth,\n DATEDIFF(yy,dDateOfBirth,GETDATE()) as Age,\n ifkMedicalAidID\n from Patients\n where datepart(month,dDateOfBirth)=7\n"
},
{
"answer_id": 74377617,
"author": "planetmatt",
"author_id": 12775291,
"author_profile": "https://Stackoverflow.com/users/12775291",
"pm_score": 0,
"selected": false,
"text": "SELECT \nFLOOR((DATEDIFF(DAY,0,GETDATE()) - DATEDIFF(DAY,0,dDateOfBirth)) / 365.2425) AS AgeYears\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15321226/"
] |
74,377,314 | <p>I want to get a day based on a number from 1 to 365. An integer in the range of 1 to 365 is given and I need to find the day of the week for a given day in a year (starting with Sunday).</p>
<pre><code>a = int(input()) # Integer from 1 to 365
print( # day )
</code></pre>
<p>Example: input <code>1</code>, output <code>4</code></p>
| [
{
"answer_id": 74377450,
"author": "dangarfield",
"author_id": 3265253,
"author_profile": "https://Stackoverflow.com/users/3265253",
"pm_score": 0,
"selected": false,
"text": "10 modulo 7"
},
{
"answer_id": 74377471,
"author": "BokiX",
"author_id": 16843389,
"author_profile": "https://Stackoverflow.com/users/16843389",
"pm_score": 1,
"selected": true,
"text": "days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"]\nday_number = int(input(\"What day do you want to get: \"))\nday = days[day_number % 7]\nprint(f\"Your day: {day}\")\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20460426/"
] |
74,377,320 | <p>I am having a bit of a struggle to use a dataframe that I have created. The dataframe is to keep track each day of the wake up time, 1st meal, last meal (2ndMeal here) and time when the person goes to sleep (Sleep time).</p>
<p>Here attached you can see what the initial dataframe looks like:</p>
<pre><code> Unnamed: 1 Unnamed: 2 Unnamed: 3 Unnamed: 4 Unnamed: 5
0 2022-09-06 08:03:00 12:09:00 20:19:00 22:35:00
1 2022-09-07 07:30:00 12:20:00 20:35:00 00:10:00
2 2022-09-08 08:30:00 12:15:00 21:30:00 00:33:00
3 2022-09-09 08:56:00 11:00:00 23:00:00 02:00:00
</code></pre>
<p>I convert the columns into datetime with</p>
<pre><code>test['Date'] = pd.to_datetime(df['Unnamed: 1'])
</code></pre>
<p>for the first column and</p>
<pre><code>test['WakeUp'] = pd.to_datetime(df['Unnamed: 2'], format='%H:%M:%S')
</code></pre>
<p>for the rest (cannot use the same code line as the first column or otherwise I get an error) and get this:</p>
<pre><code> Date WakeUp 1stMeal 2ndMeal Sleep
0 2022-09-06 1900-01-01 08:03:00 1900-01-01 12:09:00 1900-01-01 20:19:00 1900-01-01 22:35:00
1 2022-09-07 1900-01-01 07:30:00 1900-01-01 12:20:00 1900-01-01 20:35:00 1900-01-01 00:10:00
2 2022-09-08 1900-01-01 08:30:00 1900-01-01 12:15:00 1900-01-01 21:30:00 1900-01-01 00:33:00
3 2022-09-09 1900-01-01 08:56:00 1900-01-01 11:00:00 1900-01-01 23:00:00 1900-01-01 02:00:00
</code></pre>
<p>My problem is that I would like the dates of the WakeUp, 1stMeal, 2ndMeal and Sleep to be the same of the Date column but I am not managing to do so...</p>
<p>Additionally, if the time is beyond 00:00, I'd like the date to change so that it is show the day after and not the same day (i.e. I wake up at 7:00 of day1 but go to sleep at 2:00 of day2)</p>
<p><a href="https://i.stack.imgur.com/kqaL7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kqaL7.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/lPpAg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lPpAg.png" alt="enter image description here" /></a></p>
<p>I have tried to extract the times and used them independently but with no success (I am not sure how to manipulate them).</p>
<p>I have tried to use:</p>
<pre><code>pd.to_datetime(test['Date'].dt.date) + pd.to_datetime(test['WakeUp'].dt.time)
</code></pre>
<p>but with no success.</p>
<p>I was expecting for the sleep time to not have those large gaps due to the different dates...</p>
<p>All the help that I found online is people using dataframes with date and/or times but as x axis and never as y axis which is slowly making think that there is no solution to this...</p>
| [
{
"answer_id": 74377450,
"author": "dangarfield",
"author_id": 3265253,
"author_profile": "https://Stackoverflow.com/users/3265253",
"pm_score": 0,
"selected": false,
"text": "10 modulo 7"
},
{
"answer_id": 74377471,
"author": "BokiX",
"author_id": 16843389,
"author_profile": "https://Stackoverflow.com/users/16843389",
"pm_score": 1,
"selected": true,
"text": "days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"]\nday_number = int(input(\"What day do you want to get: \"))\nday = days[day_number % 7]\nprint(f\"Your day: {day}\")\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20458278/"
] |
74,377,360 | <p>Why can't I detect the np.nan value in data using np.isnan() in the list comprehension below? Does the list comprehension transform the type of values in some way?</p>
<pre><code>data = pd.DataFrame({'col':['a', 'b', np.nan]})
[print('NaN') if np.isnan(i) else print('Not NaN') for i in data.col]
</code></pre>
| [
{
"answer_id": 74377446,
"author": "saeedghadiri",
"author_id": 1988231,
"author_profile": "https://Stackoverflow.com/users/1988231",
"pm_score": 1,
"selected": false,
"text": "pd.isna"
},
{
"answer_id": 74377513,
"author": "Luke B",
"author_id": 8228122,
"author_profile": "https://Stackoverflow.com/users/8228122",
"pm_score": 1,
"selected": false,
"text": "pd.isnull(i)"
},
{
"answer_id": 74377531,
"author": "Celius Stingher",
"author_id": 11897007,
"author_profile": "https://Stackoverflow.com/users/11897007",
"pm_score": 3,
"selected": true,
"text": "np.isnan()"
},
{
"answer_id": 74377568,
"author": "Zelemist",
"author_id": 7512185,
"author_profile": "https://Stackoverflow.com/users/7512185",
"pm_score": 2,
"selected": false,
"text": "'a'"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8510149/"
] |
74,377,367 | <p>I have a list of specific gitlab runners. I want to create a ci script, which would pick one of them to run.</p>
<p>GitLab docs only tells how to run job with <a href="https://docs.gitlab.com/ee/ci/yaml/index.html#tags" rel="nofollow noreferrer">both tags</a>, bot not with one of them.</p>
| [
{
"answer_id": 74377446,
"author": "saeedghadiri",
"author_id": 1988231,
"author_profile": "https://Stackoverflow.com/users/1988231",
"pm_score": 1,
"selected": false,
"text": "pd.isna"
},
{
"answer_id": 74377513,
"author": "Luke B",
"author_id": 8228122,
"author_profile": "https://Stackoverflow.com/users/8228122",
"pm_score": 1,
"selected": false,
"text": "pd.isnull(i)"
},
{
"answer_id": 74377531,
"author": "Celius Stingher",
"author_id": 11897007,
"author_profile": "https://Stackoverflow.com/users/11897007",
"pm_score": 3,
"selected": true,
"text": "np.isnan()"
},
{
"answer_id": 74377568,
"author": "Zelemist",
"author_id": 7512185,
"author_profile": "https://Stackoverflow.com/users/7512185",
"pm_score": 2,
"selected": false,
"text": "'a'"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7355324/"
] |
74,377,374 | <p>How to duplicate elements of an array in Java and add them to a new array in the same order of the original array?</p>
<pre><code>// Pass an array of the form {4, 16, 8},
// The returned array should then contain {4, 4, 16, 16, 8, 8}.
public static int[] duplicateElements(final int[] elements){
int duplicate = 0 ;
int [] newArray = new int [elements.length*2];
for(int i = 0; i < elements.length;i++) {
newArray[i] = elements[i];
}
for(int j = 0; j < newArray.length/2;j++) {
newArray[newArray.length-j-1] = newArray[j];
}
for(int i = 0; i < (newArray.length/2) ;i++) {
duplicate = newArray[i];
newArray[i+1] = newArray[newArray.length-i-1];
newArray[newArray.length-i-1] = duplicate;
}
return newArray;
}
public static void main(String[] args) {
int [] newArray = new int []{4, 16, 8};
System.out.println(Arrays.toString(duplicateElements(newArray)));
}
</code></pre>
<p>Please explain why the above code is not working.</p>
<p>My output is : <code>// [4, 4, 16, 16, 4, 4]</code></p>
<p>Instead of : <code>// [4, 4, 16, 16, 8, 8]</code></p>
| [
{
"answer_id": 74378022,
"author": "chptr-one",
"author_id": 13797513,
"author_profile": "https://Stackoverflow.com/users/13797513",
"pm_score": 0,
"selected": false,
"text": "public static int[] duplicateElements(final int[] origin) {\n int[] result = new int[origin.length * 2];\n int resultIndex = 0;\n\n for (int i : origin) {\n result[resultIndex++] = i;\n result[resultIndex++] = i;\n }\n return result;\n }\n"
},
{
"answer_id": 74378484,
"author": "Joop Eggen",
"author_id": 984823,
"author_profile": "https://Stackoverflow.com/users/984823",
"pm_score": 1,
"selected": false,
"text": "public static int[] duplicateElements(final int[] elements){\n int duplicate = 0 ;\n int [] newArray = new int [elements.length*2];\n for (int i = 0; i < elements.length; i++) {\n newArray[2*i] = elements[i]; \n newArray[2*i + 1] = elements[i]; \n }\n return newArray;\n}\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16854605/"
] |
74,377,375 | <p>Given the current example array of objects:</p>
<pre><code>const data = {
...otherData,
formGroups: [{roldependence: "a", rol2dependence: "", rol3dependence: "b"},{roldependence: "", rol2dependence: "1", rol3dependence: ""}]
}
</code></pre>
<p>I need to iterate through the objects and do 3 things:
Delete empty objects
Delete empty keys
Modify key names and delete the word "dependence"</p>
<p>The new array should look like:</p>
<pre><code>console.log(data.formGroups)
// [{ rol: "a", rol3: "b" }, { rol2: 1 }]
</code></pre>
<p>What I tried so far:</p>
<pre><code>const newData = { ...data };
if (newData.formGroups) {
newData = {
...newData,
formGroups: newData.formGroups
.filter((element) => {
// Removing empty objects
if (Object.keys(element).length !== 0) {
return true;
}
return false;
})
.map((element) => {
const newElem = { ...element };
for (let key in newElem) {
// Remove dependence word
if (key.includes("dependence")) {
newElem[key.replace(/dependence([0-9]+)$/, "")] = newElem[key];
delete newElem[key];
}
// Remove empty keys
if (!newElem[key]) {
delete newElem[key];
}
}
return newElem;
}),
};
//Then the parsed "newData" will be used for something else...
</code></pre>
<p>Is there an elegant way to do this? I feel I'm mutating state in ways I shouldn´t.</p>
| [
{
"answer_id": 74377965,
"author": "AryaveerSR",
"author_id": 20459167,
"author_profile": "https://Stackoverflow.com/users/20459167",
"pm_score": 0,
"selected": false,
"text": "data.formGroups.map((formGroup) => {\n Object.keys(formGroup).forEach((key) => {\n if (formGroup[key] !== \"\") {\n formGroup[key.replace(\"dependence\", \"\")] = formGroup[key];\n }\n delete formGroup[key];\n });\n});\n"
},
{
"answer_id": 74378514,
"author": "Ben Aston",
"author_id": 38522,
"author_profile": "https://Stackoverflow.com/users/38522",
"pm_score": 3,
"selected": true,
"text": "noFalsyProps"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19632949/"
] |
74,377,429 | <p>I would like to use a value of a state variable in a JSX expression and cannot figure out the syntax. Here is simplified code:</p>
<pre><code>function App() {
const [isLoading, setIsLoading] = useState(false);
const [page, setPage] = useState(1);
return (
<div>
{isLoading ? `Loading...` : 'Load Page ' + {page}}
</div>
);
}
export default App;
</code></pre>
<p>If <code>isLoading</code> is false, I would like the output to say <strong>Load Page 1</strong>.</p>
<p>As of now it says <strong>Load Page [object Object]</strong> and I am stuck on the syntax.</p>
<p>Thanks.</p>
| [
{
"answer_id": 74377965,
"author": "AryaveerSR",
"author_id": 20459167,
"author_profile": "https://Stackoverflow.com/users/20459167",
"pm_score": 0,
"selected": false,
"text": "data.formGroups.map((formGroup) => {\n Object.keys(formGroup).forEach((key) => {\n if (formGroup[key] !== \"\") {\n formGroup[key.replace(\"dependence\", \"\")] = formGroup[key];\n }\n delete formGroup[key];\n });\n});\n"
},
{
"answer_id": 74378514,
"author": "Ben Aston",
"author_id": 38522,
"author_profile": "https://Stackoverflow.com/users/38522",
"pm_score": 3,
"selected": true,
"text": "noFalsyProps"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1417658/"
] |
74,377,438 | <p>I am trying to make something a puzzle for a school project and for one of the puzzles, it requires me to make almost like an among-us fixing wire game. The most simple way to do that and do to get to get the best result is to use buttons. But how would I make it so when my first button is clicked, the second one appears?</p>
<p>I've tried using inputs, and the text appear.</p>
| [
{
"answer_id": 74377965,
"author": "AryaveerSR",
"author_id": 20459167,
"author_profile": "https://Stackoverflow.com/users/20459167",
"pm_score": 0,
"selected": false,
"text": "data.formGroups.map((formGroup) => {\n Object.keys(formGroup).forEach((key) => {\n if (formGroup[key] !== \"\") {\n formGroup[key.replace(\"dependence\", \"\")] = formGroup[key];\n }\n delete formGroup[key];\n });\n});\n"
},
{
"answer_id": 74378514,
"author": "Ben Aston",
"author_id": 38522,
"author_profile": "https://Stackoverflow.com/users/38522",
"pm_score": 3,
"selected": true,
"text": "noFalsyProps"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20460480/"
] |
74,377,452 | <pre><code> class PopUpCard extends StatefulWidget {
final String title;
const PopUpCard({super.key, required this.title});
}
Container(
child: Card(
child: Center(
child: Text(
widget.title,
)),
),
</code></pre>
<p>I'm calling the widget I created on my homepage.</p>
<pre><code> Row(
children: const [
PopUpCard(
title: '9',
),
</code></pre>
<p><a href="https://i.stack.imgur.com/R6dds.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/R6dds.png" alt="enter image description here" /></a></p>
<p>For example, when the card number 9 is clicked, as in the image, I want a red border around it.</p>
| [
{
"answer_id": 74377600,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 1,
"selected": false,
"text": " Container(\n height: 80,\n width: 80,\n decoration: BoxDecoration(\n color: Color.fromARGB(255, 19, 85, 144),\n borderRadius: isTapped ? BorderRadius.circular(24) : null,\n border:\n isTapped ? Border.all(color: Colors.red, width: 4) : null,\n ),\n alignment: Alignment.center,\n child: Text(\"Button\"),\n),\n"
},
{
"answer_id": 74377606,
"author": "Rohan Jariwala",
"author_id": 13954519,
"author_profile": "https://Stackoverflow.com/users/13954519",
"pm_score": 0,
"selected": false,
"text": "String selectedTitle = '';\n\n\n\nGestureDetectore(\n onTap:() {\nsetState((),{\n selectedTitle = widget.title;\n});\n},\n Container(\n height: 80,\n width: 80,\n child: Card(\n color: Color.fromARGB(255, 19, 85, 144),\n shape: RoundedRectangleBorder( \n side: BorderSide(\n color: widget.title == selectedTitle ? Colors.red : Colors.transparent,\n ),\n ),\n child: Center(\n child: Text(\n widget.title,\n style: GoogleFonts.poppins(\n color: Colors.white,\n fontSize: 20,\n fontWeight: FontWeight.bold),\n )),\n ),),\n"
},
{
"answer_id": 74377627,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 2,
"selected": true,
"text": "bool isSelected = false;\n"
},
{
"answer_id": 74377634,
"author": "Fugipe",
"author_id": 17626346,
"author_profile": "https://Stackoverflow.com/users/17626346",
"pm_score": 0,
"selected": false,
"text": "List<int> listSelected = [];\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(title: Text(\"Test\")),\n body: ListView.builder(\n itemBuilder: (context, index) {\n return InkWell(\n onTap: () {\n if (listSelected.contains(index)) {\n listSelected.remove(index);\n } else {\n listSelected.add(index);\n }\n setState(() {});\n },\n child: Container(\n height: 80,\n width: 80,\n decoration: BoxDecoration(\n border: listSelected.contains(index)\n ? Border.all(color: Colors.red, width: 2)\n : null),\n child: Card(\n color: Color.fromARGB(255, 19, 85, 144),\n child: Center(\n child: Text(\n index.toString(),\n style: GoogleFonts.poppins(\n color: Colors.white,\n fontSize: 20,\n fontWeight: FontWeight.bold),\n ),\n ),\n ),\n ),\n );\n },\n ),\n );\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17906689/"
] |
74,377,462 | <p>How could I make a program that sums up all numbers in a txt file like this:</p>
<pre><code>12 49 1 4 5
4 5
14
20
4 5 91
etc..
</code></pre>
<p>I was thinking of doing for line in readline(), then checking if there are spaces in the line and splitting it if there is. How would I go about and do that?</p>
| [
{
"answer_id": 74377565,
"author": "ShlomiF",
"author_id": 5024514,
"author_profile": "https://Stackoverflow.com/users/5024514",
"pm_score": 0,
"selected": false,
"text": "int"
},
{
"answer_id": 74377722,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 1,
"selected": false,
"text": "with open('test.txt') as test:\n print(sum(map(int, test.read().split())))\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19310613/"
] |
74,377,497 | <p>So I have this folder</p>
<p><a href="https://i.stack.imgur.com/fhRcS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fhRcS.png" alt="img1" /></a></p>
<p>In which I run (using Powershell)</p>
<blockquote>
<p>Get-Content Dockerfile | docker build -</p>
</blockquote>
<p>But I get the following error :</p>
<pre><code> => ERROR [8/8] COPY docker-entrypoint.sh /
0.0s
------
> [8/8] COPY docker-entrypoint.sh /:
------
failed to compute cache key: "/docker-entrypoint.sh" not found: not found
</code></pre>
<p>This obviously has something to with an absolute path problem, but what is the intended fix for this ? I've tried multiple things from stackoverflow without success (changing CRLF to LF, using . instead of /, etc).</p>
<p>Thanks.</p>
| [
{
"answer_id": 74377592,
"author": "Hans Kilian",
"author_id": 3924803,
"author_profile": "https://Stackoverflow.com/users/3924803",
"pm_score": 3,
"selected": true,
"text": "docker build -"
},
{
"answer_id": 74377599,
"author": "Nick ODell",
"author_id": 530160,
"author_profile": "https://Stackoverflow.com/users/530160",
"pm_score": 0,
"selected": false,
"text": "docker build ."
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19800284/"
] |
74,377,503 | <p>I would like to run a shell script every time when a shell is started using <code>docker exec</code> or <code>kubectl exec</code>. I am looking for something similar to <code>.bashrc</code>/<code>.bash_profile</code>/<code>.profile</code>, but since this particular container is based on alpine linux, bash is not available.</p>
<p>How could I execute a shell script in the container?</p>
<p>I would like to achieve something like this:</p>
<pre class="lang-bash prettyprint-override"><code>> docker exec -it my_alpine_based_container sh
Hi! Welcome to the container. This message comes from a shell script.
/usr/src/app $
</code></pre>
<p>And similarly with <code>kubectl</code>:</p>
<pre class="lang-bash prettyprint-override"><code>> kubectl exec -it my_pod_running_the_container -- sh
Hi! Welcome to the container. This message comes from a shell script.
/usr/src/app $
</code></pre>
| [
{
"answer_id": 74377919,
"author": "Nick ODell",
"author_id": 530160,
"author_profile": "https://Stackoverflow.com/users/530160",
"pm_score": 1,
"selected": false,
"text": "/bin/sh"
},
{
"answer_id": 74561721,
"author": "Attila",
"author_id": 1167226,
"author_profile": "https://Stackoverflow.com/users/1167226",
"pm_score": 3,
"selected": true,
"text": "FROM alpine:latest\nENV ENV=/root/.ashrc\nRUN echo \"echo 'Hello from .ashrc!'\" >> /root/.ashrc\nCMD [\"/bin/sh\"]\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1167226/"
] |
74,377,516 | <p>I need to read the observations from this file and store them per day basis. The daily observations start with a # and below that line are the daily observations. The columns in the observations are 'LVLpTYP', 'ETIME', 'PRESSURE','GPH','TEMP','RH','DPDP','WDIR','WSPD'respectively. I don't want to skip the heading rows containing the #s as they have the timestamps.</p>
<p><a href="https://drive.google.com/file/d/1-o_M_nOSFU4J39Bczs4VfsCONrM-9l5w/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/1-o_M_nOSFU4J39Bczs4VfsCONrM-9l5w/view?usp=sharing</a></p>
<p>I couldn't come up with any solutions which will allow me to do the same.</p>
<p>This way I could read them as the strings but it's not helpful.</p>
<pre><code>import numpy as np
import sys
arrays = [np.array(list(map(str, line.split()))) for line in open('INM00043333-data.txt')]
</code></pre>
<p>The output should be something like this:</p>
<p>time_stamps = [2016 02 06, 2016 03 06...... like this] #list/array containing the time information from the #line i.e., #INM00043333 2016 02 06 00 0000 247 ncdc-gts 116667 927167</p>
<p>and</p>
<p>data = [ ] #the lines between the two #ed lines in a dataframe</p>
<p>So that the index i from the time_stamps array represents the data for the first date and so on. If I pull up a particular date from the time_stamps array it should reflect the corresponding data.</p>
| [
{
"answer_id": 74377919,
"author": "Nick ODell",
"author_id": 530160,
"author_profile": "https://Stackoverflow.com/users/530160",
"pm_score": 1,
"selected": false,
"text": "/bin/sh"
},
{
"answer_id": 74561721,
"author": "Attila",
"author_id": 1167226,
"author_profile": "https://Stackoverflow.com/users/1167226",
"pm_score": 3,
"selected": true,
"text": "FROM alpine:latest\nENV ENV=/root/.ashrc\nRUN echo \"echo 'Hello from .ashrc!'\" >> /root/.ashrc\nCMD [\"/bin/sh\"]\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17581930/"
] |
74,377,526 | <p>I am making a terminal app in javascript. But the problem is that I can't use innerHTML method. I tried using innerText method, but it doesnt apply multi space and & nbsp; is also ignore.
For example:</p>
<pre><code>example.innerText = "a&nbsp;&nbsp;b"; //output is not 'a b'
</code></pre>
<p>I would be glab if someone could help me.</p>
| [
{
"answer_id": 74377919,
"author": "Nick ODell",
"author_id": 530160,
"author_profile": "https://Stackoverflow.com/users/530160",
"pm_score": 1,
"selected": false,
"text": "/bin/sh"
},
{
"answer_id": 74561721,
"author": "Attila",
"author_id": 1167226,
"author_profile": "https://Stackoverflow.com/users/1167226",
"pm_score": 3,
"selected": true,
"text": "FROM alpine:latest\nENV ENV=/root/.ashrc\nRUN echo \"echo 'Hello from .ashrc!'\" >> /root/.ashrc\nCMD [\"/bin/sh\"]\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20449169/"
] |
74,377,554 | <p>enter image description here</p>
<p>I'm having difficulty with taking two dates and assigning duration in secs between all half hour intervals.</p>
<p>attached table data and attached expected output.</p>
<p><a href="https://i.stack.imgur.com/j17YV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j17YV.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/4jGdn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4jGdn.png" alt="enter image description here" /></a></p>
<p>I tried hierarchy function and it failed for me. Any help appreciated.</p>
| [
{
"answer_id": 74378256,
"author": "Alex Poole",
"author_id": 266304,
"author_profile": "https://Stackoverflow.com/users/266304",
"pm_score": 2,
"selected": true,
"text": "with p (start_time, stop_time) as (\n select cast(timestamp '2022-10-04 09:00:00' as date),\n cast(timestamp '2022-10-04 09:00:00' as date) + interval '30' minute\n from dual\n union all\n select p.stop_time, p.stop_time + interval '30' minute\n from p\n where p.stop_time < timestamp '2022-10-04 13:00:00'\n)\nselect * from p\n"
},
{
"answer_id": 74378455,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 0,
"selected": false,
"text": "id"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20459917/"
] |
74,377,567 | <p>I have an API from SQL server table with the following result:</p>
<p><code>[["Nom1", "Prénom1"], ["Nom2", "Prenom2"]]</code></p>
<p>where the API is <code>http://192.168.2.220:5000/api/get_user</code></p>
<p>I want to display the result in a dropdown menu dynamically.</p>
| [
{
"answer_id": 74378256,
"author": "Alex Poole",
"author_id": 266304,
"author_profile": "https://Stackoverflow.com/users/266304",
"pm_score": 2,
"selected": true,
"text": "with p (start_time, stop_time) as (\n select cast(timestamp '2022-10-04 09:00:00' as date),\n cast(timestamp '2022-10-04 09:00:00' as date) + interval '30' minute\n from dual\n union all\n select p.stop_time, p.stop_time + interval '30' minute\n from p\n where p.stop_time < timestamp '2022-10-04 13:00:00'\n)\nselect * from p\n"
},
{
"answer_id": 74378455,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 0,
"selected": false,
"text": "id"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20460515/"
] |
74,377,574 | <p>Hi I'm learning angular and I want to make a currency converter using angular reactive form,I figured out the form itself, all the fields are readable, but after a request to the backend, the answer does not come, tell me what I'm doing wrong?</p>
<p>this is my html</p>
<pre><code><div class="selection-container">
<form [formGroup]="currencyForm"
class ="form-box">
<div class="box">
<input type="text"
formControlName="amount">
<select name="" id="country1" formControlName="changebase">
<option value="USD">US dollar</option>
<option value="EUR">Euro</option>
<option value="UAH">Ukranian Grivna</option>
</select>
</div>
<p class="title"> to </p>
<select name="" id="country1" formControlName="tocountry">
<option value="USD">US dollar</option>
<option value="EUR">Euro</option>
<option value="UAH">Ukranian Grivna</option>
</select>
<button (click)="convert()"> Submit</button>
</form>
<div class="result-container">
<p class="title">{{changebase}} <span>=</span>{{result}} {{tocountry}}</p>
</div>
</div>
</code></pre>
<p>This is my request</p>
<pre><code>import { Injectable } from '@angular/core';
import {HttpClient} from "@angular/common/http"
@Injectable({
providedIn: 'root'
})
export class CurrencydataService {
constructor(private http:HttpClient) { }
getcurrencydata(country1:string){
let url ="https://api.exchangerate.host/latest?base=USD"+country1
return this.http.get(url)
}
}
</code></pre>
<p>This is my logic</p>
<pre><code>export class CurrencyReactiveComponent implements OnInit {
currjson:any="";
amount:number=1;
changebase:string= "";
tocountry:string="";
result:number=1
createFormGroup(){
return new FormGroup({
amount: new FormControl(""),
changebase: new FormControl(""),
tocountry:new FormControl("")
});
}
currencyForm: FormGroup;
constructor(private currency:CurrencydataService) {
this.currencyForm =this.createFormGroup()
}
ngOnInit() {
//this.getcurrencydata()
}
convert(){
this.currency
.getcurrencydata(this.changebase)
.subscribe(data=>{
this.currjson= JSON.stringify(data);
this.currjson= JSON.parse(this.currjson);
console.log(this.currencyForm.value)
if (this.tocountry ==="USD"){
this.result = this.currjson.rates.USD * (this.amount)
}
if (this.tocountry ==="EUR"){
this.result = this.currjson.rates.EUR * (this.amount)
}
if (this.tocountry ==="UAH"){
this.result = this.currjson.rates.UAH * (this.amount)
}
})
}
}
</code></pre>
<p>Please, help me to understand what i am doing bad</p>
| [
{
"answer_id": 74377907,
"author": "MoxxiManagarm",
"author_id": 11011793,
"author_profile": "https://Stackoverflow.com/users/11011793",
"pm_score": 0,
"selected": false,
"text": "export class CurrencyReactiveComponent implements OnInit {\n currjson:any=\"\";\n result:number=1\n\n createFormGroup(){\n return new FormGroup({\n amount: new FormControl(\"\"),\n changebase: new FormControl(\"\"),\n tocountry:new FormControl(\"\")\n });\n\n }\n currencyForm: FormGroup;\n\n\n constructor(private currency:CurrencydataService) {\n this.currencyForm =this.createFormGroup()\n }\n\n convert(){\n this.currency\n .getcurrencydata(this.currencyForm.get('changebase').value)\n .pipe(take(1))\n .subscribe(data=>{\n this.currjson = data;\n console.log(this.currencyForm.value)\nthis.result = this.currjson.rates[(this.currencyForm.get('tocountry').value]\n * (this.currencyForm.get('amount').value);\n \n\n }\n}\n"
},
{
"answer_id": 74378214,
"author": "Ninii",
"author_id": 13636910,
"author_profile": "https://Stackoverflow.com/users/13636910",
"pm_score": 2,
"selected": true,
"text": "getcurrencydata"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18216988/"
] |
74,377,620 | <p>I have in my application a shell that I need to execute once the container is started and that it remains in the background, I have seen using lifecycle but it does not work for me</p>
<pre><code> ports:
- name: php-port
containerPort: 9000
lifecycle:
postStart:
exec:
command: ["/bin/sh", "sh /root/script.sh"]
</code></pre>
<p>I need an artisan execution to stay in the background once the container is started</p>
| [
{
"answer_id": 74377907,
"author": "MoxxiManagarm",
"author_id": 11011793,
"author_profile": "https://Stackoverflow.com/users/11011793",
"pm_score": 0,
"selected": false,
"text": "export class CurrencyReactiveComponent implements OnInit {\n currjson:any=\"\";\n result:number=1\n\n createFormGroup(){\n return new FormGroup({\n amount: new FormControl(\"\"),\n changebase: new FormControl(\"\"),\n tocountry:new FormControl(\"\")\n });\n\n }\n currencyForm: FormGroup;\n\n\n constructor(private currency:CurrencydataService) {\n this.currencyForm =this.createFormGroup()\n }\n\n convert(){\n this.currency\n .getcurrencydata(this.currencyForm.get('changebase').value)\n .pipe(take(1))\n .subscribe(data=>{\n this.currjson = data;\n console.log(this.currencyForm.value)\nthis.result = this.currjson.rates[(this.currencyForm.get('tocountry').value]\n * (this.currencyForm.get('amount').value);\n \n\n }\n}\n"
},
{
"answer_id": 74378214,
"author": "Ninii",
"author_id": 13636910,
"author_profile": "https://Stackoverflow.com/users/13636910",
"pm_score": 2,
"selected": true,
"text": "getcurrencydata"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2928741/"
] |
74,377,656 | <p>After sending a REST POST request from an Angular frontend to a Java backend, the backend recieves the request and computes the answer. However, in the frontend, the request does not show up in the logs, instead a parsing error is given.</p>
<p>There is a Rest-Call from an Angular endpoint, which is:</p>
<pre><code>getUserID<NonSimpleObject>(nonSimpleObject: NonSimpleObject): Observable<string> {
return this.http.post<string>(this.API_URL + '/userId', nonSimpleObject);
}
</code></pre>
<p>it is recieved in the Java Endpoint which is:</p>
<pre><code>@POST
@Path("/userId")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public String userId(NonSimpleObject nonSimpleObject) {
LOG.info("The searched UserId is: " + controller.getUserId(nonSimpleObject);
return controller.getUserId(nonSimpleObject);
}
</code></pre>
<p>In the backend, the log shows that the request arrives and the string is computed correctly. The string is an alphanumeric combination, no special characters. In the frontend, the chrome log shows no trace of the request, but gives the error</p>
<pre><code>ERROR SyntaxError: Unexpected number in JSON at position 1
at JSON.parse (<anonymous>)
at JsonParser.parse (json-parser.service.ts:64:21)
at CustomJsonParserHttpInterceptor.parseJsonResponse (custom-json-parser-h…nterceptor.ts:47:50)
at custom-json-parser-h…nterceptor.ts:42:64
at map.js:7:37
at OperatorSubscriber._next (OperatorSubscriber.js:13:21)
at OperatorSubscriber.next (Subscriber.js:31:18)
at XMLHttpRequest.onLoad (http.mjs:1840:30)
at _ZoneDelegate.invokeTask (zone.js:406:31)
at Object.onInvokeTask (core.mjs:26341:33)
</code></pre>
<p>I would expect to recieve the String in an ok Response from the backend. Any clues on how to make the request process properly?</p>
| [
{
"answer_id": 74377710,
"author": "MoxxiManagarm",
"author_id": 11011793,
"author_profile": "https://Stackoverflow.com/users/11011793",
"pm_score": 2,
"selected": true,
"text": "return this.http.post(this.API_URL + '/userId', nonSimpleObject, { responseType: 'text' });\n"
},
{
"answer_id": 74401462,
"author": "Stef",
"author_id": 10905378,
"author_profile": "https://Stackoverflow.com/users/10905378",
"pm_score": 0,
"selected": false,
"text": "getUserID<NonSimpleObject>(nonSimpleObject: NonSimpleObject): Observable<string> {\n return this.http.post<string>(this.API_URL + '/userId', nonSimpleObject);\n}\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10905378/"
] |
74,377,657 | <p>Inputs:</p>
<pre><code>group1 <- c("A", "B", "C", "D")
group2 <- c("B", "A", "D", "C")
count <- c(1, 3, 2, 4)
df <- data.frame(group1, group2, count)
</code></pre>
<p>df:</p>
<pre><code> group1 group2 count
1 A B 1
2 B A 3
3 C D 2
4 D C 4
</code></pre>
<p>Desired output:</p>
<pre><code> group total
1 AB or BA 4
2 CD or DC 6
</code></pre>
<p>My actual dataset has a very long list of these group pairs.</p>
| [
{
"answer_id": 74377733,
"author": "Gregor Thomas",
"author_id": 903061,
"author_profile": "https://Stackoverflow.com/users/903061",
"pm_score": 1,
"selected": false,
"text": "library(dplyr)\ndf %>%\n mutate(g1 = pmin(group1, group2),\n g2 = pmax(group1, group2)) %>%\n group_by(g1, g2) %>%\n summarize(total = sum(count), .groups = \"drop\")\n# # A tibble: 2 × 3\n# g1 g2 total\n# <chr> <chr> <dbl>\n# 1 A B 4\n# 2 C D 6\n"
},
{
"answer_id": 74377920,
"author": "Chris Ruehlemann",
"author_id": 8039978,
"author_profile": "https://Stackoverflow.com/users/8039978",
"pm_score": 0,
"selected": false,
"text": "library(tidyverse) \ndf %>%\n mutate(\n # create row ID for each pair:\n id = (row_number() - 1) %/% 2,\n # create column `group`:\n group = str_c(group1, group2, \" or \", group2, group1)) %>%\n group_by(id) %>%\n summarise(across(group, first),\n total = sum(count)) %>%\n select(-id)\n# A tibble: 2 × 2\n group total\n <chr> <dbl>\n1 AB or BA 4\n2 CD or DC 6\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7816373/"
] |
74,377,677 | <p>The application I'm working on generates very long SQL statements as a result of very long <code>WHERE col IN (values) clauses</code>.</p>
<p>A typical query would be:</p>
<pre><code>SELECT userId, userAge
FROM users
WHERE userId IN (16,4127,51,13,17, ...{10,000 other userIds}..., 914)
</code></pre>
<p>This is "working" but it is also ugly as hell.</p>
<p>Are there any alternatives? Note that the users table has ~500k users, so the ~10k unique userIds are a non trivial filtering.</p>
<p>Note:</p>
<ul>
<li>The list of userIds that need to be queried changes all the time</li>
<li>The list of userIds is not generated via SQL (it is the output of another tool)</li>
</ul>
| [
{
"answer_id": 74377742,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 2,
"selected": false,
"text": "SELECT userId, userAge \nFROM users u\nWHERE EXISTS (SELECT 1 FROM otherTable t WHERE t.userId = u.userId);\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17194313/"
] |
74,377,689 | <p>I'd like to use an MS Word template to format emails for a mail merge. I currently use MS Access / VBA / MS Outlook to generate emails, but all of the formatting I'm looking for I hardcode (e.g. {b}, {i}, {u}, {br /}, etc.) Is there a way to use an existing MS Word template to create the body of my email, and allow me to enter data in merge fields.</p>
<p>I don't know how to integrate an MS Word template into my VBA code to generate emails in MS Outlook.</p>
| [
{
"answer_id": 74377742,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 2,
"selected": false,
"text": "SELECT userId, userAge \nFROM users u\nWHERE EXISTS (SELECT 1 FROM otherTable t WHERE t.userId = u.userId);\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11064315/"
] |
74,377,709 | <p>Trying this to replace all lowercase words is not working properly</p>
<pre><code>=regexreplace(A1;"\b[a-züöäß]+\b";"")
</code></pre>
<p>Example sentence:</p>
<blockquote>
<p>Mit Sätzen wie Gewinne laufen lassen Verluste begrenzen können vor
allem weniger erfahrene Aktienkäufer oder Börseneinsteiger die
wichtigsten Grundregeln des Aktienhandels kennenlernen und besser
verinnerlichen.</p>
</blockquote>
<p>also matches "ätzen" in "Sätzen" but Sätzen start with uppercase. Or matches "Aktienkäufer" to "Aktienk".</p>
| [
{
"answer_id": 74377805,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 2,
"selected": false,
"text": "=TRIM(SUBSTITUTE(REGEXREPLACE(SUBSTITUTE(A1, \" \", \" \"), \"(^| )[a-züöäß]+( |$)\", \"\"), \" \", \" \"))\n"
},
{
"answer_id": 74378031,
"author": "user3392296",
"author_id": 3392296,
"author_profile": "https://Stackoverflow.com/users/3392296",
"pm_score": 1,
"selected": false,
"text": "=INDEX(TEXTJOIN(\" \"; 1; LAMBDA(x;IF(REGEXMATCH(x&\"\"; \"^[a-züöäß]\");;x))(SPLIT(A1; \" \"&CHAR(10)))))\n"
},
{
"answer_id": 74403271,
"author": "marikamitsos",
"author_id": 1527780,
"author_profile": "https://Stackoverflow.com/users/1527780",
"pm_score": 1,
"selected": false,
"text": "=REGEXREPLACE(G106,\" [a-züöäß]+\",\"\")\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3392296/"
] |
74,377,720 | <p>i got a string and a scanf that reads from input until it finds a *, which is the character i picked for the end of the text. After the * all the remaining cells get filled with random characters.
I know that a string after the \0 character if not filled completly until the last cell will fill all the remaining empty ones with \0, why is this not the case and how can i make it so that after the last letter given in input all the remaining cells are the same value?</p>
<pre><code> char string1 [100];
scanf("%[^*]s", string1);
for (int i = 0; i < 100; ++i) {
printf("\n %d=%d",i,string1[i]);
}
</code></pre>
<p>if i try to input something like hello*, here's the output:</p>
<pre><code> 0=104
1=101
2=108
3=108
4=111
5=0
6=0
7=0
8=92
9=0
10=68
</code></pre>
| [
{
"answer_id": 74377799,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 3,
"selected": true,
"text": "char string1 [100];\n"
},
{
"answer_id": 74378290,
"author": "chrslg",
"author_id": 20037042,
"author_profile": "https://Stackoverflow.com/users/20037042",
"pm_score": 2,
"selected": false,
"text": "char string1[20];\nsprintf(string1, \"hello\");\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20460446/"
] |
74,377,731 | <p>I want to convert the following structured code into a more readable LINQ call:</p>
<pre class="lang-cs prettyprint-override"><code>foreach (string line in this.HeaderTexts)
{
Match match = dimensionsSearcher.Match(line);
if (match.Success)
{
// Do something
return;
}
}
</code></pre>
<p>I came up with the following code:</p>
<pre class="lang-cs prettyprint-override"><code>Match foundMatch = this.HeaderTexts
.Select(text => dimensionsSearcher.Match(text))
.Where(match => match.Success)
.FirstOrDefault();
if (foundMatch != null)
{
// Do something
return;
}
</code></pre>
<p>However, from my understanding, this will run the Regex check for each header text, while my first code breaks as soon as it hits for the first time. Is there a way to optimize the LINQ version of that code, of should I rather stick to the structural code?</p>
| [
{
"answer_id": 74377799,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 3,
"selected": true,
"text": "char string1 [100];\n"
},
{
"answer_id": 74378290,
"author": "chrslg",
"author_id": 20037042,
"author_profile": "https://Stackoverflow.com/users/20037042",
"pm_score": 2,
"selected": false,
"text": "char string1[20];\nsprintf(string1, \"hello\");\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10406502/"
] |
74,377,750 | <p>I often struggle with understanding how to assign values in <code>R</code> within loops. The desired behavior seems simple to me, but I clearly don't have a good grasp on the subtleties of evaluation and assignment in <code>R</code>.</p>
<p>For example, I've got a bunch of data objects that I want to add a comment to <em>each</em> object (they are unrelated and so using them together in a list beyond this assignment does not make sense). Here's a MWE</p>
<pre><code>
my_comment <- paste0("these objects were created on ", date())
obj1 <- "content1"
obj2 <- "content2"
obj_l <- list(obj1, obj2)
for(obj in obj_l) {
comment(obj) <- my_comment
}
## get 'NULL', but want "these objects were created ..."
comment(obj1)
## get 'NULL'
comment(obj_l)
## assignment is only made to temp variable 'obj'
## This makes sense, but not the desired outcome.
comment(obj)
</code></pre>
<p>I imagine the solution will look something like the following pseudo code</p>
<pre><code>obj_l <- c("obj1", "obj2")
for(name in obj_l)
unknown_function(name, comment, my_comment, unknown_args)
}
</code></pre>
<p>or</p>
<pre><code>
modify(obj_l, my_comment, unknown_syntax)
</code></pre>
<p>If my pseudo code is on track, can someone help me with the <code>unknown_</code> parts?</p>
| [
{
"answer_id": 74377854,
"author": "Gregor Thomas",
"author_id": 903061,
"author_profile": "https://Stackoverflow.com/users/903061",
"pm_score": 1,
"selected": false,
"text": "for(i in seq_along(obj_l)) {\n comment(obj_l[[i]]) <- my_comment\n}\n\ncomment(obj_l[[i]])\n# [1] \"these objects were created on Wed Nov 9 10:55:27 2022\"\n"
},
{
"answer_id": 74377913,
"author": "G. Grothendieck",
"author_id": 516548,
"author_profile": "https://Stackoverflow.com/users/516548",
"pm_score": 2,
"selected": false,
"text": "obj_l"
},
{
"answer_id": 74378157,
"author": "Hansel Palencia",
"author_id": 10897981,
"author_profile": "https://Stackoverflow.com/users/10897981",
"pm_score": 0,
"selected": false,
"text": "comment()"
},
{
"answer_id": 74378162,
"author": "mikemtnbikes",
"author_id": 5322644,
"author_profile": "https://Stackoverflow.com/users/5322644",
"pm_score": 2,
"selected": true,
"text": "obj1 <- \"content1\"\nobj2 <- \"content2\"\n\nobj_l <- c(\"obj1\", \"obj2\")\n\ncomment <- '\"my comment!\"'\n\nfor(x in obj_l) {\n my_exp <- paste0(\"comment(\", x, \") <- \", comment)\n parse(text = my_exp)\n}\n\ncomment(obj1)\n# [1] \"my comment\"\n\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5322644/"
] |
74,377,753 | <p>Short description: two computers in the same network, in the new one only those python scripts work that use native packages.</p>
<p>I have Pycharm in my old computer and it has worked fine. Now I got a new computer, installed the most recent version of Python and Pycharm, then opened one of my old projects. Both the old and the new computer are in the same network and the project is on a shared folder. So I did the following:</p>
<ol>
<li>File - Open - selected the project. Got a message that there is no interpreter</li>
<li>Add local interpreter - selected the latest Python 311 exe. So location of the venv is the same as in the old computer (because it's a network folder) but Base interpreter is pointing to the C drive of my new computer.</li>
<li>PyCharm creates a virtual environment and the code runs fine.</li>
<li>I select another project which uses imported packages such as pandas. Again, same steps as above, add local interpreter. Venv is created.</li>
<li>I go to File - Setting - Project and see that pip, setuptools and wheel are listed as Packages. If I double click one of these, I can re-install and get a note that installation is succesful, so nothing seems to be wrong in the connection (after all, both the old and the new computer are in the same network.</li>
<li>I click the plus sign to add a new one, search pandas. Installation fails. Same thing if I try e.g. numpy.</li>
</ol>
<p>Error message has lots of retrying, then "could not find the version that satisfies the requirement pandas (from versions: none", "not matching distribution found for pandas" (pip etc. have the latest versions).</p>
<p>After few hours of googling for solutions, I have tried the following:</p>
<ol>
<li>Complety uninstall and reinstall python and PyCharm. Checked that PATH was included in the installation.</li>
<li>Tried launching pip command from shell</li>
<li>Changed http proxy to auto-detect</li>
<li>Typed 'import pandas' in PyCharm, then used the dropdown in the yellow bulb but there is no install option</li>
<li>Started a new project in the new computer, tried to install pandas</li>
</ol>
<p>All failed. I'm surprised that changing computers is this difficult. Please let me know if there are other options than staying in the old computer...</p>
| [
{
"answer_id": 74377937,
"author": "Guf",
"author_id": 17444641,
"author_profile": "https://Stackoverflow.com/users/17444641",
"pm_score": 1,
"selected": false,
"text": "requirement.txt"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13846831/"
] |
74,377,763 | <p>My case is: I have a string with HTML elements:</p>
<pre><code><a href="something+specific_string" title="testing">This is a text and "specific_string"</a>
</code></pre>
<p>I need a Regex to match only the one that is not in a HTML attribute.</p>
<p>This is my current Regex, it works but it gives a false positive when the string is wrapped by double quotes</p>
<pre><code>((?!\"[\w\s]*)specific_string(?![\w\s]*\"))
</code></pre>
<p>I have tried the following Regex:</p>
<pre><code>((?!\"[\w\s]*)specific_string(?![\w\s]*\"))
</code></pre>
<p>It works but it gives a false positive when the string is wrapped by double quotes</p>
| [
{
"answer_id": 74377937,
"author": "Guf",
"author_id": 17444641,
"author_profile": "https://Stackoverflow.com/users/17444641",
"pm_score": 1,
"selected": false,
"text": "requirement.txt"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9447434/"
] |
74,377,816 | <p>I am looking for a way to take an ordered vector and return the percentage of the way through the vector that each value appears for the first time.</p>
<p>See below for the input vector and the expected result.</p>
<pre><code>InputVector<-c(1,1,1,1,1,2,2,2,3,3)
ExpectedResult<-data.frame(Value=c(1,2,3), Percentile=c(0,0.5,0.8))
</code></pre>
<p>In this case, 1 appears at the 0th percentile, 2 at the 50th and 3 at the 80th.</p>
| [
{
"answer_id": 74377958,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 3,
"selected": true,
"text": "rank()"
},
{
"answer_id": 74378080,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 2,
"selected": false,
"text": "rle"
},
{
"answer_id": 74380454,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "match"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17974332/"
] |
74,377,828 | <p>How can I access my user activity?<br />
I want to update something on my server when my user exit from the application</p>
<p>I try this way but I don't know where I make mistakes, because that way doesn't work.</p>
<pre><code>
class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver {
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// TODO: implement didChangeAppLifecycleState
print("----------------------------------------------------------------");
print(state);
print("----------------------------------------------------------------");
super.didChangeAppLifecycleState(state);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
</code></pre>
| [
{
"answer_id": 74377901,
"author": "aminjafari-dev",
"author_id": 19699656,
"author_profile": "https://Stackoverflow.com/users/19699656",
"pm_score": 1,
"selected": false,
"text": "initState"
},
{
"answer_id": 74378052,
"author": "Moklesur Rahman",
"author_id": 4411893,
"author_profile": "https://Stackoverflow.com/users/4411893",
"pm_score": 0,
"selected": false,
"text": "didChangeAppLifecycleState"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20184483/"
] |
74,377,835 | <p>The goal is to build a program to report the transactions for a particular stock in a human-readable format. For example, for our test data set, the transactions on the stock VTI will be printed
as:</p>
<pre><code>Bought 100 units of VTI for 1104 pounds each on day 1
Bought 50 units of VTI for 1223 pounds each on day 5
Sold 150 units of VTI for 1240 pounds each on day 9
</code></pre>
<p>Here is the test transaction code:</p>
<pre><code>type Transaction = (Char, Int, Int, String, Int)
test_log :: [Transaction]
test_log = [('B', 100, 1104, "VTI", 1),
('B', 200, 36, "ONEQ", 3),
('B', 50, 1223, "VTI", 5),
('S', 150, 1240, "VTI", 9),
('B', 100, 229, "IWRD", 10),
('S', 200, 32, "ONEQ", 11),
('S', 100, 210, "IWRD", 12)
]
</code></pre>
<p>For this, I thought is would be best to split each section into slices where they can be concatenated at the end.</p>
<pre><code>--Converting transaction to string
transaction_to_string :: Transaction -> String
transaction_to_string (action: units: stocks: price: day) =
let display = action ++ "Bought"
slice1 = units ++ "of"
slice2 = stocks ++ "for"
slice3 = price ++ "on day"
slice4 = day
in
slice1 ++ slice2 ++ slice3 + slice4
</code></pre>
<p>The error I am receiving is this. It is giving a type error but I am unsure why due to the type function used at the top:</p>
<pre><code> • Couldn't match type ‘[Char]’ with ‘Char’
Expected: [Char]
Actual: [[Char]]
• In the second argument of ‘(++)’, namely ‘slice4’
In the second argument of ‘(++)’, namely ‘slice3 ++ slice4’
In the second argument of ‘(++)’, namely
‘slice2 ++ slice3 ++ slice4’
|
| slice1 ++ slice2 ++ slice3 ++ slice4
</code></pre>
| [
{
"answer_id": 74378036,
"author": "chi",
"author_id": 3234959,
"author_profile": "https://Stackoverflow.com/users/3234959",
"pm_score": 2,
"selected": true,
"text": "transaction_to_string :: Transaction -> String\ntransaction_to_string (action, units, stocks, price, day) = \n -- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ tuple, not list\n let display = show action ++ \"Bought\" -- << convert non-strings using `show`\n slice1 = show units ++ \"of\" -- <<\n slice2 = show stocks ++ \"for\" -- <<\n slice3 = price ++ \"on day\"\n slice4 = show day -- <<\n in\n display ++ slice1 ++ slice2 ++ slice3 ++ slice4\n"
},
{
"answer_id": 74378510,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 0,
"selected": false,
"text": "Transaction"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,377,888 | <p>I have an application that uses Hibernate and it's running out of memory with a medium volume dataset (~3 million records). When analysing the memory dump using Eclipse's Memory Analyser I can see that <code>StatefulPersistenceContext</code> appears to be holding a copy of the record in memory in addition to the object itself, doubling the memory usage.</p>
<p>I'm able to reproduce this on a slightly smaller scale with a defined workflow, but am unable to simplify it to the level that I can put the full application here. The workflow is:</p>
<ol>
<li>Insert ~400,000 records (<code>Fruit</code>) into the database from a file</li>
<li>Get all of the <code>Fruit</code>s from the database and find if there are any complementary items to create ~150,000 <code>Baskets</code> (containing two <code>Fruit</code>s)</li>
<li>Retrieve all of the data - <code>Fruits</code> & <code>Baskets</code> - and save to a file</li>
</ol>
<p>It's running out of memory at the final stage, and the heap dump shows <code>StatefulPersistenceContext</code> has hundreds of thousands of <code>Fruit</code>s in memory, in addition to the <code>Fruit</code>s we retrieved to save to the file.</p>
<p>I've looked around online and the suggestion appears to be to use <code>QueryHints.READ_ONLY</code> on the query (I put it on the <code>getAll</code>), or to wrap it in a <code>Transaction</code> with the <code>readOnly</code> property set - but neither of these seem to have stopped the massive <code>StatefulPersistenceContext</code>.</p>
<p>Is there something else I should be looking at?</p>
<p>Examples of the classes / queries I'm using:</p>
<pre><code>public interface ShoppingService {
public void createBaskets();
public void loadFromFile(ObjectInput input);
public void saveToFile(ObjectOutput output);
}
</code></pre>
<pre><code>@Service
public class ShoppingServiceImpl implements ShoppingService {
@Autowired
private FruitDAO fDAO;
@Autowired
private BasketDAO bDAO;
@Override
public void createBaskets() {
bDAO.add(Basket.generate(fDAO.getAll()));
}
@Override
public void loadFromFile(ObjectInput input) {
SavedState state = ((SavedState) input.readObject());
fDAO.add(state.getFruits());
bDAO.add(state.getBaskets());
}
@Override
public void saveToFile(ObjectOutput output) {
output.writeObject(new SavedState(fDAO.getAll(), bDAO.getAll()));
}
public static void main(String[] args) throws Throwable {
ShoppingService service = null;
try (ObjectInput input = new ObjectInputStream(new FileInputStream("path\\to\\input\\file"))) {
service.loadFromFile(input);
}
service.createBaskets();
try (ObjectOutput output = new ObjectOutputStream(new FileOutputStream("path\\to\\output\\file"))) {
service.saveToFile(output);
}
}
}
</code></pre>
<pre><code>@Entity
public class Fruit {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
private String name;
// ~ 200 string fields
}
</code></pre>
<pre><code>public interface FruitDAO {
public void add(Collection<Fruit> elements);
public List<Fruit> getAll();
}
</code></pre>
<pre><code>@Repository
public class JPAFruitDAO implements FruitDAO {
@PersistenceContext
private EntityManager em;
@Override
@Transactional()
public void add(Collection<Fruit> elements) {
elements.forEach(em::persist);
}
@Override
public List<Fruit> getAll() {
return em.createQuery("FROM Fruit", Fruit.class).getResultList();
}
}
</code></pre>
<pre><code>@Entity
public class Basket {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
@OneToOne
@JoinColumn(name = "arow")
private Fruit aRow;
@OneToOne
@JoinColumn(name = "brow")
private Fruit bRow;
public static Collection<Basket> generate(List<Fruit> fruits) {
// Some complicated business logic that does things
return null;
}
}
</code></pre>
<pre><code>public interface BasketDAO {
public void add(Collection<Basket> elements);
public List<Basket> getAll();
}
</code></pre>
<pre><code>@Repository
public class JPABasketDAO implements BasketDAO {
@PersistenceContext
private EntityManager em;
@Override
@Transactional()
public void add(Collection<Basket> elements) {
elements.forEach(em::persist);
}
@Override
public List<Basket> getAll() {
return em.createQuery("FROM Basket", Basket.class).getResultList();
}
}
</code></pre>
<pre><code>public class SavedState {
private Collection<Fruit> fruits;
private Collection<Basket> baskets;
}
</code></pre>
| [
{
"answer_id": 74378036,
"author": "chi",
"author_id": 3234959,
"author_profile": "https://Stackoverflow.com/users/3234959",
"pm_score": 2,
"selected": true,
"text": "transaction_to_string :: Transaction -> String\ntransaction_to_string (action, units, stocks, price, day) = \n -- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ tuple, not list\n let display = show action ++ \"Bought\" -- << convert non-strings using `show`\n slice1 = show units ++ \"of\" -- <<\n slice2 = show stocks ++ \"for\" -- <<\n slice3 = price ++ \"on day\"\n slice4 = show day -- <<\n in\n display ++ slice1 ++ slice2 ++ slice3 ++ slice4\n"
},
{
"answer_id": 74378510,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 0,
"selected": false,
"text": "Transaction"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3107019/"
] |
74,377,972 | <pre><code>
abstract class AbstractView {
ctx : AbstractView;
constructor()
{
this.ctx = this.constructor as typeof AbstractView;
}
static getStatus() : string
{
return 'hi';
}
}
class testView extends AbstractView {
static getStatus() : string
{
return 'hi2';
}
}
</code></pre>
<p>I am trying to access an overloaded static method from the parent class, however I receive an error message that I don't quite understand.</p>
<p>"Property 'ctx' is missing in type 'typeof AbstractView' but required in type 'AbstractView'"</p>
<p><a href="https://www.typescriptlang.org/play?#code/FAQwRgzgLgTiDGUAE8A2IISQQUrBUAagJYCmA7kgN7BJ0pQAeSAXDnnIiRQNy33wA9gDtoMAK6JBMABQBKJPzo16qpFAAWxCADpEzALzqtuoaNiSo0pBnUBPAA6lBAM3ZiC3cn1UBfJUjQIFDE8EgA5qRQAMpQweIQ8qyBsMTC4QEqanQwUeIwwkgA5FpFPvT+-mgYWFCk0F5IpIx1wgAmWLgeXGSUWXRBIWGRMXFQCUlsYmkZqv1queMFxVoATGUB-sC+QA" rel="nofollow noreferrer">https://www.typescriptlang.org/play?#code/FAQwRgzgLgTiDGUAE8A2IISQQUrBUAagJYCmA7kgN7BJ0pQAeSAXDnnIiRQNy33wA9gDtoMAK6JBMABQBKJPzo16qpFAAWxCADpEzALzqtuoaNiSo0pBnUBPAA6lBAM3ZiC3cn1UBfJUjQIFDE8EgA5qRQAMpQweIQ8qyBsMTC4QEqanQwUeIwwkgA5FpFPvT+-mgYWFCk0F5IpIx1wgAmWLgeXGSUWXRBIWGRMXFQCUlsYmkZqv1queMFxVoATGUB-sC+QA</a></p>
| [
{
"answer_id": 74378047,
"author": "Ruan Mendes",
"author_id": 227299,
"author_profile": "https://Stackoverflow.com/users/227299",
"pm_score": 1,
"selected": false,
"text": "abstract class AbstractView {\n ctx : typeof AbstractView;\n constructor() {\n this.ctx = this.constructor as typeof AbstractView;\n }\n}\n"
},
{
"answer_id": 74378121,
"author": "Dimava",
"author_id": 5734961,
"author_profile": "https://Stackoverflow.com/users/5734961",
"pm_score": 2,
"selected": false,
"text": "abstract class AbstractView {\n get ctx(): typeof AbstractView {\n return this.constructor as typeof AbstractView;\n }\n static getStatus() : string\n {\n return 'hi';\n }\n}\nclass TestView extends AbstractView {\n static getStatus() : string\n {\n return 'hi2';\n }\n}\n\nconsole.log(new TestView().ctx.getStatus())\n// > \"hi2\"\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1901035/"
] |
74,377,975 | <p>Below is the current code. I'm kinda new to python, but my previous bot with virtually the same code ran perfectly fine, so i don't understand why it's not running. The bot will turn on and show as "online" in Discord, but won't send the message.</p>
<pre><code>import os
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = 'token'
client = discord.Client(intents=discord.Intents.all())
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
async def on_message(message):
channel = message.channel
content = message.content
user = message.author
userid = message.author.id
if content == "hello":
await client.send_message(channel, "rude response")
client.run(TOKEN)
</code></pre>
| [
{
"answer_id": 74378047,
"author": "Ruan Mendes",
"author_id": 227299,
"author_profile": "https://Stackoverflow.com/users/227299",
"pm_score": 1,
"selected": false,
"text": "abstract class AbstractView {\n ctx : typeof AbstractView;\n constructor() {\n this.ctx = this.constructor as typeof AbstractView;\n }\n}\n"
},
{
"answer_id": 74378121,
"author": "Dimava",
"author_id": 5734961,
"author_profile": "https://Stackoverflow.com/users/5734961",
"pm_score": 2,
"selected": false,
"text": "abstract class AbstractView {\n get ctx(): typeof AbstractView {\n return this.constructor as typeof AbstractView;\n }\n static getStatus() : string\n {\n return 'hi';\n }\n}\nclass TestView extends AbstractView {\n static getStatus() : string\n {\n return 'hi2';\n }\n}\n\nconsole.log(new TestView().ctx.getStatus())\n// > \"hi2\"\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20460807/"
] |
74,378,006 | <p>I do host a gitea server and access git via https. The certificate is <strong>not</strong> self-signed, but from a proper CA, User Trust (<a href="https://www.tbs-certificates.co.uk/FAQ/en/racine-USERTrustRSACertificationAuthority.html" rel="nofollow noreferrer">https://www.tbs-certificates.co.uk/FAQ/en/racine-USERTrustRSACertificationAuthority.html</a>).
I'm using the latest git client for windows (2.38.1, 64bit)</p>
<p>When i do a <code>git pull</code>, the error <code>unable to get local issuer certificate</code> is shown.
<a href="https://i.stack.imgur.com/jVkdg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jVkdg.png" alt="enter image description here" /></a></p>
<p>I do understand that git by default uses openssl and the certificate list via the file <strong>ca-bundle.trust</strong> for validating certificates.</p>
<p>The strange thing is that git actually contains the root certificate, but it's not exactly the same. The certificate which is part of the ca-bundle.trust file has some additional content (Marked in green)
<a href="https://i.stack.imgur.com/F1Z1Z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/F1Z1Z.png" alt="enter image description here" /></a></p>
<p>When i compare the properties of the two certificates, i don't see any difference, but i assume this is the reason why git does reject the certificate.</p>
<p>Certificates in case someone wants to have a look at it:</p>
<h1>Official User Trust root certificate</h1>
<pre><code>-----BEGIN CERTIFICATE-----
MIIF3jCCA8agAwIBAgIQAf1tMPyjylGoG7xkDjUDLTANBgkqhkiG9w0BAQwFADCB
iDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0pl
cnNleSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNV
BAMTJVVTRVJUcnVzdCBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAw
MjAxMDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBiDELMAkGA1UEBhMCVVMxEzARBgNV
BAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVU
aGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBSU0EgQ2Vy
dGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK
AoICAQCAEmUXNg7D2wiz0KxXDXbtzSfTTK1Qg2HiqiBNCS1kCdzOiZ/MPans9s/B
3PHTsdZ7NygRK0faOca8Ohm0X6a9fZ2jY0K2dvKpOyuR+OJv0OwWIJAJPuLodMkY
tJHUYmTbf6MG8YgYapAiPLz+E/CHFHv25B+O1ORRxhFnRghRy4YUVD+8M/5+bJz/
Fp0YvVGONaanZshyZ9shZrHUm3gDwFA66Mzw3LyeTP6vBZY1H1dat//O+T23LLb2
VN3I5xI6Ta5MirdcmrS3ID3KfyI0rn47aGYBROcBTkZTmzNg95S+UzeQc0PzMsNT
79uq/nROacdrjGCT3sTHDN/hMq7MkztReJVni+49Vv4M0GkPGw/zJSZrM233bkf6
c0Plfg6lZrEpfDKEY1WJxA3Bk1QwGROs0303p+tdOmw1XNtB1xLaqUkL39iAigmT
Yo61Zs8liM2EuLE/pDkP2QKe6xJMlXzzawWpXhaDzLhn4ugTncxbgtNMs+1b/97l
c6wjOy0AvzVVdAlJ2ElYGn+SNuZRkg7zJn0cTRe8yexDJtC/QV9AqURE9JnnV4ee
UB9XVKg+/XRjL7FQZQnmWEIuQxpMtPAlR1n6BB6T1CZGSlCBst6+eLf8ZxXhyVeE
Hg9j1uliutZfVS7qXMYoCAQlObgOK6nyTJccBz8NUvXt7y+CDwIDAQABo0IwQDAd
BgNVHQ4EFgQUU3m/WqorSs9UgOHYm8Cd8rIDZsswDgYDVR0PAQH/BAQDAgEGMA8G
A1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAFzUfA3P9wF9QZllDHPF
Up/L+M+ZBn8b2kMVn54CVVeWFPFSPCeHlCjtHzoBN6J2/FNQwISbxmtOuowhT6KO
VWKR82kV2LyI48SqC/3vqOlLVSoGIG1VeCkZ7l8wXEskEVX/JJpuXior7gtNn3/3
ATiUFJVDBwn7YKnuHKsSjKCaXqeYalltiz8I+8jRRa8YFWSQEg9zKC7F4iRO/Fjs
8PRF/iKz6y+O0tlFYQXBl2+odnKPi4w2r78NBc5xjeambx9spnFixdjQg3IM8WcR
iQycE0xyNN+81XHfqnHd4blsjDwSXWXavVcStkNr/+XeTWYRUc+ZruwXtuhxkYze
Sf7dNXGiFSeUHM9h4ya7b6NnJSFd5t0dCy5oGzuCr+yDZ4XUmFF0sbmZgIn/f3gZ
XHlKYC6SQK5MNyosycdiyA5d9zZbyuAlJQG03RoHnHcAP9Dc1ew91Pq7P8yF1m9/
qS3fuQL39ZeatTXaw2ewh0qpKJ4jjv9cJ2vhsE/zB+4ALtRZh8tSQZXq9EfX7mRB
VXyNWQKV3WKdwrnuWih0hKWbt5DHDAff9Yk2dDLWKMGwsAvgnEzDHNb842m1R0aB
L6KCq9NjRHDEjf8tM7qtj3u1cIiuPhnPQCjY/MiQu12ZIvVS5ljFH4gxQ+6IHdfG
jjxDah2nGN59PRbxYvnKkKj9
-----END CERTIFICATE-----
</code></pre>
<h1>Root certificate which is part of the ca-bundle.trust file from git</h1>
<pre><code>-----BEGIN TRUSTED CERTIFICATE-----
MIIF3jCCA8agAwIBAgIQAf1tMPyjylGoG7xkDjUDLTANBgkqhkiG9w0BAQwFADCB
iDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0pl
cnNleSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNV
BAMTJVVTRVJUcnVzdCBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAw
MjAxMDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBiDELMAkGA1UEBhMCVVMxEzARBgNV
BAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVU
aGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBSU0EgQ2Vy
dGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK
AoICAQCAEmUXNg7D2wiz0KxXDXbtzSfTTK1Qg2HiqiBNCS1kCdzOiZ/MPans9s/B
3PHTsdZ7NygRK0faOca8Ohm0X6a9fZ2jY0K2dvKpOyuR+OJv0OwWIJAJPuLodMkY
tJHUYmTbf6MG8YgYapAiPLz+E/CHFHv25B+O1ORRxhFnRghRy4YUVD+8M/5+bJz/
Fp0YvVGONaanZshyZ9shZrHUm3gDwFA66Mzw3LyeTP6vBZY1H1dat//O+T23LLb2
VN3I5xI6Ta5MirdcmrS3ID3KfyI0rn47aGYBROcBTkZTmzNg95S+UzeQc0PzMsNT
79uq/nROacdrjGCT3sTHDN/hMq7MkztReJVni+49Vv4M0GkPGw/zJSZrM233bkf6
c0Plfg6lZrEpfDKEY1WJxA3Bk1QwGROs0303p+tdOmw1XNtB1xLaqUkL39iAigmT
Yo61Zs8liM2EuLE/pDkP2QKe6xJMlXzzawWpXhaDzLhn4ugTncxbgtNMs+1b/97l
c6wjOy0AvzVVdAlJ2ElYGn+SNuZRkg7zJn0cTRe8yexDJtC/QV9AqURE9JnnV4ee
UB9XVKg+/XRjL7FQZQnmWEIuQxpMtPAlR1n6BB6T1CZGSlCBst6+eLf8ZxXhyVeE
Hg9j1uliutZfVS7qXMYoCAQlObgOK6nyTJccBz8NUvXt7y+CDwIDAQABo0IwQDAd
BgNVHQ4EFgQUU3m/WqorSs9UgOHYm8Cd8rIDZsswDgYDVR0PAQH/BAQDAgEGMA8G
A1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAFzUfA3P9wF9QZllDHPF
Up/L+M+ZBn8b2kMVn54CVVeWFPFSPCeHlCjtHzoBN6J2/FNQwISbxmtOuowhT6KO
VWKR82kV2LyI48SqC/3vqOlLVSoGIG1VeCkZ7l8wXEskEVX/JJpuXior7gtNn3/3
ATiUFJVDBwn7YKnuHKsSjKCaXqeYalltiz8I+8jRRa8YFWSQEg9zKC7F4iRO/Fjs
8PRF/iKz6y+O0tlFYQXBl2+odnKPi4w2r78NBc5xjeambx9spnFixdjQg3IM8WcR
iQycE0xyNN+81XHfqnHd4blsjDwSXWXavVcStkNr/+XeTWYRUc+ZruwXtuhxkYze
Sf7dNXGiFSeUHM9h4ya7b6NnJSFd5t0dCy5oGzuCr+yDZ4XUmFF0sbmZgIn/f3gZ
XHlKYC6SQK5MNyosycdiyA5d9zZbyuAlJQG03RoHnHcAP9Dc1ew91Pq7P8yF1m9/
qS3fuQL39ZeatTXaw2ewh0qpKJ4jjv9cJ2vhsE/zB+4ALtRZh8tSQZXq9EfX7mRB
VXyNWQKV3WKdwrnuWih0hKWbt5DHDAff9Yk2dDLWKMGwsAvgnEzDHNb842m1R0aB
L6KCq9NjRHDEjf8tM7qtj3u1cIiuPhnPQCjY/MiQu12ZIvVS5ljFH4gxQ+6IHdfG
jjxDah2nGN59PRbxYvnKkKj9MD0wFAYIKwYBBQUHAwQGCCsGAQUFBwMBDCVVU0VS
VHJ1c3QgUlNBIENlcnRpZmljYXRpb24gQXV0aG9yaXR5
-----END TRUSTED CERTIFICATE-----
</code></pre>
<h1>Question</h1>
<ul>
<li>Why does git not have the exact same root certificate as the one from User Trust?</li>
<li>What is in the additional content in the certificate file?</li>
</ul>
<h1>Answer</h1>
<p>As mentioned in a comment by user "qwerty 1999", the command <code>git config --global http.sslbackend schannel</code> can be used to force git to use the windows certificate store which solves my problem since the "User Trust" root certificate is part of the certificate store by default.
I still don't understand why git doesn't use the root certificate provided by "User Trust CA". This would avoid having to apply this workaround.</p>
| [
{
"answer_id": 74378047,
"author": "Ruan Mendes",
"author_id": 227299,
"author_profile": "https://Stackoverflow.com/users/227299",
"pm_score": 1,
"selected": false,
"text": "abstract class AbstractView {\n ctx : typeof AbstractView;\n constructor() {\n this.ctx = this.constructor as typeof AbstractView;\n }\n}\n"
},
{
"answer_id": 74378121,
"author": "Dimava",
"author_id": 5734961,
"author_profile": "https://Stackoverflow.com/users/5734961",
"pm_score": 2,
"selected": false,
"text": "abstract class AbstractView {\n get ctx(): typeof AbstractView {\n return this.constructor as typeof AbstractView;\n }\n static getStatus() : string\n {\n return 'hi';\n }\n}\nclass TestView extends AbstractView {\n static getStatus() : string\n {\n return 'hi2';\n }\n}\n\nconsole.log(new TestView().ctx.getStatus())\n// > \"hi2\"\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1155873/"
] |
74,378,012 | <p>This is what I am after.</p>
<ol>
<li>File or folder is dragged and dropped on the application shortcut</li>
<li>User is prompted for an entry</li>
<li>The dropped file or folder is renamed, with the text returned from the prompt as a file prefix, followed by a separator character (hyphen, underscore, space - any of those)</li>
<li>Renamed file or folder is copied to a specific destination folder, which is always the same folder</li>
</ol>
<p>If that is impossible, this is another option:</p>
<ol>
<li>Application is launched (no drag and drop)</li>
<li>User is prompted to browse to file or folder to select it</li>
<li>User is then prompted for text entry
(note: steps 2 and 3 can be reversed if it makes things easier)</li>
<li>File or folder selected in step 2 is renamed with the text returned from 3 as a prefix, followed by a separator character</li>
<li>Renamed file or folder is copied to a specific destination folder, which is always the same folder</li>
</ol>
<p>The destination folder is a hot folder. So best to do the renaming before the copy.</p>
<p>I have done this in Mac environment using AppleScript. I am not sure about how to approach in Windows. BAT file? Javascript? At this point all I have done is write a javascript which prompts for text and returns text string as an alert, with returned text of prompt in the string in a Mac environment:</p>
<pre class="lang-js prettyprint-override"><code>var app = Application("Finder")
app.includeStandardAdditions = true
var response = app.displayDialog("ENTER JOB NO",{
defaultAnswer: "",
buttons: ["Cancel","Continue"],
defaultButton: "Continue"
})
app.displayDialog("Hello! Your job number is " + (response.textReturned))
</code></pre>
<p>Different from Windows, and I am not as proficient in Windows, bat files, or javascript either. Also I'm not sure if javascript is the best approach for what I want.</p>
| [
{
"answer_id": 74378047,
"author": "Ruan Mendes",
"author_id": 227299,
"author_profile": "https://Stackoverflow.com/users/227299",
"pm_score": 1,
"selected": false,
"text": "abstract class AbstractView {\n ctx : typeof AbstractView;\n constructor() {\n this.ctx = this.constructor as typeof AbstractView;\n }\n}\n"
},
{
"answer_id": 74378121,
"author": "Dimava",
"author_id": 5734961,
"author_profile": "https://Stackoverflow.com/users/5734961",
"pm_score": 2,
"selected": false,
"text": "abstract class AbstractView {\n get ctx(): typeof AbstractView {\n return this.constructor as typeof AbstractView;\n }\n static getStatus() : string\n {\n return 'hi';\n }\n}\nclass TestView extends AbstractView {\n static getStatus() : string\n {\n return 'hi2';\n }\n}\n\nconsole.log(new TestView().ctx.getStatus())\n// > \"hi2\"\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19701285/"
] |
74,378,015 | <p>I want to know if I can use match cases within Python to match within a string - that is, if a string contains the match case. Example:</p>
<pre><code>mystring = "xmas holidays"
match mystring:
case "holidays":
return true
case "workday":
return false
</code></pre>
<p>I can see why it wouldn't, since this could potentially match several cases at once, but I wanted to know if it was possible.</p>
| [
{
"answer_id": 74378359,
"author": "Abdul Niyas P M",
"author_id": 6699447,
"author_profile": "https://Stackoverflow.com/users/6699447",
"pm_score": 1,
"selected": false,
"text": "match"
},
{
"answer_id": 74378572,
"author": "Notaru Nguyen",
"author_id": 13835451,
"author_profile": "https://Stackoverflow.com/users/13835451",
"pm_score": 0,
"selected": false,
"text": "[*_]"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198974/"
] |
74,378,018 | <p>I am trying to get the data from an API endpoint using the following block of code.</p>
<pre><code>interface IResponse{
"id": number,
"title": string,
"description": string,
"price": number,
"discountPercentage": number,
"rating": number,
"stock": number,
"brand": string,
"category": string,
"thumbnail": string,
"images": Set<string>
}
fetch('https://dummyjson.com/products/1')
.then(res => res.json())
.then(res => {
let b: IResponse = res;
console.log(b)
});
</code></pre>
<p>As you can see, the type of <code>images</code> in <code>IResponse</code> is a set of strings. However, the API response returns an array of images, and I am assigning that response object to a variable with type IResponse. So the question is, why doesn't typescript complain about type mismatch of images property in response object(array) and <code>IResponse</code> interface (set of Strings) upon assignment?</p>
| [
{
"answer_id": 74378359,
"author": "Abdul Niyas P M",
"author_id": 6699447,
"author_profile": "https://Stackoverflow.com/users/6699447",
"pm_score": 1,
"selected": false,
"text": "match"
},
{
"answer_id": 74378572,
"author": "Notaru Nguyen",
"author_id": 13835451,
"author_profile": "https://Stackoverflow.com/users/13835451",
"pm_score": 0,
"selected": false,
"text": "[*_]"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20460765/"
] |
74,378,030 | <p>I have a test stand with Cartridge cluster.
Stand start with docker-compose (use tarantool 2.10.3 docker-image with cartridge-cli inside).</p>
<p>container-1:</p>
<ul>
<li>instance-1-1</li>
<li>instance-1-2</li>
</ul>
<p>container-2:</p>
<ul>
<li>instance-2-1</li>
<li>instance-2-2</li>
</ul>
<p>After starting all instances on the container-1, the BASH script execute commands:</p>
<pre><code>sh# cartridge replicasets join --replicaset group-1 instance-1-1
sh# cartridge replicasets join --replicaset group-2 instance-1-2
</code></pre>
<p>All OK</p>
<p>But after starting container-2 and calling the same commands, an error occurs:</p>
<pre><code>sh# cartridge replicasets join --replicaset group-1 instance-2-1
• Join instance(s) instance-2-1 to replica set group-1
⨯ Failed to connect to Tarantool instance: Failed to dial: dial unix /opt/tarantool/tmp/run/test.instance-1-1.control: connect: no such file or directory
</code></pre>
<p>In WEB all OK, but I want use CLI for it or something like this (for automatization)</p>
| [
{
"answer_id": 74378359,
"author": "Abdul Niyas P M",
"author_id": 6699447,
"author_profile": "https://Stackoverflow.com/users/6699447",
"pm_score": 1,
"selected": false,
"text": "match"
},
{
"answer_id": 74378572,
"author": "Notaru Nguyen",
"author_id": 13835451,
"author_profile": "https://Stackoverflow.com/users/13835451",
"pm_score": 0,
"selected": false,
"text": "[*_]"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12066909/"
] |
74,378,057 | <p>I assume this is a simple task for <code>pandas</code> but I don't get it.</p>
<p>I have data liket this</p>
<pre><code> Group Val
0 A 0
1 A 1
2 A <NA>
3 A 3
4 B 4
5 B <NA>
6 B 6
7 B <NA>
</code></pre>
<p>And I want to know the frequency of valid and invalid values in <code>Val</code> per group <code>Group</code>. This is the expected result.</p>
<pre><code> A B Total
Valid 3 2 5
NA 1 2 3
</code></pre>
<p>Here is code to generate that sample data.</p>
<pre><code>#!/usr/bin/env python3
import pandas as pd
df = pd.DataFrame({
'Group': list('AAAABBBB'),
'Val': range(8)
})
# some values to NA
for idx in [2, 5, 7]:
df.iloc[idx, 1] = pd.NA
print(df)
</code></pre>
<p><strong>What I tried</strong> is something with grouping</p>
<pre><code>>>> df.groupby('Group').agg(lambda x: x.isna())
Val
Group
A [False, False, True, False]
B [False, True, False, True]
>>> df.groupby('Group').apply(lambda x: x.isna())
Group Val
0 False False
1 False False
2 False True
3 False False
4 False False
5 False True
6 False False
7 False True
</code></pre>
| [
{
"answer_id": 74378119,
"author": "It_is_Chris",
"author_id": 9177877,
"author_profile": "https://Stackoverflow.com/users/9177877",
"pm_score": 2,
"selected": false,
"text": "new = df.groupby(['Group', df['Val'].isna().replace({True: 'NA', False: 'Valid'})])['Group'].count().unstack(level=0)\nnew['Total'] = new.sum(axis=1)\nprint(new)\n\nGroup A B Total\nVal \nNA 1 2 3\nValid 3 2 5\n"
},
{
"answer_id": 74378292,
"author": "Naveed",
"author_id": 3494754,
"author_profile": "https://Stackoverflow.com/users/3494754",
"pm_score": 2,
"selected": true,
"text": "# cross tab to take the summarize\n# convert Val to NA or Valid depending on the value\ndf2=(pd.crosstab(df['Val'].isna().map({True: 'NA', False: 'Valid'}), \n df['Group'] )\n .reset_index() \n .rename_axis(columns=None))\n\ndf2['Total']=df2.sum(axis=1, numeric_only=True) # add Total column\nout=df2.set_index('Val') # set index to match expected output\nout\n"
},
{
"answer_id": 74378399,
"author": "PaulS",
"author_id": 11564487,
"author_profile": "https://Stackoverflow.com/users/11564487",
"pm_score": 1,
"selected": false,
"text": "pandas.pivot_table"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4865723/"
] |
74,378,061 | <p>I have the next dataframe:</p>
<pre><code>House = rep(c('A','B','C'), each=10)
Date = as.Date(c('2014-10-13','2014-10-20','2014-10-27','2014-11-03','2014-11-10','2014-10-30','2014-11-06','2014-11-13','2014-11-20','2014-11-27',
'2019-11-27','2019-12-04','2019-12-11','2019-12-18','2019-12-25','2020-01-01','2020-01-08','2020-01-15','2020-01-22','2020-01-29',
'2017-07-13','2017-07-20','2017-04-21','2017-04-28','2017-05-05','2017-05-12','2017-05-19','2017-05-26','2017-06-02','2017-06-09'))
Week = rep(c(1,2,3,4,5,6,7,8,9,10), times=3)
Value = c(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1,0.01,0.02,0.03,0.04,0.05,0.06,0.07,0.08,0.09,0.1,0.001,0.002,0.003,0.004,0.005,0.006,0.007,0.008,0.009,0.01)
mock = data.frame(House,Date,Week,Value)
</code></pre>
<p>I want to split this dataframe by <code>Year</code> in specific, BUT, I want to keep together the group <code>B</code>. Otherwise it gets split as follows:</p>
<pre><code>$`2019`
A data.frame: 5 × 4 House Date Week Value
<chr> <date> <dbl> <dbl>
11 B 2019-11-27 1 0.01
12 B 2019-12-04 2 0.02
13 B 2019-12-11 3 0.03
14 B 2019-12-18 4 0.04
15 B 2019-12-25 5 0.05
$`2020`
A data.frame: 5 × 4 House Date Week Value
<chr> <date> <dbl> <dbl>
16 B 2020-01-01 6 0.06
17 B 2020-01-08 7 0.07
18 B 2020-01-15 8 0.08
19 B 2020-01-22 9 0.09
20 B 2020-01-29 10 0.10
</code></pre>
<p>Desired output:</p>
<pre><code>$`2019-2020`
A data.frame: 5 × 4 House Date Week Value
<chr> <date> <dbl> <dbl>
11 B 2019-11-27 1 0.01
12 B 2019-12-04 2 0.02
13 B 2019-12-11 3 0.03
14 B 2019-12-18 4 0.04
15 B 2019-12-25 5 0.05
16 B 2020-01-01 6 0.06
17 B 2020-01-08 7 0.07
18 B 2020-01-15 8 0.08
19 B 2020-01-22 9 0.09
20 B 2020-01-29 10 0.10
</code></pre>
<p>I tried a similar approach using <code>dplyr::group_split()</code>, but obtaining a similar output. On the other hand, the cleanest list with <code>split()</code> is given by the next, but I DON'T need it by <code>House</code>:</p>
<pre><code>house.year = split(mock, c(House, format(mock$Date, "%Y")))
house.year = house.year[sapply(house.year, function(x) dim(x)[1]) > 0]
</code></pre>
<p>NOTE: The name of the desired list is how I imagine it, not how I expect it, but I would like that content included in this list of lists.</p>
<p><strong>EDIT: edited the title to point that I have more than 3 categories, like asked in the beginning.</strong></p>
| [
{
"answer_id": 74378136,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "house.year <- split(mock, list(mock$House, format(mock$Date, \"%Y\")), drop = TRUE)\nlst1 <- lapply(split(house.year, sub(\"\\\\.\\\\d+$\", \"\", \n names(house.year))),\n \\(x) {tmp <- do.call(rbind, x)\n row.names(tmp) <- NULL; tmp})\nnames(lst1) <- sapply(lst1, \\(x) paste(unique(format(x$Date, \"%Y\")),\n collapse = \"-\"))\n"
},
{
"answer_id": 74386976,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 3,
"selected": true,
"text": "mock %>%\n group_by(House) %>%\n mutate(year = paste0(unique(format(Date, \"%Y\")), collapse = \"-\")) %>%\n ungroup() %>%\n split(~year) %>%\n lapply(`[`, -(length(mock)+1))\n"
},
{
"answer_id": 74387036,
"author": "Gerlex",
"author_id": 14682764,
"author_profile": "https://Stackoverflow.com/users/14682764",
"pm_score": 0,
"selected": false,
"text": "House"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14682764/"
] |
74,378,065 | <pre><code>a,b = map(int, input().split())
</code></pre>
<p>In the above code or anything similar, we use split to separate multiple inputs on a single line, typically separated with a space, and assign the results to the variables.</p>
<p>This is very convenient feature, however I am facing a problem:</p>
<p>Say I want to populate a list A with n integers inside of it, It is relatively easy to ask for n to get the list size and populate it using split, BUT! what if the user wrote too many values?</p>
<p>Say I have 3 variables to fill but the user inputted 4, I get the ValueError: too many values to unpack.</p>
<p>Is there any way to limit the user input to n space separated variables that they would write on a single line? i.e: after writing n space separated variables, stop listening for inputs or don't let them type anything more or just disregard whatever comes after that.</p>
<p>Does split have any functionality like that?</p>
<p>I am newly learning python and as I write this, it comes to my mind to try and take whatever the user inputs, put it in a list, slice off whatever elements beyond n, our list size, and assign the remaining values to A, our list. But that sounds like scratching my left ear with my right hand (like the needlessly long way) and it feels, to me at least, that something like that should be included in split or in python somewhere.</p>
<p>I'm a beginner so please keep your answer relatively beginner-friendly/easy to tell what is going on.</p>
<p>Thank you,</p>
<p>Fuzzy.</p>
<hr />
<p>Note: I am aware that I can take each input on a line and use a for loop in range(n), yes. But the aim here is to use input().split().</p>
| [
{
"answer_id": 74378199,
"author": "jprebys",
"author_id": 3268228,
"author_profile": "https://Stackoverflow.com/users/3268228",
"pm_score": 2,
"selected": true,
"text": "a, b, *_ = map(int, input().split())\n"
},
{
"answer_id": 74378209,
"author": "Franklin Pezzuti Dyer",
"author_id": 10777850,
"author_profile": "https://Stackoverflow.com/users/10777850",
"pm_score": 0,
"selected": false,
"text": "a,b = map(int, input().split()[:2])\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20460678/"
] |
74,378,070 | <p>I am new to Google Sheets and need some help in validating data from one sheet into another. I have a list of item on other sheets and just want to validate on my master sheet whether that item is on each of my two other sheets.</p>
<p>On my master sheet (Delivered List), I have a list of approx 5k items and want to check to see which items are on my two other lists, Live Yes and Live No.</p>
<p>Here is the Delivered List sheet.
<a href="https://i.stack.imgur.com/ffyp4.png" rel="nofollow noreferrer">!Delivered List</a>](<a href="https://i.stack.imgur.com/ffyp4.png" rel="nofollow noreferrer">https://i.stack.imgur.com/ffyp4.png</a>)</p>
<p>In column K, I need a formula to check Live Yes to see which items in column D are on that sheet.
In column L, check Live No list for same.</p>
<p>Here are the screenshots of Live Yes and Live No.</p>
<p><a href="https://i.stack.imgur.com/4Bubn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4Bubn.png" alt="screenshot of Live Yes sheet" /></a></p>
<p><a href="https://i.stack.imgur.com/KE0fy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KE0fy.png" alt="screenshot of Live No sheet" /></a></p>
<p>I hope this is clear enough and if anyone can help me with this.
thanks tremendously!
AJ</p>
<p>I tried copying a similar formula from another example, but couldn't get it to work.</p>
| [
{
"answer_id": 74378199,
"author": "jprebys",
"author_id": 3268228,
"author_profile": "https://Stackoverflow.com/users/3268228",
"pm_score": 2,
"selected": true,
"text": "a, b, *_ = map(int, input().split())\n"
},
{
"answer_id": 74378209,
"author": "Franklin Pezzuti Dyer",
"author_id": 10777850,
"author_profile": "https://Stackoverflow.com/users/10777850",
"pm_score": 0,
"selected": false,
"text": "a,b = map(int, input().split()[:2])\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20433661/"
] |
74,378,082 | <p>I have this types:</p>
<pre><code>type IInputType = "text" | "checkbox" | "number";
type IField<T extends IInputType> = {
name: string;
value:
T extends "checkbox" ? boolean :
T extends "number" ? number :
string;
type: T;
};
type IPossibleFieldTypes = IField<IInputType>;
</code></pre>
<p>That way the conditional is not working because field.value is typed as string, number or boolean, and not only boolean as should:</p>
<pre><code> // field type is IPossibleFieldTypes
if (field.type === "checkbox") {
// Here field.value should only be boolean
// but TS are allowing string or number too
}
</code></pre>
<p>But if I specify the possible IFields manually:</p>
<pre><code>type IPossibleFieldTypes =
| IField<"text">
| IField<"checkbox">
| IField<"number">;
</code></pre>
<p>Now the types are being displayed correctly:</p>
<pre><code> if (field.type === "checkbox") {
// Here field.value can only be boolean
}
</code></pre>
<p>The question is:</p>
<p>There is a way to make this type work (IPossibleFieldTypes) without have to manually set the possible generics?</p>
| [
{
"answer_id": 74378199,
"author": "jprebys",
"author_id": 3268228,
"author_profile": "https://Stackoverflow.com/users/3268228",
"pm_score": 2,
"selected": true,
"text": "a, b, *_ = map(int, input().split())\n"
},
{
"answer_id": 74378209,
"author": "Franklin Pezzuti Dyer",
"author_id": 10777850,
"author_profile": "https://Stackoverflow.com/users/10777850",
"pm_score": 0,
"selected": false,
"text": "a,b = map(int, input().split()[:2])\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8903411/"
] |
74,378,117 | <p>I have a table with a column name HS where data is like this:</p>
<pre><code>HS <- c("44.01 44.12","44.1234","4561.10 4562.10 4620.1")
</code></pre>
<p>I would like to get a list :</p>
<pre><code>listcodes = c("44.01","44.12","44.1234","4561.10","4562.10","4620.1")
</code></pre>
<hr />
<h1>Question Update</h1>
<p>What if I have this dataset</p>
<pre><code>HS PROD
44.10 44.12 AA
44.13 BB
</code></pre>
<p>and that I want to repeat the HS2017 codes for every prod codes like</p>
<pre><code>HS PROD
44.10 AA
44.12 AA
44.13 BB
</code></pre>
| [
{
"answer_id": 74378148,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "scan"
},
{
"answer_id": 74378460,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 3,
"selected": true,
"text": "strsplit"
},
{
"answer_id": 74390526,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 1,
"selected": false,
"text": "separte_rows"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5457869/"
] |
74,378,151 | <p>I have a pipeline that loads multiple csv's and an xlsx file into 4 separate tables. Generally, this pipeline runs fine. However, occasionally one of the tables (always the same table) results in an invalid object. If I re-run the pipeline with no changes, all is fine. I have never had an issue with any of the other tables loaded by the pipeline. The table fields are all nvarchar(max) and the data is relatively simple. It is also a very small table. Well under 100 rows, and the data in the source rarely changes. It is definitely not changing between successful and unsuccessful runs.</p>
<p>I am interested in any ideas on what may be causing this periodic failure. All runs fine more than 95% of the time. When it fails, it kills the rest of the load process.</p>
| [
{
"answer_id": 74378148,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "scan"
},
{
"answer_id": 74378460,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 3,
"selected": true,
"text": "strsplit"
},
{
"answer_id": 74390526,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 1,
"selected": false,
"text": "separte_rows"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20460908/"
] |
74,378,175 | <p>The code was alright before I tried to used the setState function which is setcategory and setvalue in this code but after I did this my react page went blank. What went wrong and how should I fix it?</p>
<pre><code>import Employee_card from './Employee_card'
import '../styles/home.css'
import {
Link,
useSearchParams
} from 'react-router-dom'
const Employee_dir:React.FC <props> = (employes) => {
const [category, setcategory] = useState("")
const [value, setvalue] = useState("")
let [searchParams]=useSearchParams();
if(searchParams){
setcategory(searchParams.get('category')!)
setvalue(searchParams.get('value')!)
}
return (
<div>
Some code here which is alright
<div/>
)
}```
export default Employee_dir
</code></pre>
| [
{
"answer_id": 74378148,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "scan"
},
{
"answer_id": 74378460,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 3,
"selected": true,
"text": "strsplit"
},
{
"answer_id": 74390526,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 1,
"selected": false,
"text": "separte_rows"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15913488/"
] |
74,378,194 | <p>I have an object which is like</p>
<pre><code>[{
Date: 01/11/2022,
Questionnaire: [
{Title: 'Rating', Ans: '5' },
{Title: 'Comment', Ans: 'Awesome' }
]
},
{
Date: 01/11/2022,
Questionnaire: [
{Title: 'Rating', Ans: '2' },
{Title: 'Comment', Ans: 'Bad' }
]
},
{
Date: 09/12/2022,
Questionnaire: [
{Title: 'Rating', Ans: '3' },
{Title: 'Comment', Ans: 'Okay' }
]
}]
</code></pre>
<p>I'm trying to create a new object which looks like</p>
<pre><code>[{
Date: 01/11/2022
Ratings: ['5', '2']
},
{
Date: 09/12/2022
Ratings: ['3']
}]
</code></pre>
<p>I'm trying to filter it by date and get all the ratings for that particular date</p>
| [
{
"answer_id": 74378369,
"author": "dangarfield",
"author_id": 3265253,
"author_profile": "https://Stackoverflow.com/users/3265253",
"pm_score": 0,
"selected": false,
"text": " Date: 01/11/2022,\n Questionnaire: [\n {Title: 'Rating', Ans: '5' },\n {Title: 'Comment', Ans: 'Awesome' }\n ]\n},\n{\n Date: 01/11/2022,\n Questionnaire: [\n {Title: 'Rating', Ans: '2' },\n {Title: 'Comment', Ans: 'Bad' }\n ]\n},\n{\n Date: 09/12/2022,\n Questionnaire: [\n {Title: 'Rating', Ans: '3' },\n {Title: 'Comment', Ans: 'Okay' }\n ]\n}]\n\nconst output = _.chain(data)\n .groupBy('Date')\n .map((v,k) => ( {Date: v[0].Date, Ratings: v.map(o => o.Questionnaire.find(q => q.Title === 'Rating')).map(v2 => v2.Ans)}))\n .value()\nconsole.log(output)```\n"
},
{
"answer_id": 74378376,
"author": "kind user",
"author_id": 6695924,
"author_profile": "https://Stackoverflow.com/users/6695924",
"pm_score": 3,
"selected": true,
"text": "Array#reduce"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5447971/"
] |
74,378,196 | <p>I need <code>buffer</code> functionality with output size limiting. Say I have an observable stream <code>myInterval</code> which I want to gate the output of using a notifier observable <code>bufferBy</code>, but when the notifier fires I want to limit the number of items emitted. <code>buffer</code> doesn't have an overload like this, but it illustrates what I'd like to achieve.</p>
<pre class="lang-js prettyprint-override"><code>const maxBufferSize = 5;
const myInterval = interval(1000);
const bufferBy = fromEvent(document, 'click');
const bufferedInterval = myInterval.pipe(buffer(bufferBy, maxBufferSize));
// ex. output: [1,2,3] ... [4,5,6,7,8] ... [9,10]
</code></pre>
<p>Should be lossless. How to do this?</p>
| [
{
"answer_id": 74378369,
"author": "dangarfield",
"author_id": 3265253,
"author_profile": "https://Stackoverflow.com/users/3265253",
"pm_score": 0,
"selected": false,
"text": " Date: 01/11/2022,\n Questionnaire: [\n {Title: 'Rating', Ans: '5' },\n {Title: 'Comment', Ans: 'Awesome' }\n ]\n},\n{\n Date: 01/11/2022,\n Questionnaire: [\n {Title: 'Rating', Ans: '2' },\n {Title: 'Comment', Ans: 'Bad' }\n ]\n},\n{\n Date: 09/12/2022,\n Questionnaire: [\n {Title: 'Rating', Ans: '3' },\n {Title: 'Comment', Ans: 'Okay' }\n ]\n}]\n\nconst output = _.chain(data)\n .groupBy('Date')\n .map((v,k) => ( {Date: v[0].Date, Ratings: v.map(o => o.Questionnaire.find(q => q.Title === 'Rating')).map(v2 => v2.Ans)}))\n .value()\nconsole.log(output)```\n"
},
{
"answer_id": 74378376,
"author": "kind user",
"author_id": 6695924,
"author_profile": "https://Stackoverflow.com/users/6695924",
"pm_score": 3,
"selected": true,
"text": "Array#reduce"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6007429/"
] |
74,378,206 | <p>i decided make portfolio websites I found example, decided to copy its style etc, but I have issue at the start,i made everything good(I was thinking so),but I have a problem with its responsibility, you can see here https://olaolu.dev,that when you change window size, its automatically change size of everything, its similar to object:contain; but a little different, can you help me do it right ?</p>
<p>here is my code</p>
<pre><code><!doctype html>
<html>
<head>
<link rel="stylesheet" href="/b/cs.css">
</head>
<body>
<section class="section-top">
<img class="main1-img" src="/b/images/pngtree-portfolio-memphis-playful-abstract-pink-image_593412.jpg ">
<h2>faxraddin</h2>
<h1>Frontend</br> Developer.</h1>
<h3 class="profession-info">I like to craft solid and scalable frontend products with great user experiences.</h3>
<img class="my-img" src="/b/images/Screenshot 2022-11-04 at 19.35.20.png">
<div class="some-info">
<span>Highly skilled at progressive
enhancement, design systems &
UI Engineering.
</span>
<span>Over a decade of experience
building products for clients
across several countries.
</span>
</div>
<div class="btn-container">
<ul>
<li><a></a></li>
</ul>
</div>
</section>
<script src="/b/js.js"></script>
</body>
</html>
</code></pre>
<p>css</p>
<pre><code>body {
margin: 0;
padding: 0;
}
.section-top{
contain: size;
position: relative;
}
.main1-img{
width: 100%;
height: 666px;
position: relative;
}
.section-top h2{
position: absolute;
top: 0;
padding: 20px;
padding-left: 100px;
font-size: 2.5rem;
color: rgb(32, 166, 166);
}
.section-top h1{
position: absolute;
top: 20%;
left: 10%;
font-size: 4.5rem;
color: rgb(32, 166, 166);
}
.profession-info{
position: absolute;
top:48%;
left: 10%;
color: rgb(32, 166, 166);
width: 25rem;
}
.my-img{
width: 333px;
position: absolute;
right: 22%;
top:23%;
}
.some-info{
position: absolute;
top: 65%;
display: flex;
justify-content: space-between;
width: 30rem;
left: 10%;
}
.some-info span{
width: 50%;
margin-right: 10%;
color: rgb(8, 105, 105);
}
@media screen and (max-width:700px) {
}
</code></pre>
| [
{
"answer_id": 74378369,
"author": "dangarfield",
"author_id": 3265253,
"author_profile": "https://Stackoverflow.com/users/3265253",
"pm_score": 0,
"selected": false,
"text": " Date: 01/11/2022,\n Questionnaire: [\n {Title: 'Rating', Ans: '5' },\n {Title: 'Comment', Ans: 'Awesome' }\n ]\n},\n{\n Date: 01/11/2022,\n Questionnaire: [\n {Title: 'Rating', Ans: '2' },\n {Title: 'Comment', Ans: 'Bad' }\n ]\n},\n{\n Date: 09/12/2022,\n Questionnaire: [\n {Title: 'Rating', Ans: '3' },\n {Title: 'Comment', Ans: 'Okay' }\n ]\n}]\n\nconst output = _.chain(data)\n .groupBy('Date')\n .map((v,k) => ( {Date: v[0].Date, Ratings: v.map(o => o.Questionnaire.find(q => q.Title === 'Rating')).map(v2 => v2.Ans)}))\n .value()\nconsole.log(output)```\n"
},
{
"answer_id": 74378376,
"author": "kind user",
"author_id": 6695924,
"author_profile": "https://Stackoverflow.com/users/6695924",
"pm_score": 3,
"selected": true,
"text": "Array#reduce"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19414154/"
] |
74,378,211 | <p>I have created a simply function with sub functions that returns balance and you can add an amount to update your balance.</p>
<pre class="lang-js prettyprint-override"><code>const bankAccount = (initialBalance) => {
let balance = initialBalance;
return {
getBalance: function() {
return balance;
},
deposit: function(amount) {
balance += amount;
return balance;
},
};
};
const account = bankAccount(100);
account.getBalance();
account.deposit(10);
</code></pre>
<p>My question is I want to make this function asynchronous, my question is should the overarching function be wrapped in a promise or do the sub functions need to be wrapped in a promise.</p>
<p>This is the kind of approach I was thinking. Is this correct?</p>
<pre><code>async function bankAccount(initialBalance) {
let balance = initialBalance;
return await new Promise((resolve, reject) => {
if ("some error") {
reject("something went wrong");
}
return {
getBalance: function () {
resolve(balance);
},
deposit: function (amount) {
balance += amount;
resolve(balance);
},
};
});
}
</code></pre>
| [
{
"answer_id": 74378281,
"author": "Moussa Bistami",
"author_id": 15628525,
"author_profile": "https://Stackoverflow.com/users/15628525",
"pm_score": 0,
"selected": false,
"text": "async function bankAccount(initialBalance) {\n return await new Promise((resolve, reject) => {\n let balance = initialBalance;\n if (\"some error\") {\n reject(\"something went wrong\");\n }\n return {\n getBalance: function () {\n resolve(balance);\n },\n deposit: function (amount) {\n balance += amount;\n resolve(balance);\n },\n };\n });\n}\n"
},
{
"answer_id": 74379842,
"author": "jarmod",
"author_id": 271415,
"author_profile": "https://Stackoverflow.com/users/271415",
"pm_score": 2,
"selected": true,
"text": "function sleep(retval, ms = 2000) {\n return new Promise(function (resolve, reject) {\n setTimeout(() => {\n resolve(retval);\n }, ms);\n });\n}\n\nconst bankAccount = (initialBalance) => {\n let balance = initialBalance;\n\n return {\n getBalance: async () => sleep(balance),\n deposit: async (amount) => {\n balance += amount;\n return sleep(balance);\n },\n };\n};\n\n// An async IIFE, needed unless we have top-level await support\n(async () => {\n const account = bankAccount(100);\n console.log(\"Initial balance:\", await account.getBalance());\n console.log(\"Deposit 10, new balance:\", await account.deposit(10));\n console.log(\"Deposit 10, new balance:\", await account.deposit(10));\n})();"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19940752/"
] |
74,378,217 | <p>I'd like to redirect all visitors to my WordPress website except the translations available for pages in the <code>/cy/</code> subdirectory:</p>
<ul>
<li><code>/cy/</code></li>
</ul>
<p>so for example</p>
<ul>
<li><code>https://myoldomain.co.uk/cy/partners/</code></li>
</ul>
<p>is not redirected but</p>
<ul>
<li><code>https://myoldomain.co.uk/partners/</code></li>
<li><code>https://myoldomain.co.uk/</code></li>
</ul>
<p>are redirected.</p>
<p>I have tried lots and this one works in an online tester but not in practice - all domains including those with <code>/cy/</code> are redirected.</p>
<pre><code>RewriteBase /
RewriteCond %{HTTP_HOST} myoldomain\.co.uk
RewriteCond %{REQUEST_URI} !^/(cy|cy/.*)$
RewriteRule ^(.*)$ https://mynewdomain\.co.uk/$1 [R=301,L]
</code></pre>
<p>Any ideas what I am missing?</p>
| [
{
"answer_id": 74378281,
"author": "Moussa Bistami",
"author_id": 15628525,
"author_profile": "https://Stackoverflow.com/users/15628525",
"pm_score": 0,
"selected": false,
"text": "async function bankAccount(initialBalance) {\n return await new Promise((resolve, reject) => {\n let balance = initialBalance;\n if (\"some error\") {\n reject(\"something went wrong\");\n }\n return {\n getBalance: function () {\n resolve(balance);\n },\n deposit: function (amount) {\n balance += amount;\n resolve(balance);\n },\n };\n });\n}\n"
},
{
"answer_id": 74379842,
"author": "jarmod",
"author_id": 271415,
"author_profile": "https://Stackoverflow.com/users/271415",
"pm_score": 2,
"selected": true,
"text": "function sleep(retval, ms = 2000) {\n return new Promise(function (resolve, reject) {\n setTimeout(() => {\n resolve(retval);\n }, ms);\n });\n}\n\nconst bankAccount = (initialBalance) => {\n let balance = initialBalance;\n\n return {\n getBalance: async () => sleep(balance),\n deposit: async (amount) => {\n balance += amount;\n return sleep(balance);\n },\n };\n};\n\n// An async IIFE, needed unless we have top-level await support\n(async () => {\n const account = bankAccount(100);\n console.log(\"Initial balance:\", await account.getBalance());\n console.log(\"Deposit 10, new balance:\", await account.deposit(10));\n console.log(\"Deposit 10, new balance:\", await account.deposit(10));\n})();"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782964/"
] |
74,378,284 | <p>Why does the code below count from 0 to 9?
Does C store the variable i in test always at the same address? And when calling C initializes the variable i with its previous value?
Or is that just by random chance ?</p>
<p>I used Ubuntu with gcc.</p>
<pre><code>
#include <stdio.h>
void test(){
int i;
printf("%d\n", i);
i++;
}
int main(int argc, char const *argv[])
{
for (int i = 0; i < 10; i++){
test();
}
return 0;
}
/*
output:
0
1
2
3
4
5
6
7
8
9
*/
</code></pre>
<p>I also created an array in between function calls to see if the memory might be overritten but that did not change anything.</p>
| [
{
"answer_id": 74378336,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 2,
"selected": false,
"text": "i"
},
{
"answer_id": 74378354,
"author": "ikegami",
"author_id": 589924,
"author_profile": "https://Stackoverflow.com/users/589924",
"pm_score": 0,
"selected": false,
"text": "i"
},
{
"answer_id": 74378420,
"author": "chrslg",
"author_id": 20037042,
"author_profile": "https://Stackoverflow.com/users/20037042",
"pm_score": 2,
"selected": false,
"text": "21967\n21968\n21969\n21970\n21971\n21972\n21973\n21974\n21975\n21976\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11555394/"
] |
74,378,320 | <p>I was trying to run some c program on a RISCV processor and I got this:</p>
<pre><code>/foss/tools/riscv-gnu-toolchain-rv32i/217e7f3debe424d61374d31e33a091a630535937/lib/gcc/riscv32-unknown-linux-gnu/11.1.0/../../../../riscv32-unknown-linux-gnu/bin/ld: test_la.elf section `.data' will not fit in region `dff'
/foss/tools/riscv-gnu-toolchain-rv32i/217e7f3debe424d61374d31e33a091a630535937/lib/gcc/riscv32-unknown-linux-gnu/11.1.0/../../../../riscv32-unknown-linux-gnu/bin/ld: region `dff' overflowed by 1624 bytes
collect2: error: ld returned 1 exit status
</code></pre>
<p>According to a comment in <a href="https://stackoverflow.com/questions/42041390/region-ram-overflowed-and-section-text-will-not-fit-region-ram">this</a> thread, it might be caused by declaring some large global arrays. And it is true for me, I have these globally (outside the main function):</p>
<pre><code>int sig_A [Bits] = { 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1};
int sig_B [Bits] = { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int sig_C [Bits] = { 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0};
int data_i [Bits] = { 0, 0, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 2, 2, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 2, 3, 2, 2, 2, 2, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 6, 0, 0};
</code></pre>
<p>I need these data to be send from the RISCV to some digital circuit. How can I make this happen (if there is a way). Thank you.</p>
<p><strong>linker file</strong></p>
<pre><code>/* Copyright lowRISC contributors.
Licensed under the Apache License, Version 2.0, see LICENSE for details.
SPDX-License-Identifier: Apache-2.0 */
INCLUDE ../generated/output_format.ld
OUTPUT_ARCH(riscv)
/*******
MEMORY
{
Change this if you'd like different sizes. Arty A7-100(35) has a maximum of 607.5KB(225KB)
BRAM space. Configuration below is for maximum BRAM capacity with Artya A7-35 while letting
CoreMark run (.vmem of 152.8KB).
ram : ORIGIN = 0x00100000, LENGTH = 0x30000 * 192 kB *
stack : ORIGIN = 0x00130000, LENGTH = 0x8000 * 32 kB *
}
**********/
_entry_point = _vectors_start + 0x80;
ENTRY(_entry_point)
/* The tohost address is used by Spike for a magic "stop me now" message. This
is set to equal SIM_CTRL_CTRL (see simple_system_regs.h), which has that
effect in simple_system simulations. Note that it must be 8-byte aligned.
We don't read data back from Spike, so fromhost is set to some dummy value:
we place it just above the top of the stack.
*/
tohost = 0x20008;
fromhost = _stack_start + 0x10;
SECTIONS
{
.vectors :
{
. = ALIGN(4);
_vectors_start = .;
KEEP(*(.vectors))
_vectors_end = .;
} > flash
.text : {
. = ALIGN(4);
*(.text)
*(.text.*)
} > flash
.rodata : {
. = ALIGN(4);
/* Small RO data before large RO data */
*(.srodata)
*(.srodata.*)
*(.rodata);
*(.rodata.*)
} > flash
.data : {
. = ALIGN(4);
/* Small data before large data */
*(.sdata)
*(.sdata.*)
*(.data);
*(.data.*)
} > dff AT > flash
.bss :
{
. = ALIGN(4);
_bss_start = .;
/* Small BSS before large BSS */
*(.sbss)
*(.sbss.*)
*(.bss)
*(.bss.*)
*(COMMON)
_bss_end = .;
} > dff
}
PROVIDE(_stack_start = ORIGIN(sram) + LENGTH(sram));
</code></pre>
| [
{
"answer_id": 74378336,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 2,
"selected": false,
"text": "i"
},
{
"answer_id": 74378354,
"author": "ikegami",
"author_id": 589924,
"author_profile": "https://Stackoverflow.com/users/589924",
"pm_score": 0,
"selected": false,
"text": "i"
},
{
"answer_id": 74378420,
"author": "chrslg",
"author_id": 20037042,
"author_profile": "https://Stackoverflow.com/users/20037042",
"pm_score": 2,
"selected": false,
"text": "21967\n21968\n21969\n21970\n21971\n21972\n21973\n21974\n21975\n21976\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10566333/"
] |
74,378,330 | <p>This is a minor cosmetic thing, I'm just curious what's going on under the water. I'm converting MARC21 XML to some other XML dialext using Saxonica <code>transform.exe</code>.</p>
<p>Here's a short sample of my output. The question is: how come <code>OCLC_number</code> has tags and content each on a separate line (with the closing tag backtabbed), whereas all the others have tags and contents all on one line? The latter looks better to me, but I know it's just a cosmetic thing.</p>
<pre><code> <?xml version="1.0" encoding="UTF-8"?>
<AdlibXML xmlns:marc="http://www.loc.gov/MARC21/slim">
<record>
<OCLC_number>
776125014
</OCLC_number>
<author>Lippmann, Harry.</author>
<title>Deutsches Atlantik Wall Archiv : Register ... / Harry Lippmann.</title>
<place_of_publication>Köln :</place_of_publication>
</record>
</AdlibXML>
</code></pre>
<p>Here's a sample input XML. In real life, it's a much larger export from WorldCat.</p>
<pre><code> <collection>
<record xmlns="http://www.loc.gov/MARC21/slim">
<datafield tag="034" ind1=" " ind2=" ">
<subfield code="a">(OCoLC)776125014</subfield>
</datafield>
<datafield tag="100" ind1="1" ind2=" ">
<subfield code="a">Lippmann, Harry.</subfield>
</datafield>
<datafield tag="245" ind1="1" ind2="0">
<subfield code="a">Deutsches Atlantik Wall Archiv :</subfield>
<subfield code="b">Register ... /</subfield>
<subfield code="c">Harry Lippmann.</subfield>
</datafield>
<datafield tag="260" ind1=" " ind2=" ">
<subfield code="a">Köln :</subfield>
<subfield code="b">Lippmann,</subfield>
<subfield code="c">1996-....</subfield>
</datafield>
</record>
</collection>
</code></pre>
<p>Here's a short version of my XSLT.</p>
<pre><code> <?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:marc="http://www.loc.gov/MARC21/slim"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>
<xsl:output method="xml" indent="yes"/>
<xsl:template match="collection">
<AdlibXML>
<xsl:apply-templates select="marc:record" />
</AdlibXML>
</xsl:template>
<xsl:template match="marc:record">
<!-- OCLC-number must not be empty -->
<xsl:if test="marc:datafield[@tag=034] !=''" >
<record>
<OCLC_number>
<xsl:value-of select="translate(marc:datafield[@tag=034], '(OCoLC)', '')" />
</OCLC_number>
<author>
<xsl:value-of select="marc:datafield[@tag=100]/marc:subfield[@code='a']" />
</author>
<title>
<xsl:value-of select="marc:datafield[@tag=245]/marc:subfield[@code='a']" />
<xsl:if test="marc:datafield[@tag=245]/marc:subfield[@code='b'] != ''" >
<xsl:text> </xsl:text>
<xsl:value-of select="marc:datafield[@tag=245]/marc:subfield[@code='b']" />
</xsl:if>
<xsl:if test="marc:datafield[@tag=245]/marc:subfield[@code='c'] !=''" >
<xsl:text> </xsl:text>
<xsl:value-of select="marc:datafield[@tag=245]/marc:subfield[@code='c']" />
</xsl:if>
</title>
<place_of_publication>
<xsl:value-of select="marc:datafield[@tag=260]/marc:subfield[@code='a']" />
</place_of_publication>
</record>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
</code></pre>
<p>The XSLT works. I learned about default namespaces in the process of making it. In fact, I learned I <em>had to</em> use <code>xmlns:marc="http://www.loc.gov/MARC21/slim"</code>. But while MARC21 itself is fully documented, I couldn't find any documentation about what this specific namespace is supposed to do or define.</p>
| [
{
"answer_id": 74378336,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 2,
"selected": false,
"text": "i"
},
{
"answer_id": 74378354,
"author": "ikegami",
"author_id": 589924,
"author_profile": "https://Stackoverflow.com/users/589924",
"pm_score": 0,
"selected": false,
"text": "i"
},
{
"answer_id": 74378420,
"author": "chrslg",
"author_id": 20037042,
"author_profile": "https://Stackoverflow.com/users/20037042",
"pm_score": 2,
"selected": false,
"text": "21967\n21968\n21969\n21970\n21971\n21972\n21973\n21974\n21975\n21976\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1016065/"
] |
74,378,340 | <p>I am new to Blazor server side app. I am currently working on creating web app for my client using Blazor Server side app.
I want to understand the good practice on using Web API in Blazor server side app.
I can access the data directly in Blazor Server side app using Entity Framework, but at the same time, there are APIs already written to access the data.</p>
<p>I am wondering, why should I not use those APIs instead of connecting EF in Blazor server side app.</p>
<p>Will using the EF to pull data be much faster then API ?</p>
<p>Which approach should I use for good coding practice ?</p>
<p>Thanks</p>
| [
{
"answer_id": 74379100,
"author": "Ibrahim Timimi",
"author_id": 8316900,
"author_profile": "https://Stackoverflow.com/users/8316900",
"pm_score": 0,
"selected": false,
"text": "web-assembly"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8616968/"
] |
74,378,373 | <p>Please refer to the Widget <code>Text("HERE")</code> and corresponding ScreenShot below.
When a keyboard appears from the bottom of device, the Widget <code>Text("HERE")</code> relatively moved to upper-side, hence I should care about overflow of whole widget size as well as size of user devices.</p>
<p>How can I locate this Widget absolutely, or should I always make all things (widget) <code>scrollable</code> to corresponds to any devices and also to avoid overflow problem ?</p>
<pre><code>Stack(
children:[
,//omit
const Align(
alignment: Alignment.bottomCenter,
child: Text("HERE"),
)
]
)
</code></pre>
<p><a href="https://i.stack.imgur.com/KRipU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KRipU.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74379100,
"author": "Ibrahim Timimi",
"author_id": 8316900,
"author_profile": "https://Stackoverflow.com/users/8316900",
"pm_score": 0,
"selected": false,
"text": "web-assembly"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6843543/"
] |
74,378,388 | <p>Here is my situation: I have two Datastore kind, I need to create a python query for all Data that don't are present in Kind B. In the sample those are: Data 3 and Data 4.</p>
<p>The constraint here is that i need to filter for elements in KindA which have a key that is different from specific KindB property.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Kind A</th>
<th>Kind B</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data 1</td>
<td>Data 1</td>
</tr>
<tr>
<td>Data 2</td>
<td>Data 2</td>
</tr>
<tr>
<td>Data 3</td>
<td></td>
</tr>
<tr>
<td>Data 4</td>
<td></td>
</tr>
<tr>
<td>Data 5</td>
<td>Data 5</td>
</tr>
</tbody>
</table>
</div>
<p>According to <a href="https://cloud.google.com/appengine/docs/legacy/standard/python/ndb/queries" rel="nofollow noreferrer">documentation</a>, I can create a query in this way:</p>
<pre><code>query = Account.query(Account.userid == 42)
</code></pre>
<p>I've tried this:</p>
<pre><code>myquery = KindA.query(KindA.key.id() != KindB.documentId)
</code></pre>
<p>But it throws:
<code>AttributeError: 'ModelKey' object has no attribute 'id'</code></p>
<p>I've tried following this stack overflow <a href="https://stackoverflow.com/a/32107978/15488129">question</a>:
but it seems infeasible because the number of element in kindB is dynamic, and I can't list them all.</p>
<p><em>Written in english my query would be: filter KindA elements keys that are NOT IN KindB documentId.</em></p>
<p>Could you help?</p>
| [
{
"answer_id": 74388581,
"author": "Girolamo",
"author_id": 15488129,
"author_profile": "https://Stackoverflow.com/users/15488129",
"pm_score": 0,
"selected": false,
"text": "list_of_id = []\nentries = KindB.query()\nfor request in entries:\n list_of_id.append(request.key.id())\n\nkeys = [ndb.Key(KindA, unique_id) for unique_id in list_of_id]\nobjs= ndb.get_multi(keys)\n"
},
{
"answer_id": 74398135,
"author": "NoCommandLine",
"author_id": 15211203,
"author_profile": "https://Stackoverflow.com/users/15211203",
"pm_score": 3,
"selected": true,
"text": "# keys_only=True means Return only the keys which is faster\nkindB_Ids = [ a.id() for a in KindB.query().fetch(keys_only=True) ]\n\n\nkindA_Ids = [ a.id() for a in KindA.query().fetch(keys_only=True) ]\n\n# This gives you rows in KindA whose ids are not in KindB\ndiff = [ ndb.Key(KindA, a) for a in KindA_Ids if a not in kindB_Ids]\n\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15488129/"
] |
74,378,404 | <p>This might be difficult to explain. But Im trying to write a redshift sql query where I have want the count of organizations that fall into different market buckets. There are 50 markets. For example company x can be only be found in 1 market and company y can be found in 3 markets. I want to preface that I have over 10,000 companies to fit into these buckets. So ideally it would be more like, hypothetically 500 companies are found in 3 markets or 7 companies are found in 50 markets.</p>
<p>The table would like</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Market Bucket</th>
<th>Org Count</th>
</tr>
</thead>
<tbody>
<tr>
<td>1 Markets</td>
<td>3</td>
</tr>
<tr>
<td>2 Markets</td>
<td>1</td>
</tr>
<tr>
<td>3 Markets</td>
<td>0</td>
</tr>
</tbody>
</table>
</div>
<p><code>select count(distinct case when enterprise_account = true and (market_name then organization_id end) as "1 Market" from organization_facts</code></p>
<p>I was trying to formulate the query from above but I got confused on how to effectively formulate the query</p>
<p>Organization Facts</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Market Name</th>
<th>Org ID</th>
<th>Org Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>New York</td>
<td>15683</td>
<td>Company x</td>
</tr>
<tr>
<td>Orlando</td>
<td>38478</td>
<td>Company y</td>
</tr>
<tr>
<td>Twin Cities</td>
<td>2738</td>
<td>Company z</td>
</tr>
<tr>
<td>Twin Cities</td>
<td>15683</td>
<td>Company x</td>
</tr>
<tr>
<td>Detroit</td>
<td>99</td>
<td>Company xy</td>
</tr>
</tbody>
</table>
</div> | [
{
"answer_id": 74388581,
"author": "Girolamo",
"author_id": 15488129,
"author_profile": "https://Stackoverflow.com/users/15488129",
"pm_score": 0,
"selected": false,
"text": "list_of_id = []\nentries = KindB.query()\nfor request in entries:\n list_of_id.append(request.key.id())\n\nkeys = [ndb.Key(KindA, unique_id) for unique_id in list_of_id]\nobjs= ndb.get_multi(keys)\n"
},
{
"answer_id": 74398135,
"author": "NoCommandLine",
"author_id": 15211203,
"author_profile": "https://Stackoverflow.com/users/15211203",
"pm_score": 3,
"selected": true,
"text": "# keys_only=True means Return only the keys which is faster\nkindB_Ids = [ a.id() for a in KindB.query().fetch(keys_only=True) ]\n\n\nkindA_Ids = [ a.id() for a in KindA.query().fetch(keys_only=True) ]\n\n# This gives you rows in KindA whose ids are not in KindB\ndiff = [ ndb.Key(KindA, a) for a in KindA_Ids if a not in kindB_Ids]\n\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18113224/"
] |
74,378,408 | <p>Say I have a library function <code>int foo( const T& )</code>
that can operate with some specific containers as argument:</p>
<pre><code>std::vector<A> c1;
std::list<B>() c2;
auto a1 = foo(c1); // ok
auto a2 = foo(c2); // ok too
std::map<int, float> c3;
auto a3 = foo( c3 ); // this must fail
</code></pre>
<p>First, I wrote a traits class defining the allowed containers:</p>
<pre><code>template <typename T> struct IsContainer : std::false_type { };
template <typename T,std::size_t N> struct IsContainer<std::array<T,N>> : std::true_type { };
template <typename... Ts> struct IsContainer<std::vector<Ts...>>: std::true_type { };
template <typename... Ts> struct IsContainer<std::list<Ts... >>: std::true_type { };
</code></pre>
<p>now, "Sfinae" the function:</p>
<pre><code>template<
typename U,
typename std::enable_if<IsContainer<U>::value, U>::type* = nullptr
>
auto foo( const U& data )
{
// ... call some other function
return bar(data);
}
</code></pre>
<p>Works fine.</p>
<p>side note: <code>bar()</code> is actually inside a private namespace and is also called from other code.
On the contrary, <code>foo()</code> is part of the API.</p>
<p>But now I want to change the behavior depending on the types inside the container
i.e. inside <code>foo()</code>:</p>
<ul>
<li><p>call <code>bar1(data)</code> if argument is <code>std::vector<A></code> or <code>std::list<A></code> and</p>
</li>
<li><p>call <code>bar2(data)</code> if argument is <code>std::vector<B></code> or <code>std::list<B></code></p>
</li>
</ul>
<p>So I have this:</p>
<pre><code>struct A {}; // dummy here, but concrete type in my case
struct B {};
template<
typename U,
typename std::enable_if<
( IsContainer<U>::value, U>::type* = nullptr && std::is_same<U::value_type,A> )
>
auto foo( const U& data )
{
// ... call some other function
return bar1(data);
}
template<
typename U,
typename std::enable_if<
( IsContainer<U>::value, U>::type* = nullptr && std::is_same<U::value_type,B> )
>
auto foo( const U& data )
{
// ... call some other function
return bar2(data);
}
</code></pre>
<p>With <code>bar1()</code> and <code>bar2()</code> (dummy) defined as:</p>
<pre><code>template<typename T>
int bar1( const T& t )
{
return 42;
}
template<typename T>
int bar2( const T& t )
{
return 43;
}
</code></pre>
<p>This works fine, as <a href="http://coliru.stacked-crooked.com/a/7573c1574169111d" rel="nofollow noreferrer">demonstrated here</a></p>
<p><strong>Now my real problem:</strong> the types A and B are actually templated by some underlying type:</p>
<pre><code>template<typename T>
struct A
{
T data;
}
template<typename T>
struct B
{
T data;
}
</code></pre>
<p>And I want to be able to build this:</p>
<pre><code>int main()
{
std::vector<A<int>> a;
std::list<B<float>> b;
std::cout << foo(a) << '\n'; // print 42
std::cout << foo(b) << '\n'; // print 43
}
</code></pre>
<p>My problem is: I don't know how to "extract" the contained type:
I tried this:</p>
<pre><code>template<
typename U,
typename F,
typename std::enable_if<
( IsContainer<U>::value && std::is_same<typename U::value_type,A<F>>::value ),U
>::type* = nullptr
>
auto foo( const U& data )
{
return bar1(data);
}
template<
typename U,
typename F,
typename std::enable_if<
( IsContainer<U>::value && std::is_same<typename U::value_type,B<F>>::value ), U
>::type* = nullptr
>
auto foo( const U& data )
{
return bar2(data);
}
</code></pre>
<p>But this fails to build:</p>
<pre><code>template argument deduction/substitution failed:
main.cpp:63:21: note: couldn't deduce template parameter 'F'
</code></pre>
<p>(see live <a href="http://coliru.stacked-crooked.com/a/d0d77749b29d23fd" rel="nofollow noreferrer">here</a> )</p>
<p>Q: How can I make this work?</p>
<p>Side note: please only C++14 (or 17) if possible, I would rather avoid C++20 at present.</p>
| [
{
"answer_id": 74388581,
"author": "Girolamo",
"author_id": 15488129,
"author_profile": "https://Stackoverflow.com/users/15488129",
"pm_score": 0,
"selected": false,
"text": "list_of_id = []\nentries = KindB.query()\nfor request in entries:\n list_of_id.append(request.key.id())\n\nkeys = [ndb.Key(KindA, unique_id) for unique_id in list_of_id]\nobjs= ndb.get_multi(keys)\n"
},
{
"answer_id": 74398135,
"author": "NoCommandLine",
"author_id": 15211203,
"author_profile": "https://Stackoverflow.com/users/15211203",
"pm_score": 3,
"selected": true,
"text": "# keys_only=True means Return only the keys which is faster\nkindB_Ids = [ a.id() for a in KindB.query().fetch(keys_only=True) ]\n\n\nkindA_Ids = [ a.id() for a in KindA.query().fetch(keys_only=True) ]\n\n# This gives you rows in KindA whose ids are not in KindB\ndiff = [ ndb.Key(KindA, a) for a in KindA_Ids if a not in kindB_Ids]\n\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/193789/"
] |
74,378,428 | <p>I have data organized as lines (no columns). Lines altern between ">name" and "data", such that:</p>
<pre><code>
>name1
textA
>name2
textB
>name3
textC
</code></pre>
<p>I want to remove lines with a given name and the associated data - e.g., remove the data for >name3, meaning that both the line >name3 and the textC line should be removed.</p>
<p>I am using:</p>
<p><code>awk 'BEGIN {RS = ">"; ORS = ""} !/name3/ {print">"; print $0}' FILE</code></p>
<p>However, the output is as following:</p>
<pre><code>
>>name1
textA
>name2
textB
</code></pre>
<p>I have tried several alternatives but I did not manage to get the first line right (e.g., either the ">" is doubled or completely missing).</p>
| [
{
"answer_id": 74388581,
"author": "Girolamo",
"author_id": 15488129,
"author_profile": "https://Stackoverflow.com/users/15488129",
"pm_score": 0,
"selected": false,
"text": "list_of_id = []\nentries = KindB.query()\nfor request in entries:\n list_of_id.append(request.key.id())\n\nkeys = [ndb.Key(KindA, unique_id) for unique_id in list_of_id]\nobjs= ndb.get_multi(keys)\n"
},
{
"answer_id": 74398135,
"author": "NoCommandLine",
"author_id": 15211203,
"author_profile": "https://Stackoverflow.com/users/15211203",
"pm_score": 3,
"selected": true,
"text": "# keys_only=True means Return only the keys which is faster\nkindB_Ids = [ a.id() for a in KindB.query().fetch(keys_only=True) ]\n\n\nkindA_Ids = [ a.id() for a in KindA.query().fetch(keys_only=True) ]\n\n# This gives you rows in KindA whose ids are not in KindB\ndiff = [ ndb.Key(KindA, a) for a in KindA_Ids if a not in kindB_Ids]\n\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20461033/"
] |
74,378,432 | <p>I want to find my local time zone and then return the time zone name (cet, est etc.) using Python and my location so that I can just find it without entering any additional information except for the location of my pc (which I want to find using GPS and not manually adding it)</p>
<pre><code>import say
import datetime
def timezone():
timezone = datetime.datetime.now()
timezonename = timezone.strftime("%Z")
timezoneoffset = timezone.strftime("%z")
say.praten(f"the timezone is {timezonename} which is {timezoneoffset} off UTC")
</code></pre>
<p>I used this but this doesn't return anything with the datetime import
the say command is from a different file for text to speech</p>
<p>everyone is revering me to this post : <a href="https://stackoverflow.com/questions/35057968/get-system-local-timezone-in-python">Get system local timezone in python</a>
but I tried this and I got the full name of the time zone (Europe Berlin) but I want the 3 letter name (cet in my case)</p>
| [
{
"answer_id": 74378522,
"author": "Kaitonee",
"author_id": 9805279,
"author_profile": "https://Stackoverflow.com/users/9805279",
"pm_score": 1,
"selected": false,
"text": "import time\nprint(time.tzname)\n"
},
{
"answer_id": 74379300,
"author": "FObersteiner",
"author_id": 10197418,
"author_profile": "https://Stackoverflow.com/users/10197418",
"pm_score": 0,
"selected": false,
"text": "from datetime import datetime\n\ndt_local = datetime.now().astimezone()\n\nprint(dt_local.isoformat(timespec=\"seconds\"))\nprint(dt_local.strftime(\"%Z\"))\n\n# on my machine:\n# 2022-11-09T18:50:13+01:00\n# CET\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15370351/"
] |
74,378,433 | <p>I'm trying to understand why I am getting this <code>TypeError</code> when instantiating my <code>deque</code>. I am solving the "Number of Islands" problem</p>
<pre><code>def bfs(r,c):
q = collections.deque((r,c))
while q:
r_curr, c_curr = q.popleft()
for dr, dc in dirs:
r_next, c_next = r_curr + dr, c_curr + dc
if is_valid(r_next, c_next):
visited.add((r_next, c_next))
q.append((r_next, c_next))
</code></pre>
<p>Gives me the below error:</p>
<pre><code>TypeError: cannot unpack non-iterable int object
r_curr, c_curr = q.popleft()
</code></pre>
<p>But the below works without error.</p>
<pre><code>def bfs(r,c):
q = collections.deque()
q.append((r,c))
while q:
r_curr, c_curr = q.popleft()
for dr, dc in dirs:
r_next, c_next = r_curr + dr, c_curr + dc
if is_valid(r_next, c_next):
visited.add((r_next, c_next))
q.append((r_next, c_next))
</code></pre>
<p>Why does the first method fail but the second method works?</p>
| [
{
"answer_id": 74378522,
"author": "Kaitonee",
"author_id": 9805279,
"author_profile": "https://Stackoverflow.com/users/9805279",
"pm_score": 1,
"selected": false,
"text": "import time\nprint(time.tzname)\n"
},
{
"answer_id": 74379300,
"author": "FObersteiner",
"author_id": 10197418,
"author_profile": "https://Stackoverflow.com/users/10197418",
"pm_score": 0,
"selected": false,
"text": "from datetime import datetime\n\ndt_local = datetime.now().astimezone()\n\nprint(dt_local.isoformat(timespec=\"seconds\"))\nprint(dt_local.strftime(\"%Z\"))\n\n# on my machine:\n# 2022-11-09T18:50:13+01:00\n# CET\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14224098/"
] |
74,378,463 | <p>I currently have some data in the form of a nested map like the following:</p>
<pre><code>Map<String, Map<String, List<Integer>>> data = // intializing the Map
// data = {group1={grades=[a,b,c], age=[x,y,z]}, group={....}} and so on
</code></pre>
<p>What I want to do is essentially remove grades and then reverse the map, so it would look something like:</p>
<pre><code>{x={group1}, y={group1, group3}, z={group2}, someAge={some list of groupN}}
</code></pre>
<p>I appreciate that the data may not make sense without context, but the problem remains the same. As it stands, I have a 3-nested for loops, but there must be a better way, since that would be very inefficient with a large dataset:</p>
<pre><code>Map <Integer, List<String>> someMap = new HashMap<>();
for (var entry : data.entrySet()) {
for (var info : entry.getValue().entrySet()) {
if (info.getKey().equals("age")) {
List ages = info.getValue();
for (var age : ages) {
// if age not in someMap, add age as key // e.g add x so someMap={x={},y={}}
someMap.get(age).add(entry.getKey()) //e.g {x={entry key},y={}}
}
}
}
}
</code></pre>
<p>Is there some kind of pre-processing I can do to remove grades which would cut the 2nd for loop in half at least, and remove the need to check if the key is 'age' each iteration.</p>
| [
{
"answer_id": 74378522,
"author": "Kaitonee",
"author_id": 9805279,
"author_profile": "https://Stackoverflow.com/users/9805279",
"pm_score": 1,
"selected": false,
"text": "import time\nprint(time.tzname)\n"
},
{
"answer_id": 74379300,
"author": "FObersteiner",
"author_id": 10197418,
"author_profile": "https://Stackoverflow.com/users/10197418",
"pm_score": 0,
"selected": false,
"text": "from datetime import datetime\n\ndt_local = datetime.now().astimezone()\n\nprint(dt_local.isoformat(timespec=\"seconds\"))\nprint(dt_local.strftime(\"%Z\"))\n\n# on my machine:\n# 2022-11-09T18:50:13+01:00\n# CET\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8815285/"
] |
74,378,466 | <p>I have multiple variables to pass in if, elif and else statement. Assuming 3 variables a, b, and c. Those are simply list that contains numbers. But I need to define if, elif and else statement for each probability of the variables.</p>
<p>For example:</p>
<ul>
<li>if one of the variables >0 do something with this variable but pass the others.</li>
</ul>
<p>Based on probability I know the all the possibilities and therefore I prepare the code based on these possibilities</p>
<pre><code>weeks =9
a=[1,0,1,1,1,0,0,0,1]
b=[1,0,0,1,0,1,1,0,1]
c=[1,0,0,0,1,0,1,1,1]
for i in range (weeks):
if i <= 0:
(print('this is hypo'))
else:
if(a[i] <= 0 and b[i] <= 0 and c[i] <= 0): # no prod 0
print(a[i],b[i],c[i],'no ne is working')
elif(a[i] > 0 and b[i] <= 0 and c[i] <= 0): # only first 1
print(a[i],b[i],c[i],'only a working')
elif(a[i] > 0 and b[i] > 0 and c[i] <= 0): #first and second 1-2
print(a[i],b[i],c[i],'a and b working')
elif(a[i] > 0 and b[i] <= 0 and c[i] > 0): # first and third 1-3
print(a[i],b[i],c[i], 'a and c working')
elif(a[i] <= 0 and b[i] > 0 and c[i] <= 0): # only second 2
print(a[i],b[i],c[i],'only b working')
elif(a[i]<= 0 and b[i] > 0 and c[i] > 0): #second and third 2-3
print(a[i],b[i],c[i],'b and c working')
elif(a[i] <= 0 and b[i] <= 0 and c[i] > 0): # only third 3
print(a[i],b[i],c[i],'only c working')
else: # all of are working 1-2-3
print (a[i],b[i],c[i], 'all wokring')
print('iteration number :',i)
</code></pre>
<p>What I'm trying to achieve is finding an efficient way to pass these possibilities in few statements. It is not a big issue to deal with 3 variables, but what happens if I want to pass 10 variables. Do I need to define each probability separately ?</p>
| [
{
"answer_id": 74378522,
"author": "Kaitonee",
"author_id": 9805279,
"author_profile": "https://Stackoverflow.com/users/9805279",
"pm_score": 1,
"selected": false,
"text": "import time\nprint(time.tzname)\n"
},
{
"answer_id": 74379300,
"author": "FObersteiner",
"author_id": 10197418,
"author_profile": "https://Stackoverflow.com/users/10197418",
"pm_score": 0,
"selected": false,
"text": "from datetime import datetime\n\ndt_local = datetime.now().astimezone()\n\nprint(dt_local.isoformat(timespec=\"seconds\"))\nprint(dt_local.strftime(\"%Z\"))\n\n# on my machine:\n# 2022-11-09T18:50:13+01:00\n# CET\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15600857/"
] |
74,378,488 | <p>I've this Twitter bot that tweets out info on stock trades, whenever I run the bot from VS Code it works fine and tweets the values I want. Now I need to host it on Heroku but when I do and the script executes the values that are tweeted end up as <code>undefined</code>, <a href="https://ibb.co/j8rSY1C" rel="nofollow noreferrer">see image</a>. This is happening to <code>priceModule</code> and <code>nameModule</code> and I don't understand why, its working perfectly locally, Is there a fix for this?</p>
<p><strong>Index.js</strong></p>
<pre><code>// MODULES
const rwClient = require("./TwitterClient.js");
const cronjob = require("cron").CronJob;
const priceModule = require("./price");
const nameModule = require("./name");
(async () => {
// Async function that creates the Tweet
const tweet = async () => {
try {
await rwClient.v2.tweet(
"Name: " + await nameModule() + '\n' +
"Amount Purchased: " + await priceModule() + '\n'
);
} catch (error) {
console.error(error)
}
}
console.log(
"Name: " + await nameModule() + '\n' +
"Amount Purchased: " + await priceModule() + '\n'
);
tweet();
console.log("Tweet executed");
// CronJob, executes every 6 hours
const job = new cronjob("0 */4 * * *", () => {
tweet();
console.log("Next tweet executed");
});
job.start();
})();
</code></pre>
<p><strong>nameModule.js</strong></p>
<pre><code>// MODULES
const puppeteer = require("puppeteer");
// Url where we get and scrape the data from
const url = "https://www.sec.gov/edgar/search/#/dateRange=30d&category=custom&forms=4";
let browser;
module.exports = () => (async () => {
browser = await puppeteer.launch();
const [page] = await browser.pages();
const $ = (...args) => page.waitForSelector(...args);
const text = async (...args) =>
(await $(...args)).evaluate(el => el.textContent.trim());
await page.goto(url, {waitUntil: "domcontentloaded"});
await page.reload({waitUntil: "domcontentloaded"});
const info = {
secTableEN: await text(".table td.entity-name"),
secTableFiled: await text(".table td.filed"),
secTableLink: await text(".table td.filetype"),
};
return info.secTableEN;
})()
.catch(err => console.error(err))
.finally(() => browser?.close());
</code></pre>
<p><strong>priceModule</strong></p>
<pre><code>// MODULES
const puppeteer = require("puppeteer");
// Url where we get and scrape the data from
const url = "https://www.sec.gov/edgar/search/#/dateRange=30d&category=custom&forms=4";
let browser;
module.exports = () => (async () => {
browser = await puppeteer.launch();
const [page] = await browser.pages();
const ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36";
await page.setUserAgent(ua);
await page.goto(url, {waitUntil: "domcontentloaded", timeout: 0});
await page.reload({waitUntil: "domcontentloaded"});
const responseP = page.waitForResponse(res =>
res.status() === 200 && res.url().endsWith(".xml")
);
const a = await page.waitForSelector(".filetype .preview-file");
await a.click();
const html = await (await responseP).text();
await page.evaluate(html => document.body.outerHTML = html, html);
const price = await page.$$eval(".FormText", els =>
els.find(e => e.textContent.trim() === "$")
.parentNode
.textContent
.trim()
);
return price;
})()
.catch(err => console.error(err))
.finally(() => browser?.close());
</code></pre>
<p><strong>Activity log from Heroku</strong></p>
<pre><code>2022-11-15T12:44:00.060455+00:00 app[worker.1]: at ChromeLauncher.executablePath (/app/node_modules/puppeteer-core/lib/cjs/puppeteer/node/ChromeLauncher.js:166:25)
2022-11-15T12:44:00.060455+00:00 app[worker.1]: at ChromeLauncher.launch (/app/node_modules/puppeteer-core/lib/cjs/puppeteer/node/ChromeLauncher.js:70:37)
2022-11-15T12:44:00.060455+00:00 app[worker.1]: at async /app/numShares.js:9:15
2022-11-15T12:44:00.060456+00:00 app[worker.1]: at async CJ.<anonymous> (/app/index.js:39:46)
2022-11-15T12:44:00.060711+00:00 app[worker.1]: Error: Could not find Chromium (rev. 1056772). This can occur if either
2022-11-15T12:44:00.060711+00:00 app[worker.1]: 1. you did not perform an installation before running the script (e.g. `npm install`) or
2022-11-15T12:44:00.060711+00:00 app[worker.1]: 2. your cache path is incorrectly configured (which is: /app/.cache/puppeteer).
2022-11-15T12:44:00.060712+00:00 app[worker.1]: For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides/configuration.
2022-11-15T12:44:00.060712+00:00 app[worker.1]: at ChromeLauncher.resolveExecutablePath (/app/node_modules/puppeteer-core/lib/cjs/puppeteer/node/ProductLauncher.js:120:27)
2022-11-15T12:44:00.060712+00:00 app[worker.1]: at ChromeLauncher.executablePath (/app/node_modules/puppeteer-core/lib/cjs/puppeteer/node/ChromeLauncher.js:166:25)
2022-11-15T12:44:00.060713+00:00 app[worker.1]: at ChromeLauncher.launch (/app/node_modules/puppeteer-core/lib/cjs/puppeteer/node/ChromeLauncher.js:70:37)
2022-11-15T12:44:00.060713+00:00 app[worker.1]: at async /app/price.js:9:15
2022-11-15T12:44:00.060713+00:00 app[worker.1]: at async CJ.<anonymous> (/app/index.js:39:66)
2022-11-15T12:44:00.060953+00:00 app[worker.1]: Error: Could not find Chromium (rev. 1056772). This can occur if either
2022-11-15T12:44:00.060954+00:00 app[worker.1]: 1. you did not perform an installation before running the script (e.g. `npm install`) or
2022-11-15T12:44:00.060954+00:00 app[worker.1]: 2. your cache path is incorrectly configured (which is: /app/.cache/puppeteer).
2022-11-15T12:44:00.060954+00:00 app[worker.1]: For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides/configuration.
2022-11-15T12:44:00.060954+00:00 app[worker.1]: at ChromeLauncher.resolveExecutablePath (/app/node_modules/puppeteer-core/lib/cjs/puppeteer/node/ProductLauncher.js:120:27)
2022-11-15T12:44:00.060955+00:00 app[worker.1]: at ChromeLauncher.executablePath (/app/node_modules/puppeteer-core/lib/cjs/puppeteer/node/ChromeLauncher.js:166:25)
2022-11-15T12:44:00.060955+00:00 app[worker.1]: at ChromeLauncher.launch (/app/node_modules/puppeteer-core/lib/cjs/puppeteer/node/ChromeLauncher.js:70:37)
2022-11-15T12:44:00.060955+00:00 app[worker.1]: at async /app/stock.js:9:15
2022-11-15T12:44:00.060955+00:00 app[worker.1]: at async CJ.<anonymous> (/app/index.js:40:30)
2022-11-15T12:44:00.061194+00:00 app[worker.1]: Error: Could not find Chromium (rev. 1056772). This can occur if either
2022-11-15T12:44:00.061195+00:00 app[worker.1]: 1. you did not perform an installation before running the script (e.g. `npm install`) or
2022-11-15T12:44:00.061195+00:00 app[worker.1]: 2. your cache path is incorrectly configured (which is: /app/.cache/puppeteer).
2022-11-15T12:44:00.061195+00:00 app[worker.1]: For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides/configuration.
2022-11-15T12:44:00.061195+00:00 app[worker.1]: at ChromeLauncher.resolveExecutablePath (/app/node_modules/puppeteer-core/lib/cjs/puppeteer/node/ProductLauncher.js:120:27)
2022-11-15T12:44:00.061196+00:00 app[worker.1]: at ChromeLauncher.executablePath (/app/node_modules/puppeteer-core/lib/cjs/puppeteer/node/ChromeLauncher.js:166:25)
2022-11-15T12:44:00.061196+00:00 app[worker.1]: at ChromeLauncher.launch (/app/node_modules/puppeteer-core/lib/cjs/puppeteer/node/ChromeLauncher.js:70:37)
2022-11-15T12:44:00.061196+00:00 app[worker.1]: at async /app/date.js:9:13
2022-11-15T12:44:00.061197+00:00 app[worker.1]: at async CJ.<anonymous> (/app/index.js:41:28)
2022-11-15T12:44:00.061227+00:00 app[worker.1]: New insider trade! (form 4 filed)
2022-11-15T12:44:00.061227+00:00 app[worker.1]:
2022-11-15T12:44:00.061228+00:00 app[worker.1]: undefined bought undefined shares at $undefined
2022-11-15T12:44:00.061228+00:00 app[worker.1]:
2022-11-15T12:44:00.061228+00:00 app[worker.1]: Amount Purchased: $NaN
2022-11-15T12:44:00.061229+00:00 app[worker.1]: Stock: undefined
2022-11-15T12:44:00.061229+00:00 app[worker.1]: Date: undefined
2022-11-15T12:44:00.061229+00:00 app[worker.1]:
2022-11-15T12:44:01.000000+00:00 app[api]: Build started by user jojoamankwa@gmail.com
2022-11-15T12:44:38.942638+00:00 app[api]: Release v8 created by user jojoamankwa@gmail.com
2022-11-15T12:44:38.942638+00:00 app[api]: Deploy 2db65223 by user jojoamankwa@gmail.com
2022-11-15T12:44:40.624181+00:00 heroku[worker.1]: Restarting
2022-11-15T12:44:40.626042+00:00 heroku[worker.1]: State changed from up to starting
2022-11-15T12:44:39.000000+00:00 app[api]: Build succeeded
2022-11-15T12:44:41.596325+00:00 heroku[worker.1]: Stopping all processes with SIGTERM
2022-11-15T12:44:41.950594+00:00 heroku[worker.1]: Process exited with status 143
2022-11-15T12:44:44.285628+00:00 heroku[worker.1]: Starting process with command `node index.js`
2022-11-15T12:44:45.072715+00:00 heroku[worker.1]: State changed from starting to up
2022-11-15T12:44:53.176410+00:00 heroku[worker.1]: Restarting
2022-11-15T12:44:53.191437+00:00 heroku[worker.1]: State changed from up to starting
2022-11-15T12:44:54.322495+00:00 heroku[worker.1]: Stopping all processes with SIGTERM
2022-11-15T12:44:54.589561+00:00 heroku[worker.1]: Process exited with status 143
2022-11-15T12:44:55.711588+00:00 heroku[worker.1]: Starting process with command `node index.js`
2022-11-15T12:44:56.492554+00:00 heroku[worker.1]: State changed from starting to up
</code></pre>
| [
{
"answer_id": 74378522,
"author": "Kaitonee",
"author_id": 9805279,
"author_profile": "https://Stackoverflow.com/users/9805279",
"pm_score": 1,
"selected": false,
"text": "import time\nprint(time.tzname)\n"
},
{
"answer_id": 74379300,
"author": "FObersteiner",
"author_id": 10197418,
"author_profile": "https://Stackoverflow.com/users/10197418",
"pm_score": 0,
"selected": false,
"text": "from datetime import datetime\n\ndt_local = datetime.now().astimezone()\n\nprint(dt_local.isoformat(timespec=\"seconds\"))\nprint(dt_local.strftime(\"%Z\"))\n\n# on my machine:\n# 2022-11-09T18:50:13+01:00\n# CET\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17164833/"
] |
74,378,490 | <p>I currently have the function below which works fine:</p>
<pre><code>export const optionsFunc: Function = (token: string) => {
const options = {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
}
};
return options;
};
</code></pre>
<p>Now I want to modify it to add <code>params</code> to the <code>options</code> variable;
<code>params</code> needs to be a key/value and not mandatory variable;</p>
<p>How can I modify the <code>options</code> variable and the function parameter <code>params</code> to do that?
I'm looking for something like this in the end:</p>
<pre><code>export const optionsFunc: Function = (token: string, params: any) => {
const options = {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
};
if (params) {
const filteredParams = Object.entries(params).reduce(
(a, [k, v]) => (v == null || v === 'null' ? a : (a[k] = v, a)), {}
);
options.params = filteredParams;
}
return options;
};
</code></pre>
| [
{
"answer_id": 74378522,
"author": "Kaitonee",
"author_id": 9805279,
"author_profile": "https://Stackoverflow.com/users/9805279",
"pm_score": 1,
"selected": false,
"text": "import time\nprint(time.tzname)\n"
},
{
"answer_id": 74379300,
"author": "FObersteiner",
"author_id": 10197418,
"author_profile": "https://Stackoverflow.com/users/10197418",
"pm_score": 0,
"selected": false,
"text": "from datetime import datetime\n\ndt_local = datetime.now().astimezone()\n\nprint(dt_local.isoformat(timespec=\"seconds\"))\nprint(dt_local.strftime(\"%Z\"))\n\n# on my machine:\n# 2022-11-09T18:50:13+01:00\n# CET\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19843880/"
] |
74,378,495 | <p>I have a dataframe with several rows and I need to assign a number (new column) according to the values of the other columns:</p>
<ul>
<li>If all values in the different columns are the same the new value would be 5,</li>
<li>if at least 4 values are the same it would be 4,</li>
<li>if at least 3 values are the same, 3</li>
<li>and so on until all are different values and the new value would be 0.</li>
</ul>
<pre><code> p1 p2 p3 p4 p5
0 1 1 1 1 1
1 2 3 2 2 2
2 2 2 3 4 1
3 4 4 1 1 1
4 2 1 2 3 5
5 1 2 3 4 5
</code></pre>
<p>Output</p>
<pre><code> p1 p2 p3 p4 p5 new
0 1 1 1 1 1 5
1 2 3 2 2 2 4
2 2 2 3 4 1 2
3 4 4 1 1 1 3
4 2 1 2 3 5 2
5 1 2 3 4 5 0
</code></pre>
<p>For the first example where all are the same, I used np.where and it works:</p>
<pre><code>df['new'] = np.where((df['p1'] == df['p2']) & (df['p1'] == df['p3']) & (df['p1'] == df['p4']) & (df['p1'] == df['p5']), 5, 0)
</code></pre>
| [
{
"answer_id": 74378522,
"author": "Kaitonee",
"author_id": 9805279,
"author_profile": "https://Stackoverflow.com/users/9805279",
"pm_score": 1,
"selected": false,
"text": "import time\nprint(time.tzname)\n"
},
{
"answer_id": 74379300,
"author": "FObersteiner",
"author_id": 10197418,
"author_profile": "https://Stackoverflow.com/users/10197418",
"pm_score": 0,
"selected": false,
"text": "from datetime import datetime\n\ndt_local = datetime.now().astimezone()\n\nprint(dt_local.isoformat(timespec=\"seconds\"))\nprint(dt_local.strftime(\"%Z\"))\n\n# on my machine:\n# 2022-11-09T18:50:13+01:00\n# CET\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20062020/"
] |
74,378,534 | <p>I have a pub/sub topic in project A. I would now like to stream messages from that topic into a dataflow pipeline running in a different project B. I have followed the example at <a href="https://cloud.google.com/pubsub/docs/stream-messages-dataflow" rel="nofollow noreferrer">https://cloud.google.com/pubsub/docs/stream-messages-dataflow</a> and everything works when the topic is in the same project as the dataflow pipeline. However, when trying to stream messages from a topic in a different project I get the following permissions error:</p>
<pre><code>INFO:apache_beam.runners.dataflow.dataflow_runner:2022-11-09T16:34:40.349Z: JOB_MESSAGE_ERROR: Workflow failed. Causes: Check if topic projects/XXXXXXX/topics/test-topic exists failed with error: User not authorized to perform this action.
</code></pre>
<p>The service account which runs the pipeline has the Pub/Sub Admin role in both projects. I even tried making it Owner in project A (where the topic lives), but no success. I always get the same error.</p>
| [
{
"answer_id": 74387292,
"author": "Mazlum Tosun",
"author_id": 9261558,
"author_profile": "https://Stackoverflow.com/users/9261558",
"pm_score": 0,
"selected": false,
"text": "Dataflow"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1290055/"
] |
74,378,545 | <p>If I have below table</p>
<pre><code>|a | id | year|m2000 | m2001 | m2002 | .... | m2015|
|"hello"| 1 | 2001 | 0 | 0 | 0 | ... | 0 |
|"hello"| 1 | 2015 | 0 | 0 | 0 | ... | 0 |
|"hello"| 2 | 2002 | 0 | 0 | 0 | ... | 0 |
|"hello"| 2 | 2015 | 0 | 0 | 0 | ... | 0 |
</code></pre>
<p>How to I change the dataframe so it checks the year column in each row and changes the above example m2001 and m2015 to 1 and as id is 1 in both, the new table will look like below</p>
<pre><code>|a | id |m2000 | m2001 | m2002 | .... | m2015|
|"hello"| 1 | 0 | 1 | 0 | ... | 1 |
|"hello"| 2 | 0 | 0 | 1 | ... | 1 |
</code></pre>
| [
{
"answer_id": 74382789,
"author": "wwnde",
"author_id": 8986975,
"author_profile": "https://Stackoverflow.com/users/8986975",
"pm_score": 2,
"selected": true,
"text": "new = df.select('a','id','year',*[when((size(F.array_distinct(F.array(F.lit(col('year').astype('string')), lit(x[1:])))))==1,1).otherwise(0).alias(x) for x in df.columns if x not in ['a','id','year']])\n\nnew.groupBy('a','id').agg(*[max(x).alias(x) for x in new.columns if x not in ['a','id','year']] ).show()\n"
},
{
"answer_id": 74399723,
"author": "Azhar Khan",
"author_id": 2847330,
"author_profile": "https://Stackoverflow.com/users/2847330",
"pm_score": 0,
"selected": false,
"text": "df = spark.createDataFrame(data=[ [\"hello\", 1, 2001], [\"hello\", 1, 2015], [\"hello\", 2, 2002], [\"hello\", 2, 2015] ], schema=[\"a\", \"id\", \"year\"])\n\nstart = 2000\nend = 2015\n\ndf = df.withColumn(\"myear\", F.concat(F.lit(\"m\"), \"year\"))\ndf = df.groupBy(\"a\",\"id\").pivot(\"myear\").agg((F.count(\"myear\")>0).cast(\"integer\")).drop(\"myear\")\ndf = df.fillna({c:0 for c in df.columns if c not in [\"a\", \"id\", \"year\"]})\ndf = df.select([\"*\"] + [F.lit(0).alias(f\"m{i}\") for i in range(start,end+1)])\n\n[Out]:\n+-----+---+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+\n| a| id|m2001|m2002|m2015|m2000|m2001|m2002|m2003|m2004|m2005|m2006|m2007|m2008|m2009|m2010|m2011|m2012|m2013|m2014|m2015|\n+-----+---+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+\n|hello| 1| 1| 0| 1| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0|\n|hello| 2| 0| 1| 1| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0|\n+-----+---+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9390633/"
] |
74,378,551 | <p>I have an input field and a button. The button should be enabled on the following simple scenarios:</p>
<ul>
<li>Input length is equal to 10, or</li>
<li>Input length is greater than 15 (should be disabled for 11 to 14).</li>
</ul>
<p>I tried <code>!str.length = 10 || !str.length >= 15</code>, but these conditions fail, as there is a conflict between both cases. I know I can check whether the length is not equal to 11, 12, 13, or 14, but that doesn't look good. Any better solution will be appreciated.</p>
| [
{
"answer_id": 74378602,
"author": "Lima",
"author_id": 17258654,
"author_profile": "https://Stackoverflow.com/users/17258654",
"pm_score": 0,
"selected": false,
"text": "!(str.length == 10 || str.length > 15)\n"
},
{
"answer_id": 74378646,
"author": "Robert Bradley",
"author_id": 20206840,
"author_profile": "https://Stackoverflow.com/users/20206840",
"pm_score": 3,
"selected": true,
"text": "="
},
{
"answer_id": 74380212,
"author": "Peter Seliger",
"author_id": 2627243,
"author_profile": "https://Stackoverflow.com/users/2627243",
"pm_score": 0,
"selected": false,
"text": "(str.length > 15 || str.length === 10)"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4340444/"
] |
74,378,553 | <p><a href="https://stackoverflow.com/questions/6259515/how-can-i-split-a-string-into-segments-of-n-characters">How can I split a string into segments of n characters?</a> is similar but not exactly what we are trying to achieve:</p>
<pre><code>// let splitSentence = (sentence, nChar) => {} // creating this function
let sentence = 'the quick cucumber fox jumps over the lazy dog.'
splitSentence(sentence, 15)
// output we are trying to get
// ['the quick cucumber', 'fox jumps over', 'the lazy dog.']
</code></pre>
<p>We cannot string split only on spaces, since multiple words are needed in each array element, not just a single word. The process, for <code>nChar == 15</code>, 15 letters are counted into the string, which gets to <code>the quick cucum</code>. The function should finish the word and add <code>the quick cucumber</code> into the output array as first element, then continue counting from the remainder of the sentence, starting at the next word <code>fox</code>, and repeat this process. Not sure if <code>.match()</code> with start and end indexes works for our problem like it does for the SO post linked above.</p>
<p>Putting this logic into splitSentence(). So far we have:</p>
<pre><code>let splitSentence = (sentence, nChar) => {
let output = [];
let i = 0;
while (i < sentence.length) {
let partOfSentence = sentence.slice(i, i + 15);
output.push(partOfSentence)
i = i + 15
}
return output;
}
</code></pre>
<p>However, getting <code>['the quick cucum', 'ber fox jumps o', 'ver the lazy do', 'g.']</code>, which is not what is needed. Not sure how to keep the entire word together in the slice when we loop over the string.</p>
| [
{
"answer_id": 74378784,
"author": "Mushroomator",
"author_id": 17487348,
"author_profile": "https://Stackoverflow.com/users/17487348",
"pm_score": 1,
"selected": false,
"text": "nChar"
},
{
"answer_id": 74381456,
"author": "Cesar Gomez",
"author_id": 19044212,
"author_profile": "https://Stackoverflow.com/users/19044212",
"pm_score": 0,
"selected": false,
"text": "let sentence = 'the quick cucumber fox jumps over the lazy dog.';\nlet output = [];\nconst limit = 15;\n\nconst check = (sentence, nchar) => {\n let tempSentence = sentence;\n if (sentence[nchar] != ' ') {\n nchar = nchar + 1;\n check(sentence, nchar);\n} else {\n output.push(sentence.substring(0, nchar).trim());\n tempSentence = sentence.substring(nchar, sentence.length);\n\n nchar = limit;\n if (tempSentence.length < nchar) {\n output.push(tempSentence.trim());\n return;\n }\n check(tempSentence, limit);\n}\n\ncheck(sentence, limit);\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5573294/"
] |
74,378,562 | <p>I'm new to Web Development. I'm learning <code>JavaScript</code> now(<code>JQuery</code>) and I chose Simple Chat as a project to get started.
Unfortunately, I can't figure out how to prevent the page from refreshing after a message is sent.</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<title>Chat</title>
</head>
<body>
<h1>Chat room</h1>
<div id="status"></div>
<form id="send" class="ajax" action="action.php" method="POST">
<label for="fname">Type your message</label>
<input type="text" id="fname" name="myMessage">
<input id="upload" type="submit" name="myButton"value="Submit" />
</form>
<div id="result"></div>
<script>
$(document).ready(function () {
$("form").submit(function (event) {
var formData = {
name: $("#fname").val(),
};
var posting = $.post(url, {
name: $('#fname').val(),
});
/* So far, just listing whether the Form has managed to prevent its classic sending */
posting.done(function(data) {
$('#result').text('success');
});
$.ajax({
type: "POST",
url: "process.php",
data: formData,
dataType: "json",
encode: true,
}).done(function (data) {
console.log(data);
});
event.preventDefault();
});
});
</script>
</body>
</html>
</code></pre>
<p><strong>PHP:</strong></p>
<pre><code><?php
$path = 'messages.txt';
if (isset($_POST['myButton']) ) {
$fh = fopen($path,"a");
$string = $_POST['myMessage' ];
fwrite($fh,$string . PHP_EOL);
fclose($fh);
}
?>
</code></pre>
<p>I have created a text file <code>messages.txt</code>, where I want to save newly created messages using Ajax.
I would like the newly added message to be displayed on the page below the chat( in the <code>div</code> with <code>id #result</code>)</p>
| [
{
"answer_id": 74378784,
"author": "Mushroomator",
"author_id": 17487348,
"author_profile": "https://Stackoverflow.com/users/17487348",
"pm_score": 1,
"selected": false,
"text": "nChar"
},
{
"answer_id": 74381456,
"author": "Cesar Gomez",
"author_id": 19044212,
"author_profile": "https://Stackoverflow.com/users/19044212",
"pm_score": 0,
"selected": false,
"text": "let sentence = 'the quick cucumber fox jumps over the lazy dog.';\nlet output = [];\nconst limit = 15;\n\nconst check = (sentence, nchar) => {\n let tempSentence = sentence;\n if (sentence[nchar] != ' ') {\n nchar = nchar + 1;\n check(sentence, nchar);\n} else {\n output.push(sentence.substring(0, nchar).trim());\n tempSentence = sentence.substring(nchar, sentence.length);\n\n nchar = limit;\n if (tempSentence.length < nchar) {\n output.push(tempSentence.trim());\n return;\n }\n check(tempSentence, limit);\n}\n\ncheck(sentence, limit);\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19819759/"
] |
74,378,569 | <p>I have a parent element with 2 absolutely positioned children inside. I want one of the children's overflow to be visible and the other's overflow to be hidden. Like so:</p>
<p><a href="https://i.stack.imgur.com/R8Zzc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/R8Zzc.png" alt="What I want" /></a></p>
<p>Adding <code>overflow: 'hidden</code> to the parent hides the overflow of both the coin image and the 'most popular' sash but I want the coin image overflow to be visible.</p>
<pre><code>container: {
width: 155,
height: 145,
backgroundColor: Colours.white,
borderRadius: 10,
borderColor: Colours.borderTwo,
borderWidth: 1,
alignItems: 'center',
justifyContent: 'flex-end',
margin: 10,
marginBottom: 25,
paddingBottom: 10,
overflow: 'hidden',
},
mostPopularSash: {
position: 'absolute',
top: 2,
right: -30,
backgroundColor: Colours.yellow,
width: 100,
height: 40,
alignItems: 'center',
justifyContent: 'center',
transform: [{rotate: '40deg'}],
},
imageContainer: {
position: 'absolute',
top: -22,
width: 52,
height: 52,
borderRadius: 100,
backgroundColor: Colours.white,
borderColor: Colours.pageColour,
borderWidth: 1,
justifyContent: 'center',
alignItems: 'center',
shadowColor: '#171717',
shadowOffset: {width: 0, height: 3},
shadowOpacity: 0.2,
shadowRadius: 2,
elevation: 5,
},
image: {
width: 40,
height: 40,
},
</code></pre>
<p><a href="https://i.stack.imgur.com/7rL9w.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7rL9w.png" alt="What happens with above css" /></a></p>
<p>I've tried adding <code>zIndex: 2</code> to the image container and then <code>zIndex: 1</code> to the parents parent but it didn't work..</p>
<p>Can't find much online to solve this problem as most queries related to 'overflow' are requesting the opposite effect.</p>
<p>Any help would be much appreciated!</p>
| [
{
"answer_id": 74378784,
"author": "Mushroomator",
"author_id": 17487348,
"author_profile": "https://Stackoverflow.com/users/17487348",
"pm_score": 1,
"selected": false,
"text": "nChar"
},
{
"answer_id": 74381456,
"author": "Cesar Gomez",
"author_id": 19044212,
"author_profile": "https://Stackoverflow.com/users/19044212",
"pm_score": 0,
"selected": false,
"text": "let sentence = 'the quick cucumber fox jumps over the lazy dog.';\nlet output = [];\nconst limit = 15;\n\nconst check = (sentence, nchar) => {\n let tempSentence = sentence;\n if (sentence[nchar] != ' ') {\n nchar = nchar + 1;\n check(sentence, nchar);\n} else {\n output.push(sentence.substring(0, nchar).trim());\n tempSentence = sentence.substring(nchar, sentence.length);\n\n nchar = limit;\n if (tempSentence.length < nchar) {\n output.push(tempSentence.trim());\n return;\n }\n check(tempSentence, limit);\n}\n\ncheck(sentence, limit);\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13740590/"
] |
74,378,581 | <p>For Example, I am using the following code.</p>
<pre><code>@app.route('/test', methods=['GET', 'POST'])
def test():
if request.method == 'POST':
test = request.form['test']
print(test)
print('\nprinted')
</code></pre>
<p>If I send the post request with a value containing newline '\n' the print method will not print the content with the new line but printing directly like this "print('\nprinted')" will print the content with a new line.</p>
<p>Example: Sending data.</p>
<p>Request:</p>
<pre><code>curl http://127.0.0.1:9090/test -XPOST -d "test=\nhello"
</code></pre>
<p>Response:</p>
<pre><code> * Running on all addresses (0.0.0.0)
* Running on http://127.0.0.1:9090
Press CTRL+C to quit
\nhello
printed
</code></pre>
<p>Is there any way to pass the data containing the newline and the result containing the actual newline?</p>
<p>Updated:</p>
<pre><code>test = request.form['test']
print(test)
</code></pre>
<p>The desired output should look like this for the above code.</p>
<p>Input:
<code>curl -XPOST -d 'test=\nhello' http://127.0.0.1:5000</code></p>
<p>Output:</p>
<pre><code>
hello
</code></pre>
<p>The hello should be printed after a newline.</p>
| [
{
"answer_id": 74378784,
"author": "Mushroomator",
"author_id": 17487348,
"author_profile": "https://Stackoverflow.com/users/17487348",
"pm_score": 1,
"selected": false,
"text": "nChar"
},
{
"answer_id": 74381456,
"author": "Cesar Gomez",
"author_id": 19044212,
"author_profile": "https://Stackoverflow.com/users/19044212",
"pm_score": 0,
"selected": false,
"text": "let sentence = 'the quick cucumber fox jumps over the lazy dog.';\nlet output = [];\nconst limit = 15;\n\nconst check = (sentence, nchar) => {\n let tempSentence = sentence;\n if (sentence[nchar] != ' ') {\n nchar = nchar + 1;\n check(sentence, nchar);\n} else {\n output.push(sentence.substring(0, nchar).trim());\n tempSentence = sentence.substring(nchar, sentence.length);\n\n nchar = limit;\n if (tempSentence.length < nchar) {\n output.push(tempSentence.trim());\n return;\n }\n check(tempSentence, limit);\n}\n\ncheck(sentence, limit);\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13187206/"
] |
74,378,584 | <p>I was wondering if there was a possible way to update data of each elements in the list</p>
<p>This is my initial list,</p>
<pre><code>var list1 = ['image1.png', 'image2.png', 'image3.png']
</code></pre>
<p>I want the final list in such a way that I could update the all the elements in the list like, (just add a string at the beginning of the elements)</p>
<pre><code>var list1 = ['bucket/image1.png', 'bucket/image2.png', 'bucket/image3.png]
</code></pre>
| [
{
"answer_id": 74378633,
"author": "Ruble",
"author_id": 17991131,
"author_profile": "https://Stackoverflow.com/users/17991131",
"pm_score": 3,
"selected": true,
"text": "List result = list1.map((e) => 'bucket/$e').toList();\n"
},
{
"answer_id": 74379368,
"author": "Duck Programmer",
"author_id": 12858184,
"author_profile": "https://Stackoverflow.com/users/12858184",
"pm_score": 0,
"selected": false,
"text": "var list1 = ['image1.png', 'image2.png', 'image3.png'];\nlist1 = list1.map((item) => 'bucket/$item').toList();\n"
},
{
"answer_id": 74379452,
"author": "jamesdlin",
"author_id": 179715,
"author_profile": "https://Stackoverflow.com/users/179715",
"pm_score": 0,
"selected": false,
"text": "List"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10539761/"
] |
74,378,585 | <p>I have a <em>large</em> list of .txt files that I need to have a macro that does the following:</p>
<ol>
<li>Open Files</li>
<li>Delimit the file based on "|"</li>
<li>Select all then filter</li>
<li>Sort on a specific header</li>
</ol>
<p>Steps 3 and 4 are easy... If these files weren't all .txt with | delimiters, I know how to open multiple files and then filter/sort, the issue I run into is step 2.</p>
<p>Code so far:</p>
<pre><code>Option Explicit
Dim theDir As String, wk As Workbook, numFiles As Integer, s As String, r As Range
Const ext = ".txt"
Sub LoopThroughFiles()
Dim xFd As FileDialog
Dim xFdItem As Variant
Dim xFileName As String
theDir = ThisWorkbook.Path
s = Dir(theDir & "\*" & ext)
Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
If xFd.Show = -1 Then
xFdItem = xFd.SelectedItems(1) & Application.PathSeparator
xFileName = Dir(xFdItem & "*.txt*")
Do While xFileName <> ""
With Workbooks.Open(xFdItem & xFileName)
'your code here
Set r = Range(Range("A1"), Range("A1").End(xlDown))
r.TextToColumns Destination:=r, DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=True, Space:=False, Other:=True, OtherChar:="|", _
FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), _
Array(7, 1), Array(8, 1), Array(9, 1), Array(10, 1), Array(11, 1), Array(12, 1), Array(13, 1 _
), Array(14, 1), Array(15, 1), Array(16, 1), Array(17, 1), Array(18, 1), Array(19, 1), Array _
(20, 1), Array(21, 1), Array(22, 1), Array(23, 1), Array(24, 1), Array(25, 1), Array(26, 1), _
Array(27, 1), Array(28, 1), Array(29, 1), Array(30, 1), Array(31, 1), Array(32, 1), Array( _
33, 1), Array(34, 1), Array(35, 1), Array(36, 1), Array(37, 1), Array(38, 1), Array(39, 1), _
Array(40, 1), Array(41, 1), Array(42, 1), Array(43, 1), Array(44, 1), Array(45, 1), Array( _
46, 1), Array(47, 1), Array(48, 1), Array(49, 1), Array(50, 1), Array(51, 1), Array(52, 1), _
Array(53, 1), Array(54, 1), Array(55, 1), Array(56, 1), Array(57, 1), Array(58, 1), Array( _
59, 1), Array(60, 1), Array(61, 1), Array(62, 1), Array(63, 1), Array(64, 1)), TrailingMinusNumbers:=True
Application.DisplayAlerts = False
s = Dir()
numFiles = numFiles + 1
xFileName = Dir
End With
Loop
End If
End Sub
</code></pre>
<p>This code works... but only for the first column, I have upwards of 70 columns in some documents.</p>
| [
{
"answer_id": 74379306,
"author": "Tim Williams",
"author_id": 478884,
"author_profile": "https://Stackoverflow.com/users/478884",
"pm_score": 1,
"selected": false,
"text": "Workbooks.OpenText"
},
{
"answer_id": 74379340,
"author": "Robert Mearns",
"author_id": 5050,
"author_profile": "https://Stackoverflow.com/users/5050",
"pm_score": 0,
"selected": false,
"text": "Set r = Range(Range(\"A1\"), Range(\"A1\").End(xlDown))\n"
},
{
"answer_id": 74379827,
"author": "Tom Breit",
"author_id": 12327038,
"author_profile": "https://Stackoverflow.com/users/12327038",
"pm_score": 0,
"selected": false,
"text": "Option Explicit\nDim theDir As String, wk As Workbook, numFiles As Integer, s As String, r As Range\nConst ext = \".txt\"\n\n\nSub LoopThroughFiles()\n Dim xFd As FileDialog\n Dim xFdItem As Variant\n Dim xFileName As String\n theDir = ThisWorkbook.Path\n Dim wkbpath As String\n Dim wkbname As String\n Set xFd = Application.FileDialog(msoFileDialogFolderPicker)\n If xFd.Show = -1 Then\n xFdItem = xFd.SelectedItems(1) & Application.PathSeparator\n xFileName = Dir(xFdItem) ' old version had: & \"*.txt*\")\n Do While xFileName <> \"\"\n With Workbooks.Open(xFdItem & xFileName)\n 'your code here\n Set r = Range(Range(\"A1\"), Range(\"A1\").End(xlDown))\n r.TextToColumns Destination:=r, DataType:=xlDelimited, _\n TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _\n Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar:=\"|\", _\n FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), _\n Array(7, 1), Array(8, 1), Array(9, 1), Array(10, 1), Array(11, 1), Array(12, 1), Array(13, 1 _\n ), Array(14, 1), Array(15, 1), Array(16, 1), Array(17, 1), Array(18, 1), Array(19, 1), Array _\n (20, 1), Array(21, 1), Array(22, 1), Array(23, 1), Array(24, 1), Array(25, 1), Array(26, 1), _\n Array(27, 1), Array(28, 1), Array(29, 1), Array(30, 1), Array(31, 1), Array(32, 1), Array( _\n 33, 1), Array(34, 1), Array(35, 1), Array(36, 1), Array(37, 1), Array(38, 1), Array(39, 1), _\n Array(40, 1), Array(41, 1), Array(42, 1), Array(43, 1), Array(44, 1), Array(45, 1), Array( _\n 46, 1), Array(47, 1), Array(48, 1), Array(49, 1), Array(50, 1), Array(51, 1), Array(52, 1), _\n Array(53, 1), Array(54, 1), Array(55, 1), Array(56, 1), Array(57, 1), Array(58, 1), Array( _\n 59, 1), Array(60, 1), Array(61, 1), Array(62, 1), Array(63, 1), Array(64, 1)), TrailingMinusNumbers:=True\n Application.DisplayAlerts = False\n Cells.Select\n Selection.AutoFilter\n Application.AddCustomList ListArray:=Array(\"PREFERRED\", \"NON-PREFERRED\", _\n \"UNACCEPTABLE\", \"OBSOLETE\")\n ActiveSheet.Sort.SortFields. _\n Clear\n ActiveSheet.Sort.SortFields. _\n Add Key:=Range(\"D2:D479\"), SortOn:=xlSortOnValues, _\n CustomOrder:=\"PREFERRED,NON-PREFERRED,UNACCEPTABLE,OBSOLETE\", DataOption:= _\n xlSortNormal\n With ActiveSheet.Sort\n .SetRange Range(\"A1:BH79\")\n .Header = xlYes\n .MatchCase = False\n .Orientation = xlTopToBottom\n .SortMethod = xlPinYin\n .Apply\n\n xFileName = Dir\n \n wkbpath = \"C:\\Users\\tomas.breitinger\\Desktop\\BAE Export .DAT Files\\Finished\\\"\n wkbname = ActiveWorkbook.Name\n ActiveWorkbook.SaveAs Filename:= _\n wkbpath & wkbname & \".xlsx\", FileFormat:=51, CreateBackup:=False\n ActiveWorkbook.Close savechanges:=False\n End With\n End With\n Loop\n End If\nEnd Sub\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12327038/"
] |
74,378,592 | <p>I have an <code>orders</code> collection where each <code>order</code> has the following shape:</p>
<pre><code> {
"_id": "5252875356f64d6d28000001",
"lineItems": [
{ productId: 'prod_007', quantity: 3 },
{ productId: 'prod_003', quantity: 2 }
]
// other fields omitted
}
</code></pre>
<p>I also have a <code>products</code> collection, where each <code>product</code> contains a unique <code>productId</code> field.</p>
<p>How can I populate each <code>lineItem.productId</code> with a matching <code>product</code> from the <code>products</code> collection? Thanks! :)</p>
<p>EDIT: <code>orderSchema</code> and <code>productSchema</code>:</p>
<pre><code>const orderSchema = new Schema({
checkoutId: {
type: String,
required: true,
},
customerId: {
type: String,
required: true,
},
lineItems: {
type: [itemSubSchema],
required: true,
},
});
const itemSubSchema = new Schema(
{
productId: {
type: String,
required: true,
},
quantity: {
type: Number,
required: true,
},
},
{ _id: false }
);
const productSchema = new Schema({
productId: {
type: String,
required: true,
},
name: {
type: String,
required: true,
},
imageURL: {
type: String,
required: true,
},
price: {
type: Number,
default: 0,
},
});
</code></pre>
| [
{
"answer_id": 74378873,
"author": "J.F.",
"author_id": 13464279,
"author_profile": "https://Stackoverflow.com/users/13464279",
"pm_score": 1,
"selected": false,
"text": "$unwind"
},
{
"answer_id": 74379829,
"author": "Tim",
"author_id": 20317091,
"author_profile": "https://Stackoverflow.com/users/20317091",
"pm_score": 0,
"selected": false,
"text": "_id"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13169785/"
] |
74,378,621 | <p>I am trying to prevent users from connecting to certain pages with a script. Thus, is there any method I can use to detect if a connection to a specific web page is a client browser versus an automated script?</p>
<p>I know certain headers can be spoofed, but is there another mechanism I can use; say like if unable to set a <code>sesseion_start</code> or <code>setCookie</code>. Do those return true/false values if able or unable be to be set?</p>
<p>Something like:</p>
<pre><code>$sessionID = session_id() ;
$isSet = setCookie('cookieName',$sessionID, [ .... ]) ;
if ($isSet == false) {
... do something to kill the session
... or do something to redirect
}
</code></pre>
<p>Is this even possible? And even if it is, I know this probably isn't reliable, but what would be a better or more reliable method?</p>
<p>And to clarify, detect if its a script and if so, kill it before even serving the rest of the html page.</p>
| [
{
"answer_id": 74378753,
"author": "Zak",
"author_id": 1507691,
"author_profile": "https://Stackoverflow.com/users/1507691",
"pm_score": 0,
"selected": false,
"text": ".htaccess"
},
{
"answer_id": 74379086,
"author": "Mehedi Hasan",
"author_id": 19207212,
"author_profile": "https://Stackoverflow.com/users/19207212",
"pm_score": -1,
"selected": false,
"text": "$_SERVER['HTTP_REFERER']"
},
{
"answer_id": 74380640,
"author": "Markus Zeller",
"author_id": 2645713,
"author_profile": "https://Stackoverflow.com/users/2645713",
"pm_score": 0,
"selected": false,
"text": "if (PHP_SAPI !== php_sapi_name()) {\n die('CLI only');\n}\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2036221/"
] |
74,378,624 | <p>I would like to concurrently perform an operation on the elements of a slice<br />
I am using the <a href="https://pkg.go.dev/golang.org/x/sync/errgroup" rel="nofollow noreferrer">sync/errgroup</a> package to handle concurrency</p>
<p>Here is a minimal reproduction on Go Playground <a href="https://go.dev/play/p/yBCiy8UW_80" rel="nofollow noreferrer">https://go.dev/play/p/yBCiy8UW_80</a></p>
<pre class="lang-golang prettyprint-override"><code>import (
"fmt"
"golang.org/x/sync/errgroup"
)
func main() {
eg := errgroup.Group{}
input := []int{0, 1, 2}
output1 := []int{}
output2 := make([]int, len(input))
for i, n := range input {
eg.Go(func() (err error) {
output1 = append(output1, n+1)
output2[i] = n + 1
return nil
})
}
eg.Wait()
fmt.Printf("with append %+v", output1)
fmt.Println()
fmt.Printf("with make %+v", output2)
}
</code></pre>
<p>outputs</p>
<pre><code>with append [3 3 3]
with make [0 0 3]
</code></pre>
<p>versus expected <code>[1 2 3]</code></p>
| [
{
"answer_id": 74378829,
"author": "NotX",
"author_id": 5767484,
"author_profile": "https://Stackoverflow.com/users/5767484",
"pm_score": 2,
"selected": false,
"text": "1"
},
{
"answer_id": 74383278,
"author": "Austin",
"author_id": 3113342,
"author_profile": "https://Stackoverflow.com/users/3113342",
"pm_score": 3,
"selected": true,
"text": "for i, n, := range input {\n // ...\n}\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13210063/"
] |
74,378,631 | <p>I'm trying to use the <a href="https://github.com/microsoftgraph/msgraph-sdk-dotnet" rel="nofollow noreferrer">Graph SDK</a> and NuGet 5.0.0-preview16 and forwarding the example it says to use <code>Request</code> method in example</p>
<pre><code>var users = await graphClient.Users.Request().GetAsync();
</code></pre>
<p>but I have an error in the code:</p>
<blockquote>
<p>'UsersRequestBuilder' does not contain a definition for 'Request' and
no accessible extension method 'Request' accepting a first argument of
type 'UsersRequestBuilder' could be found (are you missing a using
directive or an assembly reference?</p>
</blockquote>
| [
{
"answer_id": 74378829,
"author": "NotX",
"author_id": 5767484,
"author_profile": "https://Stackoverflow.com/users/5767484",
"pm_score": 2,
"selected": false,
"text": "1"
},
{
"answer_id": 74383278,
"author": "Austin",
"author_id": 3113342,
"author_profile": "https://Stackoverflow.com/users/3113342",
"pm_score": 3,
"selected": true,
"text": "for i, n, := range input {\n // ...\n}\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18993539/"
] |
74,378,637 | <p>In Octave, I am playing with signal processing primitives, attempting to reproduce the convolution theorem in multiple ways: that convolution in the time domain is equivalent to point-wise multiplication in the frequency domain.</p>
<p>I consider three routes to reconstruct the original signal:</p>
<ol>
<li>The <code>fft</code> and <code>ifft</code> functions</li>
<li>The <code>conv</code> function</li>
<li>A manually constructed DFT matrix.</li>
</ol>
<p>I am attaching my working code, and the output, glad for inputs on where the bugs may be located.</p>
<pre><code>N = 512; % number of points
t = 0:N-1; % [0,1,2,...,N-1]
h = exp(-t); % filter impulse reponse
H = fft(h); % filter frequency response
x = (1+t) .* sin(sqrt(1+t)); % (input signal of our choice)
y1 = conv(x,h,"same"); % Direct convolution
y2 = ifft(fft(x) .* H); % FFT convolution
T = transpose(t) * t;
W = exp(j * 2*pi/N * T); % DFT matrix
y3 = (x * W .* H) * W/N; % "Manual" convolution
lw = 2
plot(t,
x, ";orig;", "linewidth", lw+1,
y1, ";conv;", "linestyle", "--", "linewidth", lw,
real(y2), ";fft;", "linestyle", ":", "linewidth", lw,
real(y3), ";manual;", "linestyle", "-.", "linewidth", lw)
set(gca, "fontsize", 20, "linewidth", lw)
</code></pre>
<p><a href="https://i.stack.imgur.com/VH7VL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VH7VL.png" alt="enter image description here" /></a></p>
<ol>
<li>In the first case (yellow), I am able to reconstruct the signal, but the scaling is not right (in fact the scaling is wrong in every case).</li>
<li>In the second case (red), it looks like the result is shifted, and half of the signal is lost.</li>
<li>In the third case (purple), I get something that's equivalent to <code>fft</code> but flipped horizontally.</li>
</ol>
| [
{
"answer_id": 74379209,
"author": "Cris Luengo",
"author_id": 7328782,
"author_profile": "https://Stackoverflow.com/users/7328782",
"pm_score": 3,
"selected": true,
"text": "conv"
},
{
"answer_id": 74379518,
"author": "PierU",
"author_id": 14778592,
"author_profile": "https://Stackoverflow.com/users/14778592",
"pm_score": 1,
"selected": false,
"text": "x"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/729288/"
] |
74,378,642 | <p>I want to parent and child process read the contents of a.txt file, byte by byte. And parent process write byte by byte to the b.txt file. child process write byte by byte to the c.txt file.</p>
<p>Parent and child are working on reading from the same file and writing to the same file</p>
<pre><code>#include<stdio.h>
#include<fcntl.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
int main(argc,argv)
int argc;
char *argv[];
{
int fdrt,fdwt2,fdwt3;
char c;
char parent='P';
char child='C';
int pid;
unisigned long i;
if(argc !=4) exit(1);
if((fdrd =open(argv[1],O_RDONLY))==-1)
exit(1);
if((fdwt2=creat(argv[2],0666))==-1)
exit(1);
if((fdwt3=creat(argv[3],0666))==-1)
exit(1);
printf("Parent:creating a child process\n");
pid=fork();
if(pid==0){
printf("Child process starts,id= %d\n",getpid());
for(;;)
{
if(read(fdrd,&c,1)!=1) break;
if(i=0;i<50000;i++);
write(1,&child,1);
write(fdwt2,&c,1);
}
exit(0);
}
else
{
printf("Parent starts,id= %d\n",getpid());
for(;;)
{
if(read(fdrd,&c,1)!=1) break;
if(i=0;i<50000;i++);
write(1,&parent,1);
write(fdwt3,&c,1);
}
wait(0);
}
}
</code></pre>
| [
{
"answer_id": 74379209,
"author": "Cris Luengo",
"author_id": 7328782,
"author_profile": "https://Stackoverflow.com/users/7328782",
"pm_score": 3,
"selected": true,
"text": "conv"
},
{
"answer_id": 74379518,
"author": "PierU",
"author_id": 14778592,
"author_profile": "https://Stackoverflow.com/users/14778592",
"pm_score": 1,
"selected": false,
"text": "x"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18917371/"
] |
74,378,681 | <p>I'm having this problem where my error output says that I am missing 2 positional arguments but they are defined.
if you didnt understand, this is a Cog :)
btw, if you see any problems with my sqlite, please notify me because i am kind of new to sqlite</p>
<p>this is my code:</p>
<pre><code>import discord
from discord.ext import commands
import sqlite3
import random
class EconCog(commands.Cog, name="Economy"):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
db = sqlite3.connect("economy.sqlite")
cursor = db.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS economy(
Tokens INTEGER,
Weapons TEXT,
user_id INTEGER,
)
""")
@commands.command()
async def addtokens(self, ctx, message, number: int = None):
if ctx.author.guild_permissions.ban_members:
author = message.author
db = sqlite3.connect("economy.sqlite")
cursor = db.cursor()
cursor.execute(f"SELECT Tokens FROM economy WHERE user_id = {author.id}")
result = cursor.fetchone()
if number is None:
sql = ("INSERT INTO economy(user_id, Tokens) VALUES (?, ?)")
val = (author.id, 0, 0)
cursor.execute(sql, val)
ctx.send("Please enter a number")
else:
sql = ("INSERT INTO economy(user_id, Tokens) VALUES (?, ?)")
val = (author.id, number, 0)
cursor.execute(sql, val)
ctx.send("Done!")
db.commit()
cursor.close()
db.close()
else:
await ctx.send("Nice try, but you do not have permission to do that.")
@commands.command()
async def removetokens(self, ctx):
if ctx.message.author.guild_permissions.ban_members:
print("Ok")
else:
await ctx.send("Nice try, but you do not have permission to do that.")
async def setup(bot, ctx, message):
await bot.add_cog(EconCog(bot))
print("Economy cog has been loaded successfully!")
</code></pre>
<p>this is the error output that i got:</p>
<pre><code>Failed to load extension cogs.economy
Traceback (most recent call last):
File "C:\Users\stene\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 946, in _load_from_module_spec
await setup(self)
^^^^^^^^^^^
TypeError: setup() missing 2 required positional arguments: 'ctx' and 'message'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\stene\OneDrive\Documents\GitHub\bot\main.py", line 23, in on_ready
await bot.load_extension(extension)
File "C:\Users\stene\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1012, in load_extension
await self._load_from_module_spec(spec, name)
File "C:\Users\stene\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 951, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.economy' raised an error: TypeError: setup() missing 2 required positional arguments: 'ctx' and 'message'
</code></pre>
| [
{
"answer_id": 74379198,
"author": "Der Kek",
"author_id": 18786679,
"author_profile": "https://Stackoverflow.com/users/18786679",
"pm_score": -1,
"selected": false,
"text": "async def setup(self, ctx):\n"
},
{
"answer_id": 74379249,
"author": "stijndcl",
"author_id": 13568999,
"author_profile": "https://Stackoverflow.com/users/13568999",
"pm_score": 1,
"selected": true,
"text": "setup"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20177656/"
] |
74,378,700 | <p>I want to be able to create an error flag in a sperate column.
I am not sure how to check conditions between two different DF columns.</p>
<p>Example DF</p>
<pre><code> Category Item Flag
0 Fruit Apple
1 Fruit Apple
2 Fruit Beef
3 Fruit Kiwi
4 Fruit Orange
</code></pre>
<p>What I want to achive:</p>
<pre><code>fruits = ['Apple', 'Orange', 'Kiwi']
if df['Category'] == 'Fruit'
check if df['Item'] is in fruits
if not append error
</code></pre>
<p>Expected output</p>
<pre><code> Category Item Flag
0 Fruit Apple OK
1 Fruit Apple OK
2 Fruit Beef Error
3 Fruit Kiwi OK
4 Fruit Orange OK
</code></pre>
| [
{
"answer_id": 74378924,
"author": "gotenks",
"author_id": 17028594,
"author_profile": "https://Stackoverflow.com/users/17028594",
"pm_score": 1,
"selected": false,
"text": "temp_df = df[df['Category'] == \"Fruit\"]\ntemp_df['Flag'] = ['OK' if (x in fruits) else 'Error' for x in temp_df['Item']]\n"
},
{
"answer_id": 74378977,
"author": "Martin Lange",
"author_id": 19887308,
"author_profile": "https://Stackoverflow.com/users/19887308",
"pm_score": 1,
"selected": false,
"text": "df[\"Flag\"] = df.apply(lambda x: \"OK\" if x[\"Category\"] == \"Fruit\" and x[\"Item\"] in fruits else \"ERROR\", axis=1)\n"
},
{
"answer_id": 74379051,
"author": "Karel Räppo",
"author_id": 20084657,
"author_profile": "https://Stackoverflow.com/users/20084657",
"pm_score": 0,
"selected": false,
"text": "def check(x, y):\n if y in fruits and x == \"Fruit\":\n return True\n else:\n return \"Error\"\n\ndf['Flag'] = df.apply(lambda x: check(x['Category'], x['Item']), axis=1)\n"
},
{
"answer_id": 74379076,
"author": "Jason Baker",
"author_id": 3249641,
"author_profile": "https://Stackoverflow.com/users/3249641",
"pm_score": 2,
"selected": false,
"text": "df[\"Flag\"] = np.where(df[\"Category\"].eq(\"Fruit\") & df[\"Item\"].isin(fruits), \"OK\", \"Error\")\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13278981/"
] |
74,378,702 | <p>I have a dumped sql file named <strong>my_dump.sql</strong>.</p>
<p>Within that dump file there are various tables. I'm interested in the table named <code>foo_bars</code> which has a bunch of records. I would like to modify this sql file by doing the following:</p>
<ul>
<li>keep the <code>foo_bars</code> table structure, but remove all it's records from the sql file.</li>
</ul>
<p>The outcome: when I create a new database via this sql file, It properly has the <code>foo_bars</code> table, but all the records are gone.</p>
<p><strong>Note</strong>: I realize I <em>could</em> create a new database with all the <code>foo_bars</code> table records intact and then issue a <code>delete</code> statement once the database is created. I do not want to do this though because there are tons of records. I'd rather remove the records <em>beforehand</em> from the sql file.</p>
<p>How might I do this?</p>
| [
{
"answer_id": 74378831,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 2,
"selected": false,
"text": "--no-data"
},
{
"answer_id": 74378922,
"author": "Elivan Fengler Backes",
"author_id": 20453392,
"author_profile": "https://Stackoverflow.com/users/20453392",
"pm_score": 1,
"selected": false,
"text": "INSERT INTO foo_bars"
},
{
"answer_id": 74378991,
"author": "Valeriu Ciuca",
"author_id": 4527645,
"author_profile": "https://Stackoverflow.com/users/4527645",
"pm_score": 0,
"selected": false,
"text": "foo_bars"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4044009/"
] |
74,378,703 | <p>I'm writing a PowerShell script that needs to check if items in array $arrayEmail are in array $empListEmail and throw those values in another array C. Array A has 9,500+ items and array B doesn't have many. Surprisingly, I have not seen an example that performs this. I've been searching Google for two days. Here is what I have now, but the comparison doesn't work at all like it should.</p>
<pre><code>function MatchUsers {
$array = Get-Content -Raw -Path PassDataOut.json | ConvertFrom-Json
Import-Module ActiveDirectory # Load the Active Directory module
Set-Location AD: # Change into Active Directory
set-location "DC=graytv,DC=corp" # Sets the location to the Gray TV Corporate directory
$empList = Get-ADUser -filter 'Enabled -eq "False"' -searchbase "OU=domain Users,DC=graytv,DC=corp"
$arrayTemp = $array.Email
$arrayEmail = $arrayTemp.trim()
$empListEmail = $empList.UserPrincipalName
$NotInList = @($arrayEmail) -notin $empListEmail
Write-Host $NotInList
</code></pre>
| [
{
"answer_id": 74378831,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 2,
"selected": false,
"text": "--no-data"
},
{
"answer_id": 74378922,
"author": "Elivan Fengler Backes",
"author_id": 20453392,
"author_profile": "https://Stackoverflow.com/users/20453392",
"pm_score": 1,
"selected": false,
"text": "INSERT INTO foo_bars"
},
{
"answer_id": 74378991,
"author": "Valeriu Ciuca",
"author_id": 4527645,
"author_profile": "https://Stackoverflow.com/users/4527645",
"pm_score": 0,
"selected": false,
"text": "foo_bars"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8257274/"
] |
74,378,715 | <p>I am looking for a way to take a vector and return the percentage that each element appears.</p>
<p>See below for the input vector and the expected result.</p>
<pre><code>InputVector<-c(1,1,1,1,1,2,2,2,3,3)
ExpectedResult<-data.frame(Value=c(1,2,3), Percentile=c(0.5,0.3,0.2))
</code></pre>
<p>In this case, 1 appears <code>50%</code> of the time, 2 appears <code>30%</code> and 3 appears <code>20%</code> of the time.</p>
| [
{
"answer_id": 74378727,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 3,
"selected": true,
"text": "table"
},
{
"answer_id": 74378961,
"author": "fm361",
"author_id": 20300433,
"author_profile": "https://Stackoverflow.com/users/20300433",
"pm_score": 0,
"selected": false,
"text": "table(InputVector) / length(InputVector)"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17974332/"
] |
74,378,722 | <p>[![enter image description here][1]][1]</p>
<p>dears. as we know a Map can have <key, Value> right? then in the picture I see the first element as the key and the second one is the value which is String also. but after we do have another String and also a List as the value. I'm confused about the second part. do we have tow key and value in one Map? please some one Explain it for me. or give me link to study deep an understand with example. much thanks.
[1]: <a href="https://i.stack.imgur.com/pbeOy.png" rel="nofollow noreferrer">https://i.stack.imgur.com/pbeOy.png</a></p>
| [
{
"answer_id": 74378727,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 3,
"selected": true,
"text": "table"
},
{
"answer_id": 74378961,
"author": "fm361",
"author_id": 20300433,
"author_profile": "https://Stackoverflow.com/users/20300433",
"pm_score": 0,
"selected": false,
"text": "table(InputVector) / length(InputVector)"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20019751/"
] |
74,378,754 | <p><em>Is there any way to achieve this UI in flutter, images are calling by an API, Card sizes are fixed. This should be scroll horizontally same as this. My code is down below</em></p>
<pre><code>StaggeredGrid.count(
axisDirection: AxisDirection.right,
crossAxisCount: 3,
mainAxisSpacing: 4,
crossAxisSpacing: 4,
children: const [
StaggeredGridTile.count(
crossAxisCellCount: 1,
mainAxisCellCount: 2,
child: Card(
elevation: 50,
shadowColor: Colors.black,
color: Colors.black,
),
),
StaggeredGridTile.count(
crossAxisCellCount: 1,
mainAxisCellCount: 1,
child: Card(
elevation: 50,
shadowColor: Colors.black,
color: Colors.black,
),
),
StaggeredGridTile.count(
crossAxisCellCount: 1,
mainAxisCellCount: 1,
child: Card(
elevation: 50,
shadowColor: Colors.black,
color: Colors.black,
),
),
StaggeredGridTile.count(
crossAxisCellCount: 1,
mainAxisCellCount: 1,
child: Card(
elevation: 50,
shadowColor: Colors.black,
color: Colors.black,
),
),
StaggeredGridTile.count(
crossAxisCellCount: 1,
mainAxisCellCount: 2,
child: Card(
elevation: 50,
shadowColor: Colors.black,
color: Colors.black,
),
),
StaggeredGridTile.count(
crossAxisCellCount: 2,
mainAxisCellCount: 1,
child: Card(
elevation: 50,
shadowColor: Colors.black,
color: Colors.black,
),
),
],
),
</code></pre>
<p>I tried with mentioned code & I attached the result as well, I use Staggered GridView to implement this</p>
<p><a href="https://i.stack.imgur.com/G9wTU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/G9wTU.png" alt="enter image description here" /></a></p>
<p>My code output <a href="https://i.stack.imgur.com/pP1C2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pP1C2.png" alt="I just wanted to do is loop this grid " /></a></p>
<p>I just wanted to do is loop this grid and add images to tiles.</p>
| [
{
"answer_id": 74378813,
"author": "Ruble",
"author_id": 17991131,
"author_profile": "https://Stackoverflow.com/users/17991131",
"pm_score": -1,
"selected": false,
"text": "ListView(\n // This next line does the trick.\n scrollDirection: Axis.horizontal,\n children: <Widget>[ /* your widgets */],\n),\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14214495/"
] |
74,378,759 | <p>I'm drawing a blank at the moment. I need to translate back and forth between "signed" and "unsigned" degrees, [-180..180] and [0..360]</p>
<p>The simple way to go from [-180..180] to [0..360] is</p>
<p><code>(d+360) % 360</code> // (+360 removes ambiguity about the sign in some languages).</p>
<p>How do I do the inverse operation? I can do</p>
<p><code>if d<180 d else d-360</code></p>
<p>but it looks ugly.</p>
<p><strong>Edit:</strong>
Here are some example numbers. I want to map this</p>
<p><code>[0, 90, 180, 270, 360]</code></p>
<p>to this:</p>
<p><code>[0, 90, 180, -90, 0]</code></p>
<p><strong>Edit 2:</strong></p>
<p>OK, brain freeze is over. The answer is</p>
<p><code>(a+180)%360-180</code></p>
| [
{
"answer_id": 74378933,
"author": "Isaí",
"author_id": 20163376,
"author_profile": "https://Stackoverflow.com/users/20163376",
"pm_score": 0,
"selected": false,
"text": "float map(float n, float x1, float x2, float y1, float y2)\n{\n float m = (y2 - y1) / (x2 - x1);\n return y1 + m * (n - x1);\n}\n"
},
{
"answer_id": 74380412,
"author": "iter",
"author_id": 271594,
"author_profile": "https://Stackoverflow.com/users/271594",
"pm_score": 2,
"selected": true,
"text": "(a+180)%360-180"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/271594/"
] |
74,378,763 | <p>I have a data text file(17 columns) that i want to read in R. I'm using the read.table() function.</p>
<pre><code>read.table(file="data.txt", header = TRUE, sep = "\t", quote = "",comment.char="")
</code></pre>
<p>The problem is that some of the rows take multiple lines(example below)</p>
<pre><code>10 Macron serait-il plus pro-salafiste que Hamon?!
t.co/g29oOgqih1
#Presidentielle2017 FALSE 0 NA 2017-03-02 13:45:08 FALSE NA 837297724378726400 NA <a href="https://about.twitter.com/products/tweetdeck" rel="nofollow">TweetDeck</a> Trader496 0 FALSE FALSE NA NA
</code></pre>
<p>Is there any way to read this type of data in a single row or do i have to use <code>fill=TRUE</code></p>
<p>Data File: <a href="https://pastebin.com/b90VHvSt" rel="nofollow noreferrer">https://pastebin.com/b90VHvSt</a></p>
| [
{
"answer_id": 74379463,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 2,
"selected": true,
"text": "readr::melt_*()"
},
{
"answer_id": 74379863,
"author": "Ric Villalba",
"author_id": 6912817,
"author_profile": "https://Stackoverflow.com/users/6912817",
"pm_score": 0,
"selected": false,
"text": "data <- readLines(\"b90VHvSt.txt\")\ndata <- paste(data, collapse = \" \") \ndata <- gsub(\"(([^\\\\t]*\\\\t){15}[^ ]+) \", \"\\\\1\\t\", data, perl = T)\ndata <- unlist(strsplit(data, \"\\t\"))\ndata <- append(data, \"?\", 9)\ndata <- matrix(data, nrow = 17)\ndata <- as.data.frame(t(data[,-1]), row.names = data[,1] ))\n\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16082960/"
] |
74,378,767 | <p>Why does casting</p>
<pre class="lang-sql prettyprint-override"><code>select cast(st_makepoint(-90.345929, 37.278424) as geography)
</code></pre>
<p>raise the following error:</p>
<blockquote>
<p>SQL compilation error: invalid type [CAST(ST_MAKEPOINT(TO_DOUBLE(-90.345929), TO_DOUBLE(37.278424)) AS GEOGRAPHY)] for parameter 'TO_GEOGRAPHY'</p>
</blockquote>
<p>While a seemingly more direct pass of the <code>st_makepoint</code> result to <code>to_geography</code> does not?</p>
<pre class="lang-sql prettyprint-override"><code>select to_geography(st_makepoint(-90.345929, 37.278424))
</code></pre>
<p>I'm fairly sure I'm stuck with the casting behavior in the <code>dbt</code> tool I'm using. Basically I'm trying to union a bunch of tables with this <code>geography</code> field, and in the compiled SQL this casting logic appears as a function of <code>dbt</code>'s <code>union_relations</code> macro, and I don't seem to be able to control whether the casting occurs.</p>
| [
{
"answer_id": 74379674,
"author": "tconbeer",
"author_id": 10813082,
"author_profile": "https://Stackoverflow.com/users/10813082",
"pm_score": 3,
"selected": true,
"text": "union_relations"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5015569/"
] |
74,378,785 | <p>I need some help in writing a query which will return the distinct count of memberid who are active YTD and by each month</p>
<p>i.e.</p>
<p>202201 - distinct memberid who are active in 202201</p>
<p>202202 - distinct memberid who are active between 202201 - 202202</p>
<p>202203 - distinct memberid who are active between 202201 - 202203</p>
<p>the data structure are similar to below.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>memberid</th>
<th>yearmonth</th>
<th>activestatus</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>202201</td>
<td>Y</td>
</tr>
<tr>
<td>1</td>
<td>202202</td>
<td>Y</td>
</tr>
<tr>
<td>1</td>
<td>202203</td>
<td>N</td>
</tr>
<tr>
<td>2</td>
<td>202201</td>
<td>N</td>
</tr>
<tr>
<td>2</td>
<td>202202</td>
<td>N</td>
</tr>
<tr>
<td>2</td>
<td>202203</td>
<td>Y</td>
</tr>
<tr>
<td>3</td>
<td>202201</td>
<td>N</td>
</tr>
<tr>
<td>3</td>
<td>202202</td>
<td>Y</td>
</tr>
<tr>
<td>3</td>
<td>202203</td>
<td>Y</td>
</tr>
</tbody>
</table>
</div>
<p>Thanks you.</p>
<p>Expected:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>yearmonth</th>
<th>active_status</th>
</tr>
</thead>
<tbody>
<tr>
<td>202201</td>
<td>1</td>
</tr>
<tr>
<td>202202</td>
<td>2</td>
</tr>
<tr>
<td>202203</td>
<td>3</td>
</tr>
</tbody>
</table>
</div> | [
{
"answer_id": 74378992,
"author": "DannySlor",
"author_id": 19174570,
"author_profile": "https://Stackoverflow.com/users/19174570",
"pm_score": 0,
"selected": false,
"text": "row_number()"
},
{
"answer_id": 74382063,
"author": "GMB",
"author_id": 10676716,
"author_profile": "https://Stackoverflow.com/users/10676716",
"pm_score": 2,
"selected": true,
"text": "row_number()"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20461294/"
] |
74,378,793 | <p>The task is to delete an object from an array within another array (a touple if i'm correct). To bugproof i would need to check whether the index is actually valid. This means ranges from 0 to 4 (so input should be greater 0 smaller 4) and obviously not be a string or float of any kind.</p>
<p>I have tried to do that with my def function. i obviously want loopx to only be false if indeed both of the above mentioned criteria are met. otherwise i would want to jump to except. I felt like if that is what I've done but now been stuck for over an hour.</p>
<pre><code>#Write a Python program to delete an existing item from the array
#function used to check for valid input
def valuecheck(checker):
loopx = True
while loopx:
try:
if checker == int(checker) and (checker>0 and checker<4):
#first it checks if the input is actually an integer
#checker = int(checker)
#checks if the input index number is within range of the array
loopx = False
else:
checker = input("Value isn't a valid input, try again: ")
return(checker)
#if input isn't an integer the below prompt is printed
except:
checker = input("Value isn't a valid input, try again: ")
#the example array is defined and printed
myarray = ['i', [1, 3, 5, 7, 9]]
print(myarray[1])
#input defined and checked by the loop
deletion = input("Please input the index of the element you want to remove (0 through 4). Indexes for the elements start at 0, increasing left to right: ")
deletion = valuecheck(deletion)
#pop is then used to remove the value with index "deletion" from the array
myarray[1].pop(deletion)
#finally the new array is printed
print ("This is the new array:",myarray[1])
</code></pre>
| [
{
"answer_id": 74379017,
"author": "CryptoFool",
"author_id": 7631480,
"author_profile": "https://Stackoverflow.com/users/7631480",
"pm_score": 2,
"selected": true,
"text": "valuecheck()"
},
{
"answer_id": 74379095,
"author": "frankfalse",
"author_id": 18108367,
"author_profile": "https://Stackoverflow.com/users/18108367",
"pm_score": 1,
"selected": false,
"text": "#Write a Python program to delete an existing item from the array\n\n#function used to check for valid input\ndef valuecheck(checker):\n loopx = True\n while loopx:\n try:\n if (int(checker)>=0 and int(checker)<=4):\n loopx = False\n else:\n checker = input(\"Value isn't a valid input, try again: \")\n except Exception as ex:\n checker = input(\"Value isn't a valid input, try again: \")\n return checker\n\n#the example array is defined and printed\nmyarray = ['i', [1, 3, 5, 7, 9]]\nprint(myarray[1])\n\n#input defined and checked by the loop\ndeletion = input(\"Please input the index of the element you want to remove (0 through 4). Indexes for the elements start at 0, increasing left to right: \")\ndeletion = valuecheck(deletion)\n\n#pop is then used to remove the value with index \"deletion\" from the array\nmyarray[1].pop(int(deletion))\n#finally the new array is printed\nprint (\"This is the new array:\",myarray[1])\n"
},
{
"answer_id": 74379231,
"author": "Gábor Fekete",
"author_id": 6464041,
"author_profile": "https://Stackoverflow.com/users/6464041",
"pm_score": 0,
"selected": false,
"text": "def valuecheck():\n prompt = \"Please input the index of the element you want to remove (0 through 4). Indexes for the elements start at 0, increasing left to right: \"\n while True:\n try:\n checker = int(input(prompt))\n if 0 <= checker <= 4:\n return checker\n prompt = \"Value isn't in range [0,4], try again: \"\n except ValueError:\n prompt = \"Value isn't a valid integer, try again: \"\n\n#the example array is defined and printed\nmyarray = ['i', [1, 3, 5, 7, 9]]\nprint(myarray[1])\n\n#input defined and checked by the loop\ndeletion = valuecheck()\n\n#pop is then used to remove the value with index \"deletion\" from the array\nmyarray[1].pop(deletion)\n#finally the new array is printed\nprint (\"This is the new array:\",myarray[1])\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74378793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20458305/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.