qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,414,179
<p>I need to dynamically update the fields of this class dynamically with an object</p> <pre><code>export default class Foo { private accessKey: string; private workspaceId: string; private api: AxiosInstance; public bar: string; public name: string; ... ... private async fetch() { try { // data contains bar and name value const { data } = await this.api.get(&quot;/&quot;); // goal this = {...this, ...data}; </code></pre> <p>See goal comment, how can I do this dynamically?</p>
[ { "answer_id": 74414238, "author": "Mahendra Raj", "author_id": 7053203, "author_profile": "https://Stackoverflow.com/users/7053203", "pm_score": 1, "selected": false, "text": "List<Category> categoryFromJson(String str) => List<Category>.from(json.decode(str).map((x) => Category.fromJson(x)));\n" }, { "answer_id": 74414293, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 3, "selected": true, "text": "List<Category> categoryFromJson(String str) => (json.decode(str)[\"data\"] as List<Map<String, dynamic>>).map((x) => Category.fromJson(x)).toList();\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19154870/" ]
74,414,202
<pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; struct queue { int front; int rear; int size; int *arr; }; void enqueue(struct queue *q, int value) { if(q-&gt;rear!=q-&gt;size-1) { printf(&quot;Entry\n&quot;); q-&gt;rear++; q-&gt;arr[q-&gt;rear] = value; } } int main() { struct queue *q; /*struct queue *q=(struct queue *)malloc(sizeof(struct queue));*/ q-&gt;front = -1; q-&gt;rear = -1; q-&gt;size = 10; q-&gt;arr = (int *)malloc((q-&gt;size) * sizeof(int)); enqueue(q,14); enqueue(q,7); enqueue(q,5); enqueue(q,4); enqueue(q,3); enqueue(q,2); for(int i=0;i&lt;q-&gt;rear;i++){ printf(&quot;%d &quot;,q-&gt;arr[i]); } return 0; } </code></pre> <p>I was expecting the elements of the queue to be printed. When the line &quot;struct queue *q;&quot; is replaced with this &quot; *struct queue *q=(struct queue *)malloc(sizeof(struct queue));&quot; it works, what is the reason?</p>
[ { "answer_id": 74414238, "author": "Mahendra Raj", "author_id": 7053203, "author_profile": "https://Stackoverflow.com/users/7053203", "pm_score": 1, "selected": false, "text": "List<Category> categoryFromJson(String str) => List<Category>.from(json.decode(str).map((x) => Category.fromJson(x)));\n" }, { "answer_id": 74414293, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 3, "selected": true, "text": "List<Category> categoryFromJson(String str) => (json.decode(str)[\"data\"] as List<Map<String, dynamic>>).map((x) => Category.fromJson(x)).toList();\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20486552/" ]
74,414,208
<p>I have a big model in PowerBI where there are many different aggregation and grouping based on columns being displayed or not on the final table.</p> <p>Simplifying: I need to do a conditional statement doing the <strong>sum if the value of column 1 is A1 but doing the MAX() if the value of column 1 is A2.</strong></p> <p><a href="https://i.stack.imgur.com/AOQxV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AOQxV.png" alt="enter image description here" /></a></p> <p>I need to have that information in the same column of the final output.</p> <p>How would you go for this one?</p> <p>Thank you very much for your help!</p>
[ { "answer_id": 74414329, "author": "Vojtěch Šíma", "author_id": 15414213, "author_profile": "https://Stackoverflow.com/users/15414213", "pm_score": 1, "selected": false, "text": "Measure = IF ( SELECTEDVALUE('Table'[Column1]) = \"A1\", SUM('Table'[Column2]), MAX('Table'[Column2]))\n" }, { "answer_id": 74419132, "author": "Ozan Sen", "author_id": 19469088, "author_profile": "https://Stackoverflow.com/users/19469088", "pm_score": 0, "selected": false, "text": "TblMeasure =\nVAR TblSummary =\n ADDCOLUMNS (\n VALUES ( FactTable[Column1] ),\n \"Test\",\n IF (\n FactTable[Column1] = \"A1\",\n SUM ( FactTable[Column2] ),\n MAX ( FactTable[Column2] )\n )\n )\nRETURN\n SUMX ( TblSummary, [Test] )\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20479369/" ]
74,414,212
<p>I have to check whether a number is an <a href="https://en.wikipedia.org/wiki/Narcissistic_number" rel="nofollow noreferrer">Armstrong number</a> or not, using a recursive method.</p> <pre><code>public class ArmStrong { public static void main(String[] args) { System.out.println(isArm(407, 0, 0)); } static boolean isArm(int n,int last,int sum) { if (n &lt;= 0 ) { if (sum == n) { return true; } else { return false; } } return isArm(n / 10, n % 10,sum + last * last * last); } } </code></pre> <p>When I debug, in the last call of <code>isArm</code> when <code>n</code> is 4, the base statement is skipped.</p>
[ { "answer_id": 74414282, "author": "rzwitserloot", "author_id": 768644, "author_profile": "https://Stackoverflow.com/users/768644", "pm_score": 1, "selected": false, "text": "if (n <= 0)" }, { "answer_id": 74414809, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 1, "selected": true, "text": "sum" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17425522/" ]
74,414,215
<p>In my code I have a number of places where I need to take an std::vector of things and put it into a std::map indexed by something. For example here are two code snippets:</p> <pre><code>//sample A std::map&lt;Mode::Type, std::vector&lt;Mode&gt;&gt; modesByType; for( const auto&amp; mode : _modes ) { Mode::Type type = mode.getType(); auto it = modesByType.find( type ); if( it == modesByType.end() ) { std::vector&lt;Mode&gt; v = { mode }; modesByType.insert( std::pair( type, v ) ); } else { it-&gt;second.push_back( mode ); } } //sample B std::map&lt;unsigned, std::vector&lt;Category&gt;&gt; categoriesByTab; for( const auto&amp; category : _categories ) { unsigned tabIndex = category.getTab(); auto it = categoriesByTab.find( tabIndex ); if( it == categoriesByTab.end() ) { std::vector&lt;Category&gt; v = { category }; categoriesByTab.insert( std::pair( tabIndex, v ) ); } else { it-&gt;second.push_back( category ); } } </code></pre> <p>I'd like to generalize this and create a template function like:</p> <pre><code>template&lt;typename T, typename V&gt; std::map&lt;T,std::vector&lt;V&gt;&gt; getMapByType( const std::vector&lt;V&gt;&amp; items, ?? ) { std::map&lt;T,std::vector&lt;V&gt;&gt; itemsByType; for( const auto&amp; item : items ) { unsigned index = ??; auto it = itemsByType.find( index ); if( it == itemsByType.end() ) { std::vector&lt;V&gt; v = { item }; itemsByType.insert( std::pair( index, v ) ); } else { it-&gt;second.push_back( item ); } } return itemsByType; } </code></pre> <p>My question is, how do I define the ?? argument to this function so that I can call the correct V.foo() function to get the index value for the map?</p> <p>Note, I do not want to make all the classes that this template (V) accepts, inherit from a base class. Can I somehow specify a lambda argument?</p>
[ { "answer_id": 74414282, "author": "rzwitserloot", "author_id": 768644, "author_profile": "https://Stackoverflow.com/users/768644", "pm_score": 1, "selected": false, "text": "if (n <= 0)" }, { "answer_id": 74414809, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 1, "selected": true, "text": "sum" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2179289/" ]
74,414,232
<p>I don't know how to rename columns that are unnamed. I have tried both approaches where I am putting the indices in quoutes and not, like this, and it didn't work:</p> <pre><code> train_dataset_with_pred_new_df.rename(columns={ 0 : 'timestamp', 1 : 'open', 2 : 'close', 3 : 'high', 4 : 'low', 5 : 'volume', 6 : 'CCI7', 7 : 'DI+',\ 8 : 'DI-', 9 : 'ADX', 10 : 'MACD Main', 11 : 'MACD Signal', 12 : 'MACD histogram', 13 : 'Fisher Transform',\ 14 : 'Fisher Trigger' }) </code></pre> <p>And</p> <pre><code> train_dataset_with_pred_new_df.rename(columns={ '0' : 'timestamp', '1' : 'open', '2' : 'close', '3' : 'high', '4' : 'low', '5' : 'volume', '6' : 'CCI7', '8' : 'DI+',\ '9' : 'DI-', '10' : 'ADX', '11' : 'MACD Main', '12' : 'MACD Signal', '13' : 'MACD histogram', '15' : 'Fisher Transform',\ '16' : 'Fisher Trigger' }) </code></pre> <p>So If both didn't worked, how do I rename them?</p> <p>Thank you for your help in advance :)</p>
[ { "answer_id": 74414282, "author": "rzwitserloot", "author_id": 768644, "author_profile": "https://Stackoverflow.com/users/768644", "pm_score": 1, "selected": false, "text": "if (n <= 0)" }, { "answer_id": 74414809, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 1, "selected": true, "text": "sum" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19797660/" ]
74,414,234
<p>I'm trying to change the blank cells into specific value of 16. However, the value it shows is like 44877. I tried changing the format, but it won't change.</p> <p>The link is here: <a href="https://docs.google.com/spreadsheets/d/17cm-C9ueGSqkK4kvAQCcSY_YYjPJ7EZ3T6Njfc9NjkM/edit?usp=sharing" rel="nofollow noreferrer">sample sheet</a></p> <p>Thank you so much</p>
[ { "answer_id": 74414260, "author": "doubleunary", "author_id": 13045193, "author_profile": "https://Stackoverflow.com/users/13045193", "pm_score": 1, "selected": false, "text": "isblank()" }, { "answer_id": 74414569, "author": "Martín", "author_id": 20363318, "author_profile": "https://Stackoverflow.com/users/20363318", "pm_score": 0, "selected": false, "text": "=ArrayFormula((IFS(isblank(A2:A), \"16\",TODAY()=A2:A, \"Is today\",TODAY()-A2:A>=1, TODAY()-A2:A, TODAY()-A2:A<=-1, \"0\")))\n" }, { "answer_id": 74415287, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 0, "selected": false, "text": "=INDEX(LAMBDA(a, t, \n IF(a=\"\", 16, \n IF(t-a > 1, t-a-1,\n IF(t-a = 0, t-a, \n IF(t-a < -1, 0, )))))(A2:A, TODAY()))\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16811337/" ]
74,414,236
<p>I have this command on my personnal bot that generates a image based on a discord users prompt but when i make it into a slash command, there is an error, i have done tests and the image is fine but it never sends the image back</p> <p>working code</p> <pre><code>@client.command(aliases=['gen']) async def genimage(ctx, *, ideel): print(&quot;reg: &quot; + ideel) response = openai.Image.create( prompt=ideel, n=1, size=&quot;1024x1024&quot;) image_url = response['data'][0]['url'] print(image_url) print(&quot; &quot;) await ctx.send(image_url) </code></pre> <p>non working code</p> <pre><code>@slash.slash(name=&quot;gen&quot;) async def gen(ctx, *, ideasl): print(&quot;slash: &quot; + ideasl) response = openai.Image.create( prompt=ideasl, n=1, size=&quot;1024x1024&quot;) image_urll = response['data'][0]['url'] print(image_urll) print(&quot; &quot;) await ctx.send(image_urll) </code></pre> <p>Console</p> <pre><code>reg: dog cat https://oaidalleapiprodscus.blob.core.windows.net/private/org-C8Nv06yDvE0bz1w78n80B2a9/user-rzBkmNENqDdD8oHXFf9VWfNh/img-6mmEETlF8a5bA7B4hUI46nSE.png?st=2022-11-12T14%3A22%3A00Z&amp;se=2022-11-12T16%3A22%3A00Z&amp;sp=r&amp;sv=2021-08-06&amp;sr=b&amp;rscd=inline&amp;rsct=image/png&amp;skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&amp;sktid=a48cca56-e6da-484e-a814-9c849652bcb3&amp;skt=2022-11-11T23%3A38%3A17Z&amp;ske=2022-11-12T23%3A38%3A17Z&amp;sks=b&amp;skv=2021-08-06&amp;sig=6MuyNRj6MDOalZLJOD9/1TwX2KbJAJJSCsMvRqgaC5c%3D slash: dog cat https://oaidalleapiprodscus.blob.core.windows.net/private/org-C8Nv06yDvE0bz1w78n80B2a9/user-rzBkmNENqDdD8oHXFf9VWfNh/img-bUNRJwcIjhFcYf3xywxE96Aw.png?st=2022-11-12T14%3A22%3A31Z&amp;se=2022-11-12T16%3A22%3A31Z&amp;sp=r&amp;sv=2021-08-06&amp;sr=b&amp;rscd=inline&amp;rsct=image/png&amp;skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&amp;sktid=a48cca56-e6da-484e-a814-9c849652bcb3&amp;skt=2022-11-12T03%3A02%3A46Z&amp;ske=2022-11-13T03%3A02%3A46Z&amp;sks=b&amp;skv=2021-08-06&amp;sig=cAOqhtWoe5VIq0ITY0%2BPhBRUZb%2BsLj%2BVy%2BarZe9OHsk%3D An exception has occurred while executing command `gen`: Traceback (most recent call last): File &quot;/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_slash/client.py&quot;, line 1352, in invoke_command await func.invoke(ctx, **args) File &quot;/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_slash/model.py&quot;, line 210, in invoke return await self.func(*args, **kwargs) File &quot;main.py&quot;, line 42, in gen await ctx.send(image_urll) File &quot;/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_slash/context.py&quot;, line 256, in send await self._http.post_initial_response(json_data, self.interaction_id, self._token) File &quot;/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py&quot;, line 243, in request raise NotFound(r, data) discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction </code></pre> <p><a href="https://i.stack.imgur.com/GMPJv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GMPJv.png" alt="example of command" /></a></p> <p>Example of working slash command in code</p> <pre><code>@slash.slash(name=&quot;modapp&quot;) async def enbed(ctx: SlashContext): embed = Embed(title=&quot;Mod Applications.&quot;, url=&quot;https://www.youtube.com/watch?v=QB7ACr7pUuE&quot;, description=&quot;Click above to apply for mod.&quot;) await ctx.send(embed=embed) </code></pre> <p><a href="https://i.stack.imgur.com/eNRGh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eNRGh.png" alt="image of working code" /></a></p> <p>i tried running both commands and everthing work on both exept for the returning of the slash command's image</p> <p>full code</p> <pre><code>import discord import random import os import openai import json import math from discord.ext import commands, tasks from itertools import cycle from random import choice from math import pi from keep_alive import keep_alive from discord import Client, Intents, Embed from discord_slash import SlashCommand, SlashContext openai.api_key = os.getenv(&quot;teken&quot;) openai.Model.list() client = commands.Bot(command_prefix = '+',intents=Intents.default()) status = cycle(['with life','with death']) slash = SlashCommand(client, sync_commands=True) #slash commands @slash.slash(name=&quot;modapp&quot;) async def enbed(ctx: SlashContext): embed = Embed(title=&quot;Mod Applications.&quot;, url=&quot;https://www.youtube.com/watch?v=QB7ACr7pUuE&quot;, description=&quot;Click above to apply for mod.&quot;) await ctx.send(embed=embed) @slash.slash(name=&quot;sus&quot;) async def simp(ctx: SlashContext): image=&quot;index.jpg&quot; await ctx.send(file=discord.File(image)) @slash.slash(name=&quot;gen&quot;) async def gen(ctx, *, ideasl): print(&quot;slash: &quot; + ideasl) response = openai.Image.create( prompt=ideasl, n=1, size=&quot;1024x1024&quot;) image_urll = response['data'][0]['url'] print(image_urll) print(&quot; &quot;) await ctx.send(image_urll) #events @client.event async def on_ready(): change_status.start() print('We have logged in as {0.user}'.format(client)) print(&quot; &quot;) @client.event async def on_command_error(ctx, error): if isinstance(error, commands.MissingRequiredArgument): await ctx.send('Please Put In The Required Argument!') elif isinstance(error, commands.MissingPermissions): await ctx.send(&quot;Don't cheat the System Please!&quot;) #tasks @tasks.loop(seconds=10) async def change_status(): await client.change_presence(activity=discord.Game(next(status))) #commands @client.command() async def ping(ctx): await ctx.send(f'Pong! {round(client.latency * 1000)}ms') @client.command() async def hello(ctx): await ctx.send('Hi!') @client.command(aliases=['8ball']) async def _8ball(ctx, *, question): responses = ['Definitely', 'Maybe', 'Absolutely Not'] await ctx.send(f'Question: {question}\nAwnswer: {random.choice(responses)}') print (f'Question: {question}') print(&quot; &quot;) @client.command(aliases=['gen']) async def genimage(ctx, *, ideel): print(&quot;reg: &quot; + ideel) response = openai.Image.create( prompt=ideel, n=1, size=&quot;1024x1024&quot;) image_url = response['data'][0]['url'] print(image_url) print(&quot; &quot;) await ctx.send(image_url) @client.command() async def roll(ctx, *, dicesize): await ctx.send(f'You rolled a d{dicesize}\nYou got a {random.randint(1,int(dicesize))}') @client.command() async def calculator(ctx): await ctx.send('https://replit.com/@Hoadi605/Calculator#main.py') @client.command() async def testss(ctx): await ctx.send('this was a rickroll') @client.command() async def idea(ctx, *,idean): ideeees = open('ideaas.txt', 'a+') ideeees.write(f'{idean}\n') ideeees.close @client.command() async def ideas(ctx): ideeees = open('ideaas.txt', 'r') cheeese = ideeees.read() await ctx.send(cheeese) ideeees.close @client.command() async def pylearn(ctx): await ctx.send('https://www.youtube.com/watch?v=rfscVS0vtbw&amp;t=615s') #MOVE @client.command() async def start_move(ctx): move_them.start() @client.command() async def stop_move(ctx): move_them.stop() @tasks.loop(seconds=10) async def move_them(): await client.move_member(next('336185999824650242', '801605503250595844')) keep_alive() client.run(os.getenv('TOKEN')) </code></pre>
[ { "answer_id": 74414487, "author": "nub_discordDev", "author_id": 20369766, "author_profile": "https://Stackoverflow.com/users/20369766", "pm_score": 0, "selected": false, "text": "@slash.slash(name=\"gen\")\nasync def gen(ctx: SlashContext, *, ideasl):\n print(\"slash: \" + ideasl)\n response = openai.Image.create(\n prompt=ideasl,\n n=1,\n size=\"1024x1024\")\n image_urll = response['data'][0]['url']\n print(image_urll)\n print(\" \")\n await ctx.send(image_urll)\n" }, { "answer_id": 74414529, "author": "stijndcl", "author_id": 13568999, "author_profile": "https://Stackoverflow.com/users/13568999", "pm_score": 2, "selected": true, "text": "defer" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16920053/" ]
74,414,243
<p>I wonder where the literal string that <code>str</code> points to is allocated, given that (I assume) malloc only makes room for the pointer into the Heap.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; typedef struct { int a; char* str; } Bar; int main(int argc, char *argv[]) { Bar* bar_ptr = malloc(sizeof *bar_ptr); bar_ptr-&gt;a = 51; bar_ptr-&gt;str = &quot;hello world!&quot;; printf(&quot;%d\n&quot;, bar_ptr-&gt;a); printf(&quot;%s\n&quot;, bar_ptr-&gt;str); free(bar_ptr); return 0; } </code></pre>
[ { "answer_id": 74414487, "author": "nub_discordDev", "author_id": 20369766, "author_profile": "https://Stackoverflow.com/users/20369766", "pm_score": 0, "selected": false, "text": "@slash.slash(name=\"gen\")\nasync def gen(ctx: SlashContext, *, ideasl):\n print(\"slash: \" + ideasl)\n response = openai.Image.create(\n prompt=ideasl,\n n=1,\n size=\"1024x1024\")\n image_urll = response['data'][0]['url']\n print(image_urll)\n print(\" \")\n await ctx.send(image_urll)\n" }, { "answer_id": 74414529, "author": "stijndcl", "author_id": 13568999, "author_profile": "https://Stackoverflow.com/users/13568999", "pm_score": 2, "selected": true, "text": "defer" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4640963/" ]
74,414,248
<p>I am running sql query in python, I have a requirement to dynamically generate dates and append it to my sql query.This script runs on every Monday. If the week of Monday falls between two months then I have to restrict the date range till last of the previous month (i.e 30th or 31st). Any Ideas on how to achieve this ?</p> <p>I tried to get the weeknumber and their respective dates but I couldn't find the exact function which will return me list of dates with corresponding week number</p>
[ { "answer_id": 74414487, "author": "nub_discordDev", "author_id": 20369766, "author_profile": "https://Stackoverflow.com/users/20369766", "pm_score": 0, "selected": false, "text": "@slash.slash(name=\"gen\")\nasync def gen(ctx: SlashContext, *, ideasl):\n print(\"slash: \" + ideasl)\n response = openai.Image.create(\n prompt=ideasl,\n n=1,\n size=\"1024x1024\")\n image_urll = response['data'][0]['url']\n print(image_urll)\n print(\" \")\n await ctx.send(image_urll)\n" }, { "answer_id": 74414529, "author": "stijndcl", "author_id": 13568999, "author_profile": "https://Stackoverflow.com/users/13568999", "pm_score": 2, "selected": true, "text": "defer" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16715954/" ]
74,414,252
<p>I have a Navigation bar at the top of the browser window with different dropdown menus. A few are on the left, a few on the right.</p> <h1>The Problem:</h1> <p>If the Content of the Dropdown is large, it automatically extends the div where it's contained within. This only becomes a Problem as soon as it goes off screen.</p> <h1>The Code:</h1> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>:root { /* Theme */ --theme_color: #fff; --theme_color_select: #BBB; --theme_text: #000; --theme_text_select: #444; --theme_shadow: #0004; --theme_shadow_select: #4444; } /* Taskbar */ #taskbar { position: sticky; display: flex; justify-content: space-between; top: 0; left: 0; right: 0; bottom: 0; height: 3em; width: 100%; background-color: var(--theme_color); box-shadow: 2px 2px 2px 2px var(--theme_shadow); z-index: 1; } #taskbar .dropdown-name { line-height: 3em; min-width: 4em; text-align: center; vertical-align: middle; } #taskbar .button { padding: 0; border: 0; /* width: 4em; */ } #taskbar .dropdown-content { background-color: var(--theme_color); box-shadow: 0px 0px 4px 4px var(--theme_shadow); border: 4px solid #0000; border-radius: 4px; } /* Dropdowns */ .dropdown { position: relative; display: inline-block; } .dropdown-content { display: none; position: absolute; z-index: 2; flex-direction: column; max-width: 50vw; } .dropdown-name { cursor: default; -webkit-user-select: none; user-select: none; } .dropdown:hover .dropdown-content { display: flex; } .dropdown:hover .dropdown-name { background-color: var(--theme_color_select); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;header id="taskbar"&gt; &lt;section id="taskbar_left"&gt; &lt;div class="dropdown"&gt; &lt;div class="dropdown-name"&gt;UwU&lt;/div&gt; &lt;div class="dropdown-content"&gt; &lt;button&gt;Create Column&lt;/button&gt; &lt;button&gt;Button 2 uwuuwuuwuuwuuwuwuwuwuwuuwuwuwuwuuwuwuwuuwuwuuwuuwu&lt;/button&gt; &lt;button&gt;Button 3 h&lt;/button&gt; &lt;/div&gt; &lt;/div&gt;&lt;div class="dropdown"&gt; &lt;div class="dropdown-name"&gt;UwU&lt;/div&gt; &lt;div class="dropdown-content"&gt; &lt;button&gt;Create Column&lt;/button&gt; &lt;button&gt;Button 2 uwuuwu&lt;/button&gt; &lt;button&gt;Button 3 h&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; &lt;section id="taskbar_right"&gt; &lt;div class="dropdown"&gt; &lt;div class="dropdown-name"&gt;UwUwUwUwUwUwU&lt;/div&gt; &lt;div class="dropdown-content"&gt; &lt;button&gt;Create Column&lt;/button&gt; &lt;button&gt;Button 2 uwuuwuuwuuwuuwuwuwuwuwuuwuwuwuwuuwuwuwuuwuwuuwuuwu&lt;/button&gt; &lt;button&gt;Button 3 h&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; &lt;/header&gt;</code></pre> </div> </div> </p> <h1>My Attempts:</h1> <ul> <li>I added to the CSS <code>#taskbar_right .dropdown-content {transform: translate(calc(4em - 100%), 0);}</code> to move every dropdown content contained in the right Taskbar to be moved. However, if the Text of the class &quot;dropdown-name&quot; is bigger than 4em it isn't perfectly aligned to the right side anymore.</li> <li>I also tried using the left, right, top and bottom CSS, but that doesn't work, because the dropdown-content is absolutely positioned, so it just gets completely messed up.</li> </ul> <h1>What I need:</h1> <p>A &quot;Simple&quot; way of shifting the content the exact amount to the left it goes off screen. It would be best if the solution only includes CSS, or if it's impossible, then JavaScript. <strong>No jQuery</strong>, the Rest of my code works without it.</p> <p>PS: The CSS is just a portion of all the 340 Lines of CSS, here it only contains the most Relevant.</p> <p>PPS: The text inside the button elements is just for testing purposes.</p> <p>PPPS: Where do I add Code Snippets? There's no button for it. There's only &quot;Link, Blockquote, Code Block, Image, Table&quot;. There's no 6th button... am I missing something?</p>
[ { "answer_id": 74414487, "author": "nub_discordDev", "author_id": 20369766, "author_profile": "https://Stackoverflow.com/users/20369766", "pm_score": 0, "selected": false, "text": "@slash.slash(name=\"gen\")\nasync def gen(ctx: SlashContext, *, ideasl):\n print(\"slash: \" + ideasl)\n response = openai.Image.create(\n prompt=ideasl,\n n=1,\n size=\"1024x1024\")\n image_urll = response['data'][0]['url']\n print(image_urll)\n print(\" \")\n await ctx.send(image_urll)\n" }, { "answer_id": 74414529, "author": "stijndcl", "author_id": 13568999, "author_profile": "https://Stackoverflow.com/users/13568999", "pm_score": 2, "selected": true, "text": "defer" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19701713/" ]
74,414,272
<p><code>aes_string</code> had some convenient behaviours that I made use of when programming with ggplot2. But <code>aes_string</code> has been deprecated (noticeably since ggplot2 version 3.4.0 I believe). I am struggling with how to nicely replace it.</p> <p>Specifically, I previously created functions that accepted arbitrary string arguments through the ellipsis, and passed these to aes_string via do.call, as shown in the first reprex below.</p> <p>Since noticing the deprecation warning I have tried to avoid <code>aes_string</code>, and found myself effectively just mimicking it in a rather &quot;hacky&quot; looking way. Presumably, whatever flaw in <code>aes_string</code> led to its deprecation, would also apply to my hacky workaround. See the second reprex.</p> <p><strong>Is there a more elegant solution? I want to continue passing the variable names as strings.</strong></p> <h2>Reprex of my old approach with aes_string</h2> <pre class="lang-r prettyprint-override"><code>library(ggplot2) plotterOld &lt;- function(...) { args &lt;- list(...) pointAes &lt;- do.call(aes_string, args = args) ggplot(mpg, aes(displ, cty)) + geom_point(mapping = pointAes) } plotterOld(colour = &quot;cyl&quot;, size = &quot;year&quot;) #&gt; Warning: `aes_string()` was deprecated in ggplot2 3.0.0. #&gt; ℹ Please use tidy evaluation ideoms with `aes()` </code></pre> <p><img src="https://i.imgur.com/jB7GJtC.png" alt="plot 1" /></p> <pre class="lang-r prettyprint-override"><code># it can accept NULLs, and e.g. intuitively doesn't map size to anything plotterOld(colour = &quot;cyl&quot;, size = NULL) </code></pre> <p><img src="https://i.imgur.com/JVZl9Jl.png" alt="plot 2" /></p> <pre class="lang-r prettyprint-override"><code># no arguments also works fine plotterOld() </code></pre> <p><img src="https://i.imgur.com/aQ6aPoP.png" alt="plot 3" /></p> <p><sup>Created on 2022-11-11 with reprex v2.0.2</sup></p> <hr /> <h2>Reprex of my hacky attempt at replacing aes_string's behaviour?</h2> <pre class="lang-r prettyprint-override"><code>library(ggplot2) # arbitrary aesthetics passed as strings using ellipses, aes, quo and .data myAesString &lt;- function(...) { dots &lt;- list(...) # early exits stopifnot(rlang::is_named2(dots)) if (length(dots) == 0) { return(NULL) } # initialise empty mapping object and fill it with quosures where appropriate mapping &lt;- aes() for (n in names(dots)) { v &lt;- dots[[n]] if (!is.null(v)) { if (!rlang::is_string(v)) stop(n, &quot; must be a string or NULL&quot;) mapping[[n]] &lt;- quo(.data[[v]]) } } return(mapping) } plotterNew &lt;- function(...) { pointAes &lt;- myAesString(...) ggplot(mpg, aes(displ, cty)) + geom_point(mapping = pointAes) } plotterNew(colour = &quot;cyl&quot;, size = &quot;year&quot;) </code></pre> <p><img src="https://i.imgur.com/0tl4ugG.png" alt="plot 4" /></p> <pre class="lang-r prettyprint-override"><code>plotterNew(colour = &quot;cyl&quot;, size = NULL, shape = &quot;drv&quot;) </code></pre> <p><img src="https://i.imgur.com/3sNKGfw.png" alt="plot 5" /></p> <pre class="lang-r prettyprint-override"><code>plotterNew() </code></pre> <p><img src="https://i.imgur.com/hvPgzrn.png" alt="plot 6" /></p> <pre class="lang-r prettyprint-override"><code> # seems to work fine p &lt;- plotterNew(colour = &quot;cyl&quot;, size = &quot;year&quot;) p$layers[[1]]$mapping #&gt; Aesthetic mapping: #&gt; * `colour` -&gt; `.data[[&quot;cyl&quot;]]` #&gt; * `size` -&gt; `.data[[&quot;year&quot;]]` </code></pre> <p><sup>Created on 2022-11-11 with <a href="https://reprex.tidyverse.org" rel="nofollow noreferrer">reprex v2.0.2</a></sup></p> Session info <pre class="lang-r prettyprint-override"><code>sessioninfo::session_info() #&gt; ─ Session info ─────────────────────────────────────────────────────────────── #&gt; setting value #&gt; version R version 4.2.1 (2022-06-23) #&gt; os macOS Big Sur ... 10.16 #&gt; system x86_64, darwin17.0 #&gt; ui X11 #&gt; language (EN) #&gt; collate en_GB.UTF-8 #&gt; ctype en_GB.UTF-8 #&gt; tz Europe/Amsterdam #&gt; date 2022-11-11 #&gt; pandoc 2.18 @ /Applications/RStudio.app/Contents/MacOS/quarto/bin/tools/ (via rmarkdown) #&gt; #&gt; ─ Packages ─────────────────────────────────────────────────────────────────── #&gt; package * version date (UTC) lib source #&gt; assertthat 0.2.1 2019-03-21 [1] CRAN (R 4.2.0) #&gt; cli 3.4.1 2022-09-23 [1] CRAN (R 4.2.0) #&gt; colorspace 2.0-3 2022-02-21 [1] CRAN (R 4.2.0) #&gt; curl 4.3.3 2022-10-06 [1] CRAN (R 4.2.0) #&gt; DBI 1.1.3 2022-06-18 [1] CRAN (R 4.2.0) #&gt; digest 0.6.30 2022-10-18 [1] CRAN (R 4.2.1) #&gt; dplyr 1.0.10 2022-09-01 [1] CRAN (R 4.2.0) #&gt; evaluate 0.18 2022-11-07 [1] CRAN (R 4.2.0) #&gt; fansi 1.0.3 2022-03-24 [1] CRAN (R 4.2.0) #&gt; farver 2.1.1 2022-07-06 [1] CRAN (R 4.2.0) #&gt; fastmap 1.1.0 2021-01-25 [1] RSPM (R 4.2.0) #&gt; fs 1.5.2 2021-12-08 [1] RSPM (R 4.2.0) #&gt; generics 0.1.3 2022-07-05 [1] CRAN (R 4.2.0) #&gt; ggplot2 * 3.4.0 2022-11-04 [1] CRAN (R 4.2.1) #&gt; glue 1.6.2 2022-02-24 [1] CRAN (R 4.2.0) #&gt; gtable 0.3.1 2022-09-01 [1] CRAN (R 4.2.0) #&gt; highr 0.9 2021-04-16 [1] RSPM (R 4.2.0) #&gt; htmltools 0.5.3 2022-07-18 [1] CRAN (R 4.2.0) #&gt; httr 1.4.4 2022-08-17 [1] CRAN (R 4.2.0) #&gt; knitr 1.40 2022-08-24 [1] CRAN (R 4.2.0) #&gt; labeling 0.4.2 2020-10-20 [1] CRAN (R 4.2.0) #&gt; lifecycle 1.0.3 2022-10-07 [1] CRAN (R 4.2.0) #&gt; magrittr 2.0.3 2022-03-30 [1] CRAN (R 4.2.0) #&gt; mime 0.12 2021-09-28 [1] RSPM (R 4.2.0) #&gt; munsell 0.5.0 2018-06-12 [1] CRAN (R 4.2.0) #&gt; pillar 1.8.1 2022-08-19 [1] CRAN (R 4.2.0) #&gt; pkgconfig 2.0.3 2019-09-22 [1] CRAN (R 4.2.0) #&gt; purrr 0.3.5 2022-10-06 [1] CRAN (R 4.2.0) #&gt; R.cache 0.16.0 2022-07-21 [1] CRAN (R 4.2.0) #&gt; R.methodsS3 1.8.2 2022-06-13 [1] CRAN (R 4.2.0) #&gt; R.oo 1.25.0 2022-06-12 [1] CRAN (R 4.2.0) #&gt; R.utils 2.12.1 2022-10-30 [1] CRAN (R 4.2.0) #&gt; R6 2.5.1 2021-08-19 [1] CRAN (R 4.2.0) #&gt; reprex 2.0.2 2022-08-17 [1] CRAN (R 4.2.0) #&gt; rlang 1.0.6 2022-09-24 [1] CRAN (R 4.2.0) #&gt; rmarkdown 2.18 2022-11-09 [1] CRAN (R 4.2.1) #&gt; rstudioapi 0.14 2022-08-22 [1] CRAN (R 4.2.0) #&gt; scales 1.2.1 2022-08-20 [1] CRAN (R 4.2.0) #&gt; sessioninfo 1.2.2 2021-12-06 [1] RSPM (R 4.2.0) #&gt; stringi 1.7.8 2022-07-11 [1] CRAN (R 4.2.0) #&gt; stringr 1.4.1 2022-08-20 [1] CRAN (R 4.2.0) #&gt; styler 1.8.1 2022-11-07 [1] CRAN (R 4.2.0) #&gt; tibble 3.1.8 2022-07-22 [1] CRAN (R 4.2.0) #&gt; tidyselect 1.2.0 2022-10-10 [1] CRAN (R 4.2.0) #&gt; utf8 1.2.2 2021-07-24 [1] CRAN (R 4.2.0) #&gt; vctrs 0.5.0 2022-10-22 [1] CRAN (R 4.2.0) #&gt; withr 2.5.0 2022-03-03 [1] CRAN (R 4.2.0) #&gt; xfun 0.34 2022-10-18 [1] CRAN (R 4.2.0) #&gt; xml2 1.3.3 2021-11-30 [1] RSPM (R 4.2.0) #&gt; yaml 2.3.6 2022-10-18 [1] CRAN (R 4.2.1) #&gt; #&gt; [1] /Library/Frameworks/R.framework/Versions/4.2/Resources/library #&gt; #&gt; ────────────────────────────────────────────────────────────────────────────── </code></pre> ```
[ { "answer_id": 74414389, "author": "stefan", "author_id": 12993861, "author_profile": "https://Stackoverflow.com/users/12993861", "pm_score": 3, "selected": true, "text": "sym" }, { "answer_id": 74414473, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 2, "selected": false, "text": "ensyms" }, { "answer_id": 74424353, "author": "David Barnett", "author_id": 9005116, "author_profile": "https://Stackoverflow.com/users/9005116", "pm_score": 0, "selected": false, "text": "sym()" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9005116/" ]
74,414,297
<p>To simplify, as much as possible, a <a href="https://stackoverflow.com/questions/74409065/cartpy-and-pcolormesh-how-to-project-polar-data-onto-a-map">question I already asked</a>, how would you OVERLAY or PROJECT a polar plot onto a cartopy map.</p> <pre><code>phis = np.linspace(1e-5,10,10) # SV half cone ang, measured up from nadir thetas = np.linspace(0,2*np.pi,361)# SV azimuth, 0 coincides with the vel vector X,Y = np.meshgrid(thetas,phis) Z = np.sin(X)**10 + np.cos(10 + Y*X) * np.cos(X) fig, ax = plt.subplots(figsize=(4,4),subplot_kw=dict(projection='polar')) im = ax.pcolormesh(X,Y,Z, cmap=mpl.cm.jet_r,shading='auto') ax.set_theta_direction(-1) ax.set_theta_offset(np.pi / 2.0) ax.grid(True) </code></pre> <p>that results in <a href="https://i.stack.imgur.com/Gc0vvm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gc0vvm.png" alt="enter image description here" /></a></p> <p>Over a cartopy map like this...</p> <pre><code>flatMap = ccrs.PlateCarree() resolution = '110m' fig = plt.figure(figsize=(12,6), dpi=96) ax = fig.add_subplot(111, projection=flatMap) ax.imshow(np.tile(np.array([[cfeature.COLORS['water'] * 255]], dtype=np.uint8), [2, 2, 1]), origin='upper', transform=ccrs.PlateCarree(), extent=[-180, 180, -180, 180]) ax.add_feature(cfeature.NaturalEarthFeature('physical', 'land', resolution, edgecolor='black', facecolor=cfeature.COLORS['land'])) ax.pcolormesh(X,Y,Z, cmap=mpl.cm.jet_r,shading='auto') gc.collect() </code></pre> <p><a href="https://i.stack.imgur.com/tg8G8l.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tg8G8l.png" alt="enter image description here" /></a></p> <p>I'd like to project this polar plot over an arbitrary lon/lat... I can convert the polar theta/phi into lon/lat, but lon/lat coords (used on the map) are more 'cartesian like' than polar, hence you cannot just substitute lon/lat for theta/phi ... This is a conceptual problem. How would you tackle it?</p>
[ { "answer_id": 74417371, "author": "swatchai", "author_id": 2177413, "author_profile": "https://Stackoverflow.com/users/2177413", "pm_score": 1, "selected": false, "text": "XX = X/np.pi*180 # wrap around data in EW direction\nYY = Y*9 # spread across N hemisphere \n" }, { "answer_id": 74418122, "author": "earnric", "author_id": 2687317, "author_profile": "https://Stackoverflow.com/users/2687317", "pm_score": 0, "selected": false, "text": "X_cart = np.array([[p*np.sin(t) for p in phis] for t in thetas]).T\nY_cart = np.array([[p*np.cos(t) for p in phis] for t in thetas]).T\n# Need to map cartesian XY to Z that is compatbile with above... \n\nZ_cart = np.sin(X)**10 + np.cos(10 + Y*X) * np.cos(X) # This Z does NOT map to cartesian X,Y\nprint(X_cart.shape,Y_cart.shape,Z_cart.shape) \n\nflatMap = ccrs.PlateCarree()\nresolution = '110m'\nfig = plt.figure(figsize=(12,6), dpi=96)\nax = fig.add_subplot(111, projection=flatMap)\n\nax.imshow(np.tile(np.array([[cfeature.COLORS['water'] * 255]], dtype=np.uint8), [2, 2, 1]), origin='upper', transform=ccrs.PlateCarree(), extent=[-180, 180, -180, 180])\nax.add_feature(cfeature.NaturalEarthFeature('physical', 'land', resolution, edgecolor='black', facecolor=cfeature.COLORS['land']))\n\nim = ax.pcolormesh(X_cart*2,Y_cart*2, Z_cart, cmap=mpl.cm.jet_r, shading='auto') # c=mapper.to_rgba(Z_cart), cmap=mpl.cm.jet_r) \n\n\ngc.collect()\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2687317/" ]
74,414,314
<p>I'm using .NET exclusively for Entity Framework's elegant handling of migrations. I have a working project with an EF schema. The part I now need is to move the DB connection string into configuration.</p> <p>All I have so far is the following:</p> <pre><code>public partial class EfContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { optionsBuilder.UseNpgsql(&quot;Host=localhost;Port=5432;Database=...;Username=...;Password=...&quot;); } } } </code></pre> <p>There is no other code apart from the entity definitions and migrations (no Startup class or HostBuilder stuff at all).</p> <p>Can any kind soul instruct me in the simplest way to move the string into <code>appSettings.&lt;env&gt;.json</code>?</p>
[ { "answer_id": 74417371, "author": "swatchai", "author_id": 2177413, "author_profile": "https://Stackoverflow.com/users/2177413", "pm_score": 1, "selected": false, "text": "XX = X/np.pi*180 # wrap around data in EW direction\nYY = Y*9 # spread across N hemisphere \n" }, { "answer_id": 74418122, "author": "earnric", "author_id": 2687317, "author_profile": "https://Stackoverflow.com/users/2687317", "pm_score": 0, "selected": false, "text": "X_cart = np.array([[p*np.sin(t) for p in phis] for t in thetas]).T\nY_cart = np.array([[p*np.cos(t) for p in phis] for t in thetas]).T\n# Need to map cartesian XY to Z that is compatbile with above... \n\nZ_cart = np.sin(X)**10 + np.cos(10 + Y*X) * np.cos(X) # This Z does NOT map to cartesian X,Y\nprint(X_cart.shape,Y_cart.shape,Z_cart.shape) \n\nflatMap = ccrs.PlateCarree()\nresolution = '110m'\nfig = plt.figure(figsize=(12,6), dpi=96)\nax = fig.add_subplot(111, projection=flatMap)\n\nax.imshow(np.tile(np.array([[cfeature.COLORS['water'] * 255]], dtype=np.uint8), [2, 2, 1]), origin='upper', transform=ccrs.PlateCarree(), extent=[-180, 180, -180, 180])\nax.add_feature(cfeature.NaturalEarthFeature('physical', 'land', resolution, edgecolor='black', facecolor=cfeature.COLORS['land']))\n\nim = ax.pcolormesh(X_cart*2,Y_cart*2, Z_cart, cmap=mpl.cm.jet_r, shading='auto') # c=mapper.to_rgba(Z_cart), cmap=mpl.cm.jet_r) \n\n\ngc.collect()\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/607269/" ]
74,414,349
<p>How can I retrain only 2 decimals for each values in a Pandas series? (I'm working with latitudes and longitudes). dtype is float64.</p> <pre><code>series = [-74.002568, -74.003085, -74.003546] </code></pre> <p>I tried using the round function but as the name suggests, it rounds. I looked into trunc() but this can only remove all decimals. Then I figures why not try running a For loop. I tried the following:</p> <pre><code>for i in series: i = &quot;{0:.2f}&quot;.format(i) </code></pre> <p>I was able to run the code without any errors but it didn't modify the data in any way.</p> <p>Expected output would be the following:</p> <pre><code>[-74.00, -74.00, -74.00] </code></pre> <p>Anyone knows how to achieve this? Thanks!</p>
[ { "answer_id": 74414365, "author": "rafaelc", "author_id": 2535611, "author_profile": "https://Stackoverflow.com/users/2535611", "pm_score": 0, "selected": false, "text": "pd.options.display.float_format = \"{:,.2f}\".format\n" }, { "answer_id": 74414441, "author": "Naveed", "author_id": 3494754, "author_profile": "https://Stackoverflow.com/users/3494754", "pm_score": 1, "selected": false, "text": "# you indicated its a series but defined only a list\n# assuming you meant pandas.Series, and if its true then\n\nseries = [-74.002568, -74.003085, -74.003546] \ns=pd.Series(series)\n\n# use regex extract to pick the number until first two decimal places\nout=s.astype(str).str.extract(r\"(.*\\..{2})\")[0]\nout\n\n" }, { "answer_id": 74414474, "author": "Talha Tayyab", "author_id": 13086128, "author_profile": "https://Stackoverflow.com/users/13086128", "pm_score": 2, "selected": true, "text": "series = [-74.002568, -74.003085, -74.003546]\n\n[\"%0.2f\" % (x,) for x in series]\n\n['-74.00', '-74.00', '-74.00']\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19961084/" ]
74,414,366
<p>I have a situation in a piece of dynamic programming where i either want to get the pre computed results, or call a function to compute these results.</p> <p>This is the situation in short</p> <pre><code>let previous_results HashMap&lt;String, Result&gt; = HashMap::new(); for i in some_values { let result = previous_results.get(i).unwrap_or_else(|| calculate_results(i)) } </code></pre> <p>The rust compiler justly complains about the function call and it says</p> <pre><code>expected reference `&amp;HashMap&lt;std::string::String, Result&gt;` found struct `HashMap&lt;std::string::String, Result&gt;` </code></pre> <p>This is because <code>.get</code> normally returns a reference to the object,and not the actual object, but the function returns an actual object. So i could just return a reference to what the function returns</p> <pre><code>let result = previous_results.get(i).unwrap_or_else(|| &amp;calculate_results(i)) </code></pre> <p>Note the <code>&amp;</code>in front of the function call. But this is also an issue, cause a reference to something that is scoped within the anonymous function will be meaningless as soon as the anonymous function returns. And rust complains</p> <pre><code>cannot return reference to temporary value returns a reference to data owned by the current function </code></pre> <p>What am i missing here? What is the correct approach to do this in rust?</p>
[ { "answer_id": 74414742, "author": "rodrigo", "author_id": 865874, "author_profile": "https://Stackoverflow.com/users/865874", "pm_score": 3, "selected": true, "text": "unwrap_or_else" }, { "answer_id": 74478851, "author": "Nicola Pedretti", "author_id": 4484923, "author_profile": "https://Stackoverflow.com/users/4484923", "pm_score": 0, "selected": false, "text": "Cow" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4484923/" ]
74,414,372
<p>Basically what I want is something like below</p> <pre><code> [SomeJsonIgnoreAnnotation] class MySecret { public int Secret { get; set; } = 1; } class A { public MySecret SecretA { get; set; } = new(); } class B { public MySecret SecretB { get; set; } = new(); } </code></pre> <p>And <code>System.Text.Json.JsonSerializer</code> would treat class <code>A</code> and class <code>B</code> as if <code>SecretA</code> and <code>SecretB</code> are annotated with <code>[JsonIgnore]</code></p>
[ { "answer_id": 74414619, "author": "Poul Bak", "author_id": 5741643, "author_profile": "https://Stackoverflow.com/users/5741643", "pm_score": 3, "selected": true, "text": "class MySecret {\n [JsonIgnore]\n public int Secret { get; set; } = 1;\n}\n" }, { "answer_id": 74414812, "author": "Serge", "author_id": 11392290, "author_profile": "https://Stackoverflow.com/users/11392290", "pm_score": 0, "selected": false, "text": " [DataContract]\n public class MySecret\n {\n public int Secret { get; set; } = 1;\n\n }\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7614469/" ]
74,414,403
<p><strong>This is the code I've been using in Node.js</strong></p> <pre><code>const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/vegesDB', { useNewUrlParser: true }); const vegeSchema = new mongoose.Schema({ name: String, rating: Number, review: String }); const Vege = mongoose.model(&quot;Vege&quot;, vegeSchema); const vege = new Vege({ name: &quot;Potato&quot;, rating: 9, review: &quot;Very versatile vegetable&quot; }); vege.save(); mongoose.connection.close(); </code></pre> <p><strong>And this is the error message I get in the console:</strong></p> <pre><code>C:\Users\85569\Desktop\Neptune Pluto\FruitsProject\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:153 const err = new MongooseError(message); ^ MongooseError: Operation `veges.insertOne()` buffering timed out after 10000ms at Timeout.&lt;anonymous&gt; (C:\Users\85569\Desktop\Neptune Pluto\FruitsProject\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:153:23) at listOnTimeout (node:internal/timers:564:17) at process.processTimers (node:internal/timers:507:7) Node.js v18.6.0 </code></pre> <p>For the record, I'm using MongoDB version v5.0.9 I have no other problems with the version of MongoDB I have loaded on my laptop. It's when I try to use Mongoose that everything goes haywire. Any information about the latest super-duper updated way of using Mongoose for this purpose would be greatly appreciated.</p> <p>I've tried using variations of the above code suggested by other programmers on other sites and, to date, I haven't found one of them that works.</p>
[ { "answer_id": 74414619, "author": "Poul Bak", "author_id": 5741643, "author_profile": "https://Stackoverflow.com/users/5741643", "pm_score": 3, "selected": true, "text": "class MySecret {\n [JsonIgnore]\n public int Secret { get; set; } = 1;\n}\n" }, { "answer_id": 74414812, "author": "Serge", "author_id": 11392290, "author_profile": "https://Stackoverflow.com/users/11392290", "pm_score": 0, "selected": false, "text": " [DataContract]\n public class MySecret\n {\n public int Secret { get; set; } = 1;\n\n }\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8246276/" ]
74,414,426
<p>I have a file named default.xex that is located in XBLA_Unpacked/DirectoryName/Subdirectory/000D0000/default.xex. I am trying to rename default.xex to be DirectoryName.xex. I managed to accomplish this with File.Move() but it pulled the .xex file up into XBLA_Unpacked, so both DirectoryName and DirectoryName.xex are located there. I need to be able to rename the .xex file while also keeping it inside the 000D000 subdirectory.</p> <p>This is my current code which renames the .xex file and moves it up to the XBLA_Unpacked directory, as well as the code I wrote to try to move it back after it was renamed that doesn't work.</p> <pre><code> static void ReNamePirs() { string homePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); string unpackedPath = homePath + &quot;\\XBLA_Unpacked\\&quot;; string reNamePath = homePath + &quot;\\XBLA_Unpacked&quot;; var files = GetAllFiles(unpackedPath); var folders = GetAllFolders(unpackedPath); List&lt;string&gt; sourceName = Directory.GetFiles(unpackedPath, &quot;default.xex&quot;, SearchOption.AllDirectories).ToList(); List&lt;string&gt; destinationName = Directory.GetDirectories(unpackedPath, &quot;*&quot;, SearchOption.TopDirectoryOnly).ToList(); List&lt;string&gt; finalDestination = Directory.GetDirectories(unpackedPath, &quot;000D0000&quot;, SearchOption.AllDirectories).ToList(); for (int i = 0; i &lt; sourceName.Count; i++) { destinationName[i] = destinationName[i] + &quot;.xex&quot;; File.Move(sourceName[i], destinationName[i]); } sourceName = Directory.GetFiles(reNamePath, &quot;.xex&quot;, SearchOption.AllDirectories).ToList(); for (int i = 0; i &lt; sourceName.Count; i++) { destinationName = Directory.GetDirectories(unpackedPath, &quot;000D0000&quot;, SearchOption.AllDirectories).ToList(); File.Move(sourceName[i], destinationName[i]); } return; } </code></pre>
[ { "answer_id": 74414675, "author": "hossein sabziani", "author_id": 4301195, "author_profile": "https://Stackoverflow.com/users/4301195", "pm_score": 0, "selected": false, "text": " for (int i = 0; i < sourceName.Count; i++)\n {\n destinationName[i] = destinationName[i] + \".xex\";\n File.Move(sourceName[i], destinationName[i]); \n }\n\n sourceName = Directory.GetFiles(reNamePath, \".xex\", SearchOption.AllDirectories).ToList();\n\n for (int i = 0; i < sourceName.Count; i++)\n {\n destinationName = Directory.GetDirectories(unpackedPath, \"000D0000\", SearchOption.AllDirectories).ToList();\n File.Move(sourceName[i], destinationName[i]);\n\n }\n" }, { "answer_id": 74414705, "author": "OJ-55", "author_id": 19965031, "author_profile": "https://Stackoverflow.com/users/19965031", "pm_score": 2, "selected": true, "text": "DirectoryInfo directoryInfo = new DirectoryInfo(renamePath);\nFileInfo fileInfo = directoryInfo.GetFiles(\"default.xex\", SearchOption.AllDirectories).FirstOrDefault();\n\nif (fileInfo != null)\n{\n string newFileName = fileInfo.FullName.Replace( Path.GetFileNameWithoutExtension(fileInfo.Name), fileInfo.Directory.Parent.Parent.Name);\n fileInfo.MoveTo(newFileName);\n}\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20325402/" ]
74,414,446
<p>I want to delete a column if a cell within a range (in this case the very first row) contains a specific value. I thought I could do it like this:</p> <pre><code>Public Sub Delete_Column() Select Case Range(A1:A10) Case &quot;Birthday&quot;, &quot;Gender&quot; cell.EntireColumn.Delete End Select End Sub </code></pre> <p>But it's not working. I'm sure it's the <code>Select Case Range(A1:A10)</code> line that's wrong, but I don't know how to fix it.</p>
[ { "answer_id": 74414618, "author": "Shai Rado", "author_id": 6344363, "author_profile": "https://Stackoverflow.com/users/6344363", "pm_score": 2, "selected": false, "text": "Range(\"A1:A10\")" }, { "answer_id": 74414646, "author": "Tahbaza", "author_id": 313121, "author_profile": "https://Stackoverflow.com/users/313121", "pm_score": 1, "selected": false, "text": "Public Sub Delete_Column()\nDim rng As Excel.Range, searchValue As Variant\n Set rng = Range(\"A1:A10\")\n searchValue = \"q\"\n If Not rng.Find(searchValue, LookIn:=xlValues) Is Nothing Then\n Debug.Print \"found\"\n Else\n Debug.Print \"not found\"\n End If\nEnd Sub\n" }, { "answer_id": 74414685, "author": "VBasic2008", "author_id": 9814069, "author_profile": "https://Stackoverflow.com/users/9814069", "pm_score": 2, "selected": false, "text": "Union" }, { "answer_id": 74423382, "author": "user3598756", "author_id": 3598756, "author_profile": "https://Stackoverflow.com/users/3598756", "pm_score": 0, "selected": false, "text": " Sub DeleteColumns()\n\n With ThisWorkbook.Worksheets(\"Sheet1\").Range(\"A1:J1\")\n\n Dim cel As Range\n For Each cel In .Cells\n Select Case cel.Value\n Case \"Birthday\", \"Gender\"\n Case Else\n cel.EntireColumn.Hidden = True ' hide \"valid\" columns\n End Select\n Next\n\n On Error Resume Next ' ignore any error should no columns have been hidden\n .SpecialCells(xlCellTypeVisible).EntireColumn.Delete ' delete hidden columns\n\n .EntireColumn.Hidden = False ' make all \"valid\" columns back visible\n\n End With\n\n End Sub\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20197062/" ]
74,414,465
<pre><code>import &quot;./styles.css&quot;; const data = [ { firstname: &quot;junaid&quot;, lastname: &quot;hossain&quot;, phones: [{ home: &quot;015000&quot; }, { office: &quot;0177&quot; }] }, { firstname: &quot;arman&quot;, lastname: &quot;hossain&quot;, phones: [{ home: &quot;013000&quot; }, { office: &quot;0187&quot; }] } ]; export default function App() { return ( &lt;div className=&quot;App&quot;&gt; &lt;div className=&quot;users&quot;&gt; {data.map((user, index) =&gt; { const { firstname, lastname } = user; return ( &lt;div key={index} className=&quot;user&quot;&gt; &lt;p&gt; name: {firstname} {lastname} &lt;/p&gt; {user.phones.map((phone, i) =&gt; ( &lt;div&gt; &lt;p&gt;home phone:{phone.home}&lt;/p&gt; &lt;p&gt;office phone:{phone.office}&lt;/p&gt; &lt;/div&gt; ))} &lt;/div&gt; ); })} &lt;/div&gt; &lt;/div&gt; ); } </code></pre> <p><a href="https://i.stack.imgur.com/TgMIx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TgMIx.png" alt="enter image description here" /></a></p> <p>why a nested map showing repeated content? In this code, I don't want to show the empty office phone and home phone that I indicate in the picture by the red line. Now, what can I do to remove the extra content?</p> <p>I would be very helpful if you tell me the answer.</p>
[ { "answer_id": 74414618, "author": "Shai Rado", "author_id": 6344363, "author_profile": "https://Stackoverflow.com/users/6344363", "pm_score": 2, "selected": false, "text": "Range(\"A1:A10\")" }, { "answer_id": 74414646, "author": "Tahbaza", "author_id": 313121, "author_profile": "https://Stackoverflow.com/users/313121", "pm_score": 1, "selected": false, "text": "Public Sub Delete_Column()\nDim rng As Excel.Range, searchValue As Variant\n Set rng = Range(\"A1:A10\")\n searchValue = \"q\"\n If Not rng.Find(searchValue, LookIn:=xlValues) Is Nothing Then\n Debug.Print \"found\"\n Else\n Debug.Print \"not found\"\n End If\nEnd Sub\n" }, { "answer_id": 74414685, "author": "VBasic2008", "author_id": 9814069, "author_profile": "https://Stackoverflow.com/users/9814069", "pm_score": 2, "selected": false, "text": "Union" }, { "answer_id": 74423382, "author": "user3598756", "author_id": 3598756, "author_profile": "https://Stackoverflow.com/users/3598756", "pm_score": 0, "selected": false, "text": " Sub DeleteColumns()\n\n With ThisWorkbook.Worksheets(\"Sheet1\").Range(\"A1:J1\")\n\n Dim cel As Range\n For Each cel In .Cells\n Select Case cel.Value\n Case \"Birthday\", \"Gender\"\n Case Else\n cel.EntireColumn.Hidden = True ' hide \"valid\" columns\n End Select\n Next\n\n On Error Resume Next ' ignore any error should no columns have been hidden\n .SpecialCells(xlCellTypeVisible).EntireColumn.Delete ' delete hidden columns\n\n .EntireColumn.Hidden = False ' make all \"valid\" columns back visible\n\n End With\n\n End Sub\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20486656/" ]
74,414,466
<p>I am trying to save image upload from the camera or gallery permanently, I am using the <code>image_picker</code> package, and each time I choose a picture for a pfp and click on a different tab it's gone, it only saves it temporarily. this is my code below:</p> <pre><code>import 'dart:io'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; import 'package:path_provider/path_provider.dart'; </code></pre> <pre><code>// camera Future getCameraImage() async{ // getting the image final image = await ImagePicker().pickImage(source: ImageSource.camera); if(image == null) return; // final imageTemporary = File(image.path); final imagePerm = await saveImagePermanently(image.path); setState(() { this.image = imagePerm; }); } </code></pre> <pre><code>// image picker/ gallery File? image; Future getImage() async{ final image = await ImagePicker().pickImage(source: ImageSource.gallery); if(image == null) return; final imageTemporary = File(image.path); setState(() { this.image = imageTemporary; }); } </code></pre> <p>I have tried a few different methods but run into the same error.</p>
[ { "answer_id": 74414618, "author": "Shai Rado", "author_id": 6344363, "author_profile": "https://Stackoverflow.com/users/6344363", "pm_score": 2, "selected": false, "text": "Range(\"A1:A10\")" }, { "answer_id": 74414646, "author": "Tahbaza", "author_id": 313121, "author_profile": "https://Stackoverflow.com/users/313121", "pm_score": 1, "selected": false, "text": "Public Sub Delete_Column()\nDim rng As Excel.Range, searchValue As Variant\n Set rng = Range(\"A1:A10\")\n searchValue = \"q\"\n If Not rng.Find(searchValue, LookIn:=xlValues) Is Nothing Then\n Debug.Print \"found\"\n Else\n Debug.Print \"not found\"\n End If\nEnd Sub\n" }, { "answer_id": 74414685, "author": "VBasic2008", "author_id": 9814069, "author_profile": "https://Stackoverflow.com/users/9814069", "pm_score": 2, "selected": false, "text": "Union" }, { "answer_id": 74423382, "author": "user3598756", "author_id": 3598756, "author_profile": "https://Stackoverflow.com/users/3598756", "pm_score": 0, "selected": false, "text": " Sub DeleteColumns()\n\n With ThisWorkbook.Worksheets(\"Sheet1\").Range(\"A1:J1\")\n\n Dim cel As Range\n For Each cel In .Cells\n Select Case cel.Value\n Case \"Birthday\", \"Gender\"\n Case Else\n cel.EntireColumn.Hidden = True ' hide \"valid\" columns\n End Select\n Next\n\n On Error Resume Next ' ignore any error should no columns have been hidden\n .SpecialCells(xlCellTypeVisible).EntireColumn.Delete ' delete hidden columns\n\n .EntireColumn.Hidden = False ' make all \"valid\" columns back visible\n\n End With\n\n End Sub\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20486797/" ]
74,414,472
<p>Suppose I have a class template</p> <pre class="lang-cpp prettyprint-override"><code>template&lt;class T&gt; class Foo{}; </code></pre> <p>Is it possible to prevent T from being an instantiation of Foo. That is, this should not compile:</p> <pre class="lang-cpp prettyprint-override"><code>struct Bar{}; Foo&lt;Foo&lt;Bar&gt;&gt; x; </code></pre>
[ { "answer_id": 74414618, "author": "Shai Rado", "author_id": 6344363, "author_profile": "https://Stackoverflow.com/users/6344363", "pm_score": 2, "selected": false, "text": "Range(\"A1:A10\")" }, { "answer_id": 74414646, "author": "Tahbaza", "author_id": 313121, "author_profile": "https://Stackoverflow.com/users/313121", "pm_score": 1, "selected": false, "text": "Public Sub Delete_Column()\nDim rng As Excel.Range, searchValue As Variant\n Set rng = Range(\"A1:A10\")\n searchValue = \"q\"\n If Not rng.Find(searchValue, LookIn:=xlValues) Is Nothing Then\n Debug.Print \"found\"\n Else\n Debug.Print \"not found\"\n End If\nEnd Sub\n" }, { "answer_id": 74414685, "author": "VBasic2008", "author_id": 9814069, "author_profile": "https://Stackoverflow.com/users/9814069", "pm_score": 2, "selected": false, "text": "Union" }, { "answer_id": 74423382, "author": "user3598756", "author_id": 3598756, "author_profile": "https://Stackoverflow.com/users/3598756", "pm_score": 0, "selected": false, "text": " Sub DeleteColumns()\n\n With ThisWorkbook.Worksheets(\"Sheet1\").Range(\"A1:J1\")\n\n Dim cel As Range\n For Each cel In .Cells\n Select Case cel.Value\n Case \"Birthday\", \"Gender\"\n Case Else\n cel.EntireColumn.Hidden = True ' hide \"valid\" columns\n End Select\n Next\n\n On Error Resume Next ' ignore any error should no columns have been hidden\n .SpecialCells(xlCellTypeVisible).EntireColumn.Delete ' delete hidden columns\n\n .EntireColumn.Hidden = False ' make all \"valid\" columns back visible\n\n End With\n\n End Sub\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/877329/" ]
74,414,504
<p>I wrote a simple backend application by spring boot and kotlin, here you can see the full settings <a href="https://github.com/lifeodyssey/demo" rel="nofollow noreferrer">https://github.com/lifeodyssey/demo</a></p> <p>this bug performed as</p> <ol> <li>I can start and access the application by <code>./gradlew bootRun</code></li> <li>I can start and access the application by <code> java -jar demo.jar</code></li> <li>But I could not access the application when I try to start it in a container, even I can see a successful log by <code>docker logs containerID</code>. The log is given below</li> </ol> <pre><code>2022-11-12 15:50:33.017 INFO 1 --- [ main] com.example.demo.DemoApplicationKt : Starting DemoApplicationKt using Java 11.0.16 on eeb1dfe09e6a with PID 1 (/Demo-0.0.1.jar started by root in /) 2022-11-12 15:50:33.029 INFO 1 --- [ main] com.example.demo.DemoApplicationKt : No active profile set, falling back to 1 default profile: &quot;default&quot; 2022-11-12 15:50:34.315 INFO 1 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode 2022-11-12 15:50:34.320 INFO 1 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data MongoDB repositories in DEFAULT mode. 2022-11-12 15:50:34.346 INFO 1 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 15 ms. Found 0 MongoDB repository interfaces. 2022-11-12 15:50:35.564 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8000 (http) 2022-11-12 15:50:35.595 INFO 1 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2022-11-12 15:50:35.596 INFO 1 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.68] 2022-11-12 15:50:35.787 INFO 1 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2022-11-12 15:50:35.788 INFO 1 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2628 ms 2022-11-12 15:50:38.155 WARN 1 --- [ main] o.s.b.a.m.MustacheAutoConfiguration : Cannot find template location: classpath:/templates/ (please add some templates, check your Mustache configuration, or set spring.mustache.check-template-location=false) 2022-11-12 15:50:38.346 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8000 (http) with context path '' 2022-11-12 15:50:38.412 INFO 1 --- [ main] com.example.demo.DemoApplicationKt : Started DemoApplicationKt in 6.588 seconds (JVM running for 7.745) </code></pre> <p>And here is the Dockerfile</p> <pre><code>FROM openjdk:11 COPY /build/libs/demo-0.0.1-SNAPSHOT.jar Demo-0.0.1.jar EXPOSE 8000 ENTRYPOINT [&quot;java&quot;,&quot;-jar&quot;,&quot;/Demo-0.0.1.jar&quot;] </code></pre> <p>Here is the commmand I used to build image and run container</p> <pre><code>docker build -t demo . docker run -dp 8000:8000 demo:latest </code></pre> <p>I could not find where is the problem. Can you help me with it ?</p> <h2>Update</h2> <p>Thanks for the comments below, here is what showed when I access localhost</p> <pre><code>This site can’t be reached localhost refused to connect. Try: Checking the connection Checking the proxy and the firewall ERR_CONNECTION_REFUSED </code></pre> <p>I have tried change <code>-dp 8000</code> to <code>-d -p 8000</code>, but nothing changed.</p>
[ { "answer_id": 74414618, "author": "Shai Rado", "author_id": 6344363, "author_profile": "https://Stackoverflow.com/users/6344363", "pm_score": 2, "selected": false, "text": "Range(\"A1:A10\")" }, { "answer_id": 74414646, "author": "Tahbaza", "author_id": 313121, "author_profile": "https://Stackoverflow.com/users/313121", "pm_score": 1, "selected": false, "text": "Public Sub Delete_Column()\nDim rng As Excel.Range, searchValue As Variant\n Set rng = Range(\"A1:A10\")\n searchValue = \"q\"\n If Not rng.Find(searchValue, LookIn:=xlValues) Is Nothing Then\n Debug.Print \"found\"\n Else\n Debug.Print \"not found\"\n End If\nEnd Sub\n" }, { "answer_id": 74414685, "author": "VBasic2008", "author_id": 9814069, "author_profile": "https://Stackoverflow.com/users/9814069", "pm_score": 2, "selected": false, "text": "Union" }, { "answer_id": 74423382, "author": "user3598756", "author_id": 3598756, "author_profile": "https://Stackoverflow.com/users/3598756", "pm_score": 0, "selected": false, "text": " Sub DeleteColumns()\n\n With ThisWorkbook.Worksheets(\"Sheet1\").Range(\"A1:J1\")\n\n Dim cel As Range\n For Each cel In .Cells\n Select Case cel.Value\n Case \"Birthday\", \"Gender\"\n Case Else\n cel.EntireColumn.Hidden = True ' hide \"valid\" columns\n End Select\n Next\n\n On Error Resume Next ' ignore any error should no columns have been hidden\n .SpecialCells(xlCellTypeVisible).EntireColumn.Delete ' delete hidden columns\n\n .EntireColumn.Hidden = False ' make all \"valid\" columns back visible\n\n End With\n\n End Sub\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8606945/" ]
74,414,506
<p>Azure DataFactory File System Linked Service is not working with this error:</p> <p>Error details Error code 28051 Details c could not be resolved.</p> <p>I tried to connect file excel in onpremise machine using the self hosted integration runtimeg</p>
[ { "answer_id": 74425415, "author": "user20495886", "author_id": 20495886, "author_profile": "https://Stackoverflow.com/users/20495886", "pm_score": 3, "selected": true, "text": "c:\\" }, { "answer_id": 74440054, "author": "MarioVW", "author_id": 592732, "author_profile": "https://Stackoverflow.com/users/592732", "pm_score": 0, "selected": false, "text": "5.22.8312.1" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20486879/" ]
74,414,515
<pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;cstring&gt; int main() { int size = 5 ; int* c = (int*)calloc(size,sizeof(int)); memset(c,0,size*sizeof(int)); // when I input 1 or another value it doesn't work for (int i=0; i&lt;size;i++){ printf(&quot;values %d\n&quot;, c[i]); } free(c); } </code></pre> <p>This program's output in the below;</p> <pre class="lang-none prettyprint-override"><code>value 0 value 0 value 0 value 0 value 0 </code></pre> <p>But if I change 0 value to 1:</p> <pre class="lang-none prettyprint-override"><code>value 16843009 value 16843009 value 16843009 value 16843009 value 16843009 </code></pre> <p>I seperated the memory using calloc. I want to assign a value to this memory address that I have allocated with the memset function. When I give the value 0 here, the assignment is done successfully. I am displaying a random value instead of the values I gave outside of this value. How can I successfully perform this assignment using the memset function?</p>
[ { "answer_id": 74417966, "author": "John Kugelman", "author_id": 68587, "author_profile": "https://Stackoverflow.com/users/68587", "pm_score": 1, "selected": false, "text": "memset" }, { "answer_id": 74417969, "author": "dbush", "author_id": 1687119, "author_profile": "https://Stackoverflow.com/users/1687119", "pm_score": 3, "selected": true, "text": "memset" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15205118/" ]
74,414,553
<p>i want to display data in a CollectionView that has state = false using CommunityToolkit.Mvvm, but I don't quite understand how to do it. I wanted to use ICollectionView but didn't find it in maui. help me please</p> <p><strong>Model</strong></p> <pre><code>public class Task { public string Title { get; set; } public string Text { get; set; } public bool State { get; set; } public DateTime CreateDate { get; set; } } </code></pre> <p><strong>ViewModel</strong></p> <pre><code>public partial class ToDoViewModel : ObservableObject { [ObservableProperty] string title; [ObservableProperty] string text; [ObservableProperty] bool state = false; [ObservableProperty] DateTime createDate = DateTime.Now.Date; [ObservableProperty] ObservableCollection&lt;Task&gt; tasks; int count = 1; public ToDoViewModel() { tasks = new ObservableCollection&lt;Task&gt;(); } [RelayCommand] void Add() { if (string.IsNullOrEmpty(text)) return; Task task = new Task { Title = $&quot;Task #{count}&quot;, Text = text, State = state, CreateDate = createDate }; tasks.Add(task); count++; } [RelayCommand] void Remove(Task task) { if (tasks.Contains(task)) tasks.Remove(task); } [RelayCommand] void StateDone(Task task) { task.State = true; } } </code></pre>
[ { "answer_id": 74417966, "author": "John Kugelman", "author_id": 68587, "author_profile": "https://Stackoverflow.com/users/68587", "pm_score": 1, "selected": false, "text": "memset" }, { "answer_id": 74417969, "author": "dbush", "author_id": 1687119, "author_profile": "https://Stackoverflow.com/users/1687119", "pm_score": 3, "selected": true, "text": "memset" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20486766/" ]
74,414,604
<p>I am using the react-select library for multi-select. I am using it as a state selector but the problem is the react-select an array of objects. Like</p> <pre><code>{ &quot;label&quot;: &quot;Andaman and Nicobar Islands&quot;, &quot;value&quot;: &quot;Andaman and Nicobar Islands&quot; }, { &quot;label&quot;: &quot;Andhra Pradesh&quot;, &quot;value&quot;: &quot;Andhra Pradesh&quot; }, </code></pre> <p>I want to extract the value part from it and I tried directly but It gave me an error I decided to use a different state array to extract but the problem is I only accept three state values and also want to remove duplicate values new state also have only values. I couldn't fix this problem help me to fix this.</p> <pre><code>const [job_preference, setJobPreference] = useState([]); const [multiSelect, setMultiSelect] = useState( [] ); </code></pre> <hr /> <pre><code>const handleMultiSelectChange = (val) =&gt; { setMultiSelect(val); }; const handleJobPreference = () =&gt; { multiSelect?.map((select) =&gt; setJobPreference((prev) =&gt; [ ...prev, select.value, ]) ); }; </code></pre> <hr /> <pre><code>&lt;div className='mb-3'&gt; &lt;label className='form-label'&gt; Job Preference &lt;/label&gt; &lt;Select value={multiSelect} isMulti components={ animatedComponents } isSearchable placeholder='Choose any 3 states as job location' options={states} onChange={ handleMultiSelectChange } isOptionDisabled={() =&gt; multiSelect.length &gt;= 3 } /&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 74414730, "author": "KcH", "author_id": 11737596, "author_profile": "https://Stackoverflow.com/users/11737596", "pm_score": 2, "selected": false, "text": "values" }, { "answer_id": 74414870, "author": "narayan maity", "author_id": 6680751, "author_profile": "https://Stackoverflow.com/users/6680751", "pm_score": 2, "selected": true, "text": "const handleMultiSelectChange = (options) => {\n setMultiSelect(options);\n const values = options.map(\n (opt) => opt.value\n );\n setJobPreference([...values]);\n };\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10122516/" ]
74,414,674
<h3>A problem description:</h3> <p>I have two strings and I need to find the length of intersection of them.</p> <p><em>Let's assume the both strings are Latin-ASCII and lower case.</em></p> <p>These are expected results:</p> <pre><code>$str1 = &quot;lorem ipsum&quot;; $str2 = &quot;rem&quot;; echo str_intersection($str1, $str2); // Expected result: 3 $str2 = &quot;xzy&quot;; echo str_intersection($str1, $str2); // Expected result: 0 </code></pre> <hr /> <h3>My try to solve the problem:</h3> <p>I've tried to compare the strings using <code>array_intersect()</code> function this way:</p> <pre><code>$str_intersection = function(string $str1, string $str2): int { $arr1 = str_split($str1); // ['l','o','r','e','m',' ','i','p','s','u','m'] $arr2 = str_split($str2); // ['r','e','m'] return count(array_intersect($arr1, $arr2)); }; echo $str_intersection($str1, $str2); // Result: 4 (because of lo*REM* ipsu*M*) </code></pre> <p>But this way of comparing two strings is inappropriate because it compares occurrences of characters and not whole parts of strings as I need it.</p> <p>In addition, the str_intersection() function designed in this way is not only inappropriate, but also very slow if I need to compare thousands of strings.</p> <hr /> <h3>Example how I plan to use the needed function:</h3> <p>As requested I wrote a little example how I plan to use the string intersection function:</p> <pre><code>$strings = ['lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur']; $needle = 'lo'; $intersections = []; foreach ($strings as $str) { $intersections[] = str_intersection($str, $needle); } print_r($intersections); </code></pre> <p>Expected result (intersection &quot;<em>highlighed</em>&quot; as uppercase):</p> <pre><code>Array ( [0] =&gt; 1 // LOrem [1] =&gt; 0 // ipsum [2] =&gt; 1 // doLOr [3] =&gt; 0 // sit [4] =&gt; 0 // amet [5] =&gt; 0 // consectetur ) </code></pre>
[ { "answer_id": 74414730, "author": "KcH", "author_id": 11737596, "author_profile": "https://Stackoverflow.com/users/11737596", "pm_score": 2, "selected": false, "text": "values" }, { "answer_id": 74414870, "author": "narayan maity", "author_id": 6680751, "author_profile": "https://Stackoverflow.com/users/6680751", "pm_score": 2, "selected": true, "text": "const handleMultiSelectChange = (options) => {\n setMultiSelect(options);\n const values = options.map(\n (opt) => opt.value\n );\n setJobPreference([...values]);\n };\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/104237/" ]
74,414,683
<pre class="lang-dart prettyprint-override"><code>Future&lt;void&gt; launchInBrowser(String url) async { Uri dir = Uri.parse(url); if (!await launchUrl( dir, mode: LaunchMode.externalApplication, )) { throw 'Could not launch $url'; } } </code></pre> <p>I am using url_launcher version 6.1.6 flutter plugin and when I build the app I get this error flutter build is getting error with this : Could not load compiled classes for build file 'C:\src\flutter\flutter.pubcache\hosted\pub.dartlang.org\url_launcher_android_6.0.21\android\build.gradle' from cache '''</p> <ul> <li>What went wrong: A problem occurred configuring project ':flutter_plugin_android_lifecycle'.</li> </ul> <blockquote> <p>Could not load compiled classes for build file 'C:\src\flutter\flutter.pub-cache\hosted\pub.dartlang.org\url_launcher_android_6.0.21\android\build.gradle' from cache. Failed to notify project evaluation listener. Could not get unknown property 'android' for project ':url_launcher_android_6.0.21' of type org.gradle.api.Project. Could not get unknown property 'android' for project ':url_launcher_android_6.0.21' of type org.gradle.api.Project. '''</p> </blockquote> <p>I tried deleting .gradle folder I'm my app , and also deleted the plugin from host folder , nothing works.</p> <p>flutter doctor -v output</p> <pre><code>[√] Flutter (Channel stable, 3.3.8, on Microsoft Windows [Version 10.0.19043.2251], locale en-US) • Flutter version 3.3.8 on channel stable at C:\src\flutter • Upstream repository https://github.com/flutter/flutter.git • Framework revision 52b3dc25f6 (4 days ago), 2022-11-09 12:09:26 +0800 • Engine revision 857bd6b74c • Dart version 2.18.4 • DevTools version 2.15.0 Checking Android licenses is taking an unexpectedly long time...[√] Android toolchain - develop for Android devices (Android SDK version 31.0.0) • Android SDK at C:\Users\mo7ma\AppData\Local\Android\sdk • Platform android-33, build-tools 31.0.0 • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189) • All Android licenses accepted. [√] Chrome - develop for the web • Chrome at C:\Program Files\Google\Chrome\Application\chrome.exe [√] Visual Studio - develop for Windows (Visual Studio Build Tools 2019 16.11.13) • Visual Studio at C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools • Visual Studio Build Tools 2019 version 16.11.32413.511 • Windows 10 SDK version 10.0.19041.0 [√] Android Studio (version 2020.3) • Android Studio at C:\Program Files\Android\Android Studio • Flutter plugin can be installed from: https://plugins.jetbrains.com/plugin/9212-flutter • Dart plugin can be installed from: https://plugins.jetbrains.com/plugin/6351-dart • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189) [√] VS Code (version 1.73.1) • VS Code at C:\Users\mo7ma\AppData\Local\Programs\Microsoft VS Code • Flutter extension version 3.52.0 [√] Connected device (3 available) • Windows (desktop) • windows • windows-x64 • Microsoft Windows [Version 10.0.19043.2251] • Chrome (web) • chrome • web-javascript • Google Chrome 107.0.5304.107 • Edge (web) • edge • web-javascript • Microsoft Edge 107.0.1418.35 [√] HTTP Host Availability • All required HTTP hosts are available • No issues found! </code></pre>
[ { "answer_id": 74414730, "author": "KcH", "author_id": 11737596, "author_profile": "https://Stackoverflow.com/users/11737596", "pm_score": 2, "selected": false, "text": "values" }, { "answer_id": 74414870, "author": "narayan maity", "author_id": 6680751, "author_profile": "https://Stackoverflow.com/users/6680751", "pm_score": 2, "selected": true, "text": "const handleMultiSelectChange = (options) => {\n setMultiSelect(options);\n const values = options.map(\n (opt) => opt.value\n );\n setJobPreference([...values]);\n };\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11804723/" ]
74,414,713
<p>I have an input on the page, initially it is empty. I need to implement the following functionality: on page load, the component <code>App</code> fetches from <code>localStorage</code> a value of key <code>appData</code> and puts it in the <code>input</code>. That is, so that in the localStorage I write the value to the input and when reloading it is displayed in the input. How can i do this? <strong>I need to use <code>useEffect</code></strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>import { useEffect, useState } from "react"; export default function App() { const [userData, setUserData] = useState(""); useEffect(() =&gt; { localStorage.setItem("Userdata", JSON.stringify(userData)); }, [userData]); return ( &lt;div&gt; &lt;input value={userData} onChange={(e) =&gt; setUserData(e.target.value)}&gt;&lt;/input&gt; &lt;/div&gt; ); }</code></pre> </div> </div> </p>
[ { "answer_id": 74414730, "author": "KcH", "author_id": 11737596, "author_profile": "https://Stackoverflow.com/users/11737596", "pm_score": 2, "selected": false, "text": "values" }, { "answer_id": 74414870, "author": "narayan maity", "author_id": 6680751, "author_profile": "https://Stackoverflow.com/users/6680751", "pm_score": 2, "selected": true, "text": "const handleMultiSelectChange = (options) => {\n setMultiSelect(options);\n const values = options.map(\n (opt) => opt.value\n );\n setJobPreference([...values]);\n };\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20398508/" ]
74,414,731
<p>I merged a pull request in bit bucket from a feature branch into master and now I want to update my local copy of master. I've tried git fetch, git pull, git reset --hard, git reset --hard origin/master. I was expecting my local master branch to be updated with the new commits, but it was not. I am getting the message already up to date, and no changes are applied to my local copy. Any suggestions are appreciated.</p> <p>--update</p> <pre><code>git status On branch master Your branch is up to date with 'origin/master'. Untracked files: (use &quot;git add &lt;file&gt;...&quot; to include in what will be committed) application/config/audio/ nothing added to commit but untracked files present (use &quot;git add&quot; to track) -- git pull Already up to date </code></pre>
[ { "answer_id": 74414730, "author": "KcH", "author_id": 11737596, "author_profile": "https://Stackoverflow.com/users/11737596", "pm_score": 2, "selected": false, "text": "values" }, { "answer_id": 74414870, "author": "narayan maity", "author_id": 6680751, "author_profile": "https://Stackoverflow.com/users/6680751", "pm_score": 2, "selected": true, "text": "const handleMultiSelectChange = (options) => {\n setMultiSelect(options);\n const values = options.map(\n (opt) => opt.value\n );\n setJobPreference([...values]);\n };\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12603956/" ]
74,414,740
<p>I have a string containing a JavaScript object as follows:</p> <pre class="lang-js prettyprint-override"><code>const myString = `[{&quot;url&quot;:&quot;https:\/\/audio.ngfiles.com\/1171000\/1171300_small-talk.mp3?f1668090863&quot;,&quot;is_published&quot;:true,&quot;portal_id&quot;:2,&quot;file_id&quot;:0,&quot;project_id&quot;:1973416,&quot;item_id&quot;:1171300,&quot;description&quot;:&quot;Audio File&quot;,&quot;width&quot;:null,&quot;height&quot;:null,&quot;filesize&quot;:5776266,&quot;params&quot;:{&quot;filename&quot;:&quot;https:\/\/audio.ngfiles.com\/1171000\/1171300_small-talk.mp3?f1668090863&quot;,&quot;name&quot;:&quot;small%20talk&quot;,&quot;length&quot;:&quot;145&quot;,&quot;loop&quot;:0,&quot;artist&quot;:&quot;arbelamram&quot;,&quot;icon&quot;:&quot;https:\/\/aicon.ngfiles.com\/1171\/1171300.png?f1668090865&quot;,&quot;images&quot;:{&quot;listen&quot;:{&quot;playing&quot;:{&quot;url&quot;:&quot;https:\/\/img.ngfiles.com\/audio_peaks\/3\/1171000\/1171300.1668090863-1505287.listen.png?f1668090905&quot;,&quot;rel_path&quot;:&quot;audio_peaks\/3\/1171000\/1171300.1668090863-1505287.listen.png&quot;},&quot;completed&quot;:{&quot;url&quot;:&quot;https:\/\/img.ngfiles.com\/audio_peaks\/3\/1171000\/1171300.1668090863-1505287.listen.completed.png?f1668090905&quot;,&quot;rel_path&quot;:&quot;audio_peaks\/3\/1171000\/1171300.1668090863-1505287.listen.completed.png&quot;}},&quot;condensed&quot;:{&quot;playing&quot;:{&quot;url&quot;:&quot;https:\/\/img.ngfiles.com\/audio_peaks\/3\/1171000\/1171300.1668090863-1505287.condensed.png?f1668090906&quot;,&quot;rel_path&quot;:&quot;audio_peaks\/3\/1171000\/1171300.1668090863-1505287.condensed.png&quot;},&quot;completed&quot;:{&quot;url&quot;:&quot;https:\/\/img.ngfiles.com\/audio_peaks\/3\/1171000\/1171300.1668090863-1505287.condensed.completed.png?f1668090906&quot;,&quot;rel_path&quot;:&quot;audio_peaks\/3\/1171000\/1171300.1668090863-1505287.condensed.completed.png&quot;}}},&quot;duration&quot;:145},&quot;portal_item_requirements&quot;:[5],&quot;html&quot;:&quot;\n\n&lt;div id=\&quot;audio-listen-player\&quot; class=\&quot;audio-listen-player\&quot;&gt;\n\t&lt;div id=\&quot;audio-listen-wrapper\&quot; class=\&quot;audio-listen-wrapper\&quot;&gt;\n\n\t\t&lt;div id=\&quot;waveform\&quot; class=\&quot;audio-listen-container\&quot;&gt;&lt;\/div&gt;\n\n\t\t&lt;div class=\&quot;outer-frame\&quot;&gt;&lt;\/div&gt;\n\n\t\t&lt;p id=\&quot;cant-play-mp3\&quot; style=\&quot;display:none\&quot;&gt;Your Browser does not support html5\/mp3 audio playback.!!!&lt;\/p&gt;\n\n\t\t&lt;p id=\&quot;loading-audio\&quot;&gt;\n\t\t\t&lt;em class=\&quot;fa fa-spin fa-spinner\&quot;&gt;&lt;\/em&gt; LOADING...\n\t\t&lt;\/p&gt;\n\t&lt;\/div&gt;\n\n\t&lt;div class=\&quot;audio-listen-controls\&quot;&gt;\n\t\t&lt;div class=\&quot;play-controls\&quot;&gt;\n\t\t\t&lt;button class=\&quot;audio-listen-btn\&quot; id=\&quot;audio-listen-play\&quot; disabled&gt;\n\t\t\t\t&lt;i class=\&quot;fa fa-play\&quot;&gt;&lt;\/i&gt;\n\t\t\t&lt;\/button&gt;\n\n\t\t\t&lt;button class=\&quot;audio-listen-btn\&quot; id=\&quot;audio-listen-pause\&quot; disabled&gt;\n\t\t\t\t&lt;i class=\&quot;fa fa-pause\&quot;&gt;&lt;\/i&gt;\n\t\t\t&lt;\/button&gt;\n\n\t\t&lt;\/div&gt;\n\t\t&lt;div class=\&quot;playback-info\&quot;&gt;\n\t\t\t&lt;span id=\&quot;audio-listen-progress\&quot;&gt;00.00&lt;\/span&gt;\n\t\t\t\/\n\t\t\t&lt;span id=\&quot;audio-listen-duration\&quot;&gt;00.00&lt;\/span&gt;\n\t\t&lt;\/div&gt;\n\t\t&lt;div class=\&quot;sound-controls\&quot;&gt;\n\t\t\t&lt;button class=\&quot;audio-listen-btn\&quot; id=\&quot;audio-listen-repeat\&quot;&gt;\n\t\t\t\t&lt;i class=\&quot;fa fa-retweet\&quot;&gt;&lt;\/i&gt;\n\t\t\t&lt;\/button&gt;\n\n\t\t\t\t\t\t\t&lt;button class=\&quot;audio-listen-btn\&quot; id=\&quot;audio-listen-volumeToggle\&quot;&gt;\n\t\t\t\t\t&lt;i class=\&quot;fa fa-volume-off\&quot;&gt;&lt;\/i&gt;\n\t\t\t\t&lt;\/button&gt;\n\n\t\t\t\t&lt;div class=\&quot;off\&quot; id=\&quot;audio-listen-volume\&quot;&gt;&lt;\/div&gt;\n\t\t\t\n\t\t&lt;\/div&gt;\n\t&lt;\/div&gt;\n&lt;\/div&gt;\n\n&quot;, callback:function(){(function($) { var player = NgAudioPlayer.fromListenPage({ 'generic_id': 1171300, 'type_id': 3, 'url': &quot;https:\/\/audio.ngfiles.com\/1171000\/1171300_small-talk.mp3?f1668090863&quot;, 'version': 1668090863, 'duration': 145, 'loop': false, 'images': {&quot;listen&quot;:{&quot;playing&quot;:{&quot;url&quot;:&quot;https:\/\/img.ngfiles.com\/audio_peaks\/3\/1171000\/1171300.1668090863-1505287.listen.png?f1668090905&quot;,&quot;rel_path&quot;:&quot;audio_peaks\/3\/1171000\/1171300.1668090863-1505287.listen.png&quot;},&quot;completed&quot;:{&quot;url&quot;:&quot;https:\/\/img.ngfiles.com\/audio_peaks\/3\/1171000\/1171300.1668090863-1505287.listen.completed.png?f1668090905&quot;,&quot;rel_path&quot;:&quot;audio_peaks\/3\/1171000\/1171300.1668090863-1505287.listen.completed.png&quot;}},&quot;condensed&quot;:{&quot;playing&quot;:{&quot;url&quot;:&quot;https:\/\/img.ngfiles.com\/audio_peaks\/3\/1171000\/1171300.1668090863-1505287.condensed.png?f1668090906&quot;,&quot;rel_path&quot;:&quot;audio_peaks\/3\/1171000\/1171300.1668090863-1505287.condensed.png&quot;},&quot;completed&quot;:{&quot;url&quot;:&quot;https:\/\/img.ngfiles.com\/audio_peaks\/3\/1171000\/1171300.1668090863-1505287.condensed.completed.png?f1668090906&quot;,&quot;rel_path&quot;:&quot;audio_peaks\/3\/1171000\/1171300.1668090863-1505287.condensed.completed.png&quot;}}}, 'playlist': 'listen' }, 128); })(jQuery); }}]` </code></pre> <p>As you can see, it's JavaScript and has functions. But I need a way of parsing the rest of the object as JSON, <strong>without using eval</strong>.</p> <p>It can either return <code>null</code> where there were functions or completely remove the key and value.</p> <p>I have tried the following RegEx but I'm not the best at it so I just keep messing up the object to make it unparsable and unrunnable.</p> <pre class="lang-js prettyprint-override"><code>/function\([^()]*\){[^}]*}/gi </code></pre> <p>Which then replaces with <code>null</code></p>
[ { "answer_id": 74414730, "author": "KcH", "author_id": 11737596, "author_profile": "https://Stackoverflow.com/users/11737596", "pm_score": 2, "selected": false, "text": "values" }, { "answer_id": 74414870, "author": "narayan maity", "author_id": 6680751, "author_profile": "https://Stackoverflow.com/users/6680751", "pm_score": 2, "selected": true, "text": "const handleMultiSelectChange = (options) => {\n setMultiSelect(options);\n const values = options.map(\n (opt) => opt.value\n );\n setJobPreference([...values]);\n };\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15584743/" ]
74,414,777
<p>Is it possible to check if a prop Function is async or not?</p> <p>For example, here is a prop in my component:</p> <pre><code> callbackFunction: { type: Function, default: null, }, </code></pre> <p>How can I validate this and make sure that the passed in Function is declared as async?</p>
[ { "answer_id": 74415261, "author": "Naren", "author_id": 6516699, "author_profile": "https://Stackoverflow.com/users/6516699", "pm_score": 2, "selected": false, "text": " callbackFunction: {\n type: Function,\n validator(value) {\n if (value?.constructor?.name === 'AsyncFunction') {\n return true;\n } else {\n console.error('Function should be async');\n return false;\n }\n },\n default() {},\n },\n" }, { "answer_id": 74415628, "author": "Estus Flask", "author_id": 3731501, "author_profile": "https://Stackoverflow.com/users/3731501", "pm_score": 3, "selected": true, "text": "if (this.callbackFunction) \n await this.callbackFunction()\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16958679/" ]
74,414,778
<p>I'm trying to run my program:</p> <pre class="lang-py prettyprint-override"><code>from ursina import * from ursina.prefabs.first_person_controller import FirstPersonController app = Ursina() window.fullscreen = True class Voxel(Button): def __init__(self, colour, position = (0, 0, 0)): super().__init__( parent = scene, position = position, model = &quot;cube&quot;, orgin_y = 0.5, texture = &quot;white_cube&quot;, color = colour, ) def start_game(self): self.colour = color.white def input(self, key): if self.hovered: if key == &quot;right mouse up&quot;: voxel = Voxel(position = self.position + mouse.normal, colour = self.colour) if key == &quot;left mouse up&quot;: destroy(self) if key == &quot;0&quot;: self.colour = color.white if key == &quot;1&quot;: self.colour = color.lime for z in range(22): for x in range(22): voxel = Voxel(position = (x, 0, z), colour = color.lime) voxel.start_game() player = FirstPersonController() app.run() </code></pre> <p>I'm using python 3.10.6 and Idle.</p> <p>When I run the program it works as expected except when I choose green after I place a block it turn into white. If I spam click I get the error:</p> <pre><code> File &quot;C:\Users\game.py&quot;, line 24, in input voxel = Voxel(position = self.position + mouse.normal, colour = self.colour) AttributeError: 'Voxel' object has no attribute 'colour' </code></pre>
[ { "answer_id": 74416687, "author": "dskrypa", "author_id": 19070573, "author_profile": "https://Stackoverflow.com/users/19070573", "pm_score": 2, "selected": false, "text": "color" }, { "answer_id": 74421779, "author": "Lixt", "author_id": 11647955, "author_profile": "https://Stackoverflow.com/users/11647955", "pm_score": 0, "selected": false, "text": "voxel = Voxel(position = self.position + mouse.normal, colour = self.color)" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20487055/" ]
74,414,823
<h1>How to refer to dynamic sheet in Excel VBA instead of Sheet Name - Instead of &quot;Sheet16&quot;, i want to refer to the ActiveSheet, please see below</h1> <p>Sub Macro1()</p> <pre><code>Cells.Select Selection.Copy Sheets.Add After:=ActiveSheet ActiveSheet.Paste Application.CutCopyMode = False Selection.AutoFilter ActiveWorkbook.Worksheets(&quot;Sheet16&quot;).AutoFilter.Sort.SortFields.Clear ActiveWorkbook.Worksheets(&quot;Sheet16&quot;).AutoFilter.Sort.SortFields.Add2 Key:= _ Range(&quot;M1:M12&quot;), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption _ :=xlSortNormal With ActiveWorkbook.Worksheets(&quot;Sheet16&quot;).AutoFilter.Sort .Header = xlYes .MatchCase = False .Orientation = xlTopToBottom .SortMethod = xlPinYin .Apply End With </code></pre> <p>End Sub</p>
[ { "answer_id": 74416687, "author": "dskrypa", "author_id": 19070573, "author_profile": "https://Stackoverflow.com/users/19070573", "pm_score": 2, "selected": false, "text": "color" }, { "answer_id": 74421779, "author": "Lixt", "author_id": 11647955, "author_profile": "https://Stackoverflow.com/users/11647955", "pm_score": 0, "selected": false, "text": "voxel = Voxel(position = self.position + mouse.normal, colour = self.color)" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20487108/" ]
74,414,825
<p><strong>What does program solve:</strong><br /> Find palindrome from user input.</p> <p><strong>What issue to tweak:</strong><br /> How to make code accept sentence like <code>Rise to vote sir!</code> as Palindrome if we disregard punctuation and blank spaces. If you read it backwards it will be the same!</p> <p><strong>Things that I have tried:</strong> I tried to just save characters a-z, A-Z, and 0-9 into character-type array then proceed with the logic on it. But to no avail.</p> <p>I wish if <strong>someone</strong> could suggest where to tweak the following C snippet, in a way it can handle phrase or sentence to not include spaces, punctuation, and special characters within the computation of the code logic.</p> <pre><code>/* Search for a palindrome */ #include &lt;stdio.h&gt; #include &lt;ctype.h&gt; #define EOL '\n' #define TRUE 1 #define FALSE 0 int main() { int tag, count, countback, flag, loop = TRUE; char letter[80]; /* main loop */ while (loop) { /* anticipated palindrome */ flag = TRUE; /* read in the text */ printf(&quot;\nPlease enter a word, phrase, or sentence below:\n&quot;); for (count = 0; (letter[count] = getchar()) != EOL; ++count) ; /* test for end of program keyword END */ if ((toupper(letter[0]) == 'E') &amp;&amp; \ (toupper(letter[1]) == 'N') &amp;&amp; \ (toupper(letter[2]) == 'D')) break; tag = count - 1; /* carry out the search */ for ((count = 0, countback = tag); count &lt;= tag / 2; (++count, --countback)) { if (letter[count] != letter[countback]) { flag = FALSE; break; } } /* display message */ for (count = 0; count &lt;= tag; ++count) putchar(letter[count]); if (flag) printf(&quot; --&gt; IS a Palindrome!\n\n&quot;); else printf(&quot; --&gt; is NOT a Palindrome.\n\n&quot;); } /* end of main loop */ return 0; } </code></pre>
[ { "answer_id": 74415488, "author": "Clifford", "author_id": 168986, "author_profile": "https://Stackoverflow.com/users/168986", "pm_score": 3, "selected": true, "text": "!isalnum(letter[count])" }, { "answer_id": 74415819, "author": "chqrlie", "author_id": 4593267, "author_profile": "https://Stackoverflow.com/users/4593267", "pm_score": 1, "selected": false, "text": " // Test for not palindrome\n bool is_palindrome = true;\n int count = 0;\n int countback = text_length - 1;\n while (is_palindrome && count < countback) {\n unsigned char c1 = text[count++];\n if (isalnum(c1)) {\n unsigned char c2 = text[countback--];\n if (isalnum(c2)) {\n is_palindrome = (toupper(c1) == toupper(c2));\n } else {\n count--;\n }\n }\n }\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13633212/" ]
74,414,838
<p>Does anyone know how to move through one file to the other if they are in the same directory?</p> <p>Example: in file &quot;A.txt&quot; is written the name of the next file, meaning &quot;B.txt,&quot; then in &quot;B.txt&quot;, is written the name of the next file - &quot;C.txt,&quot; and the content of &quot;C.txt&quot; is &quot;A.txt,&quot; forming the chain &quot;A.txt&quot;-&quot;B.txt&quot;-&quot;C.txt&quot;. BUT, there might be any N amount of files, not only 3.</p> <p>I tried looping through the files, although I couldn't do anything with it.I have never worked with chaining files and their contests so i am completely lost,even one small advice would be appreciated.</p>
[ { "answer_id": 74415488, "author": "Clifford", "author_id": 168986, "author_profile": "https://Stackoverflow.com/users/168986", "pm_score": 3, "selected": true, "text": "!isalnum(letter[count])" }, { "answer_id": 74415819, "author": "chqrlie", "author_id": 4593267, "author_profile": "https://Stackoverflow.com/users/4593267", "pm_score": 1, "selected": false, "text": " // Test for not palindrome\n bool is_palindrome = true;\n int count = 0;\n int countback = text_length - 1;\n while (is_palindrome && count < countback) {\n unsigned char c1 = text[count++];\n if (isalnum(c1)) {\n unsigned char c2 = text[countback--];\n if (isalnum(c2)) {\n is_palindrome = (toupper(c1) == toupper(c2));\n } else {\n count--;\n }\n }\n }\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20487116/" ]
74,414,864
<p>My IDE is showing that navigationIcon is not a composable function. Other people are doing the same thing. I'm getting this error</p> <pre><code>@composable invocations can only happen from the context of an @composable function </code></pre> <pre class="lang-kotlin prettyprint-override"><code>@Composable fun AppBar(onClick: () -&gt; Unit){ TopAppBar( title = &quot;Princess World&quot;, navigationIcon = { IconButton(onClick = onClick) { Icon(imageVector = Icons.Default.Menu, contentDescription = null) } }, ) {} } </code></pre> <p>I'm unable to use composable functions inside of title and navigation icon {}</p> <pre class="lang-kotlin prettyprint-override"><code>@Composable fun AppBar(onClick: () -&gt; Unit){ TopAppBar(title = { }, navigationIcon = { }) { } } </code></pre>
[ { "answer_id": 74414937, "author": "z.y", "author_id": 19023745, "author_profile": "https://Stackoverflow.com/users/19023745", "pm_score": 2, "selected": false, "text": "@Composable\nfun AppBar(onClick: () -> Unit) {\n TopAppBar(\n title = { Text (text = \"Princess World\") },\n navigationIcon = {\n IconButton(onClick = onClick) {\n Icon(imageVector = Icons.Default.Menu, contentDescription = null)\n }\n }\n ) \n}\n" }, { "answer_id": 74416408, "author": "Gabriele Mariotti", "author_id": 2016562, "author_profile": "https://Stackoverflow.com/users/2016562", "pm_score": 2, "selected": true, "text": "{}" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14527579/" ]
74,414,880
<p>I have data as follows:</p> <pre><code>library(data.table) dat &lt;- fread(&quot;Variable_codes_2022 Variables_2022 Cat1_1 This_question Cat1_2 Other_question Cat2_1 One_question Cat2_2 Another_question Cat3_1 Some_question Cat3_2 Extra_question Cat3_3 This_question Cat4_1 One_question Cat4_2 Wrong_question&quot;) </code></pre> <p>What I would like to do, is to create a new column, that provides a unique new variable code, for matching variables. I started with creating a column that shows the duplicates, but this only gives <code>TRUE</code> for the second occurrence and not both. In addition, I then still have to give the <code>TRUE</code> values unique names.</p> <pre><code>dat$Common_codes_2022 &lt;- duplicated(dat[,2]) </code></pre> <p>How should I do this?</p> <p>Desired output:</p> <pre><code> Variable_codes_2022 Variables_2022 Common_codes_2022 1: Cat1_1 This_question Com_1 2: Cat1_2 Other_question 3: Cat2_1 One_question Com_2 4: Cat2_2 Another_question 5: Cat3_1 Some_question 6: Cat3_2 Extra_question 7: Cat3_3 This_question Com_1 8: Cat4_1 One_question Com_2 9: Cat4_2 Wrong_question </code></pre>
[ { "answer_id": 74414937, "author": "z.y", "author_id": 19023745, "author_profile": "https://Stackoverflow.com/users/19023745", "pm_score": 2, "selected": false, "text": "@Composable\nfun AppBar(onClick: () -> Unit) {\n TopAppBar(\n title = { Text (text = \"Princess World\") },\n navigationIcon = {\n IconButton(onClick = onClick) {\n Icon(imageVector = Icons.Default.Menu, contentDescription = null)\n }\n }\n ) \n}\n" }, { "answer_id": 74416408, "author": "Gabriele Mariotti", "author_id": 2016562, "author_profile": "https://Stackoverflow.com/users/2016562", "pm_score": 2, "selected": true, "text": "{}" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8071608/" ]
74,414,889
<p>In <a href="https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion-Builtins.html" rel="nofollow noreferrer">Programmable Completion Builtins</a> complete command, there is a -I argument. It said:</p> <blockquote> <p>The -I option indicates that other supplied options and actions should apply to completion on <strong>the initial non-assignment word on the line</strong>, or <strong>after a command delimiter</strong> such as ‘;’ or ‘|’, which is usually command name completion.</p> </blockquote> <p>I don't understand &quot;the initial non-assignment word on the line&quot; , can someone give an example.</p> <p>I set a complete by <code>complete -W 'AA BB' -I</code>, It worked &quot;after a command delimiter&quot;</p> <pre><code>root@aliecs:~# complete -W 'AA BB' -I root@aliecs:~# ls &amp;&amp;&lt;tab&gt;&lt;tab&gt; AA BB root@aliecs:~# ls ;&lt;tab&gt;&lt;tab&gt; AA BB root@aliecs:~# ls |&lt;tab&gt;&lt;tab&gt; AA BB root@aliecs:~# ls ||&lt;tab&gt;&lt;tab&gt; AA BB </code></pre> <p>I want an example of &quot;the initial non-assignment word on the line&quot;</p>
[ { "answer_id": 74415063, "author": "tinyhare", "author_id": 5232323, "author_profile": "https://Stackoverflow.com/users/5232323", "pm_score": 0, "selected": false, "text": "root@aliecs:~# complete -W 'AA BB BC' -I\nroot@aliecs:~# foo=1 B<tab><tab>\nBB BC \nroot@aliecs:~# B<tab><tab>\nBB BC \n" }, { "answer_id": 74415156, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 2, "selected": true, "text": "=" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5232323/" ]
74,414,914
<p>I have a file that looks like this:</p> <pre class="lang-none prettyprint-override"><code>1234:AnneShirly:anneshirley@seneca.ca:4:5\[SRT111,OPS105,OPS110,SPR100,ENG100\] 3217:Illyas:illay@seneca.ca:2:4\[SRT211,OPS225,SPR200,ENG200\] 1127:john Marcus:johnmarcus@seneca.ca:1:4\[SRT111,OPS105,SPR100,ENG100\] 0001:Amin Malik:amin_malik@seneca.ca:1:3\[OPS105,SPR100,ENG100\] </code></pre> <p>I want to be able to ask the user for an input(the student number at the beginning of each line) and then ask which course they want to delete(the course codes are the list). So the program would delete the course from the list in the student number without deleting other instances of the course. Cause other students have the same courses.</p> <pre><code>studentid = input(&quot;enter studentid&quot;) course = input(&quot;enter the course to delete&quot;) with open(&quot;studentDatabase.dat&quot;) as file: f = file.readlines() with open(&quot;studentDatabase.dat&quot;,&quot;w&quot;) as file: for line in lines: if line.find(course) == -1: file.write(line) </code></pre> <p>This just deletes the whole line but I only want to delete the course</p>
[ { "answer_id": 74415175, "author": "gioco a cose", "author_id": 15219507, "author_profile": "https://Stackoverflow.com/users/15219507", "pm_score": 1, "selected": false, "text": "studentid = input(\"enter studentid\")\ncourse = input(\"enter the course to delete\")\nwith open(\"studentDatabase.dat\") as file:\n f = file.readlines()\nwith open(\"studentDatabase.dat\",\"w\") as file:\n for line in lines:\n if studentid in line: # Check if it's the right sudent \n line = line.replace(course, \"\") # replace course with nothing\n file.write(line)\n" }, { "answer_id": 74415186, "author": "AirSquid", "author_id": 10789207, "author_profile": "https://Stackoverflow.com/users/10789207", "pm_score": 2, "selected": false, "text": ".dat" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
74,414,936
<p>I want to write a program where a user tells me an integer(n) and i calculate The sum of 1+(1-2)+(1-2+3)+(1-2+3-n)... where even integers are -k and odd integers are +k.</p> <p>Ive made a function which does that But the sum is never correct. For example for n=2 it should be sum=0 but shows sum=-1 for n=3 should be sum=+2 but i shows sum=3. (Ignore the debugging printfs)</p> <pre><code>#include &lt;stdio.h&gt; int athroismaAkolouthias(int n); // i sinartisi me tin opoia ypologizete to athroisma akolouthias 1+(1-2)+(1-2+3)+(1-2+3-4)..... int main(){ int n; printf(&quot;give n: &quot;); scanf(&quot;%d&quot;, &amp;n); printf(&quot;the sum is %d&quot;, athroismaAkolouthias(n)); } int athroismaAkolouthias(int n){ int sum1=0, sum2=0,sum=0; int i, temp, j; for (i=1; i&lt;=n; i++){ for (j=1; j&lt;=i; j++){ temp=j; } if (i%2==0){sum=sum-temp; printf(&quot;test1 %d%d&quot;,sum,temp);} else{sum=temp; printf(&quot;test2 %d%d&quot;,sum,temp);} } return sum; } </code></pre>
[ { "answer_id": 74415175, "author": "gioco a cose", "author_id": 15219507, "author_profile": "https://Stackoverflow.com/users/15219507", "pm_score": 1, "selected": false, "text": "studentid = input(\"enter studentid\")\ncourse = input(\"enter the course to delete\")\nwith open(\"studentDatabase.dat\") as file:\n f = file.readlines()\nwith open(\"studentDatabase.dat\",\"w\") as file:\n for line in lines:\n if studentid in line: # Check if it's the right sudent \n line = line.replace(course, \"\") # replace course with nothing\n file.write(line)\n" }, { "answer_id": 74415186, "author": "AirSquid", "author_id": 10789207, "author_profile": "https://Stackoverflow.com/users/10789207", "pm_score": 2, "selected": false, "text": ".dat" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20133060/" ]
74,414,944
<p>I have two problems that are giving me issues. First issue:</p> <pre><code>import requests import json name = 'Poe' poem = 'Raven' URL = f'https://poetrydb.org/author,title/{name};{poem}' json_object = json.loads(requests.get(URL).text) text=str(json_object) with open(&quot;choice_1.json&quot;, &quot;w&quot;) as outfile: outfile.write(json_object) </code></pre> <p>running the code gives me: TypeError: write() argument must be str, not list</p> <p>this is a json object going into a json file, what is the problem?</p> <p>second problem</p> <p>I want the saved file to read the same as the poem's name. how do I get the 'poem' variable to used for naming the new file? something like a print function:</p> <pre><code>with open(&quot;{poem}.json&quot;, &quot;w&quot;) as outfile: outfile.write(json_object) </code></pre> <p>problem 1 I tried converting the json files into a string with str() but it still didn't work.</p> <pre><code>URL = f'https://poetrydb.org/author,title/{name};{poem}' json_object = json.loads(requests.get(URL).text) text=str(json_object) with open(&quot;choice_1.json&quot;, &quot;w&quot;) as outfile: outfile.write(text) </code></pre> <p>while this creates the file it comes out like this: [{'title': 'The Raven', 'author': 'Edgar Allan Poe', 'lines': ['Once upon a midnight dreary, while I</p> <p>it's all red and underlined like there is an issue. does this actually work?</p>
[ { "answer_id": 74415175, "author": "gioco a cose", "author_id": 15219507, "author_profile": "https://Stackoverflow.com/users/15219507", "pm_score": 1, "selected": false, "text": "studentid = input(\"enter studentid\")\ncourse = input(\"enter the course to delete\")\nwith open(\"studentDatabase.dat\") as file:\n f = file.readlines()\nwith open(\"studentDatabase.dat\",\"w\") as file:\n for line in lines:\n if studentid in line: # Check if it's the right sudent \n line = line.replace(course, \"\") # replace course with nothing\n file.write(line)\n" }, { "answer_id": 74415186, "author": "AirSquid", "author_id": 10789207, "author_profile": "https://Stackoverflow.com/users/10789207", "pm_score": 2, "selected": false, "text": ".dat" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20368158/" ]
74,414,951
<p>I have a large dataset where I have a problem similar to the one below. I have something like this:</p> <pre><code>dummydf &lt;- data.frame(country = c(&quot;USA&quot;, &quot;USA&quot;), state = c(&quot;Oregon&quot;, &quot;California&quot;), name = c(&quot;anne&quot;, &quot;paul&quot;), family = c(&quot;stevens&quot;, &quot;williams&quot;), votes = c(10, 50.2), city = c(&quot;london&quot;, &quot;berlin&quot;), age = c(10, 50), `name...2` = c(&quot;joseph&quot;, &quot;vincent&quot;), `family...2` = c(&quot;ramos&quot;, &quot;williams&quot;), `votes...2` = c(15, 62), `city...2` = c(&quot;lisbon&quot;, &quot;berlin&quot;), `age...2` = c(77, 43), `name...3` = c(&quot;johanna&quot;, &quot;paul&quot;), `family...3` = c(&quot;santos&quot;, &quot;ramos&quot;), `votes...3` = c(.61, 54.2), `city...3` = c(&quot;london&quot;, &quot;berlin&quot;), `age...3` = c(56, 54), `name...4` = c(&quot;sara&quot;, &quot;edith&quot;), `family...4` = c(&quot;stevens&quot;, &quot;sanchez&quot;), `votes...4` = c(2.9, 54.1), `city...4` = c(&quot;lisbon&quot;, &quot;paris&quot;), `age...4` = c(20, 25), `name...5` = c(&quot;thomas&quot;, &quot;paul&quot;), `family...5` = c(&quot;santos&quot;, &quot;ramos&quot;), `votes...5` = c(1.2, 5.2), `city...5` = c(&quot;lisbon&quot;, &quot;toronto&quot;), `age...5` = c(45, 80)) </code></pre> <p>or maybe this is easier to understand:</p> <pre><code>country state name family votes city age name...2 family...2 votes...2 city...2 age...2 name...3 family...3 votes...3 city...3 age...3 name...4 family...4 votes...4 1 USA Oregon anne stevens 10.0 london 10 joseph ramos 15 lisbon 77 johanna santos 0.61 london 56 sara stevens 2.9 2 USA California paul williams 50.2 berlin 50 vincent williams 62 berlin 43 paul ramos 54.20 berlin 54 edith sanchez 54.1 city...4 age...4 name...5 family...5 votes...5 city...5 age...5 1 lisbon 20 thomas santos 1.2 lisbon 45 2 paris 25 paul ramos 5.2 toronto 80 </code></pre> <p>So the issue here is that all the columns except <code>country</code> and <code>state</code> are multipled 5 times. Ideally I want something like this:</p> <pre><code>idealdf name family votes city age state country 1 anne stevens 10.00 london 10 Oregon USA 2 paul williams 50.20 berlin 50 California USA 3 joseph ramos 15.00 lisbon 77 Oregon USA 4 vincent williams 62.00 berlin 43 California USA 5 johanna santos 0.61 london 56 Oregon USA 6 paul ramos 54.20 berlin 54 California USA 7 sara stevens 2.90 lisbon 20 Oregon USA 8 edith sanchez 54.10 paris 25 California USA 9 thomas santos 1.20 lisbon 45 Oregon USA 10 paul ramos 5.20 toronto 80 California USA </code></pre> <p>In the original dataset I have it multiple several hundred times and not 5 but the issue is the same. I tried a few things with pivoting and trying to clean the names with regular expressions but nothing really works well. Any pointers would be amazing - thanks!</p>
[ { "answer_id": 74415117, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 3, "selected": true, "text": "pivot_longer" }, { "answer_id": 74415830, "author": "Robert Hacken", "author_id": 2094893, "author_profile": "https://Stackoverflow.com/users/2094893", "pm_score": 1, "selected": false, "text": "nam <- sub('...\\\\d$', '', names(dummydf))\nas.data.frame(sapply(unique(nam), function(x) \n unlist(dummydf[nam==x], use.names=F), simplify=F))\n\n# country state name family votes city age\n# 1 USA Oregon anne stevens 10.00 london 10\n# 2 USA California paul williams 50.20 berlin 50\n# 3 USA Oregon joseph ramos 15.00 lisbon 77\n# 4 USA California vincent williams 62.00 berlin 43\n# 5 USA Oregon johanna santos 0.61 london 56\n# 6 USA California paul ramos 54.20 berlin 54\n# 7 USA Oregon sara stevens 2.90 lisbon 20\n# 8 USA California edith sanchez 54.10 paris 25\n# 9 USA Oregon thomas santos 1.20 lisbon 45\n# 10 USA California paul ramos 5.20 toronto 80\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13311198/" ]
74,414,981
<p>I have a path that I draw well on the canvas.</p> <p>But I can't move it.</p> <pre><code> const ctx = canvas.getContext('2d') const render = () =&gt; { ctx.resetTransform() ctx.clearRect(0, 0, innerWidth, innerHeight) ctx.beginPath() ctx.moveTo(30, 50) ctx.lineTo(150, 100) ctx.translate(1000,100) // not working ctx.strokeStyle = 'red' ctx.stroke(); } render() </code></pre>
[ { "answer_id": 74415117, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 3, "selected": true, "text": "pivot_longer" }, { "answer_id": 74415830, "author": "Robert Hacken", "author_id": 2094893, "author_profile": "https://Stackoverflow.com/users/2094893", "pm_score": 1, "selected": false, "text": "nam <- sub('...\\\\d$', '', names(dummydf))\nas.data.frame(sapply(unique(nam), function(x) \n unlist(dummydf[nam==x], use.names=F), simplify=F))\n\n# country state name family votes city age\n# 1 USA Oregon anne stevens 10.00 london 10\n# 2 USA California paul williams 50.20 berlin 50\n# 3 USA Oregon joseph ramos 15.00 lisbon 77\n# 4 USA California vincent williams 62.00 berlin 43\n# 5 USA Oregon johanna santos 0.61 london 56\n# 6 USA California paul ramos 54.20 berlin 54\n# 7 USA Oregon sara stevens 2.90 lisbon 20\n# 8 USA California edith sanchez 54.10 paris 25\n# 9 USA Oregon thomas santos 1.20 lisbon 45\n# 10 USA California paul ramos 5.20 toronto 80\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18642505/" ]
74,414,987
<p>I came up with this logic to count the duplicate 1 take input for list length 2 take input of list 3 search in list for the values from zero to last index increment the counter. I am getting error can anyone help to fix it, I know my this not accurate way to do this can someone help me out</p> <pre><code>n = int(input()) l1=[] for i in range(n): l1.append(input()) print(l1) count1=0 count2=0 count3=0 count4=0 for j in range(n): if 1 in l1[0,n-1]: count1 =count1+1 elif 2 in l1(0,n-1): count2=count2+1 elif 3 in l1(0,n-1): count3= count3+1 elif 4 in l1(0,n-1): count4=count4+1 print(count1) </code></pre> <p>input 4 1 1 2 3 4 output should be 2</p>
[ { "answer_id": 74415021, "author": "thedemons", "author_id": 13253010, "author_profile": "https://Stackoverflow.com/users/13253010", "pm_score": 1, "selected": false, "text": "set()" }, { "answer_id": 74415078, "author": "sourin", "author_id": 14912756, "author_profile": "https://Stackoverflow.com/users/14912756", "pm_score": -1, "selected": false, "text": "data = [1,2,3,4,1,4]\nprint(\"Count of 1 =\", data.count(1))\nprint(\"Count of 2 =\", data.count(2))\nprint(\"Count of 3 =\", data.count(3))\nprint(\"Count of 4 =\", data.count(4))\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20166957/" ]
74,414,992
<p>I'm new to React, and I'm trying to make a recpie app with react, right know I want to save the data in json file from the add form. so I can save the data but when I want to redirect the user to the home page using useEffict with navigate. I can't go to the create page when adding navigate to the useEffict.</p> <p>Create file code:</p> <pre><code>import { useEffect, useRef, useState } from &quot;react&quot;; import { useNavigate } from &quot;react-router-dom&quot;; import { useFetch } from &quot;../../hooks/useFetch&quot;; // Styles import &quot;./Create.css&quot;; export default function Create() { const [title, setTitle] = useState(&quot;&quot;); const [method, setMethod] = useState(&quot;&quot;); const [cookingTime, setCookingTime] = useState(&quot;&quot;); const [newIngredient, setNewIngredient] = useState(&quot;&quot;); const [ingredients, setIngredients] = useState([]); const { postData, data } = useFetch(&quot;http://localhost:3000/recipes&quot;, &quot;POST&quot;); const ingredientsInput = useRef(null); const navigate = useNavigate(); // Methods const handleSubmit = (e) =&gt; { e.preventDefault(); postData({ title, ingredients, method, cookingTime: cookingTime + &quot; minutes&quot;, }); }; const handleAdd = (e) =&gt; { e.preventDefault(); const ing = newIngredient.trim(); if (ing &amp;&amp; !ingredients.includes(ing)) { setIngredients((preIng) =&gt; [...preIng, ing]); } setNewIngredient(&quot;&quot;); ingredientsInput.current.focus(); }; useEffect(() =&gt; { if (data) { navigate(&quot;/&quot;); console.log(data); } }, [data, navigate]); return ( &lt;div className=&quot;create&quot;&gt; &lt;form onSubmit={handleSubmit}&gt; &lt;label&gt; &lt;span&gt;Recipe Title:&lt;/span&gt; &lt;input type=&quot;text&quot; onChange={(e) =&gt; setTitle(e.target.value)} value={title} required /&gt; &lt;/label&gt; &lt;label&gt; &lt;span&gt;Recipe ingredients:&lt;/span&gt; &lt;div className=&quot;ingredients&quot;&gt; &lt;input type=&quot;text&quot; onChange={(e) =&gt; setNewIngredient(e.target.value)} value={newIngredient} ref={ingredientsInput} /&gt; &lt;button onClick={handleAdd} className=&quot;btn&quot;&gt; Add &lt;/button&gt; &lt;/div&gt; &lt;/label&gt; {ingredients.length &gt; -1 &amp;&amp; ( &lt;p&gt; Current ingredients:{&quot; &quot;} {ingredients.map((ing) =&gt; ( &lt;span key={ing}&gt;{ing}, &lt;/span&gt; ))} &lt;/p&gt; )} &lt;label&gt; &lt;span&gt;Recipe Method:&lt;/span&gt; &lt;textarea onChange={(e) =&gt; setMethod(e.target.value)} value={method} required /&gt; &lt;/label&gt; &lt;label&gt; &lt;span&gt;Recipe Time (minutes):&lt;/span&gt; &lt;input type=&quot;number&quot; onChange={(e) =&gt; setCookingTime(e.target.value)} value={cookingTime} required /&gt; &lt;/label&gt; &lt;button className=&quot;btn&quot;&gt;Submit&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; ); } </code></pre> <p>useFetch file code: import { useState, useEffect } from &quot;react&quot;;</p> <pre><code>export const useFetch = (url, method = &quot;GET&quot;) =&gt; { const [data, setData] = useState(null); const [isPending, setIsPending] = useState(false); const [error, setError] = useState(null); const [option, setOption] = useState(null); const postData = (data) =&gt; { setOption({ method: &quot;POST&quot;, headers: { &quot;Content-Type&quot;: &quot;application/json&quot;, }, body: JSON.stringify(data), }); }; useEffect(() =&gt; { const controller = new AbortController(); const fetchData = async (fetchOption) =&gt; { setIsPending(true); try { const res = await fetch(url, { ...fetchOption, signal: controller.signal, }); if (!res.ok) { throw new Error(res.statusText); } const data = await res.json(); setIsPending(false); setData(data); setError(null); } catch (err) { if (err.name === &quot;AbortError&quot;) { console.log(&quot;the fetch was aborted&quot;); } else { setIsPending(false); setError(&quot;Could not fetch the data&quot;); } } }; if (method === &quot;GET&quot;) { fetchData(); } if (method === &quot;POST&quot;) { fetchData(option); } return () =&gt; { controller.abort(); }; }, [url, option, method]); return { data, isPending, error, postData }; }; </code></pre> <p>I don't know from where the issue came.</p>
[ { "answer_id": 74415040, "author": "Ibrahim shamma", "author_id": 12613405, "author_profile": "https://Stackoverflow.com/users/12613405", "pm_score": 0, "selected": false, "text": "const [recipes, setReceipies] = useState();\n\nuseEffect(async ()=> { const {data} = awawit useFetch(\"http://localhost:3000/recipes\", \"POST\")\nsetReceipies(data);\n},[])\nnavigate(\"/\");\n},[recipes]);\n" }, { "answer_id": 74415134, "author": "Andrew Grini", "author_id": 6571753, "author_profile": "https://Stackoverflow.com/users/6571753", "pm_score": 0, "selected": false, "text": "const history = createBrowserHistory()\nhistory.push(`/`)" }, { "answer_id": 74418345, "author": "عزوز الحارثي", "author_id": 20487260, "author_profile": "https://Stackoverflow.com/users/20487260", "pm_score": 2, "selected": true, "text": " const [option, setOptions] = useState(null);\n if (method === \"POST\") {\n fetchData(option);\n }\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20487260/" ]
74,414,995
<p>Example is here, should work in online compilers:</p> <pre class="lang-cs prettyprint-override"><code>internal class Program { static void Main(string[] args) { var i1 = new Item(); i1.Val1 = 1; i1.Val2 = 2.1; var i2 = new Item(); i2.Val1 = 1; i2.Val2 = 1.5; var i3 = new Item(); i3.Val1 = 3; i3.Val2 = 0.3; var list = new List&lt;Item&gt; { i1, i2, i3 }; var grouped = list.GroupBy(x =&gt; x.Val1); Program p = new Program(); foreach(var group in grouped) p.Func(group); } public void Func(IGrouping&lt;int, Item&gt; list) { list.OrderBy(x =&gt; x.Val2); //list will be ordered, but not saved list = (IGrouping&lt;int, Item&gt;)list.OrderBy(x =&gt; x.Val2); //exception } } public class Item { public int Val1 { get; set; } public double Val2 { get; set; } } </code></pre> <p>It's simplified code of what I'm trying to do - I need to order list inside <code>Func</code>, but I have no idea how. First line works in theory, but since it's not a void it's not working in practice - list is not actually ordered.</p> <p>Second line should work, actually Visual Studio suggested that, but it throws runtime exception - <code>Unable to cast object of type System.Linq.OrderedEnumerable to System.Linq.IGrouping</code>.</p> <p>I'm out of ideas for the time being, but there is no way of bypassing it - I absolutely need to order it there.</p> <p>Edit</p> <p>My current solution is to use <code>Select(x =&gt; x)</code> to flatten the <code>IGrouping</code> to normal <code>List</code>, this way I can easily order it and edit values without losing reference to <code>grouped</code>. If you really want to keep <code>IGrouping</code> then you are out of luck, does not seem to be possible.</p>
[ { "answer_id": 74415040, "author": "Ibrahim shamma", "author_id": 12613405, "author_profile": "https://Stackoverflow.com/users/12613405", "pm_score": 0, "selected": false, "text": "const [recipes, setReceipies] = useState();\n\nuseEffect(async ()=> { const {data} = awawit useFetch(\"http://localhost:3000/recipes\", \"POST\")\nsetReceipies(data);\n},[])\nnavigate(\"/\");\n},[recipes]);\n" }, { "answer_id": 74415134, "author": "Andrew Grini", "author_id": 6571753, "author_profile": "https://Stackoverflow.com/users/6571753", "pm_score": 0, "selected": false, "text": "const history = createBrowserHistory()\nhistory.push(`/`)" }, { "answer_id": 74418345, "author": "عزوز الحارثي", "author_id": 20487260, "author_profile": "https://Stackoverflow.com/users/20487260", "pm_score": 2, "selected": true, "text": " const [option, setOptions] = useState(null);\n if (method === \"POST\") {\n fetchData(option);\n }\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74414995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
74,415,044
<p>i am experimenting with a multi-column magazine style layout for an editorial project.</p> <p>Due to the increasing size of the monitors, i wanted to use of all available inches of the monitor by creating layouts very similar to paper magazine (two or three columns per page).</p> <p>I am using TipTap editor for article management (as it returns very clean HTML code) and in frontend i get this html output:</p> <p><a href="https://i.stack.imgur.com/peD2T.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/peD2T.png" alt="enter image description here" /></a></p> <p>I am using the css columns class to split the article in two:</p> <pre><code> article { columns: 2; } </code></pre> <p>But the result is this: <a href="https://i.stack.imgur.com/DWJac.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DWJac.png" alt="enter image description here" /></a></p> <p>I would like to divide all the <strong>h2</strong> as settling paragraphs, so that i could have the chapter exploded horizontally, for example like this: <a href="https://i.stack.imgur.com/EAX1Y.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EAX1Y.jpg" alt="enter image description here" /></a></p> <p>Using Pseudo-classes is it possible to intercept H2?</p>
[ { "answer_id": 74415040, "author": "Ibrahim shamma", "author_id": 12613405, "author_profile": "https://Stackoverflow.com/users/12613405", "pm_score": 0, "selected": false, "text": "const [recipes, setReceipies] = useState();\n\nuseEffect(async ()=> { const {data} = awawit useFetch(\"http://localhost:3000/recipes\", \"POST\")\nsetReceipies(data);\n},[])\nnavigate(\"/\");\n},[recipes]);\n" }, { "answer_id": 74415134, "author": "Andrew Grini", "author_id": 6571753, "author_profile": "https://Stackoverflow.com/users/6571753", "pm_score": 0, "selected": false, "text": "const history = createBrowserHistory()\nhistory.push(`/`)" }, { "answer_id": 74418345, "author": "عزوز الحارثي", "author_id": 20487260, "author_profile": "https://Stackoverflow.com/users/20487260", "pm_score": 2, "selected": true, "text": " const [option, setOptions] = useState(null);\n if (method === \"POST\") {\n fetchData(option);\n }\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4948683/" ]
74,415,058
<p>I would like to produce histograms with density lines for all my numeric columns, and facet them by another column.</p> <p>Using the <a href="https://en.wikipedia.org/wiki/Iris_flower_data_set" rel="nofollow noreferrer">Iris data set</a> as an example, I would like to produce histograms for <code>Sepal.Length</code>, etc., with facets for each of <code>Species</code>.</p> <p>This is what I have tried:</p> <pre><code>for (i in colnames(subset(iris, select = -`Species`))) { plot= ggplot(iris, aes(x= i))+ geom_histogram()+ geom_density(colour = &quot;blue&quot;, size = 1) + facet_wrap(~ Species, scales = &quot;free&quot;) print(plot) } </code></pre> <p>I also tried</p> <pre><code>for (i in colnames(subset(iris, select = -`Species`))) { plot= ggplot(subset(iris, select = -`Species`), aes(x= i))+ geom_histogram()+ geom_density(colour = &quot;blue&quot;, size = 1) + facet_wrap(~ iris$Species, scales = &quot;free&quot;) print(plot) } </code></pre> <p>The error I get is</p> <blockquote> <p>Error in <code>f()</code>: StatBin requires a continuous x variable: the x variable is discrete. Perhaps you want stat=&quot;count&quot;?</p> </blockquote> <p>Do I need to put something in the <code>geom_histogram()</code> command?</p>
[ { "answer_id": 74415163, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 3, "selected": true, "text": "library(tidyverse)\nirislong= pivot_longer(iris, cols = -Species) \nggplot(irislong, aes(x= value, fill= Species, alpha = 0.4))+ \n geom_histogram(aes(y = ..density..))+ \n geom_density(colour = \"blue\", size = 1)+ \n facet_wrap(~ name, scales = \"free\")\n" }, { "answer_id": 74415382, "author": "Mark Davies", "author_id": 12452893, "author_profile": "https://Stackoverflow.com/users/12452893", "pm_score": 0, "selected": false, "text": "aes_string" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12452893/" ]
74,415,075
<p>I wrote the code in general,but how can ı make a container that changes color with the first pink,then red, green,blue and again pink,then red, green,blue every time ı click on a container using inkwell?</p> <pre class="lang-dart prettyprint-override"><code>import 'package:flutter/material.dart'; void main() { runApp( MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold( body: MyApp(), ), ), ); } class MyApp extends StatefulWidget { @override _MyAppState createState() =&gt; _MyAppState(); } class _MyAppState extends State&lt;MyApp&gt; { int index = 0; List&lt;Color&gt; mycolors = [ Colors.pink, Colors.red, Colors.green, Colors.blue, ]; @override Widget build(BuildContext context) { return Center( child: Wrap(children: [ InkWell( child: Container( alignment: Alignment.center, margin: EdgeInsets.all(5), height: 100, width: 100, ), onTap: () { //how canı write a code? }), ])); } } </code></pre>
[ { "answer_id": 74415163, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 3, "selected": true, "text": "library(tidyverse)\nirislong= pivot_longer(iris, cols = -Species) \nggplot(irislong, aes(x= value, fill= Species, alpha = 0.4))+ \n geom_histogram(aes(y = ..density..))+ \n geom_density(colour = \"blue\", size = 1)+ \n facet_wrap(~ name, scales = \"free\")\n" }, { "answer_id": 74415382, "author": "Mark Davies", "author_id": 12452893, "author_profile": "https://Stackoverflow.com/users/12452893", "pm_score": 0, "selected": false, "text": "aes_string" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18917371/" ]
74,415,124
<p>I wrote a program to compare numbers and get the minimum one of each couple. First number on input is count of couples and the other ones are the numbers just to be compared with each other 2 by 2. When i execute and give the input the last number on the list is not included. I wanna know why and how to fix it.</p> <p>There is my code.</p> <pre class="lang-py prettyprint-override"><code>class Solution: def __init__(self): self.iput = input('Enter the numbers: ') self.num_list = self.iput.split() def min_of_two(self): result = '' for i in range(0,int(self.num_list.pop(0)) * 2 ,2): result += str(min(self.num_list[i], self.num_list[i+1])) + ' ' return result x = Solution() x.min_of_two() </code></pre> <p>When i execute this and gave the input</p> <pre class="lang-py prettyprint-override"><code>3 5 3 2 8 100 15 </code></pre> <p>The output is</p> <pre><code>'3 2 100 ' </code></pre> <p>instead of</p> <pre><code>'3 2 15 ' </code></pre>
[ { "answer_id": 74415234, "author": "thebjorn", "author_id": 75103, "author_profile": "https://Stackoverflow.com/users/75103", "pm_score": 3, "selected": true, "text": "inp = [3, 5, 3, 2, 8, 100, 15]\n" }, { "answer_id": 74415330, "author": "frouLet", "author_id": 10691339, "author_profile": "https://Stackoverflow.com/users/10691339", "pm_score": 0, "selected": false, "text": "def min_of_two(self):\n result = ''\n for i in range(0,int(self.num_list.pop(0)) * 2 ,2):\n result += str(min(int(self.num_list[i]), int(self.num_list[i+1]))) + ' '\n return result\n" }, { "answer_id": 74415594, "author": "Mustang", "author_id": 19856929, "author_profile": "https://Stackoverflow.com/users/19856929", "pm_score": -1, "selected": false, "text": "class Solution:\n\n def __init__(self):\n self.iput = input('Enter the numbers: ')\n self.num_list = self.iput.split() \n \n def min_of_two(self):\n result = ''\n for i in range(0,int(self.num_list.pop(0)) * 2 ,2):\n\n # change self.num_list[i] & self.num_list[i + 1] from str to int\n result += str(min(int(self.num_list[i]), int(self.num_list[i+1]))) + ' '\n \n return result\nx = Solution()\nprint(x.min_of_two())\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10691339/" ]
74,415,133
<p>I am trying to work with nginx in my express app and I'm following the tutorial here</p> <p><a href="https://cloud.google.com/community/tutorials/deploy-react-nginx-cloud-run" rel="nofollow noreferrer">https://cloud.google.com/community/tutorials/deploy-react-nginx-cloud-run</a></p> <p>then at the end I saw this command</p> <pre><code>CMD sh -c &quot;envsubst '\$PORT' &lt; /etc/nginx/conf.d/configfile.template &gt; /etc/nginx/conf.d/default.conf &amp;&amp; nginx -g 'daemon off;'&quot; </code></pre> <p>Please what does the above command do?</p> <p>Most specifically what does <code>&quot;envsubst '\$PORT' &lt; /etc/nginx/conf.d/configfile.template &gt; /etc/nginx/conf.d/default.conf &amp;&amp; nginx -g 'daemon off;'&quot;</code> do?</p> <p>Also, how do I run another command after that command above, because it seems I can't have multiple <code>CMD</code> statements. I need to run the below after that last command</p> <p><code>CMD[&quot;node&quot;,&quot;server.js&quot;]</code></p>
[ { "answer_id": 74415231, "author": "Florian Burel", "author_id": 2218839, "author_profile": "https://Stackoverflow.com/users/2218839", "pm_score": 1, "selected": false, "text": "sh -c" }, { "answer_id": 74415891, "author": "tripleee", "author_id": 874188, "author_profile": "https://Stackoverflow.com/users/874188", "pm_score": 3, "selected": true, "text": "sh -c" }, { "answer_id": 74420878, "author": "David Maze", "author_id": 10008173, "author_profile": "https://Stackoverflow.com/users/10008173", "pm_score": 1, "selected": false, "text": "CMD sh -c '...'" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15155716/" ]
74,415,154
<p>I have an ionic project that I haven't updated for some time.</p> <p>The project worked well and I installed the ionic app on many devices.</p> <p>Today I downloaded the code from git hub and then run the command <code>npm install</code> but the command ended with dependencies errors:</p> <pre><code>MacBook-Pro-di-Silvia:scorekeeper gottasilvia$ npm install npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: scorekeeper@0.0.1 npm ERR! Found: rxjs@6.6.7 npm ERR! node_modules/rxjs npm ERR! rxjs@&quot;^6.3.3&quot; from the root project npm ERR! npm ERR! Could not resolve dependency: npm ERR! peer rxjs@&quot;^5.5.0&quot; from @angular/core@5.0.0 npm ERR! node_modules/@angular/core npm ERR! @angular/core@&quot;5.0.0&quot; from the root project npm ERR! peer @angular/core@&quot;5.0.0&quot; from @angular/common@5.0.0 npm ERR! node_modules/@angular/common npm ERR! @angular/common@&quot;5.0.0&quot; from the root project npm ERR! npm ERR! Fix the upstream dependency conflict, or retry npm ERR! this command with --force, or --legacy-peer-deps npm ERR! to accept an incorrect (and potentially broken) dependency resolution. npm ERR! npm ERR! See /Users/gottasilvia/.npm/eresolve-report.txt for a full report. npm ERR! A complete log of this run can be found in: npm ERR! /Users/gottasilvia/.npm/_logs/2022-11-12T17_16_01_363Z-debug-0.log </code></pre> <p>I tried to follow the suggested commands but the result did not change.</p> <p>How can I install and update all the packages without any dependency issue?</p> <p>Many thanks</p>
[ { "answer_id": 74415231, "author": "Florian Burel", "author_id": 2218839, "author_profile": "https://Stackoverflow.com/users/2218839", "pm_score": 1, "selected": false, "text": "sh -c" }, { "answer_id": 74415891, "author": "tripleee", "author_id": 874188, "author_profile": "https://Stackoverflow.com/users/874188", "pm_score": 3, "selected": true, "text": "sh -c" }, { "answer_id": 74420878, "author": "David Maze", "author_id": 10008173, "author_profile": "https://Stackoverflow.com/users/10008173", "pm_score": 1, "selected": false, "text": "CMD sh -c '...'" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13815409/" ]
74,415,166
<p>You are given a string my_string and a positive integer k. Write code that prints the first substring of my_string of length k all of whose characters are identical (lowercase and uppercase are different). If none such exists, print an appropriate error message (see Example 4 below). In particular, the latter holds when my_string is empty.</p> <p>Example: For the input my_string = “abaadddefggg”, k = 3 the output is For length 3, found the substring ddd! Example: For the input my_string = “abaadddefggg”, k = 9 the output is Didn't find a substring of length 9</p> <p>this is my attempt:</p> <pre><code>my_string = 'abaadddefggg' k = 3 s='' for i in range(len(my_string) - k + 1): if my_string[i:i+k] == my_string[i] * k: s = my_string[i:i+k] if len(s) &gt; 0: print(f'For length {k}, found the substring {s}!') else: print(f&quot;Didn't find a substring of length {k}&quot;) </code></pre>
[ { "answer_id": 74415231, "author": "Florian Burel", "author_id": 2218839, "author_profile": "https://Stackoverflow.com/users/2218839", "pm_score": 1, "selected": false, "text": "sh -c" }, { "answer_id": 74415891, "author": "tripleee", "author_id": 874188, "author_profile": "https://Stackoverflow.com/users/874188", "pm_score": 3, "selected": true, "text": "sh -c" }, { "answer_id": 74420878, "author": "David Maze", "author_id": 10008173, "author_profile": "https://Stackoverflow.com/users/10008173", "pm_score": 1, "selected": false, "text": "CMD sh -c '...'" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20486728/" ]
74,415,180
<p>Im trying to understand what the sentence <code>$request-&gt;user()?-&gt;id ?: $request-&gt;ip()</code> does in this function</p> <pre><code>protected function configureRateLimiting() { RateLimiter::for('api', function (Request $request) { return Limit::perMinute(60)-&gt;by($request-&gt;user()?-&gt;id ?: $request-&gt;ip()); }); } </code></pre> <p>According to my understanding it will limit the rate attempts to 60 by minute by either user id or IP address if there is not user logged in, Am I correct?</p> <p>But then how will the ternary translates to a classical if sequence? something like this?</p> <pre><code>if (null !== $request-&gt;user()) { $request-&gt;user()-&gt;id; } else { $request-&gt;ip(); } </code></pre> <p>Its the first time i see a ternary used in this way, can you give me some more examples of this use?</p> <p>Thanks for your help!!!</p>
[ { "answer_id": 74415246, "author": "Iłya Bursov", "author_id": 2864275, "author_profile": "https://Stackoverflow.com/users/2864275", "pm_score": 3, "selected": true, "text": "?->" }, { "answer_id": 74415254, "author": "Prafulla Kumar Sahu", "author_id": 5321614, "author_profile": "https://Stackoverflow.com/users/5321614", "pm_score": 0, "selected": false, "text": "<?php\n $a = 5;\n $b = $a?:0; // same as $b = $a ? $a : 0; and $b = $a ?? 0;\n echo $b;\n?>\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2367830/" ]
74,415,181
<p>My custom blazor component uses an external script (hosted on a CDN). Usually one would reference it in <code>index.html</code>, but I don't want to do that - I want the component to be self contained and easy to use.</p> <p>The typical solution is a script loader. A popular implementation has been floating around for years: <a href="https://stackoverflow.com/a/58979941/9971404">here</a> and <a href="https://www.geekinsta.com/add-javascript-in-blazor-components/" rel="nofollow noreferrer">here</a>.</p> <p><code>wwwroot/js/scriptLoader.js</code> (referenced in <code>index.html</code>):</p> <pre class="lang-js prettyprint-override"><code>let _loadedScripts = []; // list of loading / loaded scripts export async function loadScript(src) { // only load script once if (_loadedScripts[src]) return Promise.resolve(); return new Promise(function(resolve, reject) { let tag = document.createElement('script'); tag.type = 'text/javascript'; tag.src = src; // mark script as loading/loaded _loadedScripts[src] = true; tag.onload = function() { resolve(); } tag.onerror = function() { console.error('Failed to load script.'); reject(src); } document.body.appendChild(tag); }); } </code></pre> <p>Then I create a component where I want to load a custom script.</p> <p><code>FooComponent.razor</code>:</p> <pre class="lang-cs prettyprint-override"><code>@inject IJSRuntime _js // etc... protected override async Task OnAfterRenderAsync(bool firstRender) { await base.OnAfterRenderAsync(firstRender); if (firstRender) { // load component's script (using script loader) await _js.InvokeVoidAsync(&quot;loadScript&quot;, &quot;https://cdn.example.com/foo.min.js&quot;); } // invoke `doFoo()` from 'foo.min.js' script await _js.InvokeVoidAsync(&quot;doFoo&quot;, &quot;hello world!&quot;); } </code></pre> <p>That works. I can use the <code>&lt;FooComponent /&gt;</code> and it will load its own script file.</p> <p>But if I use the component multiple times, I run into a race condition:</p> <ul> <li>instance 1 of the component <ul> <li>tries to load the script</li> <li>script loader loads the script</li> <li>the component can use it</li> </ul> </li> <li>instances 2+ of the component <ul> <li>they are loading at the same time as instance 1!</li> <li>each tries to load the script, but the loader refuses to load it more than once</li> <li>they immediately try to use the script - but it's still busy loading!</li> <li>so they all fail and the app crashes (exceptions, etc.)</li> </ul> </li> </ul> <p>How can I refactor the code to ensure that the script is actually finished loading, before using it?</p>
[ { "answer_id": 74415246, "author": "Iłya Bursov", "author_id": 2864275, "author_profile": "https://Stackoverflow.com/users/2864275", "pm_score": 3, "selected": true, "text": "?->" }, { "answer_id": 74415254, "author": "Prafulla Kumar Sahu", "author_id": 5321614, "author_profile": "https://Stackoverflow.com/users/5321614", "pm_score": 0, "selected": false, "text": "<?php\n $a = 5;\n $b = $a?:0; // same as $b = $a ? $a : 0; and $b = $a ?? 0;\n echo $b;\n?>\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9971404/" ]
74,415,191
<p>I am learning javascript functions and I got following code which gives following output:</p> <p>Output: &quot;buy 3 bottles of milk&quot; &quot;Hello master, here is your 0 change&quot;</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function getMilk(money, costPerBottle) { console.log("buy " + calcBottles(money, costPerBottle) + " bottles of milk"); return calcChange(money, costPerBottle); } function calcBottles(startingMoney, costPerBottle) { var numberOfBottles = Math.floor(startingMoney / costPerBottle); return numberOfBottles; } function calcChange(startingAmount, costPerBottle) { var change = startingAmount % costPerBottle; return change; } console.log("Hello master, here is your " + getMilk(6, 2) + " change");</code></pre> </div> </div> </p> <p>I am not understanding what roles &quot;startingMoney&quot; and &quot;startingAmount&quot; plays here. Also how it is calculating number of bottles.</p>
[ { "answer_id": 74415279, "author": "pzelenovic", "author_id": 717683, "author_profile": "https://Stackoverflow.com/users/717683", "pm_score": 1, "selected": false, "text": "getMilk" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1939153/" ]
74,415,194
<p>I want to create a program to send an email with a discord bot but when i laucnh my program i have this error. My code to send an email works fine in a separate file but when i put in in my python discord bot program there are a problem my programm :</p> <p>`</p> <pre><code>import smtplib from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders from email.mime.multipart import MIMEMultipart import os import discord from discord.ext import commands from dotenv import load_dotenv load_dotenv(dotenv_path=&quot;config&quot;) default_intents = discord.Intents.default() default_intents.members = True default_intents.message_content = True default_intents.messages = True bot = commands.Bot(command_prefix=&quot;:&quot;, intents=default_intents) mail = &quot;&quot; varBody = &quot;&quot; @bot.event async def on_ready(): print(&quot;Bot Ready !&quot;) await bot.change_presence(activity = discord.Activity(type = discord.ActivityType.listening, name = &quot;Cool Music !&quot;)) @bot.event async def on_message(message): if message.content.lower() == &quot;login&quot;: await message.channel.send(&quot;mail :&quot;) mail = await bot.wait_for(&quot;message&quot;) await message.channel.send(&quot;Message : &quot;) varBody = await bot.wait_for(&quot;message&quot;) await message.channel.send(&quot;finishing...&quot;) await email() @bot.command() async def email(, email, message): msg = MIMEMultipart() msg['Subject'] = 'Hi! I am Qiqi' msg['From'] = 'MAIL_ADDRESS' msg['To'] = mail password = &quot;MAIL_PASSWORD&quot; body = varBody msg.attach(MIMEText(body, 'html')) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(msg['From'], password) server.sendmail(msg['From'], msg['To'], msg.as_string()) server.quit() bot.run(&quot;TOKEN&quot;) #terminal error Traceback (most recent call last): File &quot;C:\Users\lussa\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py&quot;, line 409, in _run_event await coro(*args, **kwargs) File &quot;c:\Users\lussa\Documents\BotdiscordPython\main.py&quot;, line 36, in on_message await email() TypeError: __call__() missing 1 required positional argument: 'context' </code></pre> <p>`</p> <p>i have added &quot;ctx&quot; in the def email</p> <p>but again the same error</p>
[ { "answer_id": 74415279, "author": "pzelenovic", "author_id": 717683, "author_profile": "https://Stackoverflow.com/users/717683", "pm_score": 1, "selected": false, "text": "getMilk" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20487340/" ]
74,415,207
<p>I have some sort of poll where you vote either YES and NO and based on the votes it creates a poll chart (by creating two divs inside another div that has a set width and setting the width of the first two divs the percentage of YES and NO votes out of the total votes). You can see the project for a better understanding by clicking <a href="https://jsfiddle.net/2yhrsf8m/" rel="nofollow noreferrer">HERE</a>.</p> <p>I want it to appear animated as if it were in CSS with <code>transition: width 100ms linear;</code> just like here:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Document&lt;/title&gt; &lt;style&gt; .poll{ height: 50px; width: 300px; background-color: black; transition: all 300ms; } .poll:hover{ width: 500px; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="poll"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>However, whenever I add something similar to the class of my divs I see no change. The divs in question are created in this function:</p> <pre><code>function renderPoll(){ container.innerHTML=''; //reset container let poll1 = document.createElement('div'); let poll2 = document.createElement('div'); poll1.classList.add('poll-attr'); poll2.classList.add('poll-attr'); let innerTextPoll = Math.round(calcPerc()); //calcPerc() calculates the percent of YES votes with the equation percentage = (100*NumberOfYES)/NumberOfVotes poll1.style.width = calcPerc() + '%'; poll2.style.width = 100-calcPerc() + '%'; poll1.innerText = innerTextPoll + '%'; poll2.innerText = 100-innerTextPoll + '%'; container.appendChild(poll1); container.appendChild(poll2); </code></pre> <p>}</p> <p>I am not nearly experienced enough to figure this out so any input is appreciated!</p>
[ { "answer_id": 74415319, "author": "Noel Maróti", "author_id": 20150565, "author_profile": "https://Stackoverflow.com/users/20150565", "pm_score": 0, "selected": false, "text": "function animation () {\n let id = null;\n const elem = document.querySelector(\".poll\"); \n let width = 300; // default width\n clearInterval(id);\n id = setInterval(frame, 5); // changing the number will effect the speed of the animation\n function frame() {\n if (width == 500) { // if the width is 500px, then finish animation\n clearInterval(id); // finish animation\n } else {\n width++; \n elem.style.width = width + \"px\"; \n }\n }\n}\n" }, { "answer_id": 74415800, "author": "IT goldman", "author_id": 3807365, "author_profile": "https://Stackoverflow.com/users/3807365", "pm_score": 2, "selected": true, "text": "function renderPoll() {\n container.innerHTML = ''; //reset container\n let poll1 = document.createElement('div');\n let poll2 = document.createElement('div');\n\n poll1.classList.add('poll-attr');\n poll2.classList.add('poll-attr');\n\n let innerTextPoll = Math.round(calcPerc()); //calcPerc() calculates the percent of YES \n poll1.innerText = innerTextPoll + '%';\n poll2.innerText = 100 - innerTextPoll + '%';\n\n container.appendChild(poll1);\n container.appendChild(poll2);\n\n var target_length = 300;\n\n animation(poll1, 0, (calcPerc()) * target_length / 100);\n animation(poll2, 0, (100 - calcPerc()) * target_length / 100);\n\n}\n\nfunction calcPerc() {\n return 75;\n}\n\nfunction animation(elem, from, to) {\n let id = null;\n let width = from || 0;\n var speed = 2.5;\n requestAnimationFrame(frame);\n\n function frame() {\n if (width < to) {\n width += speed;\n elem.style.width = width + \"px\";\n requestAnimationFrame(frame);\n }\n }\n}\n\n\nrenderPoll();" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19217750/" ]
74,415,256
<p>I'm trying to get the data of a user, which sent an interaction (a / command). The code below sends the reply-message, but I don't get the user ID in the console. I tried this code because I found it online but it doesn't work.</p> <pre><code>if (interaction?.data?.name === 'test') { await interaction.createMessage({ content: 'test' }) const interactionUser = await interaction.guild.members.fetch(interaction.user.id) const nickName = interactionUser.nickname const userName = interactionUser.user.username const userId = interactionUser.id console.log(nickName,userName,userId) } </code></pre> <p>can anyone help me?</p>
[ { "answer_id": 74415427, "author": "Gh0st", "author_id": 15256312, "author_profile": "https://Stackoverflow.com/users/15256312", "pm_score": 1, "selected": false, "text": "const userId = interactionUser.user.id\n" }, { "answer_id": 74416306, "author": "MalwareMoon", "author_id": 20241005, "author_profile": "https://Stackoverflow.com/users/20241005", "pm_score": 0, "selected": false, "text": "interaction.guild.members.fetch(interaction.user.id)" }, { "answer_id": 74436389, "author": "MushroomFX", "author_id": 14216148, "author_profile": "https://Stackoverflow.com/users/14216148", "pm_score": 1, "selected": true, "text": "const user = interaction?.member?.user\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14216148/" ]
74,415,260
<pre><code>#include &lt;iostream&gt; #include &lt;cmath&gt; using namespace std; int main() { float Litr; int opcja; cout &lt;&lt; &quot;Konwerter&quot; &lt;&lt; endl; switch(opcja){ case 1: cout &lt;&lt; &quot;Litr na barylke amerykanska i galon amerykanski&quot; &lt;&lt; endl; cin &gt;&gt; Litr; cout &lt;&lt; Litr &lt;&lt; &quot; litrow to &quot; &lt;&lt; Litr * 159 &lt;&lt; &quot; barylek i &quot; &lt;&lt; Litr * 3,78 &lt;&lt; &quot;galonow.&quot;; break; } return 0; } </code></pre> <p>Error in line 16 (e.g cout &lt;&lt; Litr &lt;&lt; &quot; litrow to &quot; &lt;&lt; Litr * 159 &lt;&lt; &quot; barylek i &quot; &lt;&lt; Litr * 3,78 &lt;&lt; &quot;galonow.&quot;; )</p> <p>||=== Build: Debug in aeiou (compiler: GNU GCC Compiler) ===| C:\Users*file loaction*\main.cpp|16|error: invalid operands of types 'int' and 'const char [9]' to binary 'operator&lt;&lt;'| ||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|</p> <p>Don't understand what's wrong and what compiler tries to tell me.</p>
[ { "answer_id": 74415283, "author": "kvr", "author_id": 5923576, "author_profile": "https://Stackoverflow.com/users/5923576", "pm_score": 1, "selected": false, "text": "3.78" }, { "answer_id": 74415304, "author": "StellarClown", "author_id": 10026471, "author_profile": "https://Stackoverflow.com/users/10026471", "pm_score": 1, "selected": true, "text": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n int opcja;\n \n cout << \"Konwerter: \";\n cin >> opcja;\n \n switch(opcja) {\n case 1: {\n float Litr;\n cout << \"Litr na barylke amerykanska i galon amerykanski\" << endl;\n cin >> Litr;\n cout << Litr << \" litrow to \" << Litr * 159 << \" barylek i \" << Litr * 3.78 << \"galonow.\";\n break;\n }\n }\n\n return 0;\n}\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20487435/" ]
74,415,265
<p>I have a risk entry view that only project managers are able to access and no other user group how would I ensure that only this user group is able to access this view?</p> <h1>Risk page class-based view</h1> <pre><code>@method_decorator(decorators, name='dispatch') class Risk_entry_page(View): template_name = 'risk/riskEntry.html' def get(self, request, *args, **kwargds): return render(request, self.template_name) </code></pre> <h1>Risk Urls</h1> <pre><code>urlpatterns = [ path('', views.Solution_area_home_page.as_view(), name='risks-home-page'), path('risk/', views.Risk_entry_page.as_view(), name='risk-entry-page'), path('assumption/', views.Assumption_entry_page.as_view(), name='assumption-entry-page'), path('issue/', views.Issue_entry_page.as_view(), name='issue-entry-page'), path('dependency/', views.Dependency_entry_page.as_view(), name='dependency-entry-page'), path('logout/', views.Logout.as_view(), name='logout-view'), ] </code></pre>
[ { "answer_id": 74415283, "author": "kvr", "author_id": 5923576, "author_profile": "https://Stackoverflow.com/users/5923576", "pm_score": 1, "selected": false, "text": "3.78" }, { "answer_id": 74415304, "author": "StellarClown", "author_id": 10026471, "author_profile": "https://Stackoverflow.com/users/10026471", "pm_score": 1, "selected": true, "text": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n int opcja;\n \n cout << \"Konwerter: \";\n cin >> opcja;\n \n switch(opcja) {\n case 1: {\n float Litr;\n cout << \"Litr na barylke amerykanska i galon amerykanski\" << endl;\n cin >> Litr;\n cout << Litr << \" litrow to \" << Litr * 159 << \" barylek i \" << Litr * 3.78 << \"galonow.\";\n break;\n }\n }\n\n return 0;\n}\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16373329/" ]
74,415,321
<p>I have a project I want to bring into Git.<br /> I have my local <code>git config</code> complete, verified I can SSH in, and have a branch &quot;<code>main</code>&quot; setup on GitHub.<br /> I substituted &quot;<code>xyz</code>&quot; for my actual GitHub branch.</p> <p>The &quot;<code>git checkout</code>&quot; command does not appear to be creating a local branch, and no error message is issued.</p> <h1><code>git remote -v</code></h1> <pre><code>svi git@github.com:rboudrie/XYZ.git (fetch) svi git@github.com:rboudrie/XYZ.git (push) </code></pre> <h1><code>git branch -a</code></h1> <pre><code>remotes/xyz/main </code></pre> <h1><code>git checkout -b newbranch</code></h1> <pre><code>Switched to a new branch 'newbranch' </code></pre> <h1>git branch -a</h1> <pre><code>remotes/xyz/main </code></pre> <p>I am attempting to create a local branch, and am expecting the branch to show up in &quot;<code>git branch -a</code>&quot; (or just git branch) when done.<br /> I used the &quot;<code>-a</code>&quot; on <code>git branch</code> to prove I am successfully connecting to my repo on github.com.</p>
[ { "answer_id": 74415283, "author": "kvr", "author_id": 5923576, "author_profile": "https://Stackoverflow.com/users/5923576", "pm_score": 1, "selected": false, "text": "3.78" }, { "answer_id": 74415304, "author": "StellarClown", "author_id": 10026471, "author_profile": "https://Stackoverflow.com/users/10026471", "pm_score": 1, "selected": true, "text": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n int opcja;\n \n cout << \"Konwerter: \";\n cin >> opcja;\n \n switch(opcja) {\n case 1: {\n float Litr;\n cout << \"Litr na barylke amerykanska i galon amerykanski\" << endl;\n cin >> Litr;\n cout << Litr << \" litrow to \" << Litr * 159 << \" barylek i \" << Litr * 3.78 << \"galonow.\";\n break;\n }\n }\n\n return 0;\n}\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12032036/" ]
74,415,386
<p>I am writing a program in which I add students to a roster using linked lists. I am successful at adding the first student, but upon adding subsequent students, my program prints &quot;Student already exists&quot; even when the student doesn't exist yet. Below is my add function.</p> <pre><code>struct student *add(struct student *list){ struct student *p; struct student *new_student = malloc(sizeof(struct student)); printf(&quot;Enter the student's last name: &quot;); read_line(new_student-&gt;last, NAME_LEN); printf(&quot;Enter the student's first name: &quot;); read_line(new_student-&gt;first, NAME_LEN); printf(&quot;Enter the student's email: &quot;); read_line(new_student-&gt;email, EMAIL_LEN); printf(&quot;Enter the student's instrument: &quot;); read_line(new_student-&gt;instrument, INSTRUMENT_LEN); printf(&quot;Enter the student's group name: &quot;); read_line(new_student-&gt;group, GROUP_LEN); if(new_student == NULL){ printf(&quot;\nMalloc failed.\n&quot;); return list; } if(list==NULL){ return new_student; } for(p=list;p!=NULL; p=p-&gt;next){ if((strcmp(p-&gt;first,new_student-&gt;first)==0) &amp;&amp; (strcmp(p-&gt;last, new_student-&gt;last)==0)){ printf(&quot;\nThis student already exists.\n&quot;); return list; } else{ while(p-&gt;next==NULL){ p-&gt;next = new_student; new_student-&gt;next = NULL; printf(&quot;\nStudent has been added to the roster.\n&quot;); break; //FOR LOOP NOT BREAKING? } } } return new_student; } </code></pre> <p>If anyone can help me understand how to fix this so that the for loop doesn't keep executing after the student is added to the list, I'd appreciate it.</p> <p>It doesn't seem as though my break statement is working. I've tried making the return to new_student occur within my else statement, but that causes other issues in my program. Any help is appreciated.</p>
[ { "answer_id": 74415283, "author": "kvr", "author_id": 5923576, "author_profile": "https://Stackoverflow.com/users/5923576", "pm_score": 1, "selected": false, "text": "3.78" }, { "answer_id": 74415304, "author": "StellarClown", "author_id": 10026471, "author_profile": "https://Stackoverflow.com/users/10026471", "pm_score": 1, "selected": true, "text": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n int opcja;\n \n cout << \"Konwerter: \";\n cin >> opcja;\n \n switch(opcja) {\n case 1: {\n float Litr;\n cout << \"Litr na barylke amerykanska i galon amerykanski\" << endl;\n cin >> Litr;\n cout << Litr << \" litrow to \" << Litr * 159 << \" barylek i \" << Litr * 3.78 << \"galonow.\";\n break;\n }\n }\n\n return 0;\n}\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20013829/" ]
74,415,389
<p>Why is the send_keys function ignoring spaces in my python script? I used vnc on ubuntu/debian 10. Everything works correctly when I run the script on my computer, but all spaces disappear on vps with vnc. Error is in Google chrome. `</p> <pre><code>element.send_keys(&quot;1 2 3&quot;) result: &quot;123&quot; </code></pre> <p>`</p> <p>Replacing the spaces with &quot;Keys.SPACE&quot; did not help me.</p> <p>I tried adding two slashes <code>element.send_keys(&quot;John\\ Doe&quot;)</code></p>
[ { "answer_id": 74415283, "author": "kvr", "author_id": 5923576, "author_profile": "https://Stackoverflow.com/users/5923576", "pm_score": 1, "selected": false, "text": "3.78" }, { "answer_id": 74415304, "author": "StellarClown", "author_id": 10026471, "author_profile": "https://Stackoverflow.com/users/10026471", "pm_score": 1, "selected": true, "text": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n int opcja;\n \n cout << \"Konwerter: \";\n cin >> opcja;\n \n switch(opcja) {\n case 1: {\n float Litr;\n cout << \"Litr na barylke amerykanska i galon amerykanski\" << endl;\n cin >> Litr;\n cout << Litr << \" litrow to \" << Litr * 159 << \" barylek i \" << Litr * 3.78 << \"galonow.\";\n break;\n }\n }\n\n return 0;\n}\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15446570/" ]
74,415,438
<p>I'm trying to find the factorial of a number in C#. (The factorial of five is this: 5! 5x4x3x2x1) The console displays &quot;no output&quot; even though I requested to print a variable. Some syntax may be wrong, too.</p> <p>I would like if you guys could try to not use a different thing like arrays to print a value. Please use the while loop unless I <strong>need</strong> to change the way I am doing this.</p> <p>If you would like, you can use methods, but I prefer not to in this scenario. I do not think a method is necessary right now. Share your feedback.</p> <p>Does anyone know why it isn't working? Please comment to help!</p> <p>`</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoloLearn { class Program { static void Main(string[] args) { int factorial = Convert.ToInt32(Console.ReadLine()); int final = 0; int factorialCopy = factorial; int five = 5; while(factorial &gt; -1) { int digitMinusOne = five - 1; int multiplication = factorialCopy*digitMinusOne; final = final + multiplication; five = digitMinusOne; factorialCopy = multiplication; } Console.WriteLine(final); } } } </code></pre> <p>`</p> <p>Any help would be appreciated. Thanks!</p>
[ { "answer_id": 74415514, "author": "MDCCXXIX", "author_id": 20487756, "author_profile": "https://Stackoverflow.com/users/20487756", "pm_score": 0, "selected": false, "text": "using System; \n public class FactorialCalculator \n { \n public static void Main(string[] args) \n { \n int i,factorial=1,number; \n Console.Write(\"Enter any Number: \"); \n number= int.Parse(Console.ReadLine()); \n for(i=1;i<=number;i++){ \n factorial=factorial*i; \n } \n Console.Write(\"The factorial of\" +number+\" is: \"+factorial); \n } \n } \n" }, { "answer_id": 74415535, "author": "Facundo Gallardo", "author_id": 20375146, "author_profile": "https://Stackoverflow.com/users/20375146", "pm_score": 2, "selected": true, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\n\nnamespace SoloLearn\n{\n class Program\n {\n static void Main(string[] args)\n {\n int factorial = Convert.ToInt32(Console.ReadLine());\n // Init this in 1, to be able to do multiplication on it since the start.\n int final = 1;\n\n // You don't want to consider 0,\n // You'd end up with 0 every single time\n while(factorial > 0)\n {\n final = final * factorial;\n\n // Here you assign factorial to the next number\n factorial = factorial -1;\n }\n\n Console.WriteLine(final);\n }\n }\n}\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20444883/" ]
74,415,476
<p>I'm new on the OCR world and I have document with numbers to analyse with Python, openCV and pytesserract. The files I received are pdfs and the numbers are not text. So, I converted it to jpg with this :</p> <pre><code>first_page = convert_from_path(path__to_pdf, dpi=600, first_page=1, last_page=1) first_page[0].save(TEMP_FOLDER+'temp.jpg', 'JPEG') </code></pre> <p>Then , the images look like this : I still have some noise around the digits.</p> <p><a href="https://i.stack.imgur.com/a5PI3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/a5PI3.png" alt="enter image description here" /></a></p> <p>I tried to select the &quot;black color only&quot; with this :</p> <pre><code>img_hsv = cv2.cvtColor(img_raw, cv2.COLOR_BGR2HSV) img_changing = cv2.cvtColor(img_raw, cv2.COLOR_RGB2GRAY) low_color = np.array([0, 0, 0]) high_color = np.array([180, 255, 30]) blackColorMask = cv2.inRange(img_hsv, low_color, high_color) img_inversion = cv2.bitwise_not(img_changing) img_black_filtered = cv2.bitwise_and(img_inversion, img_inversion, mask = blackColorMask) img_final_inversion = cv2.bitwise_not(img_black_filtered) </code></pre> <p>So, with this code, my image looks like this : <a href="https://i.stack.imgur.com/8js13.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8js13.jpg" alt="enter image description here" /></a></p> <p>Even with cv2.blur, I don't even reach 75% of image FULLY analysed. For at least 25% of the images, pytesseract misses 1 or more digits. Is that normal ? Do you have ideas of what I can do to maximize the succesfull rate ?</p> <p>Thanks</p>
[ { "answer_id": 74438855, "author": "Esraa Abdelmaksoud", "author_id": 5617608, "author_profile": "https://Stackoverflow.com/users/5617608", "pm_score": 1, "selected": false, "text": " 0 Orientation and script detection (OSD) only.\n 1 Automatic page segmentation with OSD.\n 2 Automatic page segmentation, but no OSD, or OCR. (not implemented)\n 3 Fully automatic page segmentation, but no OSD. (Default)\n 4 Assume a single column of text of variable sizes.\n 5 Assume a single uniform block of vertically aligned text.\n 6 Assume a single uniform block of text.\n 7 Treat the image as a single text line.\n 8 Treat the image as a single word.\n 9 Treat the image as a single word in a circle.\n 10 Treat the image as a single character.\n 11 Sparse text. Find as much text as possible in no particular order.\n 12 Sparse text with OSD.\n 13 Raw line. Treat the image as a single text line,\n bypassing hacks that are Tesseract-specific.\n" }, { "answer_id": 74439976, "author": "K J", "author_id": 10802527, "author_profile": "https://Stackoverflow.com/users/10802527", "pm_score": 0, "selected": false, "text": "" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17939631/" ]
74,415,536
<p>In the leading DeepLearning libraries, does the filter (aka kernel or weight) in the convolutional layer convolves also across the &quot;channel&quot; dimension or does it take all the channels at once? To make an example, if the input dimension is <code>(60,60,10)</code> (where the last dimension is often referred as &quot;channels&quot;) and the desired output number of channels is 5, can the filter be <code>(5,5,5,5)</code> or should it be <code>(5,5,10,5)</code> instead ?</p>
[ { "answer_id": 74438855, "author": "Esraa Abdelmaksoud", "author_id": 5617608, "author_profile": "https://Stackoverflow.com/users/5617608", "pm_score": 1, "selected": false, "text": " 0 Orientation and script detection (OSD) only.\n 1 Automatic page segmentation with OSD.\n 2 Automatic page segmentation, but no OSD, or OCR. (not implemented)\n 3 Fully automatic page segmentation, but no OSD. (Default)\n 4 Assume a single column of text of variable sizes.\n 5 Assume a single uniform block of vertically aligned text.\n 6 Assume a single uniform block of text.\n 7 Treat the image as a single text line.\n 8 Treat the image as a single word.\n 9 Treat the image as a single word in a circle.\n 10 Treat the image as a single character.\n 11 Sparse text. Find as much text as possible in no particular order.\n 12 Sparse text with OSD.\n 13 Raw line. Treat the image as a single text line,\n bypassing hacks that are Tesseract-specific.\n" }, { "answer_id": 74439976, "author": "K J", "author_id": 10802527, "author_profile": "https://Stackoverflow.com/users/10802527", "pm_score": 0, "selected": false, "text": "" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1586860/" ]
74,415,572
<pre><code>{ id: 23323091, userId: 1743514, teamId: 1693131, name: 'test1' }, { id: 2332950, userId: 1743514, teamId: 1693131, name: 'test2' }, { id: 23323850, userId: 1743514, teamId: 1693131, name: 'test3' } </code></pre> <p>Im trying find solution how to parse json result returned from GET request in node.js. So I want find in json array with ex. name: 'test3' return id:</p> <p>Here is full code:</p> <pre><code>const axios = require('axios'); let token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTc0MzUxNCwidXNlcm5hbWUiOiJzbmFwa2l0cmljaEBnbWFpbC5jb20iLCJyb2xlIjoiYWRtaW4iLCJ0ZWFtSWQiOjE2OTMxMzEsInRv'; axios.get('https://dolphin-anty-api.com/browser_profiles', { headers: { Authorization: `Bearer ${token}` } }) .then(function (response) { const data = response.data; console.log(data); }) .catch(function (error) { console.log(error); }); </code></pre> <p>and here is full data response from console log <a href="https://pastebin.com/wY0RVsUv" rel="nofollow noreferrer">https://pastebin.com/wY0RVsUv</a></p>
[ { "answer_id": 74415627, "author": "LeoDog896", "author_id": 7589775, "author_profile": "https://Stackoverflow.com/users/7589775", "pm_score": 2, "selected": true, "text": "const elements = [\n\n {\n id: 23323091,\n userId: 1743514,\n teamId: 1693131,\n name: 'test1'\n },\n {\n id: 2332950,\n userId: 1743514,\n teamId: 1693131,\n name: 'test2'\n },\n {\n id: 23323850,\n userId: 1743514,\n teamId: 1693131,\n name: 'test3'\n }\n]\n\nfunction search(name) {\n return elements.find(elem => elem.name == name)?.id\n}\n\nconsole.log(search('test3'))\nconsole.log(search('test4'))" }, { "answer_id": 74415688, "author": "Dev", "author_id": 20371423, "author_profile": "https://Stackoverflow.com/users/20371423", "pm_score": 0, "selected": false, "text": "response.json()" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17055039/" ]
74,415,578
<p>Hello <strong>Stack OF</strong> Community,</p> <p>*<br /> Basically my goal is to extract values from an excel file, after reading through data from another column.*</p> <p>**<br /> Thickness** of parcel, with values for example - <strong>[0.12, 0.12, 0.13, 0.14, 0.14, 0.15]</strong> (Heading: Thickness (mm))<br /> <strong>Weight</strong> of parcel, with values for example - <strong>[4.000, 3.500, 2.500, 4.500, 5.000, 2.000]</strong> (Heading: Weight (KG))</p> <p>Excel File:<br /> <strong>Thickness</strong> <strong>Weight</strong><br /> 0.12 4.000<br /> 0.12 3.500<br /> 0.13 2.500<br /> 0.14 4.500<br /> 0.14 5.000<br /> 0.15 2.000</p> <p>Looking to generate this using <strong>Python</strong>:<br /> Thickness Weight Parcels<br /> 0.12 7.500 2 Parcels<br /> 0.13 2.500 1 Parcels<br /> 0.14 9.500 2 Parcels<br /> 0.15 2.000 1 Parcels</p> <p>TOTAL: 21.500 6 Parcels</p> <p>The user will be shown all the current values of <strong>Thickness Available</strong> and will be allowed to <strong>input</strong> a <em>single thickness value to get its weight</em> or <em>a range and get its weight</em>.</p> <p>So anyone of you who can recommend me how can this task be accomplished easily and efficiently.</p> <p>I would be very grateful for your advice.</p> <p><em>Please note: I have only done Python Programming Language.</em></p> <p>Thank You.</p> <p>I have learned Openpyxl but also got to know that Pandas is an efficent tool for Data Analysis, so please let me know!</p> <p>Arigato!</p>
[ { "answer_id": 74416015, "author": "Dimitrius", "author_id": 5558953, "author_profile": "https://Stackoverflow.com/users/5558953", "pm_score": 1, "selected": true, "text": "import pandas as pd\n\n# uncomment to read the file\n# df = pd.read_excel('tmp.xlsx', index_col=None)\n\ndf = pd.DataFrame({\n \"Thikness\": [0.12, 0.12, 0.13, 0.14, 0.14, 0.15],\n \"Weight\": [4.000, 3.500, 2.500, 4.500, 5.000, 2.000, ],\n})\n\nres = df.groupby([\"Thikness\"], as_index=False).agg(\n Weight=('Weight', sum),\n Count=('Weight', 'count'),\n)\n\n# write excel\nwriter = pd.ExcelWriter('tmp.xlsx', engine='xlsxwriter')\nres.to_excel(writer, sheet_name='Sheet1')\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18112336/" ]
74,415,582
<p>I have address of an struct store in int variable. Can I dereference the struct??</p> <p>say: int x = 3432234; // memory address of struct now I want to access the some struct from it.</p> <p>I have been suggest these steps.</p> <ol> <li>store the address in an int variable</li> <li>cast that int to a struct pointer</li> <li>then dereference it</li> </ol> <p>But don't know how to apply.</p>
[ { "answer_id": 74416015, "author": "Dimitrius", "author_id": 5558953, "author_profile": "https://Stackoverflow.com/users/5558953", "pm_score": 1, "selected": true, "text": "import pandas as pd\n\n# uncomment to read the file\n# df = pd.read_excel('tmp.xlsx', index_col=None)\n\ndf = pd.DataFrame({\n \"Thikness\": [0.12, 0.12, 0.13, 0.14, 0.14, 0.15],\n \"Weight\": [4.000, 3.500, 2.500, 4.500, 5.000, 2.000, ],\n})\n\nres = df.groupby([\"Thikness\"], as_index=False).agg(\n Weight=('Weight', sum),\n Count=('Weight', 'count'),\n)\n\n# write excel\nwriter = pd.ExcelWriter('tmp.xlsx', engine='xlsxwriter')\nres.to_excel(writer, sheet_name='Sheet1')\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19111495/" ]
74,415,597
<p>I'm trying to use curl to set up a cron to reboot my WD N900 Router on a regular basis.</p> <p>Using Chrome's developer tools, when I login to the the router via its WebGUI, it brings me to &quot;authentication.cgi&quot;. Here's its essential components copied as a curl (bash):</p> <pre><code>curl 'http://192.168.1.1/authentication.cgi' \ -H 'Cookie: QPYVIXOAZD=admin; uid=lseKLfq8zc' \ --data-raw 'USERNAME=admin&amp;DIGEST=XXXXXXXXXXXXXXXXXXX' </code></pre> <p>The critical component is the cookie entry, of which the uid is unique for that particular login.</p> <p>To reboot the router, I then go through several pages, eventually getting to &quot;service.cgi&quot;. Here's its essential components copied as a curl (bash):</p> <pre><code>curl 'http://192.168.1.1/service.cgi' \ -H 'Cookie: QPYVIXOAZD=admin; uid=lseKLfq8zc' \ --data-raw 'EVENT=REBOOT' </code></pre> <p>For a successful reboot via curl from service.cgi, the cookie uid must be the same as that in authentication.cgi. Otherwise, it doesn't reboot, and states &quot;Authorization failure.&quot;</p> <p>How can I get this to work without first obtaining a cookie via a WebGUI login (which defeats the purpose of curl)?</p> <p>I tried to set up a cookie jar (curl -c /tmp/cookie-jar.txt ....) and remove the &quot;Cookie:...&quot; line, which resulted in another &quot;Authorization failure&quot; as well as an empty cookie file save for this:</p> <pre><code># Netscape HTTP Cookie File # https://curl.se/docs/http-cookies.html # This file was generated by libcurl! Edit at your own risk. </code></pre> <p>I also tried &quot;curl - u myusername:mypassword&quot; (with and without --digest or --noauth options) to no avail (&quot;authorization failure&quot;).</p> <p>Any suggestions are greatly appreciated.</p> <hr /> <p><strong>UPDATE:</strong> When I curl authentication.cgi with my username:password:</p> <pre><code>curl --user admin:XXXXXXXXXX 'http://192.168.1.1/authentication.cgi' </code></pre> <p>I get this type of response:</p> <pre><code>{&quot;uid&quot;: &quot;9auO5hcbq8&quot;, &quot;CHALLENGE&quot;: &quot;bdce6395-f46b-4306-a61b-1ec2de1bf7d5&quot;} </code></pre> <p>Can this information be used somehow? I pasted that uid into the Cookie in my previous curl for service.cgi, but no luck.</p>
[ { "answer_id": 74418339, "author": "Misunderstood", "author_id": 3813605, "author_profile": "https://Stackoverflow.com/users/3813605", "pm_score": 1, "selected": false, "text": "curl_setopt($ch, CURLOPT_COOKIE, uid=9auO5hcbq8; QPYVIXOAZD=admin;);\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15999716/" ]
74,415,598
<h3>My problem</h3> <p>I have 2 <strong>adjacent</strong> buffers of bytes of identical size (around 20 MB each). I just want to count the differences between them.</p> <h3>My question</h3> <p>How much time this loop should take to run on a 4.8GHz Intel I7 9700K with 3600MT RAM ?</p> <p>How do we compute max theoretical speed ?</p> <h3>What I tried</h3> <pre class="lang-c++ prettyprint-override"><code>uint64_t compareFunction(const char *const __restrict buffer, const uint64_t commonSize) { uint64_t diffFound = 0; for(uint64_t byte = 0; byte &lt; commonSize; ++byte) diffFound += static_cast&lt;uint64_t&gt;(buffer[byte] != buffer[byte + commonSize]); return diffFound; } </code></pre> <p>It takes 11ms on my PC (9700K 4.8Ghz RAM 3600 Windows 10 Clang 14.0.6 -O3 MinGW ) and I feel it is too slow and that I am missing something.</p> <p>40MB should take less than 2ms to be read on the CPU (my RAM bandwidth is between 20 and 30GB/s)</p> <p><strong>I don't know how to count cycles required to execute one iteration</strong> (especially because CPUs are superscalar nowadays). If I assume 1 cycle per operation and if I don't mess up my counting, it should be 10 ops per iteration -&gt; 200 million ops -&gt; at 4.8 Ghz with only one execution unit -&gt; 40ms. Obviously I am wrong on how to compute the number of cycles per loop.</p> <p>Fun fact: I tried on Linux PopOS GCC 11.2 -O3 and it ran at 4.5ms. Why such a difference?</p> <p>Here are the dissassemblies vectorised and scalar produced by clang:</p> <pre class="lang-c prettyprint-override"><code>compareFunction(char const*, unsigned long): # @compareFunction(char const*, unsigned long) test rsi, rsi je .LBB0_1 lea r8, [rdi + rsi] neg rsi xor edx, edx xor eax, eax .LBB0_4: # =&gt;This Inner Loop Header: Depth=1 movzx r9d, byte ptr [rdi + rdx] xor ecx, ecx cmp r9b, byte ptr [r8 + rdx] setne cl add rax, rcx add rdx, 1 mov rcx, rsi add rcx, rdx jne .LBB0_4 ret .LBB0_1: xor eax, eax ret </code></pre> <p>Clang14 O3:</p> <pre class="lang-c prettyprint-override"><code>.LCPI0_0: .quad 1 # 0x1 .quad 1 # 0x1 compareFunction(char const*, unsigned long): # @compareFunction(char const*, unsigned long) test rsi, rsi je .LBB0_1 cmp rsi, 4 jae .LBB0_4 xor r9d, r9d xor eax, eax jmp .LBB0_11 .LBB0_1: xor eax, eax ret .LBB0_4: mov r9, rsi and r9, -4 lea rax, [r9 - 4] mov r8, rax shr r8, 2 add r8, 1 test rax, rax je .LBB0_5 mov rdx, r8 and rdx, -2 lea r10, [rdi + 6] lea r11, [rdi + rsi] add r11, 6 pxor xmm0, xmm0 xor eax, eax pcmpeqd xmm2, xmm2 movdqa xmm3, xmmword ptr [rip + .LCPI0_0] # xmm3 = [1,1] pxor xmm1, xmm1 .LBB0_7: # =&gt;This Inner Loop Header: Depth=1 movzx ecx, word ptr [r10 + rax - 6] movd xmm4, ecx movzx ecx, word ptr [r10 + rax - 4] movd xmm5, ecx movzx ecx, word ptr [r11 + rax - 6] movd xmm6, ecx pcmpeqb xmm6, xmm4 movzx ecx, word ptr [r11 + rax - 4] movd xmm7, ecx pcmpeqb xmm7, xmm5 pxor xmm6, xmm2 punpcklbw xmm6, xmm6 # xmm6 = xmm6[0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7] pshuflw xmm4, xmm6, 212 # xmm4 = xmm6[0,1,1,3,4,5,6,7] pshufd xmm4, xmm4, 212 # xmm4 = xmm4[0,1,1,3] pand xmm4, xmm3 paddq xmm4, xmm0 pxor xmm7, xmm2 punpcklbw xmm7, xmm7 # xmm7 = xmm7[0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7] pshuflw xmm0, xmm7, 212 # xmm0 = xmm7[0,1,1,3,4,5,6,7] pshufd xmm5, xmm0, 212 # xmm5 = xmm0[0,1,1,3] pand xmm5, xmm3 paddq xmm5, xmm1 movzx ecx, word ptr [r10 + rax - 2] movd xmm0, ecx movzx ecx, word ptr [r10 + rax] movd xmm1, ecx movzx ecx, word ptr [r11 + rax - 2] movd xmm6, ecx pcmpeqb xmm6, xmm0 movzx ecx, word ptr [r11 + rax] movd xmm7, ecx pcmpeqb xmm7, xmm1 pxor xmm6, xmm2 punpcklbw xmm6, xmm6 # xmm6 = xmm6[0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7] pshuflw xmm0, xmm6, 212 # xmm0 = xmm6[0,1,1,3,4,5,6,7] pshufd xmm0, xmm0, 212 # xmm0 = xmm0[0,1,1,3] pand xmm0, xmm3 paddq xmm0, xmm4 pxor xmm7, xmm2 punpcklbw xmm7, xmm7 # xmm7 = xmm7[0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7] pshuflw xmm1, xmm7, 212 # xmm1 = xmm7[0,1,1,3,4,5,6,7] pshufd xmm1, xmm1, 212 # xmm1 = xmm1[0,1,1,3] pand xmm1, xmm3 paddq xmm1, xmm5 add rax, 8 add rdx, -2 jne .LBB0_7 test r8b, 1 je .LBB0_10 .LBB0_9: movzx ecx, word ptr [rdi + rax] movd xmm2, ecx movzx ecx, word ptr [rdi + rax + 2] movd xmm3, ecx add rax, rsi movzx ecx, word ptr [rdi + rax] movd xmm4, ecx pcmpeqb xmm4, xmm2 movzx eax, word ptr [rdi + rax + 2] movd xmm2, eax pcmpeqb xmm2, xmm3 pcmpeqd xmm3, xmm3 pxor xmm4, xmm3 punpcklbw xmm4, xmm4 # xmm4 = xmm4[0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7] pshuflw xmm4, xmm4, 212 # xmm4 = xmm4[0,1,1,3,4,5,6,7] pshufd xmm4, xmm4, 212 # xmm4 = xmm4[0,1,1,3] movdqa xmm5, xmmword ptr [rip + .LCPI0_0] # xmm5 = [1,1] pand xmm4, xmm5 paddq xmm0, xmm4 pxor xmm2, xmm3 punpcklbw xmm2, xmm2 # xmm2 = xmm2[0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7] pshuflw xmm2, xmm2, 212 # xmm2 = xmm2[0,1,1,3,4,5,6,7] pshufd xmm2, xmm2, 212 # xmm2 = xmm2[0,1,1,3] pand xmm2, xmm5 paddq xmm1, xmm2 .LBB0_10: paddq xmm0, xmm1 pshufd xmm1, xmm0, 238 # xmm1 = xmm0[2,3,2,3] paddq xmm1, xmm0 movq rax, xmm1 cmp r9, rsi je .LBB0_13 .LBB0_11: lea r8, [r9 + rsi] sub rsi, r9 add r8, rdi add rdi, r9 xor edx, edx .LBB0_12: # =&gt;This Inner Loop Header: Depth=1 movzx r9d, byte ptr [rdi + rdx] xor ecx, ecx cmp r9b, byte ptr [r8 + rdx] setne cl add rax, rcx add rdx, 1 cmp rsi, rdx jne .LBB0_12 .LBB0_13: ret .LBB0_5: pxor xmm0, xmm0 xor eax, eax pxor xmm1, xmm1 test r8b, 1 jne .LBB0_9 jmp .LBB0_10 </code></pre>
[ { "answer_id": 74418609, "author": "Peter Cordes", "author_id": 224132, "author_profile": "https://Stackoverflow.com/users/224132", "pm_score": 3, "selected": false, "text": "pmovsxbq" }, { "answer_id": 74420608, "author": "Jérôme Richard", "author_id": 12939557, "author_profile": "https://Stackoverflow.com/users/12939557", "pm_score": 4, "selected": true, "text": "-O1" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20487094/" ]
74,415,616
<p>I'm trying to refresh the authentication token every few minutes using a refresh token. My problem is that the token is saved in a <code>Context</code> (using <code>useContext</code> to retrieve it when necessary) and I'm struggling to use a <code>setInterval</code>-like function to read the current token, POST it to the server and renew it in the state.</p> <p>This is what I'm trying to do:</p> <pre><code> const { tryLocalSignIn, signin, signout, state: AuthState, } = useContext(AuthContext); ... let id = setInterval(async () =&gt; { let token = AuthState.token; let refreshToken = AuthState.refreshToken; console.log(&quot;Running refresh token&quot;, token, refreshToken); let answer = await ApiRefreshToken(token, refreshToken); if (answer.status !== 200) { setError(&quot;Error using refresh token&quot;); return; } signin({ token: answer.data.token, refreshToken: answer.data.refreshToken, expires_in: answer.data.expires_in, }); }, 15000); ... </code></pre> <p>But I'm unable to read from the AuthState</p>
[ { "answer_id": 74418609, "author": "Peter Cordes", "author_id": 224132, "author_profile": "https://Stackoverflow.com/users/224132", "pm_score": 3, "selected": false, "text": "pmovsxbq" }, { "answer_id": 74420608, "author": "Jérôme Richard", "author_id": 12939557, "author_profile": "https://Stackoverflow.com/users/12939557", "pm_score": 4, "selected": true, "text": "-O1" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1833200/" ]
74,415,629
<p>I'm trying to implement the <code>ls</code> command in C with a few parameters like <code>-a</code>, <code>-l</code>... or <code>-la</code>, but I'm having issues with the parsing, when I use the input I get Segmentation Fault, this is an example of the <code>-a</code> parameter:</p> <pre><code>int comparator(char *av) { int i = 0; if (my_strcmp((av[i]), &quot;-a&quot;) == 0) return 0; else return 1; } int my_ls_a(char *path) { int comp = comparator(path); DIR *pdirec = opendir(&quot;.&quot;); struct dirent *direc; direc = readdir(pdirec); while (direc != NULL || comp == 0) { my_printf(&quot;%s &quot;, direc-&gt;d_name); direc = readdir(pdirec); } if ((path = readdir(pdirec)) == NULL) my_printf(&quot;\n&quot;); if (pdirec == NULL) return (84); closedir(pdirec); return (0); } </code></pre> <p>And this is my main:</p> <pre><code>int main(int ac, char *av[]) { if (ac == 1) my_ls_a(av[0]); return 0; } </code></pre> <p>I already have all the <code>#include</code> in a .h by the way.</p> <p>When I only use the <code>main</code> function it works but not when I add the parameter <code>-a</code>.</p>
[ { "answer_id": 74415676, "author": "chqrlie", "author_id": 4593267, "author_profile": "https://Stackoverflow.com/users/4593267", "pm_score": 0, "selected": false, "text": "comparator" }, { "answer_id": 74415727, "author": "wrm", "author_id": 20483162, "author_profile": "https://Stackoverflow.com/users/20483162", "pm_score": 1, "selected": false, "text": "getopt()" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19557737/" ]
74,415,634
<p>I created a class called Cards and I need to create a function called <code>points(self)</code> which returns that card and its associated points. For example the I have three lists I created,</p> <pre><code>Card_rank = [&quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;, &quot;Q&quot;, &quot;J&quot;, &quot;K&quot;, &quot;7&quot;, &quot;A&quot;] Cardsuit = [&quot;H&quot;, &quot;C&quot;, &quot;S&quot;, &quot;D&quot;] points2 = [&quot;0&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;10&quot;, &quot;11&quot;] </code></pre> <p>and when the function is called if the input in self is either &quot;2&quot; - &quot;6&quot; + any value from card suit it will print the card with value from <code>Card_rank</code> and <code>Cardsuit</code> and will give 0 points from <code>points2</code> list.</p> <p>I have tried this:</p> <pre><code>def points(self): if self[0] == &quot;2&quot;: print(self + &quot; Card points is &quot; + self.points2[0]) </code></pre>
[ { "answer_id": 74415676, "author": "chqrlie", "author_id": 4593267, "author_profile": "https://Stackoverflow.com/users/4593267", "pm_score": 0, "selected": false, "text": "comparator" }, { "answer_id": 74415727, "author": "wrm", "author_id": 20483162, "author_profile": "https://Stackoverflow.com/users/20483162", "pm_score": 1, "selected": false, "text": "getopt()" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20487839/" ]
74,415,641
<p>I'm trying to make an image to open on another location on the page while its been hovered. I looked online but didn't find a way to do that functionallty usuing only html and css. Anyone know how to achive that?</p> <p>Not hovered: <a href="https://i.stack.imgur.com/GweOk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GweOk.png" alt="Not hovered" /></a></p> <p>Hovered: <a href="https://i.stack.imgur.com/6cRjK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6cRjK.png" alt="Hovered" /></a></p> <p>I tried to make another copy of the image transpert on defined area on a grid but it can't sit on top of the text.</p> <p>html code:</p> <pre><code> &lt;section id=&quot;fav-place&quot; class=&quot;place-sec&quot;&gt; &lt;article class=&quot;place-art&quot;&gt; &lt;div class=&quot;place-desc&quot;&gt; &lt;h1&gt;A place I Enjoyed visiting&lt;/h1&gt; &lt;h2 class=&quot;sec-h2&quot;&gt;Cape Greco, Cyprus&lt;/h2&gt; &lt;p&gt;Cape Greco is cape and also a small peninsula in the southeast of Cyprus, in Famagusta, between Ayia Napa and Paralimni. According to the findings of the excavations that took place in 1992, this site is considered to be one of the most ancient settlements on the island &lt;/p&gt; &lt;p&gt; In the sea area of Cape Greco there are submarine ravines and caves that are popular for diving. Within sea ravines up to 10 meters high, there are sea caves, which are called &quot;palaces&quot;. These caves, along with Smugglers caves, are accessible only by the sea. &lt;/p&gt; &lt;/div&gt; &lt;div class=&quot;why-i-like-place&quot;&gt; &lt;h2&gt;Why I like this place&lt;/h2&gt; &lt;p&gt;Because of the clear water, the cliffs around and the beautiful sights&lt;/p&gt; &lt;/div&gt; &lt;/article&gt; &lt;aside class=&quot;place-aside&quot;&gt; &lt;img class=&quot;p-sm-img first-last-img&quot; src=&quot;/images/cape-greco-imgs/boat.jpg&quot; alt=&quot;boat-img&quot;&gt; &lt;img class=&quot;p-sm-img&quot; src=&quot;/images/cape-greco-imgs/bridge.jpg&quot; alt=&quot;bridge-img&quot;&gt; &lt;img class=&quot;p-sm-img&quot; src=&quot;/images/cape-greco-imgs/cave.jpg&quot; alt=&quot;cave-img&quot;&gt; &lt;img class=&quot;p-sm-img&quot; src=&quot;/images/cape-greco-imgs/hole.jpg&quot; alt=&quot;hole-img&quot;&gt; &lt;img class=&quot;p-sm-img&quot; src=&quot;/images/cape-greco-imgs/sm cliff.jpg&quot; alt=&quot;sm-cliff-img&quot;&gt; &lt;img class=&quot;p-sm-img&quot; src=&quot;/images/cape-greco-imgs/sunrise.jpg&quot; alt=&quot;sunrise-img&quot;&gt; &lt;img class=&quot;p-sm-img first-last-img&quot; src=&quot;/images/cape-greco-imgs/tree.jpg&quot; alt=&quot;tree-img&quot;&gt; &lt;/aside&gt; &lt;/section&gt; </code></pre> <p>css code:</p> <pre><code>.place-art { grid-column: 1/2; display: grid; grid-template-rows: 3fr 1fr; } .place-desc-sec{ grid-row: 1/-2; } .place-aside { border: solid 0.5vh; border-color: rgba(185, 218, 100, 0.862); border-radius: 1vh; margin-top: 6vh; overflow-y: scroll; display: flex; flex-direction: column; } .place-sec { display: grid; grid-template-columns: 2fr 1fr; } .first-last-img { margin: 0; } .p-sm-img { margin: 0.2vh 0; width: 23.5vw; } .p-sm-img:hover { } .p-lrg-img { visibility: hidden; opacity: 0.2; grid-row: 1/-2; grid-column: 1/2; } .why-i-like-place { grid-row: 2/3; grid-column: 1/2 } </code></pre>
[ { "answer_id": 74415676, "author": "chqrlie", "author_id": 4593267, "author_profile": "https://Stackoverflow.com/users/4593267", "pm_score": 0, "selected": false, "text": "comparator" }, { "answer_id": 74415727, "author": "wrm", "author_id": 20483162, "author_profile": "https://Stackoverflow.com/users/20483162", "pm_score": 1, "selected": false, "text": "getopt()" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18439551/" ]
74,415,648
<p>I have query:</p> <pre><code>SELECT (SELECT employee_title FROM sf_employee WHERE id = T1.worker_ref_id) AS employee_title, (SELECT sex FROM sf_employee WHERE id = T1.worker_ref_id) AS sex, ((SELECT salary FROM sf_employee WHERE id = T1.worker_ref_id) + bonus_sum) as sum_plus_bonus FROM (SELECT worker_ref_id, SUM(bonus) as bonus_sum FROM sf_bonus GROUP BY worker_ref_id) AS T1 </code></pre> <p>and the only way I know how to do the grouping is to make this table a subquery in the T2 table in FROM and then group and find the average value for the first and second columns by salary with bonuses:</p> <pre><code>SELECT employee_title, sex, AVG(sum_plus_bonus) AS avg_salary FROM (SELECT (SELECT employee_title FROM sf_employee WHERE id = T1.worker_ref_id) AS employee_title, (SELECT sex FROM sf_employee WHERE id = T1.worker_ref_id) AS sex, ((SELECT salary FROM sf_employee WHERE id = T1.worker_ref_id) + bonus_sum) as sum_plus_bonus FROM (SELECT worker_ref_id, SUM(bonus) as bonus_sum FROM sf_bonus GROUP BY worker_ref_id) AS T1) AS T2 GROUP BY employee_title, sex </code></pre> <p>It works, but I have no experience, so it looks a bit strange to me, I think I can do without adding code as in the second option. I am not interested in JOINs and some other functions, I am training subqueries to be confident in using them, if anyone is interested in the task, here it is: <a href="https://platform.stratascratch.com/coding/10077-income-by-title-and-gender?code_type=5" rel="nofollow noreferrer">https://platform.stratascratch.com/coding/10077-income-by-title-and-gender?code_type=5</a></p> <p>It's what i want to do and i got error:</p> <pre><code>SELECT (SELECT employee_title FROM sf_employee WHERE id = T1.worker_ref_id) AS employee_title, (SELECT sex FROM sf_employee WHERE id = T1.worker_ref_id) AS sex, AVG((SELECT salary FROM sf_employee WHERE id = T1.worker_ref_id) + bonus_sum) as sum_plus_bonus FROM (SELECT worker_ref_id, SUM(bonus) as bonus_sum FROM sf_bonus GROUP BY worker_ref_id) AS T1 GROUP BY employee_title, sex </code></pre> <p>i add AVG and GROUP BY</p>
[ { "answer_id": 74415720, "author": "Slonsoid", "author_id": 20474992, "author_profile": "https://Stackoverflow.com/users/20474992", "pm_score": 2, "selected": false, "text": "SELECT" }, { "answer_id": 74416098, "author": "d r", "author_id": 19023353, "author_profile": "https://Stackoverflow.com/users/19023353", "pm_score": 1, "selected": false, "text": "WITH\n sf_employee (ID, FIST_NAME, LAST_NAME, AGE, SEX, EMPLOYEE_TITLE, DEPARTMENT, SALARY, TARGET, EMAIL, CITY, ADDRESS, MANAGER_ID) AS\n (\n Select 1, 'John', 'Doe', 35, 'M', 'TITLE A', '10', 2000, 2200, 'john.doe@domain.com', 'Boston', '79, Some Street', 9 From Dual Union All\n Select 2, 'Sam', 'Smith', 25, 'M', 'TITLE C', '10', 1800, 2050, 'sam.smith@domain.com', 'Boston', '321, Some Other Street', 9 From Dual Union All\n Select 3, 'Jane', 'Doe', 31, 'F', 'TITLE B', '20', 1920, 2200, 'jane.doe@domain.com', 'Boston', '79, Some Street', 8 From Dual Union All\n Select 4, 'Ann', 'Chriss', 47, 'F', 'TITLE A', '20', 2100, 2500, 'annchriss.doe@domain.org', 'Boston', '1110, Some Big Street', 8 From Dual Union All\n Select 5, 'Bob', 'Flint', 54, 'M', 'TITLE A', '30', 2150, 2500, 'bobie.boy@domain.com', 'Boston', '1, Some Street', 7 From Dual \n ),\n sf_bonus (WORKER_REF_ID, BONUS) AS\n (\n Select 1, 175 From Dual Union All\n Select 4, 200 From Dual Union All\n Select 1, 145 From Dual Union All\n Select 5, 250 From Dual \n )\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18282659/" ]
74,415,658
<p>I've started learning <code>numpy</code> since yesterday.</p> <p><strong>my AIM is</strong></p> <p>Extract <code>odd index</code> elements from numpy array &amp; <code>even index</code> elements from numpy and merge side by side vertically.</p> <p>Let's say I have the array</p> <pre><code>mat = np.array([[1, 1, 0, 0, 0], [0, 1, 0, 0, 1], [1, 0, 0, 1, 1], [0, 0, 0, 0, 0], [1, 0, 1, 0, 1]]) </code></pre> <p><a href="https://i.stack.imgur.com/XTsI2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XTsI2.png" alt="see this picture" /></a></p> <p>What I've tried.</p> <p>--&gt;I've done transposing as I've to merge side by by side vertically.</p> <p><code>mat = np.transpose(mat)</code></p> <p>Which gives me</p> <pre><code>[[1 0 1 0 1] [1 1 0 0 0] [0 0 0 0 1] [0 0 1 0 0] [0 1 1 0 1]] </code></pre> <p>I've tried accessing odd index elements</p> <p><code>odd = mat[1::2] print(odd)</code></p> <p>Gives me</p> <p><code>[[1 1 0 0 0]</code> ----&gt; wrong...should be <code>[0,1,0,0,1]</code> right? I'm confused</p> <p><code>[0 0 1 0 0]]</code> ---&gt;wrong...Should be <code>[0,0,0,0,0]</code> right? Where these are coming from?</p> <p>My final output should like like</p> <pre><code>[[0 0 1 1 1] [1 0 1 0 0] [0 0 0 0 1] [0 0 0 1 0] [1 0 0 1 1]] </code></pre> <p>Type - <code>np.nd array</code></p>
[ { "answer_id": 74415784, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "mat[np.r_[1:mat.shape[0]:2,:mat.shape[0]:2]].T\n" }, { "answer_id": 74415786, "author": "Bhargav", "author_id": 15358800, "author_profile": "https://Stackoverflow.com/users/15358800", "pm_score": 2, "selected": true, "text": " 1. convert array to list\n 2. Access nested list items based on mat[1::2] - odd & mat[::2] for even\n 3. concat them using np.concat at `axis =0` vertically.\n 4. Transpose them.\n" }, { "answer_id": 74416244, "author": "hpaulj", "author_id": 901925, "author_profile": "https://Stackoverflow.com/users/901925", "pm_score": 2, "selected": false, "text": "In [244]: mat = np.array([[1, 1, 0, 0, 0],\n ...: [0, 1, 0, 0, 1],\n ...: [1, 0, 0, 1, 1],\n ...: [0, 0, 0, 0, 0],\n ...: [1, 0, 1, 0, 1]])\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20487724/" ]
74,415,661
<p>I have a MATLAB application that reads a .bin file and parses through the data. I am trying to convert this script from MATLAB to Python but am seeing discrepancies in the values being read.</p> <p>The read function utilized in the MATLAB script is:</p> <pre class="lang-matlab prettyprint-override"><code>fname = 'file.bin'; f=fopen(fname); data = fread(f, 100); fclose(f); </code></pre> <p>The Python conversion I attempted is: (<strong>edited</strong>)</p> <pre class="lang-py prettyprint-override"><code>fname = 'file.bin' with open(fname, mode='rb') as f: data= list(f.read(100)) </code></pre> <p>I would then print a side-by-side comparison of the read bytes with their index and found discrepancies between the two. I have confirmed that the values read in Python are correct by executing <code>$ hexdump -n 100 -C file.bin</code> and by viewing the file's contents on the application HexEdit.</p> <p>I would appreciate any insight into the source of discrepancies between the two programs and how I may be able to resolve it.</p> <p>Note: I am trying to only utilize built-in Python libraries to resolve this issue.</p> <p><strong>Solution</strong>: Utilizing incorrect file path/structure between programming languages. Implementing @juanpa.arrivillaga's suggestion cleanly reproduced the MATLAB results.</p>
[ { "answer_id": 74415789, "author": "Ahmed AEK", "author_id": 15649230, "author_profile": "https://Stackoverflow.com/users/15649230", "pm_score": 0, "selected": false, "text": "fname = 'file.bin'\nwith open(fname, mode='rb') as f:\n bytes_arr = f.read(100)\n # Conversion for visual comparison purposes\n data = [x for x in bytes_arr]\nprint(data)\n" }, { "answer_id": 74415948, "author": "Cris Luengo", "author_id": 7328782, "author_profile": "https://Stackoverflow.com/users/7328782", "pm_score": 1, "selected": false, "text": "data = np.frombuffer(f.read(100), dtype=np.uint8).astype(np.float64)\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10935387/" ]
74,415,677
<p>I am writing a small project on django with an app 'santechnic' and ran into a problem.to In which folder should I upload the images in the model Product so that the get request can find them?</p> <blockquote> <p>santechnic/models.py</p> </blockquote> <pre><code>class Category(models.Model): category_name = models.CharField(max_length=200, default=&quot;&quot;, primary_key=True) category_image = models.ImageField(default=&quot;&quot;, upload_to='upload/images/categories') class Product(models.Model): product_name = models.CharField(max_length=200, primary_key=True) length = models.FloatField(default=0.0) width = models.FloatField(default=0.0) height = models.FloatField(default=0.0) product_image = models.ImageField(default=&quot;&quot;, upload_to=) category = models.ForeignKey(Category, on_delete=models.CASCADE) </code></pre> <blockquote> <p>urls.py</p> </blockquote> <pre><code>urlpatterns = [ path('admin/', admin.site.urls), path('santechnic/', include('santechnic.urls')) ] </code></pre> <blockquote> <p>santechnic/urls.py</p> </blockquote> <pre><code>app_name = &quot;santechnic&quot; urlpatterns = \[ path('', views.CategoryView.as_view(), name='category'), path('\&lt;slug:category_name\&gt;/', views.ProductsView.as_view(), name='products'), path('\&lt;slug:category_name\&gt;/\&lt;slug:product_name\&gt;/', views.ProductDetailView.as_view(), name='detail'), \] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) </code></pre> <blockquote> <p>santechnic/views.py</p> </blockquote> <pre><code>class CategoryView(generic.ListView): template_name = 'santechnic/home.html' context_object_name = 'category_list' model = Category class ProductsView(generic.ListView): template_name = 'santechnic/products.html' context_object_name = 'products_list' model = Product </code></pre> <blockquote> <p>part of settings.py</p> </blockquote> <pre><code>MEDIA_URL = '' MEDIA_ROOT = '' </code></pre> <blockquote> <p>Directory</p> </blockquote> <p><a href="https://i.stack.imgur.com/LYPLV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LYPLV.png" alt="enter image description here" /></a></p> <p>I've tried generate path:</p> <pre><code>def generate_path(instance, filename): return '%s/upload/images/products/' % instance.category.category_name </code></pre> <p>But I had exception SuspiciousFileOperation.</p> <p>Also for example I manually add path 'toilets/upload/images/products' in upload_to and got &quot;GET /santechnic/toilets/toilets/upload/images/products/1.png HTTP/1.1&quot; 404 (here category_name='toilets').</p> <p>If path is 'upload/images/products' I again get &quot;GET /santechnic/toilets/upload/images/products/1.png HTTP/1.1&quot; 404</p> <p>Help me, please. How can I solve it?</p>
[ { "answer_id": 74418094, "author": "Ardu1na", "author_id": 20381841, "author_profile": "https://Stackoverflow.com/users/20381841", "pm_score": -1, "selected": false, "text": "pip install pillow\n" }, { "answer_id": 74418893, "author": "Manoj Tolagekar", "author_id": 17808039, "author_profile": "https://Stackoverflow.com/users/17808039", "pm_score": 0, "selected": false, "text": "product_image = models.ImageField(upload_to=\"images/\") #after writing this, it will create media/images folder inside your project.\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20473088/" ]
74,415,710
<p>I wanted to make a Japanese transliteration program. I won't explain the details, but some characters in pairs have different values ​​than if they were separated, so I made a loop that gets two characters (current and next)</p> <pre><code>b = &quot;きゃきゃ&quot; b = list(b) name = &quot;&quot; for i in b: if b.index(i) + 1 &lt;= len(b) - 1: if i in &quot;き / キ&quot; and b[b.index(i) + 1] in &quot;ゃ ャ&quot;: if b[b.index(i) + 1] != &quot; &quot;: del b[b.index(i) + 1] del b[int(b.index(i))] cur = &quot;kya&quot; name += cur print(name) </code></pre> <p>but it always automatically giving an index 0 to &quot;き&quot;, so i can't check it more than once. How can i change that?</p> <p>I tried to delete an element after analyzing it.... but it didn't help.</p>
[ { "answer_id": 74418094, "author": "Ardu1na", "author_id": 20381841, "author_profile": "https://Stackoverflow.com/users/20381841", "pm_score": -1, "selected": false, "text": "pip install pillow\n" }, { "answer_id": 74418893, "author": "Manoj Tolagekar", "author_id": 17808039, "author_profile": "https://Stackoverflow.com/users/17808039", "pm_score": 0, "selected": false, "text": "product_image = models.ImageField(upload_to=\"images/\") #after writing this, it will create media/images folder inside your project.\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20434184/" ]
74,415,752
<p>When running the LINQ Query below against Oracle 11g instance, it will throw an OUTER APPLY not supported error.</p> <pre class="lang-cs prettyprint-override"><code>var shipmentDetails = ( from r in _db.XXF_SHIPMENT_DETAILs where r.SHIP_TO == tradingPartnerId &amp;&amp; r.PICKUP_DATE &gt;= pickUpDate select r) .GroupBy(x =&gt; x.HEADERID) .Select(x =&gt; x.FirstOrDefault()); </code></pre> <blockquote> <p>&quot;OUTER APPLY is not supported by Oracle Database 11g and lower. Oracle 12c or higher is required to run this LINQ statement correctly. If you need to run this statement with Oracle Database 11g or lower, rewrite it so that it can be converted to SQL, supported by the version of Oracle you use.&quot;</p> </blockquote>
[ { "answer_id": 74418094, "author": "Ardu1na", "author_id": 20381841, "author_profile": "https://Stackoverflow.com/users/20381841", "pm_score": -1, "selected": false, "text": "pip install pillow\n" }, { "answer_id": 74418893, "author": "Manoj Tolagekar", "author_id": 17808039, "author_profile": "https://Stackoverflow.com/users/17808039", "pm_score": 0, "selected": false, "text": "product_image = models.ImageField(upload_to=\"images/\") #after writing this, it will create media/images folder inside your project.\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/129580/" ]
74,415,809
<p>Its a simple poll app in Js. where user vote count and percentages will change accordingly. But the problem i am facing is the percentages are not updated, lets say total vote is 5 and yes vote is 3 among them so yes vote percentage should be updates as the no votes comes along but it not been updated automatically.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let count = document.getElementById('count') let ncount = document.getElementById('ncount') let num = 0; let nnum = 0; document.getElementById('btn').addEventListener('click', () =&gt; { let nper = document.getElementById('per') num++ let total = num + nnum let totalPercentages = num / total * 100 count.innerHTML = num + " " + "percentages" + totalPercentages + '%' nper.innerHTML = nnum + num + '&lt;div&gt;&lt;/div&gt;' + "total vote cast" }) document.getElementById('Nbtn').addEventListener('click', () =&gt; { let per = document.getElementById('per') nnum++ let total = num + nnum let totalPercentages = nnum / total * 100 ncount.innerHTML = nnum + " " + totalPercentages + '%' per.innerHTML = num + nnum + '&lt;div&gt;&lt;/div&gt;' + "total vote cast" })</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;title&gt;Document&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;fieldset&gt; &lt;legend&gt;do you like pizza&lt;/legend&gt; &lt;div id="count"&gt; 0&lt;/div&gt; &lt;button id="btn"&gt;yes&lt;/button&gt; &lt;br&gt;&lt;/br&gt; &lt;div id="ncount"&gt; 0&lt;/div&gt; &lt;button id="Nbtn"&gt;no&lt;/button&gt; &lt;br&gt;&lt;/br&gt; &lt;div id="per"&gt;&lt;/div&gt; &lt;/fieldset&gt; &lt;script src="main.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74418094, "author": "Ardu1na", "author_id": 20381841, "author_profile": "https://Stackoverflow.com/users/20381841", "pm_score": -1, "selected": false, "text": "pip install pillow\n" }, { "answer_id": 74418893, "author": "Manoj Tolagekar", "author_id": 17808039, "author_profile": "https://Stackoverflow.com/users/17808039", "pm_score": 0, "selected": false, "text": "product_image = models.ImageField(upload_to=\"images/\") #after writing this, it will create media/images folder inside your project.\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19928051/" ]
74,415,821
<p>this creates an infinite loop</p> <pre><code>for (i=0;++i;){ console.log(i) } </code></pre> <p>this one doesn't even executed why</p> <pre><code>for (i=0;i++;){ console.log(i) } </code></pre> <p>want to understand it completely in depth</p>
[ { "answer_id": 74415851, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 2, "selected": true, "text": "for(/* runs first before the loop */;\n/* runs before every iteration, if this one is falsy, the loop breaks */;\n/* runs after every iteraion */)\n" }, { "answer_id": 74415875, "author": "Pixtane", "author_id": 15648032, "author_profile": "https://Stackoverflow.com/users/15648032", "pm_score": -1, "selected": false, "text": "for (let step = 0; step < 5; step++) {\n // Runs 5 times, with values of step 0 through 4.\n console.log('Walking east one step');\n}\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20487930/" ]
74,415,857
<p>I'm trying to learn Node.js and I'm currently making an Express app (using ejs) that will return values from a <strong>MySQL database</strong>, depending on the URL the user visits.</p> <p>For example, visiting <code>http://localhost:3000/test</code> will list all users from the db table <code>users</code>. And the link <code>http://localhost:3000/test/3</code> will return information about the user with the id number 3.</p> <p>My code for: <strong>/test</strong></p> <pre><code>app.get(&quot;/test&quot;, (req, res) =&gt; { let sql = &quot;SELECT * FROM users ORDER BY name&quot;; db.query(sql, function (err, results, fields) { if (err) logmessage(err.message); res.render(&quot;test&quot;, { data: results }); }); }); </code></pre> <p>And here is the code for <strong>/test/:id</strong></p> <pre><code>app.get(&quot;/test/:id&quot;, (req, res) =&gt; { var userId = req.params.id; let sql = &quot;SELECT * FROM users WHERE id = &quot; + userId; db.query(sql, function (err, results, fields) { if (err || !results.length) { res.redirect(&quot;/&quot;); } else { res.render(&quot;test_user&quot;, { data: results }); } }); }); </code></pre> <p>My question is: is this safe? When I previously worked in PHP development, I used to prepare statements before making any queries.</p> <p>What happens if a user changes the URL from: <code>http://localhost:3000/test/3</code> and inserts some SQL injection code at the end of the url? Can the database be breached?</p> <p>This will be for a live app on the web, so it's important no SQL injection can be made. I also want to add a form later on (req.body instead of req.params) that I also need to sanitize.</p> <p>Or is there a built-in &quot;prepared statement&quot; already in Node?</p>
[ { "answer_id": 74415894, "author": "Heiko Theißen", "author_id": 16462950, "author_profile": "https://Stackoverflow.com/users/16462950", "pm_score": 1, "selected": false, "text": "let sql = \"SELECT * FROM users WHERE id = ?\";\ndb.query(sql, [userId], function (err, results, fields) {...});\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13776183/" ]
74,415,859
<p>I was searching in the net about connection between STM32 microcontroller and AWS IoT core, didnt come across any. I cam across articles where the discovery board of STM32 is used to connect to AWS IoT core. But I want a simple way to connect the STM32 microcontroller to AWS IoT core with the help of WiFi module (since STM32 microcontroller boards dont usually have WiFi modules)</p> <p>I tried searching as I have already told but didnt come any resources related to what I was searching. I was specifically looking for resources related to STM32F1 series.</p>
[ { "answer_id": 74415894, "author": "Heiko Theißen", "author_id": 16462950, "author_profile": "https://Stackoverflow.com/users/16462950", "pm_score": 1, "selected": false, "text": "let sql = \"SELECT * FROM users WHERE id = ?\";\ndb.query(sql, [userId], function (err, results, fields) {...});\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20488007/" ]
74,415,866
<p>Why does onClick={props.onClickFunction(1)}&gt; doest not work ?</p> <pre><code>Function Button(props) { // const handleClick = () =&gt; setCounter(counter+1); return ( &lt;button onClick={props.onClickFunction(1)}&gt; +{props.increment} &lt;/button&gt; } </code></pre> <p>Why should I use another function `</p> <pre><code>function Button(props) { const handleClick = () =&gt; props.onClickFunction(1) return ( &lt;button onClick={handleClick}&gt; +{props.increment} &lt;/button&gt; ); } </code></pre> <p>`</p> <p>When I tried declaring handleclick function it's working .</p>
[ { "answer_id": 74415956, "author": "Dakeyras", "author_id": 1857909, "author_profile": "https://Stackoverflow.com/users/1857909", "pm_score": 2, "selected": false, "text": "// top example\nhandleClick = () => props.onClickFunction(1)\n\n// bottom example\nhandleClick = props.onClickFunction(1)\n" }, { "answer_id": 74416101, "author": "Yilmaz", "author_id": 10262805, "author_profile": "https://Stackoverflow.com/users/10262805", "pm_score": 1, "selected": true, "text": " // you are passing an event handler\n <button onClick={handleClick}>\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13996575/" ]
74,415,867
<p>Hello I wanted to test my method from an interface that extends from JpaRepository but I've go a strange behaviour. Every single test passes but when I run them all together the test named <code>shouldFindSingleRecipeByName()</code> doesn't pass and the error is:</p> <pre class="lang-java prettyprint-override"><code>expected: &quot;[com.example.recipesapi.model.Recipe@45f421c] (List12@14983265)&quot; but was: &quot;[com.example.recipesapi.model.Recipe@45f421c] (ArrayList@361483eb)&quot; org.opentest4j.AssertionFailedError: expected: &quot;[com.example.recipesapi.model.Recipe@45f421c] (List12@14983265)&quot; but was: &quot;[com.example.recipesapi.model.Recipe@45f421c] (ArrayList@361483eb)&quot; </code></pre> <p>I get that there is difference between <code>expected</code> and <code>but was</code> but I don't understand why when i run single test it passes and how to make it pass all together.</p> <pre class="lang-java prettyprint-override"><code>@DataJpaTest class RecipeRepositoryTest { @Autowired private RecipeRepository recipeRepositoryUnderTest; @BeforeEach void tearDown() { recipeRepositoryUnderTest.deleteAll(); } @Test void shouldFindSingleRecipeByName() { //given String searchName = &quot;Tomato soup&quot;; Recipe recipe1 = new Recipe( 1L, &quot;Tomato soup&quot;, &quot;Delicious tomato soup&quot;, Arrays.asList(&quot;1. &quot;, &quot;2. &quot;), Arrays.asList(&quot;1. &quot;, &quot;2. &quot;) ); Recipe recipe2 = new Recipe( 2L, &quot;Mushrooms soup&quot;, &quot;Delicious mushrooms soup&quot;, Arrays.asList(&quot;1. &quot;, &quot;2. &quot;), Arrays.asList(&quot;1. &quot;, &quot;2. &quot;) ); List&lt;Recipe&gt; recipes = List.of(recipe1, recipe2); recipeRepositoryUnderTest.saveAll(recipes); //when List&lt;Recipe&gt; recipesList = recipeRepositoryUnderTest.findRecipeByName(searchName.toLowerCase()); //then assertThat(recipesList).isEqualTo(List.of(recipe1)); } @Test void shouldFindTwoRecipesByName() { //given String searchName = &quot;oup&quot;; Recipe recipe1 = new Recipe( 1L, &quot;Tomato soup&quot;, &quot;Delicious tomato soup&quot;, Arrays.asList(&quot;1. &quot;, &quot;2. &quot;), Arrays.asList(&quot;1. &quot;, &quot;2. &quot;) ); Recipe recipe2 = new Recipe( 2L, &quot;Mushrooms soup&quot;, &quot;Delicious mushrooms soup&quot;, Arrays.asList(&quot;1. &quot;, &quot;2. &quot;), Arrays.asList(&quot;1. &quot;, &quot;2. &quot;) ); List&lt;Recipe&gt; recipes = List.of(recipe1, recipe2); recipeRepositoryUnderTest.saveAll(recipes); //when List&lt;Recipe&gt; recipesList = recipeRepositoryUnderTest.findRecipeByName(searchName.toLowerCase()); //then assertThat(recipesList).isEqualTo(List.of(recipe1, recipe2)); } @Test void findByNameShouldReturnEmptyListOfRecipes() { //given String searchName = &quot;Tomato soup&quot;; //when List&lt;Recipe&gt; recipesList = recipeRepositoryUnderTest.findRecipeByName(searchName.toLowerCase()); //then assertThat(recipesList).isEqualTo(List.of()); } } </code></pre> <p>Recipe class code:</p> <pre class="lang-java prettyprint-override"><code>@AllArgsConstructor @NoArgsConstructor @Getter @Entity @Table(name = &quot;Recipes&quot;) public class Recipe { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotBlank @NotNull @NotEmpty private String name; @NotNull @NotEmpty @NotBlank private String description; @ElementCollection private List&lt;String&gt; ingredients; @ElementCollection private List&lt;String&gt; directions; @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false; final Recipe recipe = (Recipe) o; return id != null &amp;&amp; Objects.equals(id, recipe.id); } @Override public int hashCode() { return getClass().hashCode(); } } </code></pre>
[ { "answer_id": 74419432, "author": "Oleksii Zghurskyi", "author_id": 2810730, "author_profile": "https://Stackoverflow.com/users/2810730", "pm_score": 1, "selected": false, "text": ".containsExactly" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10937817/" ]
74,415,884
<p>I know this code won't work in the current state because it will just select the first <code>modal</code> class. I have tried many variations of using <code>querySelectorAll</code> and <code>forEach</code> loops in the functions and event listeners but I can't seem to get it right.</p> <p>How can I convert the current code to work with the different project card modals?</p> <pre class="lang-js prettyprint-override"><code>// Project card modals const modal = document.querySelector('.modal') const trigger = document.querySelector('.trigger') const closeButton = document.querySelector('.close-button') const body = document.querySelector('body') function toggleModal() { modal.classList.toggle('show-modal') showModal() } function windowOnClick(event) { if (this.event.target === modal) { toggleModal() showModal() } } trigger.addEventListener('click', toggleModal) closeButton.addEventListener('click', toggleModal) window.addEventListener('click', windowOnClick) // Disable body scroll with modal open const showModal = function (e) { if (modal.classList.contains('show-modal')) { // Disable scroll body.style.overflow = 'hidden' } else { // Enable scroll body.style.overflow = 'auto' } } </code></pre> <pre class="lang-html prettyprint-override"><code>&lt;div class=&quot;projects-container&quot;&gt; &lt;div class=&quot;projects-grid&quot;&gt; &lt;div class=&quot;project-cell&quot;&gt; &lt;div class=&quot;project-tile trigger&quot;&gt; &lt;img Card Image /&gt; &lt;/div&gt; &lt;div class=&quot;modal&quot;&gt; &lt;div class=&quot;modal-content&quot;&gt; &lt;div class=&quot;close-button&quot;&gt;&amp;times;&lt;/div&gt; Modal Content &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <pre class="lang-css prettyprint-override"><code>.modal { position: fixed; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(68, 71, 90, 0.8); backdrop-filter: blur(20px) saturate(180%); opacity: 0; visibility: hidden; transform: scale(1.1); transition: visibility 0s linear 0.25s, opacity 0.25s 0s, transform 0.25s; z-index: 5; } .modal-content { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); padding: 1rem 2rem; width: 70%; background-color: rgb(40, 42, 54, 0.8); border-radius: 5px; backdrop-filter: blur(20px) saturate(180%); border: 2px solid transparent; box-shadow: 0 0 5px 1px var(--dracula-background); } .close-button { width: 1.5rem; line-height: 1.5rem; text-align: center; border-radius: 3px; color: black; font-weight: 500; background-color: rgba(255, 85, 85, 0.7); cursor: url('../assets/images/icons/cursor-hand-white.png'), auto; position: absolute; right: 0; top: 0; transition: ease all 0.1s; } .show-modal { opacity: 1; visibility: visible; transform: scale(1); transition: visibility 0s linear 0s, opacity 0.25s 0s, transform 0.25s; } </code></pre>
[ { "answer_id": 74419432, "author": "Oleksii Zghurskyi", "author_id": 2810730, "author_profile": "https://Stackoverflow.com/users/2810730", "pm_score": 1, "selected": false, "text": ".containsExactly" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8298834/" ]
74,415,900
<p>I have a pretty basic problem that I can't seem to solve:</p> <p>Take 3 vectors:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>V1</th> <th>V2</th> <th>V3</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>4</td> <td>7</td> </tr> <tr> <td>2</td> <td>5</td> <td>8</td> </tr> <tr> <td>3</td> <td>6</td> <td>9</td> </tr> </tbody> </table> </div> <p>I want to merge the 3 columns into a single column and assign a group.</p> <p>Desired result:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Group</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>1</td> </tr> <tr> <td>A</td> <td>2</td> </tr> <tr> <td>A</td> <td>3</td> </tr> <tr> <td>B</td> <td>4</td> </tr> <tr> <td>B</td> <td>5</td> </tr> <tr> <td>B</td> <td>6</td> </tr> <tr> <td>C</td> <td>7</td> </tr> <tr> <td>C</td> <td>8</td> </tr> <tr> <td>C</td> <td>9</td> </tr> </tbody> </table> </div> <p>My code:</p> <pre><code>V1 &lt;- c(1,2,3) V2 &lt;- c(4,5,6) V3 &lt;- c(7,8,9) data &lt;- data.frame(group = c(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;), values = c(V1, V2, V3)) </code></pre> <p>Actual result:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Group</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>1</td> </tr> <tr> <td>B</td> <td>2</td> </tr> <tr> <td>C</td> <td>3</td> </tr> <tr> <td>A</td> <td>4</td> </tr> <tr> <td>B</td> <td>5</td> </tr> <tr> <td>C</td> <td>6</td> </tr> <tr> <td>A</td> <td>7</td> </tr> <tr> <td>B</td> <td>8</td> </tr> <tr> <td>C</td> <td>9</td> </tr> </tbody> </table> </div> <p>How can I reshape the data to get the desired result?</p> <p>Thank you!</p>
[ { "answer_id": 74415953, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 3, "selected": true, "text": "stack" }, { "answer_id": 74416069, "author": "Dave2e", "author_id": 5792244, "author_profile": "https://Stackoverflow.com/users/5792244", "pm_score": 1, "selected": false, "text": "pivot_longer()" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1410769/" ]
74,415,908
<p>I've got number of places where I need to use an address in my app so I tried to make this DRY and create an address partial view like this:</p> <pre><code>@model AddressEditViewModel &lt;div class=&quot;mb-3&quot;&gt; &lt;label asp-for=&quot;Address1&quot; class=&quot;form-label&quot;&gt;&lt;/label&gt; &lt;input asp-for=&quot;Address1&quot; class=&quot;form-control&quot; /&gt; &lt;span asp-validation-for=&quot;Address1&quot; class=&quot;text-danger&quot;&gt;&lt;/span&gt; &lt;/div&gt; &lt;div class=&quot;mb-3&quot;&gt; &lt;label asp-for=&quot;Address2&quot; class=&quot;form-label&quot;&gt;&lt;/label&gt; &lt;input asp-for=&quot;Address2&quot; class=&quot;form-control&quot; /&gt; &lt;span asp-validation-for=&quot;Address2&quot; class=&quot;text-danger&quot;&gt;&lt;/span&gt; &lt;/div&gt; &lt;div class=&quot;mb-3&quot;&gt; &lt;label asp-for=&quot;City&quot; class=&quot;form-label&quot;&gt;&lt;/label&gt; &lt;input asp-for=&quot;City&quot; class=&quot;form-control&quot; /&gt; &lt;span asp-validation-for=&quot;City&quot; class=&quot;text-danger&quot;&gt;&lt;/span&gt; &lt;/div&gt; &lt;div class=&quot;row mb-3&quot;&gt; &lt;div class=&quot;col-md&quot;&gt; &lt;label asp-for=&quot;USStateID&quot; class=&quot;form-label&quot;&gt;&lt;/label&gt; &lt;select asp-items=&quot;@Model.USStates&quot; asp-for=&quot;USStateID&quot; class=&quot;form-select&quot;&gt;&lt;/select&gt; &lt;span asp-validation-for=&quot;USStateID&quot; class=&quot;text-danger&quot;&gt;&lt;/span&gt; &lt;/div&gt; &lt;div class=&quot;col-md&quot;&gt; &lt;label asp-for=&quot;Zip&quot; class=&quot;form-label&quot;&gt;&lt;/label&gt; &lt;input asp-for=&quot;Zip&quot; class=&quot;form-control&quot; /&gt; &lt;span asp-validation-for=&quot;Zip&quot; class=&quot;text-danger&quot;&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>But I had no luck when I put it into another page with the partial tag helper:</p> <pre><code>&lt;partial name=&quot;_Address&quot; model=&quot;Model.Address&quot; /&gt; </code></pre> <p>Now I understand why this technique doesn't work - that partial views are just for making HTML and don't get processed by the model binder on the way back.</p> <p>But I would prefer not to copy and paste forms all over my site. Is there any better way to reuse commonly used form bits like this?</p>
[ { "answer_id": 74415953, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 3, "selected": true, "text": "stack" }, { "answer_id": 74416069, "author": "Dave2e", "author_id": 5792244, "author_profile": "https://Stackoverflow.com/users/5792244", "pm_score": 1, "selected": false, "text": "pivot_longer()" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/339332/" ]
74,415,916
<p>My goal is to import a table of astrophysical data that I have saved to my computer (obtained from matching 2 other tables in TOPCAT, if you know it), and extract certain relevant columns. I hope to then do further manipulations on these columns. I am a complete beginner in python, so I apologise for basic errors. I've done my best to try and solve my problem on my own but I'm a bit lost.</p> <p>This script I have written so far:</p> <pre><code>import pandas as pd input_file = &quot;location\\filename&quot; dataset = pd.read_csv(input_file,skiprows=12,usecols=[1]) </code></pre> <p>The file that I'm trying to import is listed as having file type &quot;File&quot;, in my drive. I've looked at this file in Notepad and it has a lot of descriptive bumf in the first few rows, so to try and get rid of this I've used &quot;skiprows&quot; as you can see. The data in the file is separated column-wise by lines--at least that's how it appears in Notepad.</p> <p>The problem is when I try to extract the first column using &quot;usecol&quot; it instead returns what appears to be the first row in the command window, as well as a load of vertical bars between each value. I assume it is somehow not interpreting the table correctly? Not understanding what's a column and what's a row.</p> <p><strong>What I've tried:</strong> Modifying the file and saving it in a different filetype. This gives the following error:</p> <pre><code>FileNotFoundError: \[Errno 2\] No such file or directory: 'location\\filename' </code></pre> <p>Despite the fact that the new file is saved in exactly the same location.</p> <p>I've tried using &quot;pd.read_table&quot; instead of csv, but this doesn't seem to change anything (nor does it give me an error).</p> <p>When I've tried to extract multiple columns (ie &quot;usecol=[1,2]&quot;) I get the following error:</p> <pre><code>ValueError: Usecols do not match columns, columns expected but not found: \[1, 2\] </code></pre> <p>My hope is that someone with experience can give some insight into what's likely going on to cause these problems.</p>
[ { "answer_id": 74415953, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 3, "selected": true, "text": "stack" }, { "answer_id": 74416069, "author": "Dave2e", "author_id": 5792244, "author_profile": "https://Stackoverflow.com/users/5792244", "pm_score": 1, "selected": false, "text": "pivot_longer()" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20487613/" ]
74,415,918
<p>I have two inputs</p> <p>An NxM city grid where empty spaces represent vacant lots, and X's represent filled lots</p> <p>e.g</p> <pre><code>X XXX X X XXXX XX X </code></pre> <p>This is in the format List[List[str]]</p> <p>And an integer that represents the number of buildings required.</p> <p>Return a list of all possible placements, i.e. List[List[List[str]]]</p> <p>for example, a possible result using the map above and number of buildings required = 3</p> <pre><code>XBXXX BXB X XXXX XX X </code></pre> <p>another would be</p> <pre><code>X XXX X X XXXXB BXXBX </code></pre> <p>If the number of buildings required &gt; vacant lot count, return an appropriate error</p> <p>I've tried backtracking. Below is my attempt at a solution, but the 'current_city_map' can't keep track of the state one level up, as in when the 'find_permutations' returns when building_count = 0, the current city map still has the maximum building count already on it</p> <pre><code> `def can_place_building(xPos, yPos, city_map, building_code): return city_map[yPos][xPos] == ' ': def find_permutations(initial_city_map, current_city_map, building_code, required_building_count, possible_combinations): if required_building_count == 0: possible_combinations.append(current_city_map) return for x in range(len(current_city_map[0])): for y in range(len(current_city_map)): if can_place_building(x, y, current_city_map, building_code): current_city_map[y][x] = building_code find_permutations(initial_city_map, current_city_map, building_code, required_building_count - 1, possible_combinations) def find_possible_combinations(initial_city_map, required_building_count: int) -&gt; List: building_code = 'B' possible_combinations = [] current_city_map = copy.deepcopy(initial_city_map) find_permutations(initial_city_map, current_city_map, building_code, required_building_count, possible_combinations) return possible_combinations` </code></pre>
[ { "answer_id": 74415953, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 3, "selected": true, "text": "stack" }, { "answer_id": 74416069, "author": "Dave2e", "author_id": 5792244, "author_profile": "https://Stackoverflow.com/users/5792244", "pm_score": 1, "selected": false, "text": "pivot_longer()" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7734195/" ]
74,415,922
<p>I have a class with the following property exposed in the .h file:</p> <pre><code>@property (readonly, nonnull) NSArray&lt;String *&gt; * routeContext; </code></pre> <p>As you can see this is a <code>NSArray</code> which is not mutable. In the implementation though I want to be able to work with this array as a mutable one (<code>NSMutableArray</code>) so it will be easy to add, remove objects from it. What is the best approach to do it?</p> <p>I was thinking about holder a <code>NSMutableArray</code> in the m file which backs the read only <code>NSArray</code> but it seems kinda dirty to me, is there any other suggestions? The reason I don't want to set the property to <code>NSMutableArray</code> although its readonly is that readonly doesn't really make sense with <code>NSMutableArray</code>.</p> <p>Thanks.</p>
[ { "answer_id": 74417687, "author": "HangarRash", "author_id": 20287183, "author_profile": "https://Stackoverflow.com/users/20287183", "pm_score": 1, "selected": false, "text": "NSMutableArray" }, { "answer_id": 74419872, "author": "The Dreams Wind", "author_id": 5690248, "author_profile": "https://Stackoverflow.com/users/5690248", "pm_score": 0, "selected": false, "text": "routeContext" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8025085/" ]
74,415,932
<p>I'm learning Python from Brian Heinold's A Practical Introduction to Python Programming where exercise 24 in chapter 6 reads:</p> <blockquote> <p>In calculus, the derivative of <i>x</i><sup>4</sup> is 4<i>x</i><sup>3</sup>. The derivative of <i>x</i><sup>5</sup> is 5<i>x</i><sup>4</sup>. The derivative of <i>x</i>6 is 6<i>x</i><sup>5</sup>. This pattern continues. Write a program that asks the user for input like <code>x^3</code> or <code>x^25</code> and prints the derivative. For example, if the user enters <code>x^3</code>, the program should print out <code>3x^2</code>.</p> </blockquote> <p>I figured it out. Easy. However the trick is that should be solved <em><strong>without using <code>int()</code></strong></em> since it has not been mentioned in the book so far. Could you please tell me how to do that?</p> <p>Here is my solution:</p> <pre><code>original = input(&quot;Enter an x with a power: &quot;) part1 = original[2:] part2 = original[0] part3 = original[1] part4 = str(int(original[2:])-1) derivative = part1 + part2 + part3 + part4 print(&quot;The derivative is&quot;, derivative) </code></pre>
[ { "answer_id": 74416043, "author": "alexis", "author_id": 699305, "author_profile": "https://Stackoverflow.com/users/699305", "pm_score": 2, "selected": false, "text": "digits = \"0123456789\"\npower = \"25\" # from user input\nlast = power[-1]\nif last != \"0\":\n # Subtract from the last digit, e.g. \"2\" + \"4\"\n newpower = power[:-1] + digits[digits.index(last)-1]\nelse:\n # Subtract one from the tens, e.g. 30 -> 29\n tens = power[-2]\n newpower = power[:-2] + digits[digits.index(tens)-1] + \"9\"\n" }, { "answer_id": 74416195, "author": "Bhargav", "author_id": 15358800, "author_profile": "https://Stackoverflow.com/users/15358800", "pm_score": 0, "selected": false, "text": "original = input(\"Enter an x with a power: \")\npart1 = original[2:]\npart2 = original[0]\npart3 = original[1]\nc=0\npart4 = original[2:]\n\nfor i in part4: \n \n c = c * 10 + (ord(i) - 48) \npart4 = str(c-1)\n\n\n\nderivative = part1 + part2 + part3 + part4\nprint(part4)\nprint(\"The derivative is\", derivative)\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19567777/" ]
74,415,937
<p>Anyone know the cause of this error?</p> <pre><code>warn - Fast Refresh had to perform a full reload. Read more: https://nextjs.org/docs/basic-features/fast-refresh#how-it-works TypeError: Cannot read properties of null (reading 'length') at eval (webpack-internal:///./node_modules/next/dist/client/dev/error-overlay/hot-dev-client.js:262:55) </code></pre> <p>I have tried commenting out any components running in pages and creating a new NextJS-ts project from scratch but the error persists.</p>
[ { "answer_id": 74466297, "author": "nick vanderkolk", "author_id": 8560960, "author_profile": "https://Stackoverflow.com/users/8560960", "pm_score": 2, "selected": false, "text": "const hasUpdates = Boolean(updatedModules.length);" }, { "answer_id": 74480570, "author": "Zackery96", "author_id": 3173248, "author_profile": "https://Stackoverflow.com/users/3173248", "pm_score": -1, "selected": false, "text": "export default function Page(){}" }, { "answer_id": 74484946, "author": "Jordan", "author_id": 15239457, "author_profile": "https://Stackoverflow.com/users/15239457", "pm_score": -1, "selected": false, "text": "function AboutPage() {\n return <div>The About Page</div>;\n}\n\nexport default AboutPage;\n" }, { "answer_id": 74505139, "author": "Yilmaz", "author_id": 10262805, "author_profile": "https://Stackoverflow.com/users/10262805", "pm_score": 0, "selected": false, "text": "function tryApplyUpdates(onHotUpdateSuccess) {\n if (!module.hot) {\n // HotModuleReplacementPlugin is not in Webpack configuration.\n console.error('HotModuleReplacementPlugin is not in Webpack configuration.');\n // window.location.reload();\n return;\n }\n if (!isUpdateAvailable() || !canApplyUpdates()) {\n (0, _client).onBuildOk();\n return;\n }\n\n function handleApplyUpdates(err, updatedModules) {\n if (err || hadRuntimeError || !updatedModules) {\n if (err) {\n console.warn('[Fast Refresh] performing full reload\\n\\n' + \"Fast Refresh will perform a full reload when you edit a file that's imported by modules outside of the React rendering tree.\\n\" + 'You might have a file which exports a React component but also exports a value that is imported by a non-React component file.\\n' + 'Consider migrating the non-React component export to a separate file and importing it into both files.\\n\\n' + 'It is also possible the parent component of the component you edited is a class component, which disables Fast Refresh.\\n' + 'Fast Refresh requires at least one parent function component in your React tree.');\n } else if (hadRuntimeError) {\n console.warn('[Fast Refresh] performing full reload because your application had an unrecoverable error');\n }\n performFullReload(err);\n return;\n }\n const hasUpdates = Boolean(updatedModules.length);\n if (typeof onHotUpdateSuccess === 'function') {\n // Maybe we want to do something.\n onHotUpdateSuccess(hasUpdates);\n }\n if (isUpdateAvailable()) {\n // While we were updating, there was a new update! Do it again.\n // However, this time, don't trigger a pending refresh state.\n tryApplyUpdates(hasUpdates ? undefined : onBeforeHotUpdate, hasUpdates ? _client.onBuildOk : onHotUpdateSuccess);\n } else {\n (0, _client).onBuildOk();\n if (process.env.__NEXT_TEST_MODE) {\n afterApplyUpdates(()=>{\n if (self.__NEXT_HMR_CB) {\n self.__NEXT_HMR_CB();\n self.__NEXT_HMR_CB = null;\n }\n });\n }\n } \n // in here its call handleApplyUpdates\n }\n" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20216544/" ]
74,415,972
<p>An assignment is requesting that I qualify input number to ensure that it is within range of an unsigned-int on my machine. How do I determine what that range is? it says that the input needs to be taken in at execution time and that no assumptions can be made about what was entered.</p> <p>I tried using plugging in different ranges (2^7 , 2^15 , 2^31) but they all resulted in overflow.</p>
[ { "answer_id": 74416315, "author": "Andreas Wenzel", "author_id": 12149471, "author_profile": "https://Stackoverflow.com/users/12149471", "pm_score": 1, "selected": false, "text": "strtoul" }, { "answer_id": 74416392, "author": "Erdal Küçük", "author_id": 11867590, "author_profile": "https://Stackoverflow.com/users/11867590", "pm_score": 0, "selected": false, "text": "int" }, { "answer_id": 74416660, "author": "chux - Reinstate Monica", "author_id": 2410359, "author_profile": "https://Stackoverflow.com/users/2410359", "pm_score": 2, "selected": false, "text": "unsigned" } ]
2022/11/12
[ "https://Stackoverflow.com/questions/74415972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20486502/" ]