qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,320,904
<p>JavaScript is known to only check the first variable in a <code>&amp;&amp;</code> comparison in case the first variable returns false. Is there a way to 'ask' JavaScript to check both variables i.e. when they are methods?</p> <p>For example: Suppose you have 2 methods that validate 2 separate user inputs:</p> <pre><code>const validateEmail = value =&gt; { if(value.contains('@')){ setShowEmailError(false); return true; } setShowEmailError(true); return false; }; const validatePswd = value =&gt; { if(value !== ''){ setShowPswdError(false); return true; } setShowPswdError(true); return false; }; </code></pre> <p>Then check both conditions:</p> <pre><code>if(validateEmail(email) &amp;&amp; validatePswd(pswd)){ //validate entire form and render errors } </code></pre> <p>However, the above will not execute the <code>validatePswd</code> method if the first method <code>validateEmail</code> returns false.</p> <p>Is there a way to check if both values are true <strong>and</strong> run both methods? Having JavaScript run both methods would be a breeze in some cases.</p>
[ { "answer_id": 74320983, "author": "Mina", "author_id": 11887902, "author_profile": "https://Stackoverflow.com/users/11887902", "pm_score": 3, "selected": true, "text": "&&" }, { "answer_id": 74321439, "author": "ObieTrz", "author_id": 19643756, "author_profile": "https://Stackoverflow.com/users/19643756", "pm_score": 1, "selected": false, "text": "const valEmail = validateEmail(email);\nconst valPsw = validatePswd(pswd);\n\nif(valEmail && valPsw ){\n //validate entire form and render errors\n}\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74320904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10784244/" ]
74,320,939
<p>I have such a program</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;ctype.h&gt; #include &lt;string.h&gt; int main() { float x, k; int choose; _Bool valid; do { valid = 1; printf(&quot;\nChoose variant: \n1 - count of nums\n2 - float number\n3 - e:\nYour choose: &quot;); scanf(&quot; %d&quot;, &amp;choose); while(isdigit(choose) == 0) { printf(&quot;Please, choose number, not letter (number between 1 to 3): &quot;); fflush(stdin); scanf(&quot; %d&quot;, &amp;choose); } while(choose &gt; 3 || choose &lt; 0) { printf(&quot;Please, choose correct option (number between 1 to 3): &quot;); fflush(stdin); scanf(&quot; %d&quot;, &amp;choose); } if(choose == 1 || choose == 2 || choose == 3) valid = 0; } while (valid); return 0; } </code></pre> <p>I have such a program. I want to get the user to choose: 1, 2 or 3. I'm trying to put a check on characters and also on other numbers. I want the program to loop until I enter the correct one. But it does not work, I have already tried other methods to solve this problem, but it does not work for me. I have an idea that there is no cleaning here, maybe this is so?</p> <p>I can also set a condition so that scanf is equal to one - this means that a character has been entered. But I want if the user enters &quot;1gf &quot;, for example, then the condition will also work, instead of continuing from 1.</p> <p>Thank you very much in advance</p>
[ { "answer_id": 74320983, "author": "Mina", "author_id": 11887902, "author_profile": "https://Stackoverflow.com/users/11887902", "pm_score": 3, "selected": true, "text": "&&" }, { "answer_id": 74321439, "author": "ObieTrz", "author_id": 19643756, "author_profile": "https://Stackoverflow.com/users/19643756", "pm_score": 1, "selected": false, "text": "const valEmail = validateEmail(email);\nconst valPsw = validatePswd(pswd);\n\nif(valEmail && valPsw ){\n //validate entire form and render errors\n}\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74320939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20168083/" ]
74,320,949
<p>I have <code>Filterable</code> module that creates scopes usesd by various models,</p> <pre class="lang-rb prettyprint-override"><code>module Filterable extend ActiveSupport::Concern included do # References scope :filter_eq_reference, -&gt;(val){ where(reference: val) } scope :filter_eq_description, -&gt;(val){ where(description: val) } scope :filter_eq_ref1, -&gt;(val){ where(ref1: val) } scope :filter_eq_ref2, -&gt;(val){ where(ref2: val) } scope :filter_eq_ref3, -&gt;(val){ where(ref3: val) } scope :filter_eq_ref4, -&gt;(val){ where(ref4: val) } scope :filter_eq_ref5, -&gt;(val){ where(ref5: val) } scope :filter_eq_ref6, -&gt;(val){ where(ref6: val) } # Weights scope :filter_eq_weight, -&gt;(val){ where(weight: val) } scope :filter_lt_weight, -&gt;(val){ where('weight &lt; ?', val) } scope :filter_lte_weight,-&gt;(val){ where('weight &lt;= ?', val) } scope :filter_gt_weight, -&gt;(val){ where('weight &gt; ?', val) } scope :filter_gte_weight,-&gt;(val){ where('weight &gt;= ?', val) } # ... end class_methods do end end </code></pre> <p>I want to refactor it for several reasons #1. it's getting large #2. All models don't share the same attributes</p> <p>I came to this</p> <pre class="lang-rb prettyprint-override"><code>module Filterable extend ActiveSupport::Concern FILTER_ATTRIBUTES = ['reference', 'description', 'weight', 'created_at'] included do |base| base.const_get(:FILTER_ATTRIBUTES).each do |filter| class_eval %Q? def self.filter_eq_#{filter}(value) where(#{filter}: value) end ? end end </code></pre> <p>It works, but I want to have the attributes list in the model class, As issue #2, I think it more their responsability So I moved FILTER_ATTRIBUTES in each class including this module The problem when doiing that, I get an error when calling Article.filter_eq_weight 0.5</p> <p>NameError: uninitialized constant #Class:0x000055655ed90f80::FILTER_ATTRIBUTES Did you mean? Article::FILTER_ATTRIBUTES</p> <p>How can I access the base class - having 'base' injected or not doesn't change anything</p> <p>Or maybe better ideas of implementation ? Thanks</p>
[ { "answer_id": 74320983, "author": "Mina", "author_id": 11887902, "author_profile": "https://Stackoverflow.com/users/11887902", "pm_score": 3, "selected": true, "text": "&&" }, { "answer_id": 74321439, "author": "ObieTrz", "author_id": 19643756, "author_profile": "https://Stackoverflow.com/users/19643756", "pm_score": 1, "selected": false, "text": "const valEmail = validateEmail(email);\nconst valPsw = validatePswd(pswd);\n\nif(valEmail && valPsw ){\n //validate entire form and render errors\n}\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74320949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6347040/" ]
74,320,978
<p>I am trying to find a way to insert a curved (or even better a wavy) vertical bar. I have found a <a href="https://fireship.io/lessons/wavy-backgrounds/" rel="nofollow noreferrer">nice bubble pattern</a> I'm trying to replicate. The problem I have is that I don't know how to rotate this 90 degrees so that it's a column border. Other questions I've found have been for horizontal wavy borders. I am looking for a vertical one.</p> <p>This example shows a HORIZONTAL example of what I'd like to accomplish.</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>.bubble::after { content: ''; border-top-left-radius: 50% 100%; border-top-right-radius: 50% 100%; position: absolute; bottom: 0; z-index: -1; width: 100%; background-color: #0f0f10; height: 85%; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;section class="bubble"&gt; &lt;/section&gt;</code></pre> </div> </div> </p> <p>My template looks like this:</p> <pre><code>&lt;html&gt; &lt;head&gt;&lt;/head&gt; &lt;body&gt; &lt;aside&gt; Side bar navigation menu here &lt;/aside&gt; &lt;main&gt; Main content here &lt;/main&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Which looks like this: <a href="https://i.stack.imgur.com/nDjBO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nDjBO.png" alt="Sample two column example" /></a></p> <p>I want that border between the two columns to be &quot;wavy&quot;. How can I accomplish this with only CSS?</p>
[ { "answer_id": 74321283, "author": "Johannes", "author_id": 5641669, "author_profile": "https://Stackoverflow.com/users/5641669", "pm_score": 1, "selected": false, "text": ".bubble::after {\n content: '';\n border-top-right-radius: 80% 50%;\n border-bottom-right-radius: 80% 50%;\n position: absolute;\n top: 0;\n z-index: -1;\n width: 15%;\n background-color: #0f0f10;\n height: 85%;\n}" }, { "answer_id": 74321302, "author": "Ana Correia", "author_id": 19977290, "author_profile": "https://Stackoverflow.com/users/19977290", "pm_score": -1, "selected": false, "text": ".bubble::after {\n content: '';\n border-radius: 0px 120px 120px 0px;\n position: absolute;\n bottom: 0;\n z-index: -1;\n width: 10%;\n background-color: #0f0f10;\n height: 100%;\n}" }, { "answer_id": 74321358, "author": "Laaouatni Anas", "author_id": 17716837, "author_profile": "https://Stackoverflow.com/users/17716837", "pm_score": 2, "selected": false, "text": ".has-wavy {\n --w: 10%; /* we will use a css var so we don't repeat code */\n position: relative;\n}\n\n.has-wavy::after {\n content: \"\";\n height: 100%; \n width: var(--w); /* the width is getted from css var */\n border-radius: 0 100% 100% 0; /* rounding code is very simple like this, just one line */\n position: absolute; \n right: calc(-0.5 * var(--w)); /* the rounded part it will be shown out of the element */\n z-index: -1; /* half part isn't used, so we hide it use z-index */\n background-color: inherit; /* get the element color that it is used dinamically */\n}\n\nhtml,\nbody {\n height: 100%;\n margin: 0;\n}\n\nbody {\n display: flex;\n}\n\nbody * {\n display: flex;\n flex: 1;\n justify-content: center;\n}" }, { "answer_id": 74321567, "author": "FUZIION", "author_id": 13050564, "author_profile": "https://Stackoverflow.com/users/13050564", "pm_score": 2, "selected": false, "text": "clip-path" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74320978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1344579/" ]
74,321,021
<p>I'm a CS student and learning Java. For my assignment, I've created the below UML diagram for the code below. This diagram should contain class name, variables and methods.</p> <p>However, I am not sure if I created a correct UML diagram. I think class name and variables are correct, they are all public data members, but I'm not sure if the method is correct. It seems only method in my code is main method.</p> <p>Can you advise if I'm correct or not please?</p> <p>Code:</p> <pre><code>import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; import java.io.File; public class FileTest { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String fName = &quot;Students.txt&quot;; // variable to store the file name // prompt to user to enter number of names System.out.print(&quot;Enter the number of names: &quot;); int number = sc.nextInt(); // taking number of names // clear the input buffer sc.nextLine(); ArrayList&lt;String&gt; names = new ArrayList&lt;&gt;(number); // arraylist to store the entered names // take number of input names from the user for(int i=0;i&lt;number;i++){ System.out.print(&quot;Enter name &quot; + (i+1) + &quot;: &quot;); String name = sc.nextLine(); names.add(name); // add name into arrayList } // sorting the names list Collections.sort(names); // store all names into the file Students.txt try { FileWriter fw = new FileWriter(fName); // open a file for writing names for(String name:names){ // write names into files Student.txt fw.write(name + &quot;\n&quot;); } fw.close(); // close file } catch (IOException e) { e.printStackTrace(); } //prompt to user to enter a name which you want to elininate from the file System.out.print(&quot;\nEnter a name that you want to eliminated from the file: &quot;); String removeName = sc.nextLine(); // make a temporary file to copy all the names except the names which you want to remove String tempFName = &quot;StudentsTemp.txt&quot;; try { Scanner scan = new Scanner(new File(fName)); // open Student.txt file for reading names // open temp file to write all the data except eliminated name FileWriter fw = new FileWriter(tempFName); // read all data while(scan.hasNextLine()){ String name = scan.nextLine(); // read name //check the readed name with the user entered eliminated name if(name.compareTo(removeName)!=0){ fw.write(name + &quot;\n&quot;); } } // close file fw.close(); //delete the old file File old = new File(fName); old.delete(); File newFile = new File(tempFName); //rename the temporary file to the old file name newFile.renameTo(old); } catch (Exception e) { e.printStackTrace(); } } } </code></pre> <p>UML Diagram: <a href="https://i.stack.imgur.com/IK0Pn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IK0Pn.png" alt="uml diagram" /></a></p> <p>I think only method is main method, but what about rename, delete, compareto, etc.? aren't these methods should be included to uml diagram as well?</p>
[ { "answer_id": 74321593, "author": "hfontanez", "author_id": 2851311, "author_profile": "https://Stackoverflow.com/users/2851311", "pm_score": 0, "selected": false, "text": "+" }, { "answer_id": 74322997, "author": "qwerty_so", "author_id": 3379653, "author_profile": "https://Stackoverflow.com/users/3379653", "pm_score": 2, "selected": false, "text": "main" }, { "answer_id": 74323801, "author": "Christophe", "author_id": 3723423, "author_profile": "https://Stackoverflow.com/users/3723423", "pm_score": 2, "selected": false, "text": "FileTest" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20065644/" ]
74,321,040
<p>I am Trying to make a program in Python to reverse the vowels in a string and return the string like this:</p> <pre><code>vow = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'] vowin = [] place = [] def string(string): for ch in string: if ch in vow: vowin.append(ch) else: continue for ch in string: if ch in vow: index1 = string.index(ch) place.append(index1) else: continue place.reverse() str = list(string) for ch in range(len(place)): str[place[ch]] = vowin[ch] new = ''.join(str) return new print(string('Queen')) </code></pre> <p>When I try to run a word with a double vowel like queen it makes all other vowels into e too like the code above.</p> <p>Output: <code>Qeeen</code></p> <p>but if I input hello the output is holle like it should.</p> <p>Anyone know what the problem is?</p>
[ { "answer_id": 74321593, "author": "hfontanez", "author_id": 2851311, "author_profile": "https://Stackoverflow.com/users/2851311", "pm_score": 0, "selected": false, "text": "+" }, { "answer_id": 74322997, "author": "qwerty_so", "author_id": 3379653, "author_profile": "https://Stackoverflow.com/users/3379653", "pm_score": 2, "selected": false, "text": "main" }, { "answer_id": 74323801, "author": "Christophe", "author_id": 3723423, "author_profile": "https://Stackoverflow.com/users/3723423", "pm_score": 2, "selected": false, "text": "FileTest" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17442150/" ]
74,321,042
<p>Why does calling clear on the iterator here shorten the size of the batches array?</p> <pre><code>ArrayList&lt;String&gt; numbers = new ArrayList&lt;&gt;(Arrays.asList(&quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;, &quot;7&quot;, &quot;8&quot;, &quot;9&quot;, &quot;10&quot;)); List&lt;List&lt;String&gt;&gt; numberBatches = ListUtils.partition(numbers, 2); for(List&lt;String&gt; numberBatch : numberBatches) { for(String number : numberBatch) { System.out.println(number); } numberBatch.clear(); } </code></pre> <p><strong>Output</strong></p> <pre><code>1 2 5 6 9 10 </code></pre>
[ { "answer_id": 74321204, "author": "Rogue", "author_id": 1786065, "author_profile": "https://Stackoverflow.com/users/1786065", "pm_score": 2, "selected": false, "text": "List#clear" }, { "answer_id": 74321205, "author": "knittl", "author_id": 112968, "author_profile": "https://Stackoverflow.com/users/112968", "pm_score": 2, "selected": true, "text": "ListUtils.partition(numbers, 2)" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995514/" ]
74,321,069
<pre><code>import React, { useState } from &quot;react&quot;; import Input from &quot;./components/Input&quot;; import Keep from './components/Keep' export default function App() { const [keeps, setKeeps] = useState(['go','do','make','sleep',]) let keepsList = keeps.map((keep, id)=&gt;{return &lt;Keep value={keep} key={id} /&gt;}) const onSubmit = (e) =&gt; { setKeeps(...keeps, e) console.log(keeps) } return ( &lt;&gt; &lt;div className=&quot;App&quot;&gt; &lt;div className=&quot;Logo&quot;&gt;N13G's Keeps&lt;/div&gt; &lt;Input onSubmit={onSubmit}/&gt; &lt;div className=&quot;KLmain&quot;&gt; { keepsList } &lt;/div&gt; &lt;/div&gt; &lt;/&gt; ) } </code></pre> <p>My kind of analog of Google Keeps doesn't work. It returns an error in a console (keeps.map is not a function).<br /> There's also my Input</p> <pre><code>import React from &quot;react&quot;; function Input ({onSubmit}) { const handleSubmit = (e) =&gt; { e.preventDefault() onSubmit(e.target.value) } return ( &lt;&gt; &lt;form className=&quot;Icont&quot; onSubmit={handleSubmit}&gt; &lt;input type=&quot;text&quot; className=&quot;Iinput&quot;/&gt; &lt;input type=&quot;submit&quot; className=&quot;Ibut&quot; placeholder=&quot;Add&quot; value={&quot;Add&quot;}/&gt; &lt;/form&gt; &lt;/&gt; ) } export default Input </code></pre> <p>I tried to fix this error by classes, but maybe it's a React bug.</p>
[ { "answer_id": 74321204, "author": "Rogue", "author_id": 1786065, "author_profile": "https://Stackoverflow.com/users/1786065", "pm_score": 2, "selected": false, "text": "List#clear" }, { "answer_id": 74321205, "author": "knittl", "author_id": 112968, "author_profile": "https://Stackoverflow.com/users/112968", "pm_score": 2, "selected": true, "text": "ListUtils.partition(numbers, 2)" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20415871/" ]
74,321,082
<p>Working with <code>antd</code> components, if you have an <code>Alert</code> component, inside there is a tooltip that is given the styling through ​<code>ant-alert-icon</code>​ class. So, if we need to override the Tooltip color, you can have in your stylesheet a class to override the values. For example:</p> <pre><code>ant-alert-info { .ant-alert-icon { color: #3d6de7 !important; } } </code></pre> <p>However, this will apply the color #3d6de7 to all Alerts type <code>Info</code>. How can I apply a different color to just one specific Alert type <code>Info</code> while keeping the styling above for the remaining Alert type <code>Info</code> components? Is this possible? What are the alternatives to doing something similar?</p> <p>I am able to change the background of the <code>Alert</code> using the style field as follows:</p> <pre><code> &lt;Alert description={} type=&quot;info&quot; showIcon style={!props.alert ? { backgroundColor: &quot;#F4F0F0&quot;} : { backgroundColor: &quot;#fff2f0&quot;, border: &quot;#ffccc7&quot; }} /&gt; </code></pre> <p>However, I have not been able to change the Tooltip color.</p> <p>Thanks!</p>
[ { "answer_id": 74321191, "author": "yousoumar", "author_id": 15288641, "author_profile": "https://Stackoverflow.com/users/15288641", "pm_score": 2, "selected": true, "text": "ant-alert-info-custom" }, { "answer_id": 74321246, "author": "Farbod Shabani", "author_id": 14712252, "author_profile": "https://Stackoverflow.com/users/14712252", "pm_score": 0, "selected": false, "text": "<ConfigProvider csp={{ nonce: 'YourNonceCode' }}>\n <Button>My Button</Button>\n</ConfigProvider>\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4538768/" ]
74,321,117
<p>Can someone let me know if its possible to pass a parameter and an activity to a For Each in Azure Data Factory.</p> <p>From the image I want to pass the parmater 'relativeURLs' into a For Each.</p> <p><a href="https://i.stack.imgur.com/1xBp4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1xBp4.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/OYALL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OYALL.png" alt="enter image description here" /></a></p> <p>I would then like to do a For Each on the Lookup activity 'CompanyId Lookup Is that possible?</p>
[ { "answer_id": 74321191, "author": "yousoumar", "author_id": 15288641, "author_profile": "https://Stackoverflow.com/users/15288641", "pm_score": 2, "selected": true, "text": "ant-alert-info-custom" }, { "answer_id": 74321246, "author": "Farbod Shabani", "author_id": 14712252, "author_profile": "https://Stackoverflow.com/users/14712252", "pm_score": 0, "selected": false, "text": "<ConfigProvider csp={{ nonce: 'YourNonceCode' }}>\n <Button>My Button</Button>\n</ConfigProvider>\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15520615/" ]
74,321,151
<p>I have to use the assembly code to find the value of P. How do I read this? I am not quite sure how to begin. If anyone could help me by either going through it step by step or just explaining it to me. Either way would be a big help</p> <p>in C:</p> <pre><code>#define P ? #define Q ? int mat1[P][Q]; int mat2[Q][P]; void copy_element( int i, int j) { mat1[ i ][ j ] = mat2[ j ][ i ]; </code></pre> <p>in assembly:</p> <pre><code>copy_element: movslq %edi, %rdi movslq %esi, %rsi movq %rsi, %rax salq $4, %rax subq %rsi, %rax addq %rdi, %rax movl mat2(,%rax,4), %ecx leaq (%rdi, %rdi, 4), %rdx leaq 0(, %rdx, 4), %rax addq %rax, %rsi movl %ecx, mat1,(,%rsi,4) ret </code></pre> <p>My full try:</p> <pre><code>copy_element: movslq %edi, %rdi ?(rdi = i) movslq %esi, %rsi (rsi = j) movq %rsi, %rax (rax = j) salq $4, %rax (rax = 16j) subq %rsi, %rax (rax = 15j) addq %rdi, %rax (rax = 15j + i)? movl mat2(,%rax,4), %ecx (ecx = 60j + 4i)? leaq (%rdi, %rdi, 4), %rdx (rdx = 5i) leaq 0(, %rdx, 4), %rax (rax = 20i)? or maybe (rax = 15j + 21i)? addq %rax, %rsi (rsi = j + 20i) movl %ecx, mat1,(,%rsi,4) what?? (? = 64j + 80i) ret </code></pre> <p>P = 60 and Q = 80?</p> <p>or are they P = 15 and Q = 20?</p> <p>of course both could be wrong</p> <p>(I am sorry if this question is bothersome or if I didn't do something correctly.)</p>
[ { "answer_id": 74321389, "author": "Erik Eidt", "author_id": 471129, "author_profile": "https://Stackoverflow.com/users/471129", "pm_score": 1, "selected": false, "text": "mat1" }, { "answer_id": 74321965, "author": "0___________", "author_id": 6110094, "author_profile": "https://Stackoverflow.com/users/6110094", "pm_score": 0, "selected": false, "text": "int" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20168647/" ]
74,321,155
<p>I want to &quot;surround&quot; all characters in a string with pipes:</p> <pre><code>'abc' =&gt; '|a|b|c|' 'abcde' =&gt; '|a|b|c|d|e|' 'x' =&gt; '|x|' '' =&gt; '|' </code></pre> <p>What's a good way to do it, preferably as a one-line expression? Here's a way with a loop:</p> <pre><code>s = 'abcde' t = '|' for c in s: t += c + '|' print(t) # |a|b|c|d|e| </code></pre>
[ { "answer_id": 74321199, "author": "Larry Panozzo", "author_id": 7760981, "author_profile": "https://Stackoverflow.com/users/7760981", "pm_score": 1, "selected": false, "text": "join" }, { "answer_id": 74321200, "author": "wjandrea", "author_id": 4518341, "author_profile": "https://Stackoverflow.com/users/4518341", "pm_score": 2, "selected": false, "text": "'|'.join()" }, { "answer_id": 74321446, "author": "no comment", "author_id": 16759116, "author_profile": "https://Stackoverflow.com/users/16759116", "pm_score": 3, "selected": false, "text": "s.replace('', '|')\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16759116/" ]
74,321,159
<p>I have a dictionary as follow:</p> <pre><code>d1 = {1:&quot;Peter&quot;, 2:&quot;Teddy&quot;} </code></pre> <p>I want to make it to:</p> <pre><code>d1 = {1:&quot;Peter&quot;, 2:&quot;Teddy&quot;, 3:{&quot;Oliver&quot; : &quot;Big&quot;}} </code></pre> <p>I have tried but it doesn't work:</p> <pre><code>d1[3][&quot;Oliver&quot;]=&quot;Big&quot; </code></pre>
[ { "answer_id": 74321181, "author": "Jedi", "author_id": 6382901, "author_profile": "https://Stackoverflow.com/users/6382901", "pm_score": 2, "selected": false, "text": "d1[3] = {\"Oliver\": \"Big\"}\n" }, { "answer_id": 74321203, "author": "Andromeda", "author_id": 10059628, "author_profile": "https://Stackoverflow.com/users/10059628", "pm_score": 0, "selected": false, "text": "d1[3] = {}\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17217064/" ]
74,321,190
<p>Is there a way to force the zoom from the function <code>facet_zoom()</code> from the package <code>ggforce</code> on the lateral side of the graph instead of the bottom ?</p> <p>I have this code</p> <pre><code>require(dplyr) require(tidyverse) require(ggforce) g + facet_zoom(xlim = c(x1,x2))) </code></pre> <p>How should I proceed?</p> <p><strong>EDIT</strong></p> <p>Through the really good answer provided by Stefan I can add a picture representing what I want (I am definitely open for other ways to reach it).</p> <p><a href="https://i.stack.imgur.com/sDDsF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sDDsF.png" alt="Expected graph" /></a></p>
[ { "answer_id": 74321483, "author": "Isaiah", "author_id": 1738003, "author_profile": "https://Stackoverflow.com/users/1738003", "pm_score": 0, "selected": false, "text": "ggplot(iris, aes(Petal.Length, Petal.Width, colour = Species)) +\n geom_point() +\n facet_zoom(y = Species == 'versicolor')\n" }, { "answer_id": 74321707, "author": "stefan", "author_id": 12993861, "author_profile": "https://Stackoverflow.com/users/12993861", "pm_score": 2, "selected": true, "text": "x" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10370962/" ]
74,321,227
<p>This question arose, while working on this question <a href="https://stackoverflow.com/questions/74320274/replace-list-names-if-they-exist">Replace list names if they exist</a></p> <p><strong>I have this manipulated iris dataset with two vectors:</strong></p> <pre><code>new_name &lt;- c(&quot;new_setoas&quot;, &quot;new_virginica&quot;) to_select &lt;- c(&quot;setosa&quot;, &quot;virginica&quot;) iris %&gt;% group_by(Species) %&gt;% slice(1:2) %&gt;% mutate(Species = as.character(Species)) Sepal.Length Sepal.Width Petal.Length Petal.Width Species &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;chr&gt; 1 5.1 3.5 1.4 0.2 setosa 2 4.9 3 1.4 0.2 setosa 3 7 3.2 4.7 1.4 versicolor 4 6.4 3.2 4.5 1.5 versicolor 5 6.3 3.3 6 2.5 virginica 6 5.8 2.7 5.1 1.9 virginica </code></pre> <p>I would like to replace values in Species selected from a vector (<code>to_select</code>) with values from another vector (<code>new_name</code>)</p> <p><strong>When I do:</strong></p> <pre><code>new_name &lt;- c(&quot;new_setoas&quot;, &quot;new_virginica&quot;) to_select &lt;- c(&quot;setosa&quot;, &quot;virginica&quot;) iris %&gt;% group_by(Species) %&gt;% slice(1:2) %&gt;% mutate(Species = as.character(Species)) %&gt;% mutate(Species = ifelse(Species %in% to_select, new_name, Species)) # I get: Sepal.Length Sepal.Width Petal.Length Petal.Width Species &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;chr&gt; 1 5.1 3.5 1.4 0.2 new_setoas 2 4.9 3 1.4 0.2 **new_virginica** # should be new_setoas 3 7 3.2 4.7 1.4 versicolor 4 6.4 3.2 4.5 1.5 versicolor 5 6.3 3.3 6 2.5 **new_setoas** # should be new_virginica 6 5.8 2.7 5.1 1.9 new_virginica </code></pre> <p>While I know this is happening because of <strong>recycling</strong>. I don't know how to avoid this!</p>
[ { "answer_id": 74321483, "author": "Isaiah", "author_id": 1738003, "author_profile": "https://Stackoverflow.com/users/1738003", "pm_score": 0, "selected": false, "text": "ggplot(iris, aes(Petal.Length, Petal.Width, colour = Species)) +\n geom_point() +\n facet_zoom(y = Species == 'versicolor')\n" }, { "answer_id": 74321707, "author": "stefan", "author_id": 12993861, "author_profile": "https://Stackoverflow.com/users/12993861", "pm_score": 2, "selected": true, "text": "x" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13321647/" ]
74,321,230
<p>I have a .Net project includes <strong>Chart.yaml</strong><br /> I want to set a version in the file when running pipeline.</p> <p><strong>Powershell</strong></p> <pre><code>$newversion = &quot;v5.0.0-a&quot; $chartyaml = &quot;Chart.yaml&quot; $yamlText = (Get-Content $chartyaml) $yamlText.replace('appVersion: .*','appVersion: $newversion') $yamlText &gt; $chartyaml </code></pre> <p><strong>Chart.yaml</strong></p> <pre><code>apiVersion: v2 appVersion: &quot;v5.0.0-a&quot; description: A Helm chart for Kubernetes name: application-api version: &quot;v5.0.0-a&quot; type: application </code></pre>
[ { "answer_id": 74341748, "author": "RoyWang-MSFT", "author_id": 18359635, "author_profile": "https://Stackoverflow.com/users/18359635", "pm_score": 2, "selected": true, "text": " def change_yaml_content(file_path, key, value):\n \n with open(file_path, 'r') as f:\n \n data = yaml.load(f, Loader=yaml.FullLoader)\n \n data[key] = value\n \n with open(file_path, 'w') as f:\n \n yaml.dump(data, f)\n \n\n \n file_path = \"YAML_Folder/Chart.yml\"\n \n key = \"appVersion\"\n \n value = \"1.0.0\"\n \n \n \n change_yaml_content(file_path, key, value)\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10767161/" ]
74,321,259
<p>I have a very large dataset about twitter. I want to be able to compute the mean tweets per hour published by the user. I was able to groupby the tweets per hour per user but now how can I compute the mean per hour?</p> <p>I'm not able to write all the code since the dataset has been heavily preprocessed. In the dataset I have as column <code>user_id</code> and <code>created_at</code> which is a timestamp of the tweet published, so I sorted by <code>created_at</code> and than groupedby till hours</p> <pre><code>grouped_df = tweets_df.sort_values([&quot;created_at&quot;]).groupby([ tweets_df['user_id'], tweets_df['created_at'].dt.year, tweets_df['created_at'].dt.month, tweets_df['created_at'].dt.day, tweets_df['created_at'].dt.hour]) </code></pre> <p>I can count the tweets per hours per user using</p> <pre><code>tweet_per_hour = grouped_df[&quot;created_at&quot;].count() print(tweet_per_hour) </code></pre> <p>what I obtain using this code is</p> <pre><code>user_id created_at created_at created_at created_at 678033 2012 3 11 2 1 14 1 17 1 18 1 4 13 4 1 .. 3164941860 2020 4 30 7 6 9 2 5 1 1 2 9 6 2 6 1 Name: created_at, Length: 3829888, dtype: int64 </code></pre> <p>where the last column is the count of the tweets per hours</p> <pre><code>678033 2012 3 11 2 1 </code></pre> <p>indicates that user the 678033 in the day 2012-03-11 in the range of hour between 2 o'clock and 3 o'clock made just 1 tweet.</p> <p>I need to sum all the tweets per hour made by the user and compute a mean for that user So I want as output for example</p> <pre><code>user_id average_tweets_per_hour 678033 4 665353 10 </code></pre> <p>How can i do it?</p> <p>EDIT This is the reproducible example I have df_t and df_u, df_u_new is what I want to get</p> <pre><code>import pandas as pd import numpy as np df_t = pd.DataFrame({'id_t': [0, 1, 2, 3], 'id_u': [1, 1, 1, 2], 'timestamp': [&quot;2019-06-27 11:12:32&quot;, &quot;2019-06-27 11:14:32&quot;, &quot;2020-07-28 11:24:32&quot;, &quot;2020-02-27 13:30:21&quot;]}) print(df_t) df_u = pd.DataFrame({'id_u': [1, 2]}) print() print(df_u) df_u_new = pd.DataFrame({'id_u': [1, 2], 'avg_t_per_h': [2, 1]}) print() print(df_u_new) </code></pre>
[ { "answer_id": 74321436, "author": "Vincent Rupp", "author_id": 4024409, "author_profile": "https://Stackoverflow.com/users/4024409", "pm_score": 1, "selected": false, "text": "grouped_df.reset_index().groupby(\"user_id\").agg(avgTweetsPerHour = ('created_at','mean'))\n" }, { "answer_id": 74322260, "author": "Sarah Bennett", "author_id": 19897296, "author_profile": "https://Stackoverflow.com/users/19897296", "pm_score": 0, "selected": false, "text": "df.groupby('A').mean()\n" }, { "answer_id": 74362158, "author": "Yolao_21", "author_id": 15283859, "author_profile": "https://Stackoverflow.com/users/15283859", "pm_score": 2, "selected": true, "text": "pd.resample" }, { "answer_id": 74362952, "author": "maxxel_", "author_id": 17575465, "author_profile": "https://Stackoverflow.com/users/17575465", "pm_score": 0, "selected": false, "text": "for index, group in tweets_df.groupby('user_id'):\n ...\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10181236/" ]
74,321,265
<p>I have task with JSONObject, and exactly two JSONArray to retrieve some key and value values and return them as JSONArray:</p> <p>the first JSONArray consists of two objects as below:</p> <pre><code>[{&quot;name&quot;: &quot;John&quot;, &quot;id&quot;: &quot;1&quot;}, {&quot;name&quot;: &quot;Adam&quot;, &quot;id&quot;: &quot;2&quot;}] </code></pre> <p>the second JSONArray consists of three objects (the one with id = 3 is omitted), where &quot;id&quot; is a link between two JSONArray:</p> <pre><code>[{&quot;color:&quot; red &quot;,&quot; id &quot;:&quot; 1 &quot;,&quot; country &quot;:&quot; Poland &quot;}, {&quot; color &quot;:&quot; green &quot;,&quot; id &quot;:&quot; 2 &quot;,&quot; country &quot;:&quot; Germany &quot; }, {&quot;color:&quot; red &quot;,&quot; id &quot;:&quot; 3 &quot;,&quot; country &quot;:&quot; England &quot;}] </code></pre> <p>and finally I would like to get JSONArray where we have two JSONObjects:</p> <pre><code>[{&quot;color:&quot; red &quot;,&quot; name &quot;:&quot; John &quot;,&quot; country &quot;:&quot; Poland &quot;}, {&quot; color &quot;:&quot; green &quot;,&quot; name &quot;:&quot; Adam &quot;,&quot; country &quot;:&quot; Germany &quot; }] </code></pre> <p>Have any of you ever done similar things and would be able to get a tip?</p> <p>Regards, Stan</p> <p>Actually I tried create new JSONObject and next add to JSON Array, but I don't know how get only two JSONObject from second JSONArray and finally get expected result JSONArray.</p>
[ { "answer_id": 74321436, "author": "Vincent Rupp", "author_id": 4024409, "author_profile": "https://Stackoverflow.com/users/4024409", "pm_score": 1, "selected": false, "text": "grouped_df.reset_index().groupby(\"user_id\").agg(avgTweetsPerHour = ('created_at','mean'))\n" }, { "answer_id": 74322260, "author": "Sarah Bennett", "author_id": 19897296, "author_profile": "https://Stackoverflow.com/users/19897296", "pm_score": 0, "selected": false, "text": "df.groupby('A').mean()\n" }, { "answer_id": 74362158, "author": "Yolao_21", "author_id": 15283859, "author_profile": "https://Stackoverflow.com/users/15283859", "pm_score": 2, "selected": true, "text": "pd.resample" }, { "answer_id": 74362952, "author": "maxxel_", "author_id": 17575465, "author_profile": "https://Stackoverflow.com/users/17575465", "pm_score": 0, "selected": false, "text": "for index, group in tweets_df.groupby('user_id'):\n ...\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15004871/" ]
74,321,272
<p>I want to send auto messge on whatsapp, i am creating a news app i need when created a news from admin panel then autometically send news details in whatsapp groups and contacts without any confirmaion. just news creating and auto sending news on whatsapp.....???</p> <p>send auto news on whatsapp groups and contacts</p>
[ { "answer_id": 74321436, "author": "Vincent Rupp", "author_id": 4024409, "author_profile": "https://Stackoverflow.com/users/4024409", "pm_score": 1, "selected": false, "text": "grouped_df.reset_index().groupby(\"user_id\").agg(avgTweetsPerHour = ('created_at','mean'))\n" }, { "answer_id": 74322260, "author": "Sarah Bennett", "author_id": 19897296, "author_profile": "https://Stackoverflow.com/users/19897296", "pm_score": 0, "selected": false, "text": "df.groupby('A').mean()\n" }, { "answer_id": 74362158, "author": "Yolao_21", "author_id": 15283859, "author_profile": "https://Stackoverflow.com/users/15283859", "pm_score": 2, "selected": true, "text": "pd.resample" }, { "answer_id": 74362952, "author": "maxxel_", "author_id": 17575465, "author_profile": "https://Stackoverflow.com/users/17575465", "pm_score": 0, "selected": false, "text": "for index, group in tweets_df.groupby('user_id'):\n ...\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16264806/" ]
74,321,310
<p>I am performing tests in karate framework, where I must send a payload that contains a security certificate, in postman the response is satisfactory, but when performing the same operation in karate, it returns error 400, according to what I have investigated, karate changes the format of my payload (example: beautufy), this causes spaces to be added and the API response to be 400, since the JSON was not valid:</p> <p>this is payload:</p> <pre><code>{ &quot;data&quot;: { &quot;initiation&quot;: { &quot;creditor_account&quot;: { &quot;account_type&quot;: &quot;CUENTA_CORRIENTE&quot;, &quot;bank_id&quot;: &quot;0031&quot;, &quot;account_schema&quot;: &quot;BICECONNECT.PAYMENTS&quot;, &quot;identification&quot;: &quot;90354&quot;, &quot;user_identification&quot;: { &quot;name&quot;: &quot;Abono&quot;, &quot;id_schema&quot;: &quot;CLID&quot;, &quot;id&quot;: &quot;963708&quot;, &quot;email&quot;: &quot;algo@bice.cl&quot; } }, &quot;debtor_account&quot;: { &quot;account_type&quot;: &quot;CUENTA_CORRIENTE&quot;, &quot;bank_id&quot;: &quot;0028&quot;, &quot;account_schema&quot;: &quot;BICECONNECT.PAYMENTS&quot;, &quot;identification&quot;: &quot;01362364&quot;, &quot;user_identification&quot;: { &quot;name&quot;: &quot;Cargo&quot;, &quot;id_schema&quot;: &quot;CLID&quot;, &quot;id&quot;: &quot;44&quot;, &quot;email&quot;: &quot;algo@bice.cl&quot; } }, &quot;instructed_amount&quot;: { &quot;amount&quot;: &quot;901&quot;, &quot;currency&quot;: &quot;CLP&quot; }, &quot;sender&quot;: { &quot;id_schema&quot;: &quot;BICECONNECT.SENDER&quot;, &quot;id&quot;: &quot;Shinka&quot;, &quot;transaction_id&quot;: &quot;d58093ca-f9f5-ef-5143e2d41ba4&quot;, &quot;creation_date&quot;: &quot;2022-11-04T18:02:14.574&quot;, &quot;callback_url&quot;: &quot;https://postman-echo.com/post&quot; }, &quot;transaction_details&quot;: { &quot;transaction_type&quot;: &quot;payout&quot;, &quot;transaction_subtype&quot;: &quot;transferencia&quot;, &quot;transaction_route&quot;: &quot;CCA&quot;, &quot;description&quot;: &quot;Paciencia, el apuro no conduce a nada&quot; } } }, &quot;attachments&quot;: { &quot;original_message&quot;: { &quot;protected&quot;: &quot;&lt;secret-string&gt;&quot;, &quot;payload&quot;: &quot;{\&quot;document\&quot;:{\&quot;header\&quot;:{\&quot;message_id\&quot;:\&quot;f9841bc5-d03c-4364-bcd8-ea0caf8b1c8b\&quot;,\&quot;creation_date\&quot;:\&quot;2022-11-04T18:02:14.574\&quot;,\&quot;sender\&quot;:{\&quot;fin_id_schema\&quot;:\&quot;SHINKANSEN\&quot;,\&quot;fin_id\&quot;:\&quot;BUK\&quot;},\&quot;receiver\&quot;:{\&quot;fin_id_schema\&quot;:\&quot;BICECONNECT.SENDER\&quot;,\&quot;fin_id\&quot;:\&quot;Shinkansen\&quot;}},\&quot;transactions\&quot;:[{\&quot;transaction_type\&quot;:\&quot;payout\&quot;,\&quot;transaction_id\&quot;:\&quot;d58093ca-f9f5-4a70-8def-5143e2d41ba4\&quot;,\&quot;currency\&quot;:\&quot;CLP\&quot;,\&quot;amount\&quot;:\&quot;901\&quot;,\&quot;execution_date\&quot;:\&quot;2022-11-04T18:02:14.574\&quot;,\&quot;description\&quot;:\&quot;Paciencia, el apuro no conduce a nada\&quot;,\&quot;debtor\&quot;:{\&quot;name\&quot;:\&quot;Cargo\&quot;,\&quot;email\&quot;:\&quot;sebastian.fuenzalida@bice.cl\&quot;,\&quot;identification\&quot;:{\&quot;id_schema\&quot;:\&quot;CLID\&quot;,\&quot;id\&quot;:\&quot;8000000001\&quot;},\&quot;financial_institution\&quot;:{\&quot;fin_id_schema\&quot;:\&quot;BICECONNECT.PAYMENTS\&quot;,\&quot;fin_id\&quot;:\&quot;0028\&quot;},\&quot;account_type\&quot;:\&quot;CUENTA_CORRIENTE\&quot;,\&quot;account\&quot;:\&quot;01362364\&quot;},\&quot;creditor\&quot;:{\&quot;name\&quot;:\&quot;Abono\&quot;,\&quot;email\&quot;:\&quot;rafael.cruz@bice.cl\&quot;,\&quot;identification\&quot;:{\&quot;id_schema\&quot;:\&quot;CLID\&quot;,\&quot;id\&quot;:\&quot;967713708\&quot;},\&quot;financial_institution\&quot;:{\&quot;fin_id_schema\&quot;:\&quot;BICECONNECT.PAYMENTS\&quot;,\&quot;fin_id\&quot;:\&quot;0031\&quot;},\&quot;account_type\&quot;:\&quot;CUENTA_CORRIENTE\&quot;,\&quot;account\&quot;:\&quot;4\&quot;}}]}}&quot;, &quot;signature&quot;: &quot;&lt;signature-string&gt;&quot; } } } </code></pre> <p>I expected a 201 as an answer</p> <p>pdta: the payload I sent is copied from another API response, which comes with text</p>
[ { "answer_id": 74321436, "author": "Vincent Rupp", "author_id": 4024409, "author_profile": "https://Stackoverflow.com/users/4024409", "pm_score": 1, "selected": false, "text": "grouped_df.reset_index().groupby(\"user_id\").agg(avgTweetsPerHour = ('created_at','mean'))\n" }, { "answer_id": 74322260, "author": "Sarah Bennett", "author_id": 19897296, "author_profile": "https://Stackoverflow.com/users/19897296", "pm_score": 0, "selected": false, "text": "df.groupby('A').mean()\n" }, { "answer_id": 74362158, "author": "Yolao_21", "author_id": 15283859, "author_profile": "https://Stackoverflow.com/users/15283859", "pm_score": 2, "selected": true, "text": "pd.resample" }, { "answer_id": 74362952, "author": "maxxel_", "author_id": 17575465, "author_profile": "https://Stackoverflow.com/users/17575465", "pm_score": 0, "selected": false, "text": "for index, group in tweets_df.groupby('user_id'):\n ...\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11575190/" ]
74,321,430
<p>Using this formula returns values in two separate columns:</p> <p><code>=ARRAYFORMULA(REGEXEXTRACT(A2:A, &quot;(.+)\?|(.+)\&quot;&quot;&quot;))</code></p> <p>How can I modify this to return everything in the same column? It works if I remove the parentheses (), but then the last character ? or &quot; will appear at the end.</p>
[ { "answer_id": 74321436, "author": "Vincent Rupp", "author_id": 4024409, "author_profile": "https://Stackoverflow.com/users/4024409", "pm_score": 1, "selected": false, "text": "grouped_df.reset_index().groupby(\"user_id\").agg(avgTweetsPerHour = ('created_at','mean'))\n" }, { "answer_id": 74322260, "author": "Sarah Bennett", "author_id": 19897296, "author_profile": "https://Stackoverflow.com/users/19897296", "pm_score": 0, "selected": false, "text": "df.groupby('A').mean()\n" }, { "answer_id": 74362158, "author": "Yolao_21", "author_id": 15283859, "author_profile": "https://Stackoverflow.com/users/15283859", "pm_score": 2, "selected": true, "text": "pd.resample" }, { "answer_id": 74362952, "author": "maxxel_", "author_id": 17575465, "author_profile": "https://Stackoverflow.com/users/17575465", "pm_score": 0, "selected": false, "text": "for index, group in tweets_df.groupby('user_id'):\n ...\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19120926/" ]
74,321,457
<p>I am trying to create a Library and add information that is entered into my form (form is in popup window) to appear in a div (bookCard) within my grid. I was able to create an eventListener for the submit button and make my div (bookCard) appear. However, I am unable to display the input from my form on the bookCard div. How can I add to the function to make the inputs appear and display there when it is entered? Is there something I am missing within the addBookToLibrary function?</p> <p>Thank you in advance for your help.</p> <p>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;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;!----GitHub icon--&gt; &lt;script src=&quot;https://kit.fontawesome.com/4c536a6bd5.js&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt; &lt;!----------Font Below ----------------&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;https://use.typekit.net/jmq2vxa.css&quot;&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;styles.css&quot;&gt; &lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; href=&quot;images/open-book.png&quot;/&gt; &lt;title&gt;My Library&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div class=&quot;head-box&quot;&gt; &lt;h1&gt;My Library&lt;/h1&gt; &lt;/div&gt; &lt;main class =&quot;main-container&quot;&gt; &lt;div class=&quot;body-box&quot;&gt; &lt;button id=&quot;addBook&quot;&gt;Add Book&lt;/button&gt; &lt;/div&gt; &lt;div class=&quot;books-grid&quot; id=&quot;booksGrid&quot;&gt; &lt;div class=&quot;library-container&quot; id=&quot;library-container&quot;&gt;&lt;/div&gt; &lt;/div&gt; &lt;/main&gt; &lt;!-----Form information-----&gt; &lt;div class=&quot;form-popup&quot;&gt; &lt;div class=&quot;form-content&quot; &lt;form action=&quot;example.com/path&quot; class=&quot;form-container&quot; id=&quot;popUpForm&quot;&gt; &lt;h3&gt;add new book&lt;/h3&gt; &lt;input class=&quot;input&quot; type=&quot;text&quot; id=&quot;title&quot; placeholder=&quot;Title&quot; required maxlength=&quot;100&quot;&gt; &lt;input type=&quot;author&quot; id=&quot;author&quot; placeholder=&quot;Author&quot; required maxlength=&quot;100&quot;&gt; &lt;input type=&quot;number&quot; id=&quot;pages&quot; placeholder=&quot;Pages&quot; required max=&quot;10000&quot;&gt; &lt;div class=&quot;isRead&quot;&gt; &lt;label for=&quot;readOption&quot;&gt;Have you read it?&lt;/label&gt; &lt;input type=&quot;checkbox&quot; id=&quot;readOption&quot; name=&quot;readOption&quot;&gt; &lt;/div&gt; &lt;button class=&quot;btn submit&quot; type=&quot;submit&quot; id=&quot;submit&quot;&gt;Submit&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id=&quot;overlay&quot;&gt;&lt;/div&gt; &lt;div id=&quot;invisibleDiv&quot;&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>CSS</p> <pre><code>/*CSS RESET*/ * { margin:0; padding:0; } h1 { font-family: ohno-blazeface, sans-serif; font-weight: 100; font-style: normal; font-size: 8vh; color: #001D4A; } .head-box { background-color: #9DD1F1; display: flex; align-items: center; justify-content: center; height: 20vh; border-bottom: 2px solid #e0f3ff; } h2 { font-family: poppins, sans-serif; font-weight: 300; font-style: normal; font-size: 5vh; color: #001D4A; } h3 { font-family: ohno-blazeface, sans-serif; font-weight: 100; font-style: normal; font-size: 4vh; color: #001D4A; } button { height: 10vh; width: 20vh; min-width: 20vh; min-height: 10vh; font-size: 3vh; background-color: #27476E; border-radius: 22px; border-style: none; font-family: poppins, sans-serif; font-weight: 300; font-style: normal; color:#ffffff; } button:hover { background-color: #192c44; } body { min-height: 100vh; background: linear-gradient(180deg,#d0edff,#9DD1F1) no-repeat; } .body-box { margin: 3vh; display: flex; justify-content: center; } /* The pop up form - hidden by default */ .form-popup { display: none; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 9; } .form-content { text-align: center; border-radius: 20px; width: 30vh; height: auto; border: 3px solid #001D4A; padding: 20px; background-color: #9DD1F1; gap: 10px; } .form-container { min-width: 20vh; min-height: 50vh; } .isRead{ display: flex; height: 30px; width: 100%; margin: 2px; align-items: center; justify-content: center; } label { font-family: poppins, sans-serif; font-weight: 600; font-style: normal; font-size: 2.5vh; } input { border-radius: 10px; height: 50px; margin: 3px; width: 100%; padding: 4px; background-color: #d0edff; border: none; font-family: poppins, sans-serif; font-weight: 300; font-size: 2.5vh; } #submit { margin-top: 4px; height: 20px; width: 100%; border-radius: 15px; color: #ffffff; border: none; } input[type=checkbox] { width: 20px; margin: 10px; } #invisibleDiv { position: fixed; height: 100%; width: 100%; } #overlay { position: fixed; top: 0; left: 0; display: none; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); } .books-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); } /* BOOK CARD */ #library-container { display: none; height: 50vh; width: 50vh; border-radius: 15px; border: 5px solid #ffffff; background-color: #d0edff; flex-direction: column; justify-content: space-between; margin: 28px; } </code></pre> <p>JS</p> <pre><code>class book { constructor(title, author, pages, read) { this.title = form.title.value; this.author = form.author.value; this.pages = form.pages.value + 'pages'; this.read = form.read.checked; } } //creates book from Book Constructor, adds to library let myLibrary = []; function addBookToLibrary(book) { const bookTitle = document.getElementById('title').value; const bookAuthor = document.getElementById('author').value; const bookPages = document.getElementById('pages').value; } // User interface // const popUpForm = document.querySelector('.form-popup'); const button = document.getElementById('addBook'); const overlay = document.getElementById('overlay'); const booksGrid = document.getElementById('booksGrid'); const bookCard = document.querySelector('.library-container'); const form = document.querySelector('.form-container'); const submitBtn = document.getElementById('submit'); // Form Pop Up function // document.getElementById('invisibleDiv').onclick = function() { popUpForm.style.display = &quot;none&quot;; overlay.style.display = &quot;none&quot;; }; button.addEventListener(&quot;click&quot;, () =&gt; { popUpForm.style.display = &quot;block&quot;; overlay.style.display = &quot;block&quot;; }); // Submit Button Event Listener (displays bookCard) // submitBtn.addEventListener(&quot;click&quot;, () =&gt; { bookCard.style.display = &quot;block&quot;; popUpForm.style.display = &quot;none&quot;; overlay.style.display = &quot;none&quot;; addBookToLibrary(); }); </code></pre>
[ { "answer_id": 74321436, "author": "Vincent Rupp", "author_id": 4024409, "author_profile": "https://Stackoverflow.com/users/4024409", "pm_score": 1, "selected": false, "text": "grouped_df.reset_index().groupby(\"user_id\").agg(avgTweetsPerHour = ('created_at','mean'))\n" }, { "answer_id": 74322260, "author": "Sarah Bennett", "author_id": 19897296, "author_profile": "https://Stackoverflow.com/users/19897296", "pm_score": 0, "selected": false, "text": "df.groupby('A').mean()\n" }, { "answer_id": 74362158, "author": "Yolao_21", "author_id": 15283859, "author_profile": "https://Stackoverflow.com/users/15283859", "pm_score": 2, "selected": true, "text": "pd.resample" }, { "answer_id": 74362952, "author": "maxxel_", "author_id": 17575465, "author_profile": "https://Stackoverflow.com/users/17575465", "pm_score": 0, "selected": false, "text": "for index, group in tweets_df.groupby('user_id'):\n ...\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18013003/" ]
74,321,496
<p>LeetCode: longest consecutive sequence</p> <p>Question:Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.</p> <p>You must write an algorithm that runs in O(n) time.</p> <p>Example 1:</p> <p>Input: nums = [100,4,200,1,3,2] Output: 4 Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. Example 2:</p> <p>Input: nums = [0,3,7,2,5,8,4,6,0,1] Output: 9</p> <pre><code>class Solution: def longestConsecutive(self, nums: List[int]) -&gt; int: nums = [0,3,7,2,5,8,4,6,0,1] nums = list(set(nums)) # O(n) operation res = 0 count = 1 if len(nums)==1: # edge case res = 1 for i in range(len(nums)-1): if abs(nums[i] - nums[i+1]) == 1: count+=1 print(count) else: res = max(res, count) count = 1 print(res)``` this prints as follows (print(count)) adds an unneccessary 2 3 4 5 6 7 8 9 0 And when input is nums = [100,4,200,1,3,2] Output is for print(count): 2 3 3 Count variable is misbehaving </code></pre>
[ { "answer_id": 74321436, "author": "Vincent Rupp", "author_id": 4024409, "author_profile": "https://Stackoverflow.com/users/4024409", "pm_score": 1, "selected": false, "text": "grouped_df.reset_index().groupby(\"user_id\").agg(avgTweetsPerHour = ('created_at','mean'))\n" }, { "answer_id": 74322260, "author": "Sarah Bennett", "author_id": 19897296, "author_profile": "https://Stackoverflow.com/users/19897296", "pm_score": 0, "selected": false, "text": "df.groupby('A').mean()\n" }, { "answer_id": 74362158, "author": "Yolao_21", "author_id": 15283859, "author_profile": "https://Stackoverflow.com/users/15283859", "pm_score": 2, "selected": true, "text": "pd.resample" }, { "answer_id": 74362952, "author": "maxxel_", "author_id": 17575465, "author_profile": "https://Stackoverflow.com/users/17575465", "pm_score": 0, "selected": false, "text": "for index, group in tweets_df.groupby('user_id'):\n ...\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19362230/" ]
74,321,500
<p><a href="https://i.stack.imgur.com/JExlK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JExlK.png" alt="enter image description here" /></a></p> <p>I am trying some julia code as shown here:</p> <p><a href="https://i.stack.imgur.com/7jUu2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7jUu2.png" alt="enter image description here" /></a></p> <p>However, I get an error:</p> <p><a href="https://i.stack.imgur.com/bf4bZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bf4bZ.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74322859, "author": "Oscar Smith", "author_id": 5141328, "author_profile": "https://Stackoverflow.com/users/5141328", "pm_score": 1, "selected": false, "text": "1" }, { "answer_id": 74326485, "author": "Przemyslaw Szufel", "author_id": 9957710, "author_profile": "https://Stackoverflow.com/users/9957710", "pm_score": 0, "selected": false, "text": "data = DataFrame(a=1:6, b='a':'f');\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15510950/" ]
74,321,512
<p>My class have been tasked with making a simple web based kids game using basic JQuery. I've been told JQuery is becoming more old school, but never the less, that's what we've to use along with HTML/CSS and JS to make the game.</p> <p>I've been googling for a while now and can't quite find what I'm looking for.</p> <p>My first screen is asking the user to select one of four displayed avatars and to enter their name which will be stored and shown throughout the game in the top corner.</p> <p>I thought the best way to choose the avatars may be to do a radio button (button is hidden but the avatar image has a border when clicked on). I was trying to make a function that stores the selected image into a variable which I can then display whenever/wherever on the page but my brain is blanking on how to do this.</p> <p>I expect the code will most likely be very simple and obvious and I'm maybe overthinking it. Thanks to anyone who takes time to help me - also this is my first post here so please excuse any formatting.</p> <p>This is the code I have for the selection of the avatars:</p> <pre><code> &lt;div class=&quot;avatarselection&quot;&gt; &lt;label&gt; &lt;input type=&quot;radio&quot; name=&quot;test&quot; checked /&gt; &lt;img src=&quot;Elements/images/Avatar1.png&quot; alt=&quot;Blue Planet Avatar&quot; class=&quot;Avatar Planet&quot; /&gt;&lt;/label&gt; &lt;label&gt; &lt;input type=&quot;radio&quot; name=&quot;test&quot; checked /&gt; &lt;img src=&quot;Elements/images/Avatar2.png&quot; alt=&quot;Pink Spaceman Avatar&quot; class=&quot;Avatar Spaceman&quot; /&gt;&lt;/label&gt; &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;test&quot; checked /&gt; &lt;img src=&quot;Elements/images/Avatar3.png&quot; alt=&quot;Multicolour Spaceship Avatar&quot; class=&quot;Avatar Spaceship&quot; /&gt;&lt;/label&gt; &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;test&quot; checked /&gt; &lt;img src=&quot;Elements/images/Avatar4.png&quot; alt=&quot;Earth Planet Avatar&quot; class=&quot;Avatar Earth&quot; /&gt;&lt;/label&gt; &lt;button class=&quot;setAvatar&quot;&gt;Save Avatar&lt;/button&gt; &lt;div class=&quot;showavatar&quot;&gt;&lt;/div&gt; //this div is for me to test if the avatar is stored in the variable &lt;/div&gt; </code></pre> <p>This is the script I have so far to just store the name in a varible which is in a different div from the avatar selection - I'm including it because I feel like the avatar storing may be something similar... or I've just done it completely wrong!</p> <pre><code>$(&quot;.enter&quot;).on(&quot;click&quot;, displayName); //$(&quot;.setAvatar&quot;).on(&quot;click&quot;, displayAvatar); let nameValue = $(&quot;.name&quot;).val(); function displayName(){ $(&quot;.submitted&quot;).text(&quot;Welcome &quot; + nameValue + &quot;!&quot;); } /* I thought this may have been what I was looking for, but clearly isn't let selectedavatar = $(&quot;input[type='radio']:checked&quot;).val(); function displayAvatar() { $(&quot;.showavatar&quot;).html(&quot;&lt;img src=&quot; + selectedavatar + &quot;/&gt;&quot;); } */ </code></pre> <p>Answered! My issue was the file path on my second html folder plus I needed to do localstorage. Thanks!</p>
[ { "answer_id": 74322023, "author": "jyoung37", "author_id": 20408463, "author_profile": "https://Stackoverflow.com/users/20408463", "pm_score": 0, "selected": false, "text": "<input type=\"radio\" name=\"test\" value=\"Elements/images/Avatar2.png\" checked />\n" }, { "answer_id": 74322102, "author": "ObieTrz", "author_id": 19643756, "author_profile": "https://Stackoverflow.com/users/19643756", "pm_score": 1, "selected": true, "text": "var selectedavatarImg = $(\"input[type='radio']:checked\").attr(\"src\");\n" }, { "answer_id": 74340298, "author": "ObieTrz", "author_id": 19643756, "author_profile": "https://Stackoverflow.com/users/19643756", "pm_score": -1, "selected": false, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js\"></script>\n <title>Parcel Sandbox</title>\n <meta charset=\"UTF-8\" />\n </head>\n\n <body>\n <h2>Trying to help </h2>\n <div class=\"avatarselection\">\n <label>\n <input type=\"radio\" name=\"test\" value=\"https://cdn.icon-icons.com/icons2/1378/PNG/512/avatardefault_92824.png\"/>\n <img\n src=\"https://cdn.icon-icons.com/icons2/1378/PNG/512/avatardefault_92824.png\"\n value=\"https://cdn.icon-icons.com/icons2/1378/PNG/512/avatardefault_92824.png\"\n alt=\"Blue Planet Avatar\"\n class=\"Avatar Planet\"\n width=\"50\"\n height=\"50\" /></label\n ><br />\n <label>\n <input type=\"radio\" name=\"test\" value=\"https://cdn2.iconfinder.com/data/icons/essenstial-ultimate-ui/64/avatar-512.png\"/>\n <img\n src=\"https://cdn2.iconfinder.com/data/icons/essenstial-ultimate-ui/64/avatar-512.png\"\n alt=\"Pink Spaceman Avatar\"\n class=\"Avatar Spaceman\"\n width=\"50\"\n height=\"50\" /></label\n ><br />\n <label\n ><input type=\"radio\" name=\"test\" value=\"https://i.pinimg.com/564x/4b/71/f8/4b71f8137985eaa992d17a315997791e.jpg\"/>\n <img\n src=\"https://i.pinimg.com/564x/4b/71/f8/4b71f8137985eaa992d17a315997791e.jpg\"\n alt=\"Multicolour Spaceship Avatar\"\n class=\"Avatar Spaceship\"\n width=\"50\"\n height=\"50\" /></label\n ><br />\n <label\n ><input type=\"radio\" name=\"test\" value=\"https://cdn.pixabay.com/photo/2020/07/14/13/07/icon-5404125_1280.png\"/>\n <img\n src=\"https://cdn.pixabay.com/photo/2020/07/14/13/07/icon-5404125_1280.png\"\n alt=\"Earth Planet Avatar\"\n class=\"Avatar Earth\"\n width=\"50\"\n height=\"50\" /></label\n ><br /><br />\n\n <button class=\"setAvatar\">Save Avatar</button>\n <div class=\"showavatar\"></div>\n </div>\n\n <script src=\"src/index.js\"></script>\n <script>\n $(document).ready(function () {\n $(\".setAvatar\").click(function () {\n var selectedavatarImg = $(\"input[type='radio']:checked\").val();\n $(\".showavatar\").html(\n \"<img src='\" + selectedavatarImg + \"' width= '100' height='100'/>\"\n );\n });\n });\n </script>\n </body>\n</html>" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20420199/" ]
74,321,572
<pre><code>def biggestWithPos(A): answer = 0 for i in A: if i &gt; answer: answer = i return (answer) </code></pre> <p>Why is it that when I change <code>answer = i</code> to <code>answer = A[i]</code> I get the error: <code>list index out of range</code>?</p>
[ { "answer_id": 74321634, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 1, "selected": false, "text": "for i in A:\n" }, { "answer_id": 74321663, "author": "CFV", "author_id": 8551315, "author_profile": "https://Stackoverflow.com/users/8551315", "pm_score": 0, "selected": false, "text": "for i in A" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17282081/" ]
74,321,592
<p>Data (I've incorporated some extra steps because I receive the data in a particular form):</p> <pre><code> import numpy as np import pandas as pd d1 = pd.DataFrame({&quot;Date&quot; : ['1/1/2022', '12/15/2010', '6/1/2015', '1/31/2022', '12/31/2010', '3/10/2009', '1/7/2022', '12/9/2010','12/20/2010','1/13/2022'], &quot;Expense&quot;: ['Food', 'Food', 'Gasoline', 'Coffee', 'Coffee', 'PayPal', 'Gasoline', 'Gasoline','Gasoline','Coffee'], &quot;Total&quot;: [3.89, 7.00, 11, 0.99, 8.01, 99, 76, 50,48,9]}) #Change Date column to datetime d1['Date'] = pd.to_datetime(d1['Date']) #Create MMM-YY columm from Date column d1['MMM-YY'] = d1['Date'].dt.strftime('%b') + '-' + d1['Date'].dt.strftime('%y') #Sort DataFrame by Date d1.sort_values('Date', inplace=True) d1 Date Expense Total MMM-YY 5 2009-03-10 PayPal 99.00 Mar-09 7 2010-12-09 Gasoline 50.00 Dec-10 1 2010-12-15 Food 7.00 Dec-10 8 2010-12-20 Gasoline 48.00 Dec-10 4 2010-12-31 Coffee 8.01 Dec-10 2 2015-06-01 Gasoline 11.00 Jun-15 0 2022-01-01 Food 3.89 Jan-22 6 2022-01-07 Gasoline 76.00 Jan-22 9 2022-01-13 Coffee 9.00 Jan-22 3 2022-01-31 Coffee 0.99 Jan-22 </code></pre> <p>I want to sum the Total column for every expense type within every month (entry in MMM-YY). <strong>Here's the important part: I want to keep the MMM-YY column in increasing order (just like d1 DataFrame), but I want the Expense column to be sorted alphabetically.</strong> Here is the desired output after applying groupby:</p> <pre><code> MMM-YY Expense Mar-09 PayPal 99.00 Dec-10 Coffee 8.01 Food 7.00 Gasoline 98.00 Jun-15 Gasoline 11.00 Jan-22 Coffee 9.99 Food 3.89 Gasoline 76.00 </code></pre> <p>Notice how the MMM-YY column remains in ascending order, but the expense column is organized alphabetically within each group with multiple rows.</p> <p>Thank you!</p>
[ { "answer_id": 74321634, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 1, "selected": false, "text": "for i in A:\n" }, { "answer_id": 74321663, "author": "CFV", "author_id": 8551315, "author_profile": "https://Stackoverflow.com/users/8551315", "pm_score": 0, "selected": false, "text": "for i in A" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20188834/" ]
74,321,661
<p>I am trying to push a string into an array, I have multiple arrays inside properties. I want to choose what property I am pushing it into using a function call but I can't seem to do it.</p> <pre><code>var aObj = { prop5: [&quot;nameA5.1&quot;, &quot;nameA5.2&quot;], prop6: [&quot;nameA6.1&quot;, &quot;nameA6.2&quot;] }; function func (propX, namn) { var asd = aObj.prop5.push(namn); return aObj; }; console.log(func(&quot;&quot;,&quot;test text&quot;)); </code></pre> <p>This code above works but not like I want it to. Now I can only push something into the property named &quot;prop5, I want to choose what object when I call my function.</p> <p>I tried to just change this:</p> <pre><code>var asd = aObj.prop5.push(namn); </code></pre> <p>to this:</p> <pre><code>var asd = aObj.propX.push(namn); </code></pre> <p>So whenever I call the &quot;propX&quot; I can choose what object I am calling,but I couldn't do that.</p> <p>I get the error &quot;TypeError: Cannot read properties of undefined (reading 'push')&quot;</p>
[ { "answer_id": 74321708, "author": "Axekan", "author_id": 12519793, "author_profile": "https://Stackoverflow.com/users/12519793", "pm_score": 3, "selected": true, "text": "[]" }, { "answer_id": 74321782, "author": "Mina", "author_id": 11887902, "author_profile": "https://Stackoverflow.com/users/11887902", "pm_score": 1, "selected": false, "text": "array" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20419896/" ]
74,321,671
<p>I have the following code adapted to check if a range overlaps:</p> <pre><code>function isOverlapping(prevHighLow, currentHighLow) { const a = prevHighLow[0]; const b = prevHighLow[1]; const c = currentHighLow[0]; const d = currentHighLow[1]; if (a &lt; d &amp;&amp; b &gt; c) { return true; } return false; } var prevHighLow = [12350, 12900] var currentHighLow = [12100, 12800] console.log(isOverlapping(prevHighLow, currentHighLow)) //returns true </code></pre> <p>It works 100%, however I would like to also return a percentage (from 0 to 100%) of how much they overlap?</p> <p>Thank you!</p>
[ { "answer_id": 74321708, "author": "Axekan", "author_id": 12519793, "author_profile": "https://Stackoverflow.com/users/12519793", "pm_score": 3, "selected": true, "text": "[]" }, { "answer_id": 74321782, "author": "Mina", "author_id": 11887902, "author_profile": "https://Stackoverflow.com/users/11887902", "pm_score": 1, "selected": false, "text": "array" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11353477/" ]
74,321,674
<p>I would like to reverse this: A solution taken from here <a href="https://stackoverflow.com/questions/72278230/one-liner-to-concatenate-two-data-frames-with-a-distinguishing-column#72278388">One-liner to concatenate two data frames with a distinguishing column?</a></p> <pre><code>library(dplyr) bind_rows(list(A = df1, B = df2), .id = 'id') </code></pre> <p>Here we assign the names of each data frame in a list to a column named <code>id</code> in each data frame in the list.</p> <p><strong>Now how can I do the reverse:</strong> E.g when the name is stored in the column called <code>id</code> -&gt; to rename each dataframe in the list:</p> <p>An example This is <code>my_list</code>:</p> <pre><code>[[1]] # A tibble: 2 x 5 Sepal.Length Sepal.Width Petal.Length Petal.Width Species &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;chr&gt; 1 5.1 3.5 1.4 0.2 new_setoas 2 4.9 3 1.4 0.2 new_setoas [[2]] # A tibble: 2 x 5 Sepal.Length Sepal.Width Petal.Length Petal.Width Species &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;chr&gt; 1 6.3 3.3 6 2.5 new_virginica 2 5.8 2.7 5.1 1.9 new_virginica [[3]] # A tibble: 2 x 5 Sepal.Length Sepal.Width Petal.Length Petal.Width Species &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;chr&gt; 1 7 3.2 4.7 1.4 versicolor 2 6.4 3.2 4.5 1.5 versicolor my_list &lt;- structure(list(structure(list(Sepal.Length = c(5.1, 4.9), Sepal.Width = c(3.5, 3), Petal.Length = c(1.4, 1.4), Petal.Width = c(0.2, 0.2), Species = c(&quot;new_setoas&quot;, &quot;new_setoas&quot;)), class = c(&quot;tbl_df&quot;, &quot;tbl&quot;, &quot;data.frame&quot;), row.names = c(NA, -2L)), structure(list(Sepal.Length = c(6.3, 5.8), Sepal.Width = c(3.3, 2.7), Petal.Length = c(6, 5.1), Petal.Width = c(2.5, 1.9), Species = c(&quot;new_virginica&quot;, &quot;new_virginica&quot;)), class = c(&quot;tbl_df&quot;, &quot;tbl&quot;, &quot;data.frame&quot;), row.names = c(NA, -2L)), structure(list(Sepal.Length = c(7, 6.4), Sepal.Width = c(3.2, 3.2), Petal.Length = c(4.7, 4.5), Petal.Width = c(1.4, 1.5), Species = c(&quot;versicolor&quot;, &quot;versicolor&quot;)), class = c(&quot;tbl_df&quot;, &quot;tbl&quot;, &quot;data.frame&quot;), row.names = c(NA, -2L))), ptype = structure(list( Sepal.Length = numeric(0), Sepal.Width = numeric(0), Petal.Length = numeric(0), Petal.Width = numeric(0), Species = character(0)), class = c(&quot;tbl_df&quot;, &quot;tbl&quot;, &quot;data.frame&quot;), row.names = integer(0)), class = c(&quot;vctrs_list_of&quot;, &quot;vctrs_vctr&quot;, &quot;list&quot;)) </code></pre> <p>Desired output:</p> <pre><code>[[new_setoas]] # A tibble: 2 x 5 Sepal.Length Sepal.Width Petal.Length Petal.Width &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; 1 5.1 3.5 1.4 0.2 2 4.9 3 1.4 0.2 [[new_virginica]] # A tibble: 2 x 5 Sepal.Length Sepal.Width Petal.Length Petal.Width &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; 1 6.3 3.3 6 2.5 2 5.8 2.7 5.1 1.9 [[versicolor]] # A tibble: 2 x 5 Sepal.Length Sepal.Width Petal.Length Petal.Width &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; 1 7 3.2 4.7 1.4 2 6.4 3.2 4.5 1.5 </code></pre>
[ { "answer_id": 74321708, "author": "Axekan", "author_id": 12519793, "author_profile": "https://Stackoverflow.com/users/12519793", "pm_score": 3, "selected": true, "text": "[]" }, { "answer_id": 74321782, "author": "Mina", "author_id": 11887902, "author_profile": "https://Stackoverflow.com/users/11887902", "pm_score": 1, "selected": false, "text": "array" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13321647/" ]
74,321,741
<p>I was able to run a docker container but if I do <code>sudo docker-compose up -d</code> but how to reopen/watch the screen again if I need and close again. I am using ubuntu. Thanks</p>
[ { "answer_id": 74321708, "author": "Axekan", "author_id": 12519793, "author_profile": "https://Stackoverflow.com/users/12519793", "pm_score": 3, "selected": true, "text": "[]" }, { "answer_id": 74321782, "author": "Mina", "author_id": 11887902, "author_profile": "https://Stackoverflow.com/users/11887902", "pm_score": 1, "selected": false, "text": "array" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15801078/" ]
74,321,764
<p>The code is required to take addresses from a csv file and then use a function to compute the corresponding Latitudes and Longitudes. While I get the correct Latitudes and Longitudes but I am unable to save them to a new csv file.</p> <p>import requests import urllib.parse import pandas as pd</p> <p>#function to get the Coordinates:</p> <pre><code>def lat_long(add): url = 'https://nominatim.openstreetmap.org/search/'+urllib.parse.quote(add)+'?format=json' response = requests.get(url).json() print(response[0][&quot;lat&quot;], response[0][&quot;lon&quot;]) return </code></pre> <p>#function is called to get the 5 Address Values from the CSV File and pass on to the function</p> <pre><code>df = pd.read_csv('C:\\Users\\Umer Abbas\\Desktop\\lat_long.csv') i = 0 print(&quot;Latitude&quot;,&quot;&quot;,&quot;Longitude&quot;) for i in range (0,5): add = df._get_value(i, 'Address') lat_long(add) </code></pre> <p>Output is:</p> <pre><code>Latitude Longitude 34.0096961 71.8990106 34.0123846 71.5787458 33.6038766 73.048136 33.6938118 73.0651511 24.8546842 67.0207055 </code></pre> <p>I want to save this output into a new file and I am unable to get the results.</p>
[ { "answer_id": 74321708, "author": "Axekan", "author_id": 12519793, "author_profile": "https://Stackoverflow.com/users/12519793", "pm_score": 3, "selected": true, "text": "[]" }, { "answer_id": 74321782, "author": "Mina", "author_id": 11887902, "author_profile": "https://Stackoverflow.com/users/11887902", "pm_score": 1, "selected": false, "text": "array" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19911267/" ]
74,321,768
<p>I am working on my first dynamic website using HTML, Express &amp; node.js. Reading through the Stripe documentation and other sources I've come across various examples but my main goal is to use my Stripe API key and each item price ID's in my server and not in my front end code so no one can temper with them. I've successfully use my Stripe API key on my backend and used the .post method to redirect the user after pressing the Buy Now button to the checkout page as shown below:</p> <p>Node.js</p> <pre><code>const stripe = require('stripe')('sk_test_key'); const express = require('express'); const app = express(); app.use(express.static('public')); const YOUR_DOMAIN = 'http://localhost:4242'; app.post('/create-checkout-session', async (req, res) =&gt; { const session = await stripe.checkout.sessions.create({ line_items: [ { price: 'price_priceKey', quantity: 1, }, ], mode: 'payment', success_url: `${YOUR_DOMAIN}/success.html`, cancel_url: `${YOUR_DOMAIN}/cancel.html`, }); res.redirect(303, session.url); }); app.listen(4242, () =&gt; console.log('Running on port 4242')); </code></pre> <p>HTML</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;link href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot; integrity=&quot;sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT&quot; crossorigin=&quot;anonymous&quot; /&gt; &lt;title&gt;Product Page&lt;/title&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;style.css&quot; /&gt; &lt;script src=&quot;https://js.stripe.com/v3/&quot;&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col-lg-6&quot;&gt; &lt;section&gt; &lt;div class=&quot;product&quot;&gt; &lt;img class=&quot;collar-img&quot; src=&quot;image&quot; alt=&quot;product-image&quot; /&gt; &lt;div class=&quot;description&quot;&gt; &lt;h3&gt;Leather Collar&lt;/h3&gt; &lt;h5&gt;$9.99&lt;/h5&gt; &lt;/div&gt; &lt;/div&gt; &lt;form action=&quot;/create-checkout-session&quot; method=&quot;POST&quot;&gt; &lt;button type=&quot;submit&quot; id=&quot;checkout-button&quot;&gt;Checkout&lt;/button&gt; &lt;/form&gt; &lt;/section&gt; &lt;/div&gt; &lt;div class=&quot;col-lg-6&quot;&gt; &lt;section&gt; &lt;div class=&quot;product&quot;&gt; &lt;img class=&quot;collar-img&quot; src=&quot;image2&quot; alt=&quot;product-image2&quot; /&gt; &lt;div class=&quot;description&quot;&gt; &lt;h3&gt;Comsos Collar&lt;/h3&gt; &lt;h5&gt;$19.99&lt;/h5&gt; &lt;/div&gt; &lt;/div&gt; &lt;form action=&quot;/create-checkout-session&quot; method=&quot;POST&quot;&gt; &lt;button type=&quot;submit&quot; id=&quot;checkout-button&quot;&gt;Buy Now&lt;/button&gt; &lt;/form&gt; &lt;/section&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>My problem is I've only figure how to hardcode the price ID for a product inside my line_items object in node.js so when the user clicks the Buy Now button it will only add to the checkout page the items that I added. I've come across examples of adding the price ID to the attribute &quot;data-price-id&quot; inside each button element so that each item has a button that contains its correct price but that exposes all my price ID's to my frontend code. I already tried hiding the ID in my frontend using EJS and the dotenv module in node.js but this was futile. I would really appreciate if someone could point me the right direction or sample code on how to pass these different price ID's after user clicks on each button of each item back to my server.</p>
[ { "answer_id": 74322185, "author": "Corey Clavette", "author_id": 18637382, "author_profile": "https://Stackoverflow.com/users/18637382", "pm_score": 1, "selected": false, "text": "document.querySelector()" }, { "answer_id": 74322353, "author": "Nicolás Rodrigues", "author_id": 8083168, "author_profile": "https://Stackoverflow.com/users/8083168", "pm_score": 0, "selected": false, "text": "const PRODUCT_IDS = {\n toaster-x1000: {\n price_id: 'toaster-price-id'\n }\n};\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16226804/" ]
74,321,781
<p>I'm trying to make a program that randomly moves the mouse only when the right mouse button is held to prank a friend.</p> <p>I found some code online to detect right-clicks with Win32 API. When I added my own <code>while</code> loop, it didn't stop after it started. I tried adding an <code>if</code> statement with <code>break</code> but nothing changed.</p> <pre><code>import win32api import pyautogui import random state = win32api.GetKeyState(0x02) # Right button down = 1. Button up = -128 while True: pressed = win32api.GetKeyState(0x02) if pressed != state: # Button state changed state = pressed print(pressed) if pressed &lt; 0: print('Right Button Pressed') while pressed &lt; 0: # If the right mouse button is pressed, move the mouse randomly. pyautogui.moveRel(random.randint(-10, 10), random.randint(-10, 10)) if (pressed &gt; 0): break else: print('Right Button Released') </code></pre>
[ { "answer_id": 74322185, "author": "Corey Clavette", "author_id": 18637382, "author_profile": "https://Stackoverflow.com/users/18637382", "pm_score": 1, "selected": false, "text": "document.querySelector()" }, { "answer_id": 74322353, "author": "Nicolás Rodrigues", "author_id": 8083168, "author_profile": "https://Stackoverflow.com/users/8083168", "pm_score": 0, "selected": false, "text": "const PRODUCT_IDS = {\n toaster-x1000: {\n price_id: 'toaster-price-id'\n }\n};\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20420416/" ]
74,321,795
<p><strong>Input :</strong> ['A', 'B', 'C', 'A', 'D', 'B', 'B', 'A', 'D']</p> <p><strong>Expected output :</strong> 'B'</p> <p>The output should be the element with higher occurrence. If there are two or more elements which shares the same number of occurrence, then the element which reaches the maximum count earlier in the array should be the expected output. In the above case, 'B' and 'A' has count of 3. Since 'B' reaches the max count earlier than 'A', 'B' should be the output.</p> <p>I have already found the solution for this.</p> <p><strong>My Solution</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let input = ['A', 'B', 'C', 'A', 'D', 'B', 'B', 'A', 'D'] const findWinner = (arr) =&gt; { const reduced = arr.reduce((acc, value) =&gt; ({ ...acc, [value]: (acc[value] || 0) + 1 }), {}) let pickLargest = Object.entries(reduced) const winner = pickLargest.reduce((acc, [key, value]) =&gt; { if (value &gt; acc.maxValue) { acc.maxValue = value acc.winner = key } else if (value == acc.maxValue) { if (arr.lastIndexOf(key) &gt; arr.lastIndexOf(acc.winner)) { acc.winner = acc.winner } else { acc.winner = key } } return acc }, { maxValue: 0, winner: '' }) return winner.winner } console.log(findWinner(input));</code></pre> </div> </div> </p> <p>Is there any other elegant way to achieve the same result?</p>
[ { "answer_id": 74321863, "author": "Dr. Vortex", "author_id": 17637456, "author_profile": "https://Stackoverflow.com/users/17637456", "pm_score": 1, "selected": false, "text": "const findWinner = ary => {\n const occurrences = Object.fromEntries(ary.map(e => [e, 0]));\n for(let el of ary){\n occurrences[el]++\n }\n let sorted = Object.entries(occurrences).sort((a, b) => a[1] > b[1]);\n\n return sorted[0][0];\n}\n" }, { "answer_id": 74321955, "author": "Nina Scholz", "author_id": 1447675, "author_profile": "https://Stackoverflow.com/users/1447675", "pm_score": 3, "selected": true, "text": "const\n findWinner = array => {\n const counts = {};\n let max;\n \n for (const value of array) {\n counts[value] = (counts[value] || 0) + 1;\n if (counts[value] <= counts[max]) continue;\n max = value;\n }\n\n return max;\n };\n\nconsole.log(findWinner(['A', 'B', 'C', 'A', 'D', 'B', 'B', 'A', 'D']));" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12139325/" ]
74,321,808
<p>What does the <code>22 :: Int</code> mean here?</p> <pre><code>rotor3=(&quot;BDFHJLCPRTXVZNYEIWGAKMUSQO&quot;,22::Int) </code></pre>
[ { "answer_id": 74321937, "author": "chi", "author_id": 3234959, "author_profile": "https://Stackoverflow.com/users/3234959", "pm_score": 2, "selected": false, "text": "22" }, { "answer_id": 74321940, "author": "leftaroundabout", "author_id": 745903, "author_profile": "https://Stackoverflow.com/users/745903", "pm_score": 3, "selected": false, "text": "22 :: Int" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
74,321,813
<p>(Just for fun) I figured out a way to represent this:</p> <pre><code>250 : 8 = 31 + 2 31 : 8 = 3 + 7 ∴ (372)8 </code></pre> <p>in the following procedure:</p> <pre><code>(defun dec-&gt;opns (n base) (do* ((lst nil (append lst (list pos))) ; this is also not so nice (m n (truncate m base)) (pos (rem m base) (rem m base)) ) ; &lt;&lt;&lt;&lt;&lt;&lt; ((&lt; m base) (reverse (append lst (list m)))) )) </code></pre> <p>The procedure does what it is supposed to do until now.</p> <pre><code> CL-USER&gt; (dec-&gt;opns 2500000 8) (1 1 4 2 2 6 4 0) </code></pre> <p>At this point, I simply ask myself, how to avoid the two times</p> <p><code>(rem m base)</code>.</p> <p>First of all because of duplicates are looking daft. But also they may be a hint that the solution isn't the elegant way. Which also is not a problem. I am studying for becoming a primary school teacher (from 1st to 6nd class) and am considering examples for exploring math in a sense of Paperts Mindstorms. Therefore exploring all stages of creating and refining a solution are welcome.</p> <p>But to get a glimpse of the professional solution, would you be so kind to suggest a more elegant way to implement the algorithm in an idiomatic way?</p> <p>(Just to anticipate opposition to my &quot;plan&quot;: I have no intentions to overwhelm the youngsters with Common Lisp. For now, I am using Common Lisp for reflecting about my study content and using the student content for practicing Common Lisp. My intention in the medium term is to write a &quot;common (lisp) Logo setup&quot; and a Logo environment with which the examples in Harveys Computer Science Logo style (vol. 1), Paperts Mindstorms, Solomons et. al LogoWorks, and of course in Abelsons et. al Turtle Geometry can be implemented uncompromisingly. If I will not cave in, the library will be found with quickload in the still more distant future under the name &quot;c-logo-s&quot; and be called <em>cλogos</em> ;-) )</p>
[ { "answer_id": 74322182, "author": "Gwang-Jin Kim", "author_id": 9690090, "author_profile": "https://Stackoverflow.com/users/9690090", "pm_score": 3, "selected": true, "text": "cons" }, { "answer_id": 74322909, "author": "coredump", "author_id": 124319, "author_profile": "https://Stackoverflow.com/users/124319", "pm_score": 2, "selected": false, "text": "(defun digits-in-base (number base)\n (check-type number (integer 0))\n (check-type base (integer 2))\n (loop\n :with remainder\n :do (multiple-value-setq (number remainder) (truncate number base))\n :collect remainder\n :until (= number 0)))\n" }, { "answer_id": 74346860, "author": "ignis volens", "author_id": 17026934, "author_profile": "https://Stackoverflow.com/users/17026934", "pm_score": 0, "selected": false, "text": "looping" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17814577/" ]
74,321,858
<pre><code>students = {'palii':('male','170'), 'Minckach':('male','176'), 'ddl':('male','180'), 'Red1ska':('male','188'), 'Sargeras':('male','185'), 'Gerus':('female','160'), 'Liah':('male','183'), 'Chhekan':('female','182'), 'Leshega':('male','186'), 'yurii':('male','187')} </code></pre> <p>I have this dictionary. How can i delete all the females from it and calculate males average height? Maybe there is a function or something that idk?</p> <p>I tried using <code>filter()</code> like</p> <pre><code>newDict = dict(filter(lambda elem: elem[1] == 'male',students.items())) </code></pre> <p>But this is not working.</p> <pre><code>def halfmale(stats): sum = 0 for key in stats.values(): sum += float(key) half = sum / len(stats) print(half) for value, key in stats.items(): if (key+5&gt;half and key-5&lt;half): print(value) </code></pre> <p>Python says that promlem is division by zero in this part</p>
[ { "answer_id": 74321897, "author": "I'mahdi", "author_id": 1740577, "author_profile": "https://Stackoverflow.com/users/1740577", "pm_score": 2, "selected": true, "text": "dict" }, { "answer_id": 74321959, "author": "John Gordon", "author_id": 494134, "author_profile": "https://Stackoverflow.com/users/494134", "pm_score": 0, "selected": false, "text": "newDict = {k:v for k,v in students.items() if v[0] == 'male'}\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20420514/" ]
74,321,873
<p>I have a popup in my app:</p> <pre><code>&lt;div id=&quot;modal&quot;&gt;&lt;/div&gt; let modal = document.getElementById('modal') modal.innerHTML = ` &lt;button class=&quot;close-button&quot; onclick=&quot;close_modal()&quot;&gt;Close&lt;/button&gt; ` #modal{ width: 30em; height: 24em; overflow: hidden; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); visibility: hidden; } </code></pre> <p>When I click certain button function is triggered which has modal.classList.add('open-modal') in it.</p> <pre><code>.open-modal{ visibility: visible !important; } </code></pre> <p><code>close_modal</code> function is:</p> <pre><code>function close_modal(){ modal.classList.add('close-modal') } </code></pre> <p>CSS:</p> <pre><code>.close-modal{ visibility: hidden !important; } </code></pre> <p>It works just fine once(i can open and close popup but when I try to open it second time it doesn't. Why is this happening and how to fix it?</p>
[ { "answer_id": 74321900, "author": "Dr. Vortex", "author_id": 17637456, "author_profile": "https://Stackoverflow.com/users/17637456", "pm_score": 0, "selected": false, "text": "<dialog>" }, { "answer_id": 74322003, "author": "Mehmet Eren Çelik", "author_id": 20420517, "author_profile": "https://Stackoverflow.com/users/20420517", "pm_score": 3, "selected": true, "text": "function changeVisibility(modal) {\n if(modal.classList.contains('open-modal')) {\n modal.classList.remove('open-modal');\n modal.classlist.add('close-modal');\n } else {\n modal.classList.remove('close-modal');\n modal.classList.add('open-modal')\n } \n} \n " } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19433346/" ]
74,321,893
<p>I use to have my website hosted on 1and1 server for years and it was working fine (php 7.4).</p> <p>Since, i decided to switch to a dedicated server w/Linux ubuntu OS for my webserver (php 8.1.2).</p> <p>All is working fine after the migration but I have a weird issue: when I get a redirection from an Ajax/php query I usualy redict (using JS) the client to a desired web page and the session is lost.</p> <p>I do have the session_start(); and ensure that it do not switch from <a href="http://www.mywebsite.com" rel="nofollow noreferrer">www.mywebsite.com</a> to mywebsite.com.</p> <p>I am confused as it is 100% the code that is working on the hosted server.</p> <p>other clue, I see that the approval of cookies always prompt. so there is clearly a session issue that un_sync the client/server session_id.</p> <p>Any config to ensure on a new apache server ? I can see in my &quot;/var/lib/php/sessions&quot; folder a new session every time i trigger the redirection ...</p> <p>I would appreciate any advise.</p> <p>here is my SESSION config from php.ini:</p> <pre><code>Session Support enabled Registered save handlers files user Registered serializer handlers php_serialize php php_binary Directive Local Value Master Value session.auto_start Off Off session.cache_expire 180 180 session.cache_limiter nocache nocache session.cookie_domain no value no value session.cookie_httponly no value no value session.cookie_lifetime 0 0 session.cookie_path / / session.cookie_samesite no value no value session.cookie_secure 0 0 session.gc_divisor 1000 1000 session.gc_maxlifetime 1440 1440 session.gc_probability 0 0 session.lazy_write On On session.name PHPSESSID PHPSESSID session.referer_check no value no value session.save_handler files files session.save_path /var/lib/php/sessions /var/lib/php/sessions session.serialize_handler php php session.sid_bits_per_character 5 5 session.sid_length 26 26 session.upload_progress.cleanup On On session.upload_progress.enabled On On session.upload_progress.freq 1% 1% session.upload_progress.min_freq 1 1 session.upload_progress.name PHP_SESSION_UPLOAD_PROGRESS PHP_SESSION_UPLOAD_PROGRESS session.upload_progress.prefix upload_progress_ upload_progress_ session.use_cookies 1 1 session.use_only_cookies 1 1 session.use_strict_mode 0 0 session.use_trans_sid 0 0 </code></pre>
[ { "answer_id": 74322001, "author": "Valeriu Ciuca", "author_id": 4527645, "author_profile": "https://Stackoverflow.com/users/4527645", "pm_score": 0, "selected": false, "text": "session_start();" }, { "answer_id": 74323062, "author": "dvicemuse", "author_id": 1155184, "author_profile": "https://Stackoverflow.com/users/1155184", "pm_score": 0, "selected": false, "text": "<?php\n\n //DEFINE THE CUSTOM SESSION STORAGE PATH\n $session_save_path = '/path/to/custom/session/storage';\n\n //MAKE THE FOLDER IF NEEDED\n if(!file_exists($session_save_path)) mkdir($session_save_path, 0755, true);\n\n //SET THE SESSION TO USE THE CUSTOM PATH\n session_save_path(realpath($session_save_path));\n\n //START THE SESSION IF POSSIBLE\n if(!session_id()) session_start();\n\n ...\n\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4157691/" ]
74,321,914
<p>I am perhaps misunderstanding Pundit policies but I am facing an issue where the <code>UserPolicy</code> is clashing with the <code>SongPolicy</code>.</p> <p>What happens if that a statement in <code>UserPolicy</code> is being asserted ignoring what's written in <code>SongPolicy</code>:</p> <pre><code>Pundit::NotAuthorizedError in SongsController#edit not allowed to edit? this User def authorization authorize Current.user end </code></pre> <p>The issue emerged after introducing a new role for users but I believe that I probably haven't configured it right and for some reason only <code>UserPolicy</code> is looked at for asserting authorization in the <code>SongsController</code>?</p> <p>I have two controllers that check for the user to be signed in (<code>require_user_logged_in</code>) and another to check on Pundit's policies (<code>authorization</code>):</p> <pre class="lang-rb prettyprint-override"><code>class UsersController &lt; ApplicationController before_action :require_user_logged_in!, :authorization, :turbo_frame_check # Actions were removed for brevity. end </code></pre> <pre class="lang-rb prettyprint-override"><code>class SongsController &lt; ApplicationController before_action :require_user_logged_in!, :authorization, except: [:index, :show] # Actions were removed for brevity. end </code></pre> <p>The <code>authorization</code> methods looks like this:</p> <pre class="lang-rb prettyprint-override"><code> def authorization authorize Current.user end </code></pre> <p>There's an application-level policy class, <code>ApplicationPolicy</code>:</p> <pre class="lang-rb prettyprint-override"><code># frozen_string_literal: true class ApplicationPolicy attr_reader :user, :params, :record # Allows params to be part of policies. def initialize(context, record) if context.is_a?(Hash) @user = context[:user] @params = context[:params] else @user = context @params = {} end @record = record end def index? false end def show? false end def create? false end def new? create? end def update? false end def edit? update? end def destroy? false end class Scope def initialize(user, scope) @user = user @scope = scope end def resolve raise NotImplementedError, &quot;You must define #resolve in #{self.class}&quot; end private attr_reader :user, :scope end end </code></pre> <p>The <code>UserPolicy</code> to protect user views:</p> <pre class="lang-rb prettyprint-override"><code>class UserPolicy &lt; ApplicationPolicy class Scope &lt; Scope end def index? user.has_role?(:admin) end def show? # Access if admin or the same user only. user.has_role?(:admin) || is_same_user? end def create? index? end def new? create? end def update? index? || is_same_user? end def edit? update? # This is called when accessing a view for `SongsController`. end def destroy? index? || is_same_user? end def delete? destroy? end private # Used to keep a user from editing another. # Admins should be allowed to edit all users. def is_same_user? # Check if user being accessed is the one being logged in. params[:id].to_s == Current.user.username.to_s end end </code></pre> <p>And the <code>SongPolicy</code>:</p> <pre class="lang-rb prettyprint-override"><code>class SongPolicy &lt; ApplicationPolicy class Scope &lt; Scope end def index? end def show? end def create? user.has_role?(:admin) || user.has_role?(:collaborator) # This is ignored. end def new? create? end def update? create? end def edit? create? end def destroy? user.has_role?(:admin) end def delete? destroy? end end </code></pre> <p>Not sure what else to try here, I'm sure I'm missing something, if someone with more knowledge of Pundit could let me know their thoughts on why a statement for one policy can leak into another, it would be really helpful.</p>
[ { "answer_id": 74322001, "author": "Valeriu Ciuca", "author_id": 4527645, "author_profile": "https://Stackoverflow.com/users/4527645", "pm_score": 0, "selected": false, "text": "session_start();" }, { "answer_id": 74323062, "author": "dvicemuse", "author_id": 1155184, "author_profile": "https://Stackoverflow.com/users/1155184", "pm_score": 0, "selected": false, "text": "<?php\n\n //DEFINE THE CUSTOM SESSION STORAGE PATH\n $session_save_path = '/path/to/custom/session/storage';\n\n //MAKE THE FOLDER IF NEEDED\n if(!file_exists($session_save_path)) mkdir($session_save_path, 0755, true);\n\n //SET THE SESSION TO USE THE CUSTOM PATH\n session_save_path(realpath($session_save_path));\n\n //START THE SESSION IF POSSIBLE\n if(!session_id()) session_start();\n\n ...\n\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4032810/" ]
74,321,926
<p>Can anyone please let me know how to correctly click on the button using Selenium webdriver?</p> <p>I have the following html element I want to click:</p> <pre><code>&lt;button type=&quot;button&quot; class=&quot;btn button_primary&quot; data-bind=&quot;click: $parent.handleSsoLogin.bind($parent)&quot;&gt; Sign In &lt;/button&gt; </code></pre> <p>I am trying to use WebDriver with python but it doesn't find the element. Please advise how to address it?</p> <pre><code>from xml.dom.expatbuilder import InternalSubsetExtractor from selenium.webdriver.common.by import By import time # imports parts of interest from selenium import webdriver # controlling the chrome browser driver = webdriver.Chrome() link=xxxxx driver.get(link2) # login = driver.find_element(By.LINK_TEXT,&quot;Login&quot;) time.sleep(10) # login.click() driver.find_element(By.ID,'CybotCookiebotDialogBodyLevelButtonLevelOptinAllowAll') time.sleep(10) login=driver.find_element(By.CSS_SELECTOR(&quot;&lt;button type=&quot;buttonclass=&quot;btn button_primary&quot; data-bind=&quot;click: $parent.handleSsoLogin.bind($parent)&quot;&gt; Sign In </code></pre> <p>So far tried different elements but it doesn't find it</p>
[ { "answer_id": 74322001, "author": "Valeriu Ciuca", "author_id": 4527645, "author_profile": "https://Stackoverflow.com/users/4527645", "pm_score": 0, "selected": false, "text": "session_start();" }, { "answer_id": 74323062, "author": "dvicemuse", "author_id": 1155184, "author_profile": "https://Stackoverflow.com/users/1155184", "pm_score": 0, "selected": false, "text": "<?php\n\n //DEFINE THE CUSTOM SESSION STORAGE PATH\n $session_save_path = '/path/to/custom/session/storage';\n\n //MAKE THE FOLDER IF NEEDED\n if(!file_exists($session_save_path)) mkdir($session_save_path, 0755, true);\n\n //SET THE SESSION TO USE THE CUSTOM PATH\n session_save_path(realpath($session_save_path));\n\n //START THE SESSION IF POSSIBLE\n if(!session_id()) session_start();\n\n ...\n\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18211958/" ]
74,321,930
<p>So, I am trying to create a DNA to RNA sequence converter, but it isn't really displaying when I try to get the values and change them sequentially. I.E., when you type certain letters like ATG they will convert into UAC but in that specific order. Is there a way to? I've already tried an array but it isn't working.</p> <p>JS:</p> <pre><code> var dna = document.getElementById(&quot;input1&quot;).value; var rna = []; var aminoacid; function replace(){ if (dna.indexOf('a') &gt; -1) { rna.push(&quot;u&quot;); } else if(dna.indexOf('t') &gt; -1){ rna.push(&quot;a&quot;); } else if(dna.indexOf('c') &gt; -1){ rna.push(&quot;g&quot;); } else if(dna.indexOf('g') &gt; -1){ rna.push(&quot;c&quot;); } } document.getElementById(&quot;total&quot;).innerHTML = rna; </code></pre> <p>HTML:</p> <pre><code> &lt;input style=&quot;top: -350px;&quot; placeholder=&quot;Type DNA's value...&quot; onclick=&quot;onClick();&quot; id=&quot;input1&quot;&gt; &lt;button type=&quot;button&quot; onclick=&quot;getInputValue();&quot; id = &quot;button1&quot; style = &quot;position: relative; z-index: 100; top: -300px; left: -200px;&quot;&gt;Get RNA&lt;/button&gt; </code></pre>
[ { "answer_id": 74321981, "author": "Dr. Vortex", "author_id": 17637456, "author_profile": "https://Stackoverflow.com/users/17637456", "pm_score": 1, "selected": true, "text": "const input = document.querySelector('#input1').value,\n total = document.querySelector('#total');\n\nlet rna = input.replaceAll(/[atcg]/g, e =>\n e == 'a' ? 'u' :\n e == 't' ? 'a' :\n e == 'c' ? 'g' :\n e == 'g' ? 'c' :\n ' '\n);\n\ntotal.textContent = rna;\n" }, { "answer_id": 74321994, "author": "Austin Poulson", "author_id": 12817213, "author_profile": "https://Stackoverflow.com/users/12817213", "pm_score": -1, "selected": false, "text": "String.prototype.replace()" }, { "answer_id": 74322055, "author": "Scott Marcus", "author_id": 695364, "author_profile": "https://Stackoverflow.com/users/695364", "pm_score": -1, "selected": false, "text": "else if" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20273807/" ]
74,321,945
<p>I'm stuck with a classic <strong>greatest-n-per-group</strong> problem, where a cat can have many kittens, but I'm usually just interested in the youngest.</p> <p>I <em>already do know</em> how to build a <code>scope</code> and a <code>has_one</code> relation for the <code>Cat</code>.</p> <p>My question: Is there a way to...</p> <ol> <li>list all cats' names together with their youngest kittens' names...</li> <li>while at the same time ordering them by their respective youngest kitten's name...</li> </ol> <p>...using just a <em>single SELECT</em> under the hood?</p> <p>What I got so far:</p> <pre class="lang-rb prettyprint-override"><code>class Cat &lt; ApplicationRecord has_many :kittens has_one :youngest_kitten, -&gt; { merge(Kitten.youngest) }, foreign_key: :cat_id, class_name: :Kitten scope :with_youngest_kittens, lambda { joins(:kittens) .joins(Kitten.younger_kittens_sql(&quot;cats.id&quot;)) .where(younger_kittens: { id: nil }) } end class Kitten belongs_to :cat scope :youngest, lambda { joins(Kitten.younger_kittens_sql(&quot;kittens.cat_id&quot;)) .where(younger_kittens: { id: nil }) } def self.younger_kittens_sql(cat_field_name) %{ LEFT OUTER JOIN kittens AS younger_kittens ON younger_kittens.cat_id = #{cat_field_name} AND younger_kittens.created_at &gt; kittens.created_at } end end </code></pre> <p>When I run <code>Cat.with_latest_kittens.order('kittens.name').map(&amp;:name)</code> everything looks fine: I get all the cats' names with just a single SELECT.</p> <p>But when I run <code>Cat.with_latest_kittens.order('kittens.name').map {|cat| cat.youngest_kitten.name}</code>, I get the right result too, but a superfluous additional SELECT per cat is executed. Which is just logical, because the <code>with_youngest_kittens</code> doesn't know it should populate <code>youngest_kitten</code>. Is there a way to tell it or am I going about this all wrong?</p>
[ { "answer_id": 74326517, "author": "localarrow", "author_id": 20318864, "author_profile": "https://Stackoverflow.com/users/20318864", "pm_score": 2, "selected": true, "text": ":with_youngest_kittens" }, { "answer_id": 74329908, "author": "lentschi", "author_id": 757254, "author_profile": "https://Stackoverflow.com/users/757254", "pm_score": 0, "selected": false, "text": "Cat.with_youngest_kitten" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/757254/" ]
74,321,948
<p>I'm trying to publish a sheet using Google Apps script and get its (published) URL.</p> <p>The only solution I've found is <a href="https://stackoverflow.com/questions/49755421/create-a-google-sheet-then-publishing-it-via-google-apps-script">this thread</a>, however the proposed script publishes entire spreadsheet, not as suggested in the question, particular sheet. I'm not sure what syntax to use as fileId in</p> <pre><code>Drive.Revisions.update(resource, fileId, revisionId); </code></pre> <p>in order to publish only active sheet, not entire spreadsheet.</p>
[ { "answer_id": 74326517, "author": "localarrow", "author_id": 20318864, "author_profile": "https://Stackoverflow.com/users/20318864", "pm_score": 2, "selected": true, "text": ":with_youngest_kittens" }, { "answer_id": 74329908, "author": "lentschi", "author_id": 757254, "author_profile": "https://Stackoverflow.com/users/757254", "pm_score": 0, "selected": false, "text": "Cat.with_youngest_kitten" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20420512/" ]
74,321,957
<p>Hello I am trying to use selenium to automatically scrape the products titles and prices, i am using ActionChains and move_to_element, but somehow it gave me timeout exception, Is there a better way to do it? <a href="https://i.stack.imgur.com/TeVtt.png" rel="nofollow noreferrer">titles in the tab</a></p> <p><a href="https://denago.com/collections/ebikes" rel="nofollow noreferrer">https://denago.com/collections/ebikes</a></p> <pre><code>#For Dynamic webpage, import selenium !apt-get update !apt install chromium-chromedriver !cp /usr/lib/chromium-browser/chromedriver /usr/bin !pip install selenium from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC #set up Chrome driver options=webdriver.ChromeOptions() options.add_argument('--headless') options.add_argument('--no-sandbox') options.add_argument('--disable-dev-shm-usage') #Define web driver as a Chrome driver driver=webdriver.Chrome('chromedriver',options=options) driver.implicitly_wait(10) driver.get('https://denago.com/collections/ebikes') action = ActionChains(driver) ourbike = WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.XPATH, &quot;/html/body/div[6]/div/header/nav/ul/li[1]/a/span&quot;))) ActionChains(driver).move_to_element(ourbike).perform() Titles=driver.find_elements(By.CLASS_NAME,'mm-title') for i in range(len(Titles)): print(Titles[i].text) </code></pre>
[ { "answer_id": 74322694, "author": "Eugeny Okulik", "author_id": 12023661, "author_profile": "https://Stackoverflow.com/users/12023661", "pm_score": 2, "selected": true, "text": "options.add_argument('window-size=1200,1980')" }, { "answer_id": 74322766, "author": "Jaky Ruby", "author_id": 10050775, "author_profile": "https://Stackoverflow.com/users/10050775", "pm_score": 0, "selected": false, "text": "# Needed libs\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n# We create the driver\noptions=webdriver.ChromeOptions()\noptions.add_argument('--headless')\ndriver = webdriver.Chrome(options=options)\n\n# We maximize the window, because if not the page will be different\ndriver.maximize_window()\n\n# We navigate to the url\ndriver.get('https://denago.com/collections/ebikes')\n\n# We wait for the first title, I think it is enough\nWebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, \"(//h5)[1]\")))\n\n# We get all the titles elements\ntitles=driver.find_elements(By.XPATH,'//h5')\n\n# For each title element we get the text and also we get the price\nfor i in range(0,len(titles)):\n product_name = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, f'(//h5)[{i+1}]'))).text\n product_price = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, f'(//div[@class=\"price\"])[{i+1}]'))).text\n print(f\"Product {i+1}: {product_name} - Price: {product_price}\")\n\ndriver.quit()\n" }, { "answer_id": 74322791, "author": "Barry the Platipus", "author_id": 19475185, "author_profile": "https://Stackoverflow.com/users/19475185", "pm_score": 0, "selected": false, "text": "from selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\nchrome_options = Options()\nchrome_options.add_argument(\"--no-sandbox\")\nchrome_options.add_argument('disable-notifications')\nchrome_options.add_argument(\"window-size=1280,720\")\n\nwebdriver_service = Service(\"chromedriver/chromedriver\") ## path to where you saved chromedriver binary\ndriver = webdriver.Chrome(service=webdriver_service, options=chrome_options)\nwait = WebDriverWait(driver, 25)\n\n\ndriver.get('https://denago.com/collections/ebikes')\ntry:\n wait.until(EC.element_to_be_clickable((By.ID, \"CybotCookiebotDialogBodyLevelButtonLevelOptinAllowAll\"))).click()\n print('accepted cookies')\nexcept Exception as e:\n print('no cookie button!')\nbikes= wait.until(EC.presence_of_all_elements_located((By.XPATH, '//div[@class=\"grid-view-item product-card\"]//h5/a')))\nfor bike in bikes:\n print(bike.text.strip())\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19854159/" ]
74,321,963
<p>I inserted two background images to a div and gave them the top and bottom positions. However, the issue is that I want the images to have an equal top and bottom margin. I'm not sure how to accomplish it.</p> <p><a href="https://i.stack.imgur.com/yNXkI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yNXkI.png" alt="" /></a></p> <p>I want the background images like in the SS.</p> <p>html:</p> <pre><code>&lt;div class=&quot;license-info&quot;&gt; &lt;/div&gt; </code></pre> <p>css:</p> <pre><code>.license-info { width: 100%; height: 800px; background: #181f2b; background-image: url('/images/footerdiamondchain.png'), url('/images/footerdiamondchain.png'); background-repeat: repeat-x; background-position-y: top, bottom } </code></pre>
[ { "answer_id": 74322979, "author": "Giorgi Shalamberidze", "author_id": 20248276, "author_profile": "https://Stackoverflow.com/users/20248276", "pm_score": 0, "selected": false, "text": "<div class=\"license-info\">\n <img class=\"first-img\" src=\"./first/path\"></img>\n <img class=\"second-img\" src=\"./second-img/path\"></img> \n</div>\n\n.license-info {\n position:relative;\n}\n.license-info .first-img {\n position:absolute;\n top:50px// change this position\n}\n.license-info .second-img {\n position:absolute;\n bottom:50px;\n}\n" }, { "answer_id": 74323036, "author": "ray", "author_id": 636077, "author_profile": "https://Stackoverflow.com/users/636077", "pm_score": 2, "selected": true, "text": "background-position" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11961514/" ]
74,321,999
<p>I want to create a new map every time the button is pressed. I want the names of the maps to be regular. I tried using ${} in the map name but it doesn't seem to work. is there any solution?</p>
[ { "answer_id": 74322035, "author": "ANISH SAJI KUMAR", "author_id": 12309235, "author_profile": "https://Stackoverflow.com/users/12309235", "pm_score": 0, "selected": false, "text": "map_${mapNumber}" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74321999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20004246/" ]
74,322,008
<p>So I am asked to write a program that reads a sentence from the user, reports and removes wrong repetitions if any. By wrong repetitions I mean that a word (or more) is repeated (two occurrences or more) and that these repetition are consecutive.</p> <p>`</p> <pre><code>public class checker { private String sentence; checker(String sentence){this.sentence=sentence;} public String check(){ String[] word = sentence.split(&quot; &quot;); for(int i=0; i&lt;word.length; i++){ for(int j=i+1; j&lt;word.length; j++){ if(word[i].equals(word[j])){ word[j]=&quot;error&quot;;}}} for(int i=0; i&lt;word.length; i++) { if (!&quot;error&quot;.equals(word[i])) { System.out.print(word[i] + &quot; &quot;);}} return &quot;&quot;;} } </code></pre> <p>***This is the output of my code: ***</p> <p>Enter a Sentence: The operator did not not skip his meal The operator did not skip his meal BUILD SUCCESSFUL (total time: 12 seconds)</p> <p>So my code does the job of finding the repeated words and prints the corrected version, but the problem is that I just can't find a way to make it print out like it is supposed to do in the sample run!</p> <p>[Sample runs:</p> <p>-Enter a sentence: The operator did not not skip his meal -The sentence includes wrong repetitions. -The sentence should be: The operator did not skip his meal</p> <p>-Enter a sentence: Happy people live longer -There are no wrong repetitions]</p> <p>**I do know my problem, every time I try to write a piece of code containing any time type of loops and if statements together I just don't know to extract what I want from the loop and conditional statements, I was trying to</p> <p>`</p> <pre><code>for(int i=0; i&lt;word.length; i++){ for(int j=i+1; j&lt;word.length; j++){ if(word[i].equals(word[j])){ System.out.println(&quot;The sentence includes wrong repetitions.\nThe sentence should be: &quot;); word[j]=&quot;error&quot;;} else{ System.out.println(&quot;There are no wrong repetitions&quot;); } } } </code></pre> <p>` but I know it'll print it every time the loop gets executed!</p> <p>I would really appreciate a helpful tip that I can carry with me going forward!</p> <p>Thanks in advance guys!**</p>
[ { "answer_id": 74322035, "author": "ANISH SAJI KUMAR", "author_id": 12309235, "author_profile": "https://Stackoverflow.com/users/12309235", "pm_score": 0, "selected": false, "text": "map_${mapNumber}" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20401110/" ]
74,322,020
<p>I log the daily produced energy of my solar panels. Now I want to create a SQL statement to get the sum of produced energy for each month but separate columns for each year.</p> <p>I came up with the following SQL statement:</p> <pre class="lang-sql prettyprint-override"><code>SELECT LPAD(extract (month from inverterlogs_summary_daily.bucket)::text, 2, '0') as month, sum(inverterlogs_summary_daily.&quot;EnergyProduced&quot;) as a2022 from inverterlogs_summary_daily WHERE inverterlogs_summary_daily.bucket &gt;= '01.01.2022' and inverterlogs_summary_daily.bucket &lt; '01.01.2023' group by month order by 1; </code></pre> <p>This results in only getting the values from 2022:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>month</th> <th>a2022</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>100</td> </tr> <tr> <td>2</td> <td>358</td> </tr> <tr> <td>3</td> <td>495</td> </tr> </tbody> </table> </div> <p>How could I change the SQL statement to get new columns for each year? Is this even possible?</p> <p>Result should look like this (with a new column for each year, wouldn't mind if I had to update the SQL statement every year):</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>month</th> <th>a2022</th> <th>a2023</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>100</td> <td>92</td> </tr> <tr> <td>2</td> <td>358</td> <td>497</td> </tr> <tr> <td>3</td> <td>495</td> <td>508</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74322069, "author": "GMB", "author_id": 10676716, "author_profile": "https://Stackoverflow.com/users/10676716", "pm_score": 3, "selected": true, "text": "select extract(month from bucket) bucket_month,\n sum(\"EnergyProduced\") filter(where extract(year from bucket) = 2022) a_2022,\n sum(\"EnergyProduced\") filter(where extract(year from bucket) = 2021) a_2021\nfrom inverterlogs_summary_daily\nwhere bucket >= date '2021-01-01' and bucket < date '2023-01-01'\ngroup by extract(month from bucket)\norder by bucket_month\n" }, { "answer_id": 74322092, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 1, "selected": false, "text": "SUM" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8587966/" ]
74,322,080
<pre><code> Button(&quot;Login&quot;) { authenticateUser(username: username, password: password) } .foregroundColor(Color.black) .frame(width: 300, height: 50) .background(Color.blue) .cornerRadius(10) NavigationLink(destination: HomeView(), isActive: $showingLoginScreen) { EmptyView() } </code></pre> <p>I am new to coding and have no clue how to fix this. I have to click on the text in order for the button to be activated.</p>
[ { "answer_id": 74322069, "author": "GMB", "author_id": 10676716, "author_profile": "https://Stackoverflow.com/users/10676716", "pm_score": 3, "selected": true, "text": "select extract(month from bucket) bucket_month,\n sum(\"EnergyProduced\") filter(where extract(year from bucket) = 2022) a_2022,\n sum(\"EnergyProduced\") filter(where extract(year from bucket) = 2021) a_2021\nfrom inverterlogs_summary_daily\nwhere bucket >= date '2021-01-01' and bucket < date '2023-01-01'\ngroup by extract(month from bucket)\norder by bucket_month\n" }, { "answer_id": 74322092, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 1, "selected": false, "text": "SUM" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20420683/" ]
74,322,117
<p>I have created a <strong>Blazor Server</strong> Project in <strong>.NET6</strong>. In my project I need to upload files mostly exe files to the azure container. Here is the code:</p> <pre><code>// Get the file from file picker var file = e.Files.FirstOrDefault(); BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString); // Get or create the container in azure BlobContainerClient blobContainer = blobServiceClient.GetBlobContainerClient(&quot;uploadfiles&quot;); var containerResponse = await blobContainer.CreateIfNotExistsAsync(); if (containerResponse != null &amp;&amp; containerResponse.GetRawResponse().Status == 201) { await blobContainer.SetAccessPolicyAsync(Azure.Storage.Blobs.Models.PublicAccessType.Blob); } // Create the blob in container BlobClient blobClient = blobContainer.GetBlobClient(file.Name); //Read file contents using var stream = file.OpenReadStream(); using (var memoryStream = new MemoryStream()) { await stream.CopyToAsync(memoryStream); byte[] fileBytes = memoryStream.ToArray(); BinaryData uploadData = new BinaryData(fileBytes); Response&lt;BlobContentInfo&gt; uploadResponse = await blobClient.UploadAsync(uploadData, true); } </code></pre> <p>Now the problem is, I can upload small sized file to the container. But when comes to large file, for example 5 MB, I can't upload the file to the container. It says the below error:</p> <blockquote> <p>Supplied file with size 5275768 bytes exceeds the maximum of 512000 bytes.</p> </blockquote> <p>Now one solution could be making smaller chunks. But in that case I am not sure the file will be corrupted or not.</p> <p>Can anyone help me by providing any solution.</p>
[ { "answer_id": 74330616, "author": "mnu-nasir", "author_id": 2975931, "author_profile": "https://Stackoverflow.com/users/2975931", "pm_score": 2, "selected": false, "text": "var container = new BlobContainerClient(connectionString, \"uploadfiles\");\nvar createResponse = await container.CreateIfNotExistsAsync();\n\nif (createResponse != null && createResponse.GetRawResponse().Status == 201)\n{\n await container.SetAccessPolicyAsync(PublicAccessType.Blob);\n}\n\nBlockBlobClient blobClient = container.GetBlockBlobClient(file.Name);\nvar deleteResponse = await blobClient.DeleteIfExistsAsync(DeleteSnapshotsOption.IncludeSnapshots);\n\nbyte[] fileBytes;\n\n// Read file to memory stream\nusing var stream = file.OpenReadStream(long.MaxValue);\nusing (var memoryStream = new MemoryStream())\n{\n await stream.CopyToAsync(memoryStream);\n fileBytes = memoryStream.ToArray();\n}\n\n// Prepare chunks of the file\nconst int pageSizeInBytes = 1000000;\nlong prevLastByte = 0;\nlong bytesRemain = file.Size;\nint blockNumber = 0;\n\nHashSet<string> blocklist = new HashSet<string>();\n\ndo\n{\n blockNumber++;\n\n long bytesToCopy = Math.Min(bytesRemain, pageSizeInBytes);\n byte[] bytesToSend = new byte[bytesToCopy];\n\n Array.Copy(fileBytes, prevLastByte, bytesToSend, 0, bytesToCopy);\n prevLastByte += bytesToCopy;\n bytesRemain -= bytesToCopy;\n\n string blockId = $\"{blockNumber:0000000}\";\n string base64BlockId = Convert.ToBase64String(Encoding.UTF8.GetBytes(blockId));\n \n var stageResponse = blobClient.StageBlock(base64BlockId, new MemoryStream(bytesToSend));\n var responseInfo = stageResponse.GetRawResponse();\n\n blocklist.Add(base64BlockId); \n}\nwhile (bytesRemain > 0);\n\nvar contentResponse = blobClient.CommitBlockList(blocklist);\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2975931/" ]
74,322,127
<p>I am cleaning data using regex and there are matches that are a substring of the other alternative matches, and when you extract the matches, the one with the substring <strong>DIMM</strong> is extracted but the one that is intended to be extracted from the cell. <strong>SO-DIMM</strong> is extracted as intended except for <strong>SODIMM</strong>.</p> <p>I have tried</p> <pre><code>=REGEXEXTRACT(B75, &quot;(?:SO-DIMM)|(?:SODIMM)|(?:DIMM)&quot;) </code></pre> <p>but I checked the cells containing <strong>SODIMM</strong> but <strong>DIMM</strong> was extracted.</p>
[ { "answer_id": 74322481, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 0, "selected": false, "text": "=IFERROR(IFERROR(REGEXEXTRACT(B75, \"(?:SO-DIMM)\"), \n REGEXEXTRACT(B75, \"(?:SODIMM)\")),\n REGEXEXTRACT(B75, \"(?:DIMM)\"))\n" }, { "answer_id": 74326189, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 3, "selected": true, "text": "\\b(?:SO-?)?DIMM\\b\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19356517/" ]
74,322,129
<p>I have two lists <code>list1</code> and <code>list2</code> with a filename on each line. I want a <code>result</code> with all filenames that are only in <code>list2</code> and not in <code>list1</code>, regardless of specific file extensions (but not all). Using Linux bash, any commands that do not require any extra installations. In the example lists, I do know all file extensions that I wish to ignore. I made an attempt but it does not work at all, I don't know how to fix it. Apologies for my inexperience.</p> <p>I wish to ignore the following extensions: .x .xy .yx .y .jpg</p> <p><strong>list1.txt</strong></p> <pre><code>text.x example.xy file.yx data.y edit edit.jpg </code></pre> <p><strong>list2.txt</strong></p> <pre><code>text rainbow.z file data.y sunshine edit.test.jpg edit.random </code></pre> <p><strong>result.txt</strong></p> <pre><code>rainbow.z sunshine edit.test.jpg edit.random </code></pre> <p>My try:</p> <pre><code>while read LINE do line2=$LINE sed -i 's/\.x$//g' $LINE $line2 sed -i 's/\.xy$//g' $LINE $line2 sed -i 's/\.yx$//g' $LINE $line2 sed -i 's/\.y$//g' $LINE $line2 then sed -i -e '$line' result.txt; fi done &lt; list2.txt </code></pre> <p>Edit: I forgot two requirements. The filenames can have . in them and not all filenames must have an extension. I know the extensions that must be ignored. I ammended the lists accordingly.</p>
[ { "answer_id": 74322389, "author": "Shawn", "author_id": 9952196, "author_profile": "https://Stackoverflow.com/users/9952196", "pm_score": 2, "selected": false, "text": "join" }, { "answer_id": 74322398, "author": "M. Nejat Aydin", "author_id": 13809001, "author_profile": "https://Stackoverflow.com/users/13809001", "pm_score": 3, "selected": true, "text": "awk" }, { "answer_id": 74322458, "author": "jhnc", "author_id": 10971581, "author_profile": "https://Stackoverflow.com/users/10971581", "pm_score": 2, "selected": false, "text": "comm" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19017877/" ]
74,322,141
<p>I have this code and it works. But I want to get two different files.</p> <p><code>file_type</code> returns either <code>NP</code> or <code>KL</code>. So I want to get the NP file with the max value and I want to get the KL file with the max value.</p> <p>The dict looks like</p> <pre><code>{&quot;Blah_Blah_NP_2022-11-01_003006.xlsx&quot;: &quot;2022-03-11&quot;, &quot;Blah_Blah_KL_2022-11-01_003006.xlsx&quot;: &quot;2022-03-11&quot;} </code></pre> <p>This is my code and right now I am just getting the max date without regard to time. Since the date is formatted how it is and I don't care about time, I can just use <code>max()</code>.</p> <p>I'm having trouble expanding the below code to give me the greatest NP file and the greatest KL file. Again, <code>file_type</code> returns the NP or KL string from the file name.</p> <pre><code>file_dict = {} file_path = Path(r'\\place\Report') for file in file_path.iterdir(): if file.is_file(): path_object = Path(file) filename = path_object.name stem = path_object.stem file_type = file_date = stem.split(&quot;_&quot;)[2] file_date = stem.split(&quot;_&quot;)[3] file_dict.update({filename: file_date}) newest = max(file_dict, key=file_dict.get) return newest </code></pre> <p>I basically want <code>newest</code> where <code>file_type</code> = <code>NP</code> and also <code>newest</code> where <code>file_type</code> = <code>KL</code></p>
[ { "answer_id": 74322232, "author": "Artem Ermakov", "author_id": 17801973, "author_profile": "https://Stackoverflow.com/users/17801973", "pm_score": 0, "selected": false, "text": "dict" }, { "answer_id": 74322297, "author": "Grismar", "author_id": 4390160, "author_profile": "https://Stackoverflow.com/users/4390160", "pm_score": 1, "selected": false, "text": "from pathlib import Path\nfrom datetime import datetime\n\n\ndef get_newest():\n maxs = {}\n for file in Path(r'./examples').iterdir():\n if file.is_file():\n *_, t, d, _ = file.stem.split('_')\n d = datetime(*map(int, d.split('-')))\n maxs[t] = d if t not in maxs else max(d, maxs[t])\n return maxs\n\n\nprint(get_newest())\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20334665/" ]
74,322,148
<p>I am trying to package some videos on an ubuntu-ec2 machine using <a href="https://github.com/shaka-project/shaka-packager" rel="nofollow noreferrer">shaka packager</a> and following <a href="https://shaka-project.github.io/shaka-packager/html/tutorials/tutorials.html" rel="nofollow noreferrer">official tutorial</a>.</p> <p>So I have a list of multi resolution files i.e. <code>original=x.mp4</code>, converted are <code>x_480p.mp4, x_360p.mp4</code> and so on. My lowest resolution is 360p. My bash script automatically detects the height and converts lower than that automatically. Using <a href="https://ffmpeg.org/" rel="nofollow noreferrer">ffmpeg</a> it's done nicely. Now the problem is, I need to automatically package the files in <code>converted</code> directory (all of them) using shaka.</p> <p>If I run the script in a single line it works.</p> <pre><code>sudo packager in=dpnd_comp.mp4,stream=video,out=test/video.mp4 in=dpnd_comp.mp4,stream=audio,out=test/audio.mp4 </code></pre> <p>For automatic process I am saving the paths in the vairable <code>inputs</code>. when I run this using variable, it just processes the last video, here <code>360p</code> only.</p> <p>This is the part -</p> <pre><code># using a for loop here inputs=&quot;$inputs in=&quot;$output_path&quot;/&quot;$content_id&quot;_&quot;$height&quot;p.mp4,stream=video,output=&quot;$packaged_out&quot;/&quot;$content_id&quot;_&quot;$height&quot;p.mp4 &quot; done echo &quot;$inputs&quot; sudo packager &quot;$inputs&quot; </code></pre> <p>Note, `echo &quot;$inputs&quot; returns this</p> <pre><code>in=../bin/converted/0001_720p.mp4,stream=video,output=../bin/packaged/0001_720p.mp4 in=../bin/converted/0001_480p.mp4,stream=video,output=../bin/packaged/0001_480p.mp4 in=../bin/converted/0001_360p.mp4,stream=video,output=../bin/packaged/0001_360p.mp4 </code></pre> <p>Any kind of help would be highly appreciated. If anyone ever worked with shaka and made the process automatic, please help.</p> <p><strong>Edit:</strong> Need to add more arguments after the inputs like this -</p> <pre><code>sudo packager &quot;$inputs&quot; \ --enable_widevine_encryption \ --key_server_url &quot;$key_server&quot; \ --content_id &quot;$content_id&quot; \ --signer &quot;$signer_uname&quot; \ --aes_signing_key &quot;$signing_key&quot; \ --aes_signing_iv &quot;$signing_iv&quot; \ --mpd_output &quot;$packaged_out&quot;/&quot;$content_id&quot;.mpd \ --hls_master_playlist_output &quot;$packaged_out&quot;/&quot;$content_id&quot;.m3u8&quot; </code></pre>
[ { "answer_id": 74322524, "author": "chrslg", "author_id": 20037042, "author_profile": "https://Stackoverflow.com/users/20037042", "pm_score": 1, "selected": false, "text": "in=..." }, { "answer_id": 74412127, "author": "ashraf minhaj", "author_id": 17402986, "author_profile": "https://Stackoverflow.com/users/17402986", "pm_score": 1, "selected": true, "text": "cmd_prefix = 'sudo packager..'\ncmd_postfix = '--mpd_output \"${packaged_out}/${content_id}.mpd\" --hls_master_playlist_output \"${packaged_out}/${content_id}.m3u8\"\n\nfor inp in inputs\n cmd_prefix += inp\n\ndrm_command = cmd_perfix + cmd_postfix\n\n\ndrm_processor_response = Popen(f\"({drm_command})\", stderr=PIPE, stdout=PIPE, shell=True)\noutput, errors = drm_processor_response.communicate()\nlog_update([drm_processor_response.returncode, errors.decode(\"utf-8\"), output.decode(\"utf-8\")])\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17402986/" ]
74,322,151
<pre class="lang-java prettyprint-override"><code>class Base { Base() { System.out.println(&quot;Base Constructor&quot;); } } class Derived1 extends Base { private static String pattern = &quot;a+b+&quot;; Derived1() { super(); System.out.println(&quot;Derived 1 Constructor&quot;); } public static boolean doesMatch(String v) { return v.matches(pattern); } } class Derived2 extends Base { private static String pattern = &quot;c+&quot;; Derived2() { super(); System.out.println(&quot;Derived 2 Constructor&quot;); } public static boolean doesMatch(String v) { return v.matches(pattern); } } class Builder { public static Base baseFromString(String v) throws Exception { if (Derived1.doesMatch(v)) return new Derived1(); if (Derived2.doesMatch(v)) return new Derived2(); throw new Exception(&quot;Could not match &quot; + v + &quot; to any derived type.&quot;); } } class Test { public static void main(String[] args) throws Exception { Base b = Builder.baseFromString(&quot;aaab&quot;); } } </code></pre> <p>The code above has a primary problem I want to solve:</p> <ol> <li>The <code>doesMatch</code> method is repeated code for the two derived classes. I'd like to move it to the base class, but then it won't be able to access the pattern member. How do I structure my code better so that each derived class can have its own static pattern, while they all share the same base <code>doesMatch</code> method?</li> </ol> <p>I've tried messing around with abstract classes and interfaces, but I couldn't get anything to work. I am fine with those types of solutions as long as there is a hierarchy where the derived classes either extend or implement the base class.</p> <p><em>Secondary question (from original post)</em></p> <ol start="2"> <li>I might want to add several more derived classes. I'd like to not have to update the <code>baseFromString</code> method with another <code>if</code> every time I extend the base class. Is this something that can be solved with polymorphism?</li> </ol>
[ { "answer_id": 74322524, "author": "chrslg", "author_id": 20037042, "author_profile": "https://Stackoverflow.com/users/20037042", "pm_score": 1, "selected": false, "text": "in=..." }, { "answer_id": 74412127, "author": "ashraf minhaj", "author_id": 17402986, "author_profile": "https://Stackoverflow.com/users/17402986", "pm_score": 1, "selected": true, "text": "cmd_prefix = 'sudo packager..'\ncmd_postfix = '--mpd_output \"${packaged_out}/${content_id}.mpd\" --hls_master_playlist_output \"${packaged_out}/${content_id}.m3u8\"\n\nfor inp in inputs\n cmd_prefix += inp\n\ndrm_command = cmd_perfix + cmd_postfix\n\n\ndrm_processor_response = Popen(f\"({drm_command})\", stderr=PIPE, stdout=PIPE, shell=True)\noutput, errors = drm_processor_response.communicate()\nlog_update([drm_processor_response.returncode, errors.decode(\"utf-8\"), output.decode(\"utf-8\")])\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3543696/" ]
74,322,167
<p>I’m writing a query that returns data in XML format and I need to add a header that contains some static data, and a footer that contains a count of all of the records in the file. is there a way to do that so that the header and footer only appear once in the file?</p> <p>my example query is as follows:</p> <pre><code>SET QUOTED_IDENTIFIER on SET NOCOUNT ON DECLARE @XMLTEST XML SELECT @XMLTEST = ( SELECT GOLFER_NAME AS [GENERAL/NAME], GOLFER_ID AS [GENERAL/ID], HANDICAP_INDEX AS [ATTRIBUTES/HANDICAP], GOLFER_AGE AS [ATTRIBUTES/AGE] FROM GOLFERS FOR XML PATH ('row'), Root('root') ) SET @XMLTEST.modify( 'insert ( attribute xsi:noNamespaceSchemaLocation {&quot;ARIS_Inbound-v4.0.xsd&quot;} ) into (/GolfData)[1]') SELECT @XMLTEST </code></pre> <p>This returns data in the following format:</p> <pre><code>&lt;root&gt; &lt;row&gt; &lt;general&gt; &lt;name&gt;woods,tiger&lt;/name&gt; &lt;id&gt;1&lt;/id&gt; &lt;/general&gt; &lt;attributes&gt; &lt;handicap&gt;4&lt;/handicap&gt; &lt;age&gt;45&lt;/age&gt; &lt;/attributes&gt; &lt;/row&gt; &lt;row&gt; &lt;general&gt; &lt;name&gt;fowler,ricky&lt;/name&gt; &lt;id&gt;2&lt;/id&gt; &lt;/general&gt; &lt;attributes&gt; &lt;handicap&gt;7&lt;/handicap&gt; &lt;age&gt;39&lt;/age&gt; &lt;/attributes&gt; &lt;/row&gt; &lt;/root&gt; </code></pre> <p>Which is what i am looking for but I need to have a header in the file with a format of:</p> <pre><code>&lt;header&gt; &lt;version&gt;1.2.113&lt;/version&gt; &lt;author&gt;lincoln,abraham&lt;/author&gt; &lt;/header&gt; </code></pre> <p>and a footer that counts the number of entries (or rows in this case) like this:</p> <pre><code>&lt;trailer&gt; &lt;rowcount&gt;2&lt;/rowcount&gt; &lt;/trailer&gt; </code></pre> <p>is this possible?</p>
[ { "answer_id": 74322524, "author": "chrslg", "author_id": 20037042, "author_profile": "https://Stackoverflow.com/users/20037042", "pm_score": 1, "selected": false, "text": "in=..." }, { "answer_id": 74412127, "author": "ashraf minhaj", "author_id": 17402986, "author_profile": "https://Stackoverflow.com/users/17402986", "pm_score": 1, "selected": true, "text": "cmd_prefix = 'sudo packager..'\ncmd_postfix = '--mpd_output \"${packaged_out}/${content_id}.mpd\" --hls_master_playlist_output \"${packaged_out}/${content_id}.m3u8\"\n\nfor inp in inputs\n cmd_prefix += inp\n\ndrm_command = cmd_perfix + cmd_postfix\n\n\ndrm_processor_response = Popen(f\"({drm_command})\", stderr=PIPE, stdout=PIPE, shell=True)\noutput, errors = drm_processor_response.communicate()\nlog_update([drm_processor_response.returncode, errors.decode(\"utf-8\"), output.decode(\"utf-8\")])\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4160279/" ]
74,322,168
<p>I use in my app a JscrollPane with a BoxLayout panel inside. I it to never change value after repainting. How can I do this?</p> <p>I tried <code>pane.getHorizontalScrollBar().setValue()</code> but it doesn't change anything.</p>
[ { "answer_id": 74322524, "author": "chrslg", "author_id": 20037042, "author_profile": "https://Stackoverflow.com/users/20037042", "pm_score": 1, "selected": false, "text": "in=..." }, { "answer_id": 74412127, "author": "ashraf minhaj", "author_id": 17402986, "author_profile": "https://Stackoverflow.com/users/17402986", "pm_score": 1, "selected": true, "text": "cmd_prefix = 'sudo packager..'\ncmd_postfix = '--mpd_output \"${packaged_out}/${content_id}.mpd\" --hls_master_playlist_output \"${packaged_out}/${content_id}.m3u8\"\n\nfor inp in inputs\n cmd_prefix += inp\n\ndrm_command = cmd_perfix + cmd_postfix\n\n\ndrm_processor_response = Popen(f\"({drm_command})\", stderr=PIPE, stdout=PIPE, shell=True)\noutput, errors = drm_processor_response.communicate()\nlog_update([drm_processor_response.returncode, errors.decode(\"utf-8\"), output.decode(\"utf-8\")])\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20420711/" ]
74,322,183
<p>I assume this is a good task for Python's <code>itertools</code>. But I don't get it which one of it's magic methods I should use here.</p> <p>The input data</p> <pre><code>kill = ['err A', 'err B', 'err C'] lines = ['keep A', 'err B foo', 'err A bar', 'keep B', 'err C foobar'] </code></pre> <p>The expected output</p> <pre><code>['keep A', 'keep B'] </code></pre> <p>Very conservatively I would solve it like this</p> <pre><code>for e in lines: ok = True for k in kill: if e.startswith(k): ok = False if ok: result.append(e) </code></pre> <p>Can <code>itertools</code> help me here?</p>
[ { "answer_id": 74322524, "author": "chrslg", "author_id": 20037042, "author_profile": "https://Stackoverflow.com/users/20037042", "pm_score": 1, "selected": false, "text": "in=..." }, { "answer_id": 74412127, "author": "ashraf minhaj", "author_id": 17402986, "author_profile": "https://Stackoverflow.com/users/17402986", "pm_score": 1, "selected": true, "text": "cmd_prefix = 'sudo packager..'\ncmd_postfix = '--mpd_output \"${packaged_out}/${content_id}.mpd\" --hls_master_playlist_output \"${packaged_out}/${content_id}.m3u8\"\n\nfor inp in inputs\n cmd_prefix += inp\n\ndrm_command = cmd_perfix + cmd_postfix\n\n\ndrm_processor_response = Popen(f\"({drm_command})\", stderr=PIPE, stdout=PIPE, shell=True)\noutput, errors = drm_processor_response.communicate()\nlog_update([drm_processor_response.returncode, errors.decode(\"utf-8\"), output.decode(\"utf-8\")])\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4865723/" ]
74,322,204
<p>I have combined 2 dataframes and I want to make sure that the user id is not repeated and all values are written in 1 line, and not duplicated. This is a ready-made dataframe, but I need to edit it and remove repetitions. I attach the input data:</p> <pre><code>rzd = pd.DataFrame({ 'client_id': [111, 112, 113, 114, 115], 'rzd_revenue': [1093, 2810, 10283, 5774, 981]}) rzd auto = pd.DataFrame({ 'client_id': [113, 114, 115, 116, 117], 'auto_revenue': [57483, 83, 912, 4834, 98]}) auto air = pd.DataFrame({ 'client_id': [115, 116, 117, 118], 'air_revenue': [81, 4, 13, 173]}) air client_base = pd.DataFrame({ 'client_id': [111, 112, 113, 114, 115, 116, 117, 118], 'address': ['Комсомольская 4', 'Энтузиастов 8а', 'Левобережная 1а', 'Мира 14', 'ЗЖБИиДК 1', 'Строителей 18', 'Панфиловская 33', 'Мастеркова 4']}) client_base </code></pre> <pre><code>frames = [rzd, auto, air] result = pd.concat(frames) result full_result = result.merge(client_base) full_result </code></pre> <pre><code> client_id rzd_revenue auto_revenue air_revenue address 0 111 1093.0 NaN NaN Комсомольская 4 1 112 2810.0 NaN NaN Энтузиастов 8а 2 113 10283.0 NaN NaN Левобережная 1а 3 113 NaN 57483.0 NaN Левобережная 1а 4 114 5774.0 NaN NaN Мира 14 5 114 NaN 83.0 NaN Мира 14 6 115 981.0 NaN NaN ЗЖБИиДК 1 7 115 NaN 912.0 NaN ЗЖБИиДК 1 8 115 NaN NaN 81.0 ЗЖБИиДК 1 9 116 NaN 4834.0 NaN Строителей 18 10 116 NaN NaN 4.0 Строителей 18 11 117 NaN 98.0 NaN Панфиловская 33 12 117 NaN NaN 13.0 Панфиловская 33 13 118 NaN NaN 173.0 Мастеркова 4 </code></pre> <p>The numbers are different documentation, by type merge, concat, and so on, but I did not find clear articles on editing.</p> <p>As a result, it should look like this:</p> <pre><code> client_id rzd_revenue auto_revenue air_revenue address 0 111 1093.0 0.0 0.0 Комсомольская 4 1 112 2810.0 0.0 0.0 Энтузиастов 8а 2 113 10283.0 57483.0 0.0 Левобережная 1а 3 114 5774.0 83.0 0.0 Мира 14 4 115 981.0 912.0 81.0 ЗЖБИиДК 1 </code></pre>
[ { "answer_id": 74322524, "author": "chrslg", "author_id": 20037042, "author_profile": "https://Stackoverflow.com/users/20037042", "pm_score": 1, "selected": false, "text": "in=..." }, { "answer_id": 74412127, "author": "ashraf minhaj", "author_id": 17402986, "author_profile": "https://Stackoverflow.com/users/17402986", "pm_score": 1, "selected": true, "text": "cmd_prefix = 'sudo packager..'\ncmd_postfix = '--mpd_output \"${packaged_out}/${content_id}.mpd\" --hls_master_playlist_output \"${packaged_out}/${content_id}.m3u8\"\n\nfor inp in inputs\n cmd_prefix += inp\n\ndrm_command = cmd_perfix + cmd_postfix\n\n\ndrm_processor_response = Popen(f\"({drm_command})\", stderr=PIPE, stdout=PIPE, shell=True)\noutput, errors = drm_processor_response.communicate()\nlog_update([drm_processor_response.returncode, errors.decode(\"utf-8\"), output.decode(\"utf-8\")])\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20217375/" ]
74,322,259
<p>objective: save emails as PDF files in a folder problem: Outlook folder has over 1000 emails. Code runs for 26 emails then stops/freezes.<br /> attempts: tried different Outlook email folders with different content all stop at 26/27. I suspect its creating some type of memory issue? Not closing something? Thanks for any help.</p> <p>here is the code</p> <pre><code>Sub save_as_PDF() Dim objDoc As Object, objInspector As Object Dim outApp As Object, objOutlook As Object, objFolder As Object, myItems As Object, myItem As Object Dim FolderPath, FileName, ClientName, ModTime, ranDigits As String Set outApp = CreateObject(&quot;Outlook.Application&quot;) Set objOutlook = outApp.GetNamespace(&quot;MAPI&quot;) Set objFolder = objOutlook.GetDefaultFolder(olFolderInbox).Folders(&quot;regular&quot;) Set myItems = objFolder.Items FolderPath = &quot;C:\Users\xxxxx\Documents\My Documents\__AA My Daily\vbaOutlookTestFolder\&quot; On Error Resume Next For Each myItem In myItems Set objInspector = Nothing Set objDoc = Nothing Set objInspector = Nothing Set objDoc = Nothing FileName = myItem.To FileName = Replace(FileName, &quot;.&quot;, &quot;&quot;) Set objInspector = myItem.GetInspector Set objDoc = objInspector.WordEditor objDoc.ExportAsFixedFormat FolderPath &amp; FileName &amp; &quot;.pdf&quot;, 17 Next myItem End Sub attempts: tried different Outlook email folders with different content all stop at 26/27. I expected it to convert every email item in the folder to a pdf I suspect its creating some type of memory issue? Not closing something? Thanks </code></pre>
[ { "answer_id": 74322524, "author": "chrslg", "author_id": 20037042, "author_profile": "https://Stackoverflow.com/users/20037042", "pm_score": 1, "selected": false, "text": "in=..." }, { "answer_id": 74412127, "author": "ashraf minhaj", "author_id": 17402986, "author_profile": "https://Stackoverflow.com/users/17402986", "pm_score": 1, "selected": true, "text": "cmd_prefix = 'sudo packager..'\ncmd_postfix = '--mpd_output \"${packaged_out}/${content_id}.mpd\" --hls_master_playlist_output \"${packaged_out}/${content_id}.m3u8\"\n\nfor inp in inputs\n cmd_prefix += inp\n\ndrm_command = cmd_perfix + cmd_postfix\n\n\ndrm_processor_response = Popen(f\"({drm_command})\", stderr=PIPE, stdout=PIPE, shell=True)\noutput, errors = drm_processor_response.communicate()\nlog_update([drm_processor_response.returncode, errors.decode(\"utf-8\"), output.decode(\"utf-8\")])\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20420660/" ]
74,322,284
<p>The question includes that you need to have a main class consisting of fields, these fields are hours minutes, and seconds. I have to use this format and I can't import anything like datetime. the question is that I need to add 2 methods first to count full minutes in our time for example let's say we have a time of 1 hour and 22 minutes the code should give 82 minutes, so convert hours into minutes and then add it all in total which I already have done. and the second method is to remove 10 minutes from the time so I have to check that the time will not go in minus so here is my code I'm just stuck at the removing 10 minutes part but can't seem to add it all together.</p> <pre><code>class Time: def __init__(self, hour, min, sec): self.hour = hour self.min = min self.sec = sec if self.hour &gt; 24 or self.min &gt; 60 or self.sec &gt; 60: exit() def minutes_in_full_time(self): return self.hour * 60 + self.min def remove_ten(self): if self.hour &gt;= 23 and self.min &gt;= 50 and self.sec &gt;= 60: print(&quot;Add 10 min&quot; + str(0) + &quot;:&quot; + str(0) + &quot;:&quot; + str(self.min - 60 - 10)) elif self.hour &lt; 23 and self.min &gt;= 50 and self.sec &gt;= 60: print(&quot;Add 10 min&quot; + str(self.hour + 1) + &quot;:&quot; + str(0) + &quot;:&quot; + str(self.sec - 60 - 10)) elif self.hour &lt; 23 and self.min &lt; 50 and self.sec &gt;= 60: print(&quot;Add 10 min&quot; + str(self.hour + 1) + &quot;:&quot; + str(self.min + 1) + &quot;:&quot; + str(self.sec - 60 - 10)) else: print(&quot;Add 10 min&quot; + str(self.hour) + &quot;:&quot; + str(self.min + 1) + &quot;:&quot; + str(self.sec - 60 - 10)) def __del__(self): print(&quot;Видалено&quot;) time1 = Time(6, 34, 22) print(&quot;amount of minutes in hours&quot;, time1.minutes_in_full_time) time1.remove_ten() del time1 </code></pre>
[ { "answer_id": 74322524, "author": "chrslg", "author_id": 20037042, "author_profile": "https://Stackoverflow.com/users/20037042", "pm_score": 1, "selected": false, "text": "in=..." }, { "answer_id": 74412127, "author": "ashraf minhaj", "author_id": 17402986, "author_profile": "https://Stackoverflow.com/users/17402986", "pm_score": 1, "selected": true, "text": "cmd_prefix = 'sudo packager..'\ncmd_postfix = '--mpd_output \"${packaged_out}/${content_id}.mpd\" --hls_master_playlist_output \"${packaged_out}/${content_id}.m3u8\"\n\nfor inp in inputs\n cmd_prefix += inp\n\ndrm_command = cmd_perfix + cmd_postfix\n\n\ndrm_processor_response = Popen(f\"({drm_command})\", stderr=PIPE, stdout=PIPE, shell=True)\noutput, errors = drm_processor_response.communicate()\nlog_update([drm_processor_response.returncode, errors.decode(\"utf-8\"), output.decode(\"utf-8\")])\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19399005/" ]
74,322,304
<p>I am trying to add values to a 2D array in Google Apps Script. The following code runs, but is not the desired output for the array.</p> <pre><code>function fruitList() { var fruitArray = [['apple'], ['banana'], ['cherry']]; var newArray = []; fruitArray.forEach(function(value) { newArray.push([value, &quot;name&quot;]); }); } </code></pre> <p>My code yields the following output:</p> <p><code>[ [ [ 'apple' ], 'name' ], [ [ 'banana' ], 'name' ], [ [ 'cherry' ], 'name' ] ]</code></p> <p>My desired output is:</p> <p><code>[ [ 'apple', 'name' ], [ 'banana', 'name' ], [ 'cherry', 'name' ] ]</code></p>
[ { "answer_id": 74322337, "author": "TheMaster", "author_id": 8404453, "author_profile": "https://Stackoverflow.com/users/8404453", "pm_score": 3, "selected": true, "text": "value" }, { "answer_id": 74323143, "author": "Cooper", "author_id": 7215091, "author_profile": "https://Stackoverflow.com/users/7215091", "pm_score": 1, "selected": false, "text": "function fruitList() {\n var fruitArray = [['apple'], ['banana'], ['cherry']];\n var newArray = [];\n\n fruitArray.forEach(function(value) {\n newArray.push([value[0], \"name\"]);\n });\n Logger.log(JSON.stringify(newArray))\n}\n\nExecution log\n3:27:33 PM Notice Execution started\n3:27:34 PM Info [[\"apple\",\"name\"],[\"banana\",\"name\"],[\"cherry\",\"name\"]]\n3:27:34 PM Notice Execution completed\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19286901/" ]
74,322,307
<p>Right now my Django + Gunicorn app is printing only this info:</p> <pre><code>[03.10.2022 19:43:14] INFO [django.request:middleware] GET /analyse/v2/ping - 200 </code></pre> <p>If request is authorized, I would like to show also user (username/email) behind the status code, something like:</p> <pre><code>[03.10.2022 19:43:14] INFO [django.request:middleware] GET /analyse/v2/ping - 200 - useremail@outlook.com </code></pre> <p>If the request is not authorized then write UNAUTHORIZED:</p> <pre><code>[03.10.2022 19:43:14] INFO [django.request:middleware] GET /analyse/v2/ping - 200 - UNAUTHORIZED </code></pre> <p>How can I achieve this with a combination of Django and Gunicorn?</p> <p>Thank you</p> <p>Solved by adding this part of code in settings:</p> <pre><code>def add_username(record): try: username = record.request.user.username except AttributeError: username = &quot;&quot; record.username = username return True LOGGING = { &quot;version&quot;: 1, &quot;disable_existing_loggers&quot;: True, &quot;root&quot;: {&quot;level&quot;: &quot;WARNING&quot;, &quot;handlers&quot;: [&quot;console&quot;]}, &quot;formatters&quot;: { &quot;verbose&quot;: { &quot;format&quot;: &quot;[%(asctime)s] %(levelname)s [%(name)s:%(module)s] [%(username)s] %(message)s&quot;, &quot;datefmt&quot;: &quot;%d.%m.%Y %H:%M:%S&quot;, }, &quot;simple&quot;: {&quot;format&quot;: &quot;%(levelname)s %(message)s&quot;}, }, &quot;filters&quot;: { &quot;add_username&quot;: { &quot;()&quot;: &quot;django.utils.log.CallbackFilter&quot;, &quot;callback&quot;: add_username, } }, &quot;handlers&quot;: { &quot;console&quot;: { &quot;level&quot;: &quot;DEBUG&quot;, &quot;class&quot;: &quot;logging.StreamHandler&quot;, &quot;formatter&quot;: &quot;verbose&quot;, &quot;filters&quot;: [&quot;add_username&quot;], }, ... </code></pre>
[ { "answer_id": 74575273, "author": "Sam", "author_id": 10708446, "author_profile": "https://Stackoverflow.com/users/10708446", "pm_score": 1, "selected": false, "text": "import logging\n\nfrom loguru import logger # optional if you are not using it already.\n\nfrom django.utils import timezone\n\nlogger = logging.getLogger('django.request')\n\n\nclass LogRequest:\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n response = self.get_response(request)\n\n user = (\n request.user.email\n if request.user.is_authenticated\n else \"UNAUTHORIZED\"\n )\n\n logger.info(\n f\"[{timezone.now().strftime('%d.%m.%Y %H:%M:%S')}] INFO [myapp.custom_logger] {request.method} {request.path} - {response.status_code} - {user}\"\n )\n\n return response\n\n" }, { "answer_id": 74577513, "author": "Antoine Pinsard", "author_id": 1529346, "author_profile": "https://Stackoverflow.com/users/1529346", "pm_score": 3, "selected": true, "text": "django.request" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2052105/" ]
74,322,309
<p>I got a dataframe where some rows contains almost duplicate values. I'd like to combine these rows as much as possible to reduce the row numbers. Let's say I got following dataframe:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">One</th> <th style="text-align: center;">Two</th> <th style="text-align: right;">Three</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">A</td> <td style="text-align: center;">B</td> <td style="text-align: right;">C</td> </tr> <tr> <td style="text-align: left;">B</td> <td style="text-align: center;">B</td> <td style="text-align: right;">B</td> </tr> <tr> <td style="text-align: left;">C</td> <td style="text-align: center;">A</td> <td style="text-align: right;">B</td> </tr> </tbody> </table> </div> <p>In this example I'd like the output to be:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">One</th> <th style="text-align: center;">Two</th> <th style="text-align: right;">Three</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">ABC</td> <td style="text-align: center;">AB</td> <td style="text-align: right;">CB</td> </tr> </tbody> </table> </div> <p>The real dataframe got thousands of rows with eight columns.</p> <p>The csv from a dataframe-sample:</p> <pre><code>Column_1,Column_2,Column_3,Column_4,Column_5,Column_6,Column_7,Column_8 A,A,A,A,A,A,A,A A,A,A,A,A,A,A,B A,A,A,A,A,A,A,C A,A,A,A,A,A,B,A A,A,A,A,A,A,B,B A,A,A,A,A,A,B,C A,A,A,A,A,A,C,A A,A,A,A,A,A,C,B A,A,A,A,A,A,C,C C,C,C,C,C,C,A,A C,C,C,C,C,C,A,B C,C,C,C,C,C,A,C C,C,C,C,C,C,B,A C,C,C,C,C,C,B,B C,C,C,C,C,C,B,C C,C,C,C,C,C,C,A C,C,C,C,C,C,C,B C,C,C,C,C,C,C,C </code></pre> <p>To easier show how desired outcome woud look like:</p> <pre><code>Column_1,Column_2,Column_3,Column_4,Column_5,Column_6,Column_7,Column_8 AC,AC,AC,AC,AC,AC,ABC,ABC </code></pre> <p>I've tried some code but I end up in real long code snippets which I doubt could be the best and most natural solution. Any suggestions?</p>
[ { "answer_id": 74575273, "author": "Sam", "author_id": 10708446, "author_profile": "https://Stackoverflow.com/users/10708446", "pm_score": 1, "selected": false, "text": "import logging\n\nfrom loguru import logger # optional if you are not using it already.\n\nfrom django.utils import timezone\n\nlogger = logging.getLogger('django.request')\n\n\nclass LogRequest:\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n response = self.get_response(request)\n\n user = (\n request.user.email\n if request.user.is_authenticated\n else \"UNAUTHORIZED\"\n )\n\n logger.info(\n f\"[{timezone.now().strftime('%d.%m.%Y %H:%M:%S')}] INFO [myapp.custom_logger] {request.method} {request.path} - {response.status_code} - {user}\"\n )\n\n return response\n\n" }, { "answer_id": 74577513, "author": "Antoine Pinsard", "author_id": 1529346, "author_profile": "https://Stackoverflow.com/users/1529346", "pm_score": 3, "selected": true, "text": "django.request" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15905006/" ]
74,322,310
<p>Here is a reproducable stackblitz - <a href="https://stackblitz.com/edit/nuxt-starter-jlzzah?file=components/users.vue" rel="nofollow noreferrer">https://stackblitz.com/edit/nuxt-starter-jlzzah?file=components/users.vue</a></p> <p><strong>What's wrong? -</strong> My code fetches 15 items, and with the bottom scroll event it should fetch another 15 different items but it just fetches same items again.</p> <p>I've followed this bottom video for this implementation, it's okay in the video but not okay in my stackblitz code: <a href="https://www.youtube.com/watch?v=WRnoQdIU-uE&amp;t=3s&amp;ab_channel=JohnKomarnicki" rel="nofollow noreferrer">https://www.youtube.com/watch?v=WRnoQdIU-uE&amp;t=3s&amp;ab_channel=JohnKomarnicki</a></p> <p>The only difference with this video is that he's using axios while i use useFetch of nuxt 3.</p>
[ { "answer_id": 74322834, "author": "cDI", "author_id": 17882299, "author_profile": "https://Stackoverflow.com/users/17882299", "pm_score": 2, "selected": true, "text": "useFetch" }, { "answer_id": 74326966, "author": "Stefan", "author_id": 3932899, "author_profile": "https://Stackoverflow.com/users/3932899", "pm_score": 2, "selected": false, "text": "useFetch" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17817556/" ]
74,322,324
<p>I'm trying to build a script that opens all of the web dev programs I use. I want the <code>print(&quot;Opened all apps&quot;)</code> to only run once all 3 programs have opened and fully loaded (rather than currently printing after just opening the programs and not waiting for them to load) because I want to do something after they've loaded.</p> <p>I have the following:</p> <pre><code>import subprocess chrome = &quot;Google Chrome&quot; mongo = &quot;MongoDB Compass&quot; vsc = &quot;Visual Studio Code&quot; apps = [chrome, vsc, mongo] for app in apps: p = subprocess.Popen([&quot;open&quot;, &quot;-a&quot;, app]) print(&quot;Opening &quot; + app) p.wait() print(&quot;Opened?&quot;) print(&quot;Opened all apps&quot;) </code></pre> <p>However, the problem is that <code>p.wait()</code> seems to not wait for each app to load. Does anyone know why this happens and how to make it wait properly for all apps to fully load?</p> <p>I tried the suggestions from this post: <a href="https://stackoverflow.com/questions/8953119/python-waiting-for-external-launched-process-finish">Python: waiting for external launched process finish</a></p> <p>Thank you for any advice</p>
[ { "answer_id": 74322346, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 2, "selected": false, "text": "wait" }, { "answer_id": 74322558, "author": "Remzinho", "author_id": 2484591, "author_profile": "https://Stackoverflow.com/users/2484591", "pm_score": 2, "selected": true, "text": "subprocess" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8758206/" ]
74,322,377
<p>How do I let the following code know that <code>u</code> is a string?</p> <p>I am currently getting</p> <blockquote> <p><code>Argument of type 'string | number | symbol' is not assignable to parameter of type 'string'</code></p> </blockquote> <pre><code>interface MyDef { a: &quot;a&quot;, } export class Router&lt;t&gt;{ public generate&lt;u extends keyof t&gt;(path: u) { this.test(path) } public test(s: string) { console.log(s); } } const x = new Router&lt;MyDef&gt;(); // &quot;a&quot; is defined in MyDef - should work x.generate(&quot;a&quot;); // should not compile x.generate(&quot;not-in-mydef&quot;); </code></pre> <p>Things I have tried</p> <pre><code>interface RouteSet { [k: string]: string; } // … export class Router&lt;t extends RouteSet&gt;{ </code></pre> <pre><code>export class Router&lt;t extends Record&lt;string,string&gt;&gt;{ </code></pre> <pre><code>export class Router&lt;t extends {[key: string]: string}&gt;{ </code></pre> <p>I can't seem to find a way to let TypeScript know I only ever want <code>u</code> to be a string.</p> <p>I can <code>this.test(path as any as string)</code> to quiet the compiler, but that's far from ideal.</p>
[ { "answer_id": 74322424, "author": "Lesiak", "author_id": 1570854, "author_profile": "https://Stackoverflow.com/users/1570854", "pm_score": 2, "selected": true, "text": "test" }, { "answer_id": 74322480, "author": "caTS", "author_id": 18244921, "author_profile": "https://Stackoverflow.com/users/18244921", "pm_score": 2, "selected": false, "text": "keyof t" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/345350/" ]
74,322,378
<p>Does anyone know how I can extract the end 6 characters in a absoloute URL e.g</p> <pre><code>/es/ideas-de-trading-y-noticias/el-ibex-35-insiste-en-buscar-los-7900-puntos-a-la-espera-de-las--221104 </code></pre> <p>This is not a typical URL sometimetimes it ends -221104</p> <p>Also, is there a way to turn <code>221104</code> into the date <code>04 11 2022</code> easily?</p> <p>Thanks in advance</p> <p>Mark</p>
[ { "answer_id": 74322419, "author": "some_programmer", "author_id": 11135962, "author_profile": "https://Stackoverflow.com/users/11135962", "pm_score": 1, "selected": false, "text": "--" }, { "answer_id": 74322431, "author": "mattiatantardini", "author_id": 16797805, "author_profile": "https://Stackoverflow.com/users/16797805", "pm_score": 2, "selected": false, "text": "--" }, { "answer_id": 74322455, "author": "The Myth", "author_id": 15042008, "author_profile": "https://Stackoverflow.com/users/15042008", "pm_score": 2, "selected": true, "text": "yy-mm-dd" }, { "answer_id": 74322456, "author": "Jimpsoni", "author_id": 18195201, "author_profile": "https://Stackoverflow.com/users/18195201", "pm_score": 1, "selected": false, "text": "date = url.split(\"--\")[1]\n" }, { "answer_id": 74322471, "author": "Ryan Nygard", "author_id": 10593669, "author_profile": "https://Stackoverflow.com/users/10593669", "pm_score": 2, "selected": false, "text": "from datetime import datetime\n\nurl = 'https://www.ig.com/es/ideas-de-trading-y-noticias/el-ibex-35-insiste-en-buscar-los-7900-puntos-a-la-espera-de-las--221104'\n\ndatetime_string = url.split('--')[1]\n\ndate = datetime.strptime(datetime_string, '%y%m%d')\n\nprint(f\"{date.day} {date.month} {date.year}\")\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20401143/" ]
74,322,463
<p>If I have an object parent like this, and an object with every field name is the ID which include the array like childs. How can I do to have clone the parent become children with different attritube as the result I mention below?</p> <pre><code>var parent = { 'Name': 'Product ABC', } var attributes = { // AttributeId : Name 'ID0001': ['Black', 'Red'], 'ID0002': ['Small', 'Medium', 'Large'], 'ID0003': ['Cotton', 'Len'] } </code></pre> <p>The children cloned should be</p> <pre><code>{ 'Name': 'Product ABC', // Same as parent 'Attributes': [ // Black - Small - Cotton {'AttributeId':'ID0001', value:'Black'}, {'AttributeId':'ID0002', value:'Small'} {'AttributeId':'ID0003', value:'Cotton'} ] }, { 'Name': 'Product ABC', // Same as parent 'Attributes': [ // Red - Small - Cotton {'AttributeId':'ID0001', value:'Red'}, {'AttributeId':'ID0002', value:'Small'} {'AttributeId':'ID0003', value:'Cotton'} ] }, { 'Name': 'Product ABC', // Same as parent 'Attributes': [ // Black - Medium - Cotton {'AttributeId':'ID0001', value:'Black'}, {'AttributeId':'ID0002', value:'Medium'} {'AttributeId':'ID0003', value:'Cotton'} ] } ..... </code></pre> <p>P/S It seem to hard to understand the values rule of the children generated. Here is my description: children is cloned to become full of atributes in the 'attributes' object that include some arrays, but it unique atribute. like 'Black - Small - Cotton', 'Red - Small - Cotton', 'Black - Medium - Cotton', 'Black - Medium - Len', ...</p>
[ { "answer_id": 74322419, "author": "some_programmer", "author_id": 11135962, "author_profile": "https://Stackoverflow.com/users/11135962", "pm_score": 1, "selected": false, "text": "--" }, { "answer_id": 74322431, "author": "mattiatantardini", "author_id": 16797805, "author_profile": "https://Stackoverflow.com/users/16797805", "pm_score": 2, "selected": false, "text": "--" }, { "answer_id": 74322455, "author": "The Myth", "author_id": 15042008, "author_profile": "https://Stackoverflow.com/users/15042008", "pm_score": 2, "selected": true, "text": "yy-mm-dd" }, { "answer_id": 74322456, "author": "Jimpsoni", "author_id": 18195201, "author_profile": "https://Stackoverflow.com/users/18195201", "pm_score": 1, "selected": false, "text": "date = url.split(\"--\")[1]\n" }, { "answer_id": 74322471, "author": "Ryan Nygard", "author_id": 10593669, "author_profile": "https://Stackoverflow.com/users/10593669", "pm_score": 2, "selected": false, "text": "from datetime import datetime\n\nurl = 'https://www.ig.com/es/ideas-de-trading-y-noticias/el-ibex-35-insiste-en-buscar-los-7900-puntos-a-la-espera-de-las--221104'\n\ndatetime_string = url.split('--')[1]\n\ndate = datetime.strptime(datetime_string, '%y%m%d')\n\nprint(f\"{date.day} {date.month} {date.year}\")\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2622760/" ]
74,322,510
<p>I want to make data subset with logical expression i have stored in string, like this:</p> <pre><code>logical_var = paste0(&quot;input_dataset$&quot;,&quot;heigth &gt;= 1.60&quot;) </code></pre> <p>but i cant use it as</p> <pre><code>subset_data &lt;- input_dataset[ which(logical_var), ] </code></pre> <p>or</p> <pre><code>subset_data &lt;- input_dataset[ which(as.logical(logical_var)), ] </code></pre> <p>because it makes obvious syntax error. From documentation i understand, that wchich() takes only logical expressions.</p> <p>The effect I want to get would be as in such expression:</p> <pre><code>subset_data &lt;- input_dataset[ which(input_dataset$heigth &gt;= 1.60), ] </code></pre> <p>but I don't know the selection condition in advance, I read it from a specific variable.</p> <p>What should i do with it?</p>
[ { "answer_id": 74322419, "author": "some_programmer", "author_id": 11135962, "author_profile": "https://Stackoverflow.com/users/11135962", "pm_score": 1, "selected": false, "text": "--" }, { "answer_id": 74322431, "author": "mattiatantardini", "author_id": 16797805, "author_profile": "https://Stackoverflow.com/users/16797805", "pm_score": 2, "selected": false, "text": "--" }, { "answer_id": 74322455, "author": "The Myth", "author_id": 15042008, "author_profile": "https://Stackoverflow.com/users/15042008", "pm_score": 2, "selected": true, "text": "yy-mm-dd" }, { "answer_id": 74322456, "author": "Jimpsoni", "author_id": 18195201, "author_profile": "https://Stackoverflow.com/users/18195201", "pm_score": 1, "selected": false, "text": "date = url.split(\"--\")[1]\n" }, { "answer_id": 74322471, "author": "Ryan Nygard", "author_id": 10593669, "author_profile": "https://Stackoverflow.com/users/10593669", "pm_score": 2, "selected": false, "text": "from datetime import datetime\n\nurl = 'https://www.ig.com/es/ideas-de-trading-y-noticias/el-ibex-35-insiste-en-buscar-los-7900-puntos-a-la-espera-de-las--221104'\n\ndatetime_string = url.split('--')[1]\n\ndate = datetime.strptime(datetime_string, '%y%m%d')\n\nprint(f\"{date.day} {date.month} {date.year}\")\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7751099/" ]
74,322,511
<p>my column names are 22abcd123, 33sdfjsdh77, 45hgvjh77, 44vhsfgdhd88 i need my column name as 22,33,45,44.</p> <p>I tried: res = int(re.findall('(\d+)',df.columns[5])[0]) i got the answer for 1 column name . but I need it for every column name in a Dataframe</p>
[ { "answer_id": 74322573, "author": "TheDataScienceNinja", "author_id": 10929995, "author_profile": "https://Stackoverflow.com/users/10929995", "pm_score": 0, "selected": false, "text": "myArray = pandas.columns(df)\n" }, { "answer_id": 74322713, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": true, "text": "df.columns = df.columns.str.extract('(\\d+)', expand=False)\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20418639/" ]
74,322,513
<p>Has anyone figured out how to extract the numbers 4.25%-4.5% and 4%-4.5% from the cell?</p> <p><a href="https://i.stack.imgur.com/tjNd9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tjNd9.png" alt="enter image description here" /></a><br> <a href="https://i.stack.imgur.com/bcUT6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bcUT6.png" alt="enter image description here" /></a></p> <p>Thanks!</p> <p>I tried the formula for the value on the left:</p> <p><code>=IFERROR(IF(D5=&quot;&quot;,0,LEFT(D5,FIND(&quot;%&quot;,D5))+0),&quot;N/A&quot;)</code></p> <p>I tried the formula for the value on the right:</p> <p><code>=IFERROR(IF(D5=&quot;&quot;,0,RIGHT(D5,FIND(&quot;%&quot;,D5))+0),&quot;N/A&quot;)</code></p> <p>It works for Baltimore but is not working for New Jersey for me.</p>
[ { "answer_id": 74322573, "author": "TheDataScienceNinja", "author_id": 10929995, "author_profile": "https://Stackoverflow.com/users/10929995", "pm_score": 0, "selected": false, "text": "myArray = pandas.columns(df)\n" }, { "answer_id": 74322713, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": true, "text": "df.columns = df.columns.str.extract('(\\d+)', expand=False)\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17271656/" ]
74,322,557
<p>I using to jsf for web app learn. But not showing value in index.xhtml . My class name is JsfBean and Named value is cdiBean. I want to call patika variable . How can I solve this problem? Is have info anyone</p> <p>index.xhtml file</p> <pre><code>&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt; &lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; xmlns:h=&quot;http://xmlns.jcp.org/jsf/html&quot; xmlns:ui=&quot;http://xmlns.jcp.org/jsf/facelets&quot; xmlns:f=&quot;http://xmlns.jcp.org/jsf/core&quot;&gt; &lt;h:head&gt; &lt;title&gt; JSF 2.2&lt;/title&gt; &lt;/h:head&gt; &lt;h:body&gt; &lt;h:form&gt; &lt;h:outputText value=&quot;#{cdiBean.patika}&quot;/&gt; &lt;/h:form&gt; &lt;/h:body&gt; &lt;/html&gt; </code></pre> <p>JsfBean Class</p> <pre><code> import jakarta.enterprise.context.RequestScoped; import jakarta.inject.Named; import lombok.Getter; import lombok.Setter; @Named(value = &quot;cdiBean&quot;) @RequestScoped @Getter @Setter public class JsfBean { public String patika; public JsfBean() { patika=&quot;Spring Boot Eğitime Hoşgeldiniz&quot;; System.out.println(patika); } } </code></pre> <p>Web.xml file</p> <pre><code>&lt;web-app xmlns=&quot;https://jakarta.ee/xml/ns/jakartaee&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd&quot; version=&quot;5.0&quot;&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;index.xhtml&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;/web-app&gt; </code></pre>
[ { "answer_id": 74322573, "author": "TheDataScienceNinja", "author_id": 10929995, "author_profile": "https://Stackoverflow.com/users/10929995", "pm_score": 0, "selected": false, "text": "myArray = pandas.columns(df)\n" }, { "answer_id": 74322713, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": true, "text": "df.columns = df.columns.str.extract('(\\d+)', expand=False)\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12785216/" ]
74,322,570
<p>I have a stock dataset which for the sake of simplicity of this question only has a 'close' column and looks like this:</p> <pre><code>import pandas as pd df = pd.DataFrame({'close': [1, 1.01, 1.015, 1.0, 0.98]}) print(df) close 0 1.000 1 1.010 2 1.015 3 1.000 4 0.980 </code></pre> <p>Now I want to classify all datapoints wether they would be a profitable long opportunity. A profitable long opportunity means, that the future prices will hit a specific level which will be greater or equal to the specified win level. Contrary to that, it will not be profitable if it hits a loss level before.</p> <p>I'm currently using this function:</p> <pre><code>def classify_long_opportunities( df: pd.DataFrame, profit_pct: float = 0.01, # won after one percent loss_pct: float = 0.01, # lost after one percent ): res = [] for t in df[['close']].itertuples(): idx, c = t # extract index and close price win = c + c * profit_pct # calculate the desired win level loss = c - c * loss_pct # &quot;&quot; loss level for e in df[['close']].loc[idx:].itertuples(): # iterate through the future prices _, p_c = e # extract posterior closing price if c &lt; win &lt;= p_c: # found a fitting profit level res.append(1) break elif c &gt; loss &gt;= p_c: # found a losing level res.append(-1) break else: # didn't found fitting level at all res.append(0) df['long_opportunities'] = res </code></pre> <p>The function classifies correctly:</p> <pre><code>classify_long_opportunities(df=df) print(df) close long_opportunities 0 1.000 1 1 1.010 -1 2 1.015 -1 3 1.000 -1 4 0.980 0 </code></pre> <p>But it's very slow. How can I optimize this function with the use of vectorization like <code>numpy.where</code> or <code>numpy.select</code> or a <code>pandas</code> function?</p>
[ { "answer_id": 74322573, "author": "TheDataScienceNinja", "author_id": 10929995, "author_profile": "https://Stackoverflow.com/users/10929995", "pm_score": 0, "selected": false, "text": "myArray = pandas.columns(df)\n" }, { "answer_id": 74322713, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": true, "text": "df.columns = df.columns.str.extract('(\\d+)', expand=False)\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17101330/" ]
74,322,577
<p>As title says, my latest attempt will compare a column to the other column and iterate through each row. However, I am stuck on how to go to the next columns to iterate through.</p> <pre><code> Dim i As Long Dim s1, s2 As Worksheet Set s1 = Worksheets(&quot;sheet1&quot;) Set s2= Worksheets(&quot;sheet2&quot;) For i = 2 To Rows.Count If IsEmpty(s1.Range(&quot;B&quot; &amp; i)) Then Exit For End If If s1.Range(&quot;B&quot; &amp; i).Value &lt;&gt; s2.Range(&quot;B&quot; &amp; i).Value Then s1.Range(&quot;B&quot; &amp; i).Interior.Color = vbYellow End If Next i </code></pre>
[ { "answer_id": 74322573, "author": "TheDataScienceNinja", "author_id": 10929995, "author_profile": "https://Stackoverflow.com/users/10929995", "pm_score": 0, "selected": false, "text": "myArray = pandas.columns(df)\n" }, { "answer_id": 74322713, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": true, "text": "df.columns = df.columns.str.extract('(\\d+)', expand=False)\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17205679/" ]
74,322,588
<h3>Sample data:</h3> <pre class="lang-none prettyprint-override"><code>Apple iPhone 14 Samsung Galaxy S22 Xiaomi Redmi 9 John Doe </code></pre> <h3>Desired output:</h3> <pre class="lang-none prettyprint-override"><code>iPhone 14 Galaxy S22 Redmi 9 Doe </code></pre> <p>I'd like open a .txt file. How do I remove every first word from every line when file looks similar like there?</p> <p><img src="https://i.stack.imgur.com/Ikvsy.png" alt="" /></p> <p>On Notepad, I can use CTRL A &gt; Find and replace &gt; &quot;First_Name &quot; &gt; &quot;&quot; &gt; And I got a list of names It's simple when the file have only a few simple names that repeat etc. &quot;Apple iPhone 12&quot;, &quot;Apple iPhone 13&quot;, ...</p> <p>How do I do that in Python? It's possible? Each result must be one under the other \n - imo that's the easiest way to paste results into .csv file. Should I append content my .txt file to list and using slicing? Split .txt file?</p> <pre><code>f = open(&quot;text.txt&quot;, &quot;r&quot;) a = f.read().split() a1 = a[1:] print(a) print(a1) </code></pre>
[ { "answer_id": 74322573, "author": "TheDataScienceNinja", "author_id": 10929995, "author_profile": "https://Stackoverflow.com/users/10929995", "pm_score": 0, "selected": false, "text": "myArray = pandas.columns(df)\n" }, { "answer_id": 74322713, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": true, "text": "df.columns = df.columns.str.extract('(\\d+)', expand=False)\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20275480/" ]
74,322,591
<p>Here's code</p> <pre><code>const prompt = require('prompt-sync')({ sigInt: true}) /* It's generating a random number from 0 to 100. */ let wylosowanaLiczba = Math.random() * 100 /* It's converting the number to an integer. */ wylosowanaLiczba = wylosowanaLiczba.toFixed(0) /* It's asking the user to input a number from 0 to 100. */ let liczbaUzytkownika = prompt('Podaj liczbę od 0 do 100: ') /* Checking if the function `sprawdzacz` returns false, if it does, it calls the function again. */ if (sprawdzacz(wylosowanaLiczba, liczbaUzytkownika) == false) { sprawdzacz(wylosowanaLiczba, liczbaUzytkownika) } /** * It checks if the user's number is equal to the random number, if not, it checks if the user's number * is greater than the random number, if not, it checks if the user's number is less than the random * number. * @param wylosowanaLiczbaxx - the number that the computer generated * @param liczbaUzytkownikaxx - user's input * @returns the value of the last expression evaluated. */ function sprawdzacz(wylosowanaLiczbaxx, liczbaUzytkownikaxx) { /* It's checking if the random number is greater than the user's number. If it is, it prints out a message and asks the user to input a number again. */ if (wylosowanaLiczbaxx &gt; liczbaUzytkownikaxx) { console.log('\nWylosowana liczba jest większa niż twoja liczba!\n'); liczbaUzytkownikaxx = prompt('Podaj liczbę od 0 do 100: ') return false } /* It's checking if the random number is less than the user's number. If it is, it prints out a message and asks the user to input a number again. */ if (wylosowanaLiczbaxx &lt; liczbaUzytkownikaxx) { console.log('\nWylosowana liczba jest mniejsza niż twoja liczba!\n'); liczbaUzytkownikaxx = prompt('Podaj liczbę od 0 do 100: ') return false } /* It's checking if the random number is equal to the user's number. If it is, it prints out a message and returns true. */ if (wylosowanaLiczba == liczbaUzytkownika) { console.log('\n\nBRAWO, WYGRALES\n\n') return true } } </code></pre> <p>I was expecting working game, that gives you random numbers and you must guess a number. If it's more than you tried it will be console.log('\nWylosowana liczba jest większa niż twoja liczba!\n'), if less console.log('\nWylosowana liczba jest mniejsza niż twoja liczba!\n').</p>
[ { "answer_id": 74322573, "author": "TheDataScienceNinja", "author_id": 10929995, "author_profile": "https://Stackoverflow.com/users/10929995", "pm_score": 0, "selected": false, "text": "myArray = pandas.columns(df)\n" }, { "answer_id": 74322713, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": true, "text": "df.columns = df.columns.str.extract('(\\d+)', expand=False)\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15842662/" ]
74,322,614
<p>I have a pandas data frame <code>data</code> with several columns. One of these columns is <code>GEN</code>. This column contains german cities as strings. Some of these cities are in a bad format, meaning that they have values like <code>&quot;Frankfurt a.Main&quot;</code>. For every element in <code>data['GEN']</code> I would like to replace every expression of the form <code>&quot;\.[A-ZÄÖÜ]&quot;</code> (i.e. dot followed by upper case letter) by the corresponding expression <code>&quot;\.\b[A-ZÄÖÜ]&quot;</code>. For example</p> <ul> <li><code>&quot;Frankfurt a.Main&quot;</code> becomes <code>&quot;Frankfurt a. Main&quot;</code></li> <li><code>&quot;Frankfurt a.d.Oder&quot;</code> becomes <code>&quot;Frankfurt a.d. Oder&quot;</code> and so on.</li> </ul> <p>I am pretty sure that <code>pandas.Series.str.contains</code> and <code>pandas.Series.str.replace</code> are helpful here, but one of my problems is that I don't know how to put the replacement task in a form that can be used by the above functions.</p>
[ { "answer_id": 74322573, "author": "TheDataScienceNinja", "author_id": 10929995, "author_profile": "https://Stackoverflow.com/users/10929995", "pm_score": 0, "selected": false, "text": "myArray = pandas.columns(df)\n" }, { "answer_id": 74322713, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": true, "text": "df.columns = df.columns.str.extract('(\\d+)', expand=False)\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4471935/" ]
74,322,623
<p>I have a dataframe like this:</p> <pre><code>df name A B C D 0 name1 11 12 13 14 1 name2 21 22 23 24 </code></pre> <p>And there is this dictionary:</p> <pre><code>d = {'name1': {'1': {'0': 9, '1': 0, '2': 0}, '2': {'0': 14, '1': 8, '2': 10}, '3': {'0': 0, '1': 5, '2': 0}}, 'name2': {'1': {'0': 6, '1': 0, '2': 7}, '2': {'0': 8, '1': 9, '2': 8}, '3': {'0': 0, '1': 5, '2': 10}}, 'name3': {'1': {'0': 3, '1': 97, '2': 0}, '2': {'0': 36, '1': 50, '2': 1}, '3': {'0': 11, '1': 78, '2': 0}}} </code></pre> <p>I want to get a result like this:</p> <pre><code> name A B C D 1 2 3 0 name1 11 12 13 14 9 14 0 0 8 5 0 10 0 1 name2 21 22 23 24 6 8 0 0 9 5 7 8 10 </code></pre> <p>I tried to solve it myself. But my solution is pretty rough. Can you suggest a better solution? Here's what I did:</p> <pre><code>df_d = pd.DataFrame.from_dict({(i,j): d[i][j] for i in d.keys() for j in d[i].keys()}, orient='index') df_d.index.names = ['name','rating'] df_d= df_d.stack().unstack(level='rating') df_d.reset_index() df_result = pd.merge(df, df_d, how='left', on='prod_name') df_result = df_result.reset_index(drop=True).set_index(['name','A', 'B', 'C', 'D']) </code></pre>
[ { "answer_id": 74322968, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 2, "selected": false, "text": "df = df.merge(\n pd.DataFrame(d).T.reset_index().rename(columns={\"index\": \"name\"}), on=\"name\"\n).set_index([\"name\", \"A\", \"B\", \"C\", \"D\"])\ndf = df.apply(lambda x: [d.values() for d in x]).explode(df.columns.to_list())\n\nprint(df)\n" }, { "answer_id": 74323133, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": 3, "selected": true, "text": "df_d= pd.concat({k: pd.DataFrame(v) for k, v in d.items()}, axis=0, names = ['name'])\n\nout1= df.merge(df_d, on = 'name').set_index(['name', 'A','B','C','D'])\n\nprint(out1)\n\n 1 2 3\nname A B C D \nname1 11 12 13 14 9 14 0\n 14 0 8 5\n 14 0 10 0\nname2 21 22 23 24 6 8 0\n 24 0 9 5\n 24 7 8 10\n" }, { "answer_id": 74323146, "author": "Tranbi", "author_id": 13525512, "author_profile": "https://Stackoverflow.com/users/13525512", "pm_score": 1, "selected": false, "text": "d" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18048089/" ]
74,322,628
<p>I would like to use a parent function that creates two additional plot functions, and when I call the parent function, I would like both plots to be returned. Ideally, I would like the plots to be returned as two separate objects instead of using something like <code>par()</code> to combine the two plots into a single image.</p> <p>The code below only returns the second of the two plots.</p> <pre><code>test_fx &lt;- function() { # Define the first plot plot1_fx &lt;- function() { plot(x=c(1,2,3),y=c(3,4,5), type='l') abline(v=1.5, col=&quot;red&quot;, lwd=5) } # Define the second plot plot2_fx &lt;- function() { plot(x=c(1,2,3),y=c(5,4,3), type='l') abline(v=2.5, col=&quot;blue&quot;, lwd=5) } # Return the plots plot1_fx() plot2_fx() } # Call the main function test_fx() </code></pre>
[ { "answer_id": 74322855, "author": "M.Viking", "author_id": 10276092, "author_profile": "https://Stackoverflow.com/users/10276092", "pm_score": 2, "selected": false, "text": "return()" }, { "answer_id": 74322861, "author": "Rui Barradas", "author_id": 8245406, "author_profile": "https://Stackoverflow.com/users/8245406", "pm_score": 2, "selected": true, "text": "plot" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4716625/" ]
74,322,631
<p>I tried running my game on a html website, but it didn't work. can i use html or css or javascript to open and application or .exe</p> <p>i tried using iframe but it just shows me the parent directory [This is the image i receive] (<a href="https://i.stack.imgur.com/kUChj.png" rel="nofollow noreferrer">https://i.stack.imgur.com/kUChj.png</a>) (<a href="https://i.stack.imgur.com/kUChj.png" rel="nofollow noreferrer">https://i.stack.imgur.com/kUChj.png</a>) i also tried the anchor function in html it didnt work either</p>
[ { "answer_id": 74322865, "author": "loretoparisi", "author_id": 758836, "author_profile": "https://Stackoverflow.com/users/758836", "pm_score": 2, "selected": false, "text": "<py-script>" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20420993/" ]
74,322,632
<p>I want to start a celery process that always runs in the background. I want these running process to be able to track system resource (CPU, RAM, etc) usage of all other processes that will be started when a new task is needed to be executed in parallel. And then I want the tracking process to log the data to file at a regular interval.</p> <p>If the above implementation is possible, is it safe to use in production setup?</p> <p>I haven't tried them, but I have read about psutil and py-spy. But I am not sure if they can be used to track processes from another parallel process</p>
[ { "answer_id": 74322813, "author": "J_H", "author_id": 8431111, "author_profile": "https://Stackoverflow.com/users/8431111", "pm_score": 1, "selected": false, "text": "$ ps axup ${PID}" }, { "answer_id": 74324150, "author": "chrslg", "author_id": 20037042, "author_profile": "https://Stackoverflow.com/users/20037042", "pm_score": 1, "selected": true, "text": "\nimport psutil\n\np=psutil.Process(121000) # a pid you want to track. Father, son, brother, unrelated. It doesn't matter\np.cpu_percent()\n# 1.4 my process use 1.4% of a cpu\np.cpu_times()\n# pcputimes(user=42.4, system=0.01, children_user=0.0, children_system=0.0, iowait=0.01)\n# Or detail\np.cpu_times().user, p.cpu_times().system\n# Time spend so far, in sec\n\np.memory_percent()\n#0.14 (0,14% memory used)\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8862275/" ]
74,322,635
<p>I have a dataframe df with column time as a string.</p> <p><a href="https://i.stack.imgur.com/oNW5e.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oNW5e.png" alt="enter image description here" /></a></p> <p>I want to get a count of these entries grouped hourly.</p> <p>for example how many time entries are there between every hour from 00:00:00 to 23:59:59.</p>
[ { "answer_id": 74322813, "author": "J_H", "author_id": 8431111, "author_profile": "https://Stackoverflow.com/users/8431111", "pm_score": 1, "selected": false, "text": "$ ps axup ${PID}" }, { "answer_id": 74324150, "author": "chrslg", "author_id": 20037042, "author_profile": "https://Stackoverflow.com/users/20037042", "pm_score": 1, "selected": true, "text": "\nimport psutil\n\np=psutil.Process(121000) # a pid you want to track. Father, son, brother, unrelated. It doesn't matter\np.cpu_percent()\n# 1.4 my process use 1.4% of a cpu\np.cpu_times()\n# pcputimes(user=42.4, system=0.01, children_user=0.0, children_system=0.0, iowait=0.01)\n# Or detail\np.cpu_times().user, p.cpu_times().system\n# Time spend so far, in sec\n\np.memory_percent()\n#0.14 (0,14% memory used)\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14915169/" ]
74,322,676
<p>I would like to simulate typing of huge text. I've tried to use pyautogui to do that, but I't didn't worked properly since the computer was not detecting the keys being pressed:</p> <pre><code>pyautogui.typewrite('I love python! It is such an amazing language.') </code></pre> <p>I couldn't think of another way to do that than using pynput.keyboard library, but as I have a huge text, that would not be a viable option. I don't know if there is a way to simulate the keys other than create a line for each letter.</p> <pre><code>keyboard = Controller() keyboard.press('I') keyboard.release('I') keyboard.press('L') keyboard.release('L') keyboard.press('O') keyboard.release('O') keyboard.press('V') keyboard.release('V') </code></pre> <p>Is there a way to simulate keys being pressed to write a text without having to create a single line for each letter that the script would have to type?</p>
[ { "answer_id": 74322717, "author": "The Myth", "author_id": 15042008, "author_profile": "https://Stackoverflow.com/users/15042008", "pm_score": 2, "selected": false, "text": "keyboard" }, { "answer_id": 74331385, "author": "Claudio", "author_id": 7711283, "author_profile": "https://Stackoverflow.com/users/7711283", "pm_score": 2, "selected": true, "text": "import pynput\nimport random \nimport threading\nimport time\n\ntxt = \"pynput is typing like a human\"\n#txt = \"abc\" \n\nclass Sim_keyb_typing(threading.Thread):\n def __init__(self, text, \n strt_delay=1.5, \n dct_delays={('a','i'):0.15}, \n delayrange=(0.1, 0.3) ):\n threading.Thread.__init__(self)\n\n self.text = text\n self.strt_delay = strt_delay\n self.last_char = \" \"\n self.dct_delays = dct_delays\n self.delayrange = delayrange\n\n self.ppkbC = pynput.keyboard.Controller()\n\n def run(self):\n time.sleep(self.strt_delay)\n for char in self.text:\n delay = self.dct_delays.get( \n (self.last_char, char), random.uniform(*self.delayrange) )\n time.sleep(delay)\n self.ppkbC.type(char)\n self.last_char = char\n\n# Let's wait 1.5 seconds and then start typing: \nskt = Sim_keyb_typing(txt)\nskt.start()\n# Wait for Sim_keyb_typing(txt) to finish\n#skt.join()\n\n# ======================================================================\nimport tkinter\nimport time\nimport threading\nimport random\nimport string\n\nclass simpleTypeSpeedGUI: # creates tkinter GUI mainloop\n\n def __init__(self, txt):\n self.root = tkinter.Tk()\n self.root.title(\"Type Speed Test (starts on first keypress)\")\n self.root.geometry(\"1600x400\")\n\n self.text_lines = txt.split(\"\\n\")\n self.text_line = random.choice(self.text_lines)\n self.len_text_line = len(self.text_line)\n\n # Label showing text to type:\n self.sample_label = tkinter.Label(self.root, text=self.text_line, font=(\"Helvetica\", 14))\n self.sample_label.grid( row=0, column=1, columnspan=2, padx=15, pady=15, sticky='w')\n\n # Text box receiving typing input: \n self.input_textbox = tkinter.Entry(self.root, width=120, font=(\"Helvetica\", 14))\n self.input_textbox.grid(row=1, column=1, columnspan=2, padx=15, pady=15)\n # Registering callback function for text box keyboard input keypress\n self.input_textbox.bind(\"<KeyRelease>\", self.on_key_up) \n # The reason for KeyRelease is to have updated widget content in the callback function\n self.input_textbox.focus()\n\n # Label showing typing speed: \n self.speed_label = tkinter.Label(self.root, text=\"Typing speed: \\n---- \\n---- \\n---- \\n---- \", font=(\"Helvetica\", 12))\n self.speed_label.grid(row=2, column=1, columnspan=2, padx=5, pady=10)\n\n # Button for restart/reset of typing: \n self.reset_button = tkinter.Button(self.root, text=\"Reset\", command=self.reset, font=(\"Helvetica\", 18))\n self.reset_button.grid(row=3, column=1, columnspan=2, padx=15, pady=15)\n\n # Standard value for average number of characters in a word \n self.std_char_per_word = 5\n # used to calculate words per minute from typing speed in chars/min\n\n # initialisation of code flow control values: \n self.start_time = None\n self.end_time = None\n self.printable = string.printable[:-5]\n\n self.root.mainloop()\n\n def on_key_up(self, event):\n # processing on key release because on key press results\n # in the widget content are not yet updated with the key char. \n if event.keycode == 9: # pressed Escape => EXIT\n print(\"\\nEscape-EXIT\")\n self.root.destroy()\n return # <- required because root.destroy() doesn't block \n # execution of further code which then runs into \n # trouble as .destroy() makes widgets not available\n\n if self.start_time is None:\n self.start_time = time.perf_counter()\n\n input_textbox = self.input_textbox.get()\n \n # print(f'{event.keycode=} => \"{event.char=}\" ')\n\n if input_textbox == self.text_line:\n self.running = False\n self.input_textbox.config(fg=\"green\")\n self.end_time = time.perf_counter()\n else: \n if self.text_line.startswith(input_textbox):\n self.input_textbox.config(fg=\"black\")\n else:\n self.input_textbox.config(fg=\"red\")\n\n self.show_typespeed()\n\n def show_typespeed(self):\n curr_time = time.perf_counter()\n \n if self.start_time is not None and self.end_time is not None: \n time_diff = self.end_time - self.start_time\n elif self.start_time is not None and self.end_time is None: # and self.end_time is None \n time_diff = curr_time - self.start_time\n elif self.start_time is None and self.end_time is None: \n self.speed_label.config(text=\"Speed: \\n---- CPS\\n---- CPM\\n---- WPS\\n---- WPS\")\n return\n cps = self.len_text_line / time_diff\n cpm = cps * 60.0\n wps = cps / self.std_char_per_word\n wpm = wps * 60.0\n self.speed_label.config(text=f\"Speed: \\n{cps:5.2f} CPS\\n{cpm:5.2f} CPM\\n{wps:5.2f} WPS\\n{wpm:5.2f} WPM\")\n\n def reset(self):\n self.start_time = None\n self.end_time = None\n self.text_line = random.choice(self.text_lines)\n self.len_text_line = len(self.text_line)\n self.sample_label.config(text=self.text_line)\n self.input_textbox.delete(0, tkinter.END)\n self.show_typespeed()\n\nsTSG = simpleTypeSpeedGUI(txt)\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16663325/" ]
74,322,683
<p>I have the following list of dictionaries and I'm trying to come up with a single connected sentence based on whether the fact that the dictionary of the child sentences have the &quot;ref&quot; attribute connecting it to the father sentence.</p> <pre><code>clause_list = [ {&quot;id&quot;: &quot;T1&quot;, &quot;text&quot;: &quot;hi&quot;}, {&quot;id&quot;: &quot;T2&quot;, &quot;text&quot;: &quot;I'm&quot;, &quot;ref&quot;: &quot;T1&quot;}, {&quot;id&quot;: &quot;T3&quot;, &quot;text&quot;: &quot;Simone&quot;, &quot;ref&quot;: &quot;T2&quot;}, ] </code></pre> <p>Expected output is &quot;hi I'm Simone&quot; but avoiding sentences like &quot;hi I'm&quot; or &quot;I'm Simone&quot;</p> <p>What I tried so far is the following, but no matter how I flip it, the undesired sentences always get printed.</p> <pre><code>for c in clause_list: for child in clause_list: try: if c[&quot;id&quot;] == child[&quot;ref&quot;] and &quot;ref&quot; not in c.keys(): print(c[&quot;text&quot;], child[&quot;text&quot;]) elif c[&quot;id&quot;] == child[&quot;ref&quot;] and &quot;ref&quot; in c.keys(): for father in clause_list: if father[&quot;id&quot;] == c[&quot;ref&quot;] and &quot;ref&quot; not in father.keys(): print(father[&quot;text&quot;], c[&quot;text&quot;], child[&quot;text&quot;]) except KeyError: pass </code></pre>
[ { "answer_id": 74322829, "author": "Zach J.", "author_id": 20276330, "author_profile": "https://Stackoverflow.com/users/20276330", "pm_score": 0, "selected": false, "text": "clause_list = {\n # ID's are the keys\n 'T1':{'text':\"hi \", 'child':'T2','parent':True}, \n 'T2':{'text':\"I'm \", 'child':'T3'},\n 'T3':{'text':\"Simone\", 'child':None},\n}\n" }, { "answer_id": 74322835, "author": "Pablo Estevez", "author_id": 18203813, "author_profile": "https://Stackoverflow.com/users/18203813", "pm_score": 2, "selected": true, "text": "clause_list = [\n {\"id\": \"T1\", \"text\": \"hi\"},\n {\"id\": \"T2\", \"text\": \"I'm\", \"ref\": \"T1\"},\n {\"id\": \"T3\", \"text\": \"Simone\", \"ref\": \"T2\"},\n]\nclass Clause:\n def __init__(self, id, text, ref:None):\n self.id = id\n self.text = text\n self.ref = ref\n \n def search_ref(self, Clauses, text=''):\n parcialText = text + ' ' + self.text\n for clause in Clauses:\n if clause.ref == self.id:\n return clause.search_ref(Clauses, parcialText)\n print(parcialText)\n \nClauses = [Clause(id=c['id'], text=c['text'], ref=c.get('ref')) for c in clause_list]\n\nfor c in Clauses:\n if c.ref is None:\n c.search_ref(Clauses)\n" }, { "answer_id": 74322843, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 0, "selected": false, "text": "clause_list = [\n {\"id\": \"T1\", \"text\": \"hi\"},\n {\"id\": \"T2\", \"text\": \"I'm\", \"ref\": \"T1\"},\n {\"id\": \"T3\", \"text\": \"Simone\", \"ref\": \"T2\"},\n]\n\n\ninv_dict = {d.get(\"ref\", \"\"): (d[\"id\"], d[\"text\"]) for d in clause_list}\n\n\ndef get_sentence(inv_dict, key=\"\"):\n if key in inv_dict:\n id_, text = inv_dict[key]\n return [text] + get_sentence(inv_dict, id_)\n return []\n\n\nprint(\" \".join(get_sentence(inv_dict)))\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14442152/" ]
74,322,730
<p>Can someone help me with checkboxes and image</p> <p>i need the do a college homework with java</p> <p>i want to create logic gates with gui</p> <p>example</p> <p>and gate</p> <p>2 checkbox</p> <p>and one image</p> <p>if both checked image turn green</p> <p>if 1 or 0 checked image turn red Can Someone help me to do that</p> <pre><code> import java.awt.event.*; import java.awt.*; import javax.swing.\*; class solve extends JFrame { // frame static JFrame f; static JLabel l; Label label; // main class public static void main(String[] args) { // create a new frame f = new JFrame(&quot;frame&quot;); // set layout of frame f.setLayout(new FlowLayout()); // create checkbox JCheckBox c1 = new JCheckBox(&quot;checkbox 1&quot;); JCheckBox c2 = new JCheckBox(&quot;checkbox 2&quot;); // create a new panel JPanel p = new JPanel(); // add checkbox to panel p.add(c1); p.add(c2); // add panel to frame f.add(p); // set the size of frame f.setSize(300, 300); f.show(); } } </code></pre> <p>i dont know how to check checkboxes checked and place image they dont teach me on college but they give me a project i cant find a docs or something to do</p>
[ { "answer_id": 74322829, "author": "Zach J.", "author_id": 20276330, "author_profile": "https://Stackoverflow.com/users/20276330", "pm_score": 0, "selected": false, "text": "clause_list = {\n # ID's are the keys\n 'T1':{'text':\"hi \", 'child':'T2','parent':True}, \n 'T2':{'text':\"I'm \", 'child':'T3'},\n 'T3':{'text':\"Simone\", 'child':None},\n}\n" }, { "answer_id": 74322835, "author": "Pablo Estevez", "author_id": 18203813, "author_profile": "https://Stackoverflow.com/users/18203813", "pm_score": 2, "selected": true, "text": "clause_list = [\n {\"id\": \"T1\", \"text\": \"hi\"},\n {\"id\": \"T2\", \"text\": \"I'm\", \"ref\": \"T1\"},\n {\"id\": \"T3\", \"text\": \"Simone\", \"ref\": \"T2\"},\n]\nclass Clause:\n def __init__(self, id, text, ref:None):\n self.id = id\n self.text = text\n self.ref = ref\n \n def search_ref(self, Clauses, text=''):\n parcialText = text + ' ' + self.text\n for clause in Clauses:\n if clause.ref == self.id:\n return clause.search_ref(Clauses, parcialText)\n print(parcialText)\n \nClauses = [Clause(id=c['id'], text=c['text'], ref=c.get('ref')) for c in clause_list]\n\nfor c in Clauses:\n if c.ref is None:\n c.search_ref(Clauses)\n" }, { "answer_id": 74322843, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 0, "selected": false, "text": "clause_list = [\n {\"id\": \"T1\", \"text\": \"hi\"},\n {\"id\": \"T2\", \"text\": \"I'm\", \"ref\": \"T1\"},\n {\"id\": \"T3\", \"text\": \"Simone\", \"ref\": \"T2\"},\n]\n\n\ninv_dict = {d.get(\"ref\", \"\"): (d[\"id\"], d[\"text\"]) for d in clause_list}\n\n\ndef get_sentence(inv_dict, key=\"\"):\n if key in inv_dict:\n id_, text = inv_dict[key]\n return [text] + get_sentence(inv_dict, id_)\n return []\n\n\nprint(\" \".join(get_sentence(inv_dict)))\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19323597/" ]
74,322,745
<p>I am trying to position a div over another by using <code>position: relative;</code> &amp; <code>position: absolute;</code>. I have made use of this successfully previously in the project, however it isn't given the desired outcome/working on the second use of it. All it is doing is displaying the second div under the first.</p> <p>HTML</p> <pre><code>&lt;header&gt; &lt;img class=&quot;header-img&quot; src=&quot;https://i.pinimg.com/222x/ec/c6/f2/ecc6f20889bba2976601a3abb029183c.jpg&quot;&gt; &lt;div class=&quot;header-text left&quot;&gt;&amp;emsp;ToKa&amp;emsp;&amp;emsp; &amp;emsp;Fitness&lt;/div&gt; &lt;/header&gt; &lt;div&gt; &lt;div class=&quot;offer&quot;&gt;&lt;/div&gt; &lt;div class=&quot;sign-in&quot;&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS</p> <pre><code>header { width: 100%; height: 120px; position: relative; border: 2px black solid; } img.header-img { width: 122px; height: 122px; position: absolute; margin-left: auto; margin-right: auto; left: 0; right: 0; text-align: center; } div.header-text { width: 100%; position: absolute; padding-top: 42px; font-family: articulat-cf, sans-serif; font-style: normal; font-weight: 700; font-size: 30px; text-align: center; } div.offer { width: 100%; height:30px; position: relative; border: 2px green solid; } div.sign-in { width: 120px; height: 30px; position: absolute; top: 132px; right: 4px; border:2px red dashed; } </code></pre> <p>I am aiming for the smaller red div to go on top of the green div above it to the far right. I have tried using top and right to assist with positioning it but to no obvious effect on the program.</p>
[ { "answer_id": 74322933, "author": "kimia shahbaghi", "author_id": 20275256, "author_profile": "https://Stackoverflow.com/users/20275256", "pm_score": 2, "selected": true, "text": " <header>\n <img\n class=\"header-img\"\n src=\"https://i.pinimg.com/222x/ec/c6/f2/ecc6f20889bba2976601a3abb029183c.jpg\"\n />\n <div class=\"header-text left\">&emsp;ToKa&emsp;&emsp; &emsp;Fitness</div>\n </header>\n <div>\n <div class=\"offer\"><div class=\"sign-in\"></div></div>\n </div>\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19619999/" ]
74,322,756
<p>I'm trying to get a single parameter from csv file loaded into python. I created rows and appended into row variable File is saved like Column : Fruit, Amount, Price Apple, 30, 0.5 <a href="https://i.stack.imgur.com/fhBaz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fhBaz.png" alt="enter image description here" /></a></p> <pre><code>rows = [] with open(&quot;practice_file.csv&quot;, 'r') as file: csvreader = csv.reader(file) header = next(csvreader) for row in csvreader: rows.append(row) print(rows[1]) </code></pre> <p>If I do this I get an output, [Apple, 30, 0.5] How can I get an output which only pulls &quot;Apple&quot;?</p> <p>Thanks in advance</p> <p>I couldn't get anything to solved.</p>
[ { "answer_id": 74322933, "author": "kimia shahbaghi", "author_id": 20275256, "author_profile": "https://Stackoverflow.com/users/20275256", "pm_score": 2, "selected": true, "text": " <header>\n <img\n class=\"header-img\"\n src=\"https://i.pinimg.com/222x/ec/c6/f2/ecc6f20889bba2976601a3abb029183c.jpg\"\n />\n <div class=\"header-text left\">&emsp;ToKa&emsp;&emsp; &emsp;Fitness</div>\n </header>\n <div>\n <div class=\"offer\"><div class=\"sign-in\"></div></div>\n </div>\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15186937/" ]
74,322,757
<p>I am scraping some data from GitHub. The RESTful URL to this particular PR shows that it has a <code>merge_commit_sha</code> value: <a href="https://api.github.com/repos/ansible/ansible/pulls/15088" rel="nofollow noreferrer">https://api.github.com/repos/ansible/ansible/pulls/15088</a></p> <p>However, when I try to get the same PR using GitHub GraphQL API, it shows it does not have any <code>mergedCommit</code> value.</p> <pre><code> resource( url: &quot;https://github.com/ansible/ansible/pull/15088&quot; ) { ...on PullRequest { id number title merged mergeCommit { message } } } </code></pre> <p>For context, the PR of interest is actually merged and should have a merged-commit value. I am looking for an explanation of the difference between these two APIs.</p>
[ { "answer_id": 74322933, "author": "kimia shahbaghi", "author_id": 20275256, "author_profile": "https://Stackoverflow.com/users/20275256", "pm_score": 2, "selected": true, "text": " <header>\n <img\n class=\"header-img\"\n src=\"https://i.pinimg.com/222x/ec/c6/f2/ecc6f20889bba2976601a3abb029183c.jpg\"\n />\n <div class=\"header-text left\">&emsp;ToKa&emsp;&emsp; &emsp;Fitness</div>\n </header>\n <div>\n <div class=\"offer\"><div class=\"sign-in\"></div></div>\n </div>\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5420257/" ]
74,322,827
<p>I am trying to convert a date column (ie. 2012-10-02) to the first day of the year with time (ie. 2012-01-01T00:00:00) in sql.</p> <p>Is there a way to do so in the SELECT query?</p>
[ { "answer_id": 74322866, "author": "Guss", "author_id": 53538, "author_profile": "https://Stackoverflow.com/users/53538", "pm_score": 0, "selected": false, "text": "YEAR()" }, { "answer_id": 74323007, "author": "Mikhail Berlyant", "author_id": 5221944, "author_profile": "https://Stackoverflow.com/users/5221944", "pm_score": 2, "selected": true, "text": "select timestamp_trunc('2012-10-02', year) \n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20421146/" ]
74,322,839
<p>Is there a way to specify the connection method when using a proxy? I'm using the below code which sends an HTTP CONNECT. That is not supported by my load balancer. A GET request would terminate the TLS connection between the proxy and the website. The CONNECT method creates a TLS connection end to end between the end user and website. Essentially I need to inspect the traffic at the proxy.</p> <pre><code>HttpHost proxy = new HttpHost(proxyHost, proxyPort); HttpClientBuilder clientBuilder = HttpClientBuilder.create(); clientBuilder .setConnectionManager(connectionManager) .setProxy(proxy) .setDefaultRequestConfig(config); </code></pre> <p>Below is what the connection looks like:</p> <pre><code>Hypertext Transfer Protocol CONNECT xyz.com:443 HTTP/1.1\r\n Host: xyz.com\r\n User-Agent: Apache-HttpClient/4.5.13 (Java/19.0.1)\r\n \r\n </code></pre>
[ { "answer_id": 74322866, "author": "Guss", "author_id": 53538, "author_profile": "https://Stackoverflow.com/users/53538", "pm_score": 0, "selected": false, "text": "YEAR()" }, { "answer_id": 74323007, "author": "Mikhail Berlyant", "author_id": 5221944, "author_profile": "https://Stackoverflow.com/users/5221944", "pm_score": 2, "selected": true, "text": "select timestamp_trunc('2012-10-02', year) \n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13676224/" ]
74,322,857
<p>I am using pandas to convert dict to html table, but not able to figure out, how to convert row to column in this case?</p> <pre><code>import pandas as pd c = {'result': 'FAIL', &quot;LinkA&quot;: &quot;https:// example.com/dwdewdbeuwwuvdwudwufdqwdqqdqdqdqwedeuq.txt&quot;, &quot;NDT&quot;: &quot;https://example.com/dgwuydweufdwuefgwfwfdwefef.txt&quot;, &quot;KKT&quot;: &quot;https:// example.com/fewnewvbbcuwecvwxvwwecewc.txt&quot;} c = {k:[v] for k,v in c.items()} df = pd.DataFrame(c) df.to_html(&quot;/tmp/a1.html&quot;) </code></pre> <p>Actual Output: <a href="https://i.stack.imgur.com/BBUuP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BBUuP.png" alt="Actual Output" /></a></p> <p>Required Output:</p> <p><a href="https://i.stack.imgur.com/SlJ6g.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SlJ6g.png" alt="Expected Output" /></a></p>
[ { "answer_id": 74322976, "author": "Ian Thompson", "author_id": 6509519, "author_profile": "https://Stackoverflow.com/users/6509519", "pm_score": 2, "selected": true, "text": "df" }, { "answer_id": 74323095, "author": "Golden Lion", "author_id": 4001177, "author_profile": "https://Stackoverflow.com/users/4001177", "pm_score": 0, "selected": false, "text": "data=\"\"\"result,fail\nLinkA,1\nNDT,2\nKKT,3\nLinkA,4\nNDT,5\nKKT,6\n\"\"\"\n\ndf = pd.read_csv(StringIO(data), sep=\",\")\ndf.columns=columns=[\"result\",\"fail\"]\n#print(df.T)\ndf = df.pivot(index=\"result\", columns=\"fail\", values=\"fail\")\nprint(df.T)\n" }, { "answer_id": 74323231, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 0, "selected": false, "text": "pd.Series(c).reset_index().to_html()\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1025140/" ]
74,322,860
<p>I currently have a project that has grown quite a bit and I wonder if it is possible to break it down into small elements without the need to destroy everything that has been deployed in the cloud, I have worked with modules for lambda, event bridge, api gateway for example.</p> <p>im using terraform Terraform v1.2.8 on darwin_amd64</p> <p>ps: with break down into small elements i mean several new terraform projects derived from the monolith, the main reason is to automate the build process into a pipeline by components approach.</p> <p>Thanks.</p>
[ { "answer_id": 74322936, "author": "YCF_L", "author_id": 5558072, "author_profile": "https://Stackoverflow.com/users/5558072", "pm_score": 0, "selected": false, "text": "terraform.tfstate" }, { "answer_id": 74323170, "author": "malcojus", "author_id": 3486211, "author_profile": "https://Stackoverflow.com/users/3486211", "pm_score": 1, "selected": false, "text": "moved {\n from = module.security_group.aws_security_group.sg_8080\n to = module.web_security_group.aws_security_group.this[0]\n}\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2152241/" ]
74,322,864
<p>In the process of refactoring some legacy code at work and part of it is to convert an instance of <code>List&lt;Action&gt;</code> to <code>List&lt;Func&lt;Task&gt;&gt;</code>. Elsewhere in the codebase, there are several instances of something along the lines of this:</p> <pre><code>entity.Tasks.Add(() =&gt; { _service.Process(operation) } </code></pre> <p>The above would work fine when the Tasks property was <code>List&lt;Action&gt;</code>, but gives errors when turned into <code>List&lt;Func&lt;Task&gt;&gt;</code> with no obvious way to fix it.</p> <p>I know next to nothing about Func, Task, Action, asynchronous/synchronous programming, particularly in C#. Any help provided is immensely appreciated or even just a referral to information where I could find the information needed to solve this myself.</p>
[ { "answer_id": 74323164, "author": "Metro Smurf", "author_id": 9664, "author_profile": "https://Stackoverflow.com/users/9664", "pm_score": 0, "selected": false, "text": "List<Action>" }, { "answer_id": 74323813, "author": "Carlosoj", "author_id": 2708030, "author_profile": "https://Stackoverflow.com/users/2708030", "pm_score": 2, "selected": true, "text": "entity.Tasks.Add(() => Task.Run(_service.Process(operation)));\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9647366/" ]
74,322,878
<p>Practicing some regex. Trying to only get <code>Regular</code>, <code>Expressions,</code> and <code>abbreviated</code> from the below data</p> <pre><code>Regular Expressions, abbreviated as Regex or Regexp, are a string of characters created within the framework of Regex syntax rules. </code></pre> <p>With <code>(\w+\S?)</code>, I get all words including a nonwhitespace character if present.</p> <p>How would I get just <code>Regular</code>, <code>Expressions,</code> , and <code>abbreviated</code> ?</p> <p><strong>Edit:</strong></p> <p>To clarify, I'm looking for <code>Regex</code> <code>Expressions,</code> <code>abbreviated</code> separately without spaces</p> <p>not <code>Regex Expressions, abbreviated</code> (spaces included here)</p>
[ { "answer_id": 74323164, "author": "Metro Smurf", "author_id": 9664, "author_profile": "https://Stackoverflow.com/users/9664", "pm_score": 0, "selected": false, "text": "List<Action>" }, { "answer_id": 74323813, "author": "Carlosoj", "author_id": 2708030, "author_profile": "https://Stackoverflow.com/users/2708030", "pm_score": 2, "selected": true, "text": "entity.Tasks.Add(() => Task.Run(_service.Process(operation)));\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19132706/" ]
74,322,890
<p>I have to add a JavaScript function on a button click inside a plugin, i've tried but every time i update the plugin the function get removed how can i add permanently the function?</p>
[ { "answer_id": 74324756, "author": "zillionera_dev", "author_id": 15306153, "author_profile": "https://Stackoverflow.com/users/15306153", "pm_score": 0, "selected": false, "text": "add_filter('site_transient_update_plugins', 'remove_update_notification');\nfunction remove_update_notification($value) {\n unset($value->response[ plugin_basename(__FILE__) ]);\n return $value;\n} \n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20044335/" ]
74,322,894
<p>I have a set which contains objects which I have the <code>__eq__</code> and <code>__hash__</code> functions defined for.</p> <p>I would like to be able to check if an object with the same hash is in the set and if it is in the set to return the object from the set as I need the reference to the object.</p> <pre><code>class SetObject(): def __init__( self, a: int, b: int, c: int ): self.a = a self.b = b self.c = c def __repr__(self): return f&quot;SetObject ({self.a} {self.b} {self.c}) (id: {id(self)}&quot; def __eq__(self, other): return isinstance(other, SetObject) \ and self.__hash__() == other.__hash__() def __hash__(self): # Hash only depends on a, b return hash( (self.a,self.b) ) x = SetObject(1,2,3) y = SetObject(4,5,6) object_set = set([x,y]) print(f&quot;{object_set=}&quot;) z = SetObject(1,2,7) print(f&quot;{z=}&quot;) if z in object_set: print(&quot;Is in set&quot;) # Get the object in set which is equal to z for element in object_set: if element == z: print(element) z = element print(f&quot;{z=}&quot;) </code></pre>
[ { "answer_id": 74323018, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 4, "selected": true, "text": "x = SetObject(1,2,3)\ny = SetObject(4,5,6)\n\nobject_set = dict([(x, x),(y, y)])\n\nprint(f\"{object_set=}\")\n\nz = SetObject(1,2,7)\nprint(f\"{z=}\")\nif z in object_set:\n print(\"Is in set\")\n z = object_set[z]\n\nprint(f\"{z=}\")\n" }, { "answer_id": 74365925, "author": "jsbueno", "author_id": 108205, "author_profile": "https://Stackoverflow.com/users/108205", "pm_score": 2, "selected": false, "text": "def getinstance(set_, member):\n set2 = set_ - set((member,))\n return (set_ - set2).pop()\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5691573/" ]
74,322,931
<p>Looks like this:</p> <p>A | B | C True | databasename.abc.flag | ?? IF(AND(A1&quot;True&quot;,B1=&quot;flag&quot;),&quot;Success&quot;)</p>
[ { "answer_id": 74323018, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 4, "selected": true, "text": "x = SetObject(1,2,3)\ny = SetObject(4,5,6)\n\nobject_set = dict([(x, x),(y, y)])\n\nprint(f\"{object_set=}\")\n\nz = SetObject(1,2,7)\nprint(f\"{z=}\")\nif z in object_set:\n print(\"Is in set\")\n z = object_set[z]\n\nprint(f\"{z=}\")\n" }, { "answer_id": 74365925, "author": "jsbueno", "author_id": 108205, "author_profile": "https://Stackoverflow.com/users/108205", "pm_score": 2, "selected": false, "text": "def getinstance(set_, member):\n set2 = set_ - set((member,))\n return (set_ - set2).pop()\n" } ]
2022/11/04
[ "https://Stackoverflow.com/questions/74322931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15700014/" ]