qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,496,464
<p>I am trying my darndest to accomplish this relatively simple layout for 2-3 elements. Everything I've tried from <code>px/fr/%</code> with <code>minmax()</code> &amp; grid can't seem to get it quite right.</p> <p>I want my <code>input</code> to take up all remaining space leftover whether or not the <code>button</code> is present. The <code>select</code> should remain the same size regardless if <code>button</code> is present.</p> <p>The percentages make most sense, but isn't exactly working like I'd like. no button: 75% input + 25% select with button: 50% input + 25% select + 25% button</p> <p>What am I missing on getting this to work? Am I just thinking about this wrong? SHOW ME THE WAY!</p> <p>I've even tried adding independent css to each element with the <code>grid-column: 1 / 3</code>:</p> <pre><code>.input-grid .input-grid-input { grid-column: 1 / 3 } .input-grid .input-grid-select { grid-column: 4 } .input-grid .input-grid-button { grid-column: 5 } </code></pre> <p>With out button:</p> <p><a href="https://i.stack.imgur.com/zNhTQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zNhTQ.png" alt="how I want it to look with no button" /></a></p> <p>With button:</p> <p><a href="https://i.stack.imgur.com/Vc9Ti.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Vc9Ti.png" alt="how I want it to look with a button" /></a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.input-grid { display: grid; grid-auto-flow: column; grid-template-rows: 1fr; grid-column-gap: 0; grid-template-columns: minmax(50%, 75%) 25% minmax(0, 25%); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="input-grid"&gt; &lt;input type="text" class="input-grid-input" value="input" data-form-type="other"&gt; &lt;select class="input-grid-select" data-form-type="other"&gt; &lt;option value="Select Value 1"&gt;Select Value 1&lt;/option&gt; &lt;option value="Select Value 2" disabled="disabled"&gt;Select Value 2&lt;/option&gt; &lt;/select&gt; &lt;button class="btn input-grid-btn btn--primary" hidden="hidden"&gt; Check Availability &lt;/button&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74496519, "author": "Tesmond H", "author_id": 11169088, "author_profile": "https://Stackoverflow.com/users/11169088", "pm_score": 0, "selected": false, "text": ".grid {\n display: flex;\n}\n\n.grid input {\n display: flex;\n flex: 1 1 auto;\n}\n\ninput[type = button] {\n display: block;\n text - align: center;\n max - width: 150px;\n}\n <div class=\"grid\">\n <input type=\"text\" placeholder=\"Input text\">\n <select><option>Choose option</option></select>\n <input type=\"button\" value=\"Check Availability\">\n</div>\n" }, { "answer_id": 74496579, "author": "Itagaki Fumihiko", "author_id": 15821526, "author_profile": "https://Stackoverflow.com/users/15821526", "pm_score": 2, "selected": true, "text": "grid-template-columns max-content" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74496464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1908512/" ]
74,496,472
<p>i have date value coming as 2022-11-18T00:00:01.012345678Z and would like to store it as &gt;2022-11-18T00:00:01.012345678 in snowflake timestamp data type column.</p> <p>i am using following but it's always outputting 2022-11-18 00:00:01.012 .</p> <p><code>to_timestamp('2022-11-18T00:00:01.012345678z','YYYY-MM-DD&quot;T&quot;HH24:MI:SS.FF9')</code></p> <p>please suggest.</p>
[ { "answer_id": 74497082, "author": "Mike Walton", "author_id": 12178980, "author_profile": "https://Stackoverflow.com/users/12178980", "pm_score": 1, "selected": false, "text": "SELECT to_timestamp('2022-11-18T00:00:01.012345678Z','YYYY-MM-DDTHH:MI:SS.FF9Z');\n SELECT to_varchar(to_timestamp('2022-11-18T00:00:01.012345678Z','YYYY-MM-DDTHH:MI:SS.FF9Z'),'YYYY-MM-DDTHH:MI:SS.FF9');\n ALTER SESSION TIMESTAMP_LTZ_OUTPUT_FORMAT = 'YYYY-MM-DDTHH:MI:SS.FF9'\nTIMESTAMP_NTZ_OUTPUT_FORMAT = 'YYYY-MM-DDTHH:MI:SS.FF9'\nTIMESTAMP_OUTPUT_FORMAT = 'YYYY-MM-DDTHH:MI:SS.FF9'\n" }, { "answer_id": 74497215, "author": "Simeon Pilgrim", "author_id": 43992, "author_profile": "https://Stackoverflow.com/users/43992", "pm_score": 0, "selected": false, "text": "SELECT column1 as as_string\n ,to_timestamp(as_string,'YYYY-MM-DDTHH:MI:SS.FF9Z') as as_timestamp\n ,to_varchar(as_timestamp, 'YYYY-MM-DDTHH:MI:SS.FF9') as as_string_again\nfrom values \n ('2022-11-18T00:00:01.012345678Z'),\n ('2022-11-18T00:00:02.123456789Z');\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74496472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18752600/" ]
74,496,484
<p>I'm trying to add an additional argument to this mute command I have made for my discord.py bot but I'm getting a SyntaxError and have been having trouble understanding the syntax for what I'm trying to do.</p> <p>Here is the part of my program that is relevant to my issue:</p> <pre><code>#Tempmute Command @bot.command(name='tempmute') @commands.has_role('Moderator' or 'Admin') async def mute(ctx, member: discord.Member,time): #Retrieves the amount of time the user should be muted for muted_role=discord.utils.get(ctx.guild.roles, name=&quot;Muted&quot;) time_convert = {&quot;s&quot;:1, &quot;m&quot;:60, &quot;h&quot;:3600,&quot;d&quot;:86400} tempmute= int(time[0]) * time_convert[time[-1]] #Deletes invocation and adds muted role to target, sends embed confirming user has been delete THEN deletes embed await ctx.message.delete() await member.add_roles(muted_role) #Notifies target was muted through sending a direct message notify = discord.Embed(title=&quot;Muted&quot;, description=f&quot; You have been muted in {member.guild.name}.&quot;,colour=discord.Colour.light_gray()) #Catches an exception if the direct message fails to send try: await member.send(notify) except Exception as e: embedFail = discord.Embed(description= f&quot; **{ctx.author.mention}, I was unable to notify this user they were muted**&quot;, color=discord.Color.red()) await ctx.send(embed=embedFail, delete_after=5) embed = discord.Embed(description= f&quot;✅ **{member.display_name}#{member.discriminator} has been muted successfully&quot;, color=discord.Color.green()) await ctx.send(embed=embed, delete_after=5) #Removes role after given time await asyncio.sleep(tempmute) await member.remove_roles(muted_role) </code></pre> <p>This line defines my arguments for my asynchronous function 'mute'</p> <pre><code>async def mute(ctx, member: discord.Member,time): </code></pre> <p>When I try to add an additional argument 'reason' I run into a SyntaxError</p> <pre><code>async def mute(ctx, member: discord.Member,time,reason): </code></pre> <p>I should also note when adding the additional argument, I'm also changing my embedded message the bot displays to add the reason given from the author as well. See this changed line here:</p> <pre><code> embed = discord.Embed(description= f&quot;✅ **{member.display_name}#{member.discriminator} has been muted successfully for&quot;, reason, color=discord.Color.green()) </code></pre> <p>The error I get is: SyntaxError: positional argument follows keyword argument</p> <p>If someone could please explain why I'm not able to simply add this additional piece to my mute command I would greatly appreciate it. Thank you!</p> <p>Also if you have any additional suggestions for improving the use of this command please feel free leave a comment noting your suggestion as well. (Please take into consideration though I'm new to Python and discord.py so I may need a detailed explanation or example as to what you're suggesting I improve in my code.)</p>
[ { "answer_id": 74497082, "author": "Mike Walton", "author_id": 12178980, "author_profile": "https://Stackoverflow.com/users/12178980", "pm_score": 1, "selected": false, "text": "SELECT to_timestamp('2022-11-18T00:00:01.012345678Z','YYYY-MM-DDTHH:MI:SS.FF9Z');\n SELECT to_varchar(to_timestamp('2022-11-18T00:00:01.012345678Z','YYYY-MM-DDTHH:MI:SS.FF9Z'),'YYYY-MM-DDTHH:MI:SS.FF9');\n ALTER SESSION TIMESTAMP_LTZ_OUTPUT_FORMAT = 'YYYY-MM-DDTHH:MI:SS.FF9'\nTIMESTAMP_NTZ_OUTPUT_FORMAT = 'YYYY-MM-DDTHH:MI:SS.FF9'\nTIMESTAMP_OUTPUT_FORMAT = 'YYYY-MM-DDTHH:MI:SS.FF9'\n" }, { "answer_id": 74497215, "author": "Simeon Pilgrim", "author_id": 43992, "author_profile": "https://Stackoverflow.com/users/43992", "pm_score": 0, "selected": false, "text": "SELECT column1 as as_string\n ,to_timestamp(as_string,'YYYY-MM-DDTHH:MI:SS.FF9Z') as as_timestamp\n ,to_varchar(as_timestamp, 'YYYY-MM-DDTHH:MI:SS.FF9') as as_string_again\nfrom values \n ('2022-11-18T00:00:01.012345678Z'),\n ('2022-11-18T00:00:02.123456789Z');\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74496484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20541671/" ]
74,496,496
<p>I expected to preset the environment of node and then it installs aws-cdk which will be used for the matrix-ed jobs which are supposed to be an efficient solution for execution.</p> <p>Here is basically my script:</p> <pre><code>jobs: setup: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: check-latest: true cache-dependency-path: package-lock.json # include aws-cdk already - name: Install AWS CDK run: 'npm ci' deploy: runs-on: ubuntu-latest needs: [setup] if: needs.build.result == 'success' strategy: matrix: folder: ${{ fromJSON(needs.detect-changed-files.outputs.matrix) }} steps: - uses: actions/checkout@v3 with: fetch-depth: 2 - name: Configure AWS credentials uses: aws-actions/configure-aws-credentials@v1 with: aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} aws-region: us-east-1 role-to-assume: my-role role-duration-seconds: 14400 # You can find max duration by following this article, https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session - name: Login to Amazon ECR id: login-ecr uses: aws-actions/amazon-ecr-login@v1 - name: Deploy Service working-directory: services/infra env: CLOUD_FORMATION_ROLE: my-role ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }} run: | ENV=$(cat ../../artifact.txt) cdk deploy &quot;*&quot; -c app_name=my-app -c environment=prod -c image=${{env.ECR_REGISTRY}}/${{ matrix.folder }}:prod --require-approval never -r ${{env.CLOUD_FORMATION_ROLE}} </code></pre> <p>The error trace says: &quot;line 2: cdk: command not found&quot; in the step of &quot;Deploy Service&quot;. I have no clue since cdk should have been installed in the setup job.</p>
[ { "answer_id": 74498935, "author": "Matteo", "author_id": 2270041, "author_profile": "https://Stackoverflow.com/users/2270041", "pm_score": 1, "selected": false, "text": "jobs:\n setup-and-deploy:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v3\n with:\n fetch-depth: 2\n - uses: actions/setup-node@v3\n with:\n check-latest: true\n cache-dependency-path: package-lock.json # include aws-cdk already\n - name: Install AWS CDK\n run: 'npm ci'\n - name: Configure AWS credentials\n uses: aws-actions/configure-aws-credentials@v1\n with:\n aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}\n aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}\n aws-region: us-east-1\n role-to-assume: my-role\n role-duration-seconds: 14400 # You can find max duration by following this article, https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session\n - name: Login to Amazon ECR\n id: login-ecr\n uses: aws-actions/amazon-ecr-login@v1\n - name: Deploy Service\n working-directory: services/infra\n env:\n CLOUD_FORMATION_ROLE: my-role\n ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}\n run: |\n ENV=$(cat ../../artifact.txt)\n cdk deploy \"*\" -c app_name=my-app -c environment=prod -c image=${{env.ECR_REGISTRY}}/${{ matrix.folder }}:prod --require-approval never -r ${{env.CLOUD_FORMATION_ROLE}}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74496496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12097673/" ]
74,496,507
<p>In firebase backend I know how to authenticate user via many technics like email and password, Facebook authentication, google authentication , link and so on. So in web v9 modular to create provider object we use : <code>const provider = new GoogleAuthProvider()</code> and to add email scope we proceed like this: <code>provider.addScope('email')</code> After user login we get result.user object like this:</p> <pre><code>signInWithPopup(auth, provider) .then((result)=&gt;{ storeUser(result.user); }) .catch((err)=&gt;{ // console.log(`google err ---&gt;${err.message}`); }) .finally(()=&gt;{}); </code></pre> <p>The big question is: How could we retrieve the email after the successful login?</p>
[ { "answer_id": 74498935, "author": "Matteo", "author_id": 2270041, "author_profile": "https://Stackoverflow.com/users/2270041", "pm_score": 1, "selected": false, "text": "jobs:\n setup-and-deploy:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v3\n with:\n fetch-depth: 2\n - uses: actions/setup-node@v3\n with:\n check-latest: true\n cache-dependency-path: package-lock.json # include aws-cdk already\n - name: Install AWS CDK\n run: 'npm ci'\n - name: Configure AWS credentials\n uses: aws-actions/configure-aws-credentials@v1\n with:\n aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}\n aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}\n aws-region: us-east-1\n role-to-assume: my-role\n role-duration-seconds: 14400 # You can find max duration by following this article, https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session\n - name: Login to Amazon ECR\n id: login-ecr\n uses: aws-actions/amazon-ecr-login@v1\n - name: Deploy Service\n working-directory: services/infra\n env:\n CLOUD_FORMATION_ROLE: my-role\n ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}\n run: |\n ENV=$(cat ../../artifact.txt)\n cdk deploy \"*\" -c app_name=my-app -c environment=prod -c image=${{env.ECR_REGISTRY}}/${{ matrix.folder }}:prod --require-approval never -r ${{env.CLOUD_FORMATION_ROLE}}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74496507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11415346/" ]
74,496,521
<p>I've have seen some answers to similar questions, but I haven't seen one touching multiple conditions and I couldn't adapt any to this need.</p> <p>Basically, <code>ar1</code> should have its labels replaced by the urls.</p> <p>Here is the function beating me:</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 ar1 = [ ["Client", "Date", "Label1", "Label2"], ["A", "11/15/2022", "Label1", "Label2"], ["B", "11/15/2022", "Label1", "Label2"], ["C", "11/15/2022", "Label1", "Label2"] ]; const label1Col = ar1[0].indexOf('Label1') const label2Col = ar1[0].indexOf('Label2') let ar2 = [ ["Client", "Date", "Label2", "Label1",], ["A", "11/15/2022", "www.elonscrewing.com", "www.google.com"], ["B", "11/15/2022", "www.elonscrewing.com", "www.google.com"], ["C", "11/15/2022", "www.elonscrewing.com", "www.google.com"] ] const ar2label1Col = ar2[0].indexOf('Label1') const ar2label2Col = ar2[0].indexOf('Label2') ar1.forEach(function(val) { ar2.forEach(function(link) { val[label1Col] = link[ar2label1Col]; val[label2Col] = link[ar2label2Col]; }) }) console.log(ar1)</code></pre> </div> </div> </p> <p>Appreciate any help!</p>
[ { "answer_id": 74496580, "author": "rrrm93", "author_id": 2500733, "author_profile": "https://Stackoverflow.com/users/2500733", "pm_score": 2, "selected": false, "text": "ar2 L" }, { "answer_id": 74496607, "author": "Lord-JulianXLII", "author_id": 19529102, "author_profile": "https://Stackoverflow.com/users/19529102", "pm_score": 3, "selected": true, "text": "let ar1 = [\n [\"Client\", \"Date\", \"Label1\", \"Label2\"],\n [\"A\", \"11/15/2022\", \"Label1\", \"Label2\"],\n [\"B\", \"11/15/2022\", \"Label1\", \"Label2\"],\n [\"C\", \"11/15/2022\", \"Label1\", \"Label2\"]\n];\nconst label1Col = ar1[0].indexOf('Label1')\nconst label2Col = ar1[0].indexOf('Label2')\n\nlet ar2 = [\n [\"Client\", \"Date\", \"Label2\", \"Label1\",],\n [\"A\", \"11/15/2022\", \"www.elonscrewing.com\", \"www.google.com\"],\n [\"B\", \"11/15/2022\", \"www.elonscrewing.com\", \"www.google.com\"],\n [\"C\", \"11/15/2022\", \"www.elonscrewing.com\", \"www.google.com\"]\n]\nconst ar2label1Col = ar2[0].indexOf('Label1')\nconst ar2label2Col = ar2[0].indexOf('Label2')\nconsole.log(ar2label2Col) //this line is what you should have done in order to debug (this line caught the problem / typo)\n\nar1.forEach(function(val, index) {\n val[label1Col] = ar2[index][ar2label1Col];\n val[label2Col] = ar2[index][ar2label2Col];\n})\n\nconsole.log(ar1)" }, { "answer_id": 74496711, "author": "Lord-JulianXLII", "author_id": 19529102, "author_profile": "https://Stackoverflow.com/users/19529102", "pm_score": 1, "selected": false, "text": "let ar1 = [\n [\"Client\", \"Date\", \"Label1\", \"Label2\"],\n [\"B\", \"11/15/2022\", \"Label1\", \"Label2\"],\n [\"A\", \"11/15/2022\", \"Label1\", \"Label2\"],\n [\"C\", \"11/15/2022\", \"Label1\", \"Label2\"]\n];\nconst label1Col = ar1[0].indexOf('Label1')\nconst label2Col = ar1[0].indexOf('Label2')\nconst dateIdx = ar1[0].indexOf('Date')\nconst clientIdx = ar1[0].indexOf('Client')\n\nlet ar2 = [\n [\"Client\", \"Date\", \"Label2\", \"Label1\",],\n [\"A\", \"11/15/2022\", \"www.aaaaaaaaaaa.com\", \"www.google.com\"],\n [\"B\", \"11/15/2022\", \"www.bbbbbbbbbb.com\", \"www.google.com\"],\n [\"C\", \"11/15/2022\", \"www.elonscrewing.com\", \"www.google.com\"]\n]\nconst ar2label1Col = ar2[0].indexOf('Label1')\nconst ar2label2Col = ar2[0].indexOf('Label2')\nconst ar2ClientIdx = ar2[0].indexOf('Client')\nconst ar2DateIdx = ar2[0].indexOf('Date')\n\n\nar1.forEach(function(val) {\n ar2.forEach(function(link) {\n if (val[clientIdx] === link[ar2ClientIdx] && val[dateIdx] === link[ar2DateIdx]) {\n val[label1Col] = link[ar2label1Col];\n val[label2Col] = link[ar2label2Col];\n }\n })\n})\nconsole.log(ar1)" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74496521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11832197/" ]
74,496,525
<p>I'm having trouble translating the following JavaScript code into python. My problem is inheriting the parent properties and methods in the ChildNode class by using <code>super.__init__()</code>. In js, you just call <code>super()</code> and get all the props. It doesn't seem to be the same in python. The super function is demanding to have val and key inside the parenthesis but I'm not sure how that would work because Im getting val from the <code>ChildNode.__init__ </code>function</p> <p>JS CODE that does what I want</p> <pre><code>class BinarySearchTree { constructor(val, key) { this.val = val; this.left = null; this.right = null; this.key = key; } insert(val) { const currNode = this; if (val === currNode.val) return null; if (val &lt; currNode.val) { if (!currNode.left) { currNode.left = new ChildNode(val); return this; } else { currNode.left.insert(val); } } if (val &gt; currNode.val) { if (!currNode.right) { currNode.right = new ChildNode(val); return this; } else { currNode.right.insert(val); } } } } class ChildNode extends BinarySearchTree { constructor(val) { super(); this.val = val; delete this.key; } } var root = new BinarySearchTree(20, 14); root.insert(8); root.insert(22); root.insert(4); console.log(root); </code></pre> <p>Python attempt</p> <pre><code>class BinarySearchTree: def __init__(self, val: int, key: int): self.val = val self.left = None self.right = None self.key = key def insert(self, val): currNode = self if val == currNode.val: return None if val &lt; currNode.val: if not currNode.left: currNode.left = ChildNode(val) return self else: currNode.left.insert(val) if val &gt; currNode.val: if not currNode.right: currNode.right = ChildNode(val) return self else: currNode.right.insert(val) # having trouble inheriting here class ChildNode(BinarySearchTree): def __init__(self, val): super().__init__() self.val = val del self.key root = BinarySearchTree(20, 14) root.insert(8) root.insert(22) root.insert(4) print(root) </code></pre>
[ { "answer_id": 74496580, "author": "rrrm93", "author_id": 2500733, "author_profile": "https://Stackoverflow.com/users/2500733", "pm_score": 2, "selected": false, "text": "ar2 L" }, { "answer_id": 74496607, "author": "Lord-JulianXLII", "author_id": 19529102, "author_profile": "https://Stackoverflow.com/users/19529102", "pm_score": 3, "selected": true, "text": "let ar1 = [\n [\"Client\", \"Date\", \"Label1\", \"Label2\"],\n [\"A\", \"11/15/2022\", \"Label1\", \"Label2\"],\n [\"B\", \"11/15/2022\", \"Label1\", \"Label2\"],\n [\"C\", \"11/15/2022\", \"Label1\", \"Label2\"]\n];\nconst label1Col = ar1[0].indexOf('Label1')\nconst label2Col = ar1[0].indexOf('Label2')\n\nlet ar2 = [\n [\"Client\", \"Date\", \"Label2\", \"Label1\",],\n [\"A\", \"11/15/2022\", \"www.elonscrewing.com\", \"www.google.com\"],\n [\"B\", \"11/15/2022\", \"www.elonscrewing.com\", \"www.google.com\"],\n [\"C\", \"11/15/2022\", \"www.elonscrewing.com\", \"www.google.com\"]\n]\nconst ar2label1Col = ar2[0].indexOf('Label1')\nconst ar2label2Col = ar2[0].indexOf('Label2')\nconsole.log(ar2label2Col) //this line is what you should have done in order to debug (this line caught the problem / typo)\n\nar1.forEach(function(val, index) {\n val[label1Col] = ar2[index][ar2label1Col];\n val[label2Col] = ar2[index][ar2label2Col];\n})\n\nconsole.log(ar1)" }, { "answer_id": 74496711, "author": "Lord-JulianXLII", "author_id": 19529102, "author_profile": "https://Stackoverflow.com/users/19529102", "pm_score": 1, "selected": false, "text": "let ar1 = [\n [\"Client\", \"Date\", \"Label1\", \"Label2\"],\n [\"B\", \"11/15/2022\", \"Label1\", \"Label2\"],\n [\"A\", \"11/15/2022\", \"Label1\", \"Label2\"],\n [\"C\", \"11/15/2022\", \"Label1\", \"Label2\"]\n];\nconst label1Col = ar1[0].indexOf('Label1')\nconst label2Col = ar1[0].indexOf('Label2')\nconst dateIdx = ar1[0].indexOf('Date')\nconst clientIdx = ar1[0].indexOf('Client')\n\nlet ar2 = [\n [\"Client\", \"Date\", \"Label2\", \"Label1\",],\n [\"A\", \"11/15/2022\", \"www.aaaaaaaaaaa.com\", \"www.google.com\"],\n [\"B\", \"11/15/2022\", \"www.bbbbbbbbbb.com\", \"www.google.com\"],\n [\"C\", \"11/15/2022\", \"www.elonscrewing.com\", \"www.google.com\"]\n]\nconst ar2label1Col = ar2[0].indexOf('Label1')\nconst ar2label2Col = ar2[0].indexOf('Label2')\nconst ar2ClientIdx = ar2[0].indexOf('Client')\nconst ar2DateIdx = ar2[0].indexOf('Date')\n\n\nar1.forEach(function(val) {\n ar2.forEach(function(link) {\n if (val[clientIdx] === link[ar2ClientIdx] && val[dateIdx] === link[ar2DateIdx]) {\n val[label1Col] = link[ar2label1Col];\n val[label2Col] = link[ar2label2Col];\n }\n })\n})\nconsole.log(ar1)" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74496525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16693156/" ]
74,496,595
<p>everyone! I'm a new member of Stack Overflow, just like I'm beginner on swift programming. I'm making this post to find out a solution for the following case:</p> <p>I'm creating on Swift an app using the Command Line Tool for inputing data. The app basically works as an authenticator. As an example, if someone types USA for the country name and the age is 17, so the program will return a message like &quot;You can not apply to this position&quot;. Otherwise, if the country name is USA and the age is equal or higher than 18, so the message returns is &quot;You can forward to the next step&quot;. I've tried many times to set this conditions, but it's not working. I'm already knows that the function readLine() is an Optional String, but how can I make my program work correctly? It follows my code above to you understanding my thoughts.</p> <p>I really appreciate any help. Again, I'm beginner and I'm already studying Swift languages, but I'm seeking some solution that handles Integers and Strings and comparing both data types. Thank you very much!</p> <p>My code is:</p> <pre><code>import Foundation print(&quot;Enter your country: &quot;) var country = readLine() print(&quot;Enter your age: &quot;) var age = readLine() if var country, var age = readLine(){ if country == &quot;USA&quot; &amp;&amp; age &lt; &quot;18&quot; { print(&quot;You're not allowed to apply to this position.&quot;) } else { print(&quot;You can forward to the next step.&quot;) } } </code></pre> <p>PS: As you see, I'm using wrongly the variable age as an String, but I want to convert it to an Int type and then, check if the country name is the same than the value I assigned to or the age is equal or higher than 18. But not found a solution so far.</p> <p>I'm trying to find a solution that compares two different types on Swift, using Command Line Tool and the readLine() function to check if a condition is true or not. If it's true, an output message will show that the user can proceed to the next step, otherwise he will not be permitted to follow. I'm keeping for an explanation on internet since few days, but not found anything that might help me. I hope to get some help using the Stack Overflow forum to some useful answer.</p>
[ { "answer_id": 74496849, "author": "reema", "author_id": 17582294, "author_profile": "https://Stackoverflow.com/users/17582294", "pm_score": -1, "selected": false, "text": "import Foundation\n\nprint(\"Enter your country: \")\nif let country = readLine() {\n if let num = Int(country) {\n print(num)\n }\n }\n let country = readLine()\nlet age = readLine()\n\n\nif let USA = country, \n let num1 = Int(USA), \n let num2 = Int(USA) {\n print(\"The age of \\(num1) and \\(num2) is \\(num1 + num2)\")\n}\n" }, { "answer_id": 74496870, "author": "Thang Phi", "author_id": 10650407, "author_profile": "https://Stackoverflow.com/users/10650407", "pm_score": 3, "selected": true, "text": "readline() readLine() print(\"Enter your country: \")\nvar country = readLine()\n\nprint(\"Enter your age: \")\nvar ageString = readLine()\n if country == nil || ageString == nil {\n print(\"Error because one of them is nil\")\n fatalError()\n}\n ageString guard let ageString = ageString else {\n print(\"Error age nil\")\n fatalError()\n}\n\nguard let age = Int(ageString) else {\n print(\"Error age not a number\")\n fatalError()\n}\n print(\"Enter your country: \")\nvar country = readLine()\n\nprint(\"Enter your age: \")\nvar ageString = readLine()\n\n// check nil first if nil return or do something first and not get to the rest\nif country == nil || ageString == nil {\n print(\"Error because one of them is nil\")\n fatalError()\n}\n\nguard let ageString = ageString else {\n print(\"Error age nil\")\n fatalError()\n}\n\nguard let age = Int(ageString) else {\n print(\"Error age not a number\")\n fatalError()\n}\n\nif country == \"USA\" && age < 18 {\n print(\"You're not allowed to apply to this position.\")\n} else {\n print(\"You can forward to the next step.\")\n}\n if let print(\"Enter your country: \")\nvar country = readLine()\n\nprint(\"Enter your age: \")\nvar ageString = readLine()\n\n// check nil first if nil return or do something first and not get to the rest\nif country == nil || ageString == nil {\n print(\"Error because one of them is nil\")\n fatalError()\n}\n\nif let ageString = ageString {\n if let age = Int(ageString) {\n if country == \"USA\" && age < 18 {\n print(\"You're not allowed to apply to this position.\")\n } else {\n print(\"You can forward to the next step.\")\n }\n } else {\n print(\"Error age not a number\")\n fatalError()\n }\n}\n" }, { "answer_id": 74504565, "author": "Heber Neto", "author_id": 20543549, "author_profile": "https://Stackoverflow.com/users/20543549", "pm_score": 0, "selected": false, "text": "var countryCheck = \"USA\"\nvar ageCheck: Int = 18\n\nprint(\"Enter your country: \")\nvar country = readLine()\n\nprint(\"Enter your age: \")\nvar age = readLine()\n\nif var countryCheck = country, var ageCheck = Int(age!) {\n if countryCheck == \"USA\" && ageCheck >= 18 {\n print(\"You can apply.\")\n } else {\n print(\"You can not apply to this position.\")\n }\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74496595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20543549/" ]
74,496,611
<p>My goal is to extract an element from many list that similar like this. Taking elements that is food.</p> <pre><code>test_list = ['Tools: Pen', 'Food: Sandwich', 'Fruit: Apple' ] </code></pre> <p>I the final result would be <strong>&quot;Sandwich&quot;</strong> by look list element with the word &quot;Food:&quot; and split from there.</p> <p>My usual method is lookup by index</p> <pre><code>test_list[1].split(': ')[1] </code></pre> <p>However, I go through many lists that number of elements is varied, and I want to look up the food item in the &quot;food:&quot; section. I don't know if there is a function that would help me choose element from a list using &quot;keyword search&quot;</p> <p>Another example,</p> <pre><code>test_list_2 = ['Tools: Pen', 'Tree: Willow' 'Food: Drumstick', 'Fruit: Apple' ] </code></pre> <p>With the same lines of code, test_list_2 result would be <strong>&quot;Drumstick&quot;</strong></p> <p>Please kindly help my find a way to do that in Python. Thank you</p>
[ { "answer_id": 74496632, "author": "QWERTYL", "author_id": 11777402, "author_profile": "https://Stackoverflow.com/users/11777402", "pm_score": 0, "selected": false, "text": "test_list_2 =\n{'Tools': 'Pen',\n'Tree': 'Willow',\n'Food': 'Drumstick',\n'Fruit': 'Apple'\n}\n\nprint(test_list_2[\"Tools\"])\n" }, { "answer_id": 74496633, "author": "Iddo Sadeh", "author_id": 3620846, "author_profile": "https://Stackoverflow.com/users/3620846", "pm_score": 2, "selected": false, "text": "test_dict = {i.split(\": \")[0]: i.split(\": \")[1] for i in test_list}\n test_dict['Food']\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74496611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20543548/" ]
74,496,650
<p>I am trying to push parts of a string into two different stacks and popping them out so I can see if the string is balanced. For example, we have the sample input of ((())), it would push ( into one stack and it would push ) into another stack. Then it would enter a loop that pops all the characters and if both stacks are empty, it would be balanced. But Im getting this out when I run it.</p> <pre><code>Trying to pop when stack is empty Trying to pop when stack is empty Trying to pop when stack is empty Trying to pop when stack is empty Trying to pop when stack is empty Trying to pop when stack is empty true </code></pre> <p>Which I am assuming is that it isn't pushing the characters correctly, I do not know why. Here is a the method</p> <pre><code> static boolean isBalanced(String expr){ // base case: length of the expression must be even if (expr == null || expr.length() % 2 == 1) { return false; } Stack stack1 = new Stack(); Stack stack2 = new Stack(); // traverse the input expression for (int i = 0; i&lt; expr.length(); i++){ // if the current character in the expression is an opening brace, // push it into the stack if (expr.charAt(i) == '(') { stack1.push(expr.charAt(i)); } // if the current character is closing brace if (expr.charAt(i) == ')') { stack2.push(expr.charAt(i)); } } for(int i = 0; i&lt; expr.length(); i++) { stack1.pop(); stack2.pop(); } return (stack1.isEmpty() &amp;&amp; stack2.isEmpty()) ; } </code></pre> <p>Here is the stack class</p> <pre><code>public class Stack{ private Node top; public Stack() { top = null; } public boolean isEmpty(){ return (top ==null); } public void push(Object newItem){ top = new Node(newItem, top); } public Object pop(){ if (isEmpty()){ System.out.println( &quot;Trying to pop when stack is empty&quot;); return null; }else{ Node temp = top; top = top.next; return temp.info; } } void popAll(){ top = null; } public Object peek(){ if (isEmpty()){ System.out.println( &quot;Trying to peek when stack is empty&quot;); return null; }else{ return top.info; } } }// End of Stack using a linked list </code></pre> <p>Here is the node class</p> <pre><code>public class Node { Object info; Node next; Node(Object info, Node next){ this.info=info; this.next=next; } } </code></pre> <p>I am not allowed to import anything and I am only allowed to changed the method, thank you</p>
[ { "answer_id": 74496632, "author": "QWERTYL", "author_id": 11777402, "author_profile": "https://Stackoverflow.com/users/11777402", "pm_score": 0, "selected": false, "text": "test_list_2 =\n{'Tools': 'Pen',\n'Tree': 'Willow',\n'Food': 'Drumstick',\n'Fruit': 'Apple'\n}\n\nprint(test_list_2[\"Tools\"])\n" }, { "answer_id": 74496633, "author": "Iddo Sadeh", "author_id": 3620846, "author_profile": "https://Stackoverflow.com/users/3620846", "pm_score": 2, "selected": false, "text": "test_dict = {i.split(\": \")[0]: i.split(\": \")[1] for i in test_list}\n test_dict['Food']\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74496650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20200634/" ]
74,496,667
<p>Why does this code print <code>Array(7) [ &lt;7 empty slots&gt; ]</code> (or an array of <code>undefined</code>, 7 times) instead of an array with the single element <code>7</code>?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const a = [ 7 ]; console.log(new Array(...a));</code></pre> </div> </div> </p>
[ { "answer_id": 74496693, "author": "rrrm93", "author_id": 2500733, "author_profile": "https://Stackoverflow.com/users/2500733", "pm_score": 1, "selected": false, "text": "console.log([...a])\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74496667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20544074/" ]
74,496,668
<p>I'm trying to find out which words fit into this template but don't know how to compare them. Is there any way to do this without counting specific alphabetic characters in the template, getting their indices, and then checking each letter in each word?</p> <p>The desired output is a list of words from words that fit the template.</p> <pre><code>alist = [] template = ['_', '_', 'l', '_', '_'] words = ['hello', 'jacky', 'helps'] if (word fits template): alist.append(word) </code></pre>
[ { "answer_id": 74496715, "author": "Swifty", "author_id": 20267366, "author_profile": "https://Stackoverflow.com/users/20267366", "pm_score": 1, "selected": false, "text": "import re\ntemplate = ['_', '_', 'l', '_', '_']\nwords = ['hello', 'jacky', 'helps']\nregexp = ''.join(template).replace('_','.')\n# '..l..' in this case\nmatch_words = [word for word in words if re.match(regexp,word)]\n\nmatch_words\n# Out[108]: ['hello', 'helps']\n" }, { "answer_id": 74496717, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 3, "selected": true, "text": "zip def word_fits(word, template):\n if len(word) != len(template):\n return False\n\n for w, t in zip(word, template):\n if t != \"_\" and w != t:\n return False\n\n return True\n\n\ntemplate = [\"_\", \"_\", \"l\", \"_\", \"_\"]\nwords = [\"hello\", \"jacky\", \"helps\"]\n\nalist = [w for w in words if word_fits(w, template)]\n\nprint(alist)\n [\"hello\", \"helps\"]\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74496668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20251257/" ]
74,496,670
<p>The question I'm going to ask is about Pinia, but really could just be generalized to any underlying store.</p> <p>I have a Vue + Pinia application in which I want to be able to store a tree. The tree is made up of objects of type <code>Node</code>. I need to store exactly one tree at a time, and I don't care about the root (we can imagine it's there, but what I care about is the root's children, their children, and so on).</p> <p>I want to support the following operations:</p> <ul> <li>create a new top-level node</li> <li>create a node that's child of another node</li> <li>modify or delete a node, regardless of whether it's top-level or child or child of a child</li> <li>I want to be able to move around a node or an entire subtree, changing its parent or even just its position relative to its siblings</li> <li>the whole tree won't be fetched from the backend at once; it'll be fetched lazily. You can imagine when a node is opened in the UI, its direct children are fetched and so on.</li> </ul> <p>Here's something I have thought of doing:</p> <ul> <li>keep in my store an array of <code>Node</code>s containing the top level nodes. Let's call it <code>topLevelNodes</code></li> <li>keep an object <code>nodeIdToChildren</code>, which maps the id of a node to an array of <code>Node</code>s that are its children</li> </ul> <p>I would initially fetch the top level nodes, filling the array <code>topLevelNodes</code>.</p> <p>For each node that needs to know its children, fetch them and put them in <code>nodeIdToChildren</code> under the parent id as key.</p> <p>An advantage of this approach is that it's easy to add, delete, and move around nodes: just touch the relevant entries in the mapping. The biggest drawback is that it's much less efficient to just find a node, regardless of its position. Say I want to edit node with id <code>xyz</code>, not knowing whose child it is.</p> <p>I could create a getter that flattens all the values in the mapping object together with the values in the top level nodes array, but I'm not sure about efficiency of that.</p> <p>Are there any better ways of doing this?</p>
[ { "answer_id": 74542810, "author": "Duannx", "author_id": 4254681, "author_profile": "https://Stackoverflow.com/users/4254681", "pm_score": 1, "selected": false, "text": "const tree = new Map()\n node nodeId {\n id: \"the node id\",\n parentId: \"id of the parent, null if it is the root node\",\n childIds: \"array of the id of its child\",\n content: \"content of the node, whatever you want\"\n}\n // difficulty: easy\nconst rootNode = {\n id: \"nodeId\"\n parentId: null,\n childIds: [...],\n content: \"...\"\n}\n\ntree.set(nodeId, rootNode)\n // difficulty: easy\n// add the child first\nconst childNode = {\n id: \"nodeId\"\n parentId: \"parentId\",\n childIds: [...],\n content: \"...\"\n}\ntree.set(nodeId, childNode)\n\n// add the child id to the parent node\nconst parentNode = tree.get(parentId)\nparentNode.childIds.push(childNode.id)\n\n// set the parent back to your tree\ntree.set(parentNode.id, parentNode)\n // modify a node. \n// difficulty: easy\nconst node = tree.get(nodeId)\n// ... make the modification\n// set it back to the tree\ntree.set(nodeId, node)\n\n// delete a node. \n// difficulty: medium\n// retrieve the node first\nconst node = tree.get(nodeId)\n\n// delete it\ntree.delete(nodeId)\n\n// delete all of its children\n// you need a recursive delete function here to go through all of the node child and child of child and so on\ntree.childIds.forEach(recursiveDelete)\n// don't forget to delete the nodeId from its parent node. It's easy\n...\n // moving around the tree is quite easy, you just need to follow the `parentId` and `childIds`\n\n// changing a node's parent (same level)\n// difficulty: easy\n// you just need to change the parentId of the node. And modify the childIds of its old and new parent\n\n// changing a node level, moving its children accordingly\n// difficulty: easy\n// same as changing a node parent above. Its children will move accordingly\n\n// changing a node level to be a child of one of its children\n// difficulty: hard\n\n// get the node\nconst node = tree.get(nodeId)\n\n// go through its children and update the parentId of each to the node.parentId (moving its children to be the direct child of its parent)\nnode.childIds.forEach((childId)=> updateParentId(childId, node.parentId))\n\n// set the node parentId to the new one\nnode.parentId = newParentId\n\n// set new childIds for the node if you want\nnode.childIds = [...]\n\n// don't forget to set it back on the tree\ntree.set(node.id, node)\n // There is no problem at all. You just need to load from the root\n" }, { "answer_id": 74551374, "author": "tao", "author_id": 1891677, "author_profile": "https://Stackoverflow.com/users/1891677", "pm_score": 2, "selected": false, "text": "parents getItemDetails children children parents parents children parents children <TreeView /> <TableView />" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74496670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12424975/" ]
74,496,686
<p>would i write a logical AND statement the same way i would write a logical OR statement converting C to mips assembly?</p> <pre><code>else if (i == x &amp;&amp; j == y) printf(&quot;%c&quot;, 219); </code></pre> <p>this is what i put</p> <pre><code>bne $reg1, $t3, draw219 # i==x bne $reg2, $t4, draw219 # j==y </code></pre>
[ { "answer_id": 74496727, "author": "David Grayson", "author_id": 28128, "author_profile": "https://Stackoverflow.com/users/28128", "pm_score": 0, "selected": false, "text": "printf(\"%c\", 219); bne if" }, { "answer_id": 74496777, "author": "Erik Eidt", "author_id": 471129, "author_profile": "https://Stackoverflow.com/users/471129", "pm_score": 1, "selected": false, "text": "...\nif ( i == x && j == y ) {\n <then-part>\n}\nelse {\n <else-part>\n}\n...\n ...\n if ( ! (i == x && j == y) ) goto else1Part;\n then1Part:\n <then-part>\n goto endIf1;\n else1Part:\n <else-part>\n endIf1:\n ...\n && || if ( ! (i == x) || ! (j == y) ) goto else1Part;\n if ( i != x || j != y ) goto else1Part;\n if ( i != x ) goto else1Part;\n if ( j != y ) goto else1Part;\n // will come here when the original if condition is true\n && & and || | if ( i < N && a[i] == 0 ) ...\n && &" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74496686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20393581/" ]
74,496,708
<p>I am really struggling to understand what is going on with this code, what does the single line lambda return if anything ? I am unclear on what that 3rd argument is going to be ?</p> <pre><code> public Task&lt;StatusMessage&gt; MarketSubscription(MarketSubscriptionMessage message) { int id = NextId(); message.Id = id; message.Op = REQUEST_MARKET_SUBSCRIPTION; var newSub = new SubscriptionHandler&lt;MarketSubscriptionMessage, ChangeMessage&lt;MarketChange&gt;, MarketChange&gt;(id, message, false); return SendMessage(new RequestResponse(id, message, success =&gt; MarketSubscriptionHandler = newSub)); } </code></pre> <p>For info the other method is</p> <pre><code>public RequestResponse(int id, RequestMessage request, Action&lt;RequestResponse&gt; onSuccess) { Id = id; Request = request; OnSuccess = onSuccess; } </code></pre> <p>I would be most grateful if anyone could explain how to intrepret that last complex line. Thanks.</p>
[ { "answer_id": 74496761, "author": "digital_jedi", "author_id": 3019376, "author_profile": "https://Stackoverflow.com/users/3019376", "pm_score": 0, "selected": false, "text": "SendMessage() onSuccess SendMessage() RequestResponse newSub MarketSubscriptionHandler SendMessage() SendMessage() onSuccess onSuccess newSub MarketSubscriptionHandler" }, { "answer_id": 74496762, "author": "pm100", "author_id": 173397, "author_profile": "https://Stackoverflow.com/users/173397", "pm_score": 1, "selected": false, "text": "public RequestResponse(int id, RequestMessage request, Act ion<RequestResponse> onSuccess)\n{\n Id = id;\n Request = request;\n OnSuccess = onSuccess;\n}\n new RequestResponse(id, message, \n success => MarketSubscriptionHandler = newSub)\n MarketSubscriptionHandler newSub var newSub = new SubscriptionHandler<MarketSubscriptionMessage, ChangeMessage<MarketChange>, MarketChange>(id, message, false);\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74496708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4740124/" ]
74,496,713
<p>Given a <code>std::ranges::range</code> in C++20, how can I determine the type of the values in that range?</p> <p>I want to write a function that makes a <code>std::vector</code> out of an arbitrary range. I'd like this function to have a nice, explicit declaration. Something like:</p> <pre><code>template&lt;std::ranges::range Range&gt; std::vector&lt;std::value_type_t&lt;Range&gt;&gt; make_vector(Range const&amp;); </code></pre> <p>The following seems to work, but the declaration is not explicit and the implementation is ugly (even ignoring that it doesn't allocate the right size up-front where possible).</p> <pre><code> template&lt;std::ranges::range Range&gt; auto make_vector(Range const&amp; range) { using IteratorType = decltype(std::ranges::begin(std::declval&lt;Range&amp;&gt;())); using DerefType = decltype(*std::declval&lt;IteratorType&gt;()); using T = std::remove_cvref_t&lt;DerefType&gt;; std::vector&lt;T&gt; retval; for (auto const&amp; x: range) { retval.push_back(x); } return retval; } </code></pre> <p>Is there a canonical/better/shorter/nicer way to do this?</p>
[ { "answer_id": 74496753, "author": "user17732522", "author_id": 17732522, "author_profile": "https://Stackoverflow.com/users/17732522", "pm_score": 2, "selected": false, "text": "std::ranges::range_value_t std::value_type_t std::ranges::to" }, { "answer_id": 74520929, "author": "Barry", "author_id": 2069064, "author_profile": "https://Stackoverflow.com/users/2069064", "pm_score": 2, "selected": true, "text": "template<std::ranges::range Range>\nauto make_vector(Range const& range)\n Range range Range const Range R range R const template<typename Range>\n requires std::ranges::range<Range const>\nauto make_vector(Range const& range)\n Range const template<std::ranges::range Range>\nauto make_vector(Range&& range)\n using IteratorType = decltype(std::ranges::begin(std::declval<Range&>()));\nusing DerefType = decltype(*std::declval<IteratorType>());\nusing T = std::remove_cvref_t<DerefType>;\n using IteratorType = std::ranges::iterator_t<Range>;\nusing DerefType = std::iter_reference_t<IteratorType>;\n using DerefType = std::ranges::range_reference_t<Range>;\n using T = std::ranges::range_value_t<Range>;\n std::vector<T> retval;\nfor (auto const& x: range) {\n retval.push_back(x);\n}\nreturn retval;\n push_back auto&& x FWD(x) auto const& x x if constexpr (std::ranges::sized_range<Range>) {\n retval.reserve(std::ranges::size(range));\n}\n make_vector(r) std::ranges::to<std::vector>(r) vector push_back" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74496713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1171688/" ]
74,496,724
<p>This CSS is displayed on the second page of a scrolling page. The .container_block is for holding all the cards in its box. The .cards are for displaying the cards and each individual card is represented by card1,2,3, and 4.</p> <pre><code>.container_block { width: 80%; height: 40%; display: block; background-color: red; margin: auto; } .cards { display: flex; align-items: center; justify-content: center; } .cards h2 { font-size: 25px; color: white; margin: 15px; } .cards p { font-size: 20px; color: white; margin: 15px; } .card1 { box-shadow: 1px 1px 8px 6px rgba(0,0,0,0.2); transition: 0.3s; height: 30vh; width: 30vh; border-radius: 20px; margin-top: 4vh; margin-right: 5vh; } .card2 { box-shadow: 1px 1px 8px 6px rgba(0,0,0,0.2); transition: 0.3s; height: 30vh; width: 30vh; border-radius: 20px; margin-top: 4vh; margin-right: 5vh; } .card3 { box-shadow: 1px 1px 8px 6px rgba(0,0,0,0.2); transition: 0.3s; height: 30vh; width: 30vh; border-radius: 20px; margin-top: 4vh; margin-right: 5vh; } .card4 { box-shadow: 1px 1px 8px 6px rgba(0,0,0,0.2); transition: 0.3s; height: 30vh; width: 30vh; border-radius: 20px; margin-top: 4vh; margin-right: 5vh; } </code></pre> <p>Any tips on simplifying code will also be greatly appreciated!</p>
[ { "answer_id": 74496753, "author": "user17732522", "author_id": 17732522, "author_profile": "https://Stackoverflow.com/users/17732522", "pm_score": 2, "selected": false, "text": "std::ranges::range_value_t std::value_type_t std::ranges::to" }, { "answer_id": 74520929, "author": "Barry", "author_id": 2069064, "author_profile": "https://Stackoverflow.com/users/2069064", "pm_score": 2, "selected": true, "text": "template<std::ranges::range Range>\nauto make_vector(Range const& range)\n Range range Range const Range R range R const template<typename Range>\n requires std::ranges::range<Range const>\nauto make_vector(Range const& range)\n Range const template<std::ranges::range Range>\nauto make_vector(Range&& range)\n using IteratorType = decltype(std::ranges::begin(std::declval<Range&>()));\nusing DerefType = decltype(*std::declval<IteratorType>());\nusing T = std::remove_cvref_t<DerefType>;\n using IteratorType = std::ranges::iterator_t<Range>;\nusing DerefType = std::iter_reference_t<IteratorType>;\n using DerefType = std::ranges::range_reference_t<Range>;\n using T = std::ranges::range_value_t<Range>;\n std::vector<T> retval;\nfor (auto const& x: range) {\n retval.push_back(x);\n}\nreturn retval;\n push_back auto&& x FWD(x) auto const& x x if constexpr (std::ranges::sized_range<Range>) {\n retval.reserve(std::ranges::size(range));\n}\n make_vector(r) std::ranges::to<std::vector>(r) vector push_back" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74496724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19141059/" ]
74,496,734
<p>The following adds a country code to each new row inserted, in this case &quot;US&quot; for &quot;United States&quot;.</p> <pre><code>CREATE TRIGGER `country` BEFORE INSERT ON `test` FOR EACH ROW SET NEW.`countryCode` = CASE WHEN NEW.`country` LIKE 'United States' THEN 'US' END </code></pre> <p>The above works well, but I also want to insert a variable. The code below generates a #1064 syntax error:</p> <pre><code>SET @countryCode = 'US' CREATE TRIGGER `country` BEFORE INSERT ON `test` FOR EACH ROW SET NEW.`countryCode` = CASE WHEN NEW.`country` LIKE 'United States' THEN @countryCode END </code></pre> <p>Ultimately, I want to be able to use a variable so that multiple country codes can be concatenated and inserted in the same column.</p>
[ { "answer_id": 74496753, "author": "user17732522", "author_id": 17732522, "author_profile": "https://Stackoverflow.com/users/17732522", "pm_score": 2, "selected": false, "text": "std::ranges::range_value_t std::value_type_t std::ranges::to" }, { "answer_id": 74520929, "author": "Barry", "author_id": 2069064, "author_profile": "https://Stackoverflow.com/users/2069064", "pm_score": 2, "selected": true, "text": "template<std::ranges::range Range>\nauto make_vector(Range const& range)\n Range range Range const Range R range R const template<typename Range>\n requires std::ranges::range<Range const>\nauto make_vector(Range const& range)\n Range const template<std::ranges::range Range>\nauto make_vector(Range&& range)\n using IteratorType = decltype(std::ranges::begin(std::declval<Range&>()));\nusing DerefType = decltype(*std::declval<IteratorType>());\nusing T = std::remove_cvref_t<DerefType>;\n using IteratorType = std::ranges::iterator_t<Range>;\nusing DerefType = std::iter_reference_t<IteratorType>;\n using DerefType = std::ranges::range_reference_t<Range>;\n using T = std::ranges::range_value_t<Range>;\n std::vector<T> retval;\nfor (auto const& x: range) {\n retval.push_back(x);\n}\nreturn retval;\n push_back auto&& x FWD(x) auto const& x x if constexpr (std::ranges::sized_range<Range>) {\n retval.reserve(std::ranges::size(range));\n}\n make_vector(r) std::ranges::to<std::vector>(r) vector push_back" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74496734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4688190/" ]
74,496,770
<p>I am having difficulty using the javascript filter in a react native project. I need help filtering an array of objects in a typescript react native project The main issue I am having is in the function called onSearchTextChanged specifically the search method which uses a javascript filter</p> <p>Here's the main code for the screen below</p> <pre><code> const renderItem = ({ item }) =&gt; ( &lt;Pressable style={cardUtilities} android_ripple={{ color: &quot;#dddddd&quot; }} onPress={() =&gt; onTapItemHandler(item)}&gt; &lt;View style={main}&gt; &lt;Text style={utilityname}&gt;{item.title}&lt;/Text&gt; &lt;Text style={utilityDesc}&gt;{item.description}&lt;/Text&gt; &lt;/View&gt; &lt;/Pressable&gt; ) const onSearchTextChanged = (e) =&gt; { setSearchQuery(e) search() } const search = () =&gt; { console.log(&quot;inside handleSearchButtonPressed&quot;) if (!itemListStore) { return } // const text = searchQuery.toLowerCase() console.log(&quot;inside 100&quot;) console.log(itemListStore) // array of output objects const filteredObjs = itemListStore.filter( // eslint-disable-next-line array-callback-return ({ item }) =&gt; { (JSON.stringify(item?.description[0]))?.toLowerCase().includes(searchQuery.toLowerCase()) || (JSON.stringify(item?.title[0]))?.toLowerCase().includes(searchQuery.toLowerCase()) || ( JSON.stringify(item?.link[0]))?.toLowerCase().includes(searchQuery.toLowerCase()) }) console.log(&quot;filteredObjs&quot;, JSON.stringify(filteredObjs)) console.log(typeof filteredObjs) console.log(filteredObjs.length) console.log(&quot;inside 400&quot;) console.log(&quot;searchQuery &quot;, searchQuery) if (!searchQuery || searchQuery === &quot;&quot;) { console.log(&quot;1&quot;) } else if (!Array.isArray(filteredObjs) &amp;&amp; !filteredObjs.length) { console.log(&quot;2&quot;) // set no data flag to true so as to render flatlist conditionally setNoData(true) } else if (Array.isArray(filteredObjs)) { console.log(&quot;3&quot;) setNoData(false) setItemListStore(filteredObjs) } } return ( &lt;SafeAreaView style={container}&gt; {/* &lt;Loader loading={loading} /&gt; */} &lt;View style={fullContainer}&gt; &lt;View style={MAIN_IMG}&gt; &lt;Image style={$welcomeLogo} source={Images.appLogo} resizeMode=&quot;contain&quot; /&gt; &lt;/View&gt; &lt;View style={TOP_143}&gt; &lt;TextInput style={textInputStyle} onChangeText={onSearchTextChanged} underlineColorAndroid=&quot;transparent&quot; placeholder=&quot;Search Here&quot; value={searchQuery} /&gt; &lt;/View&gt; &lt;FlatList data={itemListStore} renderItem={renderItem} keyExtractor={() =&gt; { return uuid.v4() + &quot;&quot; }} /&gt; &lt;/View&gt; &lt;/SafeAreaView&gt; ) </code></pre> <p>Here is sample data made up of an array of objects to be filtered</p> <pre><code>[ { &quot;description&quot;:[ &quot;At company; Professionals, we believe that individuals and organisations need to apply a whole new level of thinking to navigate and thrive in the emerging world. We no longer have the luxury of conducting business as usual. The organisation or individual that will survive in today&amp;rsquo;s world is one who can imagine and create their future. ​ For anyone who feels uneasy and boxed up in their careers, or entrepreneurs and organisations who want to stay ahead of the new era, or youths who want to be equipped for the future - we can help you achieve this.&quot; ], &quot;guid&quot;:[ [ &quot;Object&quot; ] ], &quot;industry&quot;:[ &quot;Consulting&quot; ], &quot;link&quot;:[ &quot;https://www.myjobmag.com/jobs/business-development-executive-at-protege-management-2&quot; ], &quot;pubDate&quot;:[ &quot;Fri, 18 Nov 2022 17:31:56 GMT&quot; ], &quot;title&quot;:[ &quot;Business Development Executive at Protege Management&quot; ] }, { &quot;description&quot;:[ &quot;Montaigne Place Is the leading luxury cosmetics, wellbeing and fragrance company in country. We are the hallmark of sophistication, luxury makeup, skincare innovation and sublime fragrances.&quot; ], &quot;guid&quot;:[ [ &quot;Object&quot; ] ], &quot;industry&quot;:[ &quot;Sales / Retail&quot; ], &quot;link&quot;:[ &quot;https://www.myjobmag.com/jobs/business-development-manager-female-at-montaigne-ah-limited&quot; ], &quot;pubDate&quot;:[ &quot;Fri, 18 Nov 2022 17:28:02 GMT&quot; ], &quot;title&quot;:[ &quot;Job Openings at Montaigne AH Limited&quot; ] }] </code></pre> <p>Here are the logs output below using a searchQuery value of business</p> <pre><code> LOG filteredObjs [] LOG object LOG 0 LOG inside 400 LOG searchQuery Business LOG 3 </code></pre>
[ { "answer_id": 74496775, "author": "subparry", "author_id": 10533611, "author_profile": "https://Stackoverflow.com/users/10533611", "pm_score": 0, "selected": false, "text": " const filteredObjs = itemListStore.filter(\n // eslint-disable-next-line array-callback-return\n ({ item }) => {\n return (JSON.stringify(item?.description[0]))?.toLowerCase().includes(searchQuery.toLowerCase()) ||\n (JSON.stringify(item?.title[0]))?.toLowerCase().includes(searchQuery.toLowerCase()) ||\n ( JSON.stringify(item?.link[0]))?.toLowerCase().includes(searchQuery.toLowerCase())\n })\n" }, { "answer_id": 74496813, "author": "Pompedup", "author_id": 12239272, "author_profile": "https://Stackoverflow.com/users/12239272", "pm_score": 1, "selected": false, "text": " const filteredObjs = itemListStore.filter(\n\n // here you destructure the row and take item but item doesn't exist in your object \n ({ item }) => {\n// here there is no return \n(JSON.stringify(item?.description[0]))?.toLowerCase().includes(searchQuery.toLowerCase()) ||\n (JSON.stringify(item?.title[0]))?.toLowerCase().includes(searchQuery.toLowerCase()) ||\n ( JSON.stringify(item?.link[0]))?.toLowerCase().includes(searchQuery.toLowerCase())\n })\n const filteredObjs = itemListStore.filter(\n (item) => {\n return (JSON.stringify(item?.description[0]))?.toLowerCase().includes(searchQuery.toLowerCase()) ||\n (JSON.stringify(item?.title[0]))?.toLowerCase().includes(searchQuery.toLowerCase()) ||\n (JSON.stringify(item?.link[0]))?.toLowerCase().includes(searchQuery.toLowerCase())\n })\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74496770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12072045/" ]
74,496,788
<p>I see this sort of address used in a bunch of examples. What does it mean exactly? Does it mean it will connect to any/all machines on the subnet that have something listening to that port? Or something else entirely? I see such usage in the docs and in books without explanation. Sort of annoying.</p>
[ { "answer_id": 74499078, "author": "rveerd", "author_id": 6783775, "author_profile": "https://Stackoverflow.com/users/6783775", "pm_score": 2, "selected": true, "text": "tcp tcp://interface:port\n * *" }, { "answer_id": 74499234, "author": "bazza", "author_id": 2147218, "author_profile": "https://Stackoverflow.com/users/2147218", "pm_score": 0, "selected": false, "text": "tcp://*:5555 zmq_bind() ipc:///tmp/feeds/0 /tmp/feeds/0" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74496788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/423560/" ]
74,496,799
<p>I have a TextView in my ConstraintLayout and I want the TextView to occupy only its parent width and height (0dp,0dp). I have seen that in small devices if in my ConstraintLayout I have an ImageView or a View with <code>android:layout_width=&quot;0dp&quot;</code> <code>android:layout_height=&quot;0dp&quot;</code> it will respect the constraints and don't be bigger than its parent. But in the case of the TextView it is not working the same as in small devices, although it has the same attributes than the ImageView, the text protrudes from its maximum space. To let you undestrand I am posting an image to let you see how the TextView is protruding out of its constraints:</p> <p>Image of the problem: <a href="https://i.stack.imgur.com/Mg5Ox.jpg" rel="nofollow noreferrer">the text should show Example text</a></p> <p>I am not using wrap content because I need the TextView to occupy exactly that squere of space. I think that the problem is that the TextView size doesn't auto-adjust automatically according to the screen size. What could I do so that the size is equal to a size that all the text is perfectly seen?</p> <p>Also I ahve seen that I could use <code>android:autoSizeTextType=&quot;uniform&quot;</code> but I can't as it is needed API level &gt;=26</p> <pre><code>&lt;TextView android:id=&quot;@+id/textView&quot; android:layout_width=&quot;0dp&quot; android:layout_height=&quot;0dp&quot; android:elevation=&quot;2dp&quot; android:text=&quot;@string/example_of_text&quot; android:textAppearance=&quot;@style/TextAppearance.AppCompat.Medium&quot; android:textColor=&quot;@color/txt_light&quot; android:textStyle=&quot;bold&quot; app:layout_constraintBottom_toTopOf=&quot;@+id/view1&quot; app:layout_constraintEnd_toStartOf=&quot;@id/view2&quot; app:layout_constraintStart_toEndOf=&quot;@id/view3&quot; app:layout_constraintTop_toBottomOf=&quot;@+id/view4&quot; /&gt; </code></pre> <p>I tried to use <code>android:layout_width=&quot;0dp&quot;</code> <code>android:layout_height=&quot;0dp&quot;</code> in the TextView as I said using a ConstraintLayout but the text it is overlapping with its constraints.</p> <p>Edit:</p> <p>Changed TextView to AppCompatTextView:</p> <pre><code> &lt;androidx.appcompat.widget.AppCompatTextView android:id=&quot;@+id/textView&quot; android:layout_width=&quot;0dp&quot; android:layout_height=&quot;0dp&quot; android:elevation=&quot;2dp&quot; android:text=&quot;@string/example_of_text&quot; android:textAppearance=&quot;@style/TextAppearance.AppCompat.Medium&quot; android:textColor=&quot;@color/txt_light&quot; android:textStyle=&quot;bold&quot; app:layout_constraintBottom_toTopOf=&quot;@+id/view1&quot; app:layout_constraintEnd_toStartOf=&quot;@id/view2&quot; app:layout_constraintStart_toEndOf=&quot;@id/view3&quot; app:layout_constraintTop_toBottomOf=&quot;@+id/view4&quot; app:autoSizeTextType=&quot;uniform&quot;&gt; &lt;/androidx.appcompat.widget.AppCompatTextView&gt; </code></pre>
[ { "answer_id": 74497256, "author": "ninh312", "author_id": 16772693, "author_profile": "https://Stackoverflow.com/users/16772693", "pm_score": 0, "selected": false, "text": "dp sp android:textSize=\"15dp\"\n" }, { "answer_id": 74501523, "author": "Cheticamp", "author_id": 6287910, "author_profile": "https://Stackoverflow.com/users/6287910", "pm_score": 1, "selected": true, "text": "android:autoSizeTextType=\"uniform\" app:autoSizeTextType=\"uniform\"" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74496799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20543919/" ]
74,496,804
<p>I am trying to print the rows whereby a data condition is met in a pandas DF based on the unique values in the DF. For example, I have data that looks like this:</p> <p>DF:</p> <pre><code>site temp month day A 15 7 18 A 11 6 12 A 22 9 3 B 9 4 23 B 3 2 11 B -1 5 18 </code></pre> <p>I need the result to print the rows where the max in the 'temp' column occurs such as this for the final result: A 15 B 9</p> <p>I have tried this but it is not working correctly:</p> <pre><code>for i in DF['site'].unique(): print(DF.temp.max()) </code></pre> <p>I get the same answer of:</p> <pre><code>22 22 </code></pre> <p>but the answer should be:</p> <pre><code>site temp month day A 22 9 3 B 9 4 23 </code></pre> <p>thank you!</p>
[ { "answer_id": 74497256, "author": "ninh312", "author_id": 16772693, "author_profile": "https://Stackoverflow.com/users/16772693", "pm_score": 0, "selected": false, "text": "dp sp android:textSize=\"15dp\"\n" }, { "answer_id": 74501523, "author": "Cheticamp", "author_id": 6287910, "author_profile": "https://Stackoverflow.com/users/6287910", "pm_score": 1, "selected": true, "text": "android:autoSizeTextType=\"uniform\" app:autoSizeTextType=\"uniform\"" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74496804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2100039/" ]
74,496,821
<p>I am trying to show a pop-up menu appear when an IconButton() is clicked I added a PopupMenuButton() to the on pressed method of the IconButton as you can see below:</p> <p><a href="https://i.stack.imgur.com/fQzx7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fQzx7.png" alt="Image of code:Pop up menu in the on pressed method" /></a></p> <p>but it does not show any pop-up menu when clicked. If there's anything I'm doing wrong I hope some one can point it out for me. Here is the code:</p> <pre><code>import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; String _selectedMenu = ''; enum Menu { itemOne, itemTwo, itemThree, itemFour } class ListTileWithIcon extends StatefulWidget { const ListTileWithIcon({super.key}); @override State&lt;ListTileWithIcon&gt; createState() =&gt; _ListTileWithIconState(); } class _ListTileWithIconState extends State&lt;ListTileWithIcon&gt; { @override Widget build(BuildContext context) { return ListTile( leading: const Icon(Icons.person), title: const Text(&quot;The ListTile&quot;), trailing: IconButton( // key: _icnBtnKey, splashRadius: 20, icon: const Icon( Icons.more_vert_rounded, size: 20.0, color: Color.fromARGB(255, 135, 0, 212), ), onPressed: () { // showPopUpMenuAtTap(); if (kDebugMode) { print(&quot;Inside icon button's clickt&quot;); } PopupMenuButton&lt;Menu&gt;( // Callback that sets the selected popup menu item. onSelected: (Menu item) { setState(() { _selectedMenu = item.name; }); }, itemBuilder: (BuildContext context) =&gt; &lt;PopupMenuEntry&lt;Menu&gt;&gt;[ const PopupMenuItem&lt;Menu&gt;( value: Menu.itemOne, child: Text('Item 1'), ), const PopupMenuItem&lt;Menu&gt;( value: Menu.itemTwo, child: Text('Item 2'), ), const PopupMenuItem&lt;Menu&gt;( value: Menu.itemThree, child: Text('Item 3'), ), const PopupMenuItem&lt;Menu&gt;( value: Menu.itemFour, child: Text('Item 4'), ), ], ); }, ), onTap: () {}, ); } } </code></pre> <p>Thanks in advance.</p>
[ { "answer_id": 74497017, "author": "Lara Cesio", "author_id": 16787956, "author_profile": "https://Stackoverflow.com/users/16787956", "pm_score": 1, "selected": false, "text": "PopupMenuButton<Menu>(\n icon: const Icon(\n Icons.settings,\n size: 50,\n color: Colors.red,\n ), //use this icon\n onSelected: (Menu item) {\n setState(() {\n _selectedMenu = item.name;\n });\n },\n itemBuilder: (BuildContext context) => <PopupMenuEntry<Menu>>[\n const PopupMenuItem<Menu>(\n value: Menu.itemOne,\n child: Text('Item 1'),\n ),\n const PopupMenuItem<Menu>(\n value: Menu.itemTwo,\n child: Text('Item 2'),\n ),\n const PopupMenuItem<Menu>(\n value: Menu.itemThree,\n child: Text('Item 3'),\n ),\n const PopupMenuItem<Menu>(\n value: Menu.itemFour,\n child: Text('Item 4'),\n ),\n ],\n )\n" }, { "answer_id": 74497909, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 0, "selected": false, "text": "showMenu onTap: () {\n // popUpKey.currentState?.showButtonMenu();\n showMenu(\n context: context,\n position: RelativeRect.fromLTRB(100, 100, 100, 00),\n items: [\n final GlobalKey<PopupMenuButtonState> popUpKey = GlobalKey();\n PopupMenuButton<Menu>(\n key: popUpKey,\n onTap: () {\n popUpKey.currentState?.showButtonMenu();\n},\n class ListTileWithIcon extends StatefulWidget {\n const ListTileWithIcon({super.key});\n\n @override\n State<ListTileWithIcon> createState() => _ListTileWithIconState();\n}\n\nenum Menu { itemOne, itemTwo, itemThree, itemFour }\n\nclass _ListTileWithIconState extends State<ListTileWithIcon> {\n String _selectedMenu = '';\n\n final GlobalKey<PopupMenuButtonState> popUpKey = GlobalKey();\n\n @override\n Widget build(BuildContext context) {\n return Column(\n children: [\n InkWell(\n child: Text(\"Click to open PopUp\"),\n onTap: () {\n popUpKey.currentState?.showButtonMenu();\n },\n ),\n SizedBox(\n height: 200,\n ),\n PopupMenuButton<Menu>(\n key: popUpKey,\n onSelected: (Menu item) {\n setState(() {\n _selectedMenu = item.name;\n });\n },\n itemBuilder: (BuildContext context) => <PopupMenuEntry<Menu>>[\n const PopupMenuItem<Menu>(\n value: Menu.itemOne,\n child: Text('Item 1'),\n ),\n const PopupMenuItem<Menu>(\n value: Menu.itemTwo,\n child: Text('Item 2'),\n ),\n const PopupMenuItem<Menu>(\n value: Menu.itemThree,\n child: Text('Item 3'),\n ),\n const PopupMenuItem<Menu>(\n value: Menu.itemFour,\n child: Text('Item 4'),\n ),\n ],\n )\n ],\n );\n }\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74496821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14885706/" ]
74,496,836
<p>I prepared some code snippet from Delphi recommendations, no compiler warnings or implicit casts but the result unsatisfied me.</p> <pre><code>procedure Convert; type TUTF8Buf = array [0 .. 5] of byte; var s: string; sutf8: UTF8String; // manageable UTF-8 string utf8str: TUTF8Buf; // unmanageable buffer begin utf8str := Default (TUTF8Buf); // utf8str = (0,0,0,0,0,0) s := UTF8ArrayToString(utf8str); // s = #0#0#0#0#0#0 s := 'abc'; // s = 'abc' sutf8 := UTF8Encode(s); // sutf8 = 'abc' Move(sutf8[1], utf8str[0], Min(Length(sutf8), sizeof(utf8str) - 1)); // utf8str = (97, 98, 99, 0, 0) s := UTF8ArrayToString(utf8str); // s = 'abc'#0#0#0 s := UTF8ToString(sutf8); // s = 'abc' end; </code></pre> <p>The code works perfectly fine when it is used with the manageable UTF-8 string but always produces trailing zeroes with the unmanageable buffer. What is the proper modern way of handling such buffers?</p>
[ { "answer_id": 74497557, "author": "Remy Lebeau", "author_id": 65863, "author_profile": "https://Stackoverflow.com/users/65863", "pm_score": 2, "selected": false, "text": "UTF8ArrayToString() $0 Utf8ToUnicode() UnicodeFromLocaleChars() TEncoding.UTF8.GetChars() UTF8String UnicodeString UTF8String UTF8Encode() UTF8Decode()" }, { "answer_id": 74500313, "author": "W. Chang", "author_id": 10101441, "author_profile": "https://Stackoverflow.com/users/10101441", "pm_score": 0, "selected": false, "text": "UTF8String #$00 #$7F AnsiString #00 StrLen AnsiString function ToUTF8String(const Buf): UTF8String;\nvar \n len: Integer;\nbegin\n len := StrLen(PAnsiChar(@Buf));\n SetLength(Result, len);\n if len > 0 then Move(Buf, Result[1]);\nend;\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74496836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1886550/" ]
74,496,843
<p>I'm trying to read data from a JSON file that contains a list of blogs. I want to break each of those blogs into small paragraphs. I thought adding <code>\n</code> would do the job but it's not. How can I achieve this?</p> <p><a href="https://i.stack.imgur.com/YLZDG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YLZDG.png" alt="BookImage" /></a></p> <p>This is my <code>blogs.json</code> file:</p> <pre class="lang-js prettyprint-override"><code>[ { &quot;id&quot;: 1, &quot;name&quot;: &quot;The 48 Laws Of Power&quot;, &quot;blog&quot;: &quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. \n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. \n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum&quot;, &quot;img&quot;: &quot;https://i.ibb.co/RpP2LGp/48-Laws-Of-Power.jpg&quot; }, { &quot;id&quot;: 2, &quot;name&quot;: &quot;Rich Dad Poor Dad&quot;, &quot;blog&quot;: &quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. \n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. \n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum&quot;, &quot;img&quot;: &quot;https://i.ibb.co/8Brh2Nc/rich-Dad-Poor-Dad.jpg&quot; }, { &quot;id&quot;: 3, &quot;name&quot;: &quot;Show Your Work&quot;, &quot;blog&quot;: &quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. \n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. \n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum&quot;, &quot;img&quot;: &quot;https://i.ibb.co/VjLBT1T/show-Your-Work.jpg&quot; }, { &quot;id&quot;: 4, &quot;name&quot;: &quot;Atomic Habits&quot;, &quot;blog&quot;: &quot;Atomic Habits by James Clear is an incredible book on habits and the massive effect that they have on our lives. Published in 2018 and now an international bestseller, Atomic Habits centers around this idea that “habits are the compound interest self-improvement.” If you want to improve yourself in any way, look first to your daily habits. \n Clear relates habits to compound interest; an interesting model he suggests that really helped me visualize the effect that these tiny behaviors had on our lives is set up like this. \n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. \n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. \n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum&quot;, &quot;img&quot;: &quot;https://i.ibb.co/ss0kLQw/atomic-Habits.jpg&quot; }, { &quot;id&quot;: 5, &quot;name&quot;: &quot;The Almanack Of Naval Ravikant&quot;, &quot;blog&quot;: &quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. \n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. \n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum&quot;, &quot;img&quot;: &quot;https://i.ibb.co/87SmcFz/alamanack-naval.jpg&quot; }, { &quot;id&quot;: 6, &quot;name&quot;: &quot;The 4-Hour Work Week&quot;, &quot;blog&quot;: &quot;The first chapter, D is for Definition, followed its name and defined the clear cut differences in mindset between the new rich and the deferrers. This clued me in to the goal of this book, to escape what has been perpetuated our entire lives. However, I was still skeptical. It presented several, grandiose claims; how could any of it be truly doable? Sure, someone like Tim Ferriss, Princeton graduate and energy-supplement extraordinaire could pull it off, but that doesn't mean that me, the average Joe, could somehow make an automated stream of revenue so that I can live all around the world and have no worries.The next chapter, E is for Elimination, had the most profound effect on me. It presented ideas such as Parkinson's Law (work expands to fill the time allotted to it) and the Pareto Principle (80/20), ideas I had heard from videos before, but never explained as well as in this chapter. After reading, I immediately evaluated my time wasters and consumers and began to slowly deconstruct my day and how to best optimize it. This chapter was one that I could apply the day after reading it successfully, so it was very useful. \n The next chapter, E is for Elimination, had the most profound effect on me. It presented ideas such as Parkinson's Law (work expands to fill the time allotted to it) and the Pareto Principle (80/20), ideas I had heard from videos before, but never explained as well as in this chapter. After reading, I immediately evaluated my time wasters and consumers and began to slowly deconstruct my day and how to best optimize it. This chapter was one that I could apply the day after reading it successfully, so it was very useful. \n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum&quot;, &quot;img&quot;: &quot;https://i.ibb.co/Pxtt4dH/4-hour-work-week.jpg&quot; } ] </code></pre> <p>And here's how I'm reading from it <code>BookDetails.js</code> :</p> <pre class="lang-js prettyprint-override"><code>import React, { useEffect, useState } from &quot;react&quot;; import { useParams } from &quot;react-router-dom&quot;; const BookDetails = () =&gt; { const { id } = useParams(); const [blog, setBlog] = useState({}); useEffect(() =&gt; { const url = `/blogs.json`; console.log(url); fetch(url) .then((res) =&gt; res.json()) .then((data) =&gt; { const currentBlogArray = data.filter((book) =&gt; book.id == id); setBlog(currentBlogArray.length &gt; 0 ? currentBlogArray[0] : {}); }); }, []); return ( &lt;div className=&quot;px-6&quot;&gt; &lt;h2&gt;This is book details: {id} &lt;/h2&gt; &lt;h2 className=&quot;flex justify-center font-bold text-2xl mb-6&quot;&gt; {&quot; &quot;} {blog.name} &lt;/h2&gt; &lt;h2&gt; {blog.blog}&lt;/h2&gt; &lt;/div&gt; ); }; export default BookDetails; </code></pre>
[ { "answer_id": 74496926, "author": "Evans Wanjau", "author_id": 4812835, "author_profile": "https://Stackoverflow.com/users/4812835", "pm_score": 0, "selected": false, "text": "\\\\n\\\\ \\n \\n\\n" }, { "answer_id": 74496998, "author": "Elvin", "author_id": 11743253, "author_profile": "https://Stackoverflow.com/users/11743253", "pm_score": 2, "selected": true, "text": "<p> <p> const json = \"Paragraph 1<p>Paragraph 2\";\nconst p = document.querySelector('#paragraph');\n\np.innerHTML = json.split('<p>').map(paragraph=>{\n return '<p>' + paragraph + '</p>';\n }).join('') <html>\n<body>\n<div id=\"paragraph\"> </div>\n</body>\n</html> import React, { useEffect, useState } from \"react\";\nimport { useParams } from \"react-router-dom\";\n\nconst BookDetails = () => {\n const { id } = useParams();\n const [blog, setBlog] = useState({});\n useEffect(() => {\n const url = `blogs.json`;\n fetch(url)\n .then((res) => res.json())\n .then((data) => {\n const currentBlogArray = data.filter((book) => book.id == id);\n const currentBlog =\n currentBlogArray.length > 0 ? currentBlogArray[0] : {};\n setBlog({\n ...currentBlog,\n blog: currentBlog.blog.split(\"\\n\"),\n });\n });\n }, []);\n\n return (\n <div className=\"px-6\">\n <h2>This is book details: {id} </h2>\n <h2 className=\"flex justify-center font-bold text-2xl mb-6\">\n {blog.name}\n </h2>\n <h2>\n {blog.blog?.map((paragraph) => {\n return (\n <p>\n <span style={{ marginLeft: 25 }}></span>\n {paragraph}\n </p>\n );\n })}\n </h2>\n </div>\n );\n};\n\nexport default BookDetails;\n" }, { "answer_id": 74504636, "author": "Archon", "author_id": 7388203, "author_profile": "https://Stackoverflow.com/users/7388203", "pm_score": 1, "selected": false, "text": "<h2> {blog.blog} </h2>\n <h2> {blog.blog.split(/\\n/).map((t,i) => (<div key={i}>{t}</div>))} </h2>\n div" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74496843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20132576/" ]
74,496,853
<p>The below function parses multiple csv files in a directory and takes out values using str.startwith().</p> <p>It works find using '<em>firstline.startswith('TrakPro')</em>' and '<code>txt.startswith('Serial')</code>'. However, when I add a third str.startwith() i.e. txt2.startswith('Test'), nothing prints out, no error, appears to ignore it. What do I need to change? Basically I want to add multiple str.startwith() in the for loop pulling out various key words after the ':&quot;.</p> <pre><code>def get_csv_file_list(root): for r, d, f in os.walk(root): for file in f: if file.endswith('.csv'): path = os.path.join(r, file) dir_name = path.split(os.path.sep)[-2] file_name = os.path.basename(file) try: with open(path) as k: firstline = k.readline() if firstline.startswith('TrakPro'): file_list.append(path) file_list.append(dir_name) file_list.append(file_name) txt = 'Serial Number:' if txt.startswith('Serial'): for row in list(k)[3:4]: file_list.append(row[15:26]) txt2 = 'Test Name:' if txt2.startswith('Test'): for rows in list(k)[4:5]: print(rows) file_list.append(row[11:]) </code></pre> <p>The csv looks like this:</p> <pre><code>TrakPro Version 5.2.0.0 ASCII Data File Instrument Name:,SidePak Model Number:,TK0W02 Serial Number:,120k2136005 Test Name:,13270 Start Date:,04/17/2021 Start Time:,01:53:29 Duration (dd:hh:mm:ss):,00:07:13:00 Log Interval (mm:ss):,01:00 Number of points:,433 Description:, </code></pre> <p>So far I have tried the above code, I expected to print out values in the 'Test Name' line of the csv sample. The function does not print out anything, no error.</p> <p>Tks</p>
[ { "answer_id": 74496882, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 3, "selected": true, "text": "Test Name: with open(\"your_file.csv\", \"r\") as f_in:\n for line in map(str.strip, f_in):\n if line.startswith(\"Test Name:\"):\n _, value = line.split(\",\", maxsplit=1)\n print(value)\n 13270\n" }, { "answer_id": 74509622, "author": "Rolf of Saxony", "author_id": 4637585, "author_profile": "https://Stackoverflow.com/users/4637585", "pm_score": 0, "selected": false, "text": "k file_name = \"./abc.csv\"\nfile_list=[]\nwith open(file_name) as k:\n firstline = k.readline() # Consume first line\n if firstline.startswith('TrakPro'):\n print(\"First line:\\n\", firstline)\n file_list.append(file_name)\n txt = list(k) # here k is the file contents minus the first line\n print(\"Contents of list\\n\", txt)\n if str(txt[2]).startswith('Serial'):\n file_list.append(str(txt[2])[15:26])\n if str(txt[3]).startswith('Test'):\n file_list.append(str(txt[3].strip())[11:])\nprint(\"\\nResult:\\n\",file_list)\n TrakPro Version 5.2.0.0 ASCII Data File\nInstrument Name:,SidePak\nModel Number:,TK0W02\nSerial Number:,120k2136005\nTest Name:,13270\nStart Date:,04/17/2021\nStart Time:,01:53:29\nDuration (dd:hh:mm:ss):,00:07:13:00\nLog Interval (mm:ss):,01:00\nNumber of points:,433\nDescription:,\n First line:\n TrakPro Version 5.2.0.0 ASCII Data File\n\nContents of list\n ['Instrument Name:,SidePak\\n', 'Model Number:,TK0W02\\n', 'Serial Number:,120k2136005\\n', 'Test Name:,13270\\n', 'Start Date:,04/17/2021\\n', 'Start Time:,01:53:29\\n', 'Duration (dd:hh:mm:ss):,00:07:13:00\\n', 'Log Interval (mm:ss):,01:00\\n', 'Number of points:,433\\n', 'Description:,\\n']\n\nResult:\n ['./abc.csv', '120k2136005', '13270']\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74496853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16374285/" ]
74,496,858
<p>I have a hero with multiple images, I want to display images according to screen sizes, for example, if the user is using a big screen, the hero will load the large/wide images, and if he uses a phone, the hero will display a different image that is not wide to fit the screen. I do not know how to do this with nextjs, there is no way to specify which image to load on a different screen.</p>
[ { "answer_id": 74497053, "author": "Yilmaz", "author_id": 10262805, "author_profile": "https://Stackoverflow.com/users/10262805", "pm_score": 1, "selected": false, "text": "<div className=\"lg:absolute lg:inset-y-0 lg:right-0 lg:w-1/2\">\n <Image\n className=\"h-56 w-full object-cover sm:h-72 md:h-96 lg:w-full lg:h-full\"\n src={image}\n alt={title}\n // this is deprecated in next 13, just use \"fill\" as prop\n layout=\"fill\"\n />\n </div>\n import { useResizeDetector } from 'react-resize-detector';\n\nconst CustomComponent = () => {\n const { width, height, ref } = useResizeDetector();\n return <div ref={ref}>{`${width}x${height}`}</div>;\n};\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74496858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19796449/" ]
74,496,862
<p>We were told to do a program on stings and I wasn't able to attend class because I was sick. I am asking for your help on this task that was given to us.</p> <p>Create a java program that will ask the user to input two Strings. Compare the two strings and display the letters that are found on the first string but are not found on the second string.</p> <p>Here is what I have at the moment <a href="https://pastebin.com/7a4dHecR" rel="nofollow noreferrer">https://pastebin.com/7a4dHecR</a></p> <p>I really have no Idea what to do so any help would be appreciated!</p> <p><a href="https://pastebin.com/7a4dHecR" rel="nofollow noreferrer">https://pastebin.com/7a4dHecR</a></p> <pre><code>import java.util.*; public class filename{ public static void main(String[] args){ Scanner sc =new Scanner(System.in); System.out.print(&quot;Input first string: &quot;); String one=sc.next(); System.out.println(); System.out.print(&quot;Input second string: &quot;); String two=sc.next(); } } </code></pre>
[ { "answer_id": 74496912, "author": "Parmingo", "author_id": 20305399, "author_profile": "https://Stackoverflow.com/users/20305399", "pm_score": -1, "selected": false, "text": "String diff: StringUtils.difference(one, two);\nSystem.out.println(diff);\n" }, { "answer_id": 74496997, "author": "tgdavies", "author_id": 11002, "author_profile": "https://Stackoverflow.com/users/11002", "pm_score": 0, "selected": false, "text": "for (int i = 0; i < one.length(); i++) {\n // your code here\n}\n String String c = one.substring(i, i+1);\n String.substring i i+1 String contains String String" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74496862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20544206/" ]
74,496,871
<p>I am trying find the third and fourth max number in a list and then sum them. The solution must be linear O(n).</p> <p>eg:</p> <pre><code> &gt;&gt;&gt; Max_34([1000, 1, 100, 2, 99, 200,100]) 199 </code></pre> <p>Here's what I did:</p> <p>The problem is that it will work for max_34([1,2,3,4]), but it won't work for max_34([1000, 1, 100, 2, 99, 200,100]). Why ? Could someone please correct my code without writing a new one. I really wanna learn from my mistakes.</p> <p>Thanks in advance :)</p> <p>update :</p> <p>Would this be O(n) ? Why ?</p>
[ { "answer_id": 74496912, "author": "Parmingo", "author_id": 20305399, "author_profile": "https://Stackoverflow.com/users/20305399", "pm_score": -1, "selected": false, "text": "String diff: StringUtils.difference(one, two);\nSystem.out.println(diff);\n" }, { "answer_id": 74496997, "author": "tgdavies", "author_id": 11002, "author_profile": "https://Stackoverflow.com/users/11002", "pm_score": 0, "selected": false, "text": "for (int i = 0; i < one.length(); i++) {\n // your code here\n}\n String String c = one.substring(i, i+1);\n String.substring i i+1 String contains String String" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74496871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20544212/" ]
74,496,881
<p>I have an app in flutter that gives me a snapshot.data but I need to add a fixed text before the snapshot.data Example: &quot;Position:&quot; snapshot.data</p> <pre><code> drawer: new Drawer( child: new ListView( children: &lt;Widget&gt;[ new UserAccountsDrawerHeader( //accountEmail: Text(&quot;Paso:&quot;), accountEmail: FutureBuilder&lt;String&gt;( future: functions.FunctionsHelper.getAgentPosition(), builder: (context, snapshot) { if (snapshot.hasData) { return RichText( text: TextSpan( children: [ TextSpan( text: snapshot.data, style: new TextStyle( height: -0.2, fontSize: 11.4, color: Colors.white, fontWeight: FontWeight.w700)), ], ), ); </code></pre>
[ { "answer_id": 74496913, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 0, "selected": false, "text": " return RichText(\n text: TextSpan(\n children: [\n TextSpan(\n text: snapshot.data,\n style: new TextStyle(\n height: -0.2,\n fontSize: 11.4,\n color: Colors.white,\n fontWeight: FontWeight.w700)),\n ],\n ),\n );\n RichText(\n text: TextSpan(\n children: [\n const TextSpan(\n text: \"Position : \",\n style: TextStyle(\n color: Colors.black,\n fontSize: 16,\n ),\n ),\n TextSpan(\n text: snapshot.data,\n style: TextStyle(\n height: -0.2,\n fontSize: 11.4,\n color: Colors.white,\n fontWeight: FontWeight.w700)),\n ],\n ),\n ),\n" }, { "answer_id": 74496919, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 1, "selected": false, "text": "String TextSpan(\n text: \"position : ${snapshot.data}\",\n style: new TextStyle(\n height: -0.2,\n fontSize: 11.4,\n color: Colors.white,\n fontWeight: FontWeight.w700)),\n ],\n ),\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74496881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20264085/" ]
74,496,885
<p>I have a spark dataframe. I attempt to drop a column, but in some situations the column appears to still be there.</p> <pre><code>my_range = spark.range(1000).toDF(&quot;number&quot;) new_range = my_range.withColumn('num2', my_range.number*2).drop('number') # can still sort by &quot;number&quot; column new_range.sort('number') </code></pre> <p>Is this a bug? Or am I missing something?</p> <p>Spark version is v3.3.1 python 3 I'm on a Mbook pro M1 20221</p>
[ { "answer_id": 74496913, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 0, "selected": false, "text": " return RichText(\n text: TextSpan(\n children: [\n TextSpan(\n text: snapshot.data,\n style: new TextStyle(\n height: -0.2,\n fontSize: 11.4,\n color: Colors.white,\n fontWeight: FontWeight.w700)),\n ],\n ),\n );\n RichText(\n text: TextSpan(\n children: [\n const TextSpan(\n text: \"Position : \",\n style: TextStyle(\n color: Colors.black,\n fontSize: 16,\n ),\n ),\n TextSpan(\n text: snapshot.data,\n style: TextStyle(\n height: -0.2,\n fontSize: 11.4,\n color: Colors.white,\n fontWeight: FontWeight.w700)),\n ],\n ),\n ),\n" }, { "answer_id": 74496919, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 1, "selected": false, "text": "String TextSpan(\n text: \"position : ${snapshot.data}\",\n style: new TextStyle(\n height: -0.2,\n fontSize: 11.4,\n color: Colors.white,\n fontWeight: FontWeight.w700)),\n ],\n ),\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74496885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5767904/" ]
74,497,005
<p>I'm trying to write a SQL query to count the number of requests received every 15 minutes within the past hour. I want to return the last three 15 minute intervals.</p> <p>My data looks like:</p> <pre><code>log_date, time 2022-11-18, 2022-11-18 17:00:00 UTC 2022-11-18, 2022-11-18 17:10:00 UTC 2022-11-18, 2022-11-18 17:20:00 UTC 2022-11-18, 2022-11-18 17:40:00 UTC </code></pre> <p>My query so far:</p> <pre><code>select log_date, FLOOR(unix_timestamp(time)) div (15 * 60) as intervals, count(*) from data_log where log_date &gt;= date_sub(from_unixtime(unix_timestamp(), 'yyyy-MM-dd'), 1) and requests_recieved = true group by log_date, time order by intervals desc limit 3 </code></pre> <p>I want it to look like:</p> <pre><code>log_date, time, count 2022-11-18, 2022-11-18 17:00:00 UTC, 2 2022-11-18, 2022-11-18 17:15:00 UTC, 1 2022-11-18, 2022-11-18 17:30:00 UTC, 1 </code></pre> <p>Update: I'm using SparkSQL 2.3.1</p>
[ { "answer_id": 74497186, "author": "etsuhisa", "author_id": 13841016, "author_profile": "https://Stackoverflow.com/users/13841016", "pm_score": 2, "selected": true, "text": "time TIMESTAMPADD SELECT * FROM (\n SELECT\n log_date,\n TIMESTAMPADD(\n MINUTE,\n hour(time) * 60 + (minute(time) div 15 * 15),\n date(time)) time15m,\n COUNT(*) count\n FROM t1\n GROUP BY log_date, time15m\n ORDER BY time15m DESC\n LIMIT 3\n) s\nORDER BY time15m;\n" }, { "answer_id": 74497296, "author": "JHH", "author_id": 20127235, "author_profile": "https://Stackoverflow.com/users/20127235", "pm_score": 0, "selected": false, "text": "log_time data_log create table data_log (\n log_date date,\n log_time timestamp,\n requests_received boolean);\n\ninsert into data_log\nvalues\n('2022-11-18', '2022-11-18 17:55:00', true),\n('2022-11-18', '2022-11-18 18:00:00', true),\n('2022-11-18', '2022-11-18 18:10:00', true),\n('2022-11-18', '2022-11-18 18:20:00', true),\n('2022-11-18', '2022-11-18 18:40:00', true),\n('2022-11-18', '2022-11-18 18:50:00', true);\n with an_hour_ago as (\nselect date_add(current_timestamp, interval -1 hour) as an_hour_ago),\ninterval_an_hour_ago as (\nselect date_add(date_format(an_hour_ago, '%y-%m-%d %H:00:00'), interval 15 * floor(date_format(an_hour_ago, '%i') / 15) minute) as start_interval\n from an_hour_ago)\nselect log_date,\n date_add(date_format(log_time,'%y-%m-%d %H:00:00'), interval 15 * floor(date_format(log_time,'%i') / 15) minute ) as log_interval,\n count(*) as count\n from data_log d,\n interval_an_hour_ago i \n where d.requests_received = true\n and d.log_time >= i.start_interval\n group by 1, 2;\n log_date |log_interval |count|\n----------+-------------------+-----+\n2022-11-18|2022-11-18 18:00:00| 2|\n2022-11-18|2022-11-18 18:15:00| 1|\n2022-11-18|2022-11-18 18:30:00| 1|\n2022-11-18|2022-11-18 18:45:00| 1|\n" }, { "answer_id": 74497393, "author": "Ehab", "author_id": 20342736, "author_profile": "https://Stackoverflow.com/users/20342736", "pm_score": 0, "selected": false, "text": "SET time_zone = 'UTC';\nSET @i=0;\nSET @t_now = unix_timestamp(); /*Request time*/\nSET @hr = 3600 * (@t_now div 3600); /*Request hour*/\n\nSELECT log_date, from_unixtime(qr * 15 * 60 + @hr) AS `time`, COUNT(qr) AS `count` FROM (\n \n SELECT \n log_date, \n @i:=((@t_now - unix_timestamp(`time`)) div 60) AS m, /* minutes elapsed */\n FLOOR(@i/15) as qr /*hour quarter*/\n FROM data_log WHERE requests_recieved = true \n \n) AS t1\nWHERE m <= 60 /* Last hour only */\nGROUP BY log_date, qr /* Group by each hour quarter */\nORDER BY log_date, qr\n;\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10689661/" ]
74,497,009
<p>So I am still learning Swift and for some reason, I am having the hardest trouble with the previews and how to configure them.</p> <p>So I have the following code:</p> <pre><code>struct MainView: View { // The app's model that the containing scene passes in @ObservedObject var model: MainViewModel @State var activeTab = 0 var body: some View { VStack { TabView(selection: $activeTab) { Group { WorldView(model: model, activeTab: $activeTab) .tabItem { Label(Tabs.explore.rawValue, systemImage: Tabs.explore.icon) .environment(\.symbolVariants, .none) } .tag(0) ListView(model: model, activeTab: $activeTab) .tabItem { Label(Tabs.list.rawValue, systemImage: Tabs.list.icon) .environment(\.symbolVariants, .none) } .tag(1) FavoritesView(activeTab: $activeTab) .tabItem { Label(Tabs.favorite.rawValue, systemImage: Tabs.favorite.icon) .environment(\.symbolVariants, .none) } .tag(2) ProfileView(model: model, activeTab: $activeTab) .tabItem { Label(Tabs.profile.rawValue, systemImage: Tabs.profile.icon) .environment(\.symbolVariants, .none) } .tag(3) } .environmentObject(model) } .tint(.accentColor) .onChange(of: activeTab, perform: { value in log.info(&quot;\n : (MainView: 46) - User has selected tab: \(value).&quot;) print(&quot;&quot;) }) } .onAppear() { model.fetchPlaces() } } } </code></pre> <p>Then I have the preview, as such:</p> <pre><code>struct MainView_Previews: PreviewProvider { static var previews: some View { MainView(model: model, activeTab: activeTab) } } </code></pre> <p>I am getting the two errors on the previews:</p> <blockquote> <p>Cannot find 'activeTab' in scope<br /> Cannot find 'model' in scope</p> </blockquote> <p>If I define it as such:</p> <pre><code>struct MainView_Previews: PreviewProvider { @ObservedObject var model: MainViewModel @State var activeTab = 0 static var previews: some View { MainView(model: model, activeTab: activeTab) } } </code></pre> <p>I get the following errors:</p> <blockquote> <p>Instance member 'activeTab' cannot be used on type 'MainView_Previews'<br /> Instance member 'model' cannot be used on type 'MainView_Previews'</p> </blockquote> <p>Does anyone know how I can configure the preview so that it works properly and doesn't crash?</p>
[ { "answer_id": 74497086, "author": "Mr Developer", "author_id": 20384561, "author_profile": "https://Stackoverflow.com/users/20384561", "pm_score": 3, "selected": true, "text": "struct MyExamplePreviews: PreviewProvider{\n static var previews: some View {\n MainView(model: MainViewModel(), activeTab: 0)\n }\n}\n Previews" }, { "answer_id": 74508516, "author": "malhal", "author_id": 259521, "author_profile": "https://Stackoverflow.com/users/259521", "pm_score": 1, "selected": false, "text": "@EnvironmentObject var model: Model class Model: ObservableObject {\n @Published var items: [Item] = []\n\n static var shared = Model()\n static var preview = Model(preview: true)\n\n init(preview: Bool) {\n if preview {\n items = // set some test items\n return\n }\n load()\n }\n\n fun load(){\n // load items from disk\n }\n}\n @main\nstruct TestApp: App {\n var body: some Scene {\n WindowGroup {\n ContentView()\n .environmentObject(Model.shared)\n }\n }\n}\n struct ContentView: View {\n @EnvironmentObject var: model: Model\n\n var body: some View {\n NavigationStack {\n List {\n ForEach($model.items) $item in {\n TextField(\"Title\" text: $item.title)\n }\n .navigationTitle(\"Items\")\n }\n }\n}\n\nstruct ContentView_Previews: PreviewProvider {\n static var previews: some View {\n ContentView()\n .environmentObject(Model.preview)\n }\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19566858/" ]
74,497,025
<p>I'm using the latest version of SQL Server and have the following problem. Given the table below, the requirement, quite simply, is to delete &quot;trailing&quot; records in each <code>_category</code> partition that have <code>_value = 0</code>. Trailing in this context means, when the records are placed in <code>_date</code> order, any series or contiguous block of records with <code>_value = 0</code> at the end of the list should be deleted. Records with <code>_value = 0</code> that have subsequent records in the partition with some non-zero value should stay.</p> <pre><code>create table #x (_id int identity, _category int, _date date, _value int) insert into #x values (1, '2022-10-01', 12) insert into #x values (1, '2022-10-03', 0) insert into #x values (1, '2022-10-04', 10) insert into #x values (1, '2022-10-06', 11) insert into #x values (1, '2022-10-07', 10) insert into #x values (2, '2022-10-01', 1) insert into #x values (2, '2022-10-02', 0) insert into #x values (2, '2022-10-05', 19) insert into #x values (2, '2022-10-10', 18) insert into #x values (2, '2022-10-12', 0) insert into #x values (2, '2022-10-13', 0) insert into #x values (2, '2022-10-15', 0) insert into #x values (3, '2022-10-02', 10) insert into #x values (3, '2022-10-03', 0) insert into #x values (3, '2022-10-05', 0) insert into #x values (3, '2022-10-06', 12) insert into #x values (3, '2022-10-08', 0) </code></pre> <p>I see a few ways to do it. The brute force way is to to run the records through a cursor in date order, and grab the ID of any record where <code>_value = 0</code> and see if it holds until the category changes. I'm trying to avoid T-SQL though if I can do it in a query.</p> <p>To that end, I thought I could apply some gaps and islands trickery and do something with window functions. I feel like there might be a way to leverage <code>last_value()</code> for this, but so far I only see it useful in identifying partitions that have the criteria, not so much in helping me get the ID's of the records to delete.</p> <p>The desired result is the deletion of records 10, 11, 12 and 17.</p> <p>Appreciate any help.</p>
[ { "answer_id": 74497074, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 2, "selected": false, "text": "SELECT _id, _catrgory, _date, _value\nFROM #x x1\nWHERE _value <> 0 OR\n EXISTS (\n SELECT 1\n FROM #x x2\n WHERE x2._category = x1._category AND\n x2._date > x1._date AND\n x2._value <> 0\n );\n" }, { "answer_id": 74497090, "author": "T N", "author_id": 12637193, "author_profile": "https://Stackoverflow.com/users/12637193", "pm_score": 0, "selected": false, "text": "WITH CTE_NumberedRows AS (\n SELECT *, rn = ROW_NUMBER() OVER(PARTITION BY _category ORDER BY _date)\n FROM #x\n),\nCTE_Keepers AS (\n SELECT _category, rnLastKeeper = MAX(rn)\n FROM CTE_NumberedRows\n WHERE _value <> 0\n GROUP BY _category\n)\nDELETE NR\nFROM CTE_NumberedRows NR\nLEFT JOIN CTE_Keepers K\n ON K._category = NR._category\nWHERE NR.rn > ISNULL(K.rnLastKeeper, 0)\n" }, { "answer_id": 74499589, "author": "forpas", "author_id": 10498828, "author_profile": "https://Stackoverflow.com/users/10498828", "pm_score": 2, "selected": true, "text": "_value 0 MAX() CTE WITH cte AS (\n SELECT *, \n MAX(_value) OVER (\n PARTITION BY _category \n ORDER BY _date \n ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING\n ) max\n FROM #x\n) \nDELETE FROM cte\nWHERE max = 0;\n _value MAX(ABS(_value)) MAX(_value)" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6658435/" ]
74,497,027
<p><a href="https://i.stack.imgur.com/GKpcX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GKpcX.png" alt="enter image description here" /></a></p> <p>Here I want to operate the code in line 14. But is is type error. Can we make remove it making both int or anything.</p>
[ { "answer_id": 74497074, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 2, "selected": false, "text": "SELECT _id, _catrgory, _date, _value\nFROM #x x1\nWHERE _value <> 0 OR\n EXISTS (\n SELECT 1\n FROM #x x2\n WHERE x2._category = x1._category AND\n x2._date > x1._date AND\n x2._value <> 0\n );\n" }, { "answer_id": 74497090, "author": "T N", "author_id": 12637193, "author_profile": "https://Stackoverflow.com/users/12637193", "pm_score": 0, "selected": false, "text": "WITH CTE_NumberedRows AS (\n SELECT *, rn = ROW_NUMBER() OVER(PARTITION BY _category ORDER BY _date)\n FROM #x\n),\nCTE_Keepers AS (\n SELECT _category, rnLastKeeper = MAX(rn)\n FROM CTE_NumberedRows\n WHERE _value <> 0\n GROUP BY _category\n)\nDELETE NR\nFROM CTE_NumberedRows NR\nLEFT JOIN CTE_Keepers K\n ON K._category = NR._category\nWHERE NR.rn > ISNULL(K.rnLastKeeper, 0)\n" }, { "answer_id": 74499589, "author": "forpas", "author_id": 10498828, "author_profile": "https://Stackoverflow.com/users/10498828", "pm_score": 2, "selected": true, "text": "_value 0 MAX() CTE WITH cte AS (\n SELECT *, \n MAX(_value) OVER (\n PARTITION BY _category \n ORDER BY _date \n ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING\n ) max\n FROM #x\n) \nDELETE FROM cte\nWHERE max = 0;\n _value MAX(ABS(_value)) MAX(_value)" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20429919/" ]
74,497,048
<p>I can enter into my terminal (wsl) python3 filename.py and the code executes in the terminal just fine. But when I hit the play button (Run Python File) I get errors</p> <p>C:/Users/user1/AppData/Local/Programs/Python/Python311/python.exe &quot;c:/Online Learning/Coder Academy/Python/Lesson-3/test.py&quot; zsh: no such file or directory: C:/Users/user1/AppData/Local/Programs/Python/Python311/python.exe</p> <p>I don't see why if the code is executing fine from the terminal by typing in the command. Why can't I hit the play button without error?</p> <p>I've tried a lot of things including using extension Code-Runner. Uninstalling and re-installing various versions of python. I've tried pyenv, defining various different interpreter paths.</p> <p>I'm thinking it's not the set up of my python in wsl it's something to do with a setting in VSCode.</p>
[ { "answer_id": 74497074, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 2, "selected": false, "text": "SELECT _id, _catrgory, _date, _value\nFROM #x x1\nWHERE _value <> 0 OR\n EXISTS (\n SELECT 1\n FROM #x x2\n WHERE x2._category = x1._category AND\n x2._date > x1._date AND\n x2._value <> 0\n );\n" }, { "answer_id": 74497090, "author": "T N", "author_id": 12637193, "author_profile": "https://Stackoverflow.com/users/12637193", "pm_score": 0, "selected": false, "text": "WITH CTE_NumberedRows AS (\n SELECT *, rn = ROW_NUMBER() OVER(PARTITION BY _category ORDER BY _date)\n FROM #x\n),\nCTE_Keepers AS (\n SELECT _category, rnLastKeeper = MAX(rn)\n FROM CTE_NumberedRows\n WHERE _value <> 0\n GROUP BY _category\n)\nDELETE NR\nFROM CTE_NumberedRows NR\nLEFT JOIN CTE_Keepers K\n ON K._category = NR._category\nWHERE NR.rn > ISNULL(K.rnLastKeeper, 0)\n" }, { "answer_id": 74499589, "author": "forpas", "author_id": 10498828, "author_profile": "https://Stackoverflow.com/users/10498828", "pm_score": 2, "selected": true, "text": "_value 0 MAX() CTE WITH cte AS (\n SELECT *, \n MAX(_value) OVER (\n PARTITION BY _category \n ORDER BY _date \n ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING\n ) max\n FROM #x\n) \nDELETE FROM cte\nWHERE max = 0;\n _value MAX(ABS(_value)) MAX(_value)" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20260141/" ]
74,497,075
<p>This is the dataframe:</p> <pre><code>data = {&quot;Company&quot; : [[&quot;ConsenSys&quot;] , [&quot;Cognizant&quot;], [&quot;IBM&quot;], [&quot;IBM&quot;], [&quot;Reddit, Inc&quot;], [&quot;Reddit, Inc&quot;], [&quot;IBM&quot;]], &quot;skills&quot; : [['services', 'scientist technical expertise', 'databases'], ['datacomputing tools experience', 'deep learning models', 'cloud services'], ['quantitative analytical projects', 'financial services', 'field experience'], ['filesystems server architectures', 'systems', 'statistical analysis', 'data analytics', 'workflows', 'aws cloud services'], ['aws services'], ['data mining statistics', 'statistical analysis', 'aws cloud', 'services', 'data discovery', 'visualization'], ['communication skills experience', 'services', 'manufacturing environment', 'sox compliance']]} dff = pd.DataFrame(data) dff </code></pre> <ul> <li>I need to create a new column, and I want to start by taking specific words out of the skills column.</li> <li>The row that does not include those specific words should then be deleted.</li> <li>Specific words: 'services', 'statistical analysis'</li> </ul> <p>Expected Output:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>Company</th> <th>skills</th> <th>new_col</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>[ConsenSys]</td> <td>[services, scientist technical expertise, databases]</td> <td>[services]</td> </tr> <tr> <td>1</td> <td>[IBM]</td> <td>[filesystems server architectures, systems, statistical analysis, data analytics, workflows, aws cloud services]</td> <td>[services, statistical analysis]</td> </tr> <tr> <td>2</td> <td>[Reddit, Inc]</td> <td>[data mining statistics, statistical analysis, aws cloud, services, data discovery, visualization]</td> <td>[statistical analysis]</td> </tr> <tr> <td>3</td> <td>[IBM]</td> <td>['communication skills experience', 'services', 'manufacturing environment', 'sox compliance']</td> <td>[services]</td> </tr> </tbody> </table> </div> <p>I tried quite a lot of code in an effort to extract a specific word from the one that was available on Stack Overflow, but I was unsuccessful.</p>
[ { "answer_id": 74497127, "author": "Jason Baker", "author_id": 3249641, "author_profile": "https://Stackoverflow.com/users/3249641", "pm_score": 1, "selected": false, "text": "words = [\"services\", \"statistical analysis\"]\ndff[\"found\"] = dff[\"skills\"].apply(lambda x: \", \".join(set([i for i in x if i in words])).split(\", \"))\n" }, { "answer_id": 74497192, "author": "Panda Kim", "author_id": 20430449, "author_profile": "https://Stackoverflow.com/users/20430449", "pm_score": 1, "selected": true, "text": "word = ['services', 'statistical analysis']\ns1 = df['skills'].apply(lambda x: [i for i in word if i in x])\n s1 0 [services]\n1 []\n2 []\n3 [statistical analysis]\n4 []\n5 [services, statistical analysis]\n6 [services]\nName: skills, dtype: object\n s1 new_col boolean indexing df.assign(new_col=s1)[lambda x: x['new_col'].astype('bool')]\n Company skills new_col\n0 [ConsenSys] [services, scientist technical expertise, data... [services]\n3 [IBM] [filesystems server architectures, systems, st... [statistical analysis]\n5 [Reddit, Inc] [data mining statistics, statistical analysis,... [services, statistical analysis]\n6 [IBM] [communication skills experience, services, ma... [services]\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16792946/" ]
74,497,078
<p>I am using webpack with react. I have set up config for both production and development. I am getting this error in my src/index.js file:</p> <p>ERROR in ./src/index.js 11:1 Module parse failed: Unexpected token (11:1) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See <a href="https://webpack.js.org/concepts#loaders" rel="nofollow noreferrer">https://webpack.js.org/concepts#loaders</a></p> <p>index.js</p> <pre><code>import ReactDOM from &quot;react-dom/client&quot;; import &quot;./index.css&quot;; import App from &quot;./App&quot;; import reportWebVitals from &quot;./reportWebVitals&quot;; import &quot;bootstrap/dist/css/bootstrap.min.css&quot;; const root = ReactDOM.createRoot(document.getElementById(&quot;root&quot;)); root.render( // &lt;React.StrictMode&gt; &lt;App /&gt; // &lt;/React.StrictMode&gt; ); reportWebVitals(); </code></pre> <p>package.json</p> <pre><code> &quot;name&quot;: &quot;client&quot;, &quot;version&quot;: &quot;0.1.0&quot;, &quot;private&quot;: true, &quot;proxy&quot;: &quot;http://127.0.0.1:9000&quot;, &quot;dependencies&quot;: { &quot;@testing-library/jest-dom&quot;: &quot;^5.16.5&quot;, &quot;@testing-library/react&quot;: &quot;^13.4.0&quot;, &quot;@testing-library/user-event&quot;: &quot;^13.5.0&quot;, &quot;axios&quot;: &quot;^1.1.2&quot;, &quot;bootstrap&quot;: &quot;^5.1.0&quot;, &quot;bootstrap-css-only&quot;: &quot;^4.4.1&quot;, &quot;dotenv&quot;: &quot;^16.0.3&quot;, &quot;history&quot;: &quot;^5.3.0&quot;, &quot;react&quot;: &quot;^18.2.0&quot;, &quot;react-dom&quot;: &quot;^18.2.0&quot;, &quot;react-router-dom&quot;: &quot;^6.4.2&quot;, &quot;react-scripts&quot;: &quot;5.0.1&quot;, &quot;react-twitter-login&quot;: &quot;^1.5.0&quot;, &quot;reactstrap&quot;: &quot;^9.1.4&quot;, &quot;universal-cookie&quot;: &quot;^4.0.4&quot;, &quot;web-vitals&quot;: &quot;^2.1.4&quot;, &quot;webpack&quot;: &quot;^5.75.0&quot;, &quot;webpack-cli&quot;: &quot;^4.10.0&quot; }, &quot;scripts&quot;: { &quot;start&quot;: &quot;webpack serve&quot;, &quot;build&quot;: &quot;webpack&quot;, &quot;test&quot;: &quot;react-scripts test&quot;, &quot;eject&quot;: &quot;react-scripts eject&quot; }, &quot;eslintConfig&quot;: { &quot;extends&quot;: [ &quot;react-app&quot;, &quot;react-app/jest&quot; ] }, &quot;browserslist&quot;: { &quot;production&quot;: [ &quot;&gt;0.2%&quot;, &quot;not dead&quot;, &quot;not op_mini all&quot; ], &quot;development&quot;: [ &quot;last 1 chrome version&quot;, &quot;last 1 firefox version&quot;, &quot;last 1 safari version&quot; ] }, &quot;devDependencies&quot;: { &quot;@babel/core&quot;: &quot;^7.20.2&quot;, &quot;@babel/preset-env&quot;: &quot;^7.20.2&quot;, &quot;@babel/preset-react&quot;: &quot;^7.18.6&quot;, &quot;babel-loader&quot;: &quot;^9.1.0&quot;, &quot;clean-webpack-plugin&quot;: &quot;^4.0.0&quot;, &quot;css-loader&quot;: &quot;^6.7.2&quot;, &quot;node-sass&quot;: &quot;^7.0.3&quot;, &quot;postcss-loader&quot;: &quot;^7.0.1&quot;, &quot;postcss-preset-env&quot;: &quot;^7.8.3&quot;, &quot;saas&quot;: &quot;^1.0.0&quot;, &quot;sass-loader&quot;: &quot;^13.2.0&quot;, &quot;style-loader&quot;: &quot;^3.3.1&quot;, &quot;webpack-dev-server&quot;: &quot;^4.11.1&quot; } } </code></pre> <p>webpack.common.js</p> <pre><code>const path = require(&quot;./path&quot;); const { CleanWebpackPlugin } = require(&quot;clean-webpack-plugin&quot;); const paths = require(&quot;./paths&quot;); module.exports = { // Where webpack looks to start building the bundle entry: [paths.src + &quot;/index.js&quot;], // Where webpack outputs the assets and bundles output: { path: paths.build, filename: &quot;[name].bundle.js&quot;, publicPath: &quot;/&quot;, }, // Customize the webpack build process plugins: [ // Removes/cleans build folders and unused assets when rebuilding new CleanWebpackPlugin(), // Copies files from target to destination folder new CopyWebpackPlugin({ patterns: [ { from: paths.public, to: &quot;assets&quot;, globOptions: { ignore: [&quot;*.DS_Store&quot;], }, noErrorOnMissing: true, }, ], }), // Generates an HTML file from a template // Generates deprecation warning: https://github.com/jantimon/html-webpack-plugin/issues/1501 // new HtmlWebpackPlugin({ // title: &quot;webpack Boilerplate&quot;, // favicon: paths.src + &quot;/images/favicon.png&quot;, // template: paths.src + &quot;/template.html&quot;, // template file // filename: &quot;index.html&quot;, // output file // }), ], // Determine how modules within the project are treated module: { rules: [ // JavaScript: Use Babel to transpile JavaScript files { test: /\.(js|jsx)$/, use: [&quot;babel-loader&quot;] }, // Images: Copy image files to build folder { test: /\.(?:ico|gif|png|jpg|jpeg)$/i, type: &quot;asset/resource&quot; }, // Fonts and SVGs: Inline files { test: /\.(woff(2)?|eot|ttf|otf|svg|)$/, type: &quot;asset/inline&quot; }, ], }, resolve: { modules: [paths.src, &quot;node_modules&quot;], extensions: [&quot;.js&quot;, &quot;.jsx&quot;, &quot;.json&quot;], alias: { &quot;@&quot;: paths.src, assets: paths.public, }, }, }; </code></pre> <p>webpack.dev.js</p> <pre><code>const { merge } = require(&quot;webpack-merge&quot;); const common = require(&quot;./webpack.common&quot;); module.exports = merge(common, { // Set the mode to development or production mode: &quot;development&quot;, // Control how source maps are generated devtool: &quot;inline-source-map&quot;, // Spin up a server for quick development devServer: { historyApiFallback: true, open: true, compress: true, hot: true, port: 3000, }, module: { rules: [ // Styles: Inject CSS into the head with source maps { test: /\.(sass|scss|css)$/, use: [ &quot;style-loader&quot;, { loader: &quot;css-loader&quot;, options: { sourceMap: true, importLoaders: 1, modules: false }, }, { loader: &quot;postcss-loader&quot;, options: { sourceMap: true } }, { loader: &quot;sass-loader&quot;, options: { sourceMap: true } }, ], }, ], }, }); </code></pre> <p>.babelrc</p> <pre><code>{ &quot;presets&quot;: [&quot;@babel/preset-env&quot;,&quot;@babel/preset-react&quot;, &quot;react&quot;], &quot;plugins&quot;: [&quot;@babel/plugin-proposal-class-properties&quot;] } </code></pre> <p>./public/index.html</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot; /&gt; &lt;link rel=&quot;icon&quot; href=&quot;%PUBLIC_URL%/favicon.ico&quot; /&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot; /&gt; &lt;meta name=&quot;theme-color&quot; content=&quot;#000000&quot; /&gt; &lt;meta name=&quot;description&quot; content=&quot;Web site created using create-react-app&quot; /&gt; &lt;link rel=&quot;apple-touch-icon&quot; href=&quot;%PUBLIC_URL%/logo192.png&quot; /&gt; &lt;link rel=&quot;manifest&quot; href=&quot;%PUBLIC_URL%/manifest.json&quot; /&gt; &lt;title&gt;React App&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;noscript&gt;You need to enable JavaScript to run this app.&lt;/noscript&gt; &lt;div id=&quot;root&quot;&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>&lt;App/ &gt; is a react class component webpack.common.js,webpack.dev.js, webpack.prod.js are all in one folder &quot;config&quot;</p>
[ { "answer_id": 74497163, "author": "Yilmaz", "author_id": 10262805, "author_profile": "https://Stackoverflow.com/users/10262805", "pm_score": 0, "selected": false, "text": "js/jsx { test: /\\.(js|jsx)/, loader: \"babel-loader\", exclude: /node_modules/ },\n npm install babel-loader" }, { "answer_id": 74497233, "author": "OFRBG", "author_id": 1231844, "author_profile": "https://Stackoverflow.com/users/1231844", "pm_score": 2, "selected": true, "text": " \"scripts\": {\n \"start\": \"webpack serve --config webpack.dev.js\",\n \"build\": \"webpack --config webpack.prod.js\",\n \"test\": \"react-scripts test\",\n \"eject\": \"react-scripts eject\"\n },\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10993708/" ]
74,497,081
<p>I am new to dart so sorry if I'm missing something obvious I'm writing a code to add elements to this Set&lt;List&gt; which works fine, but when I try to check if the element exists or to delete it does not work.</p> <p>here's the code</p> <pre><code>void main(List&lt;String&gt; args) { Set&lt;List&lt;double&gt;&gt; level1barriers = {}; print(level1barriers); level1barriers.add([1, 1]); level1barriers.add([0.5, 0.3]); print(level1barriers); print(level1barriers.contains([1, 1])); level1barriers.remove([1, 1]); print(level1barriers); } </code></pre>
[ { "answer_id": 74497163, "author": "Yilmaz", "author_id": 10262805, "author_profile": "https://Stackoverflow.com/users/10262805", "pm_score": 0, "selected": false, "text": "js/jsx { test: /\\.(js|jsx)/, loader: \"babel-loader\", exclude: /node_modules/ },\n npm install babel-loader" }, { "answer_id": 74497233, "author": "OFRBG", "author_id": 1231844, "author_profile": "https://Stackoverflow.com/users/1231844", "pm_score": 2, "selected": true, "text": " \"scripts\": {\n \"start\": \"webpack serve --config webpack.dev.js\",\n \"build\": \"webpack --config webpack.prod.js\",\n \"test\": \"react-scripts test\",\n \"eject\": \"react-scripts eject\"\n },\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12203173/" ]
74,497,103
<p>What I need is to be able to customize <code>textAreaCount</code> and other props in each separate instance of <code>&lt;Texarea/&gt;</code>. The <code>textAreaCount</code> is different for each <code>&lt;Texarea/&gt;</code> so how do I modify the component to be able to pass in custom <code>textAreaCount</code> for each <code>&lt;Texarea/&gt;</code>?</p> <p><a href="https://codesandbox.io/s/rkv88-forked-vjo0rn?file=/src/App.js:0-948" rel="nofollow noreferrer">https://codesandbox.io/s/rkv88-forked-vjo0rn?file=/src/App.js:0-948</a></p> <pre><code>import React, { useState } from &quot;react&quot;; const Textarea = (value, id, maxLength, textAreaLimit) =&gt; { const [textAreaCount, ChangeTextAreaCount] = React.useState(0); const [state, setstate] = useState({ headline: &quot;&quot;, title: &quot;&quot; }); const { headline, title } = state; const changevalue = (e) =&gt; { setstate({ ...state, [e.target.name]: value }); ChangeTextAreaCount(e.target.value.length); }; return ( &lt;&gt; &lt;p&gt;{textAreaCount}/{textAreaLimit}&lt;/p&gt; &lt;textarea type=&quot;text&quot; rows={5} id={id} value={value} maxLength={maxLength} onChange={(e) =&gt; { changevalue(e); }} /&gt; &lt;/&gt; ); }; export default function FullWidthTabs() { return ( &lt;div&gt; &lt;Textarea value={headline} id=&quot;test&quot; maxLength={5} textAreaLimit={5}/&gt; &lt;Textarea value={title} id=&quot;test2&quot; maxLength={10} textAreaLimit={10}/&gt; &lt;/div&gt; ); } </code></pre>
[ { "answer_id": 74497163, "author": "Yilmaz", "author_id": 10262805, "author_profile": "https://Stackoverflow.com/users/10262805", "pm_score": 0, "selected": false, "text": "js/jsx { test: /\\.(js|jsx)/, loader: \"babel-loader\", exclude: /node_modules/ },\n npm install babel-loader" }, { "answer_id": 74497233, "author": "OFRBG", "author_id": 1231844, "author_profile": "https://Stackoverflow.com/users/1231844", "pm_score": 2, "selected": true, "text": " \"scripts\": {\n \"start\": \"webpack serve --config webpack.dev.js\",\n \"build\": \"webpack --config webpack.prod.js\",\n \"test\": \"react-scripts test\",\n \"eject\": \"react-scripts eject\"\n },\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6263953/" ]
74,497,110
<p>I have this text:</p> <pre><code>&gt;A1 KKKKKKKK DDDDDDDD &gt;A2 FFFFFFFF FFFFOOOO DAA &gt;A3 OOOZDDD KKAZAAA A </code></pre> <p>When I split it and remove the line jumps, I get this list:</p> <p>It gives me a list that looks like this:</p> <pre><code>['&gt;A1', 'KKKKKKKK', 'DDDDDDDD', '&gt;A2', 'FFFFFFFF', 'FFFFOOOO', 'DAA', '&gt;A3', 'OOOZDDD', 'KKAZAAA', 'A'] </code></pre> <p>I'm trying to merge all the strings between each part that starts with '&gt;', such that it looks like:</p> <pre><code>['KKKKKKKKDDDDDDDD', 'FFFFFFFFFFFFOOOODAA', 'OOOZDDDKKAZAAAA'] </code></pre> <hr /> <p>What I have so far, but it doesn't do anything and I'm lost:</p> <pre><code>my_list = ['&gt;A1', 'KKKKKKKK', 'DDDDDDDD', '&gt;A2', 'FFFFFFFF', 'FFFFOOOO', 'DAA', '&gt;A3', 'OOOZDDD', 'KKAZAAA', 'A'] result = [] for item in range(len(my_list)): if my_list[item][0] == '&gt;': temp = '' while my_list[item] != '&gt;': temp += my_list[item] result.append(temp) print(result) </code></pre>
[ { "answer_id": 74497129, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 1, "selected": false, "text": "itertools.groupby from itertools import groupby\n\nlst = [\n \">A1\",\n \"KKKKKKKK\",\n \"DDDDDDDD\",\n \">A2\",\n \"FFFFFFFF\",\n \"FFFFOOOO\",\n \"DAA\",\n \">A3\",\n \"OOOZDDD\",\n \"KKAZAAA\",\n \"A\",\n]\n\nout = []\nfor k, g in groupby(lst, lambda s: s.startswith(\">\")):\n if not k:\n out.append(\"\".join(g))\n\nprint(out)\n [\"KKKKKKKKDDDDDDDD\", \"FFFFFFFFFFFFOOOODAA\", \"OOOZDDDKKAZAAAA\"]\n" }, { "answer_id": 74497490, "author": "ILS", "author_id": 10017662, "author_profile": "https://Stackoverflow.com/users/10017662", "pm_score": 2, "selected": true, "text": "while if my_list[item] '>' while else-statement temp result temp '>' result = []\nfor item in range(len(my_list)):\n if my_list[item][0] == '>':\n if item != 0:\n result.append(temp)\n temp = ''\n else:\n temp += my_list[item]\nif item != 0:\n result.append(item)\nprint(result)\n result = []\nconcat_string = '' # just change a readable name\nfor string in my_list + ['>']: # iterate over list directly and add a sentinel\n if string[0] == '>': # or string.startswith('>')\n if concat_string:\n result.append(concat_string)\n concat_string = ''\n else:\n concat_string += string\nprint(result)\n" }, { "answer_id": 74497854, "author": "JL Peyret", "author_id": 1394353, "author_profile": "https://Stackoverflow.com/users/1394353", "pm_score": 0, "selected": false, "text": "data = \"\"\">A1\nKKKKKKKK\nDDDDDDDD\n\n>A2\nFFFFFFFF\nFFFFOOOO\nDAA\n\n>A3\nOOOZDDD\nKKAZAAA\nA\"\"\"\n\nimport re\n\npatre = re.compile(\"^>.+\\n\",re.MULTILINE)\n#split on `>xxx`\nchunks = patre.split(data)\n#remove whitespaces and newlines\nblocks = [v.replace(\"\\n\",\"\").strip() for v in chunks]\n#get rid of leading trailing empty blocks\nblocks = [v for v in blocks if v]\n\nprint(blocks)\n\n ['KKKKKKKKDDDDDDDD', 'FFFFFFFFFFFFOOOODAA', 'OOOZDDDKKAZAAAA']\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4652872/" ]
74,497,115
<p>I am looking to understand why this code is giving me different results.</p> <p>I want to format <code>2022-10-12T00:00:00.000Z</code> into <code>yyyy-MM-dd</code> format.</p> <ul> <li>Result when I run it online in Java IDE: <code>2022-10-12</code></li> <li>But on my own computer the result is: <code>2022-10-11</code></li> </ul> <pre><code>String date = &quot;2022-10-12T00:00:00.000Z&quot;; SimpleDateFormat dateFormat = new SimpleDateFormat(&quot;yyyy-MM-dd&quot;); TemporalAccessor ta = DateTimeFormatter.ISO_INSTANT.parse(date); Instant i = Instant.from(ta); Date d = Date.from(i); dateFormat.format(d); </code></pre>
[ { "answer_id": 74497179, "author": "guoxinyu", "author_id": 19991084, "author_profile": "https://Stackoverflow.com/users/19991084", "pm_score": 0, "selected": false, "text": "Date SimpleDateFormat LocalDate.now()\nDateTimeFormatter.ofPattern(\"yyyy-MM-dd\").format(LocalDate.now())\n" }, { "answer_id": 74498851, "author": "Arvind Kumar Avinash", "author_id": 10819573, "author_profile": "https://Stackoverflow.com/users/10819573", "pm_score": 2, "selected": false, "text": "SimpleDateFormat SimpleDateFormat SimpleDateFormat SimpleDateFormat#setTimeZone(java.util.TimeZone) SimpleDateFormat dateFormat.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\n dateFormat.format(d);\n import java.time.OffsetDateTime;\nimport java.time.format.DateTimeFormatter;\n\npublic class Main {\n public static void main(String[] args) {\n String strDate = \"2022-10-12T00:00:00.000Z\";\n\n // Parse the given text into an OffsetDateTime and format it\n String desiredString = OffsetDateTime.parse(strDate)\n .format(DateTimeFormatter.ISO_LOCAL_DATE);\n\n System.out.println(desiredString);\n }\n}\n 2022-10-12\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4375671/" ]
74,497,132
<pre><code>weight = float(input(&quot;weight: &quot;)) unit = input(&quot;(K)g or (L)bs: &quot;) if unit.upper == &quot;K&quot;: converted = weight*2.2 print(&quot;Weight in Lbs: &quot; + str(converted)) else: converted = weight/2.2 print(&quot;Weight in kgs: &quot; + str(converted)) print(&quot;Conversion done&quot;) </code></pre> <p>result:</p> <blockquote> <p>weight: 15<br /> (K)g or (L)bs: k<br /> Weight in kgs: 6.8181818181818175<br /> Conversion done</p> </blockquote> <p>I am a beginner and trying to convert the weight but only else block is executing not the if block. Why?</p>
[ { "answer_id": 74497173, "author": "scotscotmcc", "author_id": 15804190, "author_profile": "https://Stackoverflow.com/users/15804190", "pm_score": -1, "selected": false, "text": "unit.upper() () str.upper if unit.upper == 'K' unit.upper" }, { "answer_id": 74497278, "author": "Kanu Jaswal", "author_id": 20544540, "author_profile": "https://Stackoverflow.com/users/20544540", "pm_score": 1, "selected": false, "text": "weight = float(input(\"Enter weight: \"))\nunit = input(\"Entered Value is (K)g or (L)bs: \")\n\nif unit.upper() == \"K\":\n converted = weight*2.2\n print(\"Weight in Lbs: \" + str(converted))\nelse:\n converted = weight/2.2\n print(\"Weight in kgs: \" + str(converted))\nprint(\"Conversion done\")\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20544446/" ]
74,497,143
<p>UPDATE: This has been solved. I created a &quot;calculated variable&quot; in tableau called [Lab Volume] and put this code into the calculation:</p> <pre><code>If [Average Results Per Day] &lt;= 25 THEN 'Low' ELSEIF [Average Results Per Day] &gt; 25 and [Average Results Per Day] &lt; 75 THEN 'Medium' ELSEIF [Average Results Per Day] &gt;= 75 THEN 'High' END </code></pre> <p>Thank you for your help!</p> <p>ORIGINAL POST: I am having trouble figuring out how to create new categories of data, sum these categories, and then find how many days since the lab last reported. Basically I have a list of unique [patientIDs], [Lab_Name], [result_reported_date], which I believe are the only variables I need for this project. SQL code will go into Tableau for data viz.</p> <p>Here is my dilemma:</p> <p>(1) I need to average the number of reported lab results for each laboratory [lab_names] and then categorize them into three volume categories (low volume labs, medium volume labs, high volume labs) based upon how many samples submitted each day in the last 30-day window: low is &lt;25 samples/day; medium is 25-50 samples/day; high is 75+ samples/day.</p> <p>Input looks something like this, with mulitple labs over multiple days with a sum of the number of samples submitted. The file has 750 different labs, with dates going back 30+ days, and a sum of the samples submitted on each day.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Lab_Name</th> <th>Date</th> <th>Samples_Submitted</th> </tr> </thead> <tbody> <tr> <td>LabA</td> <td>1/01/22</td> <td>80</td> </tr> <tr> <td>LabB</td> <td>1/01/22</td> <td>22</td> </tr> <tr> <td>LabA</td> <td>1/02/22</td> <td>101</td> </tr> <tr> <td>LabB</td> <td>1/01/22</td> <td>12</td> </tr> <tr> <td>LabA</td> <td>1/03/22</td> <td>95</td> </tr> <tr> <td>LabB</td> <td>1/03/22</td> <td>80</td> </tr> </tbody> </table> </div> <p>Output would be something like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Lab_Name</th> <th>Vol_category</th> <th>Average_sample_per30day</th> </tr> </thead> <tbody> <tr> <td>LabA</td> <td>low</td> <td>22</td> </tr> <tr> <td>LabB</td> <td>medium</td> <td>35</td> </tr> <tr> <td>LabC</td> <td>high</td> <td>85</td> </tr> <tr> <td>LabD</td> <td>low</td> <td>15</td> </tr> <tr> <td>LabE</td> <td>medium</td> <td>32</td> </tr> </tbody> </table> </div> <p>This is the code I have to count the number of samples submitted by Lab_Name. I don't know how to average the number of samples submitted over the last 30-days and then create low, medium, high categories.</p> <pre><code>select Lab_Name, count(Lab_Name) as Lab_count from dbo.Lab_tests where result_reported_date &gt; '2022-07-01' and Test_LOINC in ('41458-1', '94306-8', '94309-2', '94500-6', '94502-2', '94531-1', '94533-7', '94534-5', '94559-2', '94565-9', '94568-9', '94640-0', '94756-4', '94757-2', '94759-8', '94760-6', '94845-5', '95406-5', '95409-9', '95423-0', '95425-5', '95608-6', '96094-8', '96123-5', '96448-6', '96986-5', '99999-9', '94558-4', '95209-3', '96119-3', '97097-0') group by Lab_Name order by Lab_count desc ; </code></pre>
[ { "answer_id": 74497173, "author": "scotscotmcc", "author_id": 15804190, "author_profile": "https://Stackoverflow.com/users/15804190", "pm_score": -1, "selected": false, "text": "unit.upper() () str.upper if unit.upper == 'K' unit.upper" }, { "answer_id": 74497278, "author": "Kanu Jaswal", "author_id": 20544540, "author_profile": "https://Stackoverflow.com/users/20544540", "pm_score": 1, "selected": false, "text": "weight = float(input(\"Enter weight: \"))\nunit = input(\"Entered Value is (K)g or (L)bs: \")\n\nif unit.upper() == \"K\":\n converted = weight*2.2\n print(\"Weight in Lbs: \" + str(converted))\nelse:\n converted = weight/2.2\n print(\"Weight in kgs: \" + str(converted))\nprint(\"Conversion done\")\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20161227/" ]
74,497,144
<p>So I have a navigation bar menu in my html which has a hover effect to the links. When I am setting the margin property to auto, the hover effect moves from the center to the edges of the links.</p> <pre><code>.nav-links ul li::after { content: ''; background-color: #f44336; display: block; width: 0%; height: 2px; margin: auto; transition: 0.8s; } .nav-links ul li:hover::after { width: 100%; } </code></pre> <p>However, when I am settings margin value to any other value, e.g, 5px, the hover effect moves from left to right. What is the reason behind this ?</p> <p>I am just beginner in front-end development, so I don't have much knowledge of CSS.</p>
[ { "answer_id": 74497198, "author": "Ethan", "author_id": 17493431, "author_profile": "https://Stackoverflow.com/users/17493431", "pm_score": 0, "selected": false, "text": "auto" }, { "answer_id": 74497409, "author": "Alohci", "author_id": 42585, "author_profile": "https://Stackoverflow.com/users/42585", "pm_score": 1, "selected": false, "text": "margin:auto ul {\n list-style: none;\n}\n\n.nav-links ul li::after {\n content: '';\n background-color: #f44336;\n display: block;\n width: 0%;\n height: 2px;\n margin: auto;\n transition: 0.8s;\n}\n\n.nav-links ul li:hover::after {\n width: 100%;\n} <nav class=\"nav-links\">\n <ul>\n <li>Home</li>\n <li>Pictures of Kittens</li>\n <li>Contact</li>\n </ul>\n</nav> ul {\n list-style: none;\n}\n\n.nav-links ul li::after {\n content: '';\n background-color: #f44336;\n display: block;\n width: 0%;\n height: 2px;\n margin: 5px;\n transition: 0.8s;\n}\n\n.nav-links ul li:hover::after {\n width: 100%;\n} <nav class=\"nav-links\">\n <ul>\n <li>Home</li>\n <li>Pictures of Kittens</li>\n <li>Contact</li>\n </ul>\n</nav> 100% - (5px + 0%) 100% - (5px + 100%) li {\n direction: rtl;\n}\n\nul {\n list-style: none;\n}\n\n.nav-links ul li::after {\n content: '';\n background-color: #f44336;\n display: block;\n width: 0%;\n height: 2px;\n margin: 5px;\n transition: 0.8s;\n}\n\n.nav-links ul li:hover::after {\n width: 100%;\n} <nav class=\"nav-links\">\n <ul>\n <li>Home</li>\n <li>Pictures of Kittens</li>\n <li>Contact</li>\n </ul>\n</nav> " } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19163367/" ]
74,497,187
<p>When writing C code, I might want to define a constant array in a header file so that it may be used in multiple <code>.c</code> files.</p> <p>Take the following example:</p> <p><strong>main.c</strong></p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include &quot;main.h&quot; int main() { int localmat[9]; for (int i = 0; i &lt; 9; i++) { localmat[i] = HEADERMAT[i]; } matadd(localmat, HEADERMAT); return 0; } </code></pre> <p><strong>main.h</strong></p> <pre class="lang-c prettyprint-override"><code>#ifndef _MAIN_H_ #define _MAIN_H_ // Constant array const int HEADERMAT[9] = {0,1,2,3,4,5,6,7,8}; // prototype function: void matadd(int matA[9], const int matB[9]); #endif </code></pre> <p><strong>functions.c</strong></p> <pre class="lang-c prettyprint-override"><code>#include &quot;main.h&quot; void matadd(int matA[9], const int matB[9]){ for (int i = 0; i &lt; 9; i++) { matA[i] += matB[i]; } } </code></pre> <p>The constant array <code>HEADERMAT</code> declared in <code>main.h</code> is used in both <code>main.c</code> and <code>functions.h</code>. The header does use ifndef to prevent redefinitions and yet, the compiler will still complain about it being defined multiple times:</p> <pre><code>/usr/bin/ld: /tmp/ccVWhI0u.o:(.rodata+0x0): multiple definition of `HEADERMAT'; /tmp/ccRAIQ5u.o:(.rodata+0x0): first defined here collect2: error: ld returned 1 exit status </code></pre> <p>What would be the better way of making this array accessible to both C files?</p>
[ { "answer_id": 74497198, "author": "Ethan", "author_id": 17493431, "author_profile": "https://Stackoverflow.com/users/17493431", "pm_score": 0, "selected": false, "text": "auto" }, { "answer_id": 74497409, "author": "Alohci", "author_id": 42585, "author_profile": "https://Stackoverflow.com/users/42585", "pm_score": 1, "selected": false, "text": "margin:auto ul {\n list-style: none;\n}\n\n.nav-links ul li::after {\n content: '';\n background-color: #f44336;\n display: block;\n width: 0%;\n height: 2px;\n margin: auto;\n transition: 0.8s;\n}\n\n.nav-links ul li:hover::after {\n width: 100%;\n} <nav class=\"nav-links\">\n <ul>\n <li>Home</li>\n <li>Pictures of Kittens</li>\n <li>Contact</li>\n </ul>\n</nav> ul {\n list-style: none;\n}\n\n.nav-links ul li::after {\n content: '';\n background-color: #f44336;\n display: block;\n width: 0%;\n height: 2px;\n margin: 5px;\n transition: 0.8s;\n}\n\n.nav-links ul li:hover::after {\n width: 100%;\n} <nav class=\"nav-links\">\n <ul>\n <li>Home</li>\n <li>Pictures of Kittens</li>\n <li>Contact</li>\n </ul>\n</nav> 100% - (5px + 0%) 100% - (5px + 100%) li {\n direction: rtl;\n}\n\nul {\n list-style: none;\n}\n\n.nav-links ul li::after {\n content: '';\n background-color: #f44336;\n display: block;\n width: 0%;\n height: 2px;\n margin: 5px;\n transition: 0.8s;\n}\n\n.nav-links ul li:hover::after {\n width: 100%;\n} <nav class=\"nav-links\">\n <ul>\n <li>Home</li>\n <li>Pictures of Kittens</li>\n <li>Contact</li>\n </ul>\n</nav> " } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2325057/" ]
74,497,208
<pre><code>class Student: def __init__(self, name, major, gpa, onProbation): self.name = name self.major = major self.gpa = gpa self.onProbation = onProbation Student1 = Student(&quot;Josh&quot;, &quot;Business&quot;, 3.8, False) Student2 = Student(&quot;Maya&quot;, &quot;Accountancy&quot;, 2.5, True) Student3 = Student(&quot;Dan&quot;, &quot;Psychology&quot;, 1.2, True) Student4 = Student(&quot;Keon&quot;, &quot;Biomedical Engineering&quot;, 4.0, False) Student5 = Student(&quot;Michelle&quot;, &quot;Medicine&quot;, 3.7, False) Student6 = Student(&quot;Joey&quot;, &quot;Law&quot;, 4.0, False) Students = [&quot;Josh&quot;, &quot;Maya&quot;, &quot;Dan&quot;, &quot;Keon&quot;, &quot;Michelle&quot;, &quot;Joey&quot;] </code></pre> <p>I want to figure out how to remove all the students who are on probation from the list, so if I were to type print(Students) it would only give me the students that are not on probation (Josh, Keon, Michelle, and Joey)</p>
[ { "answer_id": 74497230, "author": "TheCableGUI", "author_id": 16614773, "author_profile": "https://Stackoverflow.com/users/16614773", "pm_score": -1, "selected": false, "text": "\nclass Student:\n\n def __init__(self, name: str, major: str, gpa:float, onProbation: bool):\n self.name = name\n self.major = major\n self.gpa = gpa\n self.onProbation = onProbation\n\n# in your example you placed the class instances in the class, \n# notice how mine are placed outside. The __init__ method initializes\n# the object, having it within the object is infinitly recursive i believe\n\nstudent1 = Student(\"Josh\", \"Business\", 3.8, False)\nstudent2 = Student(\"Maya\", \"Accountancy\", 2.5, True)\nstudent3 = Student(\"Dan\", \"Psychology\", 1.2, True)\nstudent4 = Student(\"Keon\", \"Biomedical Engineering\", 4.0, False)\nstudent5 = Student(\"Michelle\", \"Medicine\", 3.7, False)\nstudent6 = Student(\"Joey\", \"Law\", 4.0, False)\n\nstudents = [student1,student2,student3,student4,student5, student6]\n\nmylist = students\nfor index, student in enumerate(students):\n if student.onProbation: # if the boolean isnt specified, defaults to true as is\n mylist.remove(students[index])\n\n class Student:\n\n def __init__(self, name: str, major: str, gpa:float, onProbation: bool):\n self.name = name\n self.major = major\n self.gpa = gpa\n self.onProbation = onProbation\n\n\n\nstudent1 = Student(\"Josh\", \"Business\", 3.8, False)\nstudent2 = Student(\"Maya\", \"Accountancy\", 2.5, True)\nstudent3 = Student(\"Dan\", \"Psychology\", 1.2, True)\nstudent4 = Student(\"Keon\", \"Biomedical Engineering\", 4.0, False)\nstudent5 = Student(\"Michelle\", \"Medicine\", 3.7, False)\nstudent6 = Student(\"Joey\", \"Law\", 4.0, False)\n\nstudents = [student1,student2,student3,student4,student5, student6]\n\ngood_students = [x for x in students if not student.onProbation]\n\n" }, { "answer_id": 74497260, "author": "Pickles6855", "author_id": 20200812, "author_profile": "https://Stackoverflow.com/users/20200812", "pm_score": 1, "selected": true, "text": "class Student:\n\n def __init__(self, name, major, gpa, onProbation):\n self.name = name\n self.major = major\n self.gpa = gpa\n self.onProbation = onProbation\n\nstudents = [\n Student(\"Josh\", \"Business\", 3.8, False),\n Student(\"Maya\", \"Accountancy\", 2.5, True),\n Student(\"Dan\", \"Psychology\", 1.2, True),\n Student(\"Keon\", \"Biomedical Engineering\", 4.0, False),\n Student(\"Michelle\", \"Medicine\", 3.7, False),\n Student(\"Joey\", \"Law\", 4.0, False)\n]\n\n# I created a list for new students because it will mess up the for loop if you remove objects from a list while iterating\nnew_students = []\nfor student in students:\n if student.onProbation == False:\n new_students.append(student)\n\n# print(students) will return an unreadable list with encoded numbers and such so I did this instead\nfor student in new_students:\n print(student.name, student.onProbation)\n" }, { "answer_id": 74497264, "author": "Lakshya", "author_id": 8214832, "author_profile": "https://Stackoverflow.com/users/8214832", "pm_score": 0, "selected": false, "text": "class Student:\n\n def __init__(self, name, major, gpa, onProbation):\n self.name = name\n self.major = major\n self.gpa = gpa\n self.onProbation = onProbation\n\n @staticmethod\n def getStudentsNotOnProbation(students):\n res = []\n for student in students:\n if not student.onProbation:\n res.append(student)\n return res\n\nStudent1 = Student(\"Josh\", \"Business\", 3.8, False)\nStudent2 = Student(\"Maya\", \"Accountancy\", 2.5, True)\nStudent3 = Student(\"Dan\", \"Psychology\", 1.2, True)\nStudent4 = Student(\"Keon\", \"Biomedical Engineering\", 4.0, False)\nStudent5 = Student(\"Michelle\", \"Medicine\", 3.7, False)\nStudent6 = Student(\"Joey\", \"Law\", 4.0, False)\n\nStudents = [Student1, Student2, Student3, Student4, Student5, Student6]\n\n\nprint(Student.getStudentsNotOnProbation(Students))\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20544301/" ]
74,497,224
<p>I am using Astradb and want to know specific information about my database and I am unable to write a nodetool status query in astradb</p> <p>I tried running noodtool status query in CQL of astraDB but it is showing &quot;no viable alternative at input 'nodetool' ([nodetool]...)&quot;.</p>
[ { "answer_id": 74497230, "author": "TheCableGUI", "author_id": 16614773, "author_profile": "https://Stackoverflow.com/users/16614773", "pm_score": -1, "selected": false, "text": "\nclass Student:\n\n def __init__(self, name: str, major: str, gpa:float, onProbation: bool):\n self.name = name\n self.major = major\n self.gpa = gpa\n self.onProbation = onProbation\n\n# in your example you placed the class instances in the class, \n# notice how mine are placed outside. The __init__ method initializes\n# the object, having it within the object is infinitly recursive i believe\n\nstudent1 = Student(\"Josh\", \"Business\", 3.8, False)\nstudent2 = Student(\"Maya\", \"Accountancy\", 2.5, True)\nstudent3 = Student(\"Dan\", \"Psychology\", 1.2, True)\nstudent4 = Student(\"Keon\", \"Biomedical Engineering\", 4.0, False)\nstudent5 = Student(\"Michelle\", \"Medicine\", 3.7, False)\nstudent6 = Student(\"Joey\", \"Law\", 4.0, False)\n\nstudents = [student1,student2,student3,student4,student5, student6]\n\nmylist = students\nfor index, student in enumerate(students):\n if student.onProbation: # if the boolean isnt specified, defaults to true as is\n mylist.remove(students[index])\n\n class Student:\n\n def __init__(self, name: str, major: str, gpa:float, onProbation: bool):\n self.name = name\n self.major = major\n self.gpa = gpa\n self.onProbation = onProbation\n\n\n\nstudent1 = Student(\"Josh\", \"Business\", 3.8, False)\nstudent2 = Student(\"Maya\", \"Accountancy\", 2.5, True)\nstudent3 = Student(\"Dan\", \"Psychology\", 1.2, True)\nstudent4 = Student(\"Keon\", \"Biomedical Engineering\", 4.0, False)\nstudent5 = Student(\"Michelle\", \"Medicine\", 3.7, False)\nstudent6 = Student(\"Joey\", \"Law\", 4.0, False)\n\nstudents = [student1,student2,student3,student4,student5, student6]\n\ngood_students = [x for x in students if not student.onProbation]\n\n" }, { "answer_id": 74497260, "author": "Pickles6855", "author_id": 20200812, "author_profile": "https://Stackoverflow.com/users/20200812", "pm_score": 1, "selected": true, "text": "class Student:\n\n def __init__(self, name, major, gpa, onProbation):\n self.name = name\n self.major = major\n self.gpa = gpa\n self.onProbation = onProbation\n\nstudents = [\n Student(\"Josh\", \"Business\", 3.8, False),\n Student(\"Maya\", \"Accountancy\", 2.5, True),\n Student(\"Dan\", \"Psychology\", 1.2, True),\n Student(\"Keon\", \"Biomedical Engineering\", 4.0, False),\n Student(\"Michelle\", \"Medicine\", 3.7, False),\n Student(\"Joey\", \"Law\", 4.0, False)\n]\n\n# I created a list for new students because it will mess up the for loop if you remove objects from a list while iterating\nnew_students = []\nfor student in students:\n if student.onProbation == False:\n new_students.append(student)\n\n# print(students) will return an unreadable list with encoded numbers and such so I did this instead\nfor student in new_students:\n print(student.name, student.onProbation)\n" }, { "answer_id": 74497264, "author": "Lakshya", "author_id": 8214832, "author_profile": "https://Stackoverflow.com/users/8214832", "pm_score": 0, "selected": false, "text": "class Student:\n\n def __init__(self, name, major, gpa, onProbation):\n self.name = name\n self.major = major\n self.gpa = gpa\n self.onProbation = onProbation\n\n @staticmethod\n def getStudentsNotOnProbation(students):\n res = []\n for student in students:\n if not student.onProbation:\n res.append(student)\n return res\n\nStudent1 = Student(\"Josh\", \"Business\", 3.8, False)\nStudent2 = Student(\"Maya\", \"Accountancy\", 2.5, True)\nStudent3 = Student(\"Dan\", \"Psychology\", 1.2, True)\nStudent4 = Student(\"Keon\", \"Biomedical Engineering\", 4.0, False)\nStudent5 = Student(\"Michelle\", \"Medicine\", 3.7, False)\nStudent6 = Student(\"Joey\", \"Law\", 4.0, False)\n\nStudents = [Student1, Student2, Student3, Student4, Student5, Student6]\n\n\nprint(Student.getStudentsNotOnProbation(Students))\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13438500/" ]
74,497,235
<p>I started programming not long ago and came across this problem. I want to collect stock data from the website: <a href="https://statusinvest.com.br/acoes/petr4" rel="nofollow noreferrer">https://statusinvest.com.br/acoes/petr4</a>. But apparently they are rendered with javascript and BeautifulSoup does not collect, if you can help I appreciate it</p> <p><a href="https://i.stack.imgur.com/KhxG9.png" rel="nofollow noreferrer">My soup code</a> <a href="https://i.stack.imgur.com/5lIeP.png" rel="nofollow noreferrer">Example of information loaded with javascript</a></p>
[ { "answer_id": 74497230, "author": "TheCableGUI", "author_id": 16614773, "author_profile": "https://Stackoverflow.com/users/16614773", "pm_score": -1, "selected": false, "text": "\nclass Student:\n\n def __init__(self, name: str, major: str, gpa:float, onProbation: bool):\n self.name = name\n self.major = major\n self.gpa = gpa\n self.onProbation = onProbation\n\n# in your example you placed the class instances in the class, \n# notice how mine are placed outside. The __init__ method initializes\n# the object, having it within the object is infinitly recursive i believe\n\nstudent1 = Student(\"Josh\", \"Business\", 3.8, False)\nstudent2 = Student(\"Maya\", \"Accountancy\", 2.5, True)\nstudent3 = Student(\"Dan\", \"Psychology\", 1.2, True)\nstudent4 = Student(\"Keon\", \"Biomedical Engineering\", 4.0, False)\nstudent5 = Student(\"Michelle\", \"Medicine\", 3.7, False)\nstudent6 = Student(\"Joey\", \"Law\", 4.0, False)\n\nstudents = [student1,student2,student3,student4,student5, student6]\n\nmylist = students\nfor index, student in enumerate(students):\n if student.onProbation: # if the boolean isnt specified, defaults to true as is\n mylist.remove(students[index])\n\n class Student:\n\n def __init__(self, name: str, major: str, gpa:float, onProbation: bool):\n self.name = name\n self.major = major\n self.gpa = gpa\n self.onProbation = onProbation\n\n\n\nstudent1 = Student(\"Josh\", \"Business\", 3.8, False)\nstudent2 = Student(\"Maya\", \"Accountancy\", 2.5, True)\nstudent3 = Student(\"Dan\", \"Psychology\", 1.2, True)\nstudent4 = Student(\"Keon\", \"Biomedical Engineering\", 4.0, False)\nstudent5 = Student(\"Michelle\", \"Medicine\", 3.7, False)\nstudent6 = Student(\"Joey\", \"Law\", 4.0, False)\n\nstudents = [student1,student2,student3,student4,student5, student6]\n\ngood_students = [x for x in students if not student.onProbation]\n\n" }, { "answer_id": 74497260, "author": "Pickles6855", "author_id": 20200812, "author_profile": "https://Stackoverflow.com/users/20200812", "pm_score": 1, "selected": true, "text": "class Student:\n\n def __init__(self, name, major, gpa, onProbation):\n self.name = name\n self.major = major\n self.gpa = gpa\n self.onProbation = onProbation\n\nstudents = [\n Student(\"Josh\", \"Business\", 3.8, False),\n Student(\"Maya\", \"Accountancy\", 2.5, True),\n Student(\"Dan\", \"Psychology\", 1.2, True),\n Student(\"Keon\", \"Biomedical Engineering\", 4.0, False),\n Student(\"Michelle\", \"Medicine\", 3.7, False),\n Student(\"Joey\", \"Law\", 4.0, False)\n]\n\n# I created a list for new students because it will mess up the for loop if you remove objects from a list while iterating\nnew_students = []\nfor student in students:\n if student.onProbation == False:\n new_students.append(student)\n\n# print(students) will return an unreadable list with encoded numbers and such so I did this instead\nfor student in new_students:\n print(student.name, student.onProbation)\n" }, { "answer_id": 74497264, "author": "Lakshya", "author_id": 8214832, "author_profile": "https://Stackoverflow.com/users/8214832", "pm_score": 0, "selected": false, "text": "class Student:\n\n def __init__(self, name, major, gpa, onProbation):\n self.name = name\n self.major = major\n self.gpa = gpa\n self.onProbation = onProbation\n\n @staticmethod\n def getStudentsNotOnProbation(students):\n res = []\n for student in students:\n if not student.onProbation:\n res.append(student)\n return res\n\nStudent1 = Student(\"Josh\", \"Business\", 3.8, False)\nStudent2 = Student(\"Maya\", \"Accountancy\", 2.5, True)\nStudent3 = Student(\"Dan\", \"Psychology\", 1.2, True)\nStudent4 = Student(\"Keon\", \"Biomedical Engineering\", 4.0, False)\nStudent5 = Student(\"Michelle\", \"Medicine\", 3.7, False)\nStudent6 = Student(\"Joey\", \"Law\", 4.0, False)\n\nStudents = [Student1, Student2, Student3, Student4, Student5, Student6]\n\n\nprint(Student.getStudentsNotOnProbation(Students))\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19396132/" ]
74,497,293
<p>We can use Arrays.asList( ) method for String[ ] and Integer[ ] arrays. Can we use the char[ ] array in Arrays.asList( ) method?</p> <pre><code>Arrays.asList(75,85,95,70); Arrays.asList(&quot;String&quot;, &quot;Integer&quot;, &quot;Character&quot;); </code></pre>
[ { "answer_id": 74497407, "author": "DevAra", "author_id": 4122324, "author_profile": "https://Stackoverflow.com/users/4122324", "pm_score": 0, "selected": false, "text": "import java.util.stream.Collectors;\nimport java.util.List;\nchar[] chars = {'c','d','e', 'f','g'};\n List<Character> cahrList = String.valueOf(chars).chars().mapToObj(c -> (char) c).collect(Collectors.toList());\n" }, { "answer_id": 74497574, "author": "Mustafa Poya", "author_id": 5515287, "author_profile": "https://Stackoverflow.com/users/5515287", "pm_score": 0, "selected": false, "text": "Character import java.util.Arrays;\nimport java.util.List;\n\npublic class TestCode {\n public static void main(String[] args) {\n List<Character> charList = Arrays.asList('c','d','e', 'f','g');\n System.out.println(charList);\n }\n}\n\n" }, { "answer_id": 74498528, "author": "Stephen C", "author_id": 139985, "author_profile": "https://Stackoverflow.com/users/139985", "pm_score": 1, "selected": false, "text": "Arrays.asList(75,85,95,70);\n 75,85,95,70 Integer[] int[] int int Integer Integer[] Integer[] asList Integer T Arrays.asList() char[] List<Character> charList = Arrays.asList('a', 'b', 'c');\n int List<Character> List<char> char[] test = char[]{'a', 'b', 'c'};\n Arrays.asList(test);\n List<char[]> char[] char asList List<Character>" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19670437/" ]
74,497,309
<p>I'm trying to write a spring endpoint that generates different reports, depending on the request parameters</p> <pre><code>@GetMapping @ResponseBody public ResponseEntity&lt;String&gt; getReport( @RequestParam(value = &quot;category&quot;) String category, @Valid ReportRequestDTO reportRequestDTO) { Optional&lt;ReportCategory&gt; reportCategory = ReportCategory.getReportCategoryByRequest(category); if (reportCategory.isEmpty()) { throw new ApiRequestException(&quot;Requested report category does not exist.&quot;); } try { Report report = reportFactory.getReport(reportCategory.get()); return ResponseEntity.ok().body(report.generate(reportRequestDTO)); } catch (Exception e) { throw new ApiRequestException(&quot;Could not generate report.&quot;, HttpStatus.INTERNAL_SERVER_ERROR); } } </code></pre> <p>The ReportCategory is an enum and Report is an abstract class of which multiple concrete implementations exist. Depending on the passed category the ReportFactory will instantiate the right Report. ReportRequestDTO is a class that contains all parameters that are required to generate the report. If this is passed to the generate() method, the report is generated.</p> <p>Depending on the ReportCategory, different parameters may be required and need to be validated, but there can also be some common ones.</p> <p>Is it possible to have an abstract class ReportRequestDTO with the common parameters and then a concrete DTO implementation for each report with its unique parameters, that is instantiated and validated depending on the report category before it is passed to the generate() method?</p> <p><strong>Edit:</strong></p> <p>I want something like this for shared parameters:</p> <pre><code>@Data public abstract class ReportRequestDTO { @NotEmpty private String foo; @NotEmpty private String bar; } </code></pre> <p>And then for each Report the individual parameters:</p> <pre><code>@Data public class ReportADTO extends ReportRequestDTO { @NotEmpty private String foobar; } </code></pre> <p>But I can't use and abstract class as DTO, because it can't be instantiated. Also this would try to validate <code>foobar</code> even if I don't need it in ReportB.</p> <p>Basically I want this endpoint to be able to generate all reports. Since I don't know yet which reports exist and may be added in the future and which parameters they require, I'd like to have the DTO extendable so that I don't have to touch the endpoint anymore and simply implement the report and create a DTO that extends ReportRequestDTO with the required parameters for that report.</p> <p>So what I need is an Object that I can use as ReportRequestDTO that is extendable with all parameters for all reports so that I can pass them on the request, and then I would instantiate the DTO for the particular report with the request parameters and validate it.</p>
[ { "answer_id": 74497407, "author": "DevAra", "author_id": 4122324, "author_profile": "https://Stackoverflow.com/users/4122324", "pm_score": 0, "selected": false, "text": "import java.util.stream.Collectors;\nimport java.util.List;\nchar[] chars = {'c','d','e', 'f','g'};\n List<Character> cahrList = String.valueOf(chars).chars().mapToObj(c -> (char) c).collect(Collectors.toList());\n" }, { "answer_id": 74497574, "author": "Mustafa Poya", "author_id": 5515287, "author_profile": "https://Stackoverflow.com/users/5515287", "pm_score": 0, "selected": false, "text": "Character import java.util.Arrays;\nimport java.util.List;\n\npublic class TestCode {\n public static void main(String[] args) {\n List<Character> charList = Arrays.asList('c','d','e', 'f','g');\n System.out.println(charList);\n }\n}\n\n" }, { "answer_id": 74498528, "author": "Stephen C", "author_id": 139985, "author_profile": "https://Stackoverflow.com/users/139985", "pm_score": 1, "selected": false, "text": "Arrays.asList(75,85,95,70);\n 75,85,95,70 Integer[] int[] int int Integer Integer[] Integer[] asList Integer T Arrays.asList() char[] List<Character> charList = Arrays.asList('a', 'b', 'c');\n int List<Character> List<char> char[] test = char[]{'a', 'b', 'c'};\n Arrays.asList(test);\n List<char[]> char[] char asList List<Character>" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11488995/" ]
74,497,345
<p>So here is the start of my program. I keep getting the error boolExpr.y:13:2: error: unknown type name 'bool' bool boolean; However when I check the bison generated file, I can see stdbool.h is included at the start of the program executing. I can't figure out how a library can be important but then bool not be recognized. I'm thinking I missed something simple, or I need to reinstall bison or lex. I can include the rest of the program if needed.</p> <p>I tried to switch it to int boolean; instead of bool boolean; and that fixed the compilation problem, however it still mystifies me. Is there some way to extend a pointer to a struct into %union without getting compile errors? I tried to make a structName * boolean; to replace bool boolean but that kept coming back as undefined wimplicit error as well.</p> <pre><code>%{ #include &quot;semantics.h&quot; #include &lt;stdbool.h&gt; #include &quot;IOMngr.h&quot; #include &lt;string.h&gt; extern int yylex(); /* The next token function. */ extern char *yytext; /* The matched token text. */ extern int yyerror(char *s); extern SymTab *table; extern SymEntry *entry; %} %union{ bool boolean;(this is the line # of error) char * string; } %type &lt;string&gt; Id %type &lt;boolean&gt; Expr %type &lt;boolean&gt; Term %type &lt;boolean&gt; Factor %token Ident %token TRUE %token FALSE %token OR %token AND %% Prog : StmtSeq {printSymTab();}; StmtSeq : Stmt StmtSeq { }; StmtSeq : { }; Stmt : Id '=' Expr ';' {storeVar($1, $3);}; Expr : Expr OR Term {$$ = doOR($1, $3);}; Expr : Term {$$ = $1;}; Term : Term AND Factor {$$ = doAND($1, $3);}; Term : Factor {$$ = $1;}; Factor : '!' Factor {$$ = doNOT($2);}; Factor : '(' Expr ')' {$$ = $2;}; Factor : Id {$$ = getVal($1);}; Factor : TRUE {$$ = true;}; Factor : FALSE {$$ = false;}; Id : Ident {$$ = strdup(yytext);}; %% int yyerror(char *s) { WriteIndicator(getCurrentColumnNum()); WriteMessage(&quot;Illegal Character in YACC&quot;); return 1; } </code></pre>
[ { "answer_id": 74497407, "author": "DevAra", "author_id": 4122324, "author_profile": "https://Stackoverflow.com/users/4122324", "pm_score": 0, "selected": false, "text": "import java.util.stream.Collectors;\nimport java.util.List;\nchar[] chars = {'c','d','e', 'f','g'};\n List<Character> cahrList = String.valueOf(chars).chars().mapToObj(c -> (char) c).collect(Collectors.toList());\n" }, { "answer_id": 74497574, "author": "Mustafa Poya", "author_id": 5515287, "author_profile": "https://Stackoverflow.com/users/5515287", "pm_score": 0, "selected": false, "text": "Character import java.util.Arrays;\nimport java.util.List;\n\npublic class TestCode {\n public static void main(String[] args) {\n List<Character> charList = Arrays.asList('c','d','e', 'f','g');\n System.out.println(charList);\n }\n}\n\n" }, { "answer_id": 74498528, "author": "Stephen C", "author_id": 139985, "author_profile": "https://Stackoverflow.com/users/139985", "pm_score": 1, "selected": false, "text": "Arrays.asList(75,85,95,70);\n 75,85,95,70 Integer[] int[] int int Integer Integer[] Integer[] asList Integer T Arrays.asList() char[] List<Character> charList = Arrays.asList('a', 'b', 'c');\n int List<Character> List<char> char[] test = char[]{'a', 'b', 'c'};\n Arrays.asList(test);\n List<char[]> char[] char asList List<Character>" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15575145/" ]
74,497,365
<p>I want to use Dymos to solve the optimal control problem:</p> <p><a href="https://i.stack.imgur.com/vP19g.png" rel="nofollow noreferrer">enter image description here</a></p> <p>subject to the dynamic system:</p> <p><a href="https://i.stack.imgur.com/c4s87.png" rel="nofollow noreferrer">enter image description here</a></p> <p>I have two questions:</p> <p>(1) How to set the object function (<code>object1</code>) of V(X(T)), where the value of state variables at final time point are the inputs of the function V.</p> <p>I think the setting</p> <pre><code>phase.add_objective('V(X)', loc='final', scale=1) </code></pre> <p>will minimize the integral from t=0 to t=T of a variable whose rate is V(X), is that right?</p> <p>(2) I think I can setup an output <code>objectval2</code> with time change rate L(X, u) then set</p> <pre><code>phase.add_objective('objectval2', loc='final', scale=1) </code></pre> <p>then how do I let the optimizer know that I want to minimize the sum of objectval1 + objectval2, instead of objectval1*objectval2 or any other function of objectval1 and objectval2.</p> <p>I read the tutorial and I didn't find an example similar to my case.</p> <p>#################</p> <p>Comments: Thanks. I cannot add the following clarifying questions at the comments to the answer, it said these are too long. So I added them here.</p> <p>I thinks the key code here is:</p> <pre><code>p.model.add_subsystem('other_calcs', om.ExecComp(&quot;f=a+b&quot;)) p.model.connect('traj.phase0.timeseries.states:v', 'other_calcs.a', src_indices=[-1]) p.model.connect('traj.pahse0.timeseries.states:v', 'other_calcs.b', src_indices=[0]) </code></pre> <p>I saw this in the tutorial and I have 3 questions:</p> <p>(1) For the keyword input <code>src_indices</code>, I think <code>src_indices=[-1]</code> passes the last value of <code>v</code>(<code>v[-1]</code>) to <code>a</code> and <code>src_indices=[0]</code> passes the first value of <code>v</code>(<code>v[0]</code>) to <code>b</code>. I think the time point at <code>v[-1]</code> depends on the number of nodes, which decided by parameter <code>num_segments</code> and <code>order</code>. So does transcription function always set the last node position to the last time point? For example, if I solve a control problem from <code>t=0</code> to <code>t=2000</code>, no matter how I set the <code>num_segments</code> and <code>order</code>, e.g. <code>num_segments=2</code> and <code>order=3</code> or <code>num_segments=20</code> and <code>order=5</code>, <code>v[-1]</code> will always be the value of <code>v</code> at <code>t=2000</code> and <code>v[0]</code> will always be the value of <code>v</code> at <code>t=0</code>?</p> <p>(2) Can I add one or more specific time points to the nodes? For example, if I solve a control problem from t=0 to t=2000, I want to minimize the sum of the value of <code>v</code> at <code>t=500</code>, <code>t=1000</code> and <code>t=2000</code>, can I required the nodes must includes the time points at <code>t=500</code>, <code>t=1000</code> and <code>t=2000</code>, no matter how I set the <code>num_segments</code> and <code>order</code>?</p> <p>(3) Last question is about the objective function setting I asked first time. In the example, you commented out <code># phase.add_objective('time', loc='final')</code>. What will the optimizer do if I set the code:</p> <pre><code>phase.add_objective('x', loc='final') p.model.add_objective('other_calcs.f') </code></pre> <p>Does the optimizer minimizes the sum of <code>x</code> integral from <code>t=0</code> to <code>t=T</code> and <code>v(T)</code>? If not, how can I set the optimizer to minimizes the sum of <code>x</code> integral from <code>t=0</code> to <code>t=T</code> and <code>v(T)</code>?</p>
[ { "answer_id": 74500395, "author": "Justin Gray", "author_id": 2301186, "author_profile": "https://Stackoverflow.com/users/2301186", "pm_score": 2, "selected": false, "text": "traj traj traj ExecComp timeseries import numpy as np\nimport openmdao.api as om\nimport dymos as dm\nimport matplotlib.pyplot as plt\n\n# First define a system which computes the equations of motion\nclass BrachistochroneEOM(om.ExplicitComponent):\n def initialize(self):\n self.options.declare('num_nodes', types=int)\n\n def setup(self):\n nn = self.options['num_nodes']\n\n # Inputs\n self.add_input('v', val=np.zeros(nn), units='m/s', desc='velocity')\n self.add_input('theta', val=np.zeros(nn), units='rad', desc='angle of wire')\n self.add_output('xdot', val=np.zeros(nn), units='m/s', desc='x rate of change')\n self.add_output('ydot', val=np.zeros(nn), units='m/s', desc='y rate of change')\n self.add_output('vdot', val=np.zeros(nn), units='m/s**2', desc='v rate of change')\n\n # Ask OpenMDAO to compute the partial derivatives using complex-step\n # with a partial coloring algorithm for improved performance\n self.declare_partials(of='*', wrt='*', method='cs')\n self.declare_coloring(wrt='*', method='cs', show_summary=True)\n\n def compute(self, inputs, outputs):\n v, theta = inputs.values()\n outputs['vdot'] = 9.80665 * np.cos(theta)\n outputs['xdot'] = v * np.sin(theta)\n outputs['ydot'] = -v * np.cos(theta)\n\np = om.Problem()\n\n# Define a Trajectory object\ntraj = p.model.add_subsystem('traj', dm.Trajectory())\n\n# Define a Dymos Phase object with GaussLobatto Transcription\ntx = dm.GaussLobatto(num_segments=10, order=3)\nphase = dm.Phase(ode_class=BrachistochroneEOM, transcription=tx)\n\ntraj.add_phase(name='phase0', phase=phase)\n\n# Set the time options\nphase.set_time_options(fix_initial=True,\n duration_bounds=(0.5, 10.0))\n# Set the state options\nphase.add_state('x', rate_source='xdot',\n fix_initial=True, fix_final=True)\nphase.add_state('y', rate_source='ydot',\n fix_initial=True, fix_final=True)\nphase.add_state('v', rate_source='vdot',\n fix_initial=True, fix_final=False)\n# Define theta as a control.\nphase.add_control(name='theta', units='rad',\n lower=0, upper=np.pi)\n\n\n######################################################\n# Post trajectory calculations for composite objective\n######################################################\n\np.model.add_subsystem('other_calcs', om.ExecComp(\"f=v[0]+v[1]\", v={\"shape\":(2,)}))\n ###################################################################\n# Standard Dymos API for objective function - minimize final time.\n###################################################################\n\n# phase.add_objective('time', loc='final')\n\n###################################################################\n# OpenMDAO API for objective functions that require post-dymos calculations\n###################################################################\n\np.model.add_objective('other_calcs.f')\n\n# Set the driver.\np.driver = om.ScipyOptimizeDriver()\n\n# Allow OpenMDAO to automatically determine total\n# derivative sparsity pattern.\n# This works in conjunction with partial derivative\n# coloring to give a large speedup\np.driver.declare_coloring()\n\n# Setup the problem\np.setup()\n\n# Now that the OpenMDAO problem is setup, we can guess the\n# values of time, states, and controls.\np.set_val('traj.phase0.t_duration', 2.0)\n\n# States and controls here use a linearly interpolated\n# initial guess along the trajectory.\np.set_val('traj.phase0.states:x',\n phase.interp('x', ys=[0, 10]),\n units='m')\np.set_val('traj.phase0.states:y',\n phase.interp('y', ys=[10, 5]),\n units='m')\np.set_val('traj.phase0.states:v',\n phase.interp('v', ys=[0, 5]),\n units='m/s')\n# constant initial guess for control\np.set_val('traj.phase0.controls:theta', 90, units='deg')\n\n# Run the driver to solve the problem and generate default plots of\n# state and control values vs time\ndm.run_problem(p, make_plots=True, simulate=True)\n" }, { "answer_id": 74505232, "author": "Justin Gray", "author_id": 2301186, "author_profile": "https://Stackoverflow.com/users/2301186", "pm_score": 3, "selected": true, "text": "timeseries Radau y_tot y y_tot import numpy as np\nimport openmdao.api as om\nimport dymos as dm\nimport matplotlib.pyplot as plt\n\n# First define a system which computes the equations of motion\nclass BrachistochroneEOM(om.ExplicitComponent):\n def initialize(self):\n self.options.declare('num_nodes', types=int)\n\n def setup(self):\n nn = self.options['num_nodes']\n\n # Inputs\n self.add_input('v', val=np.zeros(nn), units='m/s', desc='velocity')\n self.add_input('theta', val=np.zeros(nn), units='rad', desc='angle of wire')\n self.add_output('xdot', val=np.zeros(nn), units='m/s', desc='x rate of change')\n self.add_output('ydot', val=np.zeros(nn), units='m/s', desc='y rate of change')\n self.add_output('vdot', val=np.zeros(nn), units='m/s**2', desc='v rate of change')\n\n # Ask OpenMDAO to compute the partial derivatives using complex-step\n # with a partial coloring algorithm for improved performance\n self.declare_partials(of='*', wrt='*', method='cs')\n self.declare_coloring(wrt='*', method='cs', show_summary=True)\n\n def compute(self, inputs, outputs):\n v, theta = inputs.values()\n outputs['vdot'] = 9.80665 * np.cos(theta)\n outputs['xdot'] = v * np.sin(theta)\n outputs['ydot'] = -v * np.cos(theta)\n\np = om.Problem()\n\n# Define a Trajectory object\ntraj = p.model.add_subsystem('traj', dm.Trajectory())\n\n# Define a Dymos Phase object with GaussLobatto Transcription\ntx = dm.GaussLobatto(num_segments=10, order=3)\nphase = dm.Phase(ode_class=BrachistochroneEOM, transcription=tx)\n\ntraj.add_phase(name='phase0', phase=phase)\n\n# Set the time options\nphase.set_time_options(fix_initial=True,\n duration_bounds=(0.5, 10.0))\n# Set the state options\nphase.add_state('x', rate_source='xdot',\n fix_initial=True, fix_final=True)\nphase.add_state('y', rate_source='ydot',\n fix_initial=True, fix_final=True)\nphase.add_state('y_tot', rate_source='y',\n fix_initial=True, fix_final=True)\nphase.add_state('v', rate_source='vdot',\n fix_initial=True, fix_final=False)\n# Define theta as a control.\nphase.add_control(name='theta', units='rad',\n lower=0, upper=np.pi)\n\n\n# compressed transcription so we don't get duplicate nodes between each segment\nphase.add_timeseries('fixed_step', dm.Radau(num_segments=10, order=1))\nphase.add_timeseries_output('v', timeseries=\"fixed_step\")\n\n######################################################\n# Post trajectory calculations for composite objective\n######################################################\n\np.model.add_subsystem('other_calcs', om.ExecComp(\"f=v[0]+v[1]\", v={\"shape\":(2,)}))\np.model.connect('traj.phase0.timeseries.states:v', 'other_calcs.v', src_indices=[0,-1])\n\n###################################################################\n# Standard Dymos API for objective function - minimize final time.\n###################################################################\n\nphase.add_objective('time', loc='final')\n\n###################################################################\n# OpenMDAO API for objective functions that require post-dymos calculations\n###################################################################\n\n# p.model.add_objective('other_calcs.f')\n\n# Set the driver.\np.driver = om.ScipyOptimizeDriver()\n\n# Allow OpenMDAO to automatically determine total\n# derivative sparsity pattern.\n# This works in conjunction with partial derivative\n# coloring to give a large speedup\np.driver.declare_coloring()\n\n# Setup the problem\np.setup()\n\n# Now that the OpenMDAO problem is setup, we can guess the\n# values of time, states, and controls.\np.set_val('traj.phase0.t_duration', 2.0)\n\n# States and controls here use a linearly interpolated\n# initial guess along the trajectory.\np.set_val('traj.phase0.states:x',\n phase.interp('x', ys=[0, 10]),\n units='m')\np.set_val('traj.phase0.states:y',\n phase.interp('y', ys=[10, 5]),\n units='m')\np.set_val('traj.phase0.states:y_tot',\n phase.interp('y', ys=[0, 0]),\n units='m*s')\np.set_val('traj.phase0.states:v',\n phase.interp('v', ys=[0, 5]),\n units='m/s')\n# constant initial guess for control\np.set_val('traj.phase0.controls:theta', 90, units='deg')\n\n# Run the driver to solve the problem and generate default plots of\n# state and control values vs time\ndm.run_problem(p, make_plots=True, simulate=True)\n\n\nprint(p.get_val(\"traj.phase0.fixed_step.states:v\"))\ntime = p.get_val(\"traj.phase0.fixed_step.time\")[:,0]\ndt = time[1:] - time[0:-1]\nprint(\"time\", time)\n# note that dymos keeps duplicates of values between each segment, so you see double values\n# which gives 0 time steps between each segment\nprint(\"dt: \", dt)\nprint(p.get_val(\"traj.phase0.timeseries.states:y_tot\"))\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7655701/" ]
74,497,395
<p>I have a csv that looks like</p> <pre><code>AccountExternalID Customer 1 RogerInc 2 FredLLC </code></pre> <p>I am turning that into a Pandas DF, and I want to turn that into a dict that looks like</p> <p>{'RogerInc': 1, 'FredLLC': 2}</p> <p>This is what I tried;</p> <pre><code>def build_custid_dict(csv_path: str=None) -&gt; dict[str]: csv_path = r'\\path\CustomerIDs.csv' df = pd.read_csv(csv_path) # Strip whitespace df[df.columns] = df.apply(lambda x: x.str.strip()) df_dict = df.to_dict('list') return df_dict </code></pre>
[ { "answer_id": 74500395, "author": "Justin Gray", "author_id": 2301186, "author_profile": "https://Stackoverflow.com/users/2301186", "pm_score": 2, "selected": false, "text": "traj traj traj ExecComp timeseries import numpy as np\nimport openmdao.api as om\nimport dymos as dm\nimport matplotlib.pyplot as plt\n\n# First define a system which computes the equations of motion\nclass BrachistochroneEOM(om.ExplicitComponent):\n def initialize(self):\n self.options.declare('num_nodes', types=int)\n\n def setup(self):\n nn = self.options['num_nodes']\n\n # Inputs\n self.add_input('v', val=np.zeros(nn), units='m/s', desc='velocity')\n self.add_input('theta', val=np.zeros(nn), units='rad', desc='angle of wire')\n self.add_output('xdot', val=np.zeros(nn), units='m/s', desc='x rate of change')\n self.add_output('ydot', val=np.zeros(nn), units='m/s', desc='y rate of change')\n self.add_output('vdot', val=np.zeros(nn), units='m/s**2', desc='v rate of change')\n\n # Ask OpenMDAO to compute the partial derivatives using complex-step\n # with a partial coloring algorithm for improved performance\n self.declare_partials(of='*', wrt='*', method='cs')\n self.declare_coloring(wrt='*', method='cs', show_summary=True)\n\n def compute(self, inputs, outputs):\n v, theta = inputs.values()\n outputs['vdot'] = 9.80665 * np.cos(theta)\n outputs['xdot'] = v * np.sin(theta)\n outputs['ydot'] = -v * np.cos(theta)\n\np = om.Problem()\n\n# Define a Trajectory object\ntraj = p.model.add_subsystem('traj', dm.Trajectory())\n\n# Define a Dymos Phase object with GaussLobatto Transcription\ntx = dm.GaussLobatto(num_segments=10, order=3)\nphase = dm.Phase(ode_class=BrachistochroneEOM, transcription=tx)\n\ntraj.add_phase(name='phase0', phase=phase)\n\n# Set the time options\nphase.set_time_options(fix_initial=True,\n duration_bounds=(0.5, 10.0))\n# Set the state options\nphase.add_state('x', rate_source='xdot',\n fix_initial=True, fix_final=True)\nphase.add_state('y', rate_source='ydot',\n fix_initial=True, fix_final=True)\nphase.add_state('v', rate_source='vdot',\n fix_initial=True, fix_final=False)\n# Define theta as a control.\nphase.add_control(name='theta', units='rad',\n lower=0, upper=np.pi)\n\n\n######################################################\n# Post trajectory calculations for composite objective\n######################################################\n\np.model.add_subsystem('other_calcs', om.ExecComp(\"f=v[0]+v[1]\", v={\"shape\":(2,)}))\n ###################################################################\n# Standard Dymos API for objective function - minimize final time.\n###################################################################\n\n# phase.add_objective('time', loc='final')\n\n###################################################################\n# OpenMDAO API for objective functions that require post-dymos calculations\n###################################################################\n\np.model.add_objective('other_calcs.f')\n\n# Set the driver.\np.driver = om.ScipyOptimizeDriver()\n\n# Allow OpenMDAO to automatically determine total\n# derivative sparsity pattern.\n# This works in conjunction with partial derivative\n# coloring to give a large speedup\np.driver.declare_coloring()\n\n# Setup the problem\np.setup()\n\n# Now that the OpenMDAO problem is setup, we can guess the\n# values of time, states, and controls.\np.set_val('traj.phase0.t_duration', 2.0)\n\n# States and controls here use a linearly interpolated\n# initial guess along the trajectory.\np.set_val('traj.phase0.states:x',\n phase.interp('x', ys=[0, 10]),\n units='m')\np.set_val('traj.phase0.states:y',\n phase.interp('y', ys=[10, 5]),\n units='m')\np.set_val('traj.phase0.states:v',\n phase.interp('v', ys=[0, 5]),\n units='m/s')\n# constant initial guess for control\np.set_val('traj.phase0.controls:theta', 90, units='deg')\n\n# Run the driver to solve the problem and generate default plots of\n# state and control values vs time\ndm.run_problem(p, make_plots=True, simulate=True)\n" }, { "answer_id": 74505232, "author": "Justin Gray", "author_id": 2301186, "author_profile": "https://Stackoverflow.com/users/2301186", "pm_score": 3, "selected": true, "text": "timeseries Radau y_tot y y_tot import numpy as np\nimport openmdao.api as om\nimport dymos as dm\nimport matplotlib.pyplot as plt\n\n# First define a system which computes the equations of motion\nclass BrachistochroneEOM(om.ExplicitComponent):\n def initialize(self):\n self.options.declare('num_nodes', types=int)\n\n def setup(self):\n nn = self.options['num_nodes']\n\n # Inputs\n self.add_input('v', val=np.zeros(nn), units='m/s', desc='velocity')\n self.add_input('theta', val=np.zeros(nn), units='rad', desc='angle of wire')\n self.add_output('xdot', val=np.zeros(nn), units='m/s', desc='x rate of change')\n self.add_output('ydot', val=np.zeros(nn), units='m/s', desc='y rate of change')\n self.add_output('vdot', val=np.zeros(nn), units='m/s**2', desc='v rate of change')\n\n # Ask OpenMDAO to compute the partial derivatives using complex-step\n # with a partial coloring algorithm for improved performance\n self.declare_partials(of='*', wrt='*', method='cs')\n self.declare_coloring(wrt='*', method='cs', show_summary=True)\n\n def compute(self, inputs, outputs):\n v, theta = inputs.values()\n outputs['vdot'] = 9.80665 * np.cos(theta)\n outputs['xdot'] = v * np.sin(theta)\n outputs['ydot'] = -v * np.cos(theta)\n\np = om.Problem()\n\n# Define a Trajectory object\ntraj = p.model.add_subsystem('traj', dm.Trajectory())\n\n# Define a Dymos Phase object with GaussLobatto Transcription\ntx = dm.GaussLobatto(num_segments=10, order=3)\nphase = dm.Phase(ode_class=BrachistochroneEOM, transcription=tx)\n\ntraj.add_phase(name='phase0', phase=phase)\n\n# Set the time options\nphase.set_time_options(fix_initial=True,\n duration_bounds=(0.5, 10.0))\n# Set the state options\nphase.add_state('x', rate_source='xdot',\n fix_initial=True, fix_final=True)\nphase.add_state('y', rate_source='ydot',\n fix_initial=True, fix_final=True)\nphase.add_state('y_tot', rate_source='y',\n fix_initial=True, fix_final=True)\nphase.add_state('v', rate_source='vdot',\n fix_initial=True, fix_final=False)\n# Define theta as a control.\nphase.add_control(name='theta', units='rad',\n lower=0, upper=np.pi)\n\n\n# compressed transcription so we don't get duplicate nodes between each segment\nphase.add_timeseries('fixed_step', dm.Radau(num_segments=10, order=1))\nphase.add_timeseries_output('v', timeseries=\"fixed_step\")\n\n######################################################\n# Post trajectory calculations for composite objective\n######################################################\n\np.model.add_subsystem('other_calcs', om.ExecComp(\"f=v[0]+v[1]\", v={\"shape\":(2,)}))\np.model.connect('traj.phase0.timeseries.states:v', 'other_calcs.v', src_indices=[0,-1])\n\n###################################################################\n# Standard Dymos API for objective function - minimize final time.\n###################################################################\n\nphase.add_objective('time', loc='final')\n\n###################################################################\n# OpenMDAO API for objective functions that require post-dymos calculations\n###################################################################\n\n# p.model.add_objective('other_calcs.f')\n\n# Set the driver.\np.driver = om.ScipyOptimizeDriver()\n\n# Allow OpenMDAO to automatically determine total\n# derivative sparsity pattern.\n# This works in conjunction with partial derivative\n# coloring to give a large speedup\np.driver.declare_coloring()\n\n# Setup the problem\np.setup()\n\n# Now that the OpenMDAO problem is setup, we can guess the\n# values of time, states, and controls.\np.set_val('traj.phase0.t_duration', 2.0)\n\n# States and controls here use a linearly interpolated\n# initial guess along the trajectory.\np.set_val('traj.phase0.states:x',\n phase.interp('x', ys=[0, 10]),\n units='m')\np.set_val('traj.phase0.states:y',\n phase.interp('y', ys=[10, 5]),\n units='m')\np.set_val('traj.phase0.states:y_tot',\n phase.interp('y', ys=[0, 0]),\n units='m*s')\np.set_val('traj.phase0.states:v',\n phase.interp('v', ys=[0, 5]),\n units='m/s')\n# constant initial guess for control\np.set_val('traj.phase0.controls:theta', 90, units='deg')\n\n# Run the driver to solve the problem and generate default plots of\n# state and control values vs time\ndm.run_problem(p, make_plots=True, simulate=True)\n\n\nprint(p.get_val(\"traj.phase0.fixed_step.states:v\"))\ntime = p.get_val(\"traj.phase0.fixed_step.time\")[:,0]\ndt = time[1:] - time[0:-1]\nprint(\"time\", time)\n# note that dymos keeps duplicates of values between each segment, so you see double values\n# which gives 0 time steps between each segment\nprint(\"dt: \", dt)\nprint(p.get_val(\"traj.phase0.timeseries.states:y_tot\"))\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20497632/" ]
74,497,399
<p>I have the following data that looks like this:</p> <pre><code>my_data = c(&quot;red A1B 5L2 101&quot;, &quot;blue A1C 5L8 10872&quot;, &quot;Green A1D 5L5 100003&quot; ) </code></pre> <p><strong>Starting from the right hand side of each string, I wanted to remove the number as well as the spaces before the number.</strong></p> <p>The final result would look something like this:</p> <pre><code>[1] &quot;red A1B 5L2&quot; &quot;blue A1C 5L8&quot; &quot;Green A1D 5L5&quot; </code></pre> <p>I know that there is a regex pattern that appears in each string in the following format: <code>'(([A-Z] ?[0-9]){3})|.', '\\1'</code></p> <p>Thus, I want to identify the position where this regex pattern finishes and the position where the string finishes - then I could delete the space between these two positions and obtain the desired result.</p> <p>I found this link which shows how to remove all characters in a string appearing to the left or to the right of a certain pattern (<a href="https://datascience.stackexchange.com/questions/8922/removing-strings-after-a-certain-character-in-a-given-text">https://datascience.stackexchange.com/questions/8922/removing-strings-after-a-certain-character-in-a-given-text</a>). I tried to apply the logic provided here to my example:</p> <pre><code>gsub(&quot;(([A-Z] ?[0-9]){3})|.', '\\1.*&quot;,&quot;&quot;,my_data) </code></pre> <p>But this is producing the opposite result!</p> <pre><code>[1] &quot;red 101&quot; &quot;blue 10872&quot; &quot;Green 100003&quot; </code></pre> <p>Can someone please show me how to resolve this problem?</p>
[ { "answer_id": 74500395, "author": "Justin Gray", "author_id": 2301186, "author_profile": "https://Stackoverflow.com/users/2301186", "pm_score": 2, "selected": false, "text": "traj traj traj ExecComp timeseries import numpy as np\nimport openmdao.api as om\nimport dymos as dm\nimport matplotlib.pyplot as plt\n\n# First define a system which computes the equations of motion\nclass BrachistochroneEOM(om.ExplicitComponent):\n def initialize(self):\n self.options.declare('num_nodes', types=int)\n\n def setup(self):\n nn = self.options['num_nodes']\n\n # Inputs\n self.add_input('v', val=np.zeros(nn), units='m/s', desc='velocity')\n self.add_input('theta', val=np.zeros(nn), units='rad', desc='angle of wire')\n self.add_output('xdot', val=np.zeros(nn), units='m/s', desc='x rate of change')\n self.add_output('ydot', val=np.zeros(nn), units='m/s', desc='y rate of change')\n self.add_output('vdot', val=np.zeros(nn), units='m/s**2', desc='v rate of change')\n\n # Ask OpenMDAO to compute the partial derivatives using complex-step\n # with a partial coloring algorithm for improved performance\n self.declare_partials(of='*', wrt='*', method='cs')\n self.declare_coloring(wrt='*', method='cs', show_summary=True)\n\n def compute(self, inputs, outputs):\n v, theta = inputs.values()\n outputs['vdot'] = 9.80665 * np.cos(theta)\n outputs['xdot'] = v * np.sin(theta)\n outputs['ydot'] = -v * np.cos(theta)\n\np = om.Problem()\n\n# Define a Trajectory object\ntraj = p.model.add_subsystem('traj', dm.Trajectory())\n\n# Define a Dymos Phase object with GaussLobatto Transcription\ntx = dm.GaussLobatto(num_segments=10, order=3)\nphase = dm.Phase(ode_class=BrachistochroneEOM, transcription=tx)\n\ntraj.add_phase(name='phase0', phase=phase)\n\n# Set the time options\nphase.set_time_options(fix_initial=True,\n duration_bounds=(0.5, 10.0))\n# Set the state options\nphase.add_state('x', rate_source='xdot',\n fix_initial=True, fix_final=True)\nphase.add_state('y', rate_source='ydot',\n fix_initial=True, fix_final=True)\nphase.add_state('v', rate_source='vdot',\n fix_initial=True, fix_final=False)\n# Define theta as a control.\nphase.add_control(name='theta', units='rad',\n lower=0, upper=np.pi)\n\n\n######################################################\n# Post trajectory calculations for composite objective\n######################################################\n\np.model.add_subsystem('other_calcs', om.ExecComp(\"f=v[0]+v[1]\", v={\"shape\":(2,)}))\n ###################################################################\n# Standard Dymos API for objective function - minimize final time.\n###################################################################\n\n# phase.add_objective('time', loc='final')\n\n###################################################################\n# OpenMDAO API for objective functions that require post-dymos calculations\n###################################################################\n\np.model.add_objective('other_calcs.f')\n\n# Set the driver.\np.driver = om.ScipyOptimizeDriver()\n\n# Allow OpenMDAO to automatically determine total\n# derivative sparsity pattern.\n# This works in conjunction with partial derivative\n# coloring to give a large speedup\np.driver.declare_coloring()\n\n# Setup the problem\np.setup()\n\n# Now that the OpenMDAO problem is setup, we can guess the\n# values of time, states, and controls.\np.set_val('traj.phase0.t_duration', 2.0)\n\n# States and controls here use a linearly interpolated\n# initial guess along the trajectory.\np.set_val('traj.phase0.states:x',\n phase.interp('x', ys=[0, 10]),\n units='m')\np.set_val('traj.phase0.states:y',\n phase.interp('y', ys=[10, 5]),\n units='m')\np.set_val('traj.phase0.states:v',\n phase.interp('v', ys=[0, 5]),\n units='m/s')\n# constant initial guess for control\np.set_val('traj.phase0.controls:theta', 90, units='deg')\n\n# Run the driver to solve the problem and generate default plots of\n# state and control values vs time\ndm.run_problem(p, make_plots=True, simulate=True)\n" }, { "answer_id": 74505232, "author": "Justin Gray", "author_id": 2301186, "author_profile": "https://Stackoverflow.com/users/2301186", "pm_score": 3, "selected": true, "text": "timeseries Radau y_tot y y_tot import numpy as np\nimport openmdao.api as om\nimport dymos as dm\nimport matplotlib.pyplot as plt\n\n# First define a system which computes the equations of motion\nclass BrachistochroneEOM(om.ExplicitComponent):\n def initialize(self):\n self.options.declare('num_nodes', types=int)\n\n def setup(self):\n nn = self.options['num_nodes']\n\n # Inputs\n self.add_input('v', val=np.zeros(nn), units='m/s', desc='velocity')\n self.add_input('theta', val=np.zeros(nn), units='rad', desc='angle of wire')\n self.add_output('xdot', val=np.zeros(nn), units='m/s', desc='x rate of change')\n self.add_output('ydot', val=np.zeros(nn), units='m/s', desc='y rate of change')\n self.add_output('vdot', val=np.zeros(nn), units='m/s**2', desc='v rate of change')\n\n # Ask OpenMDAO to compute the partial derivatives using complex-step\n # with a partial coloring algorithm for improved performance\n self.declare_partials(of='*', wrt='*', method='cs')\n self.declare_coloring(wrt='*', method='cs', show_summary=True)\n\n def compute(self, inputs, outputs):\n v, theta = inputs.values()\n outputs['vdot'] = 9.80665 * np.cos(theta)\n outputs['xdot'] = v * np.sin(theta)\n outputs['ydot'] = -v * np.cos(theta)\n\np = om.Problem()\n\n# Define a Trajectory object\ntraj = p.model.add_subsystem('traj', dm.Trajectory())\n\n# Define a Dymos Phase object with GaussLobatto Transcription\ntx = dm.GaussLobatto(num_segments=10, order=3)\nphase = dm.Phase(ode_class=BrachistochroneEOM, transcription=tx)\n\ntraj.add_phase(name='phase0', phase=phase)\n\n# Set the time options\nphase.set_time_options(fix_initial=True,\n duration_bounds=(0.5, 10.0))\n# Set the state options\nphase.add_state('x', rate_source='xdot',\n fix_initial=True, fix_final=True)\nphase.add_state('y', rate_source='ydot',\n fix_initial=True, fix_final=True)\nphase.add_state('y_tot', rate_source='y',\n fix_initial=True, fix_final=True)\nphase.add_state('v', rate_source='vdot',\n fix_initial=True, fix_final=False)\n# Define theta as a control.\nphase.add_control(name='theta', units='rad',\n lower=0, upper=np.pi)\n\n\n# compressed transcription so we don't get duplicate nodes between each segment\nphase.add_timeseries('fixed_step', dm.Radau(num_segments=10, order=1))\nphase.add_timeseries_output('v', timeseries=\"fixed_step\")\n\n######################################################\n# Post trajectory calculations for composite objective\n######################################################\n\np.model.add_subsystem('other_calcs', om.ExecComp(\"f=v[0]+v[1]\", v={\"shape\":(2,)}))\np.model.connect('traj.phase0.timeseries.states:v', 'other_calcs.v', src_indices=[0,-1])\n\n###################################################################\n# Standard Dymos API for objective function - minimize final time.\n###################################################################\n\nphase.add_objective('time', loc='final')\n\n###################################################################\n# OpenMDAO API for objective functions that require post-dymos calculations\n###################################################################\n\n# p.model.add_objective('other_calcs.f')\n\n# Set the driver.\np.driver = om.ScipyOptimizeDriver()\n\n# Allow OpenMDAO to automatically determine total\n# derivative sparsity pattern.\n# This works in conjunction with partial derivative\n# coloring to give a large speedup\np.driver.declare_coloring()\n\n# Setup the problem\np.setup()\n\n# Now that the OpenMDAO problem is setup, we can guess the\n# values of time, states, and controls.\np.set_val('traj.phase0.t_duration', 2.0)\n\n# States and controls here use a linearly interpolated\n# initial guess along the trajectory.\np.set_val('traj.phase0.states:x',\n phase.interp('x', ys=[0, 10]),\n units='m')\np.set_val('traj.phase0.states:y',\n phase.interp('y', ys=[10, 5]),\n units='m')\np.set_val('traj.phase0.states:y_tot',\n phase.interp('y', ys=[0, 0]),\n units='m*s')\np.set_val('traj.phase0.states:v',\n phase.interp('v', ys=[0, 5]),\n units='m/s')\n# constant initial guess for control\np.set_val('traj.phase0.controls:theta', 90, units='deg')\n\n# Run the driver to solve the problem and generate default plots of\n# state and control values vs time\ndm.run_problem(p, make_plots=True, simulate=True)\n\n\nprint(p.get_val(\"traj.phase0.fixed_step.states:v\"))\ntime = p.get_val(\"traj.phase0.fixed_step.time\")[:,0]\ndt = time[1:] - time[0:-1]\nprint(\"time\", time)\n# note that dymos keeps duplicates of values between each segment, so you see double values\n# which gives 0 time steps between each segment\nprint(\"dt: \", dt)\nprint(p.get_val(\"traj.phase0.timeseries.states:y_tot\"))\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13203841/" ]
74,497,401
<p>I have two very large lists, and I want use one loop for iterating over two of them with the different sliding windows. Is that possible? if not, what is the best way?</p> <blockquote> <p>For example, I have A and B, I want a loop which provide the summation of sliding window 2 of list B and sliding window of size 3 of A.</p> </blockquote> <pre><code>A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13] B = [-1,2, 3, 14, 51, 16, 7, 18 ] </code></pre> <p>Sliding window of size 3 in <code>A = [1,4,7,10]</code><br/> Sliding window of size 2 in <code>B = [-1,3,5,7]</code><br/> Out: <code>A + B = [0, 7, 12, 17]</code></p>
[ { "answer_id": 74500395, "author": "Justin Gray", "author_id": 2301186, "author_profile": "https://Stackoverflow.com/users/2301186", "pm_score": 2, "selected": false, "text": "traj traj traj ExecComp timeseries import numpy as np\nimport openmdao.api as om\nimport dymos as dm\nimport matplotlib.pyplot as plt\n\n# First define a system which computes the equations of motion\nclass BrachistochroneEOM(om.ExplicitComponent):\n def initialize(self):\n self.options.declare('num_nodes', types=int)\n\n def setup(self):\n nn = self.options['num_nodes']\n\n # Inputs\n self.add_input('v', val=np.zeros(nn), units='m/s', desc='velocity')\n self.add_input('theta', val=np.zeros(nn), units='rad', desc='angle of wire')\n self.add_output('xdot', val=np.zeros(nn), units='m/s', desc='x rate of change')\n self.add_output('ydot', val=np.zeros(nn), units='m/s', desc='y rate of change')\n self.add_output('vdot', val=np.zeros(nn), units='m/s**2', desc='v rate of change')\n\n # Ask OpenMDAO to compute the partial derivatives using complex-step\n # with a partial coloring algorithm for improved performance\n self.declare_partials(of='*', wrt='*', method='cs')\n self.declare_coloring(wrt='*', method='cs', show_summary=True)\n\n def compute(self, inputs, outputs):\n v, theta = inputs.values()\n outputs['vdot'] = 9.80665 * np.cos(theta)\n outputs['xdot'] = v * np.sin(theta)\n outputs['ydot'] = -v * np.cos(theta)\n\np = om.Problem()\n\n# Define a Trajectory object\ntraj = p.model.add_subsystem('traj', dm.Trajectory())\n\n# Define a Dymos Phase object with GaussLobatto Transcription\ntx = dm.GaussLobatto(num_segments=10, order=3)\nphase = dm.Phase(ode_class=BrachistochroneEOM, transcription=tx)\n\ntraj.add_phase(name='phase0', phase=phase)\n\n# Set the time options\nphase.set_time_options(fix_initial=True,\n duration_bounds=(0.5, 10.0))\n# Set the state options\nphase.add_state('x', rate_source='xdot',\n fix_initial=True, fix_final=True)\nphase.add_state('y', rate_source='ydot',\n fix_initial=True, fix_final=True)\nphase.add_state('v', rate_source='vdot',\n fix_initial=True, fix_final=False)\n# Define theta as a control.\nphase.add_control(name='theta', units='rad',\n lower=0, upper=np.pi)\n\n\n######################################################\n# Post trajectory calculations for composite objective\n######################################################\n\np.model.add_subsystem('other_calcs', om.ExecComp(\"f=v[0]+v[1]\", v={\"shape\":(2,)}))\n ###################################################################\n# Standard Dymos API for objective function - minimize final time.\n###################################################################\n\n# phase.add_objective('time', loc='final')\n\n###################################################################\n# OpenMDAO API for objective functions that require post-dymos calculations\n###################################################################\n\np.model.add_objective('other_calcs.f')\n\n# Set the driver.\np.driver = om.ScipyOptimizeDriver()\n\n# Allow OpenMDAO to automatically determine total\n# derivative sparsity pattern.\n# This works in conjunction with partial derivative\n# coloring to give a large speedup\np.driver.declare_coloring()\n\n# Setup the problem\np.setup()\n\n# Now that the OpenMDAO problem is setup, we can guess the\n# values of time, states, and controls.\np.set_val('traj.phase0.t_duration', 2.0)\n\n# States and controls here use a linearly interpolated\n# initial guess along the trajectory.\np.set_val('traj.phase0.states:x',\n phase.interp('x', ys=[0, 10]),\n units='m')\np.set_val('traj.phase0.states:y',\n phase.interp('y', ys=[10, 5]),\n units='m')\np.set_val('traj.phase0.states:v',\n phase.interp('v', ys=[0, 5]),\n units='m/s')\n# constant initial guess for control\np.set_val('traj.phase0.controls:theta', 90, units='deg')\n\n# Run the driver to solve the problem and generate default plots of\n# state and control values vs time\ndm.run_problem(p, make_plots=True, simulate=True)\n" }, { "answer_id": 74505232, "author": "Justin Gray", "author_id": 2301186, "author_profile": "https://Stackoverflow.com/users/2301186", "pm_score": 3, "selected": true, "text": "timeseries Radau y_tot y y_tot import numpy as np\nimport openmdao.api as om\nimport dymos as dm\nimport matplotlib.pyplot as plt\n\n# First define a system which computes the equations of motion\nclass BrachistochroneEOM(om.ExplicitComponent):\n def initialize(self):\n self.options.declare('num_nodes', types=int)\n\n def setup(self):\n nn = self.options['num_nodes']\n\n # Inputs\n self.add_input('v', val=np.zeros(nn), units='m/s', desc='velocity')\n self.add_input('theta', val=np.zeros(nn), units='rad', desc='angle of wire')\n self.add_output('xdot', val=np.zeros(nn), units='m/s', desc='x rate of change')\n self.add_output('ydot', val=np.zeros(nn), units='m/s', desc='y rate of change')\n self.add_output('vdot', val=np.zeros(nn), units='m/s**2', desc='v rate of change')\n\n # Ask OpenMDAO to compute the partial derivatives using complex-step\n # with a partial coloring algorithm for improved performance\n self.declare_partials(of='*', wrt='*', method='cs')\n self.declare_coloring(wrt='*', method='cs', show_summary=True)\n\n def compute(self, inputs, outputs):\n v, theta = inputs.values()\n outputs['vdot'] = 9.80665 * np.cos(theta)\n outputs['xdot'] = v * np.sin(theta)\n outputs['ydot'] = -v * np.cos(theta)\n\np = om.Problem()\n\n# Define a Trajectory object\ntraj = p.model.add_subsystem('traj', dm.Trajectory())\n\n# Define a Dymos Phase object with GaussLobatto Transcription\ntx = dm.GaussLobatto(num_segments=10, order=3)\nphase = dm.Phase(ode_class=BrachistochroneEOM, transcription=tx)\n\ntraj.add_phase(name='phase0', phase=phase)\n\n# Set the time options\nphase.set_time_options(fix_initial=True,\n duration_bounds=(0.5, 10.0))\n# Set the state options\nphase.add_state('x', rate_source='xdot',\n fix_initial=True, fix_final=True)\nphase.add_state('y', rate_source='ydot',\n fix_initial=True, fix_final=True)\nphase.add_state('y_tot', rate_source='y',\n fix_initial=True, fix_final=True)\nphase.add_state('v', rate_source='vdot',\n fix_initial=True, fix_final=False)\n# Define theta as a control.\nphase.add_control(name='theta', units='rad',\n lower=0, upper=np.pi)\n\n\n# compressed transcription so we don't get duplicate nodes between each segment\nphase.add_timeseries('fixed_step', dm.Radau(num_segments=10, order=1))\nphase.add_timeseries_output('v', timeseries=\"fixed_step\")\n\n######################################################\n# Post trajectory calculations for composite objective\n######################################################\n\np.model.add_subsystem('other_calcs', om.ExecComp(\"f=v[0]+v[1]\", v={\"shape\":(2,)}))\np.model.connect('traj.phase0.timeseries.states:v', 'other_calcs.v', src_indices=[0,-1])\n\n###################################################################\n# Standard Dymos API for objective function - minimize final time.\n###################################################################\n\nphase.add_objective('time', loc='final')\n\n###################################################################\n# OpenMDAO API for objective functions that require post-dymos calculations\n###################################################################\n\n# p.model.add_objective('other_calcs.f')\n\n# Set the driver.\np.driver = om.ScipyOptimizeDriver()\n\n# Allow OpenMDAO to automatically determine total\n# derivative sparsity pattern.\n# This works in conjunction with partial derivative\n# coloring to give a large speedup\np.driver.declare_coloring()\n\n# Setup the problem\np.setup()\n\n# Now that the OpenMDAO problem is setup, we can guess the\n# values of time, states, and controls.\np.set_val('traj.phase0.t_duration', 2.0)\n\n# States and controls here use a linearly interpolated\n# initial guess along the trajectory.\np.set_val('traj.phase0.states:x',\n phase.interp('x', ys=[0, 10]),\n units='m')\np.set_val('traj.phase0.states:y',\n phase.interp('y', ys=[10, 5]),\n units='m')\np.set_val('traj.phase0.states:y_tot',\n phase.interp('y', ys=[0, 0]),\n units='m*s')\np.set_val('traj.phase0.states:v',\n phase.interp('v', ys=[0, 5]),\n units='m/s')\n# constant initial guess for control\np.set_val('traj.phase0.controls:theta', 90, units='deg')\n\n# Run the driver to solve the problem and generate default plots of\n# state and control values vs time\ndm.run_problem(p, make_plots=True, simulate=True)\n\n\nprint(p.get_val(\"traj.phase0.fixed_step.states:v\"))\ntime = p.get_val(\"traj.phase0.fixed_step.time\")[:,0]\ndt = time[1:] - time[0:-1]\nprint(\"time\", time)\n# note that dymos keeps duplicates of values between each segment, so you see double values\n# which gives 0 time steps between each segment\nprint(\"dt: \", dt)\nprint(p.get_val(\"traj.phase0.timeseries.states:y_tot\"))\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20224348/" ]
74,497,414
<p>I would like to print 10, but I get the error: <code>AttributeError: 'function' object has no attribute 'x'</code></p> <p>How to fix? Thank you</p> <pre><code>def function1(): def x(): a=10 return a def function2(): y = function1.x() return y function2() </code></pre>
[ { "answer_id": 74497423, "author": "Samathingamajig", "author_id": 12101554, "author_profile": "https://Stackoverflow.com/users/12101554", "pm_score": -1, "selected": true, "text": "return x function1 def function1():\n def x(): \n a=10\n return a\n return x\n \ndef function2():\n y = function1()()\n return y\n\nfunction2()\n" }, { "answer_id": 74497529, "author": "Jason Liam", "author_id": 12002570, "author_profile": "https://Stackoverflow.com/users/12002570", "pm_score": 0, "selected": false, "text": "class class function1(object):\n def x(): \n a=10\n return a\n \ndef function2():\n y = function1.x()\n return y\n\n\nfunction2() #works now and returns 10\n" }, { "answer_id": 74497593, "author": "ItzKarizma", "author_id": 17937268, "author_profile": "https://Stackoverflow.com/users/17937268", "pm_score": -1, "selected": false, "text": "def function1(func):\n def x():\n a=10\n return func(a)\n return x\n\n@function1\ndef function2(y):\n return y\n\n\nprint(function2())\n \n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20430033/" ]
74,497,439
<p>Sometimes I need to delete from half till end of the scope, how to do that in vim I know that I can delete everything inside {} with <code>di{</code> but I want to delete just half</p> <p>Here is a ScreenShot for more details:</p> <p><img src="https://i.stack.imgur.com/6vP8F.png" alt="Code Preview" /></p> <p>or how to dele this part of code:</p> <p><img src="https://i.stack.imgur.com/bpWIV.png" alt="CodePreivew2" /></p> <p>I tried <code>V/} Enter n n</code> till I reach to the parent {} then <code>d</code></p> <p>I also know that I can do <code>vt}</code> if } is in the same line</p> <p>but I need to select lines until } while it's not in the same line</p>
[ { "answer_id": 74497522, "author": "Max Shen", "author_id": 20297231, "author_profile": "https://Stackoverflow.com/users/20297231", "pm_score": 0, "selected": false, "text": "d/}<Enter>\n" }, { "answer_id": 74499038, "author": "romainl", "author_id": 546861, "author_profile": "https://Stackoverflow.com/users/546861", "pm_score": 1, "selected": false, "text": "viB<C-c>d''\n xnoremap EB iB<C-c>v''\nonoremap EB <Cmd>normal vEB<CR>\n dEB :help omap-info" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20544845/" ]
74,497,460
<p>I want to use the structure of model's rodo.rs in controller's todo.rs. How should I write the mod?</p> <pre><code> use actix_web::{get, post, web, HttpResponse,Responder}; mod model; #[get(&quot;/todos/{id}&quot;)] pub async fn get_todo(web::Path(id): web::Path&lt;u32&gt;) -&gt; impl Responder { println!(&quot;get_todo&quot;); let id_option: Option&lt;u32&gt; = Some(id); HttpResponse::Ok().json(model::Todo { id: id_option, content: String::from(&quot;やること&quot;), completed: false, }) } #[post(&quot;/todos&quot;)] pub async fn post_todo(todo: web::Json&lt;model::Todo&gt;) -&gt; impl Responder { println!(&quot;post_todo&quot;); println!(&quot;{:?}&quot;, todo); HttpResponse::Ok().body(&quot;ok&quot;) } </code></pre> <pre><code>use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize)] pub struct Todo { id: Option&lt;u32&gt;, content: String, completed: bool, } </code></pre> <p><a href="https://i.stack.imgur.com/za9DH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/za9DH.png" alt="enter image description here" /></a></p> <p>I want to use the structure of model's rodo.rs in controller's todo.rs. How should I write the mod? How else can I use the file?</p>
[ { "answer_id": 74497522, "author": "Max Shen", "author_id": 20297231, "author_profile": "https://Stackoverflow.com/users/20297231", "pm_score": 0, "selected": false, "text": "d/}<Enter>\n" }, { "answer_id": 74499038, "author": "romainl", "author_id": 546861, "author_profile": "https://Stackoverflow.com/users/546861", "pm_score": 1, "selected": false, "text": "viB<C-c>d''\n xnoremap EB iB<C-c>v''\nonoremap EB <Cmd>normal vEB<CR>\n dEB :help omap-info" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20396543/" ]
74,497,496
<pre><code>#include &lt;stdio.h&gt; int main() { int inpa, med, oper, day, total; char agree; printf(&quot; Bach Mai Hospital&quot;); printf(&quot;\n\nHello, please enter your fee and we will calculate\npayment based on your insurance\n&quot;); printf(&quot;How many days have you been in the hospital &quot;); scanf(&quot;%d&quot;, &amp;day); printf(&quot;How much is your medicine fee &quot;); scanf(&quot;%d&quot;, &amp;med); printf(&quot;Have you undergone surgery (Yes or No)&quot;); scanf(&quot;%s&quot;, &amp;agree); switch(agree){ case 'Y': printf(&quot;Enter your surgery fee &quot;); scanf(&quot; %d&quot;, &amp;oper); break; case 'N': oper = 0; break; }; printf(&quot;%s&quot;, agree); inpa = day * 15000; printf(&quot;Your total fee\n&quot;); printf(&quot;Inpatient fee: %-10d x 15000 = %d\n&quot;, day, inpa); printf(&quot;Medicine fee: %-10d\n&quot;, med); printf(&quot;Surgery fee: %-10d\n&quot;, oper); total = inpa + med + oper; printf(&quot;\n\nYou pay: %d\n&quot;, total); return 0; } </code></pre> <p>It skips my command from when I enter &amp;oper</p> <pre><code>printf(&quot;Enter your surgery fee &quot;); scanf(&quot; %d&quot;, &amp;oper); </code></pre> <p>And it is the result</p> <pre><code> Bach Mai Hospital Hello, please enter your fee and we will calculate payment based on your insurance How many days have you been in the hospital 8 How much is your medicine fee 90000000 Have you undergone surgery (Yes or No)Yes Enter your surgery fee 80000000 PS D:\Desktop\Cprogram&gt; </code></pre> <p>I would be so thankful if someone explain for me why</p> <p>previously I have trouble with the &quot;agree&quot; variable which I declare a char but it understands &quot;agree&quot; as int. Thank you</p>
[ { "answer_id": 74497522, "author": "Max Shen", "author_id": 20297231, "author_profile": "https://Stackoverflow.com/users/20297231", "pm_score": 0, "selected": false, "text": "d/}<Enter>\n" }, { "answer_id": 74499038, "author": "romainl", "author_id": 546861, "author_profile": "https://Stackoverflow.com/users/546861", "pm_score": 1, "selected": false, "text": "viB<C-c>d''\n xnoremap EB iB<C-c>v''\nonoremap EB <Cmd>normal vEB<CR>\n dEB :help omap-info" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20544865/" ]
74,497,502
<p>Hi I am trying to write a function that will test for a valid URL I found this</p> <pre><code> const pattern = new RegExp( '^(https?:\\/\\/)?' + // protocol '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name '((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // port and path '(\\?[;&amp;a-z\\d%_.~+=-]*)?' + // query string '(\\#[-a-z\\d_]*)?$', 'i' ); // fragment locator </code></pre> <p>However it has a false positive it return <code>true</code> when I call it with <code>http://something</code> I need to check that url has a top level domain as well has a protocol <code>.org</code>. Any help would be much appreciated.</p>
[ { "answer_id": 74497507, "author": "chovy", "author_id": 33522, "author_profile": "https://Stackoverflow.com/users/33522", "pm_score": -1, "selected": false, "text": "const url = new URL('http://....');\n" }, { "answer_id": 74497566, "author": "Build For Dev", "author_id": 20477335, "author_profile": "https://Stackoverflow.com/users/20477335", "pm_score": 2, "selected": true, "text": "const isValidUrl = (urlString) => {\n var urlPattern = new RegExp('^(https?:\\\\/\\\\/)?' + // validate protocol\n '((([a-z\\\\d]([a-z\\\\d-]*[a-z\\\\d])*)\\\\.)+[a-z]{2,}|' + // validate domain name\n '((\\\\d{1,3}\\\\.){3}\\\\d{1,3}))' + // validate OR ip (v4) address\n '(\\\\:\\\\d+)?(\\\\/[-a-z\\\\d%_.~+]*)*' + // validate port and path\n '(\\\\?[;&a-z\\\\d%_.~+=-]*)?' + // validate query string\n '(\\\\#[-a-z\\\\d_]*)?$', 'i'); // validate fragment locator\n return !!urlPattern.test(urlString);\n}\n\nconst yourUrl = 'http://google.com';\nconst wrongUrl = 'http://google';\nconsole.log(isValidUrl(yourUrl)); //true\nconsole.log(isValidUrl(wrongUrl)); //false\n" }, { "answer_id": 74497683, "author": "Firoz", "author_id": 17848207, "author_profile": "https://Stackoverflow.com/users/17848207", "pm_score": 0, "selected": false, "text": "function isValidUrl(str) {\n const pattern = new RegExp(\n '^(https?:\\\\/\\\\/)?' + // protocol\n '((([a-z\\\\d]([a-z\\\\d-]*[a-z\\\\d])*)\\\\.)+[a-z]{2,}|' + // domain name\n '((\\\\d{1,3}\\\\.){3}\\\\d{1,3}))' + // OR ip (v4) address\n '(\\\\:\\\\d+)?(\\\\/[-a-z\\\\d%_.~+]*)*' + // port and path\n '(\\\\?[;&a-z\\\\d%_.~+=-]*)?' + // query string\n '(\\\\#[-a-z\\\\d_]*)?$', // fragment locator\n 'i'\n );\n return pattern.test(str);\n }\n\n console.log(isValidUrl('https://stackoverflow.com')); // true\n console.log(isValidUrl('app://stackoverflow.com')); // false\n console.log(isValidUrl('stackoverflow')); // false" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2411628/" ]
74,497,559
<p>I just designed a simple sign-in form to practice CSS and HTML but I can't align 2 divs horizontally to input my name and surname.</p> <p>Actually, I can't understand why if I apply a width of 50% they are stuck on top of each other and if I apply 49% width they are perfectly horizontally aligned as I want.</p> <p>MY CSS (child width 50%):</p> <p>I'm expecting with the child property set to 50% they should take 50% of the parent space.. but actually not, why? what I'm doing wrong, why have to reduce the width to 49% to align them horizontally</p> <p>see my image 50% width: <a href="https://i.stack.imgur.com/gy5xG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gy5xG.jpg" alt="wrong" /></a></p> <p>I want them aligned side by side like here:</p> <p><a href="https://i.stack.imgur.com/aHjRG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aHjRG.jpg" alt="ok effect" /></a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.title{ padding: 1vh; text-transform: uppercase; font-size: 2vh; } .wrapper{ margin: 0; padding: 0; background-color: yellow; } .parent{ background-color: red; width: 100%; } .child{ width: 50%; &lt;--------- HERE THE ISSUE display: inline-block; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;body class="body"&gt; &lt;div class="center"&gt; &lt;h1 class="title"&gt;Sign Up New User&lt;/h1&gt; &lt;form class="submit_form"&gt; &lt;div class="wrapper"&gt; &lt;div class="parent"&gt; &lt;div class="child"&gt; &lt;label for="Name"&gt;Name:&lt;/label&gt;&lt;br&gt; &lt;input type="text" id="Name" name="fname"&gt; &lt;/div&gt; &lt;div class="child"&gt; &lt;label for="Surname"&gt;Surname:&lt;/label&gt;&lt;br&gt; &lt;input type="text" id="Surname" name="fsurname" &gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/body&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74497507, "author": "chovy", "author_id": 33522, "author_profile": "https://Stackoverflow.com/users/33522", "pm_score": -1, "selected": false, "text": "const url = new URL('http://....');\n" }, { "answer_id": 74497566, "author": "Build For Dev", "author_id": 20477335, "author_profile": "https://Stackoverflow.com/users/20477335", "pm_score": 2, "selected": true, "text": "const isValidUrl = (urlString) => {\n var urlPattern = new RegExp('^(https?:\\\\/\\\\/)?' + // validate protocol\n '((([a-z\\\\d]([a-z\\\\d-]*[a-z\\\\d])*)\\\\.)+[a-z]{2,}|' + // validate domain name\n '((\\\\d{1,3}\\\\.){3}\\\\d{1,3}))' + // validate OR ip (v4) address\n '(\\\\:\\\\d+)?(\\\\/[-a-z\\\\d%_.~+]*)*' + // validate port and path\n '(\\\\?[;&a-z\\\\d%_.~+=-]*)?' + // validate query string\n '(\\\\#[-a-z\\\\d_]*)?$', 'i'); // validate fragment locator\n return !!urlPattern.test(urlString);\n}\n\nconst yourUrl = 'http://google.com';\nconst wrongUrl = 'http://google';\nconsole.log(isValidUrl(yourUrl)); //true\nconsole.log(isValidUrl(wrongUrl)); //false\n" }, { "answer_id": 74497683, "author": "Firoz", "author_id": 17848207, "author_profile": "https://Stackoverflow.com/users/17848207", "pm_score": 0, "selected": false, "text": "function isValidUrl(str) {\n const pattern = new RegExp(\n '^(https?:\\\\/\\\\/)?' + // protocol\n '((([a-z\\\\d]([a-z\\\\d-]*[a-z\\\\d])*)\\\\.)+[a-z]{2,}|' + // domain name\n '((\\\\d{1,3}\\\\.){3}\\\\d{1,3}))' + // OR ip (v4) address\n '(\\\\:\\\\d+)?(\\\\/[-a-z\\\\d%_.~+]*)*' + // port and path\n '(\\\\?[;&a-z\\\\d%_.~+=-]*)?' + // query string\n '(\\\\#[-a-z\\\\d_]*)?$', // fragment locator\n 'i'\n );\n return pattern.test(str);\n }\n\n console.log(isValidUrl('https://stackoverflow.com')); // true\n console.log(isValidUrl('app://stackoverflow.com')); // false\n console.log(isValidUrl('stackoverflow')); // false" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9962676/" ]
74,497,572
<p>I am trying to insert values from a datetimepicker into a database, but I get an unhandled exception</p> <blockquote> <p>Conversion failed when converting date and/or time from character string</p> </blockquote> <p>This is the code I used:</p> <pre><code>private void bunifuFlatButton8_Click(object sender, EventArgs e) { if (OrderID.Text == &quot;&quot; || CustomerID.Text == &quot;&quot; || CustName.Text == &quot;&quot; || AmountTB.Text ==&quot;&quot;) { MessageBox.Show(&quot;Fill the data correctly&quot;); } else { SqlCommand cmd = new SqlCommand(&quot;insert into OrderTB values(&quot; + OrderID.Text + &quot;,&quot; + CustomerID.Text + &quot;,'&quot; + CustName.Text + &quot;','&quot; + OrderDate.Text + &quot;',&quot; + AmountTB.Text + &quot;)&quot;, Con); Con.Open(); cmd.ExecuteNonQuery(); MessageBox.Show(&quot;Order successfully added&quot;); Con.Close(); populate(); } } </code></pre> <p>Any help will be appreciated.</p>
[ { "answer_id": 74497634, "author": "Mustafa Ozbalci", "author_id": 12167812, "author_profile": "https://Stackoverflow.com/users/12167812", "pm_score": -1, "selected": true, "text": "private void bunifuFlatButton8_Click(object sender, EventArgs e)\n{\n if (OrderID.Text == \"\" || CustomerID.Text == \"\" || CustName.Text == \"\" || AmountTB.Text ==\"\")\n {\n MessageBox.Show(\"Fill The data Correctly\");\n }\n else\n {\n try\n {\n //Instead of OrderDate.Text use OrderDate.Value.ToString(\"yyyy-MM-dd HH:mm:ss.fff\") then you will have correct format for SQL Insert\n using(SqlCommand cmd = new SqlCommand(\"insert into OrderTB values(\" + OrderID.Text + \",\" + CustomerID.Text + \",'\" + CustName.Text + \"','\" + OrderDate.Value.ToString(\"yyyy-MM-dd HH:mm:ss.fff\") + \"',\" + AmountTB.Text + \")\", Con))\n {\n Con.Open();\n cmd.ExecuteNonQuery();\n MessageBox.Show(\"Order Successfully Added\");\n Con.Close();\n populate();\n }\n }\n catch(Exception ex)\n {\n MessageBox.Show(\"I got an error : \" + ex.Message); // This will give you error message instead of stopping your program\n }\n } \n}\n" }, { "answer_id": 74497653, "author": "vivek nuna", "author_id": 6527049, "author_profile": "https://Stackoverflow.com/users/6527049", "pm_score": 0, "selected": false, "text": "DateTime using null null ExecuteNonQuery" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20545003/" ]
74,497,573
<p>I'm a junior web developer trying to develop my first Ruby on Rails project. I'm following this guide to deploy the app on render.com.</p> <p>However, after installing rails and following this command to create a database (I'm on Ubuntu):</p> <pre><code>rails db:create </code></pre> <p>I come across this problem in command window:</p> <pre><code> We could not find your database: postgres. Which can be found in the database configuration file located at config/database.yml. To resolve this issue: - Did you create the database for this app, or delete it? You may need to create your database. - Has the database name changed? Check your database.yml config has the correct database name. To create your database, run: bin/rails db:create Couldn't create 'mysite_development' database. Please check your configuration. rails aborted! ActiveRecord::NoDatabaseError: We could not find your database: postgres. Which can be found in the database configuration file located at config/database.yml. To resolve this issue: - Did you create the database for this app, or delete it? You may need to create your database. - Has the database name changed? Check your database.yml config has the correct database name. To create your database, run: bin/rails db:create Caused by: PG::ConnectionBad: connection to server on socket &quot;/var/run/postgresql/.s.PGSQL.5432&quot; failed: No such file or directory Is the server running locally and accepting connections on that socket? </code></pre> <p>It says we couldnt find your database. But I have it in config/database.yml:</p> <pre><code> # PostgreSQL. Versions 9.3 and up are supported. # # Install the pg driver: # gem install pg # On macOS with Homebrew: # gem install pg -- --with-pg-config=/usr/local/bin/pg_config # On macOS with MacPorts: # gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config # On Windows: # gem install pg # Choose the win32 build. # Install PostgreSQL and put its /bin directory on your path. # # Configure Using Gemfile # gem &quot;pg&quot; # default: &amp;default adapter: postgresql encoding: unicode # For details on connection pooling, see Rails configuration guide # https://guides.rubyonrails.org/configuring.html#database-pooling pool: &lt;%= ENV.fetch(&quot;RAILS_MAX_THREADS&quot;) { 5 } %&gt; development: &lt;&lt;: *default database: mysite_development # The specified database role being used to connect to postgres. # To create additional roles in postgres see `$ createuser --help`. # When left blank, postgres will use the default role. This is # the same name as the operating system user running Rails. #username: mysite # The password associated with the postgres role (username). #password: # Connect on a TCP socket. Omitted by default since the client uses a # domain socket that doesn't need configuration. Windows does not have # domain sockets, so uncomment these lines. #host: localhost # The TCP port the server listens on. Defaults to 5432. # If your server runs on a different port number, change accordingly. #port: 5432 # Schema search path. The server defaults to $user,public #schema_search_path: myapp,sharedapp,public # Minimum log levels, in increasing order: # debug5, debug4, debug3, debug2, debug1, # log, notice, warning, error, fatal, and panic # Defaults to warning. #min_messages: notice # Warning: The database defined as &quot;test&quot; will be erased and # re-generated from your development database when you run &quot;rake&quot;. # Do not set this db to the same as development or production. test: &lt;&lt;: *default database: mysite_test # As with config/credentials.yml, you never want to store sensitive information, # like your database password, in your source code. If your source code is # ever seen by anyone, they now have access to your database. # # Instead, provide the password or a full connection URL as an environment # variable when you boot the app. For example: # # DATABASE_URL=&quot;postgres://myuser:mypass@localhost/somedatabase&quot; # # If the connection URL is provided in the special DATABASE_URL environment # variable, Rails will automatically merge its configuration values on top of # the values provided in this file. Alternatively, you can specify a connection # URL environment variable explicitly: # # production: # url: &lt;%= ENV[&quot;MY_APP_DATABASE_URL&quot;] %&gt; # # Read https://guides.rubyonrails.org/configuring.html#configuring-a-database # for a full overview on how database connection configuration can be specified. # production: &lt;&lt;: *default database: mysite_production username: mysite password: &lt;%= ENV[&quot;MYSITE_DATABASE_PASSWORD&quot;] %&gt; </code></pre> <p>What should I do? I'm going crazy over this.</p> <p>I tried a different command:</p> <pre><code> bin/rails db:create </code></pre> <p>also didn't work.</p>
[ { "answer_id": 74497735, "author": "dwhitemv", "author_id": 20545176, "author_profile": "https://Stackoverflow.com/users/20545176", "pm_score": 0, "selected": false, "text": "sudo systemctl start postgresql" }, { "answer_id": 74514012, "author": "Monarch Wadia", "author_id": 1204556, "author_profile": "https://Stackoverflow.com/users/1204556", "pm_score": -1, "selected": false, "text": "EDIT: Probably not the right answer for most people, since it seems to be a DB connection issue for OP. But this did catch me out. Hopefully someone else with the same circumstances as I can find this thread helpful in the future. database.yml database.yml default: &default\n adapter: postgresql\n encoding: unicode\n # For details on connection pooling, see Rails configuration guide\n # https://guides.rubyonrails.org/configuring.html#database-pooling\n pool: <%= ENV.fetch(\"RAILS_MAX_THREADS\") { 5 } %>\n default development test production rails db:create development test production default database default postgres default &default <<: *default default development development: &default\n <<: *default\n adapter: postgresql\n encoding: unicode\n # For details on connection pooling, see Rails configuration guide\n # https://guides.rubyonrails.org/configuring.html#database-pooling\n pool: <%= ENV.fetch(\"RAILS_MAX_THREADS\") { 5 } %>\n database: mysite_development\n # PostgreSQL. Versions 9.3 and up are supported.\n#\n# Install the pg driver:\n# gem install pg\n# On macOS with Homebrew:\n# gem install pg -- --with-pg-config=/usr/local/bin/pg_config\n# On macOS with MacPorts:\n# gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config\n# On Windows:\n# gem install pg\n# Choose the win32 build.\n# Install PostgreSQL and put its /bin directory on your path.\n#\n# Configure Using Gemfile\n# gem \"pg\"\n#\n\ndevelopment: &default\n <<: *default\n adapter: postgresql\n encoding: unicode\n # For details on connection pooling, see Rails configuration guide\n # https://guides.rubyonrails.org/configuring.html#database-pooling\n pool: <%= ENV.fetch(\"RAILS_MAX_THREADS\") { 5 } %>\n database: mysite_development\n\n # The specified database role being used to connect to postgres.\n # To create additional roles in postgres see `$ createuser --help`.\n # When left blank, postgres will use the default role. This is\n # the same name as the operating system user running Rails.\n #username: mysite\n\n # The password associated with the postgres role (username).\n #password:\n\n # Connect on a TCP socket. Omitted by default since the client uses a\n # domain socket that doesn't need configuration. Windows does not have\n # domain sockets, so uncomment these lines.\n #host: localhost\n\n # The TCP port the server listens on. Defaults to 5432.\n # If your server runs on a different port number, change accordingly.\n #port: 5432\n\n # Schema search path. The server defaults to $user,public\n #schema_search_path: myapp,sharedapp,public\n\n # Minimum log levels, in increasing order:\n # debug5, debug4, debug3, debug2, debug1,\n # log, notice, warning, error, fatal, and panic\n # Defaults to warning.\n #min_messages: notice\n\n# Warning: The database defined as \"test\" will be erased and\n# re-generated from your development database when you run \"rake\".\n# Do not set this db to the same as development or production.\ntest:\n <<: *default\n database: mysite_test\n\n# As with config/credentials.yml, you never want to store sensitive information,\n# like your database password, in your source code. If your source code is\n# ever seen by anyone, they now have access to your database.\n#\n# Instead, provide the password or a full connection URL as an environment\n# variable when you boot the app. For example:\n#\n# DATABASE_URL=\"postgres://myuser:mypass@localhost/somedatabase\"\n#\n# If the connection URL is provided in the special DATABASE_URL environment\n# variable, Rails will automatically merge its configuration values on top of\n# the values provided in this file. Alternatively, you can specify a connection\n# URL environment variable explicitly:\n#\n# production:\n# url: <%= ENV[\"MY_APP_DATABASE_URL\"] %>\n#\n# Read https://guides.rubyonrails.org/configuring.html#configuring-a-database\n# for a full overview on how database connection configuration can be specified.\n#\nproduction:\n <<: *default\n database: mysite_production\n username: mysite\n password: <%= ENV[\"MYSITE_DATABASE_PASSWORD\"] %>\n\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20544975/" ]
74,497,596
<p><a href="https://i.stack.imgur.com/MCmuO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MCmuO.png" alt="enter image description here" /></a></p> <p>Here, line segment ab is cast upward on arbitrary vector n where I do somethings to find the black point on the line segment cd. My question is, how do I find the point on ab that intersects with the inverted n vector coming down from the new point?</p>
[ { "answer_id": 74497735, "author": "dwhitemv", "author_id": 20545176, "author_profile": "https://Stackoverflow.com/users/20545176", "pm_score": 0, "selected": false, "text": "sudo systemctl start postgresql" }, { "answer_id": 74514012, "author": "Monarch Wadia", "author_id": 1204556, "author_profile": "https://Stackoverflow.com/users/1204556", "pm_score": -1, "selected": false, "text": "EDIT: Probably not the right answer for most people, since it seems to be a DB connection issue for OP. But this did catch me out. Hopefully someone else with the same circumstances as I can find this thread helpful in the future. database.yml database.yml default: &default\n adapter: postgresql\n encoding: unicode\n # For details on connection pooling, see Rails configuration guide\n # https://guides.rubyonrails.org/configuring.html#database-pooling\n pool: <%= ENV.fetch(\"RAILS_MAX_THREADS\") { 5 } %>\n default development test production rails db:create development test production default database default postgres default &default <<: *default default development development: &default\n <<: *default\n adapter: postgresql\n encoding: unicode\n # For details on connection pooling, see Rails configuration guide\n # https://guides.rubyonrails.org/configuring.html#database-pooling\n pool: <%= ENV.fetch(\"RAILS_MAX_THREADS\") { 5 } %>\n database: mysite_development\n # PostgreSQL. Versions 9.3 and up are supported.\n#\n# Install the pg driver:\n# gem install pg\n# On macOS with Homebrew:\n# gem install pg -- --with-pg-config=/usr/local/bin/pg_config\n# On macOS with MacPorts:\n# gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config\n# On Windows:\n# gem install pg\n# Choose the win32 build.\n# Install PostgreSQL and put its /bin directory on your path.\n#\n# Configure Using Gemfile\n# gem \"pg\"\n#\n\ndevelopment: &default\n <<: *default\n adapter: postgresql\n encoding: unicode\n # For details on connection pooling, see Rails configuration guide\n # https://guides.rubyonrails.org/configuring.html#database-pooling\n pool: <%= ENV.fetch(\"RAILS_MAX_THREADS\") { 5 } %>\n database: mysite_development\n\n # The specified database role being used to connect to postgres.\n # To create additional roles in postgres see `$ createuser --help`.\n # When left blank, postgres will use the default role. This is\n # the same name as the operating system user running Rails.\n #username: mysite\n\n # The password associated with the postgres role (username).\n #password:\n\n # Connect on a TCP socket. Omitted by default since the client uses a\n # domain socket that doesn't need configuration. Windows does not have\n # domain sockets, so uncomment these lines.\n #host: localhost\n\n # The TCP port the server listens on. Defaults to 5432.\n # If your server runs on a different port number, change accordingly.\n #port: 5432\n\n # Schema search path. The server defaults to $user,public\n #schema_search_path: myapp,sharedapp,public\n\n # Minimum log levels, in increasing order:\n # debug5, debug4, debug3, debug2, debug1,\n # log, notice, warning, error, fatal, and panic\n # Defaults to warning.\n #min_messages: notice\n\n# Warning: The database defined as \"test\" will be erased and\n# re-generated from your development database when you run \"rake\".\n# Do not set this db to the same as development or production.\ntest:\n <<: *default\n database: mysite_test\n\n# As with config/credentials.yml, you never want to store sensitive information,\n# like your database password, in your source code. If your source code is\n# ever seen by anyone, they now have access to your database.\n#\n# Instead, provide the password or a full connection URL as an environment\n# variable when you boot the app. For example:\n#\n# DATABASE_URL=\"postgres://myuser:mypass@localhost/somedatabase\"\n#\n# If the connection URL is provided in the special DATABASE_URL environment\n# variable, Rails will automatically merge its configuration values on top of\n# the values provided in this file. Alternatively, you can specify a connection\n# URL environment variable explicitly:\n#\n# production:\n# url: <%= ENV[\"MY_APP_DATABASE_URL\"] %>\n#\n# Read https://guides.rubyonrails.org/configuring.html#configuring-a-database\n# for a full overview on how database connection configuration can be specified.\n#\nproduction:\n <<: *default\n database: mysite_production\n username: mysite\n password: <%= ENV[\"MYSITE_DATABASE_PASSWORD\"] %>\n\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20544997/" ]
74,497,624
<p>I'm trying to code a gradebook as a project. So far I have developed the code to calculate exam grades and display the outputs however, I'm having trouble displaying my arrays once the user inputs the information (Student first and last name, ID and Exams) It wont display it. Also my code still wants to add user inputs once I click the cancel button on the browser. I would like the user inputs to stop once I hit the cancel button but how would I fix that?</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;title&gt;Document&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;script&gt; //Initilization of Grades let grade = 0; //Start of the function studentArray(); //Student Function function studentArray(){ const student = [{ firstName :&quot;&quot;, lastName :&quot;&quot;, ID :0, Exams :0 }] while(true){ student.firstName = prompt(&quot;Enter First Name : &quot;); student.lastName = prompt(&quot;Enter Last Name : &quot;); student.ID = prompt(&quot;Enter ID : &quot;); student.Exams = calculateExamgrade(grade); if(student === &quot;e&quot; || student=== null){ break; } student.push(student.firstName); student.push(student.lastName); student.push(student.ID); student.push(student.Exams); } //Displays array for(i = 0; i &lt; studentArray; i++){ console.log(i+1 + studentArray[i]); } } //Calculate the grade of the exams function calculateExamgrade(grade){ let TestGrades = []; while(true){ let input = prompt(&quot;Add Grades&quot;) if(input ===&quot;e&quot; || input === null){ break; } TestGrades.push(Number(input)); } //Calclate the arrays var sum = 0; for(var i in TestGrades){ sum += TestGrades[i]; } //Calculate average grade grade = Math.round((sum/TestGrades.length)); //Return grade letter switch(true){ case grade &gt;= 90: console.log(&quot;You recived an A&quot;) return grade; break; case grade &lt;= 89 &amp;&amp; grade &gt;= 80: console.log(&quot;You recived a B&quot;) return grade; break; case grade &lt;= 79 &amp;&amp; grade &gt;= 70: console.log(&quot;You recived a C&quot;) return grade; break; case grade &lt;= 69 &amp;&amp; grade &gt;= 60: console.log(&quot;You recived a D&quot;) return grade; break; case grade &lt;= 59: return grade; break; } } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 74497735, "author": "dwhitemv", "author_id": 20545176, "author_profile": "https://Stackoverflow.com/users/20545176", "pm_score": 0, "selected": false, "text": "sudo systemctl start postgresql" }, { "answer_id": 74514012, "author": "Monarch Wadia", "author_id": 1204556, "author_profile": "https://Stackoverflow.com/users/1204556", "pm_score": -1, "selected": false, "text": "EDIT: Probably not the right answer for most people, since it seems to be a DB connection issue for OP. But this did catch me out. Hopefully someone else with the same circumstances as I can find this thread helpful in the future. database.yml database.yml default: &default\n adapter: postgresql\n encoding: unicode\n # For details on connection pooling, see Rails configuration guide\n # https://guides.rubyonrails.org/configuring.html#database-pooling\n pool: <%= ENV.fetch(\"RAILS_MAX_THREADS\") { 5 } %>\n default development test production rails db:create development test production default database default postgres default &default <<: *default default development development: &default\n <<: *default\n adapter: postgresql\n encoding: unicode\n # For details on connection pooling, see Rails configuration guide\n # https://guides.rubyonrails.org/configuring.html#database-pooling\n pool: <%= ENV.fetch(\"RAILS_MAX_THREADS\") { 5 } %>\n database: mysite_development\n # PostgreSQL. Versions 9.3 and up are supported.\n#\n# Install the pg driver:\n# gem install pg\n# On macOS with Homebrew:\n# gem install pg -- --with-pg-config=/usr/local/bin/pg_config\n# On macOS with MacPorts:\n# gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config\n# On Windows:\n# gem install pg\n# Choose the win32 build.\n# Install PostgreSQL and put its /bin directory on your path.\n#\n# Configure Using Gemfile\n# gem \"pg\"\n#\n\ndevelopment: &default\n <<: *default\n adapter: postgresql\n encoding: unicode\n # For details on connection pooling, see Rails configuration guide\n # https://guides.rubyonrails.org/configuring.html#database-pooling\n pool: <%= ENV.fetch(\"RAILS_MAX_THREADS\") { 5 } %>\n database: mysite_development\n\n # The specified database role being used to connect to postgres.\n # To create additional roles in postgres see `$ createuser --help`.\n # When left blank, postgres will use the default role. This is\n # the same name as the operating system user running Rails.\n #username: mysite\n\n # The password associated with the postgres role (username).\n #password:\n\n # Connect on a TCP socket. Omitted by default since the client uses a\n # domain socket that doesn't need configuration. Windows does not have\n # domain sockets, so uncomment these lines.\n #host: localhost\n\n # The TCP port the server listens on. Defaults to 5432.\n # If your server runs on a different port number, change accordingly.\n #port: 5432\n\n # Schema search path. The server defaults to $user,public\n #schema_search_path: myapp,sharedapp,public\n\n # Minimum log levels, in increasing order:\n # debug5, debug4, debug3, debug2, debug1,\n # log, notice, warning, error, fatal, and panic\n # Defaults to warning.\n #min_messages: notice\n\n# Warning: The database defined as \"test\" will be erased and\n# re-generated from your development database when you run \"rake\".\n# Do not set this db to the same as development or production.\ntest:\n <<: *default\n database: mysite_test\n\n# As with config/credentials.yml, you never want to store sensitive information,\n# like your database password, in your source code. If your source code is\n# ever seen by anyone, they now have access to your database.\n#\n# Instead, provide the password or a full connection URL as an environment\n# variable when you boot the app. For example:\n#\n# DATABASE_URL=\"postgres://myuser:mypass@localhost/somedatabase\"\n#\n# If the connection URL is provided in the special DATABASE_URL environment\n# variable, Rails will automatically merge its configuration values on top of\n# the values provided in this file. Alternatively, you can specify a connection\n# URL environment variable explicitly:\n#\n# production:\n# url: <%= ENV[\"MY_APP_DATABASE_URL\"] %>\n#\n# Read https://guides.rubyonrails.org/configuring.html#configuring-a-database\n# for a full overview on how database connection configuration can be specified.\n#\nproduction:\n <<: *default\n database: mysite_production\n username: mysite\n password: <%= ENV[\"MYSITE_DATABASE_PASSWORD\"] %>\n\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20429705/" ]
74,497,652
<p>Trying to get the submenu items in antd scrollable, with the below code</p> <p>Codesandbox Link: <a href="https://codesandbox.io/s/dazzling-antonelli-t4g3nu?file=/index.js" rel="nofollow noreferrer">https://codesandbox.io/s/dazzling-antonelli-t4g3nu?file=/index.js</a></p> <pre><code>import ReactDOM from &quot;react-dom&quot;; import &quot;antd/dist/antd.css&quot;; import &quot;./index.css&quot;; import { Menu, Icon } from &quot;antd&quot;; const { SubMenu } = Menu; function handleClick(e) { console.log(&quot;click&quot;, e); } const options = [ { key: &quot;1&quot;, value: &quot;option1&quot; }, { key: &quot;2&quot;, value: &quot;option12&quot; }, { key: &quot;3&quot;, value: &quot;option13&quot; }, { key: &quot;4&quot;, value: &quot;option14&quot; }, { key: &quot;5&quot;, value: &quot;option15&quot; }, { key: &quot;6&quot;, value: &quot;option16&quot; }, { key: &quot;7&quot;, value: &quot;option17&quot; }, { key: &quot;8&quot;, value: &quot;option18&quot; }, { key: &quot;9&quot;, value: &quot;option19&quot; }, { key: &quot;10&quot;, value: &quot;option134&quot; }, { key: &quot;11&quot;, value: &quot;option132&quot; }, { key: &quot;12&quot;, value: &quot;option142&quot; }, { key: &quot;13&quot;, value: &quot;option123&quot; } ]; ReactDOM.render( &lt;Menu onClick={handleClick} style={{ width: 256 }} mode=&quot;vertical&quot;&gt; &lt;SubMenu key=&quot;sub4&quot; title={ &lt;span&gt; &lt;Icon type=&quot;setting&quot; /&gt; &lt;span&gt;Navigation Three&lt;/span&gt; &lt;/span&gt; } &gt; &lt;div style={{ height: &quot;100px&quot;, overflow: &quot;scroll&quot; }}&gt; {options?.map((data) =&gt; { return &lt;li style={{ lineHeight: &quot;20px&quot; }}&gt; {data?.value} &lt;/li&gt;; })} &lt;/div&gt; &lt;/SubMenu&gt; &lt;/Menu&gt;, document.getElementById(&quot;container&quot;) ); </code></pre> <p>the items displayed in submenu is not scrollable even though the scroll icon is present, need some help in fixing it. Thanks.</p>
[ { "answer_id": 74497724, "author": "sms", "author_id": 16835747, "author_profile": "https://Stackoverflow.com/users/16835747", "pm_score": 3, "selected": true, "text": "<SubMenu\n key=\"sub4\"\n title={\n <span>\n <Icon type=\"setting\" />\n <span>Navigation Three</span>\n </span>\n }\n >\n {options?.map((data) => {\n return <Menu.Item> {data?.value} </Menu.Item>;\n })}\n </SubMenu>\n .ant-menu-submenu-popup {\n max-height: 100px ;\n overflow: auto ;\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8146699/" ]
74,497,661
<p>Suppose I have <strong>N</strong> float variables <code>x0</code>, <code>x1</code>, <code>x2</code>, ..., <code>xn</code>.</p> <p>I basically want to loop through each of them and sum them all in a final variable <code>sum</code>.</p> <p>I'm in a context where I cannot make use of data structures like arrays, vectors, etc. If it helps, in my context <strong>N</strong> is always less than 10.</p> <p>Is it possible to make a <code>for</code> loop to do this?</p> <hr /> <p>My first thought was using macros like the concatenate (<code>##</code>) or something like that but I guess it won't fit my case.</p>
[ { "answer_id": 74497745, "author": "Iłya Bursov", "author_id": 2864275, "author_profile": "https://Stackoverflow.com/users/2864275", "pm_score": 2, "selected": true, "text": "#define SUM_X0 (x0)\n#define SUM_X1 (SUM_X0 + x1)\n#define SUM_X2 (SUM_X1 + x2)\n#define SUM_X3 (SUM_X2 + x3)\n#define SUM_X4 (SUM_X3 + x4)\n#define SUM_X5 (SUM_X4 + x5)\n#define SUM_X6 (SUM_X5 + x6)\n#define SUM_X7 (SUM_X6 + x7)\n#define SUM_X8 (SUM_X7 + x8)\n#define SUM_X9 (SUM_X8 + x9)\n\nint main(int argc, char* argv[]) {\n\n int x0, x1, x2, x3, x4, x5;\n if (scanf(\"%d %d %d %d %d %d\", &x0, &x1, &x2, &x3, &x4, &x5) != 6) {\n printf(\"error\");\n return 1;\n }\n\n printf(\"%d\\n\", SUM_X0);\n printf(\"%d\\n\", SUM_X1);\n printf(\"%d\\n\", SUM_X2);\n printf(\"%d\\n\", SUM_X3);\n printf(\"%d\\n\", SUM_X4);\n printf(\"%d\\n\", SUM_X5);\n\n return 0;\n}\n" }, { "answer_id": 74498594, "author": "fabian", "author_id": 2991525, "author_profile": "https://Stackoverflow.com/users/2991525", "pm_score": 0, "selected": false, "text": "malloc /**\n * Execute the desired logic with \\p inputText as content of the input\n */\nvoid Test(char const* inputText)\n{\n std::allocator<float> allocator;\n\n size_t const n = 9;\n\n auto deleter = [n, &allocator](float* mem) {allocator.deallocate(mem, n); };\n\n // notAnArray makes sure the memory gets freed by calling allocator.deallocate(<allocated memory>, n)\n std::unique_ptr<float[], decltype(deleter)> notAnArray{ allocator.allocate(n), deleter };\n\n std::istringstream input{inputText};\n\n size_t count = 0;\n\n for (; count != n; ++count)\n {\n if (!(input >> notAnArray[count]))\n {\n break;\n }\n }\n\n std::cout << count << \" elements read\\n\";\n\n float sum = 0;\n for (size_t i = 0; i != count; ++i)\n {\n sum += notAnArray[i];\n }\n\n std::cout << \"sum = \" << sum << \"\\n------------------------\\n\";\n}\n\nint main()\n{\n Test(\"1 2 3 4 5 6 7 8 9 10\");\n Test(\"\");\n Test(\"5 4 32 1\");\n}\n \nconstexpr size_t MaxCount = 9;\n\nstruct NotAnArray\n{\n float x0;\n float x1;\n float x2;\n float x3;\n float x4;\n float x5;\n float x6;\n float x7;\n float x8;\n};\n\nstatic_assert((offsetof(NotAnArray, x8) - offsetof(NotAnArray, x0)) == (sizeof(float) * (MaxCount - 1)));\n\n/**\n * Execute the desired logic with \\p inputText as content of the input\n */\nvoid Test(char const* inputText)\n{\n NotAnArray storage;\n float* const notAnArray = &storage.x0;\n\n std::istringstream input{inputText};\n\n size_t count = 0;\n\n for (; count != MaxCount; ++count)\n {\n if (!(input >> notAnArray[count]))\n {\n break;\n }\n }\n\n std::cout << count << \" elements read\\n\";\n\n float sum = 0;\n for (size_t i = 0; i != count; ++i)\n {\n sum += notAnArray[i];\n }\n\n std::cout << \"sum = \" << sum << \"\\n------------------------\\n\";\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5348875/" ]
74,497,703
<p>I created a page that displays goods, next to every good there is a button with which you can select or deselect the good. My problem is, when I click on any of my buttons, all buttons change. How can I make it so that the callback function responsible for changing the state of the button only applies to the one that has been clicked?</p> <pre><code>import React from 'react'; import { useState } from 'react'; import 'bulma/css/bulma.css'; import './App.scss'; export const goods = [ 'Dumplings', 'Carrot', 'Eggs', 'Ice cream', 'Apple', 'Bread', 'Fish', 'Honey', 'Jam', 'Garlic', ]; export const App: React.FC = () =&gt; { const [selected, selectGood] = useState(true); const [selectedGood, changeSelectedGood] = useState(goods[0]) const handleChange = (button: any) =&gt; { changeSelectedGood(button.target.id); return selectGood(!selected); } const clearAll = () =&gt; { return selectGood(!selected); } return ( &lt;main className=&quot;section container&quot;&gt; {!selected &amp;&amp; ( &lt;h1 className=&quot;title&quot;&gt;No goods selected&lt;/h1&gt; )} {/* eslint-disable-next-line jsx-a11y/control-has-associated-label */} {selected &amp;&amp; ( &lt;h1 className=&quot;title is-flex is-align-items-center&quot;&gt; {selectedGood + ' is selected'} &lt;button data-cy=&quot;ClearButton&quot; type=&quot;button&quot; className=&quot;delete ml-3&quot; onClick={clearAll} /&gt; &lt;/h1&gt; )} &lt;table className=&quot;table&quot;&gt; &lt;tbody&gt; {goods.map((good) =&gt; ( &lt;tr data-cy=&quot;Good&quot; key={good} className={selected ? &quot;has-background-success-light&quot; : &quot;&quot; } &gt; &lt;td&gt; {good &amp;&amp; ( &lt;button data-cy=&quot;AddButton&quot; type=&quot;button&quot; className={&quot;button&quot;} id={good} onClick={(good) =&gt; {handleChange(good)}} &gt; {selected ? '-' : '+'} &lt;/button&gt; )} &lt;/td&gt; &lt;td data-cy=&quot;GoodTitle&quot; className=&quot;is-vcentered&quot; &gt; {good} &lt;/td&gt; &lt;/tr&gt; ))} &lt;/tbody&gt; &lt;/table&gt; &lt;/main&gt; ) } </code></pre>
[ { "answer_id": 74497745, "author": "Iłya Bursov", "author_id": 2864275, "author_profile": "https://Stackoverflow.com/users/2864275", "pm_score": 2, "selected": true, "text": "#define SUM_X0 (x0)\n#define SUM_X1 (SUM_X0 + x1)\n#define SUM_X2 (SUM_X1 + x2)\n#define SUM_X3 (SUM_X2 + x3)\n#define SUM_X4 (SUM_X3 + x4)\n#define SUM_X5 (SUM_X4 + x5)\n#define SUM_X6 (SUM_X5 + x6)\n#define SUM_X7 (SUM_X6 + x7)\n#define SUM_X8 (SUM_X7 + x8)\n#define SUM_X9 (SUM_X8 + x9)\n\nint main(int argc, char* argv[]) {\n\n int x0, x1, x2, x3, x4, x5;\n if (scanf(\"%d %d %d %d %d %d\", &x0, &x1, &x2, &x3, &x4, &x5) != 6) {\n printf(\"error\");\n return 1;\n }\n\n printf(\"%d\\n\", SUM_X0);\n printf(\"%d\\n\", SUM_X1);\n printf(\"%d\\n\", SUM_X2);\n printf(\"%d\\n\", SUM_X3);\n printf(\"%d\\n\", SUM_X4);\n printf(\"%d\\n\", SUM_X5);\n\n return 0;\n}\n" }, { "answer_id": 74498594, "author": "fabian", "author_id": 2991525, "author_profile": "https://Stackoverflow.com/users/2991525", "pm_score": 0, "selected": false, "text": "malloc /**\n * Execute the desired logic with \\p inputText as content of the input\n */\nvoid Test(char const* inputText)\n{\n std::allocator<float> allocator;\n\n size_t const n = 9;\n\n auto deleter = [n, &allocator](float* mem) {allocator.deallocate(mem, n); };\n\n // notAnArray makes sure the memory gets freed by calling allocator.deallocate(<allocated memory>, n)\n std::unique_ptr<float[], decltype(deleter)> notAnArray{ allocator.allocate(n), deleter };\n\n std::istringstream input{inputText};\n\n size_t count = 0;\n\n for (; count != n; ++count)\n {\n if (!(input >> notAnArray[count]))\n {\n break;\n }\n }\n\n std::cout << count << \" elements read\\n\";\n\n float sum = 0;\n for (size_t i = 0; i != count; ++i)\n {\n sum += notAnArray[i];\n }\n\n std::cout << \"sum = \" << sum << \"\\n------------------------\\n\";\n}\n\nint main()\n{\n Test(\"1 2 3 4 5 6 7 8 9 10\");\n Test(\"\");\n Test(\"5 4 32 1\");\n}\n \nconstexpr size_t MaxCount = 9;\n\nstruct NotAnArray\n{\n float x0;\n float x1;\n float x2;\n float x3;\n float x4;\n float x5;\n float x6;\n float x7;\n float x8;\n};\n\nstatic_assert((offsetof(NotAnArray, x8) - offsetof(NotAnArray, x0)) == (sizeof(float) * (MaxCount - 1)));\n\n/**\n * Execute the desired logic with \\p inputText as content of the input\n */\nvoid Test(char const* inputText)\n{\n NotAnArray storage;\n float* const notAnArray = &storage.x0;\n\n std::istringstream input{inputText};\n\n size_t count = 0;\n\n for (; count != MaxCount; ++count)\n {\n if (!(input >> notAnArray[count]))\n {\n break;\n }\n }\n\n std::cout << count << \" elements read\\n\";\n\n float sum = 0;\n for (size_t i = 0; i != count; ++i)\n {\n sum += notAnArray[i];\n }\n\n std::cout << \"sum = \" << sum << \"\\n------------------------\\n\";\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18126421/" ]
74,497,712
<p>I would like to know how to make new columns that are row sums of existing columns using a loop. Given this data,</p> <pre><code>df &lt;- data.frame(A=c(22, 25, 29, 13, 22, 30), B=c(12, 10, 6, 6, 8, 11), C=c(NA, 15, 15, 18, 22, 13)) </code></pre> <p>I would like to make two columns called a1 and a2, where a1 is the row sums of columns A and B, and a2 is the row sums of columns A, B, and C.</p> <p>The desired output would look as follows.</p> <pre><code>+----+----+----+----+----+ | A | B | C | a1 | a2 | +----+----+----+----+----+ | 22 | 12 | NA | 34 | 34 | | 25 | 10 | 15 | 35 | 50 | | 29 | 6 | 15 | 35 | 50 | | 13 | 6 | 18 | 19 | 37 | | 22 | 8 | 22 | 30 | 52 | | 30 | 11 | 13 | 41 | 54 | +----+----+----+----+----+ </code></pre> <p>I tried the following methods, but these methods are giving me errors.</p> <p>First, I tried using dplyr</p> <pre><code>for(i in 1:2) { df&lt;-df%&gt;% mutate_(paste0(&quot;a&quot;,i)= rowSums(df[,1:(1+i)],na.rm=TRUE)) } </code></pre> <p>Second, I tried using data.table</p> <pre><code>for(i in 1:2) { df&lt;-df[,paste0(&quot;a&quot;,i) := rowSums(df[,1:(1+i)])] } </code></pre> <p>I would like to know how to get the desired output in both ways Also, I think using a loop may not be the best method. I also would like to know how to do this using &quot;apply&quot; functions, if possible.</p> <p>Thank you so much in advance!</p>
[ { "answer_id": 74497745, "author": "Iłya Bursov", "author_id": 2864275, "author_profile": "https://Stackoverflow.com/users/2864275", "pm_score": 2, "selected": true, "text": "#define SUM_X0 (x0)\n#define SUM_X1 (SUM_X0 + x1)\n#define SUM_X2 (SUM_X1 + x2)\n#define SUM_X3 (SUM_X2 + x3)\n#define SUM_X4 (SUM_X3 + x4)\n#define SUM_X5 (SUM_X4 + x5)\n#define SUM_X6 (SUM_X5 + x6)\n#define SUM_X7 (SUM_X6 + x7)\n#define SUM_X8 (SUM_X7 + x8)\n#define SUM_X9 (SUM_X8 + x9)\n\nint main(int argc, char* argv[]) {\n\n int x0, x1, x2, x3, x4, x5;\n if (scanf(\"%d %d %d %d %d %d\", &x0, &x1, &x2, &x3, &x4, &x5) != 6) {\n printf(\"error\");\n return 1;\n }\n\n printf(\"%d\\n\", SUM_X0);\n printf(\"%d\\n\", SUM_X1);\n printf(\"%d\\n\", SUM_X2);\n printf(\"%d\\n\", SUM_X3);\n printf(\"%d\\n\", SUM_X4);\n printf(\"%d\\n\", SUM_X5);\n\n return 0;\n}\n" }, { "answer_id": 74498594, "author": "fabian", "author_id": 2991525, "author_profile": "https://Stackoverflow.com/users/2991525", "pm_score": 0, "selected": false, "text": "malloc /**\n * Execute the desired logic with \\p inputText as content of the input\n */\nvoid Test(char const* inputText)\n{\n std::allocator<float> allocator;\n\n size_t const n = 9;\n\n auto deleter = [n, &allocator](float* mem) {allocator.deallocate(mem, n); };\n\n // notAnArray makes sure the memory gets freed by calling allocator.deallocate(<allocated memory>, n)\n std::unique_ptr<float[], decltype(deleter)> notAnArray{ allocator.allocate(n), deleter };\n\n std::istringstream input{inputText};\n\n size_t count = 0;\n\n for (; count != n; ++count)\n {\n if (!(input >> notAnArray[count]))\n {\n break;\n }\n }\n\n std::cout << count << \" elements read\\n\";\n\n float sum = 0;\n for (size_t i = 0; i != count; ++i)\n {\n sum += notAnArray[i];\n }\n\n std::cout << \"sum = \" << sum << \"\\n------------------------\\n\";\n}\n\nint main()\n{\n Test(\"1 2 3 4 5 6 7 8 9 10\");\n Test(\"\");\n Test(\"5 4 32 1\");\n}\n \nconstexpr size_t MaxCount = 9;\n\nstruct NotAnArray\n{\n float x0;\n float x1;\n float x2;\n float x3;\n float x4;\n float x5;\n float x6;\n float x7;\n float x8;\n};\n\nstatic_assert((offsetof(NotAnArray, x8) - offsetof(NotAnArray, x0)) == (sizeof(float) * (MaxCount - 1)));\n\n/**\n * Execute the desired logic with \\p inputText as content of the input\n */\nvoid Test(char const* inputText)\n{\n NotAnArray storage;\n float* const notAnArray = &storage.x0;\n\n std::istringstream input{inputText};\n\n size_t count = 0;\n\n for (; count != MaxCount; ++count)\n {\n if (!(input >> notAnArray[count]))\n {\n break;\n }\n }\n\n std::cout << count << \" elements read\\n\";\n\n float sum = 0;\n for (size_t i = 0; i != count; ++i)\n {\n sum += notAnArray[i];\n }\n\n std::cout << \"sum = \" << sum << \"\\n------------------------\\n\";\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17303844/" ]
74,497,718
<p>in following code: `</p> <pre><code>#include &lt;iostream&gt; struct MyStruct { int i = 1; }; int main() { MyStruct(some); // some is actually a variable name, it compiles, is it in the // c++ standard? std::cout &lt;&lt; some.i &lt;&lt; std::endl; } </code></pre> <p>`</p> <p>why can i initialzie <code>MyStruct(some)</code>? above code compiles and runs</p>
[ { "answer_id": 74497745, "author": "Iłya Bursov", "author_id": 2864275, "author_profile": "https://Stackoverflow.com/users/2864275", "pm_score": 2, "selected": true, "text": "#define SUM_X0 (x0)\n#define SUM_X1 (SUM_X0 + x1)\n#define SUM_X2 (SUM_X1 + x2)\n#define SUM_X3 (SUM_X2 + x3)\n#define SUM_X4 (SUM_X3 + x4)\n#define SUM_X5 (SUM_X4 + x5)\n#define SUM_X6 (SUM_X5 + x6)\n#define SUM_X7 (SUM_X6 + x7)\n#define SUM_X8 (SUM_X7 + x8)\n#define SUM_X9 (SUM_X8 + x9)\n\nint main(int argc, char* argv[]) {\n\n int x0, x1, x2, x3, x4, x5;\n if (scanf(\"%d %d %d %d %d %d\", &x0, &x1, &x2, &x3, &x4, &x5) != 6) {\n printf(\"error\");\n return 1;\n }\n\n printf(\"%d\\n\", SUM_X0);\n printf(\"%d\\n\", SUM_X1);\n printf(\"%d\\n\", SUM_X2);\n printf(\"%d\\n\", SUM_X3);\n printf(\"%d\\n\", SUM_X4);\n printf(\"%d\\n\", SUM_X5);\n\n return 0;\n}\n" }, { "answer_id": 74498594, "author": "fabian", "author_id": 2991525, "author_profile": "https://Stackoverflow.com/users/2991525", "pm_score": 0, "selected": false, "text": "malloc /**\n * Execute the desired logic with \\p inputText as content of the input\n */\nvoid Test(char const* inputText)\n{\n std::allocator<float> allocator;\n\n size_t const n = 9;\n\n auto deleter = [n, &allocator](float* mem) {allocator.deallocate(mem, n); };\n\n // notAnArray makes sure the memory gets freed by calling allocator.deallocate(<allocated memory>, n)\n std::unique_ptr<float[], decltype(deleter)> notAnArray{ allocator.allocate(n), deleter };\n\n std::istringstream input{inputText};\n\n size_t count = 0;\n\n for (; count != n; ++count)\n {\n if (!(input >> notAnArray[count]))\n {\n break;\n }\n }\n\n std::cout << count << \" elements read\\n\";\n\n float sum = 0;\n for (size_t i = 0; i != count; ++i)\n {\n sum += notAnArray[i];\n }\n\n std::cout << \"sum = \" << sum << \"\\n------------------------\\n\";\n}\n\nint main()\n{\n Test(\"1 2 3 4 5 6 7 8 9 10\");\n Test(\"\");\n Test(\"5 4 32 1\");\n}\n \nconstexpr size_t MaxCount = 9;\n\nstruct NotAnArray\n{\n float x0;\n float x1;\n float x2;\n float x3;\n float x4;\n float x5;\n float x6;\n float x7;\n float x8;\n};\n\nstatic_assert((offsetof(NotAnArray, x8) - offsetof(NotAnArray, x0)) == (sizeof(float) * (MaxCount - 1)));\n\n/**\n * Execute the desired logic with \\p inputText as content of the input\n */\nvoid Test(char const* inputText)\n{\n NotAnArray storage;\n float* const notAnArray = &storage.x0;\n\n std::istringstream input{inputText};\n\n size_t count = 0;\n\n for (; count != MaxCount; ++count)\n {\n if (!(input >> notAnArray[count]))\n {\n break;\n }\n }\n\n std::cout << count << \" elements read\\n\";\n\n float sum = 0;\n for (size_t i = 0; i != count; ++i)\n {\n sum += notAnArray[i];\n }\n\n std::cout << \"sum = \" << sum << \"\\n------------------------\\n\";\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18579739/" ]
74,497,722
<p>I have this below code:</p> <pre class="lang-java prettyprint-override"><code>import java.util.HashMap; import java.util.Map; public class Demo { public static void main(String[] args) { Map&lt;String, String&gt; map = new HashMap&lt;&gt;(); map.put(&quot;colors&quot;, &quot;Red, Green, Blue, Purple&quot;); map.entrySet() .stream() .filter(entrySet -&gt; entrySet.getKey().equalsIgnoreCase(&quot;Colors&quot;)) .map(entrySet -&gt; entrySet.getValue().replaceAll(&quot; &quot;, &quot;&quot;).split(&quot;,&quot;)); } } </code></pre> <p>As you can see I am looking for a specific entry in the map and then extracting the value associated with that entry. The value is a String (i.e. <code>Red, Green, Blue, Purple</code>) and I require these comma-delimited colors as a String array. Also, I am removing any white space before splitting this String. Using Streams I was able to get this <code>Stream&lt;String[]&gt;</code> from the above code.</p> <p>But ultimately I need a String array that contains these colors so can anyone tell me how I can collect a String array from this <code>Stream&lt;String[]&gt;</code>?</p> <p>And I want to use just streams, no <code>for</code> loop or enhanced <code>for</code> loop.</p>
[ { "answer_id": 74497755, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "Map<String, String> map = new HashMap<>();\n\nmap.put(\"colors\", \"Red, Green, Blue, Purple\");\nmap.put(\"numbers\", \"One, Two, Three\");\nmap.put(\"COLORS\", \"Yellow, Magenta, Cyan\");\n\nString[] result = map.entrySet().stream()\n .filter(entry -> entry.getKey().equalsIgnoreCase(\"Colors\"))\n .map(entry -> entry.getValue().replaceAll(\" \", \"\").split(\",\"))\n .flatMap(Stream::of)\n .toArray(String[]::new);\n\nSystem.out.println(Arrays.toString(result));\n [Yellow, Magenta, Cyan, Red, Green, Blue, Purple]\n String[] result = map.entrySet().stream()\n .filter(entry -> entry.getKey().equalsIgnoreCase(\"Colors\"))\n .map(entry -> entry.getValue().replaceAll(\" \", \"\").split(\",\"))\n .findFirst().orElse(new String[0]);\n\nSystem.out.println(Arrays.toString(result));\n [Yellow, Magenta, Cyan]\n" }, { "answer_id": 74499988, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 0, "selected": false, "text": "Pattern.splitAsStream() String \"^\\\\p{Alpha}+\" Pattern.splitAsStream() String.split() Pattern.splitAsStream() dropWhile() String.split() public static final Pattern NON_ALPHA = Pattern.compile(\"[^\\\\p{Alpha}]+\");\n Map<String, String> colorsByKey = // initializing the map\n \nString[] result = colorsByKey.entrySet().stream()\n .filter(e -> e.getKey().equalsIgnoreCase(\"colors\"))\n .flatMap(e -> NON_ALPHA.splitAsStream(e.getValue()).dropWhile(String::isEmpty))\n .toArray(String[]::new);\n \"Red, Dark Blue\" \"Red \"DarkBlue\" \"\\\\s*,\\\\s*\" map() .map(s -> s.replaceAll(\"\\\\s*\", \"\"))\n Matcher.results() \"\\\\p{Alpha}+\" Matcher.results() Stream MatchResult MatchResult MatchResult.group() public static final Pattern ALPHA = Pattern.compile(\"\\\\p{Alpha}+\");\n Map<String, String> colorsByKey = // initializing the map\n \nString[] result = colorsByKey.entrySet().stream()\n .filter(e -> e.getKey().equalsIgnoreCase(\"colors\"))\n .flatMap(e -> ALPHA.matcher(e.getValue()).results())\n .map(MatchResult::group)\n .toArray(String[]::new);\n \"Red, Dark Blue\" \"[\\\\p{Alpha}\\\\p{Space}]+\" map() .map(s -> s.replaceAll(\"\\\\s*\", \"\"))\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16002380/" ]
74,497,732
<p>I'm new to C and have read that each function may only be defined once, but I can't seem to reconcile this with what I'm seeing in the console. For example, I am able to overwrite the definition of <code>printf</code> without an error or warning:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; extern int printf(const char *__restrict__format, ...) { putchar('a'); } int main() { printf(&quot;Hello, world!&quot;); return 0; } </code></pre> <p>So, I tried looking up the one-definition rule in the standard and found <a href="https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf#page=173" rel="nofollow noreferrer">Section 6.9 (5)</a> on page 155, which says (emphasis added):</p> <blockquote> <p>An <em>external definition</em> is an external declaration that is also a definition of a function (other than an inline definition) or an object. If an identifier delared with external linkage is used in an expression [...], <strong>somewhere in the entire program there shall be exactly one external definition for that identifier; otherwise, there shall be no more than one.</strong></p> </blockquote> <p>My understanding of linkage is very shaky, so I'm not sure if this is the relevant clause or what exactly is meant by &quot;entire program&quot;. <strong>But if I take &quot;entire program&quot; to mean all the stuff in <code>&lt;stdio.h&gt;</code> + my source file, then shouldn't I be prohibited from redefining <code>printf</code> in my source file since it has already been defined earlier in the &quot;entire program&quot; (i.e. in the <code>stdio</code> bit of the program)?</strong></p> <hr /> <p>My apologies if this question is a dupe, I couldn't find any existing answers.</p>
[ { "answer_id": 74499264, "author": "ThongDT", "author_id": 19344229, "author_profile": "https://Stackoverflow.com/users/19344229", "pm_score": -1, "selected": false, "text": "declaration definition declaration" }, { "answer_id": 74500049, "author": "Eric Postpischil", "author_id": 298225, "author_profile": "https://Stackoverflow.com/users/298225", "pm_score": 3, "selected": true, "text": "printf printf printf printf printf printf printf printf cos sin cos sin cos sin cos printf printf(\"Hello, world!\");\nprintf(\"Hello, world!\\n\");\n printf printf printf printf(\"Hello, world!\\n\"); puts call puts printf printf puts" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10841085/" ]
74,497,748
<p>I have this program that I finally finished however I am trying to get it after finishing once to prompt the user &quot;Do you wish to run again? Yes(Y), No(N)&quot;. But I also want it to ask for s2 again, and the ch again as well. Keeping s1 to be the same random string if that makes sense.</p> <p>This is my code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; void s1(char *random); void s2(char *s2_input, int index); void strfilter(char *random, char *s2_input, char replacement); int main() { char run = 'Y'; while(run != 'N') { int s1_index = 41; char s1_random[s1_index]; s1(s1_random); printf(&quot;\ns1 = &quot;); puts(s1_random); printf(&quot;s2 = &quot;); int s2_index = 21; char s2_input[s2_index]; s2(s2_input, s2_index); if(s2_input[1] == '\0') { printf(&quot;size too small&quot;); exit(0); } printf(&quot;ch = &quot;); char replacement = getchar(); printf(&quot;\n&quot;); int filter_index = 41; strfilter(s1_random, s2_input, replacement); printf(&quot;\ns1 filtered = &quot;); puts(s1_random); printf(&quot;Do you wish to run again? Yes(Y), No(N) &quot;); scanf(&quot;%c&quot;, &amp;run); } } void s1(char *random) { int limit = 0; char characters; while((characters = (('A' + (rand() % 26))))) /* random generatro */ { if(limit == 41) { *(random + 41 - 1) = '\0'; break; } *(random + limit) = characters; limit++; } } void s2(char *s2_input, int index) { char array[21] = &quot;123456789012345678901&quot;; /* populated array to make sure no random memory is made */ char input; int count = 0; int check = 0; while((input = getchar() )) { if(input == '\n') { *(s2_input + count) = '\0'; break; } else if(input &lt; 65 || input &gt; 90) { printf(&quot;invalid input&quot;); exit(0); } *(s2_input + count) = input; count++; } index = count; } void strfilter(char *random, char *s2_input, char replacement) /* replacement function */ { while(*s2_input) { char *temp = random; while(*temp) { if(*temp == *s2_input) *temp = replacement; temp++; } s2_input++; } } </code></pre> <p>At first I tried a do-while loop within the main function. But it doesn't seem to work. It just messes up the output of my program and still doesn't prompt the user. Should I create a new function with the sole purpose of prompting the User? If so how would I? Thanks in advance.</p>
[ { "answer_id": 74497961, "author": "Allan Wind", "author_id": 9706, "author_profile": "https://Stackoverflow.com/users/9706", "pm_score": 1, "selected": false, "text": "EOF for(;;)\n {\n int s1_index = 41;\n char s1_random[s1_index];\n s1(s1_random);\n printf(\"\\ns1 = \");\n puts(s1_random);\n printf(\"s2 = \");\n int s2_index = 21;\n char s2_input[s2_index];\n s2(s2_input, s2_index);\n if(s2_input[1] == '\\0')\n {\n printf(\"size too small\");\n exit(0);\n }\n\n printf(\"ch = \");\n int replacement = getchar();\n if(replacement == EOF)\n break;\n while(getchar() != '\\n');\n printf(\"\\n\");\n strfilter(s1_random, s2_input, replacement);\n printf(\"\\ns1 filtered = \");\n puts(s1_random);\n\n printf(\"Do you wish to run again? Yes(Y), No(N) \");\n int run = getchar();\n // or include ctype.h and do:\n // run == EOF || toupper(run) == 'N'\n if(run == EOF || run == 'N' || run == 'n')\n break;\n while(getchar() != '\\n');\n }\n s1 = NWLRBBMQBHCDARZOWKKYHIDDQSCDXRJMOWFRXSJY\ns2 = NWLRBBMQBHCDARZOWKKYHIDDQSCDXRJMOWFRXSJY\nch = B\n\n\ns1 filtered = BBBBBBBB\nDo you wish to run again? Yes(Y), No(N) y\n\ns1 = DBEFSARCBYNECDYGGXXPKLORELLNMPAPQFWKHOPK\ns2 = NWLRBBMQBHCDARZOWKKYHIDDQSCDXRJMOWFRXSJY\nch = B \n\n\ns1 filtered = BBBBBBBB\nDo you wish to run again? Yes(Y), No(N) N\n" }, { "answer_id": 74498188, "author": "Support Ukraine", "author_id": 4386427, "author_profile": "https://Stackoverflow.com/users/4386427", "pm_score": 0, "selected": false, "text": "getchar scanf scanf(\"%c\", &run);\n getchar scanf %c char run = 'Y';\nwhile(run != 'N')\n{\n // ... do your stuff\n\n while(1)\n {\n // notice the space before %c to remove initial white spaces\n if (scanf(\" %c\", &run) != 1) exit(1); // Input error\n\n // Empty the input stream until a newline is found\n while (1)\n {\n int temp = getchar();\n if (temp == '\\n') break; // Found end-of-line so break this while-loop\n if (temp == EOF) exit(1); // Input error\n }\n\n if (run == 'Y' || run == 'N') break; // Valid input so break this while-loop\n }\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20544996/" ]
74,497,752
<p>I'm trying to solve a question from PepCoding, Graph Foundation 1, Shortest Path In Weights, and replicating the solution from Java to Python.</p> <p>Question:</p> <pre><code>1. You are given a graph and a source vertex. The vertices represent cities and the edges represent distance in kms. 2. You are required to find the shortest path to each city (in terms of kms) from the source city along with the total distance on path from source to destinations. Note -&gt; For output, check the sample output and question video. </code></pre> <p>Sample input:</p> <pre><code>7 9 0 1 10 1 2 10 2 3 10 0 3 40 3 4 2 4 5 3 5 6 3 4 6 8 2 5 5 0 </code></pre> <p>Output:</p> <pre><code>0 via 0 @ 0 1 via 01 @ 10 2 via 012 @ 20 5 via 0125 @ 25 4 via 01254 @ 28 6 via 01256 @ 28 3 via 012543 @ 30 </code></pre> <p>I implemented a list instead of PriorityQueue, and trying to sort the <code>Pair</code> element in the class using operator such as <code>__lt__</code> and <code>__ge__ </code>. However, I was getting all the results correct except the shortest path between <code>0</code> and <code>3</code> is incorrect.</p> <p>This is my output:</p> <pre><code>0 via 0 @ 0 1 via 01 @ 10 2 via 012 @ 20 5 via 0125 @ 25 4 via 01254 @ 28 6 via 01256 @ 28 3 via 0123 @ 30 &lt;-- This differ should be: 3 via 012543 @ 30 </code></pre> <pre><code>Loop: [(28, 6, '01256'), (30, 3, '0123'), (40, 3, '03'), (30, 3, '012543')] Loop: [(28, 6, '01256'), (30, 3, '0123'), (40, 3, '03'), (30, 3, '012543'), (36, 6, '012546')] POP: (28, 6, '01256') 6 via 01256 @ 28 POP: (30, 3, '0123') &lt;-- *This is getting pop instead of, POP: (30, 3, '012543') 3 via 0123 @ 30 POP: (30, 3, '012543') POP: (36, 6, '012546') POP: (40, 3, '03') </code></pre> <p>This code in Java where <strong>compareTo</strong> is implemented, is making the difference.</p> <pre><code>static class Pair implements Comparable&lt;Pair&gt; { int v; String psf; int wsf; Pair(int v, String psf, int wsf){ this.v = v; this.psf = psf; this.wsf = wsf; } public int compareTo(Pair o){ return this.wsf - o.wsf; } } </code></pre> <p>Here is the code in Python:</p> <pre><code> class Edge: def __init__(self, src, nbr, wt): self.src = src self.nbr = nbr self.wt = wt def __repr__(self): return repr(self.__dict__) class Pair: def __init__(self, wsf, v, psf): self.wsf = wsf self.v = v self.psf = psf def __repr__(self): return repr((self.wsf, self.v, self.psf)) def __lt__(self, o): return self.wsf &lt; o.wsf def __ge__(self, o): return len(self.psf) &lt; len(o.psf) def main(): vtces = int(input()) edges = int(input()) graph = {} for i in range(vtces): graph[i] = [] for i in range(edges): lines = input().split(&quot; &quot;) v1 = int(lines[0]) v2 = int(lines[1]) wt = int(lines[2]) e1 = Edge(v1, v2, wt) e2 = Edge(v2, v1, wt) graph[e1.src].append(e1) graph[e2.src].append(e2) src = int(input()) # print(type(graph)) # for i in graph: # for j in graph[i]: # print(i, j) # Write your code here pq = [] pq.append(Pair(0, src, str(src) + &quot;&quot;)) # print(&quot;\nStart: &quot;,pq) visited = [False] * vtces while len(pq) &gt; 0: pq.sort() rem = pq.pop(0) # print(&quot;POP: &quot;, rem) if visited[rem.v] == True: continue visited[rem.v] = True print(rem.v, &quot; via &quot;, rem.psf, &quot;@&quot;, rem.wsf) for e in graph[rem.v]: if visited[e.nbr] == False: pq.append(Pair(rem.wsf + e.wt, e.nbr, str(rem.psf) + str(e.nbr))) # print(&quot;Loop: &quot;,pq) # print(pq) if __name__ == &quot;__main__&quot;: main() </code></pre> <p>PS: Please forgive me if I typed or unable to explain properly as I am new to this world and trying my best.</p>
[ { "answer_id": 74497961, "author": "Allan Wind", "author_id": 9706, "author_profile": "https://Stackoverflow.com/users/9706", "pm_score": 1, "selected": false, "text": "EOF for(;;)\n {\n int s1_index = 41;\n char s1_random[s1_index];\n s1(s1_random);\n printf(\"\\ns1 = \");\n puts(s1_random);\n printf(\"s2 = \");\n int s2_index = 21;\n char s2_input[s2_index];\n s2(s2_input, s2_index);\n if(s2_input[1] == '\\0')\n {\n printf(\"size too small\");\n exit(0);\n }\n\n printf(\"ch = \");\n int replacement = getchar();\n if(replacement == EOF)\n break;\n while(getchar() != '\\n');\n printf(\"\\n\");\n strfilter(s1_random, s2_input, replacement);\n printf(\"\\ns1 filtered = \");\n puts(s1_random);\n\n printf(\"Do you wish to run again? Yes(Y), No(N) \");\n int run = getchar();\n // or include ctype.h and do:\n // run == EOF || toupper(run) == 'N'\n if(run == EOF || run == 'N' || run == 'n')\n break;\n while(getchar() != '\\n');\n }\n s1 = NWLRBBMQBHCDARZOWKKYHIDDQSCDXRJMOWFRXSJY\ns2 = NWLRBBMQBHCDARZOWKKYHIDDQSCDXRJMOWFRXSJY\nch = B\n\n\ns1 filtered = BBBBBBBB\nDo you wish to run again? Yes(Y), No(N) y\n\ns1 = DBEFSARCBYNECDYGGXXPKLORELLNMPAPQFWKHOPK\ns2 = NWLRBBMQBHCDARZOWKKYHIDDQSCDXRJMOWFRXSJY\nch = B \n\n\ns1 filtered = BBBBBBBB\nDo you wish to run again? Yes(Y), No(N) N\n" }, { "answer_id": 74498188, "author": "Support Ukraine", "author_id": 4386427, "author_profile": "https://Stackoverflow.com/users/4386427", "pm_score": 0, "selected": false, "text": "getchar scanf scanf(\"%c\", &run);\n getchar scanf %c char run = 'Y';\nwhile(run != 'N')\n{\n // ... do your stuff\n\n while(1)\n {\n // notice the space before %c to remove initial white spaces\n if (scanf(\" %c\", &run) != 1) exit(1); // Input error\n\n // Empty the input stream until a newline is found\n while (1)\n {\n int temp = getchar();\n if (temp == '\\n') break; // Found end-of-line so break this while-loop\n if (temp == EOF) exit(1); // Input error\n }\n\n if (run == 'Y' || run == 'N') break; // Valid input so break this while-loop\n }\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20274823/" ]
74,497,758
<p>I have a problem with the All function. I would like to use the random result of the Template1 function and the random result of the Template2 function. Then I apply another random to the two functions inside All, but I get the error:</p> <pre><code>NameError: the name 'Template1' is not defined </code></pre> <p>How can I fix? By solving the definition, will the script print correctly what I asked? Thank you</p> <p>The output I would like to receive is <strong>only one (1)</strong> of these: &quot;aaa&quot;, &quot;bbb&quot;, &quot;ccc&quot;, &quot;ddd&quot;, &quot;eee&quot;, &quot;fff&quot;</p> <pre><code>import random class Main: def __init__(self): self.templ1 = (&quot;aaa&quot;, &quot;bbb&quot;, &quot;ccc&quot;) self.templ2 = (&quot;ddd&quot;, &quot;eee&quot;, &quot;fff&quot;) def Template1(self): templ1_random = print(random.choice(self.templ1)) return templ1_random def Template2(self): templ2_random = print(random.choice(self.templ2)) return templ2_random def All(self): list0 = [Template1(self), Template2(self)] all_random = print(random.choice(list0)) return all_random final = Main() final.All() </code></pre>
[ { "answer_id": 74497771, "author": "gtj520", "author_id": 19920392, "author_profile": "https://Stackoverflow.com/users/19920392", "pm_score": 0, "selected": false, "text": "list0 = [Template1(self), Template2(self)] [self.Template1(), self.Template2()] def __init__(self):\n self.templ1 = (\"aaa\", \"bbb\", \"ccc\")\n self.templ2 = (\"ddd\", \"eee\", \"fff\")\n\ndef Template1(self):\n templ1_random = random.choice(self.templ1)\n return templ1_random\n\ndef Template2(self):\n templ2_random = random.choice(self.templ2)\n return templ2_random\n\ndef All(self):\n list0 = [self.Template1(), self.Template2()]\n all_random = random.choice(list0)\n return all_random\n\n\nfinal = Main()\nprint(final.All())\n" }, { "answer_id": 74497809, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 2, "selected": true, "text": "print() None print() print(final.All()) import random\n\nclass Main:\n\n def __init__(self):\n self.templ1 = (\"aaa\", \"bbb\", \"ccc\")\n self.templ2 = (\"ddd\", \"eee\", \"fff\")\n\n def Template1(self):\n templ1_random =random.choice(self.templ1)\n return templ1_random\n\n def Template2(self):\n templ2_random = random.choice(self.templ2)\n return templ2_random\n\n def All(self):\n list0 = [self.Template1(), self.Template2()]\n all_random = random.choice(list0)\n return all_random\n\n\nfinal = Main()\nprint(final.All())\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20430033/" ]
74,497,812
<p>I have a warning that says</p> <pre><code>Warning: You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. `Otherwise, set either `onChange` or `readOnly`.` </code></pre> <p>Of course, I have googled a solution for it. One way to fix it is to replace &quot;value&quot; attribute with &quot;defaultValues&quot;. But, this is causing another issue because my component is a controlled.</p> <p>I could add onchange attribute and method to the fields. But the problem is that it will cause redundancy as I have a single onChange method on the tag that manages all the values and states. For example,</p> <pre><code>const [allStates, setAllStates] = useState({value_one: &quot;&quot;, value_two:&quot;&quot;}); function handleOnChange(event){ ......... //update the allStates state here } &lt;Form onChange={handleOnChange}&gt; &lt;input value={allStates.value_one} /&gt; &lt;input value={allStates.value_two} /&gt; &lt;/Form&gt; </code></pre> <p>What are the alternatives I have? Should I just ignore it since I can only see it on dev environments, the end users cannot and won't see it on the prod environment anyway?</p>
[ { "answer_id": 74497930, "author": "Dev-Siri", "author_id": 18646049, "author_profile": "https://Stackoverflow.com/users/18646049", "pm_score": 0, "selected": false, "text": "const [allStates, setAllStates] = useState({\n value_one: 'I will be display in the input initially', // <-- This text will already be entered in the text input.\n value_two: ''\n});\n\n<input value={allStates.value_one} />\n value onChange onChange const [allStates, setAllStates] = useState({\n value_one: '',\n value_two: ''\n});\n\nconst handleOnChange = (event) => {\n setAllStates({\n ...allStates,\n // Now you can target the name prop\n [event.target.name]: event.target.value\n });\n}\n\nreturn (\n <>\n {/* I will suggest adding a name prop also */}\n <input name=\"value_one\" value={allStates.value_one} onChange={handleOnChange} />\n <input name=\"value_two\" value={allStates.value_two} onChange={handleOnChange} />\n </>\n);\n" }, { "answer_id": 74497935, "author": "M. G.", "author_id": 14013535, "author_profile": "https://Stackoverflow.com/users/14013535", "pm_score": 2, "selected": true, "text": "defaultValue defaultValue <input> const [state, setState] = useState({});\n\nconst handleChange = (ev) => {\n setState(prev_state => {\n return {\n ...prev_state,\n [ev.target.name]: ev.target.value\n }\n })\n}\n\n<form onChange={handleChange}>\n <input name={\"foo\"} defaultValue={state.foo}/>\n <input name={\"bar\"} defaultValue={state.bar}/>\n</form>" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6707111/" ]
74,497,867
<p>so I'm making a text-based game in python and I'm trying to create an option which allows the user to return to the question if their answer was incorrect. It works like this:</p> <p>There are three options to a question, 1,2,3. 1 and 3 are the incorrect option which will fail the user, then they will have the option to go back to the question. If a user picks 2 the first time then their answer is correct and they'll be allowed to proceed.</p> <p>The problem is trying to create that option which allows them to go back.</p> <p>I've tried using while loops and if statements. But none of those have worked. with the while loop, i expected that it would print the incorrect answers over and over again until the user picked the correct answer, but it printed the same answer even if the user picked something different.</p> <p>and with if statements, I tried to create a variable which stored the user's input, and then used that variable in an if statement which made it so that when the user pressed &quot;q&quot; the question would print again.</p> <p>I had hoped that when the question would print again, when the user picked a different option it would print the different answer assigned to it, but it instead printed nothing. When I type the incorrect answer, it prints the answer assigned to it, and gives me the option to press q, everything worked accordingly until that point, but when I typed the correct answer, it printed nothing, even though it should've printed a option.</p> <p>Here's the code so you can a better understanding:</p> <pre><code>question_1 = input(&quot;You have three options 1) Try to break the window and escape. 2) Search the house for supplies. 3) Try to contact local authorities. Which do you choose?\n &quot;) if question_1 == &quot;1&quot;: quit = input(&quot;You manage to break the window, but the glass cuts your hand and your face, you scream in pain and as the glass cuts through your face, and eventually die from the wounds. Press q to go back &quot;) if quit == &quot;q&quot;: second = input(&quot;You have three options 1) Try to break the window and escape. 2) Search the house for supplies. 3) Try to contact local authorities. Which do you choose?\n &quot;) if question_1 == &quot;2&quot;: print(&quot;You find an array of supplies in your basement, everything from hammers, tools, weapons and food and water. You then safely break the window and jump out.&quot;) </code></pre> <p>That's the problem I'm facing, I'm not sure what's going on or what the fix is, so hope you all can help me.</p> <p>Note: Also, it prints nothing IF only the incorrect option is chosen first, then the quit option. If I originally chose 2, then it prints the answer assigned to it with no problem.</p>
[ { "answer_id": 74497930, "author": "Dev-Siri", "author_id": 18646049, "author_profile": "https://Stackoverflow.com/users/18646049", "pm_score": 0, "selected": false, "text": "const [allStates, setAllStates] = useState({\n value_one: 'I will be display in the input initially', // <-- This text will already be entered in the text input.\n value_two: ''\n});\n\n<input value={allStates.value_one} />\n value onChange onChange const [allStates, setAllStates] = useState({\n value_one: '',\n value_two: ''\n});\n\nconst handleOnChange = (event) => {\n setAllStates({\n ...allStates,\n // Now you can target the name prop\n [event.target.name]: event.target.value\n });\n}\n\nreturn (\n <>\n {/* I will suggest adding a name prop also */}\n <input name=\"value_one\" value={allStates.value_one} onChange={handleOnChange} />\n <input name=\"value_two\" value={allStates.value_two} onChange={handleOnChange} />\n </>\n);\n" }, { "answer_id": 74497935, "author": "M. G.", "author_id": 14013535, "author_profile": "https://Stackoverflow.com/users/14013535", "pm_score": 2, "selected": true, "text": "defaultValue defaultValue <input> const [state, setState] = useState({});\n\nconst handleChange = (ev) => {\n setState(prev_state => {\n return {\n ...prev_state,\n [ev.target.name]: ev.target.value\n }\n })\n}\n\n<form onChange={handleChange}>\n <input name={\"foo\"} defaultValue={state.foo}/>\n <input name={\"bar\"} defaultValue={state.bar}/>\n</form>" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20408338/" ]
74,497,887
<p>A couple of days ago the code worked, but now it gives an error, please help `</p> <pre class="lang-py prettyprint-override"><code>#оповищение о новом сервере @client.event async def on_guild_join( guild ): me = client.get_user(404915501727219723) emb = discord.Embed( title = f'Я пришел на новый сервер' ) for guild in client.guilds: category = guild.categories[0] try: channel = category.text_channels[0] except: channel = category.voice_channels[0] link = await channel.create_invite() emb.add_field( name = guild.name, value = f&quot;Участников: {len(guild.members)}\nСсылка: {link}&quot; ) await me.send( embed = emb ) </code></pre> <p>`</p> <p>Now it gives this error, didn't find anything on the internet. Here is the error: <a href="https://i.stack.imgur.com/B6zC7.png" rel="nofollow noreferrer">enter image description here</a></p>
[ { "answer_id": 74497930, "author": "Dev-Siri", "author_id": 18646049, "author_profile": "https://Stackoverflow.com/users/18646049", "pm_score": 0, "selected": false, "text": "const [allStates, setAllStates] = useState({\n value_one: 'I will be display in the input initially', // <-- This text will already be entered in the text input.\n value_two: ''\n});\n\n<input value={allStates.value_one} />\n value onChange onChange const [allStates, setAllStates] = useState({\n value_one: '',\n value_two: ''\n});\n\nconst handleOnChange = (event) => {\n setAllStates({\n ...allStates,\n // Now you can target the name prop\n [event.target.name]: event.target.value\n });\n}\n\nreturn (\n <>\n {/* I will suggest adding a name prop also */}\n <input name=\"value_one\" value={allStates.value_one} onChange={handleOnChange} />\n <input name=\"value_two\" value={allStates.value_two} onChange={handleOnChange} />\n </>\n);\n" }, { "answer_id": 74497935, "author": "M. G.", "author_id": 14013535, "author_profile": "https://Stackoverflow.com/users/14013535", "pm_score": 2, "selected": true, "text": "defaultValue defaultValue <input> const [state, setState] = useState({});\n\nconst handleChange = (ev) => {\n setState(prev_state => {\n return {\n ...prev_state,\n [ev.target.name]: ev.target.value\n }\n })\n}\n\n<form onChange={handleChange}>\n <input name={\"foo\"} defaultValue={state.foo}/>\n <input name={\"bar\"} defaultValue={state.bar}/>\n</form>" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20545363/" ]
74,497,917
<p><strong>Context</strong></p> <p>I have a working standard form, with method POST, with a standard submit button, and I would like to leave this in this way.</p> <pre><code>&lt;form id=&quot;myform&quot; method=&quot;post&quot;... &gt; ... &lt;input type=&quot;submit .../&gt; &lt;/form&gt; </code></pre> <p>However in some circumstances, I would like to programmatically send the form data to server side and re-render the form. Sending the form data with GET would be great this case.</p> <p><strong>Question</strong></p> <p>How can I achieve that <code>document.myform.submit();</code> use the GET method, instead the POST what is declared in the <code>&lt;form ...&gt;</code> element?</p>
[ { "answer_id": 74498046, "author": "Rehman Ahmed Khan", "author_id": 14447630, "author_profile": "https://Stackoverflow.com/users/14447630", "pm_score": 0, "selected": false, "text": "<form id=\"my-form\" method=\"post\"... >\n ...\n <button id=\"btn-submit\" type=\"button\" .../>\n</form>\n\n<script>\n const submit = document.getElementById('btn-submit');\n submit.addEventListener('click', function(event) {\n event.preventDefault();\n const form = document.getElementById('my-form');\n if(SOME CONDITION) // some usecases in which we need different method.\n {\n form.method = 'POST';\n } else {\n form.method = 'GET';\n }\n form.submit();\n});\n\n</script>\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1157814/" ]
74,497,924
<pre><code>&lt;!doctype html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;!-- Required meta tags --&gt; &lt;meta charset=&quot;utf-8&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt; &lt;!-- Bootstrap CSS --&gt; &lt;link href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot; integrity=&quot;sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC&quot; crossorigin=&quot;anonymous&quot;&gt; &lt;!-- Own Css --&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;css/style.css&quot;&gt; &lt;title&gt;Tropico&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;!-- Section - 1 Navigation Starts --&gt; &lt;nav class=&quot;navbar navbar-expand-lg&quot;&gt; &lt;div class=&quot;container&quot;&gt; &lt;a href=&quot;#&quot; class=&quot;navbar-brand&quot;&gt;&lt;img src=&quot;img/logo.png&quot; alt=&quot;&quot;&gt;&lt;span&gt;Tropico&lt;/span&gt;&lt;/a&gt; &lt;button class=&quot;navbar-toggler&quot; type=&quot;button&quot; data-toggle=&quot;collapse&quot; data-target=&quot;#navmenu&quot;&gt; &lt;span class=&quot;navbar-toggler-icon&quot;&gt;&lt;/span&gt; &lt;/button&gt; &lt;div class=&quot;collapse navbar-collapse&quot; id=&quot;navmenu&quot;&gt; &lt;ul class=&quot;navbar-nav ms-auto&quot;&gt; &lt;li class=&quot;nav-item&quot;&gt; &lt;a href=&quot;#home&quot; class=&quot;nav-link&quot;&gt;Home&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item&quot;&gt; &lt;a href=&quot;#fruits&quot; class=&quot;nav-link&quot;&gt;Fruits&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item&quot;&gt; &lt;a href=&quot;#service&quot; class=&quot;nav-link&quot;&gt;Services&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item&quot;&gt; &lt;a href=&quot;#contact&quot; class=&quot;nav-link&quot;&gt;Contact us&lt;/a&gt; &lt;/li&gt; &lt;button class=&quot;nav-item&quot;&gt;Get a quote&lt;/button&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/nav&gt; &lt;!-- Section - 1 Navigation End --&gt; &lt;script src=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js&quot; integrity=&quot;sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Nav icon not showing when display goes below 992px as i used navbar-expand-lg in bootstrap5. Nav icon not showing when display goes below 992px as i used navbar-expand-lg in bootstrap5 Nav icon not showing when display goes below 992px as i used navbar-expand-lg in bootstrap5 Nav icon not showing when display goes below 992px as i used navbar-expand-lg in bootstrap5 Nav icon not showing when display goes below 992px as i used navbar-expand-lg in bootstrap5 Nav icon not showing when display goes below 992px as i used navbar-expand-lg in bootstrap5</p>
[ { "answer_id": 74498046, "author": "Rehman Ahmed Khan", "author_id": 14447630, "author_profile": "https://Stackoverflow.com/users/14447630", "pm_score": 0, "selected": false, "text": "<form id=\"my-form\" method=\"post\"... >\n ...\n <button id=\"btn-submit\" type=\"button\" .../>\n</form>\n\n<script>\n const submit = document.getElementById('btn-submit');\n submit.addEventListener('click', function(event) {\n event.preventDefault();\n const form = document.getElementById('my-form');\n if(SOME CONDITION) // some usecases in which we need different method.\n {\n form.method = 'POST';\n } else {\n form.method = 'GET';\n }\n form.submit();\n});\n\n</script>\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20033714/" ]
74,497,938
<p>I have an abstract base class validator with a method which takes a generic type as parameter. I will be passing generic type parameter to base class from the subclass inheriting the base class.</p> <p><strong>Base Class:</strong></p> <pre><code>abstract class BaseValidator { bool isValid&lt;T&gt;(T obj); } </code></pre> <p><strong>Child Class:</strong></p> <pre><code>class IPv4Validator extends BaseValidator{ final IPV4_REGEX = &quot;^((25[0-5]|(2[0-4]|1d|[1-9]|)d).?\b){4}\$&quot;; @override bool isValid&lt;String&gt;(String obj) { bool hasMatch = RegExp(IPV4_REGEX).hasMatch(obj); return hasMatch; } } </code></pre> <p>Here <code>hasMatch</code> takes in non nullable string. When I directly pass some string hasMatch doesn't throw an error. But when I try to pass the generic value in the method parameter, it shows an error.</p> <blockquote> <p>The argument type 'String' can't be assigned to the parameter type 'String'.</p> </blockquote> <p>I couldn't able to understand why generic type is not accepting, even though its compile-time type.</p> <p><a href="https://i.stack.imgur.com/sQGv5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sQGv5.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74498110, "author": "Kasymbek R. Tashbaev", "author_id": 14891973, "author_profile": "https://Stackoverflow.com/users/14891973", "pm_score": 2, "selected": true, "text": "abstract class BaseValidator<T> {\n bool isValid(T obj);\n}\n\nclass IPv4Validator extends BaseValidator<String>{\n final IPV4_REGEX = \"^((25[0-5]|(2[0-4]|1d|[1-9]|)d).?\\b){4}\\$\";\n\n @override\n bool isValid(String obj) {\n bool hasMatch = RegExp(IPV4_REGEX).hasMatch(obj);\n\n return hasMatch;\n }\n}\n class IPv4Validator extends BaseValidator<String> BaseValidator BaseValidator<T> BaseValidator bool isValid<String>(String obj) String bool isValid<String>(String obj) isValid<T>(T obj) T String String" }, { "answer_id": 74498128, "author": "john", "author_id": 16146701, "author_profile": "https://Stackoverflow.com/users/16146701", "pm_score": 0, "selected": false, "text": "covariant abstract class BaseValidator<T> {\n bool isValid(T obj);\n}\n\nclass IPv4Validator extends BaseValidator {\n final IPV4_REGEX = \"^((25[0-5]|(2[0-4]|1d|[1-9]|)d).?\\b){4}\\$\";\n\n @override\n bool isValid(covariant String obj) {\n bool hasMatch = RegExp(IPV4_REGEX).hasMatch(obj);\n return hasMatch;\n }\n}" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9248098/" ]
74,497,942
<p>I have an array of images:</p> <pre><code>const imageArray = Object.entries(profileData.images) //imageArray = [&quot;0&quot;: &quot;http://imagelink1&quot;, &quot;1&quot; : &quot;http://imagelink2&quot;] </code></pre> <p>I am setting an initial state of images array to</p> <pre><code> const [imageUrl, setImageUrl] = useState([ { image: '' }, { image: '' }, { image: '' }, { image: '' }, { image: '' }, { image: '' }, ]) </code></pre> <p>Expected initial state is</p> <pre><code> const [imageUrl, setImageUrl] = useState([ { image: 'http://imagelink1' }, { image: 'http://imagelink2' }, { image: '' }, { image: '' }, { image: '' }, { image: '' }, ]) </code></pre> <p>How to get values from first array and construct this new array of length 6?</p>
[ { "answer_id": 74497980, "author": "Mina", "author_id": 11887902, "author_profile": "https://Stackoverflow.com/users/11887902", "pm_score": 1, "selected": false, "text": "Array n fill map imageArray const [imageUrl, setImageUrl] = useState(Array(6).fill(undefined).map((item, index) => ({ image: imageArray[index] ?? '' })))\n" }, { "answer_id": 74498016, "author": "Nick Parsons", "author_id": 5648954, "author_profile": "https://Stackoverflow.com/users/5648954", "pm_score": 3, "selected": true, "text": "Array.from() imageArray imageArray \"\" ?? const [imageUrl, setImageUrl] = useState(() => \n Array.from({length: 6}, (_, i) => ({image: imageArray[i] ?? \"\"}))\n)\n useState()" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3717114/" ]
74,497,953
<p>I have a dataframe with one column and one row like:</p> <pre><code>list_id 12,13,14,16 </code></pre> <p>The <code>list_id</code> column type is <code>Object</code>:</p> <pre><code>df['list'].dtypes =&gt; Object </code></pre> <p>When I try to get the number of elements in this column</p> <pre><code>l = list(df.list_id) len(l) =&gt; 1 </code></pre> <p>Or</p> <pre><code>len(df['list_id'] =&gt; 1 </code></pre> <p>Why I am getting 1 instead of 4?</p> <p>I want to get the count of elements as 4. What Can I do?</p>
[ { "answer_id": 74498012, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 0, "selected": false, "text": "list_id df['list_id'].str.len()\n ',' df['list_id'].str.count(',') + df['list_id'].ne('')\n 0 4\nName: list_id, dtype: int64\n" }, { "answer_id": 74498018, "author": "Panda Kim", "author_id": 20430449, "author_profile": "https://Stackoverflow.com/users/20430449", "pm_score": 2, "selected": true, "text": "data = {'list_id': {0: '12,13,14,16'}} \ndf = pd.DataFrame(data)\n df['list_id'].str.split(',').str.len()\n 0 4\nName: list_id, dtype: int64\n df['list_id'].str.split(',').str.len()[0]\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19917575/" ]
74,497,994
<p>I made a program to find primes below a given number.</p> <pre><code>number = int(input(&quot;Enter number: &quot;)) prime_numbers = [2] # First prime is needed. for number_to_be_checked in range(3, number + 1): square_root = number_to_be_checked ** 0.5 for checker in prime_numbers: # Checker will become # every prime number below the 'number_to_be_checked' # variable because we are adding all the prime numbers # in the 'prime_numbers' list. if checker &gt; square_root: prime_numbers.append(number_to_be_checked) break elif number_to_be_checked % checker == 0: break print(prime_numbers) </code></pre> <p>This program checks every number below the number given as the input. But primes are of the form <code>6k ± 1</code> only. Therefore, instead of checking all the numbers, I defined a generator that generates all the numbers of form <code>6k ± 1</code> below the number given as the input. (I added 3 also in the <code>prime_numbers</code> list while initializing it as <code>2,3</code> cannot be of the form <code>6k ± 1</code>)</p> <pre><code>def potential_primes(number: int) -&gt; int: &quot;&quot;&quot;Generate the numbers potential to be prime&quot;&quot;&quot; # Prime numbers are always of the form 6k ± 1. number_for_function = number // 6 for k in range(1, number_for_function + 1): yield 6*k - 1 yield 6*k + 1 </code></pre> <p>Obviously, the program should have been much faster because I am checking comparatively many less numbers. But, counterintuitively the program is slower than before. What could be the reason behind this?</p>
[ { "answer_id": 74498933, "author": "rossum", "author_id": 820127, "author_profile": "https://Stackoverflow.com/users/820127", "pm_score": 0, "selected": false, "text": "function listPrimes(n)\n // Deal with low numbers.\n if (n < 2) return []\n if (n = 2) return [2]\n if (n = 3) return [2, 3]\n\n // Main loop\n primeList ← [2, 3]\n limit ← 1 + sqrt(n) // Calculate square root once.\n index ← 5 // We have checked 2 and 3 already.\n step ← 2 // Starting step value: 5 + 2 = 7.\n \n while (index <= limit) {\n if (isPrime(index)) {\n primeList.add(index)\n }\n index ← index + step\n step ← 6 - step // Alternate steps of 2 and 4\n }\n \n return primeList\nend function\n" }, { "answer_id": 74499806, "author": "Will Ness", "author_id": 849891, "author_profile": "https://Stackoverflow.com/users/849891", "pm_score": 1, "selected": false, "text": "6k+0 6k+1 6k+2 6k+3 6k+4 6k+5\neven even even\n3x 3x\n range prime_numbers = [5,7]" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74497994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18092470/" ]
74,498,003
<p>in the below array i want to filter out records, that match the substring &quot;11/2022&quot; for key StartTime</p> <pre><code>[ { StartTime: '17/10/2022 14:45', Duration: '000:00:44:32', }, { StartTime: '17/11/2022 14:45', Duration: '000:00:44:30', }, { StartTime: '18/11/2022 14:45', Duration: '000:00:44:30', }, { StartTime: '17/12/2022 14:45', Duration: '000:00:44:30', } ] </code></pre> <p>expected output:</p> <pre><code>[ { StartTime: '17/11/2022 14:45', Duration: '000:00:44:30', }, { StartTime: '18/11/2022 14:45', Duration: '000:00:44:30', } ] </code></pre>
[ { "answer_id": 74498933, "author": "rossum", "author_id": 820127, "author_profile": "https://Stackoverflow.com/users/820127", "pm_score": 0, "selected": false, "text": "function listPrimes(n)\n // Deal with low numbers.\n if (n < 2) return []\n if (n = 2) return [2]\n if (n = 3) return [2, 3]\n\n // Main loop\n primeList ← [2, 3]\n limit ← 1 + sqrt(n) // Calculate square root once.\n index ← 5 // We have checked 2 and 3 already.\n step ← 2 // Starting step value: 5 + 2 = 7.\n \n while (index <= limit) {\n if (isPrime(index)) {\n primeList.add(index)\n }\n index ← index + step\n step ← 6 - step // Alternate steps of 2 and 4\n }\n \n return primeList\nend function\n" }, { "answer_id": 74499806, "author": "Will Ness", "author_id": 849891, "author_profile": "https://Stackoverflow.com/users/849891", "pm_score": 1, "selected": false, "text": "6k+0 6k+1 6k+2 6k+3 6k+4 6k+5\neven even even\n3x 3x\n range prime_numbers = [5,7]" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74498003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10298898/" ]
74,498,007
<p>I have created app registration in azure active directory. I'm trying to invoke an azure ad authenticated with below PowerShell script, but it always display an error:</p> <pre><code>$clientID = '&lt;clientID&gt;' $secretKey = '&lt;key&gt;' $tenantID = '&lt;TenantID&gt;' $password = ConvertTo-SecureString -String $secretKey -AsPlainText -Force $credential = New-Object System.Management.Automation.PSCredential($ClientID,$password) Connect-AzureRmAccount -ServicePrincipal -Credential $credential -Tenant $tenantID $authUrl = &quot;https://login.microsoftonline.com/&quot; + $tenantID + &quot;/oauth2/v2.0/token/&quot; $body = @{ &quot;scope&quot; = &quot;api://a193b314b-7854-9aab-bb78-6a50ffxxxxxx/&quot;; &quot;grant_type&quot; = &quot;client_credentials&quot;; &quot;client_id&quot; = $ClientID &quot;client_secret&quot; = $secretKey } Write-Output &quot;Getting Authentication-Token&quot; $adlsToken = Invoke-RestMethod -Uri $authUrl –Method POST -Body $body Write-Output $adlsToken </code></pre> <p>I am getting this error. please make me to understand Why I am getting this error</p> <blockquote> <p>Invoke-RestMethod: {&quot;error&quot;:&quot;invalid_scope&quot;,&quot;error_description&quot;:&quot;AADSTS1002012: The provided value for scope api://3e3643c5-90af-ece is not valid. Client credential flows must have a scope value with /.default suffixed to the resource identifier (application ID URI).\r\nTrace ID:2d4f23bf-b317-4d5c-b5xxxxx\r\nCorrelation ID:fe5945b4-b2c2-4814-9xxxxxxx\r\nTimestamp:04:26:09Z&quot;,&quot;error_codes&quot;:[1002012],&quot;timestamp&quot;:&quot;2022-11-19 04:26:09Z&quot;,&quot;trace_id&quot;:&quot;2d4f23bfb3174d5cb5a7xxxxxxx&quot;,&quot;correlation_id&quot;:&quot;fe5945b4-b2c2-4814-99xxxxxxxx&quot;}</p> </blockquote> <blockquote> <p>Connect-AzAccount: ClientSecretCredential authentication failed: AADSTS700016: Application with identifier '3e3643c5-90af-4af6-afxxxxxxx' was not found in the directory 'Default</p> </blockquote>
[ { "answer_id": 74498350, "author": "Charles Han", "author_id": 11514907, "author_profile": "https://Stackoverflow.com/users/11514907", "pm_score": 0, "selected": false, "text": "\"scope\" = \"api://a193b314b-7854-9aab-bb78-6a50ffxxxxxx/.default\"\n" }, { "answer_id": 74498366, "author": "Imran", "author_id": 18229970, "author_profile": "https://Stackoverflow.com/users/18229970", "pm_score": 2, "selected": true, "text": "/.default /.default \"api://xxxxxx/.default\";\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74498007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20545442/" ]
74,498,017
<p>Given this working version</p> <pre><code>IDENTIFICATION DIVISION. PROGRAM-ID. HELLO-WORLD. DATA DIVISION. WORKING-STORAGE SECTION. 01 UC-COUNTER PIC 99. 01 LC-COUNTER PIC 99. PROCEDURE DIVISION. INSPECT &quot;My dog has fleas&quot; TALLYING UC-COUNTER FOR ALL 'A','B','C','D','E','F', 'G','H','I','J','K','L','M','N','O','P','Q','R','S','T', 'U','V','W','X','Y','Z' LC-COUNTER FOR ALL 'a','b','c','d','e','f', 'g','h','i','j','k','l','m','n','o','p','q','r','s','t', 'u','v','w','x','y','z'. DISPLAY UC-COUNTER &quot; UPPER CASE CHARACTERS&quot;. DISPLAY LC-COUNTER &quot; LOWER CASE CHARACTERS&quot;. GOBACK. </code></pre> <p>Is there a better way of expressing the alphabets? That is, can we have a SPECIAL-NAMES or something like that so that the instruction can be INSPECT TALLYING FOR ALL LATIN-UPPERCASE-LETTERS-ENGLISH or something similar.</p> <p><strong>LATER</strong></p> <p>Things like this don't appear to work (and given the GnuCOBOL docs, probably won't)</p> <pre><code>IDENTIFICATION DIVISION. PROGRAM-ID. HELLO-WORLD. ENVIRONMENT DIVISION. CONFIGURATION SECTION. SPECIAL-NAMES. CLASS UPPER-CASE-ENGLISH-LETTERS IS 'A','B','C','D','E','F','G','H','I','J','K','L','M', 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z'. DATA DIVISION. WORKING-STORAGE SECTION. 01 UC-COUNTER PIC 99. PROCEDURE DIVISION. INSPECT &quot;My dog has fleas&quot; TALLYING UC-COUNTER FOR ALL UPPER-CASE-ENGLISH-LETTERS. DISPLAY UC-COUNTER &quot; UPPER CASE CHARACTERS&quot;. STOP RUN. </code></pre>
[ { "answer_id": 74501341, "author": "Rick Smith", "author_id": 9170346, "author_profile": "https://Stackoverflow.com/users/9170346", "pm_score": 2, "selected": false, "text": "ALPHABETIC-UPPER ALPHABETIC-LOWER INSPECT INSPECT data division.\n working-storage section.\n 01 uc-counter pic 99.\n 01 lc-counter pic 99.\n 01 str pic x(50).\n 01 n comp pic 9(4).\n procedure division.\n initialize uc-counter lc-counter\n string \"My dog has fleas\" low-value delimited size\n into str\n perform varying n from 1 by 1\n until str(n:1) = low-value\n evaluate true\n when str(n:1) = space\n continue *> ignore space\n when str(n:1) is alphabetic-upper\n add 1 to uc-counter *> count upper-case letter\n when str(n:1) is alphabetic-lower\n add 1 to lc-counter *> count lower-case letter\n when other\n continue\n end-evaluate\n end-perform\n display uc-counter \" upper case characters\"\n display lc-counter \" lower case characters\"\n goback\n .\n 01 upper case characters\n12 lower case characters\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74498017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/426/" ]
74,498,025
<p>I create a website where there is a normal user and admin. They both have different log in system.But the problem is when a user logged in as a user, he also logged in into admin page. Also when a admin logged in, he also logged in into user page.</p> <pre><code>def userlogin(request): error = &quot;&quot; if request.method == 'POST': u = request.POST['emailid'] p = request.POST['pwd'] user = authenticate(username=u, password=p) try: if user: login(request, user) error = &quot;no&quot; return redirect(profile) else: error = &quot;yes&quot; except: error = &quot;yes&quot; return render(request, 'login.html', locals()) </code></pre> <pre><code> def login_admin(request): error = &quot;&quot; if request.method == 'POST': u = request.POST['uname'] p = request.POST['pwd'] user = authenticate(username=u, password=p) try: if user.is_staff: login(request, user) error = &quot;no&quot; else: error =&quot;yes&quot; except: error = &quot;yes&quot; return render(request,'login_admin.html', locals()) </code></pre> <p>This model is used for normal user signup</p> <pre><code>class Signup(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) contact = models.CharField(max_length=10) branch = models.CharField(max_length=30) role = models.CharField(max_length=15) username = models.CharField(max_length=15, unique=True) image = models.ImageField(upload_to=&quot;images/img&quot;, default=&quot;&quot;) upvotesuser = models.IntegerField(default=0) </code></pre> <p>I want to achive different authentication system for user and also for admin.</p>
[ { "answer_id": 74501341, "author": "Rick Smith", "author_id": 9170346, "author_profile": "https://Stackoverflow.com/users/9170346", "pm_score": 2, "selected": false, "text": "ALPHABETIC-UPPER ALPHABETIC-LOWER INSPECT INSPECT data division.\n working-storage section.\n 01 uc-counter pic 99.\n 01 lc-counter pic 99.\n 01 str pic x(50).\n 01 n comp pic 9(4).\n procedure division.\n initialize uc-counter lc-counter\n string \"My dog has fleas\" low-value delimited size\n into str\n perform varying n from 1 by 1\n until str(n:1) = low-value\n evaluate true\n when str(n:1) = space\n continue *> ignore space\n when str(n:1) is alphabetic-upper\n add 1 to uc-counter *> count upper-case letter\n when str(n:1) is alphabetic-lower\n add 1 to lc-counter *> count lower-case letter\n when other\n continue\n end-evaluate\n end-perform\n display uc-counter \" upper case characters\"\n display lc-counter \" lower case characters\"\n goback\n .\n 01 upper case characters\n12 lower case characters\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74498025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15856442/" ]
74,498,033
<p>I am very new to programming and to stackOverflow. I am implementing First Come First Serve(FCFS).But I am getting array index out of bound exception, while entering input in []ArrivalTime I can be a silly mistake but i can not figure out why ,Please help me</p> <pre><code>import java.util.Scanner; public class FCFS_Practice { public static Scanner scanner = new Scanner(System.in); static int numberOfProcess = 0; int[]ProcessID = new int[numberOfProcess]; int[]ArrivalTime = new int[numberOfProcess]; int[]BurstTime = new int[numberOfProcess]; int[]CompletionTime = new int[numberOfProcess]; int[]TurnAroundTime = new int[numberOfProcess]; int[]WaitingTime = new int[numberOfProcess]; float avgWaitingTime = 0,avgTurnAroundTime = 0; public void takeInput(){ System.out.println(&quot;Enter the number of process: &quot;); numberOfProcess = scanner.nextInt(); } public void inputArrivalAndBurstTime(){ for(int i = 0;i &lt; numberOfProcess;i++){ System.out.printf(&quot;Enter Arrival Time for Process %d: &quot;,i+1); ArrivalTime[i] = scanner.nextInt(); scanner.nextLine(); // Buffer Flush System.out.printf(&quot;Enter Burst Time for Process %d: &quot;,i+1); BurstTime[i] = scanner.nextInt(); scanner.nextLine(); // Buffer flush ProcessID[i] = i+1; } } public void calculateCompletionTime(){ for(int i = 0 ; i &lt; numberOfProcess ; i++){ if(i==0){ CompletionTime[0]=BurstTime[0]; } else if (ArrivalTime[i]&lt;CompletionTime[i-1]) { CompletionTime[i]=CompletionTime[i-1]+BurstTime[i]; } else { CompletionTime[i]=ArrivalTime[i]+BurstTime[i]; } } } public void calculateTurnAroundAndWaitingTime(){ for(int i = 0 ; i &lt; numberOfProcess ; i++){ TurnAroundTime[i]=CompletionTime[i]+ArrivalTime[i]; WaitingTime[i]=TurnAroundTime[i]-BurstTime[i]; } } public void getAvgWaitingTimeAndAvgTurnAroundTime(){ for(int i = 0 ; i&lt;numberOfProcess;i++){ avgTurnAroundTime+=TurnAroundTime[i]; avgWaitingTime+=WaitingTime[i]; } avgWaitingTime = avgWaitingTime/numberOfProcess; avgTurnAroundTime = avgTurnAroundTime/numberOfProcess; } public void getTable(){ System.out.println(&quot;ProcessNo. ArrivalTime BurstTime CompletionTime TurnAroundTime WaitingTime&quot;); for(int i = 0 ; i &lt; numberOfProcess ; i++){ System.out.println(ProcessID[i]+&quot;\t\t&quot;+ArrivalTime[i]+&quot;\t\t&quot;+BurstTime[i]+&quot;\t\t&quot;+CompletionTime[i]+&quot;\t\t\t&quot;+TurnAroundTime[i]+&quot;\t\t\t&quot;+WaitingTime[i]); } scanner.close(); } } [Output](https://i.stack.imgur.com/z1CEd.png) </code></pre>
[ { "answer_id": 74501341, "author": "Rick Smith", "author_id": 9170346, "author_profile": "https://Stackoverflow.com/users/9170346", "pm_score": 2, "selected": false, "text": "ALPHABETIC-UPPER ALPHABETIC-LOWER INSPECT INSPECT data division.\n working-storage section.\n 01 uc-counter pic 99.\n 01 lc-counter pic 99.\n 01 str pic x(50).\n 01 n comp pic 9(4).\n procedure division.\n initialize uc-counter lc-counter\n string \"My dog has fleas\" low-value delimited size\n into str\n perform varying n from 1 by 1\n until str(n:1) = low-value\n evaluate true\n when str(n:1) = space\n continue *> ignore space\n when str(n:1) is alphabetic-upper\n add 1 to uc-counter *> count upper-case letter\n when str(n:1) is alphabetic-lower\n add 1 to lc-counter *> count lower-case letter\n when other\n continue\n end-evaluate\n end-perform\n display uc-counter \" upper case characters\"\n display lc-counter \" lower case characters\"\n goback\n .\n 01 upper case characters\n12 lower case characters\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74498033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20545530/" ]
74,498,051
<p>I'm attempting to solve some Java questions and I came across a question that asked me to print out a diamond of size <code>n</code>.</p> <p>Since I got stumped on this question, I decided to look up other's solutions to get an idea as to how I could tackle this problem.</p> <p>A diamond of size 2 should look like this by the way.</p> <pre><code>##*## #***# ##*## </code></pre> <p>However, one part of the code really stumped me out and that is how does the <code>#</code> get printed out in that manner.</p> <p>Here is what I found for the top left bit of the diamond, basically this bit:</p> <pre><code>## # </code></pre> <p>Here is the code for that:</p> <pre><code> public static void printDiamond(int k){ for(int i=1; i &lt;= k; i++) { for(int j = i; j &lt;= k; j++) { System.out.print(&quot;#&quot;); } System.out.println(&quot;&quot;); } } </code></pre> <p>and the output when k = 5:</p> <pre><code>##### #### ### ## # </code></pre> <p>From my understanding, int <code>j</code> is looping upwards since it's declared as <code>i</code> which also loops upwards until it reaches <code>k</code>.</p> <p>Shouldn't that print out 1,2,3,4,5 diamonds instead since the loop goes from 0 to k, which is 5?</p> <p>I was expecting the output to be like:</p> <pre><code># ## ### #### ##### </code></pre> <p>Can someone explain how does the code snippet I attached returns the output from top to bottom?</p>
[ { "answer_id": 74498106, "author": "user7", "author_id": 4405757, "author_profile": "https://Stackoverflow.com/users/4405757", "pm_score": 3, "selected": true, "text": "for(int i = 1; i <= k; i++) {\n for(int j = i; j <= k; j++) {\n ...\n }\n}\n i = 1 j 1 k k k i = 2 j 2 k k - 1 k - 1 i = k j k k" }, { "answer_id": 74498157, "author": "Nowhere Man", "author_id": 13279831, "author_profile": "https://Stackoverflow.com/users/13279831", "pm_score": 0, "selected": false, "text": "j i k # i for (int j = 1; j <= i; j++0) System.out.print(\"#\") String::repeat public static void diamond(int k) {\n // upper part, decreasing # increasing *\n for (int i = 1; i <= k; i++) {\n System.out.println(\"#\".repeat(k - i) + \"*\".repeat(2 * i - 1) + \"#\".repeat(k - i));\n }\n \n // lower part, decreasing * increasing #\n for (int i = 1; i < k; i++) {\n System.out.println(\"#\".repeat(i) + \"*\".repeat(2 * (k - i) - 1) + \"#\".repeat(i));\n }\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74498051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18984687/" ]
74,498,062
<p>i'm trying to use the search engine of a website, but captcha blocks me continuously. Is there any way to perform search?</p> <pre><code>driver = webdriver.Firefox() driver.implicitly_wait(10) # seconds driver.get(&quot;https://www.autodoc.pl/&quot;) query ='H317W01' driver.find_element(By.ID, &quot;search&quot;).send_keys(query) driver.find_element(By.ID, &quot;search&quot;).send_keys(Keys.ENTER) </code></pre>
[ { "answer_id": 74498106, "author": "user7", "author_id": 4405757, "author_profile": "https://Stackoverflow.com/users/4405757", "pm_score": 3, "selected": true, "text": "for(int i = 1; i <= k; i++) {\n for(int j = i; j <= k; j++) {\n ...\n }\n}\n i = 1 j 1 k k k i = 2 j 2 k k - 1 k - 1 i = k j k k" }, { "answer_id": 74498157, "author": "Nowhere Man", "author_id": 13279831, "author_profile": "https://Stackoverflow.com/users/13279831", "pm_score": 0, "selected": false, "text": "j i k # i for (int j = 1; j <= i; j++0) System.out.print(\"#\") String::repeat public static void diamond(int k) {\n // upper part, decreasing # increasing *\n for (int i = 1; i <= k; i++) {\n System.out.println(\"#\".repeat(k - i) + \"*\".repeat(2 * i - 1) + \"#\".repeat(k - i));\n }\n \n // lower part, decreasing * increasing #\n for (int i = 1; i < k; i++) {\n System.out.println(\"#\".repeat(i) + \"*\".repeat(2 * (k - i) - 1) + \"#\".repeat(i));\n }\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74498062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055027/" ]
74,498,074
<p>Let say I want to change color of my element. Unfortunately, after use query Selector method, my code doesn't work but blank. Please anyone can solve this?</p> <p>I try to select my element to change its color using javascript instead of using css</p> <pre><code>&lt;template&gt; &lt;br&gt;&lt;br&gt;&lt;br&gt; &lt;h1&gt;Dashboard Page Here&lt;/h1&gt; &lt;/template&gt; &lt;script&gt; export default { name: &quot;xxxView&quot;, } &lt;/script&gt; &lt;script setup&gt; const color = document.querySelector('h1'); color.style.color = 'green'; &lt;/script&gt; &lt;style scoped&gt; &lt;/style&gt; </code></pre>
[ { "answer_id": 74498093, "author": "Mina", "author_id": 11887902, "author_profile": "https://Stackoverflow.com/users/11887902", "pm_score": 2, "selected": true, "text": "setup DOM DOM onMounted <template>\n <br><br><br>\n<h1>Dashboard Page Here</h1>\n</template>\n\n<script>\nexport default {\n name: \"xxxView\",\n}\n</script>\n\n<script setup>\nimport { onMounted } from 'vue'\nonMounted(() => {\n const color = document.querySelector('h1');\n color.style.color = 'green';\n})\n</script>\n\n<style scoped>\n\n</style>\n style" }, { "answer_id": 74498175, "author": "hamid-davodi", "author_id": 13770936, "author_profile": "https://Stackoverflow.com/users/13770936", "pm_score": 0, "selected": false, "text": "<template>\n <br><br><br>\n <h1 ref=\"myHeader\">Dashboard Page Here</h1>\n</template>\n\n\n<script setup>\nimport {ref, onMounted} from \"vue\";\nconst myHeader = ref(null)\n\nonMounted(() => {\n myHeader.value.style.color = 'green';\n})\n</script>\n\n<style scoped>\n\n</style>" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74498074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20545571/" ]
74,498,075
<p>I have an issue with <code>graphQLSchemaExtension</code></p> <p>I don’t have active <strong>session</strong> on my custom mutations..</p> <p>An example below of the beginning of custom mutation And my graphQLSchemaExtension declaration And my <code>Keystone.ts</code> file</p> <p>On my generic <strong>queries/mutations</strong> on playground I have a <strong>session</strong>. On my frontend too</p> <p>Thanks &lt;3</p> <p><a href="https://i.stack.imgur.com/aKl6e.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aKl6e.png" alt="resolvers/mutations/confirmBooking.ts" /></a></p> <p><a href="https://i.stack.imgur.com/ljhSO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ljhSO.png" alt="resolvers/index.ts" /></a></p> <p><a href="https://i.stack.imgur.com/vONAI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vONAI.png" alt="Keystone.ts" /></a></p> <p>I tried to change secure option on keystone.ts but nothing change Check on google, check on KeystoneJS github issues</p>
[ { "answer_id": 74527486, "author": "Molomby", "author_id": 762028, "author_profile": "https://Stackoverflow.com/users/762028", "pm_score": 1, "selected": false, "text": "session context null package.json getRandom keystone.ts import { list, config, graphql } from '@keystone-6/core';\nimport { statelessSessions } from '@keystone-6/core/session';\nimport { allowAll } from '@keystone-6/core/access';\nimport { text, password } from '@keystone-6/core/fields';\nimport { createAuth } from '@keystone-6/auth';\nimport { Context } from '.keystone/types';\n\nlet sessionSecret = Math.random().toString(36).substring(2, 10).repeat(4);\nlet sessionMaxAge = 60 * 60 * 24 * 30;\n\nconst { withAuth } = createAuth({\n listKey: 'User',\n identityField: 'email',\n secretField: 'password',\n sessionData: 'name',\n});\n\nconst lists = {\n User: list({\n access: allowAll,\n fields: {\n name: text({ validation: { isRequired: true } }),\n email: text({ isIndexed: 'unique', validation: { isRequired: true } }),\n password: password(),\n },\n }),\n};\n\nconst extendGraphqlSchema = graphql.extend(base => ({\n mutation: {\n getRandom: graphql.field({\n type: graphql.Float,\n args: {},\n resolve(source, {}, context: Context) {\n console.log('Dumping session object:', context.session);\n return Math.random();\n },\n }),\n },\n}));\n\nexport default withAuth(\n config({\n db: {\n provider: 'postgresql',\n url: process.env.DATABASE_URL || 'postgres://molomby@localhost/ks6-auth',\n },\n lists,\n session: statelessSessions({\n maxAge: sessionMaxAge,\n secret: sessionSecret,\n }),\n extendGraphqlSchema,\n })\n);\n @keystone-6/auth@5.0.1 @keystone-6/core@3.1.2 mutation {\n getRandom\n}\n context.session Dumping session object: undefined\n Dumping session object: {\n listKey: 'User',\n itemId: 'claro2yq40008lh6y5wpkh2s1',\n data: [Object: null prototype] { name: 'Molomby' }\n}\n" }, { "answer_id": 74528532, "author": "user11898473", "author_id": 11898473, "author_profile": "https://Stackoverflow.com/users/11898473", "pm_score": 0, "selected": false, "text": "context.session const extendGraphqlSchema = graphql.extend(base => ({\n mutation: {\n getRandom: graphql.field({\n type: graphql.Float,\n args: {},\n resolve(source, {}, context: Context) {\n console.log('Dumping session object:', context.session);\n return Math.random();\n },\n }),\n },\n}));\n type \"dependencies\": {\n \"@keystone-6/auth\": \"^4.0.0\",\n \"@keystone-6/core\": \"^2.1.0\",\n \"@keystone-6/fields-document\": \"^4.0.1\",\n \"@keystonejs/server-side-graphql-client\": \"^2.1.2\",\n \"@prisma/client\": \"^4.4.0\",\n \"@types/nodemailer\": \"^6.4.4\",\n \"dotenv\": \"^10.0.0\",\n \"graphql\": \"^15.8.0\",\n \"next\": \"12.2.4\",\n \"nodemailer\": \"^6.6.2\",\n \"stripe\": \"^8.161.0\",\n \"typescript\": \"^4.7.4\"\n },\n" }, { "answer_id": 74557072, "author": "user11898473", "author_id": 11898473, "author_profile": "https://Stackoverflow.com/users/11898473", "pm_score": 0, "selected": false, "text": "export const extendGraphqlSchema = (schema: GraphQLSchema) =>\n mergeSchemas({\n schemas: [schema],\n typeDefs: `\n type Query {\n allGifts: [Gift]\n }\n type Mutation {\n confirmBooking(giftId: ID!): Boolean\n }\n `,\n resolvers: {\n Query: {\n // Testing\n allGifts: (root, { id, days }, context: Context) =>\n context.db.Gift.findMany(),\n },\n Mutation: {\n // To implement\n confirmBooking: (root, { giftId }, context: Context) => {\n console.log('CONTEXT', Object.keys(context));\n /*\n 'db', 'query',\n 'totalResults', 'prisma',\n 'graphql', 'maxTotalResults',\n 'sudo', 'exitSudo',\n 'withSession', 'req',\n 'session', 'startSession',\n 'endSession', 'gqlNames',\n 'images', 'files'\n */\n const session = context.session as Session;\n console.log('SESSION', session); // undefined\n return true;\n },\n },\n },\n });\n" }, { "answer_id": 74557466, "author": "user11898473", "author_id": 11898473, "author_profile": "https://Stackoverflow.com/users/11898473", "pm_score": 0, "selected": false, "text": "export const extendGraphqlSchema = (schema: GraphQLSchema) =>\n mergeSchemas({\n schemas: [schema],\n typeDefs: `\n type Query {\n allGifts: [Gift]\n }\n type Mutation {\n confirmBooking(giftId: ID!): Boolean\n }\n `,\n resolvers: {\n Query: {\n // Testing\n allGifts: (root, { id, days }, context: Context) =>\n context.db.Gift.findMany(),\n },\n Mutation: {\n // To implement\n confirmBooking: (root, { giftId }, context: Context) => {\n console.log('CONTEXT', Object.keys(context));\n /*\n 'db', 'query',\n 'totalResults', 'prisma',\n 'graphql', 'maxTotalResults',\n 'sudo', 'exitSudo',\n 'withSession', 'req',\n 'session', 'startSession',\n 'endSession', 'gqlNames',\n 'images', 'files'\n */\n const session = context.session as Session;\n console.log('SESSION', session); // undefined\n return true;\n },\n },\n },\n });\n graphql.extend(base) dumping session object export const extendGraphqlSchema = graphql.extend((base) => ({\n mutation: {\n confirmBooking: graphql.field({\n type: graphql.Float,\n args: {},\n // eslint-disable-next-line no-empty-pattern\n resolve(source, {}, context: Context) {\n console.log('Dumping session object:', context.session);\n return Math.random();\n },\n }),\n },\n}));\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74498075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11898473/" ]
74,498,090
<p>Let's say my data is <code>df &lt;- c(&quot;Author1&quot;,&quot;Reference1&quot;,&quot;Abstract1&quot;,&quot;Author2&quot;,&quot;Reference2&quot;,&quot;Abstract2&quot;,&quot;Author3&quot;,&quot;Reference3&quot;,&quot;Author4&quot;,&quot;Reference4&quot;,&quot;Abstract4&quot;)</code>.</p> <p>This is a series in which the order is Author, Reference and Abstract. But in some cases, the Abstract data is missing. (In this example, the third Abstract is missing.) So, how can I add NA values in place of Abstract, when Abstract is missing?</p> <p>In other words, If an element in the vector starts with the word &quot;Reference&quot;, but its next element doesn't start with the word &quot;Abstract&quot;, I want to add an NA value just after the element starting with &quot;Reference&quot;. The result vector should be <code>result &lt;- c(&quot;Author1&quot;,&quot;Reference1&quot;,&quot;Abstract1&quot;,&quot;Author2&quot;,&quot;Reference2&quot;,&quot;Abstract2&quot;,&quot;Author3&quot;,&quot;Reference3&quot;,NA,&quot;Author4&quot;,&quot;Reference4&quot;,&quot;Abstract4&quot;)</code> How can I do it?</p> <p>I have tried the append function in R, but for using it, I need to have the index number of the element where I want to add NA. So, it takes a manual entry for each NA element.</p>
[ { "answer_id": 74498235, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 2, "selected": false, "text": "x parse_number() readr parse_number() summarise(cur_data()[seq(3),]) library(dplyr)\nlibrary(readr)\n\nmy_vector <- tibble(x = c(\"Author1\",\"Reference1\",\"Abstract1\",\"Author2\",\"Reference2\",\n \"Abstract2\",\"Author3\",\"Reference3\",\"Author4\",\"Reference4\",\"Abstract4\")) %>% \n group_by(group= parse_number(x)) %>% \n summarise(cur_data()[seq(3),]) %>% \n pull(x)\n\n[1] \"Author1\" \"Reference1\" \"Abstract1\" \"Author2\" \"Reference2\" \"Abstract2\" \"Author3\" \n [8] \"Reference3\" NA \"Author4\" \"Reference4\" \"Abstract4\"\n library(dplyr)\nlibrary(readr)\nmy_vector <- tibble(x = c(\"Author1\",\"Reference1\",\"Abstract1\",\"Author2\",\"Reference2\",\n \"Abstract2\",\"Author3\",\"Reference3\",\"Author4\",\"Reference4\",\"Abstract4\")) %>% \n group_by(group= parse_number(x)) %>% \n summarise(cur_data()[seq(3),]) %>% \n mutate(group = paste0(c(\"Author\", \"Reference\", \"Abstract\"), group)) %>% \n pull(group)\n [1] \"Author1\" \"Reference1\" \"Abstract1\" \"Author2\" \"Reference2\" \"Abstract2\" \"Author3\" \n [8] \"Reference3\" \"Abstract3\" \"Author4\" \"Reference4\" \"Abstract4\" \n" }, { "answer_id": 74498255, "author": "Josh White", "author_id": 20289207, "author_profile": "https://Stackoverflow.com/users/20289207", "pm_score": 2, "selected": false, "text": "Reference Abstract NA append() ab_missing <- grepl(\"Reference\", df) & c(!grepl(\"Abstract\", df)[-1], FALSE)\ndf <- append(df, NA, which(ab_missing))\n\ndf\n [1] \"Author1\" \"Reference1\" \"Abstract1\" \"Author2\" \"Reference2\" \"Abstract2\" \"Author3\" \"Reference3\" NA \"Author4\" \n[11] \"Reference4\" \"Abstract4\" \n" }, { "answer_id": 74498736, "author": "tmfmnk", "author_id": 5964557, "author_profile": "https://Stackoverflow.com/users/5964557", "pm_score": 0, "selected": false, "text": "c(sapply(split(x, cumsum(grepl(\"Author\", x))), function(x) head(c(x, NA_character_), 3)))\n\n [1] \"Author1\" \"Reference1\" \"Abstract1\" \"Author2\" \"Reference2\" \"Abstract2\" \"Author3\" \n [8] \"Reference3\" NA \"Author4\" \"Reference4\" \"Abstract4\" \n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74498090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12806202/" ]
74,498,095
<p>I have a database in mysql. I want clear field contents that contains specific value.</p> <p>I have database like this:</p> <pre class="lang-none prettyprint-override"><code>`id` `cat1` `cat2` `cat3` 1 1185 A1 3185 2 1585 A2 3131 3 2513 B3 3113 4 3369 C4 3333 </code></pre> <p>I want to clear only 'fields' (not entire row) that contain &quot;A&quot; in cat2 column. how should I do that?</p> <p>my query doesn't seem to work properly. instead delete entire row.</p> <pre class="lang-sql prettyprint-override"><code>DELETE FROM table_name WHERE cat2='A*'; </code></pre>
[ { "answer_id": 74498100, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 3, "selected": true, "text": "LIKE UPDATE table_name SET cat2 = NULL WHERE cat2 LIKE 'A%';\n" }, { "answer_id": 74498143, "author": "Wang Zerui", "author_id": 16232205, "author_profile": "https://Stackoverflow.com/users/16232205", "pm_score": 2, "selected": false, "text": "UPDATE REGEXP UPDATE EMPLOYEE SET cat2='' WHERE cat2 REGEXP '^A';\n" }, { "answer_id": 74498277, "author": "cottontail", "author_id": 19123103, "author_profile": "https://Stackoverflow.com/users/19123103", "pm_score": 1, "selected": false, "text": "SELECT id, cat1, \n CASE\n WHEN cat2 NOT LIKE 'A%' THEN cat2\n END AS cat2\n ,cat3\nFROM my_table;\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74498095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14002808/" ]
74,498,105
<p>I'm using Jupyter notebook to run a PL/SQL script but I get an error. The code block in the notebook is as follows:</p> <pre><code>%%sql DECLARE BEGIN FOR record_item IN ( SELECT * FROM duplicated_records ) LOOP EXECUTE IMMEDIATE 'UPDATE table_name SET record_id ='|| record_item.original_record_id || ' WHERE record_id =' || record_item.duplicated_record_id; EXECUTE IMMEDIATE 'DELETE FROM records WHERE id ='|| record_item.duplicated_record_id; END LOOP; END </code></pre> <p>The error is</p> <pre><code>(cx_Oracle.DatabaseError) ORA-06550: line 8, column 165: PLS-00103: Encountered the symbol &quot;end-of-file&quot; when expecting one of the following: </code></pre> <p>Non-PL/SQL code, such as select, and update statements, seems to work.</p> <p>It works perfectly fine with other SQL clients like SQL developer. I've tried adding/removing the<code>;</code> at the end but it still doesn't work.</p>
[ { "answer_id": 74498199, "author": "Littlefoot", "author_id": 9097906, "author_profile": "https://Stackoverflow.com/users/9097906", "pm_score": 2, "selected": false, "text": "DECLARE EXECUTE IMMEDIATE BEGIN\n FOR record_item IN (SELECT * FROM duplicated_records) LOOP\n UPDATE table_name\n SET record_id = record_item.original_record_id\n WHERE record_id = record_item.duplicated_record_id;\n\n DELETE FROM records\n WHERE id = record_item.duplicated_record_id;\n END LOOP;\nEND;\n merge into table_name a\n using duplicated_records b\n on (a.record_id = b.duplicate_record_id) \n when matched then update set\n a.record_id = b.original_record_id;\n\ndelete from records a\n where a.id in (select b.duplicated_record_id from duplicated_records b);\n ID" }, { "answer_id": 74498668, "author": "Christopher Jones", "author_id": 4799035, "author_profile": "https://Stackoverflow.com/users/4799035", "pm_score": 1, "selected": false, "text": "import oracledb\nimport traceback\nimport os\nimport sys\n\n#if sys.platform.startswith('darwin'):\n# oracledb.init_oracle_client(lib_dir=os.environ.get('HOME')+'/Downloads/instantclient_19_8')\n\nun = os.environ.get('PYTHON_USERNAME')\npw = os.environ.get('PYTHON_PASSWORD')\ncs = os.environ.get('PYTHON_CONNECTSTRING')\n\ntry:\n connection = oracledb.connect(user=un, password=pw, dsn=cs)\n\n with connection.cursor() as cursor:\n plsql = \"\"\"BEGIN\n FOR RECORD_ITEM IN (\n SELECT\n *\n FROM\n DUPLICATED_RECORDS\n ) LOOP\n EXECUTE IMMEDIATE 'UPDATE table_name SET record_id ='\n || RECORD_ITEM.ORIGINAL_RECORD_ID\n || ' WHERE record_id ='\n || RECORD_ITEM.DUPLICATED_RECORD_ID;\n EXECUTE IMMEDIATE 'DELETE FROM records WHERE id ='\n || RECORD_ITEM.DUPLICATED_RECORD_ID;\n END LOOP;\n END;\"\"\"\n\n cursor.execute(plsql)\n\nexcept oracledb.Error as e:\n error, = e.args\n traceback.print_tb(e.__traceback__)\n print(error.message)\n oracledb import cx_Oracle as oracledb" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74498105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12031410/" ]
74,498,204
<p>if i have</p> <pre><code>def (a=10, b=2): ... </code></pre> <p>how do I unset a=1? I was told I need to not set 'a' but I can't find how to do that on google, it just sets itself to the default value if I don't have it, and I need to completely unset it</p> <p>the library is madmom and the instruction was &quot;If look_ahead is not set, a constant tempo throughout the whole piece is assumed. If look_ahead is set, the local tempo (in a range +/- look_ahead seconds around the actual position) is estimated and then the next beat is tracked accordingly. This procedure is repeated from the new position to the end of the piece.&quot;. <a href="https://madmom.readthedocs.io/en/v0.16/modules/features/beats.html" rel="nofollow noreferrer">https://madmom.readthedocs.io/en/v0.16/modules/features/beats.html</a></p>
[ { "answer_id": 74498253, "author": "Bohdan", "author_id": 15171133, "author_profile": "https://Stackoverflow.com/users/15171133", "pm_score": 0, "selected": false, "text": "def func(a=10, b=2)\n print(a, b)\n func()\n func(20, 3)\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74498204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15673832/" ]
74,498,217
<p>My logic calculates and returns a value based on user input, I want to modify that value to always have three decimal digits</p> <p><strong>For example;</strong></p> <p><code>1</code> to <code>1.000</code><br /> <code>1.02</code> to <code>1.020</code><br /> <code>2.000004</code> to <code>2.000</code><br /> <code>2.5687</code> to <code>2.569</code></p> <p>How would I achieve it on javascript?</p>
[ { "answer_id": 74498224, "author": "flyingfox", "author_id": 3176419, "author_profile": "https://Stackoverflow.com/users/3176419", "pm_score": 3, "selected": true, "text": "Number().toFixed() const formatVal = (val,precise = 3) =>{\n return Number(val).toFixed(precise)\n}\n\nconsole.log(formatVal(1,3))\nconsole.log(formatVal(1.02,3))\nconsole.log(formatVal(2.000004,3))\nconsole.log(formatVal(2.5687))\nconsole.log(\"-----------------\")\nconsole.log(formatVal(2.5687,2))" }, { "answer_id": 74498239, "author": "Ankit", "author_id": 19757319, "author_profile": "https://Stackoverflow.com/users/19757319", "pm_score": 1, "selected": false, "text": "let newNum = Number(1.34).toFixed(3);\nconsole.log(newNum);" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74498217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18617343/" ]
74,498,252
<p><a href="https://www.typescriptlang.org/play?#code/C4TwDgpgBAQghgZ2gXig4AnAlgOwOYDaAugFAm7AQYBmcAxtAGID2zUA3lGBs2AFyxE0AL5kKVWg0EYOXHv0FIookqEhQWzeDNSaoAH2lk6zHOiiV0Azdqip2JKE7m8BxEisvAAdN15A" rel="nofollow noreferrer">Playground</a></p> <pre><code>type Base = string[] interface Foo { prop: Base } interface Bar { prop: Base } type FooBar = Foo | Bar const test: FooBar = { prop: [] // property prop resolves to never[] here } test.prop // property prop resolves to Base here </code></pre> <p>Why is the type in cost declaration resolved to <code>never[]</code> and not <code>Base</code> since the definitions in both <code>Foo</code> and <code>Bar</code> of property <code>prop</code> are the same?</p>
[ { "answer_id": 74498224, "author": "flyingfox", "author_id": 3176419, "author_profile": "https://Stackoverflow.com/users/3176419", "pm_score": 3, "selected": true, "text": "Number().toFixed() const formatVal = (val,precise = 3) =>{\n return Number(val).toFixed(precise)\n}\n\nconsole.log(formatVal(1,3))\nconsole.log(formatVal(1.02,3))\nconsole.log(formatVal(2.000004,3))\nconsole.log(formatVal(2.5687))\nconsole.log(\"-----------------\")\nconsole.log(formatVal(2.5687,2))" }, { "answer_id": 74498239, "author": "Ankit", "author_id": 19757319, "author_profile": "https://Stackoverflow.com/users/19757319", "pm_score": 1, "selected": false, "text": "let newNum = Number(1.34).toFixed(3);\nconsole.log(newNum);" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74498252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2534830/" ]