qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,633,720
<p>With this script I am trying to parse the content from my Gmail to Google Spreadsheet and it works well with Google Apps Script.</p> <p>The problem is that in my mail there are two identical fields called &quot;Indirizzo mail:&quot; that I need to be parsed, but I would to parse only the second.</p> <p>How could I ignore the first one into the body of the mail?</p> <p>--- Mail Body Example:</p> <p>Indirizzo mail: bad@test.it <br>Phone: 00000000 <br>Website: <a href="http://www.test.it" rel="nofollow noreferrer">www.test.it</a></p> <hr /> <p>Lorem Ipsum</p> <p>Cognome: XXX <br>Nome: XXX <br>Codice fiscale: XXX <br><strong>Indirizzo mail: good@test.it</strong></p> <hr /> <pre><code>function parseEmailMessages(start) { start = start || 0; var label = GmailApp.getUserLabelByName(&quot;testparser&quot;); var threads = label.getThreads(); var sheet = SpreadsheetApp.getActiveSheet(); for (var i = 0; i &lt; threads.length; i++) { var tmp, message = threads[i].getMessages()[0], content = message.getPlainBody(); if (content) { tmp = content.match(/Cognome:\s*([A-Za-z0-9!&quot;?`?|õüö’çëÅíšÃÉÁÇÃáéñãóú#&amp;;()-,'@./\s\-]+)(\r?\n)/); var Cognome = (tmp &amp;&amp; tmp[1]) ? tmp[1].trim() : 'Null'; tmp = content.match(/Nome:\s*([A-Za-z0-9!&quot;?`?|õüö’çëÅíšÃÉÁÇÃáéñãóú#&amp;;()-,'@./\s\-]+)(\r?\n)/); var Nome = (tmp &amp;&amp; tmp[1]) ? tmp[1].trim() : 'Null'; tmp = content.match(/Codice fiscale:\s*([A-Za-z0-9!&quot;?`?|õüö’çëÅíšÃÉÁÇÃáéñãóú#&amp;;()-,'@./\s\-]+)(\r?\n)/); var CF = (tmp &amp;&amp; tmp[1]) ? tmp[1].trim() : 'Null'; tmp = content.match(/Indirizzo mail:\s*([A-Za-z0-9!&quot;?`?|õüö’çëÅíšÃÉÁÇÃáéñãóú#&amp;;()-,'@./\s\-]+)(\r?\n)/); var Mail = (tmp &amp;&amp; tmp[1]) ? tmp[1].trim() : 'Null'; sheet.appendRow([Cognome,Nome,CF,Mail]); } // End if } // End for loop } </code></pre>
[ { "answer_id": 74634186, "author": "Chris", "author_id": 2199001, "author_profile": "https://Stackoverflow.com/users/2199001", "pm_score": 0, "selected": false, "text": "@Composable\nfun AlertDialogSample() {\n MaterialTheme {\n Column {\n val openDialog = remember { mutableStateOf(false) }\n\n Button(onClick = {\n openDialog.value = true\n }) {\n Text(\"Click me\")\n }\n\n if (openDialog.value) {\n\n AlertDialog(\n onDismissRequest = {\n // Dismiss the dialog when the user clicks outside the dialog or on the back\n // button. If you want to disable that functionality, simply use an empty\n // onCloseRequest.\n openDialog.value = false\n },\n title = {\n Text(text = \"Dialog Title\")\n },\n text = {\n Text(\"Here is a text \")\n },\n confirmButton = {\n Button(\n modifier = Modifier\n .fillMaxWidth(0.75f)\n .padding(start = 12.dp, end = 12.dp, bottom = 8.dp),\n onClick = {\n openDialog.value = false\n }) {\n Text(\"This is the Confirm Button\")\n }\n },\n dismissButton = {\n Button(\n modifier = Modifier\n .fillMaxWidth(0.75f)\n .padding(start = 12.dp, end = 12.dp, bottom = 8.dp),\n onClick = {\n openDialog.value = false\n }) {\n Text(\"This is the dismiss Button\")\n }\n }\n )\n }\n }\n\n }\n}\n" }, { "answer_id": 74636555, "author": "z.y", "author_id": 19023745, "author_profile": "https://Stackoverflow.com/users/19023745", "pm_score": 3, "selected": true, "text": "AlertDialog AlertDialog(\n modifier = Modifier.fillMaxWidth(),\n ...\n AlertDialog(\n modifier = Modifier.width(150.dp),\n ...\n AlertDialog Button recomposition" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14680755/" ]
74,633,742
<p>I am working with this code:</p> <pre><code>test_list = ['small_cat', 'big_dog', 'turtle'] if 'dog' not in test_list: output = 'Good' else: output = 'Bad' print (Output) </code></pre> <p>Because 'dog' is not in the list, 'output' will come back with a response of 'Good'. However, I am looking for 'output' to return 'Bad' because the word 'dog' is part of an item in the list. How would I go about doing this?</p>
[ { "answer_id": 74633767, "author": "Tom Ron", "author_id": 1481986, "author_profile": "https://Stackoverflow.com/users/1481986", "pm_score": 3, "selected": true, "text": "test_list output = 'Good'\nfor test_word in test_list:\n if 'dog' in test_word:\n output = 'Bad'\n break\n\nprint(output)\n" }, { "answer_id": 74633804, "author": "César Rodrigues", "author_id": 2359882, "author_profile": "https://Stackoverflow.com/users/2359882", "pm_score": 0, "selected": false, "text": "output = 'Good'\nfor item in test_list:\n if 'dog' in item:\n output = 'Bad'\nprint(output)\n" }, { "answer_id": 74633815, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 0, "selected": false, "text": "any all if any('dog' in w for w in test_list):\n ...\nelse:\n ...\n any all output = \"Bad\" if any('dog' in w for w in test_list) else \"Good\"\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17212057/" ]
74,633,755
<p>Using NetLogo 5.3.1, i'm trying to set up BehaviorSpace so that all its model runs start after exactly the same 500-tick warmup period. However, the results are not intuitive to me.</p> <p>For illustrative purposes, I will use the 'Flocking.nlogo' model in the model library. Below is the model code, with 2 lines of code added to the end of the setup which saves the model's state after 500 ticks.</p> <pre><code>turtles-own [ flockmates ;; agentset of nearby turtles nearest-neighbor ;; closest one of our flockmates ] to setup clear-all create-turtles population [ set color yellow - 2 + random 7 ;; random shades look nice set size 1.5 ;; easier to see setxy random-xcor random-ycor set flockmates no-turtles ] reset-ticks ; Now execute a 500-tick warm-up period and save the model's state repeat 500 [ go ] export-world &quot;Flocking-after-500ticks.csv&quot; end to go ask turtles [ flock ] ;; the following line is used to make the turtles ;; animate more smoothly. repeat 5 [ ask turtles [ fd 0.2 ] display ] ;; for greater efficiency, at the expense of smooth ;; animation, substitute the following line instead: ;; ask turtles [ fd 1 ] tick end to flock ;; turtle procedure find-flockmates if any? flockmates [ find-nearest-neighbor ifelse distance nearest-neighbor &lt; minimum-separation [ separate ] [ align cohere ] ] end to find-flockmates ;; turtle procedure set flockmates other turtles in-radius vision end to find-nearest-neighbor ;; turtle procedure set nearest-neighbor min-one-of flockmates [distance myself] end ;;; SEPARATE to separate ;; turtle procedure turn-away ([heading] of nearest-neighbor) max-separate-turn end ;;; ALIGN to align ;; turtle procedure turn-towards average-flockmate-heading max-align-turn end to-report average-flockmate-heading ;; turtle procedure ;; We can't just average the heading variables here. ;; For example, the average of 1 and 359 should be 0, ;; not 180. So we have to use trigonometry. let x-component sum [dx] of flockmates let y-component sum [dy] of flockmates ifelse x-component = 0 and y-component = 0 [ report heading ] [ report atan x-component y-component ] end ;;; COHERE to cohere ;; turtle procedure turn-towards average-heading-towards-flockmates max-cohere-turn end to-report average-heading-towards-flockmates ;; turtle procedure ;; &quot;towards myself&quot; gives us the heading from the other turtle ;; to me, but we want the heading from me to the other turtle, ;; so we add 180 let x-component mean [sin (towards myself + 180)] of flockmates let y-component mean [cos (towards myself + 180)] of flockmates ifelse x-component = 0 and y-component = 0 [ report heading ] [ report atan x-component y-component ] end ;;; HELPER PROCEDURES to turn-towards [new-heading max-turn] ;; turtle procedure turn-at-most (subtract-headings new-heading heading) max-turn end to turn-away [new-heading max-turn] ;; turtle procedure turn-at-most (subtract-headings heading new-heading) max-turn end ;; turn right by &quot;turn&quot; degrees (or left if &quot;turn&quot; is negative), ;; but never turn more than &quot;max-turn&quot; degrees to turn-at-most [turn max-turn] ;; turtle procedure ifelse abs turn &gt; max-turn [ ifelse turn &gt; 0 [ rt max-turn ] [ lt max-turn ] ] [ rt turn ] end ; Copyright 1998 Uri Wilensky. ; See Info tab for full copyright and license. </code></pre> <p>The BehaviorSpace window looks like this:</p> <p><a href="https://i.stack.imgur.com/dySmW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dySmW.png" alt="enter image description here" /></a></p> <p>The added 2 lines of code, which saves the model's state after 500 ticks, come from the answer to question 6 in Chapter 9 in Railsback &amp; Grimm 2012: Agent-based and individual-based modeling (1st edition). The answer continues by stating the next step: &quot;Then, in BehaviorSpace, change the &quot;Setup commands&quot; to just import the saved world and run 1000 more ticks&quot;.</p> <p>I did this, and then imported the file into R to summarise the data by calculating the mean and SD of number of flockmates at tick 100, 200, 300, 400, and 500. Below the R code:</p> <pre><code>df &lt;- read.csv(&quot;ibm_table_output-test.csv&quot;, skip = 6) df1 &lt;- df %&gt;% rename(run_number = X.run.number., time_step = X.step., mean_flockmates = mean..count.flockmates..of.turtles ) %&gt;% select(run_number, time_step, mean_flockmates, vision) %&gt;% arrange(run_number, time_step) %&gt;% filter(time_step == 100 | time_step == 200 | time_step == 300 | time_step == 400 | time_step == 500) df1_long &lt;- melt(df1, # Apply melt function id.vars = c(&quot;run_number&quot;, &quot;time_step&quot;,&quot;vision&quot;)) # Calculate a summary table df1.summ &lt;- df1_long %&gt;% group_by(time_step, vision) %&gt;% summarise(avg = mean(value), sd = sd(value)) </code></pre> <p>The output is as follows:</p> <pre><code> # A tibble: 15 × 4 # Groups: time_step [5] time_step vision avg sd &lt;int&gt; &lt;int&gt; &lt;dbl&gt; &lt;dbl&gt; 1 100 1 8.34 0 2 100 2 8.34 0 3 100 3 8.34 0 4 200 1 7.83 0 5 200 2 7.83 0 6 200 3 7.83 0 7 300 1 7.95 0 8 300 2 7.95 0 9 300 3 7.95 0 10 400 1 7.45 0 11 400 2 7.45 0 12 400 3 7.45 0 13 500 1 7.92 0 14 500 2 7.92 0 15 500 3 7.92 0 </code></pre> <p>To me this output doesn't make sense.</p> <p>My question is why is the average number of flockmates the same across different vision levels within the same time_step group? And why are the SDs all 0? In other words, why do the model runs produce identical outputs? I thought that initiating a burnin period would initiate identical starting positions for all simulations, but create different mean and SD values for each run because of different random numbers used? Or am I misunderstanding?</p> <hr /> <p>EDIT: The reason why the SDs are 0 is because there is no variation in mean values, but I don't understand why there is no variation. Below is the <code>df1_long</code> data frame:</p> <pre><code> run_number time_step vision variable value 1 1 100 1 mean_flockmates 8.340000 2 1 200 1 mean_flockmates 7.833333 3 1 300 1 mean_flockmates 7.953333 4 1 400 1 mean_flockmates 7.446667 5 1 500 1 mean_flockmates 7.920000 6 2 100 1 mean_flockmates 8.340000 7 2 200 1 mean_flockmates 7.833333 8 2 300 1 mean_flockmates 7.953333 9 2 400 1 mean_flockmates 7.446667 10 2 500 1 mean_flockmates 7.920000 11 3 100 2 mean_flockmates 8.340000 12 3 200 2 mean_flockmates 7.833333 13 3 300 2 mean_flockmates 7.953333 14 3 400 2 mean_flockmates 7.446667 15 3 500 2 mean_flockmates 7.920000 16 4 100 2 mean_flockmates 8.340000 17 4 200 2 mean_flockmates 7.833333 18 4 300 2 mean_flockmates 7.953333 19 4 400 2 mean_flockmates 7.446667 20 4 500 2 mean_flockmates 7.920000 21 5 100 3 mean_flockmates 8.340000 22 5 200 3 mean_flockmates 7.833333 23 5 300 3 mean_flockmates 7.953333 24 5 400 3 mean_flockmates 7.446667 25 5 500 3 mean_flockmates 7.920000 26 6 100 3 mean_flockmates 8.340000 27 6 200 3 mean_flockmates 7.833333 28 6 300 3 mean_flockmates 7.953333 29 6 400 3 mean_flockmates 7.446667 30 6 500 3 mean_flockmates 7.920000 </code></pre>
[ { "answer_id": 74633767, "author": "Tom Ron", "author_id": 1481986, "author_profile": "https://Stackoverflow.com/users/1481986", "pm_score": 3, "selected": true, "text": "test_list output = 'Good'\nfor test_word in test_list:\n if 'dog' in test_word:\n output = 'Bad'\n break\n\nprint(output)\n" }, { "answer_id": 74633804, "author": "César Rodrigues", "author_id": 2359882, "author_profile": "https://Stackoverflow.com/users/2359882", "pm_score": 0, "selected": false, "text": "output = 'Good'\nfor item in test_list:\n if 'dog' in item:\n output = 'Bad'\nprint(output)\n" }, { "answer_id": 74633815, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 0, "selected": false, "text": "any all if any('dog' in w for w in test_list):\n ...\nelse:\n ...\n any all output = \"Bad\" if any('dog' in w for w in test_list) else \"Good\"\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1087942/" ]
74,633,763
<p>I have the following markup:</p> <pre><code>&lt;div class=&quot;wrapper&quot;&gt; &lt;div class=&quot;one&quot;&gt;One&lt;/div&gt; &lt;div class=&quot;two&quot;&gt;Two&lt;/div&gt; &lt;div class=&quot;three&quot;&gt;Three&lt;/div&gt; &lt;/div&gt; </code></pre> <p>I want the layout to accomplish a layout in which the first two child divs are arranged next to each other as two columns while the 3rd sits on a row of its occupying full width.</p> <p>The first child column will be a fixed width (30px), while the second should occupy the remaining space.</p> <p>I have tried this, but it doesn't accomplish what I need:</p> <pre><code>.wrapper { display: grid; grid-template-columns: 20px auto 100%; border:1px solid white; } </code></pre>
[ { "answer_id": 74633767, "author": "Tom Ron", "author_id": 1481986, "author_profile": "https://Stackoverflow.com/users/1481986", "pm_score": 3, "selected": true, "text": "test_list output = 'Good'\nfor test_word in test_list:\n if 'dog' in test_word:\n output = 'Bad'\n break\n\nprint(output)\n" }, { "answer_id": 74633804, "author": "César Rodrigues", "author_id": 2359882, "author_profile": "https://Stackoverflow.com/users/2359882", "pm_score": 0, "selected": false, "text": "output = 'Good'\nfor item in test_list:\n if 'dog' in item:\n output = 'Bad'\nprint(output)\n" }, { "answer_id": 74633815, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 0, "selected": false, "text": "any all if any('dog' in w for w in test_list):\n ...\nelse:\n ...\n any all output = \"Bad\" if any('dog' in w for w in test_list) else \"Good\"\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3469841/" ]
74,633,790
<p>Consider a matrix where you don't need the third column:</p> <pre class="lang-matlab prettyprint-override"><code>X = zeros(Int64, (4, 3)); X[:, 1] = [0, 0, 1, 1]; X[:, 2] = [1, 2, 1, 2]; </code></pre> <pre><code>julia&gt; X 4×3 Matrix{Int64}: 0 1 0 0 2 0 1 1 0 1 2 0 </code></pre> <p>So you want to select (copy) everything <strong>except</strong> column 3:</p> <pre><code>4×2 Matrix{Int64}: 0 1 0 2 1 1 1 2 </code></pre> <p>Is there a shorthand way to express this?</p> <p>These work, but feel impractical when you have a large number of columns:</p> <pre class="lang-matlab prettyprint-override"><code>X[:, [1, 2]] X[:, sort(collect(setdiff(Set([1, 2, 3]), Set([3]))))] </code></pre>
[ { "answer_id": 74633767, "author": "Tom Ron", "author_id": 1481986, "author_profile": "https://Stackoverflow.com/users/1481986", "pm_score": 3, "selected": true, "text": "test_list output = 'Good'\nfor test_word in test_list:\n if 'dog' in test_word:\n output = 'Bad'\n break\n\nprint(output)\n" }, { "answer_id": 74633804, "author": "César Rodrigues", "author_id": 2359882, "author_profile": "https://Stackoverflow.com/users/2359882", "pm_score": 0, "selected": false, "text": "output = 'Good'\nfor item in test_list:\n if 'dog' in item:\n output = 'Bad'\nprint(output)\n" }, { "answer_id": 74633815, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 0, "selected": false, "text": "any all if any('dog' in w for w in test_list):\n ...\nelse:\n ...\n any all output = \"Bad\" if any('dog' in w for w in test_list) else \"Good\"\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12439119/" ]
74,633,795
<p>I have three components <code>First</code>, <code>Second</code> and <code>Third</code> that need to render one after the other.</p> <p>My App looks like this at the moment:</p> <pre><code>function App() { return ( &lt;First/&gt; ) } </code></pre> <p>So ideally, there's a form inside <code>First</code> that on submission (onSubmit probably) triggers rendering the <code>Second</code> component, essentially getting replaced in the DOM. The <code>Second</code> after some logic triggers rendering the <code>Third</code> component and also passes a value down to it. I'm not sure how to go on about it.</p> <p>I tried using the <code>useState</code> hook to set a boolean state to render one of the first two components but I would need to render <code>First</code>, then somehow from within it change the set state in the parent which then checks the boolean and renders the second. Not sure how to do that. Something like below?</p> <pre><code>function App() { const { isReady, setIsReady } = useState(false); return ( isReady ? &lt;First/&gt; //inside this I need the state to change on form submit and propagate back up to the parent which checks the state value and renders the second? : &lt;Second/&gt; ); } </code></pre> <p>I'm mostly sure this isn't the right way to do it. Also need to figure out how to pass the value onto another component at the time of rendering it and getting replaced in the DOM. So how does one render multiple components one after the other on interaction inside each? A button click for example?</p> <p>Would greatly appreciate some guidance for this.</p>
[ { "answer_id": 74633767, "author": "Tom Ron", "author_id": 1481986, "author_profile": "https://Stackoverflow.com/users/1481986", "pm_score": 3, "selected": true, "text": "test_list output = 'Good'\nfor test_word in test_list:\n if 'dog' in test_word:\n output = 'Bad'\n break\n\nprint(output)\n" }, { "answer_id": 74633804, "author": "César Rodrigues", "author_id": 2359882, "author_profile": "https://Stackoverflow.com/users/2359882", "pm_score": 0, "selected": false, "text": "output = 'Good'\nfor item in test_list:\n if 'dog' in item:\n output = 'Bad'\nprint(output)\n" }, { "answer_id": 74633815, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 0, "selected": false, "text": "any all if any('dog' in w for w in test_list):\n ...\nelse:\n ...\n any all output = \"Bad\" if any('dog' in w for w in test_list) else \"Good\"\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3327875/" ]
74,633,844
<p>I have a form and I want to add a pattern validator to one of the input boxes to only allow numbers between 0 and 130.</p> <p>I am new in coding and I have no clue what I am doing. I want the input box to get red or have some error message if another number / letters are written.</p>
[ { "answer_id": 74633767, "author": "Tom Ron", "author_id": 1481986, "author_profile": "https://Stackoverflow.com/users/1481986", "pm_score": 3, "selected": true, "text": "test_list output = 'Good'\nfor test_word in test_list:\n if 'dog' in test_word:\n output = 'Bad'\n break\n\nprint(output)\n" }, { "answer_id": 74633804, "author": "César Rodrigues", "author_id": 2359882, "author_profile": "https://Stackoverflow.com/users/2359882", "pm_score": 0, "selected": false, "text": "output = 'Good'\nfor item in test_list:\n if 'dog' in item:\n output = 'Bad'\nprint(output)\n" }, { "answer_id": 74633815, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 0, "selected": false, "text": "any all if any('dog' in w for w in test_list):\n ...\nelse:\n ...\n any all output = \"Bad\" if any('dog' in w for w in test_list) else \"Good\"\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18724085/" ]
74,633,850
<p>A sequence of non-empty strings stringList is given, containing only uppercase letters of the Latin alphabet. For all strings starting with the same letter, determine their total length and obtain a sequence of strings of the form &quot;S-C&quot;, where S is the total length of all strings from stringList that begin with the character C. <strong>Order the resulting sequence in descending order of the numerical values of the sums, and for equal values of the sums, in ascending order of the C character codes.</strong></p> <p>This question is related to one of my previous questions.</p> <p>One solution that works is this one:</p> <pre><code>stringList.GroupBy(x =&gt; x[0]).Select(g =&gt; $&quot;{g.Sum(x =&gt; x.Length)}-{g.Key}&quot;); </code></pre> <p>The problem is that with this given example I don't know where to add the OrderByDescending()/ThenBy() clauses in order to get the correctly sorted list.</p>
[ { "answer_id": 74633935, "author": "Joe Enos", "author_id": 111266, "author_profile": "https://Stackoverflow.com/users/111266", "pm_score": 1, "selected": false, "text": "stringList\n .GroupBy(x => x[0])\n .Select(g => new {\n Len = g.Sum(x => x.Length),\n Char = g.Key,\n Val = $\"{g.Sum(x => x.Length)}-{g.Key}\"\n })\n .OrderByDescending(x => Len)\n .ThenBy(x => x.Char)\n .Select(x => x.Val);\n" }, { "answer_id": 74633976, "author": "Guru Stron", "author_id": 2501279, "author_profile": "https://Stackoverflow.com/users/2501279", "pm_score": 2, "selected": false, "text": "stringList\n .GroupBy(x => x[0])\n .Select(g => (Length: g.Sum(x => x.Length), Char: g.Key))\n .OrderByDescending(t => t.Length)\n .ThenBy(t => t.Char)\n .Select(t => $\"{t.Length}-{t.Char}\");\n" }, { "answer_id": 74634002, "author": "Sweeper", "author_id": 5133585, "author_profile": "https://Stackoverflow.com/users/5133585", "pm_score": 1, "selected": false, "text": "Select GroupBy OrderByDescending ThenBy Select stringList.GroupBy(x => x[0]) // assuming all strings are non-empty\n .Select(g => new {\n LengthSum = g.Sum(x => x.Length),\n FirstChar = g.Key\n })\n .OrderByDescending(x => x.LengthSum)\n .ThenBy(x => x.FirstChar)\n .Select(x => $\"{x.LengthSum}-{x.FirstChar}\");\n let var query = from str in stringList\n group str by str[0] into g\n let lengthSum = g.Sum(x => x.Length)\n let firstChar = g.Key\n orderby lengthSum descending, firstChar\n select $\"{lengthSum}-{firstChar}\";\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20569938/" ]
74,633,851
<p>I try to compare two dictionaries and if on key, value differs from the other dictionary then print the difference key, value in red.</p> <p>I think my views.py is correct. But how to show the difference in the template?</p> <p>So I have views.py:</p> <pre><code> def data_compare(): fruits = { &quot;appel&quot;: 3962.00, &quot;waspeen&quot;: 3304.07, &quot;ananas&quot;: 24, } set1 = set([(k, v) for k, v in fruits.items()]) return set1 def data_compare2(): fruits2 = { &quot;appel&quot;: 3962.00, &quot;waspeen&quot;: 3304.07, &quot;ananas&quot;: 30, } set2 = set([(k, v) for k, v in fruits2.items()]) return set2 def data_combined(request): data1 = data_compare() data2 = data_compare2() diff_set = list(data1 - data2) + list(data2 - data1) print(data1) return render(request, &quot;main/data_compare.html&quot;, context={&quot;data1&quot;: data1, &quot;data2&quot;: data2, &quot;diff_set&quot;: diff_set}) </code></pre> <p>and template:</p> <pre><code> &lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;title&gt;Document&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div class=&quot;container center&quot;&gt; {% for key, value in data1 %} &lt;span {% if diff_set %} style=&quot;color: red;&quot;&gt;{% endif %} {{ key }}: {{value}}&lt;/span&gt;&lt;br&gt; {% endfor %} &lt;/div&gt; &lt;div class=&quot;container center&quot;&gt; {% for key, value in data2 %} &lt;span {% if diff_set %} style=&quot;color: red;&quot;&gt;{% endif %}{{ key }}: {{value}}&lt;/span&gt;&lt;br&gt; {% endfor %} &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I did a print(diff_set) and that shows:</p> <pre><code>[('ananas', 24), ('ananas', 30)] </code></pre> <p>so that is correct</p> <p>But everything is now red. and only in this case ananas has to be red</p> <p>Question: how to return the key, value from a dictionary that differes from the other dictionary in red?</p>
[ { "answer_id": 74633935, "author": "Joe Enos", "author_id": 111266, "author_profile": "https://Stackoverflow.com/users/111266", "pm_score": 1, "selected": false, "text": "stringList\n .GroupBy(x => x[0])\n .Select(g => new {\n Len = g.Sum(x => x.Length),\n Char = g.Key,\n Val = $\"{g.Sum(x => x.Length)}-{g.Key}\"\n })\n .OrderByDescending(x => Len)\n .ThenBy(x => x.Char)\n .Select(x => x.Val);\n" }, { "answer_id": 74633976, "author": "Guru Stron", "author_id": 2501279, "author_profile": "https://Stackoverflow.com/users/2501279", "pm_score": 2, "selected": false, "text": "stringList\n .GroupBy(x => x[0])\n .Select(g => (Length: g.Sum(x => x.Length), Char: g.Key))\n .OrderByDescending(t => t.Length)\n .ThenBy(t => t.Char)\n .Select(t => $\"{t.Length}-{t.Char}\");\n" }, { "answer_id": 74634002, "author": "Sweeper", "author_id": 5133585, "author_profile": "https://Stackoverflow.com/users/5133585", "pm_score": 1, "selected": false, "text": "Select GroupBy OrderByDescending ThenBy Select stringList.GroupBy(x => x[0]) // assuming all strings are non-empty\n .Select(g => new {\n LengthSum = g.Sum(x => x.Length),\n FirstChar = g.Key\n })\n .OrderByDescending(x => x.LengthSum)\n .ThenBy(x => x.FirstChar)\n .Select(x => $\"{x.LengthSum}-{x.FirstChar}\");\n let var query = from str in stringList\n group str by str[0] into g\n let lengthSum = g.Sum(x => x.Length)\n let firstChar = g.Key\n orderby lengthSum descending, firstChar\n select $\"{lengthSum}-{firstChar}\";\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7713770/" ]
74,633,905
<p>I'm getting started with packaging a Python library, and I'm experiencing odd behavior when trying to import a function. I built a wheel for this library and installed in my conda environment using pip. The structure of my library is:</p> <pre><code>|- setup.py |- test_package |- __init__.py |- module1.py |- myutils.py </code></pre> <p>The <code>myutils.py</code> file contains a simple function:</p> <pre><code>def test_utils(): print(&quot;utils test function is working correctly&quot;) </code></pre> <p>The following import works as expected:</p> <pre><code>from test_package import myutils myutils.test_utils() </code></pre> <p>result:</p> <pre><code>utils test function is working correctly </code></pre> <p>However, the following import results in an error:</p> <pre><code>import test_package test_package.myutils.test_utils() </code></pre> <p>result:</p> <pre><code>AttributeError Traceback (most recent call last) Input In [1], in &lt;cell line: 2&gt;() 1 import test_package ----&gt; 2 test_package.myutils.test_utils() AttributeError: module 'test_package' has no attribute 'myutils' </code></pre> <p>The odd behavior is that if I call <code>help()</code> after receiving the error above and then call the function again, it works as expected:</p> <pre><code>help('test_package.myutils.test_utils') print(&quot;~~~~~ line break ~~~~~&quot;) test_package.myutils.test_utils() </code></pre> <p>result:</p> <pre><code>Help on function test_utils in test_package.myutils: test_package.myutils.test_utils = test_utils() ~~~~~ line break ~~~~~ utils test function is working correctly </code></pre> <p>I'm having difficulty understanding why using <code>from &lt;package&gt; import &lt;module&gt;</code> works while <code>import &lt;package&gt;</code> fails, and I'm definitely not understanding why <code>help()</code> resolves the AttributeError</p>
[ { "answer_id": 74633979, "author": "Noah May", "author_id": 4373214, "author_profile": "https://Stackoverflow.com/users/4373214", "pm_score": 0, "selected": false, "text": "test_package/__init__.py import myutils\n __init__.py module/__init__.py module.py" }, { "answer_id": 74634118, "author": "ShadowRanger", "author_id": 364696, "author_profile": "https://Stackoverflow.com/users/364696", "pm_score": 3, "selected": true, "text": "import os os.path import test_package\n import test_package.myutils\n test_package.myutils.test_utils() help help('test_package.myutils.test_utils') import test_package.myutils myutils test_package test_package.myutils" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20648944/" ]
74,633,907
<p>I have the beginnings of some python that will take columns out of a specific csv file and then rename the csv columns something else. The issue that I have is the CSV file will always be in the same directory this script is ran in, but the name won't always be the same (and there will only ever be one csv in the directory at a time)</p> <p>Is there a way to automatically grab the csv name and pass it as a variable? Here is what I have so far:</p> <p>`</p> <pre><code> import pandas as pd #df = pd.read_csv(&quot;csv_import.csv&quot;,skiprows=1) #==&gt; use to skip first row (header if required) df = pd.read_csv(&quot;test.csv&quot;) #===&gt; Include the headers correct_df = df.copy() correct_df.rename(columns={'Text1': 'Address1', 'Text2': 'Address2'}, inplace=True) #Exporting to CSV file correct_df.to_csv(r'.csv', index=False,header=True) </code></pre> <p>`</p> <p>What I'm looking for is to not have to specify &quot;test.csv&quot; and instead have it grab the name of the csv inthe directory.</p>
[ { "answer_id": 74633948, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": 2, "selected": true, "text": "glob.glob *.csv from glob import glob\nimport pandas as pd\n\ncsv_file = glob(\"*.csv\")[0]\n\ndf= pd.read_csv(csv_file)\n" }, { "answer_id": 74633962, "author": "Ivan Perehiniak", "author_id": 20637117, "author_profile": "https://Stackoverflow.com/users/20637117", "pm_score": 0, "selected": false, "text": "import os\ncsvfiles = [p for p in os.listdir() if p.endswith(\".csv\")]\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19137886/" ]
74,633,912
<p>Azure DevOps 2020, I created a new project collection on our DevOps server. When I went to create a new project for that new collection from my work computer browser, I received this message:</p> <p><em><strong>Oops, something went wrong. Project creation operation failed.</strong></em></p> <p>Hitting button Try Again on that error screen produced the same result.</p> <p>On our DevOps server, the log file from my attempt <em>C:\ProgramData\Microsoft\Azure DevOps\Server Configuration\Logs..._CreateProject_1130_141424.log</em> had this error:</p> <p><strong>This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms.</strong></p> <pre><code>Executing step: Create the Team Project Executing step: 'Create the Team Project' WorkItemTracking.CreateTeamProject (5 of 12) Process guids. TypeId: b8a3a935-7e91-48b8-a94c-606d37c3e9f2 Inherits: 00000000-0000-0000-0000-000000000000 Process flags. : IsSystem: True IsCustom: False All projects count:1 Well-formed projects count:0 Refreshing server caches. Importing queries. Failure while provisioning project - will retry (Message): This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms. Failure while provisioning project - will retry (Stacktrace): at System.Security.Cryptography.SHA1Managed..ctor() at Microsoft.TeamFoundation.WorkItemTracking.Server.CommonWITUtils.GetSha1HashString(String text) at Microsoft.TeamFoundation.WorkItemTracking.Server.DalUpdateQueryItemHashElement.JoinBatch(ElementGroup group, ServerQueryItem item, IVssRequestContext requestContext) at Microsoft.TeamFoundation.WorkItemTracking.Server.Update.ExplodeQueryUpdates(Guid id) at Microsoft.TeamFoundation.WorkItemTracking.Server.Update.AddQueryUpdatesToBatch() at Microsoft.TeamFoundation.WorkItemTracking.Server.Update.BuildBatch(XmlElement updateElement, MetadataTable[] tablesRequested, Int64[] rowVersions, Boolean bypassRules, Boolean validationOnly, Boolean provisionRules) at Microsoft.TeamFoundation.WorkItemTracking.Server.DataAccessLayerImpl.UpdateImpl(XmlElement updateElement, MetadataTable[] tablesRequested, Int64[] rowVersions, Payload metadataPayload, Boolean bisNotification, String&amp; dbStamp, Boolean bulkUpdate, Boolean&amp; bulkUpdateSuccess, IVssIdentity user, Boolean overwrite, Boolean bypassRules, Boolean validationOnly, Boolean provisionRules) at Microsoft.TeamFoundation.WorkItemTracking.Server.DataAccessLayerImpl.Update(XmlElement package, Boolean overwrite, Boolean provisionRules) at Microsoft.TeamFoundation.WorkItemTracking.Server.ProvisioningService.ImportQueries(IVssRequestContext requestContext, IProcessTemplate template, XmlNode queriesNode, Uri projectUri, ProvisioningActionType action) at Microsoft.TeamFoundation.Server.Deploy.TFCollection.Project.WorkItemTrackingImporter.ImportQueries() at Microsoft.TeamFoundation.Server.Servicing.TFCollection.WorkItemStepPerformer.ProvisionTeamProject(IVssRequestContext requestContext, IServicingContext servicingContext, Lazy`1 witImporter, String projectUri, ProcessDescriptor processDescriptor) at Microsoft.TeamFoundation.Server.Servicing.TFCollection.WorkItemStepPerformer.CreateTeamProject(IServicingContext servicingContext) Failure while provisioning project - will retry (Exception Type): InvalidOperationException Importing queries. [Error] This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms. System.InvalidOperationException: This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms. at System.Security.Cryptography.SHA1Managed..ctor() at Microsoft.TeamFoundation.WorkItemTracking.Server.CommonWITUtils.GetSha1HashString(String text) at Microsoft.TeamFoundation.WorkItemTracking.Server.DalUpdateQueryItemHashElement.JoinBatch(ElementGroup group, ServerQueryItem item, IVssRequestContext requestContext) at Microsoft.TeamFoundation.WorkItemTracking.Server.Update.ExplodeQueryUpdates(Guid id) at Microsoft.TeamFoundation.WorkItemTracking.Server.Update.AddQueryUpdatesToBatch() at Microsoft.TeamFoundation.WorkItemTracking.Server.Update.BuildBatch(XmlElement updateElement, MetadataTable[] tablesRequested, Int64[] rowVersions, Boolean bypassRules, Boolean validationOnly, Boolean provisionRules) at Microsoft.TeamFoundation.WorkItemTracking.Server.DataAccessLayerImpl.UpdateImpl(XmlElement updateElement, MetadataTable[] tablesRequested, Int64[] rowVersions, Payload metadataPayload, Boolean bisNotification, String&amp; dbStamp, Boolean bulkUpdate, Boolean&amp; bulkUpdateSuccess, IVssIdentity user, Boolean overwrite, Boolean bypassRules, Boolean validationOnly, Boolean provisionRules) at Microsoft.TeamFoundation.WorkItemTracking.Server.DataAccessLayerImpl.Update(XmlElement package, Boolean overwrite, Boolean provisionRules) at Microsoft.TeamFoundation.WorkItemTracking.Server.ProvisioningService.ImportQueries(IVssRequestContext requestContext, IProcessTemplate template, XmlNode queriesNode, Uri projectUri, ProvisioningActionType action) at Microsoft.TeamFoundation.Server.Deploy.TFCollection.Project.WorkItemTrackingImporter.ImportQueries() at Microsoft.TeamFoundation.Server.Servicing.TFCollection.WorkItemStepPerformer.ProvisionTeamProject(IVssRequestContext requestContext, IServicingContext servicingContext, Lazy`1 witImporter, String projectUri, ProcessDescriptor processDescriptor) at Microsoft.TeamFoundation.Server.Servicing.TFCollection.WorkItemStepPerformer.CreateTeamProject(IServicingContext servicingContext) at Microsoft.TeamFoundation.Framework.Server.TeamFoundationStepPerformerBase.PerformHostStep(String servicingOperation, ServicingOperationTarget target, IServicingStep servicingStep, String stepData, ServicingContext servicingContext) at Microsoft.TeamFoundation.Framework.Server.TeamFoundationStepPerformerBase.PerformStep(String servicingOperation, ServicingOperationTarget target, String stepType, String stepData, ServicingContext servicingContext) at Microsoft.TeamFoundation.Framework.Server.ServicingStepDriver.PerformServicingStep(ServicingStep step, ServicingContext servicingContext, ServicingStepGroup group, ServicingOperation servicingOperation, Int32 stepNumber, Int32 totalSteps) Step failed: Create the Team Project. Execution time: 220 milliseconds. [StepDuration] 0.1820582 [GroupDuration] 0.2299482 [OperationDuration] 1.1763862 Clearing dictionary, removing all items. </code></pre> <p>Based on that error, I performed the following steps on the DevOps server. After each step I stopped/started IIS, then went back to attempt Create Project again. No luck with any of these solutions.</p> <ul> <li><p>Modified file C:\ProgramData\Microsoft\Azure DevOps\Configuration\SavedSettings\ApplicationTier\web.config to contain element <em>enforceFIPSPolicy enabled=&quot;false&quot;</em>.</p> </li> <li><p>Since the app pools for Azure DevOps use the .NET CLR Version v4.0.30319, I modified file C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Aspnet.config to contain element <em>enforceFIPSPolicy enabled=&quot;false&quot;</em>.</p> </li> <li><p>On the machine's Local Security Policy, disabled setting <em>System cryptography: Use FIPS compliant algorithms...</em></p> </li> </ul> <p>Can anyone suggest what else I can try? I'm assuming the error message is accurate, and quite frankly I was surprised that the last thing I tried did not solve the problem.</p> <p><strong>UPDATE:</strong> In the error message I also see</p> <p><code>at System.Security.Cryptography.SHA1Managed..ctor()</code></p> <p>I'm assuming SHA1Managed..ctor() means SHA1Managed constructor. If that's true then <a href="https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha1managed.-ctor?redirectedfrom=MSDN&amp;view=net-7.0#System_Security_Cryptography_SHA1Managed__ctor" rel="nofollow noreferrer">Microsoft</a> says that SHA1Managed is not FIPS compliant.</p> <p>But I can't change the DevOps code, if it's using SHA1Managed there's nothing I can do about it, correct?</p> <p>On our DevOps server, we have DevOps 2020 Update 1. So we are behind, would getting to Update 2 solve this problem? Or should I ask, does Update 2 use a different/newer cryptography class which might solve my problem?</p>
[ { "answer_id": 74633948, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": 2, "selected": true, "text": "glob.glob *.csv from glob import glob\nimport pandas as pd\n\ncsv_file = glob(\"*.csv\")[0]\n\ndf= pd.read_csv(csv_file)\n" }, { "answer_id": 74633962, "author": "Ivan Perehiniak", "author_id": 20637117, "author_profile": "https://Stackoverflow.com/users/20637117", "pm_score": 0, "selected": false, "text": "import os\ncsvfiles = [p for p in os.listdir() if p.endswith(\".csv\")]\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8149311/" ]
74,633,925
<p>Having diffuclty grasping the concept of generics. How can I return a vector from a function with a generic value? I'd like to input text and the output be either a vector of eithers strings or integers. However, the compiler gives me <code>error[E0277]: &lt;T as FromStr&gt;::Err doesn't implement Debug</code>. It's telling me that I need to implement the 'Debug'trait? But I don't understand why. How can I simply return a vector of an arbitrary type?</p> <pre><code>use std::str::FromStr; fn main() { let a: Vec&lt;u32&gt; = text_to_vec(&quot;1 2 3 4&quot;); } fn text_to_vec&lt;T: FromStr&gt;(text: &amp;str) -&gt; Vec&lt;T&gt; { let mut list = Vec::new(); for word in text.split(&quot; &quot;){ if let w = word { let w = w.parse().unwrap(); list.push(w); } } return list; } </code></pre> <p>I'm expecting to get a vector of u32 integers in this case.</p>
[ { "answer_id": 74634097, "author": "PitaJ", "author_id": 847382, "author_profile": "https://Stackoverflow.com/users/847382", "pm_score": 2, "selected": false, "text": "unwrap unwrap <T as FromStr>::Err Debug Result use std::str::FromStr;\n\nfn main() {\n let a: Vec<u32> = text_to_vec(\"1 2 3 4\").unwrap();\n}\n\nfn text_to_vec<T: FromStr>(text: &str) -> Result<Vec<T>, <T as FromStr>::Err> {\n text.split(\" \").map(|word| word.parse()).collect()\n}\n use std::fmt::Debug;\n\nfn text_to_vec_unwrap<T>(text: &str) -> Vec<T>\nwhere\n T: FromStr,\n <T as FromStr>::Err: Debug,\n{\n text.split(\" \").map(|word| word.parse().unwrap()).collect()\n}\n" }, { "answer_id": 74634136, "author": "kmdreko", "author_id": 2189130, "author_profile": "https://Stackoverflow.com/users/2189130", "pm_score": 3, "selected": true, "text": "error[E0277]: `<T as FromStr>::Err` doesn't implement `Debug`\n --> src/main.rs:12:21\n |\n12 | let w = w.parse().unwrap();\n | ^^^^^^^^^ ------ required by a bound introduced by this call\n | |\n | `<T as FromStr>::Err` cannot be formatted using `{:?}` because it doesn't implement `Debug`\n |\n = help: the trait `Debug` is not implemented for `<T as FromStr>::Err`\nnote: required by a bound in `Result::<T, E>::unwrap`\nhelp: consider further restricting the associated type\n |\n7 | fn text_to_vec<T: FromStr>(text: &str) -> Vec<T> where <T as FromStr>::Err: Debug {\n | ++++++++++++++++++++++++++++++++\n Debug .unwrap() Debug where .parse() Debug match match w.parse() {\n Ok(w) => list.push(w),\n Err(_) => println!(\"failed to parse {w}\"),\n}\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8973803/" ]
74,633,966
<p>I'm doing a project for my school about the solar system and I added a line (image) to represent the distance between the planets. I tried searching for an answer but all the other websites told to use float left to position my text</p> <p>HTML:</p> <pre><code>&lt;main&gt; &lt;div&gt; &lt;!-- Images des planetes --&gt; &lt;img src=&quot;images/Sun.png&quot; alt=&quot;Soleil&quot; title=&quot;&quot; id=&quot;Soleil&quot;&gt; &lt;p&gt; Text Test Alignment&lt;/p&gt; &lt;img src=&quot;images/lines.png&quot; alt=&quot;Ligne&quot;&gt; &lt;img src=&quot;images/mercury.png&quot; alt=&quot;Mercure&quot; title=&quot;Mercure&quot; id=&quot;Mercure&quot;&gt; &lt;img src=&quot;images/lines.png&quot; alt=&quot;Ligne&quot;&gt; &lt;img src=&quot;images/Venus.png&quot; alt=&quot;Vénus&quot; title=&quot;Vénus&quot; id=&quot;Venus&quot;&gt; &lt;img src=&quot;images/lines.png&quot; alt=&quot;Ligne&quot;&gt; &lt;img src=&quot;images/Earth.png&quot; alt=&quot;Terre&quot; title=&quot;Terre&quot; id=&quot;Terre&quot;&gt; &lt;img src=&quot;images/lines.png&quot; alt=&quot;Ligne&quot;&gt; &lt;img src=&quot;images/Mars.png&quot; alt=&quot;Mars&quot; title=&quot;Mars&quot; id=&quot;Mars&quot;&gt; &lt;img src=&quot;images/lines.png&quot; alt=&quot;Ligne&quot;&gt; &lt;img src=&quot;images/Jupiter.png&quot; alt=&quot;Jupiter&quot; title=&quot;Jupiter&quot; id=&quot;Jupiter&quot;&gt; &lt;img src=&quot;images/lines.png&quot; alt=&quot;Ligne&quot;&gt; &lt;img src=&quot;images/Saturn.png&quot; alt=&quot;Saturne&quot; title=&quot;Saturne&quot; id=&quot;Saturne&quot;&gt; &lt;img src=&quot;images/lines.png&quot; alt=&quot;Ligne&quot;&gt; &lt;img src=&quot;images/Uranus.png&quot; alt=&quot;Uranus&quot; title=&quot;Uranus&quot; id=&quot;Uranus&quot;&gt; &lt;img src=&quot;images/lines.png&quot; alt=&quot;Ligne&quot;&gt; &lt;img src=&quot;images/Neptune.png&quot; alt=&quot;Neptune&quot; title=&quot;Neptune&quot; id=&quot;Neptune&quot;&gt; &lt;/div&gt; &lt;/main&gt; </code></pre> <p>CSS:</p> <pre><code>main div { display: flex; align-items: center; flex-direction: column; } p{ color:white; } </code></pre> <p>I also tried text align in both areas and won't work</p> <p>Link to what my page looks like <a href="https://i.stack.imgur.com/jDdAF.jpg" rel="nofollow noreferrer">here</a></p> <p>I tried text-align, float, justify-content,align-items. I hope someone could find a solution for this thanks.</p>
[ { "answer_id": 74634196, "author": "dbonev", "author_id": 4200334, "author_profile": "https://Stackoverflow.com/users/4200334", "pm_score": 0, "selected": false, "text": "<main>\n <div>\n <!-- Images des planetes -->\n <div class=\"inner\">\n <img src=\"images/Sun.png\" alt=\"Soleil\" title=\"\" id=\"Soleil\">\n <p> Text Test Alignment</p>\n </div>\n <img src=\"images/lines.png\" alt=\"Ligne\"> \n <img src=\"images/mercury.png\" alt=\"Mercure\" title=\"Mercure\" id=\"Mercure\">\n <img src=\"images/lines.png\" alt=\"Ligne\">\n <img src=\"images/Venus.png\" alt=\"Vénus\" title=\"Vénus\" id=\"Venus\">\n <img src=\"images/lines.png\" alt=\"Ligne\">\n <img src=\"images/Earth.png\" alt=\"Terre\" title=\"Terre\" id=\"Terre\">\n <img src=\"images/lines.png\" alt=\"Ligne\">\n <img src=\"images/Mars.png\" alt=\"Mars\" title=\"Mars\" id=\"Mars\">\n <img src=\"images/lines.png\" alt=\"Ligne\">\n <img src=\"images/Jupiter.png\" alt=\"Jupiter\" title=\"Jupiter\" id=\"Jupiter\">\n <img src=\"images/lines.png\" alt=\"Ligne\">\n <img src=\"images/Saturn.png\" alt=\"Saturne\" title=\"Saturne\" id=\"Saturne\">\n <img src=\"images/lines.png\" alt=\"Ligne\">\n <img src=\"images/Uranus.png\" alt=\"Uranus\" title=\"Uranus\" id=\"Uranus\">\n <img src=\"images/lines.png\" alt=\"Ligne\">\n <img src=\"images/Neptune.png\" alt=\"Neptune\" title=\"Neptune\" id=\"Neptune\">\n </div>\n </main>\n\n\nmain div:not(.inner) {\n display: flex;\n align-items: center;\n flex-direction: column;\n}\n\np {\n color:white;\n}\n\n.inner {\n display: flex;\n}\n" }, { "answer_id": 74634446, "author": "Kameron", "author_id": 16496357, "author_profile": "https://Stackoverflow.com/users/16496357", "pm_score": 1, "selected": false, "text": "img p div flex main div {} main flex-direction: row; > main>div {\n display: flex;\n align-items: center;\n flex-direction: column;\n row-gap: 2em;\n}\n\nmain>div>div {\n display: flex;\n align-items: center;\n justify-content: space-between;\n text-align: center;\n}\n\nmain>div>div>p {\n padding: 0 1em;\n} <main>\n <div>\n <div>\n <!-- Images des planetes -->\n <img src=\"https://dummyimage.com/300/000/fff\" alt=\"Soleil\" title=\"\" id=\"Soleil\">\n <p> Text Test Alignment</p>\n </div>\n <div>\n <!-- Images des planetes -->\n <img src=\"https://dummyimage.com/300/000/fff\" alt=\"Soleil\" title=\"\" id=\"Soleil\">\n <p> Text Test Alignment</p>\n </div>\n <div>\n <!-- Images des planetes -->\n <img src=\"https://dummyimage.com/300/000/fff\" alt=\"Soleil\" title=\"\" id=\"Soleil\">\n <p> Text Test Alignment</p>\n </div>\n </div>\n</main>" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20478892/" ]
74,633,999
<p>I am trying to create a new column &quot;Starting_time&quot; by subtracting 60 days out of &quot;Harvest_date&quot; but I get the same date each time. Can someone point out what did I do wrong please?</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Harvest_date</th> </tr> </thead> <tbody> <tr> <td>20.12.21</td> </tr> <tr> <td>12.01.21</td> </tr> <tr> <td>10.03.21</td> </tr> </tbody> </table> </div> <pre class="lang-py prettyprint-override"><code>import pandas as pd from datetime import timedelta df1 = pd.read_csv (r'C:\Flower_weight.csv') def subtract_days_from_date(date, days): subtracted_date = pd.to_datetime(date) - timedelta(days=days) subtracted_date = subtracted_date.strftime(&quot;%Y-%m-%d&quot;) return subtracted_date df1['Harvest_date'] = pd.to_datetime(df1.Harvest_date) df1.style.format({&quot;Harvest_date&quot;: lambda t: t.strftime(&quot;%Y-%m-%d&quot;)}) for harvest_date in df1['Harvest_date']: df1[&quot;Starting_date&quot;]=subtract_days_from_date(harvest_date,60) print(df1[&quot;Starting_date&quot;]) </code></pre> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Starting_date</th> </tr> </thead> <tbody> <tr> <td>2021-10-05</td> </tr> <tr> <td>2021-10-05</td> </tr> <tr> <td>2021-10-05</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74634196, "author": "dbonev", "author_id": 4200334, "author_profile": "https://Stackoverflow.com/users/4200334", "pm_score": 0, "selected": false, "text": "<main>\n <div>\n <!-- Images des planetes -->\n <div class=\"inner\">\n <img src=\"images/Sun.png\" alt=\"Soleil\" title=\"\" id=\"Soleil\">\n <p> Text Test Alignment</p>\n </div>\n <img src=\"images/lines.png\" alt=\"Ligne\"> \n <img src=\"images/mercury.png\" alt=\"Mercure\" title=\"Mercure\" id=\"Mercure\">\n <img src=\"images/lines.png\" alt=\"Ligne\">\n <img src=\"images/Venus.png\" alt=\"Vénus\" title=\"Vénus\" id=\"Venus\">\n <img src=\"images/lines.png\" alt=\"Ligne\">\n <img src=\"images/Earth.png\" alt=\"Terre\" title=\"Terre\" id=\"Terre\">\n <img src=\"images/lines.png\" alt=\"Ligne\">\n <img src=\"images/Mars.png\" alt=\"Mars\" title=\"Mars\" id=\"Mars\">\n <img src=\"images/lines.png\" alt=\"Ligne\">\n <img src=\"images/Jupiter.png\" alt=\"Jupiter\" title=\"Jupiter\" id=\"Jupiter\">\n <img src=\"images/lines.png\" alt=\"Ligne\">\n <img src=\"images/Saturn.png\" alt=\"Saturne\" title=\"Saturne\" id=\"Saturne\">\n <img src=\"images/lines.png\" alt=\"Ligne\">\n <img src=\"images/Uranus.png\" alt=\"Uranus\" title=\"Uranus\" id=\"Uranus\">\n <img src=\"images/lines.png\" alt=\"Ligne\">\n <img src=\"images/Neptune.png\" alt=\"Neptune\" title=\"Neptune\" id=\"Neptune\">\n </div>\n </main>\n\n\nmain div:not(.inner) {\n display: flex;\n align-items: center;\n flex-direction: column;\n}\n\np {\n color:white;\n}\n\n.inner {\n display: flex;\n}\n" }, { "answer_id": 74634446, "author": "Kameron", "author_id": 16496357, "author_profile": "https://Stackoverflow.com/users/16496357", "pm_score": 1, "selected": false, "text": "img p div flex main div {} main flex-direction: row; > main>div {\n display: flex;\n align-items: center;\n flex-direction: column;\n row-gap: 2em;\n}\n\nmain>div>div {\n display: flex;\n align-items: center;\n justify-content: space-between;\n text-align: center;\n}\n\nmain>div>div>p {\n padding: 0 1em;\n} <main>\n <div>\n <div>\n <!-- Images des planetes -->\n <img src=\"https://dummyimage.com/300/000/fff\" alt=\"Soleil\" title=\"\" id=\"Soleil\">\n <p> Text Test Alignment</p>\n </div>\n <div>\n <!-- Images des planetes -->\n <img src=\"https://dummyimage.com/300/000/fff\" alt=\"Soleil\" title=\"\" id=\"Soleil\">\n <p> Text Test Alignment</p>\n </div>\n <div>\n <!-- Images des planetes -->\n <img src=\"https://dummyimage.com/300/000/fff\" alt=\"Soleil\" title=\"\" id=\"Soleil\">\n <p> Text Test Alignment</p>\n </div>\n </div>\n</main>" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11125039/" ]
74,634,022
<p>Let's say I have two tables like below:</p> <p><strong>users</strong> table:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>user_id</th> <th>name</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>kevin</td> </tr> <tr> <td>1</td> <td>alice</td> </tr> <tr> <td>2</td> <td>jake</td> </tr> <tr> <td>3</td> <td>mike</td> </tr> </tbody> </table> </div> <p><strong>permissions</strong> table:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>user_id</th> <th>permission</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>12</td> </tr> <tr> <td>1</td> <td>5</td> </tr> <tr> <td>3</td> <td>1</td> </tr> </tbody> </table> </div> <p>And let's say that I want to add permission <strong>5</strong> to every single user who doesn't already have it. What would be the best MySQL query for this?</p>
[ { "answer_id": 74634196, "author": "dbonev", "author_id": 4200334, "author_profile": "https://Stackoverflow.com/users/4200334", "pm_score": 0, "selected": false, "text": "<main>\n <div>\n <!-- Images des planetes -->\n <div class=\"inner\">\n <img src=\"images/Sun.png\" alt=\"Soleil\" title=\"\" id=\"Soleil\">\n <p> Text Test Alignment</p>\n </div>\n <img src=\"images/lines.png\" alt=\"Ligne\"> \n <img src=\"images/mercury.png\" alt=\"Mercure\" title=\"Mercure\" id=\"Mercure\">\n <img src=\"images/lines.png\" alt=\"Ligne\">\n <img src=\"images/Venus.png\" alt=\"Vénus\" title=\"Vénus\" id=\"Venus\">\n <img src=\"images/lines.png\" alt=\"Ligne\">\n <img src=\"images/Earth.png\" alt=\"Terre\" title=\"Terre\" id=\"Terre\">\n <img src=\"images/lines.png\" alt=\"Ligne\">\n <img src=\"images/Mars.png\" alt=\"Mars\" title=\"Mars\" id=\"Mars\">\n <img src=\"images/lines.png\" alt=\"Ligne\">\n <img src=\"images/Jupiter.png\" alt=\"Jupiter\" title=\"Jupiter\" id=\"Jupiter\">\n <img src=\"images/lines.png\" alt=\"Ligne\">\n <img src=\"images/Saturn.png\" alt=\"Saturne\" title=\"Saturne\" id=\"Saturne\">\n <img src=\"images/lines.png\" alt=\"Ligne\">\n <img src=\"images/Uranus.png\" alt=\"Uranus\" title=\"Uranus\" id=\"Uranus\">\n <img src=\"images/lines.png\" alt=\"Ligne\">\n <img src=\"images/Neptune.png\" alt=\"Neptune\" title=\"Neptune\" id=\"Neptune\">\n </div>\n </main>\n\n\nmain div:not(.inner) {\n display: flex;\n align-items: center;\n flex-direction: column;\n}\n\np {\n color:white;\n}\n\n.inner {\n display: flex;\n}\n" }, { "answer_id": 74634446, "author": "Kameron", "author_id": 16496357, "author_profile": "https://Stackoverflow.com/users/16496357", "pm_score": 1, "selected": false, "text": "img p div flex main div {} main flex-direction: row; > main>div {\n display: flex;\n align-items: center;\n flex-direction: column;\n row-gap: 2em;\n}\n\nmain>div>div {\n display: flex;\n align-items: center;\n justify-content: space-between;\n text-align: center;\n}\n\nmain>div>div>p {\n padding: 0 1em;\n} <main>\n <div>\n <div>\n <!-- Images des planetes -->\n <img src=\"https://dummyimage.com/300/000/fff\" alt=\"Soleil\" title=\"\" id=\"Soleil\">\n <p> Text Test Alignment</p>\n </div>\n <div>\n <!-- Images des planetes -->\n <img src=\"https://dummyimage.com/300/000/fff\" alt=\"Soleil\" title=\"\" id=\"Soleil\">\n <p> Text Test Alignment</p>\n </div>\n <div>\n <!-- Images des planetes -->\n <img src=\"https://dummyimage.com/300/000/fff\" alt=\"Soleil\" title=\"\" id=\"Soleil\">\n <p> Text Test Alignment</p>\n </div>\n </div>\n</main>" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13538357/" ]
74,634,028
<p>so some time ago i was assigned a project to find the position relative to time of a simulated pendulum on a free moving cart, i managed to calculate some equations to describe this motion and i tried to simulate it in python to make sure it is correct. The program i made can run and plot its position correctly, but it is quite slow especially when i try to plot it with higher accuracy. How can i improve this program, any tips is greatly appreciated.</p> <p>the program :</p> <pre><code>from scipy.integrate import quad from scipy.optimize import fsolve import numpy as np import matplotlib.pyplot as plt # These values can be changed masstot = 5 mass = 2 g= 9.8 l = 9.8 wan = (g/l)**(1/2) vuk = 0.1 oug = 1 def afad(lah): # Find first constant wan = 1 vuk = 0.1 oug = 1 kan = (12*(lah**4)*((3*(vuk**2)-(wan**2))))-((16*((wan**2)-(vuk**2))-(5*oug**2))*(lah**2))+(4*(oug**2)) return (kan) solua = fsolve(afad, 1) intsolua = sum(solua) def kfad(solua, wan, vuk): # Find second constant res = ((wan**2)-(vuk**2)-((2*(solua**2)*((2*(vuk**2))+(wan**2)))/((5*(solua**2))+4)))**(1/2) return (res) ksol = kfad(solua, wan, vuk) def deg(t, solua, vuk, ksol): # Find angle of pendulum relative to time res = 2*np.arctan(solua*np.exp(-1*vuk*t)*np.sin(ksol*t)) return(res) def chandeg(t, solua, vuk, ksol): # Find velocity of pendulum relative to time res = (((-2*solua*vuk*np.exp(vuk*t)*np.sin(ksol*t))+(2*solua*ksol*np.exp(vuk*t)*np.cos(ksol*t)))/(np.exp(2*vuk*t)+((solua**2)*(np.sin(ksol*t)**2)))) return(res) xs = np.linspace(0, 60, 20) # Value can be changed to alter plotting accuracy and length def dinte1(deg, bond, solua, vuk, ksol): # used to plot angle at at a certain time res = [] for x in (bond): res.append(deg(x, solua, vuk, ksol)) return res def dinte2(chandeg, bond, solua, vuk, ksol): # used to plot angular velocity at a certain time res = [] for x in (bond): res.append(chandeg(x, solua, vuk, ksol)) return res def dinte(a, bond, mass, l, solua, vuk, ksol, g, masstot ): # used to plot acceleration of system at certain time res = [] for x in (bond): res.append(a(x, mass, l, solua, vuk, ksol, g, masstot)) return res def a(t, mass, l, solua, vuk, ksol, g, masstot): # define acceleration of system to time return (((mass*l*(chandeg(t, solua, vuk, ksol)**2))+(mass*g*np.cos(deg(t, solua, vuk, ksol))))*np.sin(deg(t, solua, vuk, ksol))/masstot) def j(t): return sum(a(t, mass, l, intsolua, vuk, ksol, g, masstot)) def f(ub): return quad(lambda ub: quad(j, 0, ub)[0], 0, ub)[0] def int2(f, bond): # Integrates system acceleration twice to get posistion relative to time res = [] for x in (bond): res.append(f(x)) print(res) return res plt.plot(xs, int2(f, xs)) # This part of the program runs quite slowly #plt.plot(xs, dinte(a, xs, mass, l, solua, vuk, ksol, g, masstot)) #plt.plot(xs, dinte2(chandeg, xs, solua, vuk, ksol)) #plt.plot(xs, dinte1(deg, xs, solua, vuk, ksol)) plt.show() </code></pre> <p>Ran the program, it can run relatively well just very slowly. Disclaimer that i am new at using python and scipy so it's probably a very inneficient program.</p>
[ { "answer_id": 74634196, "author": "dbonev", "author_id": 4200334, "author_profile": "https://Stackoverflow.com/users/4200334", "pm_score": 0, "selected": false, "text": "<main>\n <div>\n <!-- Images des planetes -->\n <div class=\"inner\">\n <img src=\"images/Sun.png\" alt=\"Soleil\" title=\"\" id=\"Soleil\">\n <p> Text Test Alignment</p>\n </div>\n <img src=\"images/lines.png\" alt=\"Ligne\"> \n <img src=\"images/mercury.png\" alt=\"Mercure\" title=\"Mercure\" id=\"Mercure\">\n <img src=\"images/lines.png\" alt=\"Ligne\">\n <img src=\"images/Venus.png\" alt=\"Vénus\" title=\"Vénus\" id=\"Venus\">\n <img src=\"images/lines.png\" alt=\"Ligne\">\n <img src=\"images/Earth.png\" alt=\"Terre\" title=\"Terre\" id=\"Terre\">\n <img src=\"images/lines.png\" alt=\"Ligne\">\n <img src=\"images/Mars.png\" alt=\"Mars\" title=\"Mars\" id=\"Mars\">\n <img src=\"images/lines.png\" alt=\"Ligne\">\n <img src=\"images/Jupiter.png\" alt=\"Jupiter\" title=\"Jupiter\" id=\"Jupiter\">\n <img src=\"images/lines.png\" alt=\"Ligne\">\n <img src=\"images/Saturn.png\" alt=\"Saturne\" title=\"Saturne\" id=\"Saturne\">\n <img src=\"images/lines.png\" alt=\"Ligne\">\n <img src=\"images/Uranus.png\" alt=\"Uranus\" title=\"Uranus\" id=\"Uranus\">\n <img src=\"images/lines.png\" alt=\"Ligne\">\n <img src=\"images/Neptune.png\" alt=\"Neptune\" title=\"Neptune\" id=\"Neptune\">\n </div>\n </main>\n\n\nmain div:not(.inner) {\n display: flex;\n align-items: center;\n flex-direction: column;\n}\n\np {\n color:white;\n}\n\n.inner {\n display: flex;\n}\n" }, { "answer_id": 74634446, "author": "Kameron", "author_id": 16496357, "author_profile": "https://Stackoverflow.com/users/16496357", "pm_score": 1, "selected": false, "text": "img p div flex main div {} main flex-direction: row; > main>div {\n display: flex;\n align-items: center;\n flex-direction: column;\n row-gap: 2em;\n}\n\nmain>div>div {\n display: flex;\n align-items: center;\n justify-content: space-between;\n text-align: center;\n}\n\nmain>div>div>p {\n padding: 0 1em;\n} <main>\n <div>\n <div>\n <!-- Images des planetes -->\n <img src=\"https://dummyimage.com/300/000/fff\" alt=\"Soleil\" title=\"\" id=\"Soleil\">\n <p> Text Test Alignment</p>\n </div>\n <div>\n <!-- Images des planetes -->\n <img src=\"https://dummyimage.com/300/000/fff\" alt=\"Soleil\" title=\"\" id=\"Soleil\">\n <p> Text Test Alignment</p>\n </div>\n <div>\n <!-- Images des planetes -->\n <img src=\"https://dummyimage.com/300/000/fff\" alt=\"Soleil\" title=\"\" id=\"Soleil\">\n <p> Text Test Alignment</p>\n </div>\n </div>\n</main>" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20649661/" ]
74,634,070
<p>trying to convert pandas dataframe column from a to b as below -</p> <pre><code>import pandas as pd a = {'01AB': [[&quot;ABC&quot;,5],[&quot;XYZ&quot;,4],[&quot;LMN&quot;,1]], '02AB_QTY': [[&quot;Other&quot;,20],[&quot;not_Other&quot;,150],[&quot;another&quot;,15]]} b = {'01AB': {&quot;ABC&quot;:5,&quot;XYZ&quot;:4,&quot;LMN&quot;:1}, '02AB_QTY': {&quot;Other&quot;:20,&quot;not_Other&quot;:150,&quot;another&quot;:150}} df = pd.DataFrame(a).to_dict(orient='dict') print(df) </code></pre> <p>gives me -</p> <pre><code>{'01AB': {0: ['ABC', 5], 1: ['XYZ', 4], 2: ['LMN', 1]}, '02AB_QTY': {0: ['Other', 20], 1: ['not_Other', 150], 2: ['another', 15]}} </code></pre> <p>what will be the cleaner way to do this? This is what I have tried, dict 'a' is only to create the dataframe. I dont want to iterate through that, have to iterate through the column available in the pandas dataframe</p> <pre><code>import pandas as pd a = {'01AB': [[&quot;ABC&quot;,5],[&quot;XYZ&quot;,4],[&quot;LMN&quot;,1]], '02AB_QTY': [[&quot;Other&quot;,20],[&quot;not_Other&quot;,150],[&quot;another&quot;,15]]} b = {'01AB': {&quot;ABC&quot;:5,&quot;XYZ&quot;:4,&quot;LMN&quot;:1}, '02AB_QTY': {&quot;Other&quot;:20,&quot;not_Other&quot;:150,&quot;another&quot;:150}} df = pd.DataFrame(a)#.to_dict(orient='dict') col_list = [&quot;01AB&quot;, &quot;02AB_QTY&quot;,] for col in col_list: # print(df) df[col] = df[col].apply(lambda x: {} if x is None else {key: {v[0]:v[1] for v in list_item} for key, list_item in x}) display(df) </code></pre>
[ { "answer_id": 74634235, "author": "Ivan Perehiniak", "author_id": 20637117, "author_profile": "https://Stackoverflow.com/users/20637117", "pm_score": 1, "selected": false, "text": "for key, list_item in a.items():\n a[key] = {v[0]:v[1] for v in list_item}\n b = {}\nfor key, list_item in a.items():\n b[key] = {v[0]:v[1] for v in list_item}\n b = {key: {v[0]:v[1] for v in list_item} for key, list_item in a.items()}\n" }, { "answer_id": 74634303, "author": "pyjedy", "author_id": 15222211, "author_profile": "https://Stackoverflow.com/users/15222211", "pm_score": 0, "selected": false, "text": "a = {\"01AB\": [[\"ABC\", 5], [\"XYZ\", 4], [\"LMN\", 1]],\n \"02AB_QTY\": [[\"Other\", 20], [\"not_Other\", 150]]}\n\nb = {\"01AB\": {\"ABC\": 5, \"XYZ\": 4, \"LMN\": 1},\n \"02AB_QTY\": {\"Other\": 20, \"not_Other\": 150}}\n\nb1 = {}\nfor key1, list_of_key2_value in a.items():\n for key2, value in list_of_key2_value:\n b1.setdefault(key1, {}).update({key2: value})\nassert b == b1\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16578438/" ]
74,634,073
<p>I wasn't sure how to word this question.</p> <p>I have a data frame called p08, that shows how each state voted in the 2008 election. The indicator variable is named 'DemStatus' where 1==voted democrat and 0==voted republican.</p> <p>I want to label each state as republican and democrat for all four years between elections. For instance, Alabama voted republican in 2008, so I want to label them as 0 (republican) for 2008, 2009,2010, and 2011.</p> <p>I accomplished this by copying the data frame and naming it something else for each year. However, this is a very tedious process since I have election data from the 90s until 2020.</p> <p><strong>QUESTION:</strong> Is there a faster/simpler way to accomplish exactly what I have below?</p> <pre><code>p08=structure(list(STATE = c(&quot;Alabama&quot;, &quot;Alaska&quot;, &quot;Arizona&quot;, &quot;Arkansas&quot;, &quot;California&quot;, &quot;Colorado&quot;, &quot;Connecticut&quot;, &quot;Delaware&quot;, &quot;Dist. of Col.&quot;, &quot;Florida&quot;, &quot;Georgia&quot;, &quot;Hawaii&quot;, &quot;Idaho&quot;, &quot;Illinois&quot;, &quot;Indiana&quot;, &quot;Iowa&quot;, &quot;Kansas&quot;, &quot;Kentucky&quot;, &quot;Louisiana&quot;, &quot;Maine&quot;, &quot;Maryland&quot;, &quot;Massachusetts&quot;, &quot;Michigan&quot;, &quot;Minnesota&quot;, &quot;Mississippi&quot;, &quot;Missouri&quot;, &quot;Montana&quot;, &quot;Nebraska&quot;, &quot;Nevada&quot;, &quot;New Hampshire&quot;, &quot;New Jersey&quot;, &quot;New Mexico&quot;, &quot;New York&quot;, &quot;North Carolina&quot;, &quot;North Dakota&quot;, &quot;Ohio&quot;, &quot;Oklahoma&quot;, &quot;Oregon&quot;, &quot;Pennsylvania&quot;, &quot;Rhode Island&quot;, &quot;South Carolina&quot;, &quot;South Dakota&quot;, &quot;Tennessee&quot;, &quot;Texas&quot;, &quot;Utah&quot;, &quot;Vermont&quot;, &quot;Virginia&quot;, &quot;Washington&quot;, &quot;West Virginia&quot;, &quot;Wisconsin&quot;, &quot;Wyoming&quot;), YEAR = c(2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008), DemStatus = c(0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0)), row.names = 10:60, class = &quot;data.frame&quot;) party09=p08 party09$YEAR=2009 party10=p08 party10$YEAR=2010 party11=p08 party11$YEAR=2011 party08_11 = bind_rows(p08,party09,party10,party11) </code></pre>
[ { "answer_id": 74634106, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, "author_profile": "https://Stackoverflow.com/users/3358272", "pm_score": 2, "selected": false, "text": "library(dplyr)\np08 %>%\n left_join(tibble(YEAR=2008, YEAR1=2008:2011), by = \"YEAR\") %>%\n mutate(YEAR = YEAR1, YEAR1 = NULL)\n# # A tibble: 204 x 3\n# STATE YEAR DemStatus\n# <chr> <int> <dbl>\n# 1 Alabama 2008 0\n# 2 Alabama 2009 0\n# 3 Alabama 2010 0\n# 4 Alabama 2011 0\n# 5 Alaska 2008 0\n# 6 Alaska 2009 0\n# 7 Alaska 2010 0\n# 8 Alaska 2011 0\n# 9 Arizona 2008 0\n# 10 Arizona 2009 0\n# # ... with 194 more rows\n dplyr bind_rows tidyr::complete p08 %>%\n tidyr::complete(STATE, YEAR = 2008:2011) %>%\n group_by(STATE) %>%\n mutate(DemStatus = na.omit(DemStatus)[1]) %>%\n ungroup()\n# # A tibble: 204 x 3\n# STATE YEAR DemStatus\n# <chr> <dbl> <dbl>\n# 1 Alabama 2008 0\n# 2 Alabama 2009 0\n# 3 Alabama 2010 0\n# 4 Alabama 2011 0\n# 5 Alaska 2008 0\n# 6 Alaska 2009 0\n# 7 Alaska 2010 0\n# 8 Alaska 2011 0\n# 9 Arizona 2008 0\n# 10 Arizona 2009 0\n# # ... with 194 more rows\n" }, { "answer_id": 74634190, "author": "arg0naut91", "author_id": 8389003, "author_profile": "https://Stackoverflow.com/users/8389003", "pm_score": 3, "selected": true, "text": "library(data.table)\n\np08 <- setDT(p08)[, .(STATE, YEAR = seq(YEAR, YEAR + 3L), DemStatus), by = 1:nrow(p08)][, nrow := NULL]\n STATE YEAR DemStatus\n 1: Alabama 2008 0\n 2: Alabama 2009 0\n 3: Alabama 2010 0\n 4: Alabama 2011 0\n 5: Alaska 2008 0\n --- \n200: Wisconsin 2011 1\n201: Wyoming 2008 0\n202: Wyoming 2009 0\n203: Wyoming 2010 0\n204: Wyoming 2011 0\n" }, { "answer_id": 74634230, "author": "onyambu", "author_id": 8380272, "author_profile": "https://Stackoverflow.com/users/8380272", "pm_score": 2, "selected": false, "text": "outer merge(p08[-2], list(YEAR=2008:2011), by = NULL) # -2 means remove year\n\n STATE DemStatus YEAR\n1 Alabama 0 2008\n2 Alaska 0 2008\n3 Arizona 0 2008\n4 Arkansas 0 2008\n5 California 1 2008\n6 Colorado 1 2008\n: : : : \n merge(subset(p08, select = -YEAR), list(YEAR = 2008:2011), by =NULL)\n merge(p08, 2008:2011)\n merge(p08, 2008:2011)[-2]\n STATE DemStatus y\n1 Alabama 0 2008\n2 Alaska 0 2008\n3 Arizona 0 2008\n4 Arkansas 0 2008\n5 California 1 2008\n6 Colorado 1 2008\n7 Connecticut 1 2008\n8 Delaware 1 2008\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15858688/" ]
74,634,076
<p>I am trying to solve this problem. Here is my question that I am trying to solve using SQL.</p> <ol> <li><p>I have a project table which has many columns with data; such as (<code>ID</code>, <code>TITLE</code>, <code>DESCRIPTIO</code>,..ETC).</p> </li> <li><p>I have another table called field table; the field table has thousands of questions(it is similar to a survey poll with questions).</p> </li> <li><p>Each project has specific questions from the field table.</p> </li> <li><p>One of the questions in the field table is called <code>record_id</code>, some projects does not have this <code>record_id</code>.</p> </li> <li><p>Therefore, I sorted all the projects that does not have <code>record_id</code> using a SQL subquery; I was successfully able to sort the projects without <code>record_id</code>.</p> </li> <li><p>I am confused and stuck on how to use insert statement to insert <code>record_id</code> to those projects without <code>record_id</code>.</p> </li> </ol> <pre><code>SELECT PROJECT.PROJECTID FROM PROJECT WHERE PROJECTID NOT IN (SELECT PROJECT.PROJECTID FROM PROJECT JOIN FIELD ON PROJECT.PROJECTID = FIELD.PROJECTID WHERE FIELD.ISPROJECTID = 1); </code></pre> <p>I have tried to use this query, but it is not working.</p> <pre><code>INSERT INTO FIELD (NAME, LABEL, DATATYPE, ALIGNMENT, ISPROJECTID) VALUES ('record_id', 'Record ID', 'Text', 'RV', 1); SELECT PROJECT.PROJECTID FROM PROJECT WHERE PROJECTID NOT IN (SELECT PROJECT.PROJECTID FROM PROJECT JOIN FIELD ON PROJECT.PROJECTID = FIELD.PROJECTID WHERE FIELD.ISPROJECTID = 1); </code></pre>
[ { "answer_id": 74634198, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 0, "selected": false, "text": "INSERT INTO FIELD (NAME, LABEL, DATATYPE,ALIGNMENT,\n ISPROJECTID) \nSELECT 'record_id','Record ID','Text','RV', PROJECT.PROJECTID\n FROM PROJECT WHERE PROJECTID NOT IN\n (\n SELECT PROJECT.PROJECTID\n FROM PROJECT\n JOIN FIELD\n ON PROJECT.PROJECTID = FIELD.PROJECTID\n WHERE FIELD.ISPROJECTID = 1\n );\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13668877/" ]
74,634,082
<p>I would like to access my server that I host on my computer (Node.js &amp; Express) from my phone. The computer is on the same network as the phone.</p> <p>As soon as I type localhost:3000 in the address bar of the browser on the desktop PC, everything works without problems.</p> <p>If I now try to open my site with the cell phone under the following address 192.168.0.100:3000, I get no error message but nothing is displayed... The IP address was retrieved with ipconfig.</p> <p>I have tried several solutions that I have found here on Stack Overflow such as port sharing in the firewall settings. Unfortunately without success.</p> <p>Here is my code when creating at the server:</p> <pre><code>var express = require('express'); var app = express(); var server = app.listen(process.env.PORT || 3000, listen); function listen() { var host = server.address().address; var port = server.address().port; console.log('Example app listening at http://' + host + ':' + port); } </code></pre> <p>When I try to check my IP address via the console.log, I get the following:</p> <p><a href="https://i.stack.imgur.com/vNwKe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vNwKe.png" alt="enter image description here" /></a></p> <p>If someone has an idea what this could be I would be very happy!</p> <p>#1 Update:</p> <p>I have now replaced my line of code with</p> <blockquote> <p>var server = app.listen(3000, &quot;127.0.0.1&quot;, listen);</p> </blockquote> <p>and I get the following back from my console:</p> <p><a href="https://i.stack.imgur.com/WXyiZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WXyiZ.png" alt="enter image description here" /></a></p> <p>I can access my server from my computer through</p> <p>127.0.0.1:3000</p> <p>localhost:3000</p> <p>If I try to access (on computer) through 192.168.0.100:3000 nothing happens. I also get no error message. Only a white screen.</p> <p>#2 Update:</p> <p>Typing &quot;ipconfig&quot; in cmd</p> <p><a href="https://i.stack.imgur.com/ZIBrR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZIBrR.png" alt="enter image description here" /></a></p> <p>After changing the IP to</p> <blockquote> <p>var server = app.listen(3000, &quot;192.168.0.100&quot;, listen);</p> </blockquote> <p>I could not access my server anymore. Not even using localhost:3000. However, when examining the item I found an error that does not show up when I set</p> <blockquote> <p>var server = app.listen(3000, &quot;127.0.0.1:3000&quot;, listen);</p> </blockquote> <p>I do not understand why the error shows up when changing the IP address, since the code is the same.</p> <p>Heres a picture of the error</p> <p><a href="https://i.stack.imgur.com/KdZ84.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KdZ84.png" alt="enter image description here" /></a></p> <p><a href="https://github.com/processing/p5.js-sound/issues/454" rel="nofollow noreferrer">Error fixing</a></p> <p>Apparently one way to work around the error is to use a tunneling service (ngrok). I will try it</p> <p>#3 Update</p> <p>In my last attempt, i was trying to tunnel my server via ngrok. At first, everything looked like it was finally going to work. From my own PC I could access my websocket server via ngrok forwarding link. However, when I tried to click on the link with my phone/second pc, I got the error that the connection is refused...</p> <p><a href="https://i.stack.imgur.com/yGJso.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yGJso.png" alt="enter image description here" /></a></p> <p>If someone has an idea or an approach to what this could be, I would be very happy.</p> <p>SOLUTION IS POSTED IN THE COMMENTS</p>
[ { "answer_id": 74634198, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 0, "selected": false, "text": "INSERT INTO FIELD (NAME, LABEL, DATATYPE,ALIGNMENT,\n ISPROJECTID) \nSELECT 'record_id','Record ID','Text','RV', PROJECT.PROJECTID\n FROM PROJECT WHERE PROJECTID NOT IN\n (\n SELECT PROJECT.PROJECTID\n FROM PROJECT\n JOIN FIELD\n ON PROJECT.PROJECTID = FIELD.PROJECTID\n WHERE FIELD.ISPROJECTID = 1\n );\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17788969/" ]
74,634,093
<p>Good afternoon. I work for a telecom company, specifically in the Customer Success team. I created a spreadsheet for one of my customers monthly invoice using the raw csv file that our billing system generates. It works fine in excel, but is a bit messy, and my higher ups wanted me to start using power BI. I was able to create a much better looking report in power BI, but i'm running into the issue of recreating the report every month efficiently. In excel, I created a template file, that allows me to copy/past the raw data, and all the slicers and pivot tables are kept and only takes me minutes to send off. I've googled this a few times now and I cannot see a way to do the same thing with power BI, where i add in the csv file, and all the visualizations are kept and just the data is updated. Any help would be appreciated</p> <p><a href="https://i.stack.imgur.com/NIWUu.jpg" rel="nofollow noreferrer">Blank Excel Pivots</a></p> <p><a href="https://i.stack.imgur.com/WVV6P.jpg" rel="nofollow noreferrer">Excel Drop section</a></p> <p><a href="https://i.stack.imgur.com/BSE5i.jpg" rel="nofollow noreferrer">Filled Pivot Tables</a></p> <p><a href="https://i.stack.imgur.com/pYGkN.jpg" rel="nofollow noreferrer">Power BI Report</a></p> <p>I tried creating a template via export in Power BI, and that didn't seem to do anything, as it just continues to load the previous data. I also tried importing a new spreadsheet, but couldn't figure out how to get the system to use the new data, rather than the old one.</p>
[ { "answer_id": 74634718, "author": "David Browne - Microsoft", "author_id": 7297700, "author_profile": "https://Stackoverflow.com/users/7297700", "pm_score": 1, "selected": false, "text": "let\n dir = Folder.Contents(\"c:\\temp\" ),\n #\"Filtered Rows\" = Table.SelectRows(dir, each ([Extension] = \".csv\")),\n #\"Sorted Rows\" = Table.Sort(#\"Filtered Rows\",{{\"Date modified\", Order.Descending}}),\n #\"Contents\" = Table.FirstN(#\"Sorted Rows\",1)[Content]{0},\n #\"Imported CSV\" = Csv.Document(#\"Contents\",[Delimiter=\",\", Columns=3, Encoding=1252, QuoteStyle=QuoteStyle.None])\nin\n #\"Imported CSV\"\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20649726/" ]
74,634,127
<p>I am in the process of writing my own task app using Django and would like a few specific functions to be executed every day at a certain time (updating tasks, checking due dates, etc.). Is there a way to have Django run functions on a regular basis or how do I go about this in general?</p> <p>Does it make sense to write an extra program with an infinite loop for this or are there better ways?</p>
[ { "answer_id": 74634718, "author": "David Browne - Microsoft", "author_id": 7297700, "author_profile": "https://Stackoverflow.com/users/7297700", "pm_score": 1, "selected": false, "text": "let\n dir = Folder.Contents(\"c:\\temp\" ),\n #\"Filtered Rows\" = Table.SelectRows(dir, each ([Extension] = \".csv\")),\n #\"Sorted Rows\" = Table.Sort(#\"Filtered Rows\",{{\"Date modified\", Order.Descending}}),\n #\"Contents\" = Table.FirstN(#\"Sorted Rows\",1)[Content]{0},\n #\"Imported CSV\" = Csv.Document(#\"Contents\",[Delimiter=\",\", Columns=3, Encoding=1252, QuoteStyle=QuoteStyle.None])\nin\n #\"Imported CSV\"\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16554083/" ]
74,634,139
<p>I installed the ingress controller using the following command:</p> <p><code>kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.5.1/deploy/static/provider/cloud/deploy.yaml</code></p> <p>And the result of <code>kubectl get pods --namespace=ingress-nginx</code> is:</p> <pre><code>NAME READY STATUS RESTARTS AGE ingress-nginx-admission-create-x4mss 0/1 Completed 0 28m ingress-nginx-admission-patch-jn9cz 0/1 Completed 1 28m ingress-nginx-controller-8574b6d7c9-k4jbj 1/1 Running 0 28m </code></pre> <p>For <code>kubectl get service ingress-nginx-controller --namespace=ingress-nginx</code> I get:</p> <pre><code>NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE ingress-nginx-controller LoadBalancer 10.106.134.128 localhost 80:32294/TCP,443:30997/TCP 30m </code></pre> <p>As for my deployment and service I have the following:</p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: labels: app: app name: app namespace: namespace spec: replicas: 1 selector: matchLabels: app: app template: labels: app: app spec: containers: - image: image name: app ports: - containerPort: 5000 restartPolicy: Always --- apiVersion: v1 kind: Service metadata: name: app-service namespace: namespace spec: type: ClusterIP selector: app: app ports: - name: app-service port: 5000 targetPort: 5000 </code></pre> <p>My Ingress is as follows:</p> <pre><code>apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: ingress namespace: namespace annotations: kubernetes.io/ingress.class: nginx nginx.ingress.kubernetes.io/rewrite-target: / spec: ingressClassName: nginx rules: - host: com.host.com http: paths: - path: / pathType: Prefix backend: service: name: app-service port: number: 5000 </code></pre> <p>My pod and service are both running fine. The result of running <code>kubectl describe pod</code> command is:</p> <pre><code>Name: app-6b9f7fc47b-sh6nc Namespace: namespace Priority: 0 Service Account: default Node: docker-desktop/192.168.65.4 Start Time: Wed, 30 Nov 2022 16:22:04 -0500 Labels: app=app pod-template-hash=6b9f7fc47b Status: Running IP: 10.1.0.237 IPs: IP: 10.1.0.237 Controlled By: ReplicaSet/app-6b9f7fc47b Containers: app: Container ID: docker://ba77235d044c24b0f1391c56a2e8653a598a5c130ea4d15ff3b41cd96659fd4a Image: image Image ID: docker://sha256:912cb58ab1c3f2dd628c0b7db4d7f9ac6df4efbe4fcb86979b6a84614db8a675 Port: 5000/TCP Host Port: 0/TCP State: Running Started: Wed, 30 Nov 2022 16:22:05 -0500 Ready: True Restart Count: 0 Environment: &lt;none&gt; Mounts: /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-8pmjz (ro) Conditions: Type Status Initialized True Ready True ContainersReady True PodScheduled True Volumes: kube-api-access-8pmjz: Type: Projected (a volume that contains injected data from multiple sources) TokenExpirationSeconds: 3607 ConfigMapName: kube-root-ca.crt ConfigMapOptional: &lt;nil&gt; DownwardAPI: true QoS Class: BestEffort Node-Selectors: &lt;none&gt; Tolerations: node.kubernetes.io/not-ready:NoExecute op=Exists for 300s node.kubernetes.io/unreachable:NoExecute op=Exists for 300s Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal Scheduled 29m default-scheduler Successfully assigned namespace/app-6b9f7fc47b-sh6nc to docker-desktop Normal Pulled 29m kubelet Container image &quot;image&quot; already present on machine Normal Created 29m kubelet Created container app Normal Started 29m kubelet Started container app </code></pre> <p>Running the following command <code>kubectl get ingress --all-namespaces</code> yields:</p> <pre><code>NAMESPACE NAME CLASS HOSTS ADDRESS PORTS AGE namespace ingress nginx com.host.com 80 7s </code></pre> <p>I have tried using different ports, changing the controller, using a load balance type instead of cluster ip and yet nothing works when it comes to trying to make the ingress rule work. I have set the ingress-controller external ip as com.host.com in my hosts file as well. Furthermore, I am using docker-desktop as my node, however, I'm having this issue on minikube as well. Any help is appreciated.</p>
[ { "answer_id": 74634718, "author": "David Browne - Microsoft", "author_id": 7297700, "author_profile": "https://Stackoverflow.com/users/7297700", "pm_score": 1, "selected": false, "text": "let\n dir = Folder.Contents(\"c:\\temp\" ),\n #\"Filtered Rows\" = Table.SelectRows(dir, each ([Extension] = \".csv\")),\n #\"Sorted Rows\" = Table.Sort(#\"Filtered Rows\",{{\"Date modified\", Order.Descending}}),\n #\"Contents\" = Table.FirstN(#\"Sorted Rows\",1)[Content]{0},\n #\"Imported CSV\" = Csv.Document(#\"Contents\",[Delimiter=\",\", Columns=3, Encoding=1252, QuoteStyle=QuoteStyle.None])\nin\n #\"Imported CSV\"\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19155128/" ]
74,634,142
<p>I have a number of long strings and I want to match those that contain all <strong>words</strong> of a given list.</p> <pre><code>keywords=['special','dreams'] search_string1=&quot;This is something that manifests especially in dreams&quot; search_string2=&quot;This is something that manifests in special cases in dreams&quot; </code></pre> <p>I want only search_string2 matched. So far I have this code:</p> <pre><code>if all(x in search_text for x in keywords): print(&quot;matched&quot;) </code></pre> <p>The problem is that it will also match search_string1. Obviously I need to include some regex matching that uses \w or or \b, but I can't figure out how I can include a regex in the <code>if all</code> statement.</p> <p>Can anyone help?</p>
[ { "answer_id": 74634718, "author": "David Browne - Microsoft", "author_id": 7297700, "author_profile": "https://Stackoverflow.com/users/7297700", "pm_score": 1, "selected": false, "text": "let\n dir = Folder.Contents(\"c:\\temp\" ),\n #\"Filtered Rows\" = Table.SelectRows(dir, each ([Extension] = \".csv\")),\n #\"Sorted Rows\" = Table.Sort(#\"Filtered Rows\",{{\"Date modified\", Order.Descending}}),\n #\"Contents\" = Table.FirstN(#\"Sorted Rows\",1)[Content]{0},\n #\"Imported CSV\" = Csv.Document(#\"Contents\",[Delimiter=\",\", Columns=3, Encoding=1252, QuoteStyle=QuoteStyle.None])\nin\n #\"Imported CSV\"\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5539535/" ]
74,634,223
<p>I used a Redgate tool to synchronize data from a SQL Server database, and in the process, the tool created four new columns in each table with names like <code>createdby</code>, <code>updatedby</code>, etc.</p> <p>Now that the data is in sync, I don't want these columns anymore.</p> <p>Is there a simple way, maybe a script, to remove these columns?</p>
[ { "answer_id": 74634416, "author": "Piotr Rodak", "author_id": 227606, "author_profile": "https://Stackoverflow.com/users/227606", "pm_score": 3, "selected": true, "text": "ALTER TABLE table_name\nDROP COLUMN column_name;\n select 'alter table ' + quotename(table_schema) + '.' + quotename(table_name) + ' drop column ' + quotename(column_name) \nfrom information_schema.columns\nwhere 1=1\nand column_name in ('createdby', 'updatedby')\n" }, { "answer_id": 74644423, "author": "Tom McDonald", "author_id": 358574, "author_profile": "https://Stackoverflow.com/users/358574", "pm_score": 0, "selected": false, "text": "\\[CreatedAt\\][^\\,.]+\\,\n \\,([\\s\\r][\\s]+)+\\)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/358574/" ]
74,634,225
<p>On a MAUI app, I'm trying to pass a value from one page to another through their respective ViewModels, but it's not working and for the life of me I can't figure out why.</p> <p>Source VM:</p> <pre><code>[RelayCommand] public async Task GetAdvertDetailsPageAsync(int advertId) { await Shell.Current.GoToAsync($&quot;{nameof(AdvertDetails)}?AdvertId={advertId.ToString()}&quot;); } </code></pre> <p>Destination VM:</p> <pre><code>[QueryProperty(&quot;AdvertId&quot;, &quot;AdvertId&quot;)] public partial class AdvertDetailsVM : ObservableObject { [ObservableProperty] public string advertId; public AdvertDetailsVM(IMyHttpClient httpClient) { LoadAdvertAsync(Convert.ToInt32(AdvertId)); } </code></pre> <p>Destination ContentPage:</p> <pre><code>public partial class AdvertDetails : ContentPage { public AdvertDetails(AdvertDetailsVM vm) { InitializeComponent(); BindingContext = vm; } } </code></pre> <p>The parameter <strong>advertId</strong> on the <strong>GetAdvertDetailsPageAsync</strong> on the source page has a value, the destination page gets called, and the ViewModel gets injected just fine, but the <strong>AdvertId</strong> property on the destination comes up empty and I can't figure out why. For the record, I'm following <a href="https://www.youtube.com/watch?v=ddmZ6k1GIkM" rel="nofollow noreferrer">this tutorial</a></p> <p>Thanks in advance</p>
[ { "answer_id": 74634416, "author": "Piotr Rodak", "author_id": 227606, "author_profile": "https://Stackoverflow.com/users/227606", "pm_score": 3, "selected": true, "text": "ALTER TABLE table_name\nDROP COLUMN column_name;\n select 'alter table ' + quotename(table_schema) + '.' + quotename(table_name) + ' drop column ' + quotename(column_name) \nfrom information_schema.columns\nwhere 1=1\nand column_name in ('createdby', 'updatedby')\n" }, { "answer_id": 74644423, "author": "Tom McDonald", "author_id": 358574, "author_profile": "https://Stackoverflow.com/users/358574", "pm_score": 0, "selected": false, "text": "\\[CreatedAt\\][^\\,.]+\\,\n \\,([\\s\\r][\\s]+)+\\)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9978445/" ]
74,634,267
<p>I have a Django container and I want to consume another DL container inside it? For example, I have a Django app that predicting images classes and I want to make the prediction using a docker container and not a python library. That Django app will be containerised as well. In production, I will have three docker containers: Django container + Postgres container + YoloV5 container. How can I link the Django with the YoloV5 so that the prediction inside the Django will be done using the YoloV5?</p> <p>I want to connect a deep learning container with Django container to make prediction using the DL container and not a python package.</p>
[ { "answer_id": 74634416, "author": "Piotr Rodak", "author_id": 227606, "author_profile": "https://Stackoverflow.com/users/227606", "pm_score": 3, "selected": true, "text": "ALTER TABLE table_name\nDROP COLUMN column_name;\n select 'alter table ' + quotename(table_schema) + '.' + quotename(table_name) + ' drop column ' + quotename(column_name) \nfrom information_schema.columns\nwhere 1=1\nand column_name in ('createdby', 'updatedby')\n" }, { "answer_id": 74644423, "author": "Tom McDonald", "author_id": 358574, "author_profile": "https://Stackoverflow.com/users/358574", "pm_score": 0, "selected": false, "text": "\\[CreatedAt\\][^\\,.]+\\,\n \\,([\\s\\r][\\s]+)+\\)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13473785/" ]
74,634,277
<p>so i have a database that has a payment entity within it, the payment entity has few parameters, the most important one is the date parameter, the problem that am facing is am trying to sort the list of payments in the database into a list of lists, each mini list contains the payments made on the same day, <a href="https://i.stack.imgur.com/g2V2F.png" rel="nofollow noreferrer">here is an image so you can better understand what am trying to explain.</a></p> <p>i don't know how do i go about this whatsoever so am just looking for some guidance on how i should approach this.</p> <p>i don't think that any code is needed here but here is the code to the payment class, and am more than happy to provide more code if it's needed :</p> <pre><code>public class Payment { @PrimaryKey(autoGenerate = true) @ColumnInfo(name = &quot;id_payment&quot;) int paymentID; @Embedded SubjectTeacherCrossRef subjectTeacherCrossRef; @ColumnInfo(name = &quot;payment_date&quot;) String paymentDate; @ColumnInfo(name = &quot;payment_total&quot;) int paymentTotal; public void setPaymentID(int paymentID) { this.paymentID = paymentID; } public Payment(SubjectTeacherCrossRef subjectTeacherCrossRef, String paymentDate, int paymentTotal) { this.subjectTeacherCrossRef = subjectTeacherCrossRef; this.paymentDate = paymentDate; this.paymentTotal = paymentTotal; } public int getPaymentID() { return paymentID; } public SubjectTeacherCrossRef getSubjectTeacherCrossRef() { return subjectTeacherCrossRef; } public String getPaymentDate() { return paymentDate; } public int getPaymentTotal() { return paymentTotal; } </code></pre> <p>}</p>
[ { "answer_id": 74634416, "author": "Piotr Rodak", "author_id": 227606, "author_profile": "https://Stackoverflow.com/users/227606", "pm_score": 3, "selected": true, "text": "ALTER TABLE table_name\nDROP COLUMN column_name;\n select 'alter table ' + quotename(table_schema) + '.' + quotename(table_name) + ' drop column ' + quotename(column_name) \nfrom information_schema.columns\nwhere 1=1\nand column_name in ('createdby', 'updatedby')\n" }, { "answer_id": 74644423, "author": "Tom McDonald", "author_id": 358574, "author_profile": "https://Stackoverflow.com/users/358574", "pm_score": 0, "selected": false, "text": "\\[CreatedAt\\][^\\,.]+\\,\n \\,([\\s\\r][\\s]+)+\\)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18222209/" ]
74,634,301
<p>I wrote code in JavaScript for a counter to be output in my HTML webpage, but nothing is being printed. Where is my logic wrong?</p> <pre><code>&lt;script&gt; function calCountDown(){ var temp = new Date(&quot;Dec 11, 2022&quot;); //makes an object 'temp' with current date and time var deadline = temp.getTime(); //stores the deadline time temp= new Date(); //stores the object of current date and time var currentTime = temp.getTime(); //gets the current time var timeDifference = deadline - currentTime; var day = Math.floor(timeDifference / (1000*60*60*24)); //calculates the difference in days from today till deadline var hour = Math.floor((timeDifference % (1000*60*60*24))/(1000*60*60)); //calculates the difference in hours from today till deadline var minute = Math.floor((timeDifference % (1000*60*60))/(1000*60)); //calculates the difference in minutes from today till deadline var sec = Math.floor((timeDifference % (1000*60))/1000); //calculates the difference in seconds from today till deadline //THIS WILL OUTPUT THE TIME EVERYTIME THIS FUNCTION IS CALLED document.getElementById(&quot;demo&quot;).innerHTML = days + &quot;d &quot; + hours + &quot;h &quot; + minutes + &quot;m &quot; + seconds + &quot;s &quot;; if(timeDifference &lt; 0){ clearInterval(x); document.getElementById(&quot;countdown&quot;).innerHTML = &quot;ENDED !!!&quot;; } } var x = setInterval(calCountDown(), 1000); &lt;/script&gt; </code></pre>
[ { "answer_id": 74634416, "author": "Piotr Rodak", "author_id": 227606, "author_profile": "https://Stackoverflow.com/users/227606", "pm_score": 3, "selected": true, "text": "ALTER TABLE table_name\nDROP COLUMN column_name;\n select 'alter table ' + quotename(table_schema) + '.' + quotename(table_name) + ' drop column ' + quotename(column_name) \nfrom information_schema.columns\nwhere 1=1\nand column_name in ('createdby', 'updatedby')\n" }, { "answer_id": 74644423, "author": "Tom McDonald", "author_id": 358574, "author_profile": "https://Stackoverflow.com/users/358574", "pm_score": 0, "selected": false, "text": "\\[CreatedAt\\][^\\,.]+\\,\n \\,([\\s\\r][\\s]+)+\\)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20411469/" ]
74,634,321
<p>In the new version of Android Studio (Flamingo | 2022.2.1 Canary 9) with the org.jetbrains.kotlin (1.8.0-Beta) plugin and 8.0.0-alpha09 gradle plugin, a new build suddenly gets this error:</p> <blockquote> <p>Build Type 'release' contains custom BuildConfig fields, but the feature is disabled.</p> </blockquote> <p>Is there a way to make this go away?</p>
[ { "answer_id": 74634322, "author": "fattire", "author_id": 3035127, "author_profile": "https://Stackoverflow.com/users/3035127", "pm_score": 2, "selected": false, "text": "gradle.properties android.defaults.buildfeatures.buildconfig=true\n buildConfigField BuildConfig.java build.gradle build.gradle.kts buildConfigField(\"String\", \"BUILD_TIME\", \"\\\"\" + System.currentTimeMillis().toString() + \"\\\"\")\n build.gradle.kts import com.android.build.api.variant.BuildConfigField\n android { ... } build.config.kts androidComponents {\n onVariants {\n it.buildConfigFields.put(\n \"BUILD_TIME\", BuildConfigField(\n \"String\", \"\\\"\" + System.currentTimeMillis().toString() + \"\\\"\", \"build timestamp\"\n )\n )\n }\n}\n private val buildDate = Date(BuildConfig.BUILD_TIME.toLong())\nLog.i(\"MyProgram\", \"This .apk was built on ${buildDate.toString()}\");\n gradle.properties BuildConfigField" }, { "answer_id": 74673405, "author": "SarathEXP ", "author_id": 7367757, "author_profile": "https://Stackoverflow.com/users/7367757", "pm_score": 0, "selected": false, "text": "android.defaults.buildfeatures.buildconfig=true gradle.properties" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3035127/" ]
74,634,347
<p>I'm a beginner and I'm trying to figure out a way to get the corresponding neighbors of an index in a 2D array.</p> <pre><code> public class Main { public static int[][] graph(){ int[][] myGraph = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20} }; return myGraph; } public static int[][] findNeighbors(int[][] graph, int x, int y){ for (int i = 0; i &lt; graph.length; i++){ for (int j = 0; j &lt; graph[i].length; j++){ } } } public static void main(String[] args) { System.out.println(findNeighbors(graph(), 2, 2)); } } </code></pre> <p>I created a simple 2D array above, and lets say I want to find the neighbors to index (2,2), so in this case given '13', I want to return the values '8', '18', '14, and '12'. I tried to use a nested for loop to get the values +- 1 but I couldn't really figure it out.</p>
[ { "answer_id": 74634322, "author": "fattire", "author_id": 3035127, "author_profile": "https://Stackoverflow.com/users/3035127", "pm_score": 2, "selected": false, "text": "gradle.properties android.defaults.buildfeatures.buildconfig=true\n buildConfigField BuildConfig.java build.gradle build.gradle.kts buildConfigField(\"String\", \"BUILD_TIME\", \"\\\"\" + System.currentTimeMillis().toString() + \"\\\"\")\n build.gradle.kts import com.android.build.api.variant.BuildConfigField\n android { ... } build.config.kts androidComponents {\n onVariants {\n it.buildConfigFields.put(\n \"BUILD_TIME\", BuildConfigField(\n \"String\", \"\\\"\" + System.currentTimeMillis().toString() + \"\\\"\", \"build timestamp\"\n )\n )\n }\n}\n private val buildDate = Date(BuildConfig.BUILD_TIME.toLong())\nLog.i(\"MyProgram\", \"This .apk was built on ${buildDate.toString()}\");\n gradle.properties BuildConfigField" }, { "answer_id": 74673405, "author": "SarathEXP ", "author_id": 7367757, "author_profile": "https://Stackoverflow.com/users/7367757", "pm_score": 0, "selected": false, "text": "android.defaults.buildfeatures.buildconfig=true gradle.properties" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20020829/" ]
74,634,383
<p>Let's say I have a cheap and less reliable datacenter A, and an expensive and more reliable datacenter B. I want to run Kafka in the <strong>most cost-effective</strong> way, even if that means risking data loss and/or downtime. I can run any number of brokers in either datacenter, but remember that costs need to be as low as possible.</p> <p>For this scenario, assume that no costs are incurred if brokers are not running. Also assume that producers/consumers run completely reliably with no concern for their cost.</p> <p>Two ideas I have are as follows:</p> <ol> <li>Provision two completely separate Kafka clusters, one in each datacenter, but keep the cluster in the more expensive datacenter (B) powered off. Upon detecting an outage in A, power on the cluster in B. Producers/consumers will have logic to switch between clusters.</li> <li>Run the Zookeeper cluster in B, with powered on brokers in A, and powered off brokers in B. If there is an outage in A, then brokers in B come online to pick up where A left off.</li> </ol> <p>Option 1 would be cheaper, but requires more complexity in the producers/consumers. Option 2 would be more expensive, but requires less complexity in the producers/consumers.</p> <p>Is Option 2 even possible? If there is an outage in A, is there any way to have brokers in B come online, get elected as leaders for the topics and have the producers/consumers seamlessly start sending to them? Again, data loss is okay and so is switchover downtime. But whatever option needs to not require manual intervention.</p> <p>Is there any other approach that I can consider?</p>
[ { "answer_id": 74634322, "author": "fattire", "author_id": 3035127, "author_profile": "https://Stackoverflow.com/users/3035127", "pm_score": 2, "selected": false, "text": "gradle.properties android.defaults.buildfeatures.buildconfig=true\n buildConfigField BuildConfig.java build.gradle build.gradle.kts buildConfigField(\"String\", \"BUILD_TIME\", \"\\\"\" + System.currentTimeMillis().toString() + \"\\\"\")\n build.gradle.kts import com.android.build.api.variant.BuildConfigField\n android { ... } build.config.kts androidComponents {\n onVariants {\n it.buildConfigFields.put(\n \"BUILD_TIME\", BuildConfigField(\n \"String\", \"\\\"\" + System.currentTimeMillis().toString() + \"\\\"\", \"build timestamp\"\n )\n )\n }\n}\n private val buildDate = Date(BuildConfig.BUILD_TIME.toLong())\nLog.i(\"MyProgram\", \"This .apk was built on ${buildDate.toString()}\");\n gradle.properties BuildConfigField" }, { "answer_id": 74673405, "author": "SarathEXP ", "author_id": 7367757, "author_profile": "https://Stackoverflow.com/users/7367757", "pm_score": 0, "selected": false, "text": "android.defaults.buildfeatures.buildconfig=true gradle.properties" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5859621/" ]
74,634,406
<p>Based on the script originally suggested by u/commandlineluser at reddit, I (as a Python novice) attempted to revise the original code to remove unwanted parts that vary across column values. The Python script involves creating a dictionary with keys and values and using a list comprehension with str.replace.</p> <p>(part of the original script by u/commandlineluser at reddit)</p> <p>extensions = &quot;dat&quot;, &quot;ssp&quot;, &quot;dta&quot;, &quot;v9&quot;, &quot;xlsx&quot;</p> <p>(The next line is my revision to the above part, and below is the complete code block)</p> <p>extensions = &quot;dat&quot;, &quot;ssp&quot;, &quot;dta&quot;, &quot;20dta&quot;, &quot;u20dta&quot;, &quot;f1dta&quot;, &quot;f2dta&quot;, &quot;v9&quot;, &quot;xlsx&quot;</p> <p>Some of the results are different than what I desire. Please see below (what I tried).</p> <pre><code>import pandas as pd import re data = {&quot;full_url&quot;: ['https://meps.ahrq.gov/data_files/pufs/h225/h225dat.zip', 'https://meps.ahrq.gov/data_files/pufs/h51bdat.zip', 'https://meps.ahrq.gov/data_files/pufs/h47f1dat.zip', 'https://meps.ahrq.gov/data_files/pufs/h225/h225ssp.zip', 'https://meps.ahrq.gov/data_files/pufs/h220i/h220if1dta.zip', 'https://meps.ahrq.gov/data_files/pufs/h220h/h220hv9.zip', 'https://meps.ahrq.gov/data_files/pufs/h220e/h220exlsx.zip', 'https://meps.ahrq.gov/data_files/pufs/h224/h224xlsx.zip', 'https://meps.ahrq.gov/data_files/pufs/h036brr/h36brr20dta.zip', 'https://meps.ahrq.gov/data_files/pufs/h036/h36u20dta.zip', 'https://meps.ahrq.gov/data_files/pufs/h197i/h197if1dta.zip', 'https://meps.ahrq.gov/data_files/pufs/h197i/h197if2dta.zip']} df = pd.DataFrame(data) extensions = [&quot;dat&quot;, &quot;ssp&quot;, &quot;dta&quot;, &quot;20dta&quot;, &quot;u20dta&quot;, &quot;f1dta&quot;, &quot;f2dta&quot;, &quot;v9&quot;, &quot;xlsx&quot;] replacements = dict.fromkeys((f&quot;{ext}[.]zip$&quot; for ext in extensions), &quot;&quot;) df[&quot;file_id&quot;] = df[&quot;full_url&quot;].str.split(&quot;/&quot;).str[-1].replace(replacements, regex=True) print(df[&quot;file_id&quot;]) </code></pre> <blockquote> <p>Annotated output</p> </blockquote> <pre><code>0 h225 (looks good) 1 h51b (looks good) 2 h47f1 (h47 -&gt; desired) 3 h225 (looks good) 4 h220if1 (h220i -&gt; desired) 5 h220h (looks good) 6 h220e (looks good) 7 h224 (looks good) 8 h36brr20 (h36brr -&gt; desired) 9 h36u20 (h36 -&gt; desired) 10 h197if1 (h197i -&gt; desired) 11 h197if2 (h197i -&gt; desired) </code></pre> <pre><code></code></pre>
[ { "answer_id": 74634322, "author": "fattire", "author_id": 3035127, "author_profile": "https://Stackoverflow.com/users/3035127", "pm_score": 2, "selected": false, "text": "gradle.properties android.defaults.buildfeatures.buildconfig=true\n buildConfigField BuildConfig.java build.gradle build.gradle.kts buildConfigField(\"String\", \"BUILD_TIME\", \"\\\"\" + System.currentTimeMillis().toString() + \"\\\"\")\n build.gradle.kts import com.android.build.api.variant.BuildConfigField\n android { ... } build.config.kts androidComponents {\n onVariants {\n it.buildConfigFields.put(\n \"BUILD_TIME\", BuildConfigField(\n \"String\", \"\\\"\" + System.currentTimeMillis().toString() + \"\\\"\", \"build timestamp\"\n )\n )\n }\n}\n private val buildDate = Date(BuildConfig.BUILD_TIME.toLong())\nLog.i(\"MyProgram\", \"This .apk was built on ${buildDate.toString()}\");\n gradle.properties BuildConfigField" }, { "answer_id": 74673405, "author": "SarathEXP ", "author_id": 7367757, "author_profile": "https://Stackoverflow.com/users/7367757", "pm_score": 0, "selected": false, "text": "android.defaults.buildfeatures.buildconfig=true gradle.properties" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1849365/" ]
74,634,440
<p>I have two 2d arrays, one containing float values, one containing bool. I want to create an array containing the mean values of the first matrix for each column considering only the values corresponding to False in the second matrix.</p> <p>For example:</p> <pre><code>A = [[1 3 5] [2 4 6] [3 1 0]] B = [[True False False] [False False False] [True True False]] result = [2, 3.5, 3.67] </code></pre>
[ { "answer_id": 74634632, "author": "gleerman", "author_id": 726156, "author_profile": "https://Stackoverflow.com/users/726156", "pm_score": 0, "selected": false, "text": "A = [[1, 3, 5],\n [2, 4, 6],\n [3, 1, 0]]\n\nB = [[True, False, False],\n [False, False, False],\n [True, True, False]]\n\nsums = [0]*len(A[0])\namounts = [0]*len(A[0])\nfor i in range(0, len(A)):\n for j in range(0, len(A[0])):\n sums[j] = sums[j] + (A[i][j] if not B[i][j] else 0)\n amounts[j] = amounts[j] + (1 if not B[i][j] else 0)\n\n\nresult = [sums[i]/amounts[i] for i in range(0, len(sums))]\n\nprint(result)\n" }, { "answer_id": 74634640, "author": "supersquires", "author_id": 18182675, "author_profile": "https://Stackoverflow.com/users/18182675", "pm_score": 0, "selected": false, "text": "numpy result = np.array([a_col[~b_col].mean() for a_col, b_col in zip(A.T,B.T)])\n result=[]\nfor i in range(len(A)):\n new_col = A[:,i][~B[:,i]]\n result.append(new_col.mean())\n" }, { "answer_id": 74634874, "author": "Nathan Furnal", "author_id": 9479128, "author_profile": "https://Stackoverflow.com/users/9479128", "pm_score": 3, "selected": true, "text": "B NaN nanmean NaN np.nanmean(np.where(~B, A, np.nan), axis=0)\n\n>>> array([2. , 3.5 , 3.66666667])\n" }, { "answer_id": 74634913, "author": "DarrylG", "author_id": 3066077, "author_profile": "https://Stackoverflow.com/users/3066077", "pm_score": 2, "selected": false, "text": "np.mean(A, where = ~B, axis = 0)\n>>> [2. 3.5 3.66666667]\n" }, { "answer_id": 74635020, "author": "Chrysophylaxs", "author_id": 9499196, "author_profile": "https://Stackoverflow.com/users/9499196", "pm_score": 0, "selected": false, "text": "import numpy as np\n\nresult = np.ma.array(A, mask=B).mean(axis=0).filled(fill_value=0)\n# Output:\n# array([2. , 3.5 , 3.66666667])\n fill_value B True" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13955154/" ]
74,634,456
<p>I am trying to access an object within an object using the key from another object.</p> <p>I have two objects:</p> <pre><code>const OutputReference = {Key1: &quot;Some Random String&quot;,Key2: &quot;Some Random String&quot;} const masterKey = { ... 'Key1':{ Label: &quot;Key 1&quot;, view: [1,2,3], }, 'Key2':{ Label: &quot;Key 2&quot;, view: [4,5,6], }, ... } </code></pre> <p>OutputReference contains multiple keys and values, and I want match these keys to the keys in masterKey to grab each corresponding 'view'. So far, I use this function to break out OutputReference into a key (k) and value (v):</p> <pre><code>Object.keys(OutpufReference).filter(([k,v])=&gt;{ ... //code here ... }); </code></pre> <p>I then want to grab &quot;view&quot; for the corresponding key and store it in an array. I used:</p> <pre><code>var tempArr = [] tempArr.push(masterKey.k.view) </code></pre> <p>Making the entire function:</p> <pre><code>Object.keys(OutpufReference).filter(([k,v])=&gt;{ ... var tempArr = [] tempArr.push(masterKey.k.view) ... }); </code></pre> <p>The issue is masterKey.k is coming back undefined. Note console.log(k) in this case outputs exactly this: Key1</p> <p><em>What I have tried (just to access k):</em></p> <pre><code>tempArr.push(masterKey.k) </code></pre> <pre><code>tempArr.push(masterKey[k]) </code></pre> <pre><code>var temp = JSON.stringify(k) tempArr.push(masterKey[temp]) </code></pre> <pre><code>Object.keys(masterKey).forEach((v,i)=&gt;{ if(v === k) //k is the index from mapping OutputReference tempArr.push(masterKey.v) }) </code></pre> <p>None of these work; all return an undefined object (masterKey.v, masterKey[temp], etc.). Note, when doing console.log() on each of these keys (temp, v, k), it outputs the string Key1. However, using</p> <pre><code>tempArr.push(masterKey.Key1) </code></pre> <p>Places the correct value in tempArr (Being the object Key1). This is not ideal however, as there are many keys and values in masterKey and OutputReference only contains a few of them.</p> <p><em>Where I looked</em></p> <p>I researched mozilla's guide on objects, which led me to my previous attempts <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects" rel="nofollow noreferrer">Mozilla</a>. I also researched this thread <a href="https://stackoverflow.com/questions/208105/how-do-i-remove-a-property-from-a-javascript-object">Deleting a property from a javascript object</a>. However it recommends what I have already tried.</p> <p>I see from this <a href="https://stackoverflow.com/questions/39115385/get-key-of-an-object-when-the-key-is-an-object">thread</a> that JavaScript objects can only use strings as keys, so why doesn't stringifying my key in</p> <pre><code>var temp = JSON.stringify(k) tempArr.push(masterKey[temp]) </code></pre> <p>work?</p> <p>The final output desired: The array tempArr containing every view that outputReference matched with masterKey (In this case: tempArr = [[1,2,3],[4,5,6])</p>
[ { "answer_id": 74634632, "author": "gleerman", "author_id": 726156, "author_profile": "https://Stackoverflow.com/users/726156", "pm_score": 0, "selected": false, "text": "A = [[1, 3, 5],\n [2, 4, 6],\n [3, 1, 0]]\n\nB = [[True, False, False],\n [False, False, False],\n [True, True, False]]\n\nsums = [0]*len(A[0])\namounts = [0]*len(A[0])\nfor i in range(0, len(A)):\n for j in range(0, len(A[0])):\n sums[j] = sums[j] + (A[i][j] if not B[i][j] else 0)\n amounts[j] = amounts[j] + (1 if not B[i][j] else 0)\n\n\nresult = [sums[i]/amounts[i] for i in range(0, len(sums))]\n\nprint(result)\n" }, { "answer_id": 74634640, "author": "supersquires", "author_id": 18182675, "author_profile": "https://Stackoverflow.com/users/18182675", "pm_score": 0, "selected": false, "text": "numpy result = np.array([a_col[~b_col].mean() for a_col, b_col in zip(A.T,B.T)])\n result=[]\nfor i in range(len(A)):\n new_col = A[:,i][~B[:,i]]\n result.append(new_col.mean())\n" }, { "answer_id": 74634874, "author": "Nathan Furnal", "author_id": 9479128, "author_profile": "https://Stackoverflow.com/users/9479128", "pm_score": 3, "selected": true, "text": "B NaN nanmean NaN np.nanmean(np.where(~B, A, np.nan), axis=0)\n\n>>> array([2. , 3.5 , 3.66666667])\n" }, { "answer_id": 74634913, "author": "DarrylG", "author_id": 3066077, "author_profile": "https://Stackoverflow.com/users/3066077", "pm_score": 2, "selected": false, "text": "np.mean(A, where = ~B, axis = 0)\n>>> [2. 3.5 3.66666667]\n" }, { "answer_id": 74635020, "author": "Chrysophylaxs", "author_id": 9499196, "author_profile": "https://Stackoverflow.com/users/9499196", "pm_score": 0, "selected": false, "text": "import numpy as np\n\nresult = np.ma.array(A, mask=B).mean(axis=0).filled(fill_value=0)\n# Output:\n# array([2. , 3.5 , 3.66666667])\n fill_value B True" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18748354/" ]
74,634,459
<p>I want to create a public and private key using curve25519 to encrypt some data in a file. It looks like iOS has something in the CryptoKit to allow clients to build something like this below. How can I use Curve25519 encryption in an Android project? I could not find any android-specific libraries that come with it. Any suggestion on how I can do this would be greatly appreciated.</p> <pre><code>let albusPrivateKey = Curve25519.KeyAgreement.PrivateKey() let albusPublicKeyData = albusPrivateKey.publicKey.rawRepresentation let harryPrivateKey = Curve25519.KeyAgreement.PrivateKey() let harryPublicKeyData = harryPrivateKey.publicKey.rawRepresentation </code></pre>
[ { "answer_id": 74634632, "author": "gleerman", "author_id": 726156, "author_profile": "https://Stackoverflow.com/users/726156", "pm_score": 0, "selected": false, "text": "A = [[1, 3, 5],\n [2, 4, 6],\n [3, 1, 0]]\n\nB = [[True, False, False],\n [False, False, False],\n [True, True, False]]\n\nsums = [0]*len(A[0])\namounts = [0]*len(A[0])\nfor i in range(0, len(A)):\n for j in range(0, len(A[0])):\n sums[j] = sums[j] + (A[i][j] if not B[i][j] else 0)\n amounts[j] = amounts[j] + (1 if not B[i][j] else 0)\n\n\nresult = [sums[i]/amounts[i] for i in range(0, len(sums))]\n\nprint(result)\n" }, { "answer_id": 74634640, "author": "supersquires", "author_id": 18182675, "author_profile": "https://Stackoverflow.com/users/18182675", "pm_score": 0, "selected": false, "text": "numpy result = np.array([a_col[~b_col].mean() for a_col, b_col in zip(A.T,B.T)])\n result=[]\nfor i in range(len(A)):\n new_col = A[:,i][~B[:,i]]\n result.append(new_col.mean())\n" }, { "answer_id": 74634874, "author": "Nathan Furnal", "author_id": 9479128, "author_profile": "https://Stackoverflow.com/users/9479128", "pm_score": 3, "selected": true, "text": "B NaN nanmean NaN np.nanmean(np.where(~B, A, np.nan), axis=0)\n\n>>> array([2. , 3.5 , 3.66666667])\n" }, { "answer_id": 74634913, "author": "DarrylG", "author_id": 3066077, "author_profile": "https://Stackoverflow.com/users/3066077", "pm_score": 2, "selected": false, "text": "np.mean(A, where = ~B, axis = 0)\n>>> [2. 3.5 3.66666667]\n" }, { "answer_id": 74635020, "author": "Chrysophylaxs", "author_id": 9499196, "author_profile": "https://Stackoverflow.com/users/9499196", "pm_score": 0, "selected": false, "text": "import numpy as np\n\nresult = np.ma.array(A, mask=B).mean(axis=0).filled(fill_value=0)\n# Output:\n# array([2. , 3.5 , 3.66666667])\n fill_value B True" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8207093/" ]
74,634,468
<p>So here's a simple algorithmic problem,</p> <blockquote> <p>Given a list of integers, check if there are two numbers in this list that when added together give eight (8).</p> </blockquote> <p>Here's my solution,</p> <pre><code>import java.util.List; public class Main { static List&lt;Integer&gt; arrayOne = List.of(1,3,6,9); static List&lt;Integer&gt; arrayTwo = List.of(1,6,2,10); static boolean validateArray(int result, List&lt;Integer&gt; array){ for (int i = 0; i&lt;array.size() - 1; i++){ for (int j = i + 1; j &lt; array.size(); j ++){ int value1 = array.get(i); int value2 = array.get(j); if(value1 + value2 == result){ return true; } } } return false; } public static void main(String[] args) { System.out.println(validateArray(8, arrayTwo)); } } </code></pre> <p>This works fine. What I'm trying to learn is how to rewrite this code in Java 8. As in what the different options with the loops in Java 8.</p>
[ { "answer_id": 74634632, "author": "gleerman", "author_id": 726156, "author_profile": "https://Stackoverflow.com/users/726156", "pm_score": 0, "selected": false, "text": "A = [[1, 3, 5],\n [2, 4, 6],\n [3, 1, 0]]\n\nB = [[True, False, False],\n [False, False, False],\n [True, True, False]]\n\nsums = [0]*len(A[0])\namounts = [0]*len(A[0])\nfor i in range(0, len(A)):\n for j in range(0, len(A[0])):\n sums[j] = sums[j] + (A[i][j] if not B[i][j] else 0)\n amounts[j] = amounts[j] + (1 if not B[i][j] else 0)\n\n\nresult = [sums[i]/amounts[i] for i in range(0, len(sums))]\n\nprint(result)\n" }, { "answer_id": 74634640, "author": "supersquires", "author_id": 18182675, "author_profile": "https://Stackoverflow.com/users/18182675", "pm_score": 0, "selected": false, "text": "numpy result = np.array([a_col[~b_col].mean() for a_col, b_col in zip(A.T,B.T)])\n result=[]\nfor i in range(len(A)):\n new_col = A[:,i][~B[:,i]]\n result.append(new_col.mean())\n" }, { "answer_id": 74634874, "author": "Nathan Furnal", "author_id": 9479128, "author_profile": "https://Stackoverflow.com/users/9479128", "pm_score": 3, "selected": true, "text": "B NaN nanmean NaN np.nanmean(np.where(~B, A, np.nan), axis=0)\n\n>>> array([2. , 3.5 , 3.66666667])\n" }, { "answer_id": 74634913, "author": "DarrylG", "author_id": 3066077, "author_profile": "https://Stackoverflow.com/users/3066077", "pm_score": 2, "selected": false, "text": "np.mean(A, where = ~B, axis = 0)\n>>> [2. 3.5 3.66666667]\n" }, { "answer_id": 74635020, "author": "Chrysophylaxs", "author_id": 9499196, "author_profile": "https://Stackoverflow.com/users/9499196", "pm_score": 0, "selected": false, "text": "import numpy as np\n\nresult = np.ma.array(A, mask=B).mean(axis=0).filled(fill_value=0)\n# Output:\n# array([2. , 3.5 , 3.66666667])\n fill_value B True" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20395420/" ]
74,634,484
<p>I am using javascript to check if a pdf or doc extension is found in the item of a list. If it is, I want to remove that element. Is there an easy way to make this work. I can detect if its there. It returns true, but not sure how to select that specific element.</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>if (document.querySelector("#myList").innerHTML.includes(".pdf") || (".doc")) { //find and remove item }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="myList"&gt; &lt;div class="style"&gt; &lt;img class="myIm" src="/v2l/le/1196xx/discussions/posts/26adsd89/ViewAttachment?fileId=273383625"&gt; &lt;div class=""&gt;photoTest.jpg&lt;/div&gt; &lt;/div&gt; &lt;div class="style"&gt; &lt;img class="myImg-style" src="/v2l/le/11961xx/discussions/posts/26ss489/ViewAttachment?fileId=27773626"&gt; &lt;div class=""&gt;dog.png&lt;/div&gt; &lt;/div&gt; &lt;div class="style"&gt; &lt;img class="myImg-style" src="/v2l/common/viewFile.v2lfile/Im/638054389092471030/testpde.pdf?ou=11961xxx&amp;amp;fid=ZTZlMDllZGEtMWM0Yi00ZWRlLWI5ODAtMjhhNWRmYjc1MzBmO0dyYXBoaWNEZXNpZ25fT25saW5lX0NvdXJzZU91dGxpbmUucGRmOzU1ODY0MDE"&gt; &lt;div class=""&gt;testpde.pdf&lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74634515, "author": "Dimava", "author_id": 5734961, "author_profile": "https://Stackoverflow.com/users/5734961", "pm_score": -1, "selected": false, "text": "function hasExtOfList(src, list) {\n return list.some(ext => src.includes(ext))\n}\n\nhasExtOfList(\n document.querySelector(\"#myList\").innerHTML,\n [\".pdf\", \".doc\"]\n)\n Set" }, { "answer_id": 74634555, "author": "Serhiy Mamedov", "author_id": 10509015, "author_profile": "https://Stackoverflow.com/users/10509015", "pm_score": -1, "selected": false, "text": "const el = document.querySelector(\"#myList\");\nel.parentElement.removeChild(el);\n" }, { "answer_id": 74634703, "author": "Roko C. Buljan", "author_id": 383904, "author_profile": "https://Stackoverflow.com/users/383904", "pm_score": 1, "selected": true, "text": ".pdf .doc // DOM utility functions:\n\nconst el = (sel, par) => (par || document).querySelector(sel);\nconst els = (sel, par) => (par || document).querySelectorAll(sel);\n\n// Utility functions:\n\nconst isDocument = (fileName) => /\\.(pdf|doc)$/.test(fileName);\n\n// Task: Remove element if child text is document\n\nels(\".style\").forEach(elStyle => {\n const elFile = el(\"div\", elStyle);\n const text = elFile.textContent.trim();\n isDocument(text) && elFile.remove();\n}); <div id=\"myList\">\n <div class=\"style\">\n <img class=\"myIm\" src=\"/v2l/le/1196xx/discussions/posts/26adsd89/ViewAttachment?fileId=273383625\">\n <div class=\"\">photoTest.jpg</div>\n </div>\n <div class=\"style\">\n <img class=\"myImg-style\" src=\"/v2l/le/11961xx/discussions/posts/26ss489/ViewAttachment?fileId=27773626\">\n <div class=\"\">dog.png</div>\n </div>\n <div class=\"style\">\n <img class=\"myImg-style\" src=\"/v2l/common/viewFile.v2lfile/Im/638054389092471030/testpde.pdf?ou=11961xxx&amp;fid=ZTZlMDllZGEtMWM0Yi00ZWRlLWI5ODAtMjhhNWRmYjc1MzBmO0dyYXBoaWNEZXNpZ25fT25saW5lX0NvdXJzZU91dGxpbmUucGRmOzU1ODY0MDE\">\n <div class=\"\">testpde.pdf</div>\n </div>\n</div>" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4570185/" ]
74,634,504
<p>I'm writing a library with both a C and C++ API. I need to write many enums in the C API and wrap them in the C++ API.</p> <pre class="lang-c prettyprint-override"><code>typedef enum PREFIX_SomeType { PREFIX_SOME_TYPE_A, PREFIX_SOME_TYPE_B, PREFIX_SOME_TYPE_C, } PREFIX_SomeType; </code></pre> <p>In the C++ wrapper header I'd like to have a similar enum without name prefixes, since the C++ wrapping API uses a namespace called PREFIX.</p> <pre class="lang-cpp prettyprint-override"><code>namespace PREFIX { enum SomeType : int { SOME_TYPE_A, SOME_TYPE_B, SOME_TYPE_C, }; } </code></pre> <p>Since these two enums are different enums they don't cleanly convert to one another. Whenever I define a struct in the C api containing enums, I'd like to use a C++ alias.</p> <pre class="lang-c prettyprint-override"><code>typedef struct PREFIX_ApiStruct { PREFIX_SomeType type; // ... } PREFIX_ApiStruct; </code></pre> <p>And in the C++ wrapper:</p> <pre class="lang-cpp prettyprint-override"><code>using namespace PREFIX { using ApiStruct = PREFIX_ApiStruct; } </code></pre> <p>But, when trying to use the C++ wrapper we cannot assign a C++ enum...</p> <pre class="lang-cpp prettyprint-override"><code>ApiStruct instance; instance.type = SOME_TYPE_A; // Error! </code></pre> <p>Is there a way to let a C++ user not write type out PREFIX_ and instead use C++ namespaces, without requiring explicit casts?</p>
[ { "answer_id": 74635006, "author": "David Ranieri", "author_id": 1606345, "author_profile": "https://Stackoverflow.com/users/1606345", "pm_score": 1, "selected": false, "text": "#define SOME_TYPE \\\n X(SOME_TYPE_A) \\\n X(SOME_TYPE_B) \\\n X(SOME_TYPE_C)\n typedef enum PREFIX_SomeType\n{\n#define X(type) PREFIX_##type,\n SOME_TYPE\n#undef X\n} PREFIX_SomeType;\n namespace PREFIX\n{\n\nenum SomeType : int\n{\n#define X(type) type,\n SOME_TYPE\n#undef X\n};\n\n}\n" }, { "answer_id": 74635705, "author": "Cecil", "author_id": 6410671, "author_profile": "https://Stackoverflow.com/users/6410671", "pm_score": 0, "selected": false, "text": "inline constexpr PREFIX_SomeType SOME_TYPE_A = PREFIX_SOME_TYPE_A;\ninline constexpr PREFIX_SomeType SOME_TYPE_B = PREFIX_SOME_TYPE_B;\ninline constexpr PREFIX_SomeType SOME_TYPE_C = PREFIX_SOME_TYPE_C;\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6410671/" ]
74,634,540
<p>I am trying to create an array of 10 for each item I have, but then put those arrays of 10 into a larger array diagonally with zeros filling the missing spaces.</p> <p>Here is an example of what I am looking for, but only with arrays of 3.</p> <pre><code>import numpy as np arr = np.tri(3,3) arr </code></pre> <p>This creates an array that looks like this:</p> <pre><code>[[1,0,0], [1,1,0], [1,1,1]] </code></pre> <p>But I need an array of 10 * n that looks like this: (using arrays a 3 for example here, with n=2)</p> <p>{1,0,0,0,0,0, 1,1,0,0,0,0, 1,1,1,0,0,0, 0,0,0,1,0,0, 0,0,0,1,1,0, 0,0,0,1,1,1}</p> <p>Any help would be appreciated, thanks!</p> <p>I have also tried</p> <pre><code>df_arr2 = pd.concat([df_arr] * (n), ignore_index=True) df_arr3 = pd.concat([df_arr2] *(n), axis=1, ignore_index=True) </code></pre> <p>But this repeats the matrix across all rows and columns, when I only want the diagnonal ones.</p>
[ { "answer_id": 74635006, "author": "David Ranieri", "author_id": 1606345, "author_profile": "https://Stackoverflow.com/users/1606345", "pm_score": 1, "selected": false, "text": "#define SOME_TYPE \\\n X(SOME_TYPE_A) \\\n X(SOME_TYPE_B) \\\n X(SOME_TYPE_C)\n typedef enum PREFIX_SomeType\n{\n#define X(type) PREFIX_##type,\n SOME_TYPE\n#undef X\n} PREFIX_SomeType;\n namespace PREFIX\n{\n\nenum SomeType : int\n{\n#define X(type) type,\n SOME_TYPE\n#undef X\n};\n\n}\n" }, { "answer_id": 74635705, "author": "Cecil", "author_id": 6410671, "author_profile": "https://Stackoverflow.com/users/6410671", "pm_score": 0, "selected": false, "text": "inline constexpr PREFIX_SomeType SOME_TYPE_A = PREFIX_SOME_TYPE_A;\ninline constexpr PREFIX_SomeType SOME_TYPE_B = PREFIX_SOME_TYPE_B;\ninline constexpr PREFIX_SomeType SOME_TYPE_C = PREFIX_SOME_TYPE_C;\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20454313/" ]
74,634,598
<p>For some reason Rust Analyzer isn't generating a warning for undefined variables. Do I need to tweak some settings somewhere?</p> <p><a href="https://i.stack.imgur.com/YHdCN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YHdCN.png" alt="enter image description here" /></a></p> <p>I'm also not getting warnings for unused variables, unimported crates, etc.</p> <p>Edit: Tested this out with a new workspace. Both <code>cargo check</code> and Rust Analyzer work. It reports a single intentional error. When I run <code>cargo check</code> in the first workspace, it reports a lot of errors in the <code>~/.cargo</code> directory, and none in the current workspace. Perhaps a crate I am using has errors and is locking up <code>cargo check</code> before it can get around to checking the files in my directory?</p>
[ { "answer_id": 74635006, "author": "David Ranieri", "author_id": 1606345, "author_profile": "https://Stackoverflow.com/users/1606345", "pm_score": 1, "selected": false, "text": "#define SOME_TYPE \\\n X(SOME_TYPE_A) \\\n X(SOME_TYPE_B) \\\n X(SOME_TYPE_C)\n typedef enum PREFIX_SomeType\n{\n#define X(type) PREFIX_##type,\n SOME_TYPE\n#undef X\n} PREFIX_SomeType;\n namespace PREFIX\n{\n\nenum SomeType : int\n{\n#define X(type) type,\n SOME_TYPE\n#undef X\n};\n\n}\n" }, { "answer_id": 74635705, "author": "Cecil", "author_id": 6410671, "author_profile": "https://Stackoverflow.com/users/6410671", "pm_score": 0, "selected": false, "text": "inline constexpr PREFIX_SomeType SOME_TYPE_A = PREFIX_SOME_TYPE_A;\ninline constexpr PREFIX_SomeType SOME_TYPE_B = PREFIX_SOME_TYPE_B;\ninline constexpr PREFIX_SomeType SOME_TYPE_C = PREFIX_SOME_TYPE_C;\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13131208/" ]
74,634,672
<p>I'm using Trino/Presto and trying to unnest array column which can contain rows with empty or null arrays which results in such rows missing:</p> <pre><code>with table1(id, arr) as ( values (1, array[1,2,3]), (2, array[]), (3, array[42]), (4, null) ) select id, a from table1 cross join unnest(arr) as t(a); </code></pre> <p>And output:</p> <pre><code> id | a ----+---- 1 | 1 1 | 2 1 | 3 3 | 42 </code></pre> <p>As you see ids 2 and 4 are missing. Is it possible to rewrite query so they will be present?</p>
[ { "answer_id": 74634706, "author": "Guru Stron", "author_id": 2501279, "author_profile": "https://Stackoverflow.com/users/2501279", "pm_score": 2, "selected": true, "text": "unnest null unnest cross join -- query\nselect id, a\nfrom table1,\nunnest(arr, array[1]) as t(a, ignored);\n" }, { "answer_id": 74634855, "author": "Martin Traverso", "author_id": 2958752, "author_profile": "https://Stackoverflow.com/users/2958752", "pm_score": 0, "selected": false, "text": "UNNEST LEFT JOIN CROSS JOIN WITH table1(id, arr) AS (\n VALUES (1, array[1,2,3]),\n (2, array[]),\n (3, array[42]),\n (4, null)\n)\nSELECT id, a\nFROM table1\nLEFT JOIN UNNEST(arr) AS t(a) ON true;\n id | a\n----+------\n 1 | 1\n 1 | 2\n 1 | 3\n 2 | NULL\n 3 | 42\n 4 | NULL\n(6 rows)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20472928/" ]
74,634,692
<p>I have a class template, that creates a class with two members:</p> <pre><code>template&lt;typename coordinateType, typename ...DataTypes&gt; class Object{ public: std::tuple&lt;coordinateType, coordinateType, coordinateType&gt; position; std::tuple&lt;std::vector&lt;DataTypes&gt;...&gt; plantData; }; </code></pre> <p>The issue is, rather than calling</p> <pre><code>auto myObject = Object&lt;float, int, int, int&gt;(); </code></pre> <p>for an instance of Object with 3 ints of data, I want to clean this up and use two separate templates, without the unrelated &quot;float&quot; as the first argument.</p> <p>Is there a way to implement this class so that it would be the equivalent of:</p> <pre><code>auto myObject = Object&lt;float&gt;(); myObject.track&lt;int, int, int&gt;(); </code></pre> <p>And if not, is it possible to separate those two template arguments in any way, or am I stuck with grouping them together?</p>
[ { "answer_id": 74634706, "author": "Guru Stron", "author_id": 2501279, "author_profile": "https://Stackoverflow.com/users/2501279", "pm_score": 2, "selected": true, "text": "unnest null unnest cross join -- query\nselect id, a\nfrom table1,\nunnest(arr, array[1]) as t(a, ignored);\n" }, { "answer_id": 74634855, "author": "Martin Traverso", "author_id": 2958752, "author_profile": "https://Stackoverflow.com/users/2958752", "pm_score": 0, "selected": false, "text": "UNNEST LEFT JOIN CROSS JOIN WITH table1(id, arr) AS (\n VALUES (1, array[1,2,3]),\n (2, array[]),\n (3, array[42]),\n (4, null)\n)\nSELECT id, a\nFROM table1\nLEFT JOIN UNNEST(arr) AS t(a) ON true;\n id | a\n----+------\n 1 | 1\n 1 | 2\n 1 | 3\n 2 | NULL\n 3 | 42\n 4 | NULL\n(6 rows)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9776926/" ]
74,634,699
<p>I need a code to get the first and second numbers from the PHP string.</p> <p><code>$string = &quot;ACCESS_NUMBER:160375356:13176570247&quot;; $stringOne = &quot;&quot;; $stringTwo = &quot;&quot;;</code> I need a code that can get 160375356 and store it in $stringOne and also get this 13176570247 and store it in string $stringTwo</p> <p>I don't want to count the strings, I need a code that can get them via this: sign</p>
[ { "answer_id": 74634731, "author": "Harley Swift", "author_id": 12348779, "author_profile": "https://Stackoverflow.com/users/12348779", "pm_score": 0, "selected": false, "text": "$pizza = \"piece1 piece2 piece3 piece4 piece5 piece6\";\n$pieces = explode(\" \", $pizza);\necho $pieces[0]; // piece1\necho $pieces[1]; // piece2\n" }, { "answer_id": 74634748, "author": "Łukasz Piotr Łuczak", "author_id": 20633817, "author_profile": "https://Stackoverflow.com/users/20633817", "pm_score": 0, "selected": false, "text": "<?php \n$string = \"ACCESS_NUMBER:160375356:13176570247\";\n$parts = explode(':', $string);\n$stringOne = $parts[1];\n$stringTwo = $parts[2];\n?>\n explode explode('#', 'Apple#Banana#Orange')\n" }, { "answer_id": 74634823, "author": "KIKO Software", "author_id": 3986005, "author_profile": "https://Stackoverflow.com/users/3986005", "pm_score": 2, "selected": false, "text": "<?php \n$string = \"ACCESS_NUMBER:160375356:13176570247\";\n[, $stringOne, $stringTwo] = explode(':', $string);\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20520274/" ]
74,634,781
<p>I am a beginner programmer, working on a project for an online course. I am trying to build a tip calculator. I want it to take input from the user for three values: Bill total, how many are splitting the bill, and the percent they would wish to tip. My conditional statement only has one if:</p> <p>if meal_price &gt;= 0.01: example(example) else: example(example)</p> <p>There are no elifs, only an else clause, stating to the user to enter only a numerical value. The program is designed to loop if the else clause runs, or continue if the 'if' condition is met. I would like this program to be completely user-friendly and run regardless of what is typed in. But instead of the else clause being ran when a user enters a string value, the terminal returns an error. How would I check the datatype the user enters, and run my conditional statement based off of that instead of the literal user response?</p> <p>Note, I've tried:</p> <ul> <li>if isinstance(meal_price, float):</li> <li>Converting the user input into a string, but then the conditional statement becomes the problem</li> </ul> <p>Thank you all for the help. I started my coding journey about 3 months ago and I am trying to learn as much as I can. Any feedback or criticism is GREATLY appreciated.</p> <p><a href="https://i.stack.imgur.com/LCKAd.jpg" rel="nofollow noreferrer">enter image description here</a></p> <pre><code>def calculation(): tip_percent = percentage / 100 tip_amount = meal_price * tip_percent meal_and_tip = tip_amount + meal_price total_to_return = meal_and_tip / to_split return total_to_return print(&quot;\nWelcome to the \&quot;Bill Tip Calculator\&quot;!&quot;) print(&quot;All you need to do is enter the bill, the amount of people splitting it, and the percent you would like to tip.\n&quot;) while True: print(&quot;First, what was the total for the bill?&quot;) meal_price = float(input(&quot;Bill (Numerical values only): &quot;)) if meal_price &gt;= 0.01: meal_price2 = str(meal_price) print(&quot;\nPerfect. The total is &quot; + &quot;$&quot; + meal_price2 + &quot;.&quot;) while True: print(&quot;\nHow many people are splitting the bill?&quot;) to_split = int(input(&quot;People: &quot;)) if to_split &gt;= 1: to_split2 = str(to_split) print(&quot;\nAwesome, there is&quot;, &quot;\&quot;&quot; + to_split2 + &quot;\&quot;&quot;, &quot;person(s) paying.&quot;) while True: print(&quot;\nWhat percent would you like to tip?&quot;) percentage = float(input(&quot;Percentage (Numerical values only, include decimals): &quot;)) if percentage &gt;= 0: percentage2 = str(percentage) print(&quot;\nGot it.&quot;, percentage2 + '%.') calculation() total = str(calculation()) #total2 = str(total) print(&quot;\n\nEach person pays&quot;, &quot;$&quot; + total + &quot;.&quot;) exit() else: print(&quot;\nPlease enter only a numerical value. No decimals or special characters.&quot;) else: print(&quot;\nPlease respond with a numerical value greater than 0.\n&quot;) else: print(&quot;Please remember to enter only a numerical value.\n&quot;) </code></pre> <p>Included image snapshot in case copy &amp; paste isn't accurate.</p>
[ { "answer_id": 74634731, "author": "Harley Swift", "author_id": 12348779, "author_profile": "https://Stackoverflow.com/users/12348779", "pm_score": 0, "selected": false, "text": "$pizza = \"piece1 piece2 piece3 piece4 piece5 piece6\";\n$pieces = explode(\" \", $pizza);\necho $pieces[0]; // piece1\necho $pieces[1]; // piece2\n" }, { "answer_id": 74634748, "author": "Łukasz Piotr Łuczak", "author_id": 20633817, "author_profile": "https://Stackoverflow.com/users/20633817", "pm_score": 0, "selected": false, "text": "<?php \n$string = \"ACCESS_NUMBER:160375356:13176570247\";\n$parts = explode(':', $string);\n$stringOne = $parts[1];\n$stringTwo = $parts[2];\n?>\n explode explode('#', 'Apple#Banana#Orange')\n" }, { "answer_id": 74634823, "author": "KIKO Software", "author_id": 3986005, "author_profile": "https://Stackoverflow.com/users/3986005", "pm_score": 2, "selected": false, "text": "<?php \n$string = \"ACCESS_NUMBER:160375356:13176570247\";\n[, $stringOne, $stringTwo] = explode(':', $string);\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20650051/" ]
74,634,784
<p>What am I doing wrong?</p> <p>This is all the code needed to reproduce.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd g = pd.Grouper('datetime', freq='D') </code></pre> <p>Result:</p> <pre class="lang-none prettyprint-override"><code>--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In [1], line 2 1 import pandas as pd ----&gt; 2 g = pd.Grouper('datetime', freq='D') TypeError: TimeGrouper.__init__() got multiple values for argument 'freq' </code></pre> <p>Pandas version 1.5.1, Python version 3.10.6.</p>
[ { "answer_id": 74634898, "author": "cottontail", "author_id": 19123103, "author_profile": "https://Stackoverflow.com/users/19123103", "pm_score": 1, "selected": false, "text": "key g = pd.Grouper(key='datetime', freq='D')\nprint(type(g))\n# pandas.core.resample.TimeGrouper\n TimeGrouper freq Grouper g1 = pd.Grouper('datetime', None, pd.offsets.Day())\nprint(type(g1))\n# pandas.core.groupby.grouper.Grouper\n g1.freq pd._libs.tslibs.offsets.Day" }, { "answer_id": 74635314, "author": "wjandrea", "author_id": 4518341, "author_profile": "https://Stackoverflow.com/users/4518341", "pm_score": 3, "selected": true, "text": "Grouper.__new__() TimeGrouper freq freq TimeGrouper.__init__() freq key key **kwargs Grouper.__init__() key g = pd.Grouper(key='datetime', freq='D')\n None pd.Grouper('datetime', None, 'D', origin='epoch')\n TypeError: __init__() got an unexpected keyword argument 'origin'\n Grouper df = pd.DataFrame({\n 'datetime': pd.to_datetime([\n '2022-11-29T15', '2022-11-30T15', '2022-11-30T16']),\n 'v': [1, 2, 3]})\n >>> g = pd.Grouper('datetime', None, 'D')\n>>> df.groupby(g).sum()\n v\ndatetime \n2022-11-29 15:00:00 1\n2022-11-30 15:00:00 2\n2022-11-30 16:00:00 3\n >>> g1 = pd.Grouper(key='datetime', freq='D')\n>>> df.groupby(g1).sum()\n v\ndatetime \n2022-11-29 1\n2022-11-30 5\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7644741/" ]
74,634,786
<p>I have a class that can accept arithmetic types and std::complex. A simplified code of the class is</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;complex&gt; template&lt;typename T&gt; struct is_complex : std::false_type {}; template&lt;typename T&gt; struct is_complex&lt;std::complex&lt;T&gt;&gt; : std::true_type {}; template&lt;class T&gt; struct Foo { void foo(typename T::value_type t) requires (is_complex&lt;T&gt;::value) { } }; </code></pre> <p>Now, I would like to take the internal type of <code>std::complex</code> and use it as the type of the parameters in the <code>foo</code> function.For example, if T is std::complex&lt;<strong>double</strong>&gt;, then I want the parameter types to be <code>double</code>.</p> <p><strong>This function should only be available when T is indeed <code>std::complex</code></strong>.</p> <p>I thought I could use <code>typename T::value_type</code> as the parameter type, since <code>std::complex</code> has a typedef <code>value_type</code>. Plus, I thought using <code>requires</code> here would avoid T to be substitued in this function in case T wasn't std::complex. Silly me. The issue is that whenever I create a <code>Foo&lt;FundamentalType&gt;</code> the code breaks, since fundamentals don't have <code>::value_type</code>.</p> <pre class="lang-cpp prettyprint-override"><code>int main() { Foo&lt;int&gt; obj; // Breaks the code. //obj.foo(4); // Function shouldn't be considered in overload resolution ideally... Foo&lt;std::complex&lt;int&gt;&gt; obj2; // Works obj2.foo(4); // Works as expected } </code></pre> <p>Ideally, I would like the substitution of T to be ignored for this function in case T is not std::complex. Is that possible? If not, how can I circumvent this?</p>
[ { "answer_id": 74634872, "author": "HolyBlackCat", "author_id": 2752075, "author_profile": "https://Stackoverflow.com/users/2752075", "pm_score": 1, "selected": false, "text": "requires struct nullptr_value_type {using value_type = std::nullptr_t;};\n using elem_or_null_t = typename std::conditional_t<is_complex<T>::value, T, nullptr_value_type>::value_type;\n \nvoid foo(elem_or_null_t t)\nrequires (is_complex<T>::value)\n{}\n" }, { "answer_id": 74634879, "author": "lorro", "author_id": 6292621, "author_profile": "https://Stackoverflow.com/users/6292621", "pm_score": 2, "selected": true, "text": "is_complex template<typename T> struct complex_value_type {};\ntemplate<typename T> struct complex_value_type<std::complex<T>> { using type = T; };\n\ntemplate<typename T>\nusing complex_value_type_t = typename complex_value_type<T>::type;\n complex_value_type_t<T> template<class T>\nstruct Foo {\n template<typename T_ = T>\n void foo(complex_value_type_t<T_> t)\n requires (is_complex<T_>::value) {\n }\n};\n requires complex_value_type_t<T> complex<T>" }, { "answer_id": 74634900, "author": "Botond Horváth", "author_id": 16825566, "author_profile": "https://Stackoverflow.com/users/16825566", "pm_score": 0, "selected": false, "text": "#include <complex>\n\ntemplate<template<class> class T> struct is_complex : std::false_type {};\ntemplate<> struct is_complex<std::complex> : std::true_type {};\n\ntemplate<template<class> class T>\nstruct Foo {\n void foo(typename T<double>::value_type t)//could be typename<T<TT>> if you made foo a templated function\n requires (is_complex<T>::value) {\n }\n};\nint main(){\n Foo<std::complex> f;\n};\n double Foo foo" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15112100/" ]
74,634,801
<p>Im still new to javascript and ajax and all that. Im working on a project for my web dev course and have been stuck on this for a while now. The professor hasnt been of any help.</p> <p>I am making a data page. On the index there are 4 radio buttons, each on loading another html page into the div. Each of these other pages have data sets and allow for searches on a few of the fields. The issue is that when these pages are called by the index page, none of the functions work on them anymore. The functions work on them when I open the page alone and not through the index.</p> <p>This is the Index Page html and javascript</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 name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt; &lt;title&gt;Index&lt;/title&gt; &lt;link href=&quot;index.css&quot; rel=&quot;stylesheet&quot;&gt; &lt;script src=&quot;index.js&quot;&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt; Welcome to Data Sets - Calgary&lt;/h1&gt; &lt;table id=&quot;buttons&quot;&gt; &lt;tr&gt;&lt;td&gt;Find Calgary Libraries&lt;/td&gt;&lt;td&gt;Find Traffic Incidents In Calgary&lt;/td&gt;&lt;td&gt;Search Calgary Building Permits&lt;/td&gt;&lt;td&gt;Search Calgary Crimes&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;p&gt;Clicking on this loads a search for Calgary Libraries&lt;/p&gt;&lt;/td&gt;&lt;td&gt;&lt;p&gt;Clicking on this loads a search for Calgary traffic incidents&lt;/p&gt;&lt;/td&gt;&lt;td&gt;&lt;p&gt;Clicking on this loads a search for Calgary Building permits&lt;/p&gt;&lt;/td&gt;&lt;td&gt;&lt;p&gt;Clicking on this loads a search for Calgary Crimes&lt;/p&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;input type=&quot;radio&quot; id=&quot;calgLib&quot; name=&quot;butt&quot;&gt;&lt;/td&gt;&lt;td&gt;&lt;input type=&quot;radio&quot; id=&quot;calgTraff&quot; name=&quot;butt&quot;&gt;&lt;/td&gt;&lt;td&gt;&lt;input type=&quot;radio&quot; id=&quot;calgBuild&quot; name=&quot;butt&quot;&gt;&lt;/td&gt;&lt;td&gt;&lt;input type=&quot;radio&quot; id=&quot;calgCrime&quot; name=&quot;butt&quot;&gt;&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; &lt;div class=&quot;buttonresults&quot; id=&quot;buttonresults&quot;&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <pre><code>window.onload=registerListeners; function registerListeners() { var asd; asd=document.getElementById(&quot;calgLib&quot;); asd.addEventListener(&quot;change&quot;, function () { getContent(&quot;liblocations.html&quot;);}, false); asd=document.getElementById(&quot;calgTraff&quot;); asd.addEventListener(&quot;change&quot;, function () { getContent(&quot;trafficincident.html&quot;);}, false); asd=document.getElementById(&quot;calgBuild&quot;); asd.addEventListener(&quot;change&quot;, function () { getContent(&quot;buildpermit.html&quot;);}, false); asd=document.getElementById(&quot;calgCrime&quot;); asd.addEventListener(&quot;change&quot;, function () { getContent(&quot;commcrime.html&quot;);}, false); } function getContent(infopage) { asynchrequest= new XMLHttpRequest(); asynchrequest.onreadystatechange = function() { if (asynchrequest.readyState == 4 &amp;&amp; asynchrequest.status == 200) { document.getElementById(&quot;buttonresults&quot;).innerHTML = asynchrequest.responseText; } }; asynchrequest.open(&quot;GET&quot;, infopage, true); asynchrequest.send(); } </code></pre> <p>This is one of the pages being called from the index</p> <pre><code>&lt;script src=&quot;liblocations.js&quot;&gt;&lt;/script&gt; &lt;h1&gt;Find Calgary Libraries&lt;/h1&gt; &lt;div class=&quot;textfields&quot;&gt; &lt;table id=&quot;fields&quot;&gt; &lt;tr&gt;&lt;td&gt;&lt;label&gt;Find Libraries by Name &lt;/label&gt;&lt;/td&gt;&lt;td&gt;&lt;input type=&quot;text&quot; id=&quot;libname&quot;&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;label&gt;Find Libraries by Postal Code &lt;/label&gt;&lt;/td&gt;&lt;td&gt;&lt;input type=&quot;text&quot; id=&quot;libPostal&quot;&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;label&gt;Find Libraries by Square Feet &lt;/label&gt;&lt;/td&gt;&lt;td&gt;&lt;input type=&quot;text&quot; id=&quot;libSquareFeet&quot;&gt;&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;br&gt; &lt;br&gt; &lt;h3 id=&quot;searchvalue&quot;&gt; Enter a search&lt;/h3&gt; &lt;table id=&quot;searchresults&quot;&gt; &lt;/table&gt; </code></pre> <p>This is the unfinished Java script for the liblocations page</p> <pre><code>var xhr = new XMLHttpRequest; var parsedrecord; window.onload=pageSetup; function pageSetup() { document.getElementById(&quot;libname&quot;).addEventListener(&quot;keyup&quot;, function (){ searchByLibraryName();},false); document.getElementById(&quot;libPostal&quot;).addEventListener(&quot;keyup&quot;, function (){ searchByLibraryPostal();},false); document.getElementById(&quot;libSquareFeet&quot;).addEventListener(&quot;keyup&quot;, function (){ searchByLibrarySqrFeet();},false); xhr.onreadystatechange = function() { if (xhr.readyState == 4 &amp;&amp; xhr.status == 200) { parsedrecord = JSON.parse(xhr.responseText); } }; xhr.open(&quot;GET&quot;, &quot;https://data.calgary.ca/resource/m9y7-ui7j.json&quot;, true); xhr.send(); } function searchByLibraryName() { document.getElementById(&quot;searchvalue&quot;).innerHTML=&quot;Searching by Library Name&quot;; var librarytoUse=libname.value.toUpperCase(); libPostal.value=&quot;&quot;; libSquareFeet.value=&quot;&quot;; var gmap=&quot;&quot;; var position=&quot;&quot;; var output=&quot;&lt;tr&gt;&lt;th&gt;Library&lt;/th&gt;&lt;th&gt;Postal Code&lt;/th&gt;&lt;th&gt;Square Feet&lt;/th&gt;&lt;th&gt;Phone Number&lt;/th&gt;&lt;th&gt;Location&lt;/th&gt;&lt;/tr&gt;&quot;; for(var i=0;i&lt;parsedrecord.length;i++) { var record=parsedrecord[i]; var searchLib=record.library.toUpperCase();//assign if(searchLib.startsWith(librarytoUse))//partial match on string { output+=&quot;&lt;tr&gt;&lt;td&gt;&quot;; output+=record.library; output+=&quot;&lt;/td&gt;&lt;td&gt;&quot; output+=record.postal_code; output+=&quot;&lt;/td&gt;&lt;td&gt;&quot;; output+=record.square_feet; output+=&quot;&lt;/td&gt;&lt;td&gt;&quot;; output+=record.phone_number; output+=&quot;&lt;/td&gt;&lt;td&gt;&quot;; position=record.location.latitude+&quot;,&quot;+record.location.longitude; gmap =&quot;&lt;a href=https://www.google.com/maps/search/?api=1&amp;query=&quot;+position+&quot; target=_blank&gt;Click here to see map&lt;/a&gt; &quot;; output+=gmap; output+=&quot;&lt;/td&gt;&lt;/tr&gt;&quot;; } } document.getElementById(&quot;searchresults&quot;).innerHTML=output; } </code></pre> <p>When opening liblocations.html, the functions work but when I use the radio button and the index.html loads the page, the functions stop working. I'm not sure what is going on, or how to fix it. Any help is appreciated!</p> <p>This is the index page calling the liblocations <a href="https://i.stack.imgur.com/oiqnZ.png" rel="nofollow noreferrer">enter image description here</a></p> <p>This is what the liblocations page looks like when I open it alone <a href="https://i.stack.imgur.com/sFTat.png" rel="nofollow noreferrer">enter image description here</a></p>
[ { "answer_id": 74634872, "author": "HolyBlackCat", "author_id": 2752075, "author_profile": "https://Stackoverflow.com/users/2752075", "pm_score": 1, "selected": false, "text": "requires struct nullptr_value_type {using value_type = std::nullptr_t;};\n using elem_or_null_t = typename std::conditional_t<is_complex<T>::value, T, nullptr_value_type>::value_type;\n \nvoid foo(elem_or_null_t t)\nrequires (is_complex<T>::value)\n{}\n" }, { "answer_id": 74634879, "author": "lorro", "author_id": 6292621, "author_profile": "https://Stackoverflow.com/users/6292621", "pm_score": 2, "selected": true, "text": "is_complex template<typename T> struct complex_value_type {};\ntemplate<typename T> struct complex_value_type<std::complex<T>> { using type = T; };\n\ntemplate<typename T>\nusing complex_value_type_t = typename complex_value_type<T>::type;\n complex_value_type_t<T> template<class T>\nstruct Foo {\n template<typename T_ = T>\n void foo(complex_value_type_t<T_> t)\n requires (is_complex<T_>::value) {\n }\n};\n requires complex_value_type_t<T> complex<T>" }, { "answer_id": 74634900, "author": "Botond Horváth", "author_id": 16825566, "author_profile": "https://Stackoverflow.com/users/16825566", "pm_score": 0, "selected": false, "text": "#include <complex>\n\ntemplate<template<class> class T> struct is_complex : std::false_type {};\ntemplate<> struct is_complex<std::complex> : std::true_type {};\n\ntemplate<template<class> class T>\nstruct Foo {\n void foo(typename T<double>::value_type t)//could be typename<T<TT>> if you made foo a templated function\n requires (is_complex<T>::value) {\n }\n};\nint main(){\n Foo<std::complex> f;\n};\n double Foo foo" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20650126/" ]
74,634,811
<p>We have a site design that makes use of modules that are developed separately from the master site. Thru reflection, we pick up the modules when the main app starts.</p> <p>This works fine in local development and on a normal web server. But in the Azure environment when we try to use FTP to deploy the modules to our Azure-hosted site we are unable to because the main Azure deployment is read-only (because it is running from a package). Is it possible to not have the main site running from a package? Is it acceptable to run it that way?</p> <p>Is there another way to deploy Dlls to the Azure-hosted site without having them be part of the main site's build and deploy? Ultimately we are trying to avoid rebuilding the main site every time we want to add a module.</p>
[ { "answer_id": 74634872, "author": "HolyBlackCat", "author_id": 2752075, "author_profile": "https://Stackoverflow.com/users/2752075", "pm_score": 1, "selected": false, "text": "requires struct nullptr_value_type {using value_type = std::nullptr_t;};\n using elem_or_null_t = typename std::conditional_t<is_complex<T>::value, T, nullptr_value_type>::value_type;\n \nvoid foo(elem_or_null_t t)\nrequires (is_complex<T>::value)\n{}\n" }, { "answer_id": 74634879, "author": "lorro", "author_id": 6292621, "author_profile": "https://Stackoverflow.com/users/6292621", "pm_score": 2, "selected": true, "text": "is_complex template<typename T> struct complex_value_type {};\ntemplate<typename T> struct complex_value_type<std::complex<T>> { using type = T; };\n\ntemplate<typename T>\nusing complex_value_type_t = typename complex_value_type<T>::type;\n complex_value_type_t<T> template<class T>\nstruct Foo {\n template<typename T_ = T>\n void foo(complex_value_type_t<T_> t)\n requires (is_complex<T_>::value) {\n }\n};\n requires complex_value_type_t<T> complex<T>" }, { "answer_id": 74634900, "author": "Botond Horváth", "author_id": 16825566, "author_profile": "https://Stackoverflow.com/users/16825566", "pm_score": 0, "selected": false, "text": "#include <complex>\n\ntemplate<template<class> class T> struct is_complex : std::false_type {};\ntemplate<> struct is_complex<std::complex> : std::true_type {};\n\ntemplate<template<class> class T>\nstruct Foo {\n void foo(typename T<double>::value_type t)//could be typename<T<TT>> if you made foo a templated function\n requires (is_complex<T>::value) {\n }\n};\nint main(){\n Foo<std::complex> f;\n};\n double Foo foo" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/61623/" ]
74,634,832
<p>How can I document a method that a subclass overrides without being redundant? For example...</p> <pre><code>class Parent # Is this the parent? # @return [Boolean] def parent? true end end class Child &lt; Parent def parent? false end end </code></pre> <p>YARD generates something like this.</p> <blockquote> <h2>Class: Parent</h2> <h3>Instance Method Summary</h3> <pre><code>#parent? ⇒ Boolean </code></pre> <p>Is this the parent?.</p> </blockquote> <blockquote> <h2>Class: Child</h2> <h3>Instance Method Summary</h3> <pre><code>#parent? ⇒ Boolean </code></pre> </blockquote> <p>The generated YARD documentation will not include &quot;Is this the parent?&quot; in the docs for Child#parent?, nor will it indicate that it is an override.</p> <p>I would like to see something like this:</p> <blockquote> <h2>Class: Parent</h2> <h3>Instance Method Summary</h3> <pre><code>#parent? ⇒ Boolean </code></pre> <p>Is this the parent?.</p> </blockquote> <blockquote> <h2>Class: Child</h2> <h3>Instance Method Summary</h3> <pre><code>#parent? ⇒ Boolean </code></pre> <p>Is this the parent?.</p> <h3>Methods inherited from Parent</h3> <pre><code>#parent? </code></pre> </blockquote> <p>I would prefer not to have to copy the documentation into every subclass.</p>
[ { "answer_id": 74634872, "author": "HolyBlackCat", "author_id": 2752075, "author_profile": "https://Stackoverflow.com/users/2752075", "pm_score": 1, "selected": false, "text": "requires struct nullptr_value_type {using value_type = std::nullptr_t;};\n using elem_or_null_t = typename std::conditional_t<is_complex<T>::value, T, nullptr_value_type>::value_type;\n \nvoid foo(elem_or_null_t t)\nrequires (is_complex<T>::value)\n{}\n" }, { "answer_id": 74634879, "author": "lorro", "author_id": 6292621, "author_profile": "https://Stackoverflow.com/users/6292621", "pm_score": 2, "selected": true, "text": "is_complex template<typename T> struct complex_value_type {};\ntemplate<typename T> struct complex_value_type<std::complex<T>> { using type = T; };\n\ntemplate<typename T>\nusing complex_value_type_t = typename complex_value_type<T>::type;\n complex_value_type_t<T> template<class T>\nstruct Foo {\n template<typename T_ = T>\n void foo(complex_value_type_t<T_> t)\n requires (is_complex<T_>::value) {\n }\n};\n requires complex_value_type_t<T> complex<T>" }, { "answer_id": 74634900, "author": "Botond Horváth", "author_id": 16825566, "author_profile": "https://Stackoverflow.com/users/16825566", "pm_score": 0, "selected": false, "text": "#include <complex>\n\ntemplate<template<class> class T> struct is_complex : std::false_type {};\ntemplate<> struct is_complex<std::complex> : std::true_type {};\n\ntemplate<template<class> class T>\nstruct Foo {\n void foo(typename T<double>::value_type t)//could be typename<T<TT>> if you made foo a templated function\n requires (is_complex<T>::value) {\n }\n};\nint main(){\n Foo<std::complex> f;\n};\n double Foo foo" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14660/" ]
74,634,925
<p>Following example code is provided in order to introduce the matter ...</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const elm = document.getElementById('fname'); elm.addEventListener('focus', evt =&gt; console.log( `input element focused, event.type: "${ evt.type }"` ) ); elm.focus();</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input type="text" id="fname" name="fname"&gt;</code></pre> </div> </div> </p> <p>As one can see, the <code>'focus'</code> event gets dispatched. But I wish to focus the input element without dispatching this event.</p> <p>Can this be done. And how would one achieve such behavior?</p>
[ { "answer_id": 74635445, "author": "Marlon Amado", "author_id": 11816824, "author_profile": "https://Stackoverflow.com/users/11816824", "pm_score": -1, "selected": false, "text": "const body = document.querySelector('body')\nconst btn = document.getElementById('btn'); \nconst el = document.getElementById('fname');\nlet toggle = false;\n\nfunction makeBackgroundYellow() {\n console.log(\"input focus\");\n body.style.backgroundColor = toggle ? 'white' : 'yellow';\n toggle = !toggle;\n}; \n\nel.addEventListener('focus', makeBackgroundYellow);\nbtn.addEventListener('click', ()=>{\n el.removeEventListener(\"focus\", makeBackgroundYellow, false); \n}); <input type=\"text\" id=\"fname\" name=\"fname\">\n<button id=\"btn\">Press</button>" }, { "answer_id": 74635533, "author": "Peter Seliger", "author_id": 2627243, "author_profile": "https://Stackoverflow.com/users/2627243", "pm_score": 3, "selected": true, "text": "'focus' evt.stopImmediatePropagation() 'focus' 'focus' elm.addEventListener('focus', evt => evt.stopImmediatePropagation() );\n const elm = document.getElementById('fname');\n\n// the \"initial\" listener subscription prevents execution of ...\nelm.addEventListener('focus', evt =>\n evt.stopImmediatePropagation()\n);\n\n// ... other handler functionality which got registered later.\nelm.addEventListener('focus', evt =>\n console.log(\n `input element focused, event.type: \"${ evt.type }\"`\n )\n);\nelm.focus(); <input type=\"text\" id=\"fname\" name=\"fname\">" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12160654/" ]
74,634,945
<p>I need to find the line, that contains the longest word from a txt file. I can find the longest word but I am not able to find in which line that word is. Here is the part of the code that works for me. I've tried a bunch of ways to find the line but I failed (I am a begginer at python).</p> <pre><code>def reading(): doc = open(&quot;C:/Users/s.txt&quot;, &quot;r&quot;, encoding= 'utf-8') docu = doc return docu def longest_word_place(document): words = document.read().split() i = 0 max = 0 max_place = 0 for i in range(len(words)): if len(words[i]) &gt; max: max = len(words[i]) max_place = i return max_place document = reading() print(longest_word_place(document)) </code></pre>
[ { "answer_id": 74635445, "author": "Marlon Amado", "author_id": 11816824, "author_profile": "https://Stackoverflow.com/users/11816824", "pm_score": -1, "selected": false, "text": "const body = document.querySelector('body')\nconst btn = document.getElementById('btn'); \nconst el = document.getElementById('fname');\nlet toggle = false;\n\nfunction makeBackgroundYellow() {\n console.log(\"input focus\");\n body.style.backgroundColor = toggle ? 'white' : 'yellow';\n toggle = !toggle;\n}; \n\nel.addEventListener('focus', makeBackgroundYellow);\nbtn.addEventListener('click', ()=>{\n el.removeEventListener(\"focus\", makeBackgroundYellow, false); \n}); <input type=\"text\" id=\"fname\" name=\"fname\">\n<button id=\"btn\">Press</button>" }, { "answer_id": 74635533, "author": "Peter Seliger", "author_id": 2627243, "author_profile": "https://Stackoverflow.com/users/2627243", "pm_score": 3, "selected": true, "text": "'focus' evt.stopImmediatePropagation() 'focus' 'focus' elm.addEventListener('focus', evt => evt.stopImmediatePropagation() );\n const elm = document.getElementById('fname');\n\n// the \"initial\" listener subscription prevents execution of ...\nelm.addEventListener('focus', evt =>\n evt.stopImmediatePropagation()\n);\n\n// ... other handler functionality which got registered later.\nelm.addEventListener('focus', evt =>\n console.log(\n `input element focused, event.type: \"${ evt.type }\"`\n )\n);\nelm.focus(); <input type=\"text\" id=\"fname\" name=\"fname\">" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74634945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20392142/" ]
74,635,000
<p>Currently we have a set of microservice hosted on kubernetes cluster. We are setting hpa values based on rough estimates. I am planning to monitor horizontal pod autoscaling behavior using grafana to ensure we are not over/under allocating the resources like CPU/memory and come up with possible cost optimization recommendation. Need directions on how to achieve this.</p> <p>I am new to Kubernetes world. Need directions on how to achieve this.</p>
[ { "answer_id": 74635445, "author": "Marlon Amado", "author_id": 11816824, "author_profile": "https://Stackoverflow.com/users/11816824", "pm_score": -1, "selected": false, "text": "const body = document.querySelector('body')\nconst btn = document.getElementById('btn'); \nconst el = document.getElementById('fname');\nlet toggle = false;\n\nfunction makeBackgroundYellow() {\n console.log(\"input focus\");\n body.style.backgroundColor = toggle ? 'white' : 'yellow';\n toggle = !toggle;\n}; \n\nel.addEventListener('focus', makeBackgroundYellow);\nbtn.addEventListener('click', ()=>{\n el.removeEventListener(\"focus\", makeBackgroundYellow, false); \n}); <input type=\"text\" id=\"fname\" name=\"fname\">\n<button id=\"btn\">Press</button>" }, { "answer_id": 74635533, "author": "Peter Seliger", "author_id": 2627243, "author_profile": "https://Stackoverflow.com/users/2627243", "pm_score": 3, "selected": true, "text": "'focus' evt.stopImmediatePropagation() 'focus' 'focus' elm.addEventListener('focus', evt => evt.stopImmediatePropagation() );\n const elm = document.getElementById('fname');\n\n// the \"initial\" listener subscription prevents execution of ...\nelm.addEventListener('focus', evt =>\n evt.stopImmediatePropagation()\n);\n\n// ... other handler functionality which got registered later.\nelm.addEventListener('focus', evt =>\n console.log(\n `input element focused, event.type: \"${ evt.type }\"`\n )\n);\nelm.focus(); <input type=\"text\" id=\"fname\" name=\"fname\">" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74635000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7055628/" ]
74,635,060
<p>I have a monorepo for a fullstack webapp with the following directory structure</p> <pre><code>. ├── client │ ├── index.html │ ├── package.json │ ├── src │ └── vite.config.ts ├── node_modules ├── package-lock.json ├── package.json ├── server │ ├── package.json │ └── src ├── tsconfig.json └── tsconfig.node.json </code></pre> <p>However, when I run <code>npm run dev -ws client</code>, vite generates it's own <code>node_modules/</code> inside <code>client/</code>.</p> <pre><code>. ├── client │ ├── index.html │ ├── node_modules &lt;--- this │ │ └── .vite │ │ └── deps_temp │ │ └── package.json │ ├── package.json │ ├── src │ └── vite.config.ts </code></pre> <p>My understanding is that the point of using npm workspaces is to avoid having multiple <code>node_modules/</code> in each sub-project, instead having all dependencies installed in the root <code>node_modules/</code>. Vite generating it's own seems to defeat that point.</p> <p>I'm assuming I don't have something configured properly (I used <code>npx create-vite</code> to setup vite).</p> <p>Output of <code>npm run dev -ws client</code></p> <pre><code>&gt; @sargon-dashboard/client@0.0.0 dev &gt; vite client (!) Could not auto-determine entry point from rollupOptions or html files and there are no explicit optimizeDeps.include patterns. Skipping dependency pre-bundling. VITE v3.2.4 ready in 175 ms ➜ Local: http://localhost:5173/ ➜ Network: use --host to expose </code></pre> <p>Contents of <code>vite.config.ts</code></p> <pre><code>import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' // https://vitejs.dev/config/ export default defineConfig({ plugins: [react()] }) </code></pre> <p>contents of <code>root/package.json</code></p> <pre class="lang-json prettyprint-override"><code>{ &quot;name&quot;: &quot;app&quot;, &quot;private&quot;: true, &quot;workspaces&quot;: [ &quot;client&quot;, &quot;server&quot; ] } </code></pre> <p>contents of <code>root/client/package.json</code></p> <pre class="lang-json prettyprint-override"><code>{ &quot;name&quot;: &quot;@app/client&quot;, &quot;private&quot;: true, &quot;version&quot;: &quot;0.0.0&quot;, &quot;type&quot;: &quot;module&quot;, &quot;scripts&quot;: { &quot;dev&quot;: &quot;vite&quot;, &quot;build&quot;: &quot;tsc &amp;&amp; vite build&quot;, &quot;preview&quot;: &quot;vite preview&quot; }, &quot;dependencies&quot;: { &quot;react&quot;: &quot;^18.2.0&quot;, &quot;react-dom&quot;: &quot;^18.2.0&quot; }, &quot;devDependencies&quot;: { &quot;@types/react&quot;: &quot;^18.0.24&quot;, &quot;@types/react-dom&quot;: &quot;^18.0.8&quot;, &quot;@vitejs/plugin-react&quot;: &quot;^2.2.0&quot;, &quot;typescript&quot;: &quot;^4.6.4&quot;, &quot;vite&quot;: &quot;^3.2.3&quot; } } </code></pre> <p>contents of <code>root/server/package.json</code></p> <pre class="lang-json prettyprint-override"><code>{ &quot;name&quot;: &quot;@app/server&quot;, &quot;version&quot;: &quot;0.0.0&quot;, &quot;description&quot;: &quot;&quot;, &quot;main&quot;: &quot;index.js&quot;, &quot;scripts&quot;: { &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot; }, &quot;keywords&quot;: [], &quot;author&quot;: &quot;&quot;, &quot;license&quot;: &quot;ISC&quot; } </code></pre>
[ { "answer_id": 74635445, "author": "Marlon Amado", "author_id": 11816824, "author_profile": "https://Stackoverflow.com/users/11816824", "pm_score": -1, "selected": false, "text": "const body = document.querySelector('body')\nconst btn = document.getElementById('btn'); \nconst el = document.getElementById('fname');\nlet toggle = false;\n\nfunction makeBackgroundYellow() {\n console.log(\"input focus\");\n body.style.backgroundColor = toggle ? 'white' : 'yellow';\n toggle = !toggle;\n}; \n\nel.addEventListener('focus', makeBackgroundYellow);\nbtn.addEventListener('click', ()=>{\n el.removeEventListener(\"focus\", makeBackgroundYellow, false); \n}); <input type=\"text\" id=\"fname\" name=\"fname\">\n<button id=\"btn\">Press</button>" }, { "answer_id": 74635533, "author": "Peter Seliger", "author_id": 2627243, "author_profile": "https://Stackoverflow.com/users/2627243", "pm_score": 3, "selected": true, "text": "'focus' evt.stopImmediatePropagation() 'focus' 'focus' elm.addEventListener('focus', evt => evt.stopImmediatePropagation() );\n const elm = document.getElementById('fname');\n\n// the \"initial\" listener subscription prevents execution of ...\nelm.addEventListener('focus', evt =>\n evt.stopImmediatePropagation()\n);\n\n// ... other handler functionality which got registered later.\nelm.addEventListener('focus', evt =>\n console.log(\n `input element focused, event.type: \"${ evt.type }\"`\n )\n);\nelm.focus(); <input type=\"text\" id=\"fname\" name=\"fname\">" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74635060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12574341/" ]
74,635,091
<p>I am currently writing a code in Python where the objective is to find the root of the output of a function with respect to input variable x. The code looks like this:</p> <pre><code>def Compound_Correlation_Function(x): # Here comes a long part of the code... Equity_Solve = Tranches.loc[0, 'Par_Spread_bps'] - Market_Data.iloc[0,0] Mezzanine_Solve = Tranches.loc[1, 'Par_Spread_bps'] - Market_Data.iloc[1,0] return Equity_Solve, Mezzanine_Solve Correlation_Value = optimize.root(Compound_Correlation_Function, x0 = 0.3) </code></pre> <p>As can be seen in the code block above, there are two outputs specified:</p> <ol> <li>Equity_Solve</li> <li>Mezzanine_Solve</li> </ol> <p>I now want to find the root for both outputs separately. If I comment out the Mezzanine_Solve part in the return statement, then the the optimize procedure gives me the solution I want. Obviously, I want to automate my code as much as possible. Is it possible to specify the output for which I want to find the root in the optimize statement?</p> <p>I tried the following, without success:</p> <pre><code>Correlation_Value = optimize.root(Compound_Correlation_Function[0], x0 = 0.3) Correlation_Value = optimize.root(Compound_Correlation_Function(x)[0], x0 = 0.3) Correlation_Value = optimize.root(Compound_Correlation_Function()[], x0 = 0.3) </code></pre> <p>Any help is appreciated. Thank you in advance!</p>
[ { "answer_id": 74635445, "author": "Marlon Amado", "author_id": 11816824, "author_profile": "https://Stackoverflow.com/users/11816824", "pm_score": -1, "selected": false, "text": "const body = document.querySelector('body')\nconst btn = document.getElementById('btn'); \nconst el = document.getElementById('fname');\nlet toggle = false;\n\nfunction makeBackgroundYellow() {\n console.log(\"input focus\");\n body.style.backgroundColor = toggle ? 'white' : 'yellow';\n toggle = !toggle;\n}; \n\nel.addEventListener('focus', makeBackgroundYellow);\nbtn.addEventListener('click', ()=>{\n el.removeEventListener(\"focus\", makeBackgroundYellow, false); \n}); <input type=\"text\" id=\"fname\" name=\"fname\">\n<button id=\"btn\">Press</button>" }, { "answer_id": 74635533, "author": "Peter Seliger", "author_id": 2627243, "author_profile": "https://Stackoverflow.com/users/2627243", "pm_score": 3, "selected": true, "text": "'focus' evt.stopImmediatePropagation() 'focus' 'focus' elm.addEventListener('focus', evt => evt.stopImmediatePropagation() );\n const elm = document.getElementById('fname');\n\n// the \"initial\" listener subscription prevents execution of ...\nelm.addEventListener('focus', evt =>\n evt.stopImmediatePropagation()\n);\n\n// ... other handler functionality which got registered later.\nelm.addEventListener('focus', evt =>\n console.log(\n `input element focused, event.type: \"${ evt.type }\"`\n )\n);\nelm.focus(); <input type=\"text\" id=\"fname\" name=\"fname\">" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74635091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20650270/" ]
74,635,099
<p>Sample table:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>object_id</th> <th>event_time</th> <th>event_type</th> <th>event_subtype</th> <th>stage</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>2022-10-01</td> <td>create</td> <td>name, stage</td> <td>A</td> </tr> <tr> <td>1</td> <td>2022-10-02</td> <td>update</td> <td>stage</td> <td>B</td> </tr> <tr> <td>1</td> <td>2022-10-03</td> <td>update</td> <td>stage</td> <td>C</td> </tr> <tr> <td>1</td> <td>2022-10-04</td> <td>update</td> <td>stage</td> <td>A</td> </tr> <tr> <td>2</td> <td>2022-10-01</td> <td>create</td> <td>name, stage</td> <td>A</td> </tr> <tr> <td>2</td> <td>2022-10-02</td> <td>update</td> <td>stage</td> <td>C</td> </tr> <tr> <td>2</td> <td>2022-10-03</td> <td>update</td> <td>stage</td> <td>A</td> </tr> <tr> <td>2</td> <td>2022-10-04</td> <td>update</td> <td>stage</td> <td>B</td> </tr> <tr> <td>2</td> <td>2022-10-05</td> <td>update</td> <td>stage</td> <td>C</td> </tr> <tr> <td>2</td> <td>2022-10-06</td> <td>update</td> <td>stage</td> <td>A</td> </tr> </tbody> </table> </div> <p>So what I need is a column that numbers the rows based on the stage - after an object_id reaches stage C, the row number of the same object_id should be incremented. It'd look like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>object_id</th> <th>event_time</th> <th>event_type</th> <th>event_subtype</th> <th>stage</th> <th>row_number</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>2022-10-01</td> <td>create</td> <td>name, stage</td> <td>A</td> <td>1</td> </tr> <tr> <td>1</td> <td>2022-10-02</td> <td>update</td> <td>stage</td> <td>B</td> <td>1</td> </tr> <tr> <td>1</td> <td>2022-10-03</td> <td>update</td> <td>stage</td> <td>C</td> <td>1</td> </tr> <tr> <td>1</td> <td>2022-10-04</td> <td>update</td> <td>stage</td> <td>A</td> <td>2</td> </tr> <tr> <td>2</td> <td>2022-10-01</td> <td>create</td> <td>name, stage</td> <td>A</td> <td>1</td> </tr> <tr> <td>2</td> <td>2022-10-02</td> <td>update</td> <td>stage</td> <td>C</td> <td>1</td> </tr> <tr> <td>2</td> <td>2022-10-03</td> <td>update</td> <td>stage</td> <td>A</td> <td>2</td> </tr> <tr> <td>2</td> <td>2022-10-04</td> <td>update</td> <td>stage</td> <td>B</td> <td>2</td> </tr> <tr> <td>2</td> <td>2022-10-05</td> <td>update</td> <td>stage</td> <td>C</td> <td>2</td> </tr> <tr> <td>2</td> <td>2022-10-06</td> <td>update</td> <td>stage</td> <td>A</td> <td>3</td> </tr> </tbody> </table> </div> <p>The table must be ordered by object_id, event_time. I'm having troublle writing the window function that does this, this is what I've tried:</p> <pre><code>row_number() over (partition by object_id, stage order by event_time) </code></pre> <p>It just doesn't work for all cases. Also I'm having a hard time understanding how this would work when I'm not defining <code>stage = C</code> as the delimiter anywhere. Any ideas?</p> <p>Thanks!</p>
[ { "answer_id": 74635186, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 0, "selected": false, "text": "ORDER BY SELECT\n\"object_id\", \"event_time\", \"event_type\", \"event_subtype\", \"stage\",\nROW_NUMBER() OVER(PARTITION BY \"object_id\",\"stage\" ORDER BY \"event_time\") rn\n FROM tab1\n ORDER BY \"object_id\",rn,\"stage\"\n" }, { "answer_id": 74635198, "author": "Guru Stron", "author_id": 2501279, "author_profile": "https://Stackoverflow.com/users/2501279", "pm_score": 2, "selected": true, "text": "stage -- sample data\nwith dataset(object_id, event_time, event_type, event_subtype, stage) as (\n values (1, '2022-10-01', 'create', 'name, stage', 'A'),\n (1, '2022-10-02', 'update', 'stage', 'B'),\n (1, '2022-10-03', 'update', 'stage', 'C'),\n (1, '2022-10-04', 'update', 'stage', 'A'),\n (2, '2022-10-01', 'create', 'name, stage',' A'),\n (2, '2022-10-02', 'update', 'stage', 'C'),\n (2, '2022-10-03', 'update', 'stage', 'A'),\n (2, '2022-10-04', 'update', 'stage', 'B'),\n (2, '2022-10-05', 'update', 'stage', 'C'),\n (2, '2022-10-06', 'update', 'stage', 'A')\n)\n\n-- query\nselect object_id,\n event_time,\n event_type,\n event_subtype,\n stage,\n 1 + sum(counter) over (partition by object_id order by event_time) as num\nfrom (select *,\n if(lag(stage) over (partition by object_id order by event_time) = 'C', 1, 0) counter\n from dataset);\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74635099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3642271/" ]
74,635,111
<p>I have to separate .txt file into small pieces, based on the matched value. For example, I have .txt file looks like:</p> <pre><code>Names Age Country Mark 19 USA John 19 UK Elon 20 CAN Dominic 21 USA Andreas 21 UK </code></pre> <p>I have to extract all rows with the same value “Age” and to copy them to other file or perfom some other action..</p> <p>How it is possible to be done with Python, I have never do that before.</p> <p>Thank you in advance :)</p> <p>I am asking, because of I have no idea how it should be done. The excpected result is to have this data separated:</p> <pre><code>Names Age Country Mark 19 USA John 19 UK Names Age Country Elon 20 CAN Names Age Country Dominic 21 USA Andreas 21 UK </code></pre>
[ { "answer_id": 74635232, "author": "user1544752", "author_id": 1544752, "author_profile": "https://Stackoverflow.com/users/1544752", "pm_score": -1, "selected": false, "text": "alltext = [\"Names Age Country\", \"Mark 21 USA\", \"John 21 UK\",\"Elon 20 CAN\",\"Dominic 21 USA\", \"Andreas 21 UK\"]\n\nCanada = [alltext[0]] #Creates a list with your column header\nNotCanada = [alltext[0]] #Creates a list with your column header\n\nfor row in alltext[1:]:\n x = row.split()\n if x[2] == \"CAN\":\n Canada.append(row)\n else:\n NotCanada.append(row)\n\nprint(Canada)\nprint(NotCanada)\n" }, { "answer_id": 74635408, "author": "accdias", "author_id": 6789321, "author_profile": "https://Stackoverflow.com/users/6789321", "pm_score": 0, "selected": false, "text": "with open('yourfile.txt') as infile:\n header = next(infile)\n ages = {}\n\n for line in infile:\n name, age, country = line.rsplit(' ', 2)\n if age not in ages:\n ages[age] = []\n ages[age].append([name, age, country])\n\n for age in ages:\n with open(f'age-{age}.txt', 'w') as agefile:\n agefile.writeline(header) \n agefile.writelines(ages[age])\n age-19.txt age-20.txt age-21.txt" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74635111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15703588/" ]
74,635,135
<p>I have 2 objects</p> <pre><code>const obj1 = { item1: { name: '1' }, item2: { name: '2' } } const obj2 = { item1: { sample: 'sample1' }, item2: { sample: 'sample2' } } </code></pre> <p>How can I loop over the second object <code>obj2</code>, find the first match against object <code>obj1</code> and return it?</p> <p>In above example, I should return</p> <pre><code>{ item1: { name: '1' } } </code></pre> <p>since <code>item1</code> is the first match between the 2 objects and I want what's inside obj1.</p> <p>Tried the following:</p> <pre><code>const keys = obj2 &amp;&amp; Object.keys(obj2); const output = () =&gt; { if (keys) { const finalResponse = keys.map(key =&gt; { if (obj1[key]) return obj1[key]; return undefined; }); return finalResponse } return null } </code></pre> <p>But ends up getting 2 matches when I only want the first time it matches.</p> <p>Is there a cleaner way to do this.</p> <p>Fine to loop over obj1 or obj2 as long as I can return the match in obj1.</p>
[ { "answer_id": 74635200, "author": "Vit Lit", "author_id": 12769919, "author_profile": "https://Stackoverflow.com/users/12769919", "pm_score": 1, "selected": false, "text": "var result = Object.keys(obj1).find(prop=>obj2.hasOwnProperty(prop));\n var resObj = {[result]:obj1[result]};\n const obj1 = {\n item1: {name: '1'},\n item2: {name: '2'}\n}\nconst obj2 = {\n item1: {sample: 'sample1'},\n item2: {sample: 'sample2'}\n}\nvar result = Object.keys(obj1).find(prop=>obj2.hasOwnProperty(prop));\nvar resObj = {[result]:obj1[result]};\nconsole.log(resObj);" }, { "answer_id": 74635214, "author": "Ferin Patel", "author_id": 11812450, "author_profile": "https://Stackoverflow.com/users/11812450", "pm_score": 0, "selected": false, "text": "const obj1 = {\n item1: {\n name: '1'\n },\n item2: {\n name: '2'\n }\n}\n\nconst obj2 = {\n item1: {\n sample: 'sample1'\n },\n item2: {\n sample: 'sample2'\n }\n}\n\nconst obj1Keys = Object.keys(obj1)\nconst obj2Keys = Object.keys(obj2)\n\n\nlet match = null;\n\nobj2Keys.every((key) => {\n if (obj1Keys.includes(key)) {\n match = obj1[key]\n return false\n }\n return true\n})\n\nconsole.log(match)" }, { "answer_id": 74635258, "author": "danh", "author_id": 294949, "author_profile": "https://Stackoverflow.com/users/294949", "pm_score": 1, "selected": false, "text": "obj1 obj2 const object2keys = new Set(Object.keys(obj2));\nconst intersection = Object.keys(obj1).filter(key => object2keys.has(key));\n obj1 const match = intersection.length ? intersection[0] : null;\nconst result = match ? { [match] : obj1[match] } : {}\n const obj1 = {\n item1: {\n name: '1'\n },\n item2: {\n name: '2'\n }\n}\n\nconst obj2 = {\n item1: {\n sample: 'sample1'\n },\n item2: {\n sample: 'sample2'\n }\n}\n\nconst object2keys = new Set(Object.keys(obj2));\nconst intersection = Object.keys(obj1).filter(key => object2keys.has(key));\nconst match = intersection.length ? intersection[0] : null;\nconst result = match ? { [match] : obj1[match] } : {}\n\nconsole.log(result);" }, { "answer_id": 74635272, "author": "subodhkalika", "author_id": 6682406, "author_profile": "https://Stackoverflow.com/users/6682406", "pm_score": 3, "selected": true, "text": "const keys = obj2 && Object.keys(obj2);\nlet keyMatched = '';\nconst output = () => {\n if (keys) {\n const finalResponse = keys.map(key => {\n if (obj1[key] && !keyMatched) { // Check for first match \n keyMatched = key; // Save the first match\n return obj1[key];\n }\n return undefined;\n });\n return finalResponse\n }\n return null\n}\n const obj1 = {\n item1: {\n name: '1'\n },\n item2: {\n name: '2'\n }\n}\n\nconst obj2 = {\n item1: {\n sample: 'sample1'\n },\n item2: {\n sample: 'sample2'\n }\n}\nconst keys = obj2 && Object.keys(obj2);\nlet keyMatched = '';\nconst output = () => {\n if (keys) {\n const finalResponse = keys.map(key => {\n if (obj1[key] && !keyMatched) { // Check for first match \n keyMatched = key; // Save the first match\n return obj1[key];\n }\n return undefined;\n });\n return finalResponse\n }\n return null\n}\noutput();\nconst newObj = {\n [keyMatched]: obj1[keyMatched]\n}\nconsole.log(newObj)" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74635135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9401029/" ]
74,635,142
<p>i have one error that's is impossible for me to solve, what kind of problem is this shit? I've searched for many ways to fix this but i don't have found it nothing for this problem on vscode only for android studio, someone can help me? <a href="https://i.stack.imgur.com/sO2gY.jpg" rel="nofollow noreferrer">enter image description here</a></p> <p>this impossibilite me to deploy my application in a on virtual android always stop in this error</p> <pre><code>FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:mergeDebugResources'. &gt; A failure occurred while executing com.android.build.gradle.internal.res.ResourceCompilerRunnable &gt; Resource compilation failed. Check logs for details. * Try: &gt; Run with --stacktrace option to get the stack trace. &gt; Run with --info or --debug option to get more log output. &gt; Run with --scan to get full insights. * Get more help at https://help.gradle.org BUILD FAILED in 4s Exception: Gradle task assembleDebug failed with exit code 1 Exited (sigterm) </code></pre>
[ { "answer_id": 74635200, "author": "Vit Lit", "author_id": 12769919, "author_profile": "https://Stackoverflow.com/users/12769919", "pm_score": 1, "selected": false, "text": "var result = Object.keys(obj1).find(prop=>obj2.hasOwnProperty(prop));\n var resObj = {[result]:obj1[result]};\n const obj1 = {\n item1: {name: '1'},\n item2: {name: '2'}\n}\nconst obj2 = {\n item1: {sample: 'sample1'},\n item2: {sample: 'sample2'}\n}\nvar result = Object.keys(obj1).find(prop=>obj2.hasOwnProperty(prop));\nvar resObj = {[result]:obj1[result]};\nconsole.log(resObj);" }, { "answer_id": 74635214, "author": "Ferin Patel", "author_id": 11812450, "author_profile": "https://Stackoverflow.com/users/11812450", "pm_score": 0, "selected": false, "text": "const obj1 = {\n item1: {\n name: '1'\n },\n item2: {\n name: '2'\n }\n}\n\nconst obj2 = {\n item1: {\n sample: 'sample1'\n },\n item2: {\n sample: 'sample2'\n }\n}\n\nconst obj1Keys = Object.keys(obj1)\nconst obj2Keys = Object.keys(obj2)\n\n\nlet match = null;\n\nobj2Keys.every((key) => {\n if (obj1Keys.includes(key)) {\n match = obj1[key]\n return false\n }\n return true\n})\n\nconsole.log(match)" }, { "answer_id": 74635258, "author": "danh", "author_id": 294949, "author_profile": "https://Stackoverflow.com/users/294949", "pm_score": 1, "selected": false, "text": "obj1 obj2 const object2keys = new Set(Object.keys(obj2));\nconst intersection = Object.keys(obj1).filter(key => object2keys.has(key));\n obj1 const match = intersection.length ? intersection[0] : null;\nconst result = match ? { [match] : obj1[match] } : {}\n const obj1 = {\n item1: {\n name: '1'\n },\n item2: {\n name: '2'\n }\n}\n\nconst obj2 = {\n item1: {\n sample: 'sample1'\n },\n item2: {\n sample: 'sample2'\n }\n}\n\nconst object2keys = new Set(Object.keys(obj2));\nconst intersection = Object.keys(obj1).filter(key => object2keys.has(key));\nconst match = intersection.length ? intersection[0] : null;\nconst result = match ? { [match] : obj1[match] } : {}\n\nconsole.log(result);" }, { "answer_id": 74635272, "author": "subodhkalika", "author_id": 6682406, "author_profile": "https://Stackoverflow.com/users/6682406", "pm_score": 3, "selected": true, "text": "const keys = obj2 && Object.keys(obj2);\nlet keyMatched = '';\nconst output = () => {\n if (keys) {\n const finalResponse = keys.map(key => {\n if (obj1[key] && !keyMatched) { // Check for first match \n keyMatched = key; // Save the first match\n return obj1[key];\n }\n return undefined;\n });\n return finalResponse\n }\n return null\n}\n const obj1 = {\n item1: {\n name: '1'\n },\n item2: {\n name: '2'\n }\n}\n\nconst obj2 = {\n item1: {\n sample: 'sample1'\n },\n item2: {\n sample: 'sample2'\n }\n}\nconst keys = obj2 && Object.keys(obj2);\nlet keyMatched = '';\nconst output = () => {\n if (keys) {\n const finalResponse = keys.map(key => {\n if (obj1[key] && !keyMatched) { // Check for first match \n keyMatched = key; // Save the first match\n return obj1[key];\n }\n return undefined;\n });\n return finalResponse\n }\n return null\n}\noutput();\nconst newObj = {\n [keyMatched]: obj1[keyMatched]\n}\nconsole.log(newObj)" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74635142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20650374/" ]
74,635,145
<p>Is there any regex to extract words from text that are surrounded by a certain prefix and suffix?</p> <p>Example:</p> <pre><code>test[az5]test[az6]test </code></pre> <p>I need to extract the numbers surrounded by the prefix <code>[az</code> and the suffix <code>]</code>.</p> <p>I'm a bit advanced in Python, but not really familiar with regex.</p> <p>The desired output is:</p> <pre><code>5 6 </code></pre>
[ { "answer_id": 74635183, "author": "accdias", "author_id": 6789321, "author_profile": "https://Stackoverflow.com/users/6789321", "pm_score": 2, "selected": true, "text": ">>> import re\n>>> re.findall('\\[az(\\d+)\\]', 'test[az5]test[az6]test')\n['5', '6']\n>>> \n" }, { "answer_id": 74635246, "author": "user19898808", "author_id": 19898808, "author_profile": "https://Stackoverflow.com/users/19898808", "pm_score": 0, "selected": false, "text": "import re\n\ntxt = \"test[az5]test[az6]test\"\nx = re.findall(r\"\\[az(?P<num>\\d)\\]\", txt)\nprint(x)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74635145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16324551/" ]
74,635,176
<p>I am trying to scrape tweets under a hashtag using Python selinum and I use the following code to scroll down <code>driver.execute_script('window.scrollTo(0,document.body.scrollHeight);')</code></p> <p>The problem is that selinum only scrapes shown tweets (only 3 tweets) and then scroll down to the end of the page and load more tweets and scrape 3 new tweets missing a lot of tweets in between.</p> <p>Is there a way to show all tweets and then scroll down and show all new tweets or at least some new tweets (I've a mechasm to filter already scraped rweets) ?</p> <p>Note I'm running my script on GCP VM so I can't rotate the screen.</p> <p>I think that I can make the script keeps pressing the down arrow by that I can display tweets one by one and scrape them and also keep loading more tweets, but I think that this will slow down the scraper so much.</p>
[ { "answer_id": 74635183, "author": "accdias", "author_id": 6789321, "author_profile": "https://Stackoverflow.com/users/6789321", "pm_score": 2, "selected": true, "text": ">>> import re\n>>> re.findall('\\[az(\\d+)\\]', 'test[az5]test[az6]test')\n['5', '6']\n>>> \n" }, { "answer_id": 74635246, "author": "user19898808", "author_id": 19898808, "author_profile": "https://Stackoverflow.com/users/19898808", "pm_score": 0, "selected": false, "text": "import re\n\ntxt = \"test[az5]test[az6]test\"\nx = re.findall(r\"\\[az(?P<num>\\d)\\]\", txt)\nprint(x)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74635176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20616285/" ]
74,635,204
<p>I have tried to split this string but unsuccessful because of the way the string is arranged in the column. The Null value keeps appearing on the Make and model column and the actually data goes to the wrong column</p> <p>Sample data:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>MakeModelColor</th> </tr> </thead> <tbody> <tr> <td>Apple - iphone 12</td> </tr> <tr> <td>Apple - iphone 12 pro max - black -128gb</td> </tr> <tr> <td>Samsung - galaxy A12</td> </tr> </tbody> </table> </div> <p>This is the result I am looking for:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Make</th> <th style="text-align: center;">Model</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">Apple</td> <td style="text-align: center;">iphone 12</td> </tr> <tr> <td style="text-align: left;">Apple</td> <td style="text-align: center;">iphone 12 pro max</td> </tr> <tr> <td style="text-align: left;">Samsung</td> <td style="text-align: center;">Galaxy A12</td> </tr> </tbody> </table> </div> <p><a href="https://i.stack.imgur.com/7vsMS.png" rel="nofollow noreferrer">Actual result am looking for </a>](<a href="https://i.stack.imgur.com/BvzYN.png" rel="nofollow noreferrer">https://i.stack.imgur.com/BvzYN.png</a>)</p>
[ { "answer_id": 74635319, "author": "Cetin Basoz", "author_id": 894977, "author_profile": "https://Stackoverflow.com/users/894977", "pm_score": 2, "selected": false, "text": "with data(makeModelColor, part, ordinal) as (\n select makeModelColor, ltrim(rtrim(value)), ordinal\nfrom devices\ncross apply (select * from String_Split(devices.makeModelColor,'-',1)) t)\nselect makeModelColor,\n max(case when ordinal = 1 then part end) as Make,\n max(case when ordinal = 2 then part end) as Model,\n max(case when ordinal = 3 then part end) as Color,\n max(case when ordinal = 4 then part end) as Other\n from data\ngroup by makeModelColor;\n" }, { "answer_id": 74635344, "author": "John Cappelletti", "author_id": 1570000, "author_profile": "https://Stackoverflow.com/users/1570000", "pm_score": 3, "selected": true, "text": " Select Make = trim(JSON_VALUE(JS,'$[0]'))\n ,Model = trim(JSON_VALUE(JS,'$[1]'))\n From YourTable A\n Cross Apply (values ('[\"'+replace(string_escape([MakeModelColor],'json'),'-','\",\"')+'\"]') ) B(JS)\n Make Model\nApple iphone 12\nApple iphone 12 pro max\nSamsung galaxy A12\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74635204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8753764/" ]
74,635,210
<p>Need to figure out an efficient way to query a table using another table as a filter/config (postgres 14.5).</p> <p>The filter table has 4 levels that match 4 levels in the data. Each level can be read as a RegExp with wildcard, where wildcard is null. But the rules are MUTUALLY EXCLUSIVE. meaning rule aa-* excludes the rule aa-ab-* and vice versa.</p> <p>e.g. Filter Table</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Category</th> <th>Level 1</th> <th>Level 2</th> <th>Level 3</th> <th>Level 4</th> </tr> </thead> <tbody> <tr> <td>Rule1</td> <td>A</td> <td>aa</td> <td>null</td> <td>null</td> <td>null</td> </tr> <tr> <td>Rule2</td> <td>A</td> <td>aa</td> <td>ab</td> <td>null</td> <td>null</td> </tr> <tr> <td>Rule3</td> <td>A</td> <td>ab</td> <td>null</td> <td>null</td> <td>null</td> </tr> <tr> <td>Rule4</td> <td>A</td> <td>ab</td> <td>ac</td> <td>aa</td> <td>null</td> </tr> </tbody> </table> </div> <p>In this case filter rule #1 is matching all aa-* data, except when it's aa-ab-* (rule #2) Similarly, rule #3 will match ab-* data, except ab-ac-aa-*</p> <p>e.g. Data Table</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Data</th> <th>Category</th> <th>Level 1</th> <th>Level 2</th> <th>Level 3</th> <th>Level 4</th> </tr> </thead> <tbody> <tr> <td>Data1</td> <td>A</td> <td>aa</td> <td>aa</td> <td>ac</td> <td>aa</td> </tr> <tr> <td>Data2</td> <td>A</td> <td>aa</td> <td>aa</td> <td>null</td> <td>null</td> </tr> <tr> <td>Data3</td> <td>A</td> <td>aa</td> <td>ab</td> <td>null</td> <td>null</td> </tr> <tr> <td>Data4</td> <td>A</td> <td>ab</td> <td>ab</td> <td>null</td> <td>null</td> </tr> <tr> <td>Data5</td> <td>A</td> <td>ab</td> <td>ac</td> <td>null</td> <td>null</td> </tr> <tr> <td>Data6</td> <td>A</td> <td>ab</td> <td>ac</td> <td>dd</td> <td>null</td> </tr> </tbody> </table> </div> <p>This way the join between the two should produce result like:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Data ID</th> <th>Rule ID</th> </tr> </thead> <tbody> <tr> <td>Data1</td> <td>Rule1</td> </tr> <tr> <td>Data2</td> <td>Rule1</td> </tr> <tr> <td>Data3</td> <td>Rule2</td> </tr> <tr> <td>Data4</td> <td>Rule3</td> </tr> <tr> <td>Data5</td> <td>Rule3</td> </tr> <tr> <td>Data6</td> <td>Rule3</td> </tr> </tbody> </table> </div> <p>Approach toward combining all levels into a string with &quot;level-combo&quot; seem to be inefficient and has gaps. The join based on coalesce(lvl, '') is not helpful either, it's not addressing the wildcard rules.</p> <pre><code>where coalesce(a.lvl1,'') = coalesce(c.lvl1,'') and coalesce(a.lvl2,'') = coalesce(c.lvl2,'') and coalesce(a.lvl3,'') = coalesce(c.lvl3,'') and coalesce(a.lvl4,'') = coalesce(c.lvl4,'') </code></pre> <h1>DATA to replicate:</h1> <pre><code>WITH config (id, category, lvl1, lvl2, lvl3, lvl4) AS ( VALUES (1, 's', null, null, null, null ), (2, 's', 'u7', null, null, null ), (3, 's', 'u6', 'u1', null, null ), (4, 's', 'u5', 'ud', 'u2', null ), (5, 's', 'u5', 'ud', 'u3', null ), (6, 's', 'u5', 'ud', 'u4', 'ok' ), (9, 's', 'u4', null, null, null ), (7, 's', 'u4', 'u1', 'u2', 'u3' ), (8, 's', 'u4', 'cu', 'u2', null ) ), datum (id, data_id, internal_id, start_date, end_date, category, lvl1, lvl2, lvl3, lvl4) AS ( VALUES (1, 'x1', '111', '2022-01-01', '2022-12-01', 's', null, null, null, null ), (2, 'x2', '112', '2022-01-01', '2022-12-01', 's', 'u7', null, null, null ), (3, 'x3', '113', '2022-01-01', '2022-12-01', 's', 'u6', 'u1', null, null ), (4, 'x4', '114', '2022-01-01', '2022-12-01', 's', 'u5', 'ud', 'u2', null ), (5, 'x5', '115', '2022-01-01', '2022-12-01', 's', 'u5', 'ud', 'u3', null ), (6, 'x6', '116', '2022-01-01', '2022-12-01', 's', 'u5', 'ud', 'u4', 'ok' ), (9, 'x9', '119', '2022-01-01', '2022-12-01', 's', 'u4', null, null, null ), (7, 'x7', '117', '2022-01-01', '2022-12-01', 's', 'u4', 'u1', 'u2', 'u3' ), (8, 'x8', '118', '2022-01-01', '2022-12-01', 's', 'u4', 'cu', 'u2', null ), (9, 'x2', '112', '2022-01-01', '2022-12-01', 's', 'u9', null, null, null ), (10, 'x3', '113', '2022-01-01', '2022-12-01', 's', 'u5', 'u1', null, null ), (11, 'x4', '114', '2022-01-01', '2022-12-01', 's', 'u5', 'dd', 'u2', null ), (12, 'x5', '115', '2022-01-01', '2022-12-01', 's', 'u5', 'ud', 'u3', 'ck' ), (13, 'x6', '116', '2022-01-01', '2022-12-01', 's', 'u5', 'ud', 'u4', 'no' ) ) SELECT * FROM config c join datum d on c.category = d.category and coalesce(c.lvl1, '') = coalesce(d.lvl1, '') and ... ; </code></pre>
[ { "answer_id": 74635319, "author": "Cetin Basoz", "author_id": 894977, "author_profile": "https://Stackoverflow.com/users/894977", "pm_score": 2, "selected": false, "text": "with data(makeModelColor, part, ordinal) as (\n select makeModelColor, ltrim(rtrim(value)), ordinal\nfrom devices\ncross apply (select * from String_Split(devices.makeModelColor,'-',1)) t)\nselect makeModelColor,\n max(case when ordinal = 1 then part end) as Make,\n max(case when ordinal = 2 then part end) as Model,\n max(case when ordinal = 3 then part end) as Color,\n max(case when ordinal = 4 then part end) as Other\n from data\ngroup by makeModelColor;\n" }, { "answer_id": 74635344, "author": "John Cappelletti", "author_id": 1570000, "author_profile": "https://Stackoverflow.com/users/1570000", "pm_score": 3, "selected": true, "text": " Select Make = trim(JSON_VALUE(JS,'$[0]'))\n ,Model = trim(JSON_VALUE(JS,'$[1]'))\n From YourTable A\n Cross Apply (values ('[\"'+replace(string_escape([MakeModelColor],'json'),'-','\",\"')+'\"]') ) B(JS)\n Make Model\nApple iphone 12\nApple iphone 12 pro max\nSamsung galaxy A12\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74635210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/295680/" ]
74,635,226
<p>I have the following array that I'm attempting to sort each <code>scores</code> array by <code>answer</code> from high to low.</p> <pre><code>$array = [ 503 =&gt; [ 'scores' =&gt; [ 4573 =&gt; ['answer' =&gt; 100], 4574 =&gt; ['answer' =&gt; 60], 4575 =&gt; ['answer' =&gt; 100], 4576 =&gt; ['answer' =&gt; 80], 4577 =&gt; ['answer' =&gt; 40], 4578 =&gt; ['answer' =&gt; 20], 4579 =&gt; ['answer' =&gt; 60], 4580 =&gt; ['answer' =&gt; 100], 4581 =&gt; ['answer' =&gt; 60], 4582 =&gt; ['answer' =&gt; 60], 4583 =&gt; ['answer' =&gt; 80], 4584 =&gt; ['answer' =&gt; 80], ], 'category' =&gt; 'Category A', 'grade' =&gt; 70, 'color' =&gt; NULL ], 504 =&gt; [ 'scores' =&gt; [ 4585 =&gt; ['answer' =&gt; 40], 4586 =&gt; ['answer' =&gt; 100], 4587 =&gt; ['answer' =&gt; 80], 4588 =&gt; ['answer' =&gt; 60], 4589 =&gt; ['answer' =&gt; 100], 4590 =&gt; ['answer' =&gt; 40], 4591 =&gt; ['answer' =&gt; 80], 4592 =&gt; ['answer' =&gt; 60], 4593 =&gt; ['answer' =&gt; 60], 4594 =&gt; ['answer' =&gt; 100], 4595 =&gt; ['answer' =&gt; 100], 4596 =&gt; ['answer' =&gt; 80], ], 'category' =&gt; 'Category B', 'grade' =&gt; 75, 'color' =&gt; NULL ], 505 =&gt; [ 'scores' =&gt; [ 4597 =&gt;['answer' =&gt; 20], 4598 =&gt;['answer' =&gt; 80], 4599 =&gt;['answer' =&gt; 100], 4600 =&gt;['answer' =&gt; 60], 4601 =&gt;['answer' =&gt; 20], 4602 =&gt;['answer' =&gt; 20], 4603 =&gt;['answer' =&gt; 100], 4604 =&gt;['answer' =&gt; 40], 4605 =&gt;['answer' =&gt; 60], 4606 =&gt;['answer' =&gt; 100], 4607 =&gt;['answer' =&gt; 80], 4608 =&gt;['answer' =&gt; 20], ], 'category' =&gt; 'Category C', 'grade' =&gt; 58.3, 'color' =&gt; NULL, ] ]; </code></pre> <p>I've attempted to use loops to get into the array level needed, but it isn't working...</p> <pre><code>$temp_array_questions = $array_categorygrades; function sortq ($a, $b) { $highestcountfora = 0; $highestcountforb = 0; foreach ($a as $thescores) { if (is_array($thescores)) { foreach ($thescores as $thequestions) { if (is_array($thequestions)) { foreach ($thequestions as $theanswers) { if ($theanswers['answer'] &gt; $highestcountfora) { $highestcountfora = $theanswers['answer']; } } } } } } foreach ($b as $thescores) { if (is_array($thescores)) { foreach ($thescores as $thequestions) { if (is_array($thequestions)) { foreach ($thequestions as $theanswers) { if ($theanswers['answer'] &gt; $highestcountforb) { $highestcountforb = $theanswers['answer']; } } } } } } if ($highestcountfora === $highestcountforb) { return 0; } return ($highestcountfora &lt; $highestcountforb)?1:-1; //if($a['scores']['answer']==$b['scores']['answer']) return 0; //return $a['scores']['answer'] &lt; $b['scores']['answer']?1:-1; } uasort($temp_array_questions, 'sortq'); </code></pre> <p>The array should look like this after sorting (keeping the top-level categories intact):</p> <pre><code>[ 503 =&gt; [ 'scores' =&gt; [ 4573 =&gt; ['answer' =&gt; 100], 4575 =&gt; ['answer' =&gt; 100], 4580 =&gt; ['answer' =&gt; 100], 4576 =&gt; ['answer' =&gt; 80], 4583 =&gt; ['answer' =&gt; 80], 4584 =&gt; ['answer' =&gt; 80], 4574 =&gt; ['answer' =&gt; 60], 4579 =&gt; ['answer' =&gt; 60], 4581 =&gt; ['answer' =&gt; 60], 4582 =&gt; ['answer' =&gt; 60], 4577 =&gt; ['answer' =&gt; 40], 4578 =&gt; ['answer' =&gt; 20], ], 'category' =&gt; 'Category A', 'grade' =&gt; 70, 'color' =&gt; NULL ], 504 =&gt; [ 'scores' =&gt; [ 4586 =&gt; ['answer' =&gt; 100], 4589 =&gt; ['answer' =&gt; 100], 4594 =&gt; ['answer' =&gt; 100], 4595 =&gt; ['answer' =&gt; 100], 4587 =&gt; ['answer' =&gt; 80], 4591 =&gt; ['answer' =&gt; 80], 4596 =&gt; ['answer' =&gt; 80], 4588 =&gt; ['answer' =&gt; 60], 4592 =&gt; ['answer' =&gt; 60], 4593 =&gt; ['answer' =&gt; 60], 4585 =&gt; ['answer' =&gt; 40], 4590 =&gt; ['answer' =&gt; 40], ], 'category' =&gt; 'Category B', 'grade' =&gt; 75, 'color' =&gt; NULL ], 505 =&gt; [ 'scores' =&gt; [ 4599 =&gt;['answer' =&gt; 100], 4603 =&gt;['answer' =&gt; 100], 4606 =&gt;['answer' =&gt; 100], 4598 =&gt;['answer' =&gt; 80], 4607 =&gt;['answer' =&gt; 80], 4600 =&gt;['answer' =&gt; 60], 4605 =&gt;['answer' =&gt; 60], 4604 =&gt;['answer' =&gt; 40], 4597 =&gt;['answer' =&gt; 20], 4601 =&gt;['answer' =&gt; 20], 4602 =&gt;['answer' =&gt; 20], 4608 =&gt;['answer' =&gt; 20], ], 'category' =&gt; 'Category C', 'grade' =&gt; 58.3, 'color' =&gt; NULL, ] ] </code></pre>
[ { "answer_id": 74635319, "author": "Cetin Basoz", "author_id": 894977, "author_profile": "https://Stackoverflow.com/users/894977", "pm_score": 2, "selected": false, "text": "with data(makeModelColor, part, ordinal) as (\n select makeModelColor, ltrim(rtrim(value)), ordinal\nfrom devices\ncross apply (select * from String_Split(devices.makeModelColor,'-',1)) t)\nselect makeModelColor,\n max(case when ordinal = 1 then part end) as Make,\n max(case when ordinal = 2 then part end) as Model,\n max(case when ordinal = 3 then part end) as Color,\n max(case when ordinal = 4 then part end) as Other\n from data\ngroup by makeModelColor;\n" }, { "answer_id": 74635344, "author": "John Cappelletti", "author_id": 1570000, "author_profile": "https://Stackoverflow.com/users/1570000", "pm_score": 3, "selected": true, "text": " Select Make = trim(JSON_VALUE(JS,'$[0]'))\n ,Model = trim(JSON_VALUE(JS,'$[1]'))\n From YourTable A\n Cross Apply (values ('[\"'+replace(string_escape([MakeModelColor],'json'),'-','\",\"')+'\"]') ) B(JS)\n Make Model\nApple iphone 12\nApple iphone 12 pro max\nSamsung galaxy A12\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74635226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7318297/" ]
74,635,227
<p>Can someone explain to me what is going on here?</p> <p>I'm trying to get pyenv and poetry to place nice together. I am on an AWS instance of <code>Ubuntu 20.04</code> which has <code>python 3.8.10</code> installed. (I have removed all traces of python2 from the system). I would like to use python 3.10 but I can't just upgrade to that (thank you very much Amazon). So enter <code>pyenv</code>.</p> <p>I made an empty project with the <code>poetry new</code> command and here is the <code>pyproject.toml</code> file.</p> <pre class="lang-ini prettyprint-override"><code>[tool.poetry] name = &quot;test&quot; version = &quot;0.1.0&quot; description = &quot;&quot; authors = [&quot;ken &lt;crowmagnumb@gmail.com&gt;&quot;] readme = &quot;README.md&quot; [tool.poetry.dependencies] python = &quot;^3.10&quot; [build-system] requires = [&quot;poetry-core&quot;] build-backend = &quot;poetry.core.masonry.api&quot; </code></pre> <p>I have 3.10.7 installed through pyenv. If I run <code>poetry run python --version</code> I get the following output.</p> <pre><code>The currently activated Python version 3.8.10 is not supported by the project (^3.10). Trying to find and use a compatible version. Using python3 (3.10.7) Python 3.8.10 </code></pre> <p>It finds and &quot;uses&quot; 3.10.7 but then reports 3.8.10? Huh?</p> <p>If I then run <code>poetry env use 3.10</code> and try again I get ...</p> <pre><code>Current Python version (3.8.10) is not allowed by the project (^3.10). Please change python executable via the &quot;env use&quot; command. </code></pre> <p>... and it fails to run completely, i.e. no version reported from the python command. How is my current python version still 3.8.10. If I run <code>python --version</code> at the command-line straight away (not through poetry), I get <code>3.10.7</code>. What is going on here?!</p> <p>As a check if I run <code>poetry env use system</code> then I indeed get back to my first problem. :(</p>
[ { "answer_id": 74639052, "author": "9769953", "author_id": 9769953, "author_profile": "https://Stackoverflow.com/users/9769953", "pm_score": 0, "selected": false, "text": "poetry new poetry init pyproject.toml python -m poetry init python3.11 -m pip install ." }, { "answer_id": 74639166, "author": "se7en", "author_id": 14752392, "author_profile": "https://Stackoverflow.com/users/14752392", "pm_score": -1, "selected": false, "text": "pyenv global 3.10 pyproject.toml pyenv install 3.x pyenv global 3.x local global" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74635227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/433432/" ]
74,635,249
<p>I often do the following:</p> <pre><code>docker run -dt myimage docker ps # This step gives the container id necessary for next step docker exec -it &lt;container-id&gt; bash </code></pre> <p>Ideally I'd like to do it all in one line</p> <pre><code>docker run -dt myimage &amp;&amp; docker exec -it &lt;id&gt; bash </code></pre> <p>but I don't know how to get the container id to <code>docker exec</code> without looking it up in a separate step.</p> <h3>Question</h3> <p>Is there a one-liner to run an image and shell into its container?</p>
[ { "answer_id": 74635277, "author": "Garrett Hyde", "author_id": 250168, "author_profile": "https://Stackoverflow.com/users/250168", "pm_score": 2, "selected": true, "text": "docker run --name mycontainer -d myimage\ndocker exec -it mycontainer bash\n docker run --name mycontainer --rm --entrypoint=\"\" -it myimage bash\n docker run --name mycontainer --rm --entrypoint=\"\" myimage echo \"Hello, World!\"\n" }, { "answer_id": 74642587, "author": "stevec", "author_id": 5783745, "author_profile": "https://Stackoverflow.com/users/5783745", "pm_score": 0, "selected": false, "text": "&& The container name xxxx is already in use { docker stop $(docker ps -a -q) } || {} && \\\ndocker container prune -f && \\\ndocker build -t myimage . && \\\ndocker run --name mycontainer -dt myimage && \\\ndocker exec -it mycontainer bash\n docker stop $(docker ps -a -q) docker container prune -f" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74635249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5783745/" ]
74,635,284
<p>I have the following cell in jupyter notebook. What is in ***** is confidential information</p> <pre><code>import psycopg2 import sqlalchemy as sa import pandas as pds from sqlalchemy import create_engine # Create an engine instance alchemyEngine = create_engine('*****************************', pool_recycle=3600); # engine = create_engine('**************************') # Connect to PostgreSQL server dbConnection = alchemyEngine.connect(); # Read data from PostgreSQL database table and load into a DataFrame instance team = sa.Table('dialog_logger', sa.MetaData(), autoload_with=dbConnection, schema='hca') qry = sa.select(team.c.hos_name, team.c.hos_id, team.c.datetime, team.c.patient_cel_number, team.c.hospital_cel_number, team.c.message, team.c.direction).where( team.c.datetime &gt; '2022-11-01 00:00:00').where(team.c.datetime &lt; '2022-11-30 00:00:00') dataFrame_argentina = pds.read_sql_query(qry, dbConnection) pds.set_option('display.expand_frame_repr', False); # Close the database connection dbConnection.close(); </code></pre> <p>I must execute it but it gives me the following error when doing it:</p> <pre><code>AttributeError Traceback (most recent call last) C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\sql\elements.py in __getattr__(self, key) 722 try: --&gt; 723 return getattr(self.comparator, key) 724 except AttributeError: AttributeError: 'Comparator' object has no attribute 'selectable' During handling of the above exception, another exception occurred: AttributeError Traceback (most recent call last) C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\sql\selectable.py in _interpret_as_from(element) 60 try: ---&gt; 61 return insp.selectable 62 except AttributeError: C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\sql\elements.py in __getattr__(self, key) 726 &quot;Neither %r object nor %r object has an attribute %r&quot; --&gt; 727 % (type(self).__name__, type(self.comparator).__name__, key) 728 ) AttributeError: Neither 'Column' object nor 'Comparator' object has an attribute 'selectable' During handling of the above exception, another exception occurred: ArgumentError Traceback (most recent call last) &lt;ipython-input-3-ec4194d4c35c&gt; in &lt;module&gt; 1 qry = sa.select(team.c.hos_name, team.c.hos_id, team.c.datetime, team.c.patient_cel_number, ----&gt; 2 team.c.hospital_cel_number, team.c.message, team.c.direction).where( 3 team.c.datetime &gt; '2022-11-01 00:00:00').where(team.c.datetime &lt; '2022-11-30 00:00:00') 4 5 &lt;string&gt; in select(columns, whereclause, from_obj, distinct, having, correlate, prefixes, suffixes, **kwargs) &lt;string&gt; in __init__(self, columns, whereclause, from_obj, distinct, having, correlate, prefixes, suffixes, **kwargs) C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\util\deprecations.py in warned(fn, *args, **kwargs) 126 ) 127 --&gt; 128 return fn(*args, **kwargs) 129 130 doc = fn.__doc__ is not None and fn.__doc__ or &quot;&quot; C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\sql\selectable.py in __init__(self, columns, whereclause, from_obj, distinct, having, correlate, prefixes, suffixes, **kwargs) 2977 if from_obj is not None: 2978 self._from_obj = util.OrderedSet( -&gt; 2979 _interpret_as_from(f) for f in util.to_list(from_obj) 2980 ) 2981 else: C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\util\_collections.py in __init__(self, d) 363 self._list = [] 364 if d is not None: --&gt; 365 self._list = unique_list(d) 366 set.update(self, self._list) 367 else: C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\util\_collections.py in unique_list(seq, hashfunc) 777 seen_add = seen.add 778 if not hashfunc: --&gt; 779 return [x for x in seq if x not in seen and not seen_add(x)] 780 else: 781 return [ C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\util\_collections.py in &lt;listcomp&gt;(.0) 777 seen_add = seen.add 778 if not hashfunc: --&gt; 779 return [x for x in seq if x not in seen and not seen_add(x)] 780 else: 781 return [ C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\sql\selectable.py in &lt;genexpr&gt;(.0) 2977 if from_obj is not None: 2978 self._from_obj = util.OrderedSet( -&gt; 2979 _interpret_as_from(f) for f in util.to_list(from_obj) 2980 ) 2981 else: C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\sql\selectable.py in _interpret_as_from(element) 61 return insp.selectable 62 except AttributeError: ---&gt; 63 raise exc.ArgumentError(&quot;FROM expression expected&quot;) 64 65 ArgumentError: FROM expression expected </code></pre> <p>Debugging I saw that everything runs fine until this select starts: qry = sa.select(......). I don't know if the error comes from the library that I need to install before executing this cell.</p>
[ { "answer_id": 74635277, "author": "Garrett Hyde", "author_id": 250168, "author_profile": "https://Stackoverflow.com/users/250168", "pm_score": 2, "selected": true, "text": "docker run --name mycontainer -d myimage\ndocker exec -it mycontainer bash\n docker run --name mycontainer --rm --entrypoint=\"\" -it myimage bash\n docker run --name mycontainer --rm --entrypoint=\"\" myimage echo \"Hello, World!\"\n" }, { "answer_id": 74642587, "author": "stevec", "author_id": 5783745, "author_profile": "https://Stackoverflow.com/users/5783745", "pm_score": 0, "selected": false, "text": "&& The container name xxxx is already in use { docker stop $(docker ps -a -q) } || {} && \\\ndocker container prune -f && \\\ndocker build -t myimage . && \\\ndocker run --name mycontainer -dt myimage && \\\ndocker exec -it mycontainer bash\n docker stop $(docker ps -a -q) docker container prune -f" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74635284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20101840/" ]
74,635,300
<p>How i can create a function for reading structure from a test.txt. I have a good works code in main, but i need to carry out it from main(). How combine (struct student PI1[N] and (fread() or fgets() or fwrite()));</p> <pre><code>struct student { char surname[50]; char name[50]; char dayBirth[50]; int mark; }; struct student PI1[N]; </code></pre> <pre><code>int main() { int counter = 0; char str[50]; const char s[2] = &quot; &quot;; char* token; FILE* ptr; int i = 0; ptr = fopen(&quot;test.txt&quot;, &quot;r&quot;); if (NULL == ptr) { printf(&quot;file can't be opened \n&quot;); } char* tmp; int Itmp; while (fgets(str, 50, ptr) != NULL) { token = strtok(str, s); strcpy(PI1[i].surname, token); token = strtok(NULL, s); strcpy(PI1[i].name, token); token = strtok(NULL, s); strcpy(PI1[i].dayBirth, token); token = strtok(NULL, s); Itmp = atoi(token); PI1[i].mark = Itmp; i++; counter++; } } </code></pre>
[ { "answer_id": 74635571, "author": "chux - Reinstate Monica", "author_id": 2410359, "author_profile": "https://Stackoverflow.com/users/2410359", "pm_score": 2, "selected": false, "text": "fgets() struct sprintf() \" %n\" // Return success flag\nbool string_to_student(struct student *stu, const char *s) {\n int n = 0;\n sscanf(s, \"%49s%49s%49s%d %n\", stu->surname, stu->name,\n stu->dayBirth, &stu->mark, &n);\n return n > 0 && s[n] == '\\0';\n}\n while (i < N && fgets(str, sizeof str, ptr) && \n string_to_student(&PI1[i], str)) {\n i++;\n}\ncounter = i;\n" }, { "answer_id": 74638515, "author": "Elia Karrer", "author_id": 17653989, "author_profile": "https://Stackoverflow.com/users/17653989", "pm_score": -1, "selected": false, "text": "FILE* fp;\nstruct student;\n\nfp = fopen(\"test.txt\", \"wb\");\nfwrite(&student, 1, sizeof(student), fp);\nfclose(fp);\n FILE* fp;\nstruct student;\n\nfp = fopen(\"test.txt\", \"rb\");\nfread(&student, 1, sizeof(student), fp);\nfclose(fp);\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74635300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20294643/" ]
74,635,307
<p>Just getting started with ES6 classes. As far as I understood it, <strong>this</strong> was supposed to behave predictably inside a class and always point to the object. However, that doesn't seem to be the case:</p> <pre><code>class BodyPixController { #target; //Declare a private property constructor(target){ this.#target = target; // Set the property console.log(this); // logs: BodyPixController {#target: 'photo'} addEventListener('load', this.init); // Calls the method } init() { console.log(this); // logs: Window {window: Window, self: Window, document: document, name: '', location: Location,…} const img = document.getElementById(this.#target); // Throws error: Cannot read private member #target from an object whose class did not declare it console.log(img); async function loadAndPredict() { const net = await bodyPix.load( /** optional arguments, see below **/ ); const segmentation = await net.segmentPerson(img); console.log(segmentation); } loadAndPredict(); } } </code></pre> <p>In the code above, <strong>this</strong> only points to the instantiated object inside the constructor. As soon as the init() method is called, <strong>this</strong> points to Window. Why? And how do I access private properties from inside methods?</p>
[ { "answer_id": 74635338, "author": "Code Spirit", "author_id": 6770305, "author_profile": "https://Stackoverflow.com/users/6770305", "pm_score": 2, "selected": false, "text": "this load Window constructor() {\n // bind this inside init to current object\n this.init = this.init.bind(this);\n\n addEventListener('load', this.init);\n}\n" }, { "answer_id": 74635415, "author": "Hashbrown", "author_id": 2518317, "author_profile": "https://Stackoverflow.com/users/2518317", "pm_score": 1, "selected": false, "text": "init() { init = () => { this .apply()" }, { "answer_id": 74635710, "author": "Mark Schultheiss", "author_id": 125981, "author_profile": "https://Stackoverflow.com/users/125981", "pm_score": 0, "selected": false, "text": "e.target this class BodyPixController {\n constructor(target) {\n this.target = target;\n console.log(this);\n this.target.addEventListener('load', this);\n }\n boundLoad = () => this.loadEvent()\n boundInit = this.init.bind(this)\n init(e) {\n console.log(e);\n const img = document.getElementById(e.target);\n console.log(img);\n async function loadAndPredict() {\n const net = await bodyPix.load( /** optional arguments, see below **/ );\n const segmentation = await net.segmentPerson(img);\n console.log(segmentation);\n }\n loadAndPredict();\n }\n loadEvent(e){\n // Some action related to the event (e)\n console.log(e.target);\n console.log(\"loadEvent:\",this);\n console.log(\"What:\",e.target.innerText);\n }\n handleEvent(e) {\n switch (e.type) {\n case \"load\":\n this.loadEvent(e);\n break;\n case \"init\":\n this.init(e);\n break;\n }\n }\n}\nvar target = document.querySelector(\".fun-target\");\nvar myInstance = new BodyPixController(target);\ntarget.dispatchEvent(new CustomEvent('load'), {}) <div class=\"fun-target\">howdy</div>" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74635307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4344987/" ]
74,635,309
<p>Im trying to fetch data from external api, but my screen show this error message:</p> <pre><code>[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'Null' is not a subtype of type 'bool' </code></pre> <p>My Screen code is this:</p> <pre><code>class PricesScreen extends StatefulWidget { const PricesScreen({super.key}); @override State&lt;PricesScreen&gt; createState() =&gt; _PricesScreenState(); } class _PricesScreenState extends State&lt;PricesScreen&gt; { late Response response; Dio dio = Dio(); var apidata; bool error = false; //for error status bool loading = false; //for data featching status String errmsg = &quot;&quot;; getData() async { String baseUrl = &quot;https://economia.awesomeapi.com.br/last/USD-BRL&quot;; Response response = await dio.get(baseUrl); apidata = response.data; print(response); if(response.statusCode == 200){ if(apidata[&quot;error&quot;]){ error = true; errmsg = apidata[&quot;msg&quot;]; } }else{ error = true; errmsg = &quot;Error while fetching data.&quot;; } } @override void initState() { getData(); //fetching data super.initState(); } @override Widget build(BuildContext context) { return Container( padding: const EdgeInsets.all(8), child: loading? const CircularProgressIndicator() : Container( child:error?Text(&quot;Error: $errmsg&quot;): Column( children:apidata[&quot;data&quot;].map&lt;Widget&gt;((coin){ return CurrencyContainer( name: coin[&quot;name&quot;], increase: coin[&quot;varBid&quot;], symbol: coin[&quot;code&quot;], value: coin[&quot;high&quot;] ); }).toList(), ) ) ); } } </code></pre> <p>My print message show the data from api:</p> <pre><code>{&quot;USDBRL&quot;:{&quot;code&quot;:&quot;USD&quot;,&quot;codein&quot;:&quot;BRL&quot;,&quot;name&quot;:&quot;Dólar Americano/Real Brasileiro&quot;,&quot;high&quot;:&quot;5.1856&quot;,&quot;low&quot;:&quot;5.1856&quot;,&quot;varBid&quot;:&quot;0.0004&quot;,&quot;pctChange&quot;:&quot;0.01&quot;,&quot;bid&quot;:&quot;5.1851&quot;,&quot;ask&quot;:&quot;5.186&quot;,&quot;timestamp&quot;:&quot;1669850610&quot;,&quot;create_date&quot;:&quot;2022-11-30 20:23:30&quot;}} </code></pre> <p>I tried to access data as 'apidata = response[&quot;USDBRL&quot;]' but it show error: lib/screens/prices.dart:27:23: Error: The operator '[]' isn't defined for the class 'Response'.</p> <ul> <li>'Response' is from 'package:dio/src/response.dart' ('../../snap/flutter/common/flutter/.pub-cache/hosted/pub.dartlang.org/dio-4.0.6/lib/src/response.dart'). Try correcting the operator to an existing operator, or defining a '[]' operator. apidata = response[&quot;USDBRL&quot;];</li> </ul> <p>How can i show the data in screen?</p>
[ { "answer_id": 74635338, "author": "Code Spirit", "author_id": 6770305, "author_profile": "https://Stackoverflow.com/users/6770305", "pm_score": 2, "selected": false, "text": "this load Window constructor() {\n // bind this inside init to current object\n this.init = this.init.bind(this);\n\n addEventListener('load', this.init);\n}\n" }, { "answer_id": 74635415, "author": "Hashbrown", "author_id": 2518317, "author_profile": "https://Stackoverflow.com/users/2518317", "pm_score": 1, "selected": false, "text": "init() { init = () => { this .apply()" }, { "answer_id": 74635710, "author": "Mark Schultheiss", "author_id": 125981, "author_profile": "https://Stackoverflow.com/users/125981", "pm_score": 0, "selected": false, "text": "e.target this class BodyPixController {\n constructor(target) {\n this.target = target;\n console.log(this);\n this.target.addEventListener('load', this);\n }\n boundLoad = () => this.loadEvent()\n boundInit = this.init.bind(this)\n init(e) {\n console.log(e);\n const img = document.getElementById(e.target);\n console.log(img);\n async function loadAndPredict() {\n const net = await bodyPix.load( /** optional arguments, see below **/ );\n const segmentation = await net.segmentPerson(img);\n console.log(segmentation);\n }\n loadAndPredict();\n }\n loadEvent(e){\n // Some action related to the event (e)\n console.log(e.target);\n console.log(\"loadEvent:\",this);\n console.log(\"What:\",e.target.innerText);\n }\n handleEvent(e) {\n switch (e.type) {\n case \"load\":\n this.loadEvent(e);\n break;\n case \"init\":\n this.init(e);\n break;\n }\n }\n}\nvar target = document.querySelector(\".fun-target\");\nvar myInstance = new BodyPixController(target);\ntarget.dispatchEvent(new CustomEvent('load'), {}) <div class=\"fun-target\">howdy</div>" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74635309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13509268/" ]
74,635,313
<p>I come from a land of ASP.NET Core. Having fun learning a completely new stack.</p> <p>I'm used to being able to:</p> <ol> <li>name a route &quot;orders&quot;</li> <li>give it a path like <code>/customer-orders/{id}</code></li> <li>register it</li> <li>use the routing system to build a URL for my named route</li> </ol> <p>An example of (4) might be to pass a <code>routeName</code> and then <code>routeValues</code> which is an object like <code>{ id = 193, x = &quot;y&quot; }</code> and the routing system can figure out the URL <code>/customer-orders/193?x=y</code> - notice how it just appends extraneous key-vals as params.</p> <p>Can I do something like this in oak on Deno?? Thanks.</p> <p>Update: I am looking into some functions on the underlying regexp tool the routing system uses. It doesn't seem right that this often used feature should be so hard/undiscoverable/inaccessible.</p> <p><a href="https://github.com/pillarjs/path-to-regexp#compile-reverse-path-to-regexp" rel="nofollow noreferrer">https://github.com/pillarjs/path-to-regexp#compile-reverse-path-to-regexp</a></p>
[ { "answer_id": 74635338, "author": "Code Spirit", "author_id": 6770305, "author_profile": "https://Stackoverflow.com/users/6770305", "pm_score": 2, "selected": false, "text": "this load Window constructor() {\n // bind this inside init to current object\n this.init = this.init.bind(this);\n\n addEventListener('load', this.init);\n}\n" }, { "answer_id": 74635415, "author": "Hashbrown", "author_id": 2518317, "author_profile": "https://Stackoverflow.com/users/2518317", "pm_score": 1, "selected": false, "text": "init() { init = () => { this .apply()" }, { "answer_id": 74635710, "author": "Mark Schultheiss", "author_id": 125981, "author_profile": "https://Stackoverflow.com/users/125981", "pm_score": 0, "selected": false, "text": "e.target this class BodyPixController {\n constructor(target) {\n this.target = target;\n console.log(this);\n this.target.addEventListener('load', this);\n }\n boundLoad = () => this.loadEvent()\n boundInit = this.init.bind(this)\n init(e) {\n console.log(e);\n const img = document.getElementById(e.target);\n console.log(img);\n async function loadAndPredict() {\n const net = await bodyPix.load( /** optional arguments, see below **/ );\n const segmentation = await net.segmentPerson(img);\n console.log(segmentation);\n }\n loadAndPredict();\n }\n loadEvent(e){\n // Some action related to the event (e)\n console.log(e.target);\n console.log(\"loadEvent:\",this);\n console.log(\"What:\",e.target.innerText);\n }\n handleEvent(e) {\n switch (e.type) {\n case \"load\":\n this.loadEvent(e);\n break;\n case \"init\":\n this.init(e);\n break;\n }\n }\n}\nvar target = document.querySelector(\".fun-target\");\nvar myInstance = new BodyPixController(target);\ntarget.dispatchEvent(new CustomEvent('load'), {}) <div class=\"fun-target\">howdy</div>" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74635313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/107783/" ]
74,635,358
<p>I am am using ansible to add admin user in mongodb.. I used below playbook but i am getting error. Can someone suggest the solution.. i have also installed pymongo prior to adding user in order to use module. authentication is disabled in mongod.conf and bindIp is set to 0.0.0.0</p> <pre><code>- hosts: devqa_mongod_single:dwprod_mongod_single become: yes tasks: # volume config for mongodb - name: Create a new xfs primary partition community.general.parted: device: /dev/nvme1n1 number: 1 state: present fs_type: xfs label: gpt - name: Create an xfs filesystem on /dev/nvme1n1 community.general.filesystem: fstype: xfs state: present dev: /dev/nvme1n1p1 - name: Create Directory /data/db ansible.builtin.file: path: /data/db state: directory owner: root group: root mode: 0751 - name: Fetch the UUID of /dev/nvme1n1p1 command: blkid -s UUID -o value /dev/nvme1n1p1 changed_when: false register: blkid_out - name: Mount /dev/nvme1n1 by UUID ansible.posix.mount: path: /data/db src: UUID={{ blkid_out.stdout }} fstype: xfs opts: &quot;defaults,nofail&quot; passno: 2 state: mounted # Installation of mongodb - name: Install aptitude using apt apt: name: aptitude state: latest update_cache: yes - name: Import public key apt_key: url: 'https://www.mongodb.org/static/pgp/server-6.0.asc' state: present - name: Add repository apt_repository: filename: '/etc/apt/sources.list.d/mongodb-org-6.0.list' repo: 'deb https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/6.0 multiverse' state: present update_cache: yes - name: Install mongoDB apt: name: mongodb-org state: present update_cache: yes - name: Ensure mongodb is running and and enabled to start automatically on reboots service: name: mongod enabled: yes state: started # Installing pymongo to use community.mongodb.mongodb_user module - name: &quot;Install PyMongo&quot; apt: update_cache: yes name: &quot;python3-pymongo&quot; state: &quot;latest&quot; # copy config file - name: user_init | set temporary conf become: yes timeout: 300 ansible.builtin.copy: src: ../templates/mongodb/mongod_init.conf.j2 dest: /etc/mongod.conf owner: root group: root mode: '0644' notify: - restart mongodb # create mongoadmin user - name: Create mongoadmin root user #community.mongodb.mongodb_user: mongodb_user: login_port: 27017 database: &quot;admin&quot; name: &quot;mongoadmin&quot; password: &quot;mongoadmin&quot; roles: &quot;root&quot; #ignore_errors: yes notify: - restart mongodb - name: conf | set become: yes timeout: 300 ansible.builtin.copy: src: ../templates/mongodb/mongodb/mongod.conf.j2 dest: /etc/mongod.conf owner: root group: root mode: '0644' register: mongo_conf_set notify: - restart mongodb - name: Copy mongodb config file for log rotation become: yes timeout: 300 ansible.builtin.copy: src: ../templates/mongodb/mongodb dest: /etc/logrotate.d/mongodb owner: root group: root mode: 0644 - name: Create Directory /var/run/mongodb ansible.builtin.file: path: /var/run/mongodb state: directory owner: mongodb group: mongodb mode: 0751 notify: - restart mongodb - name: Recursively change ownership of a /data/db ansible.builtin.file: path: /data/db state: directory recurse: yes owner: mongodb group: mongodb handlers: - name: restart mongodb service: name=mongod state=restarted </code></pre> <p>I am getting below error</p> <pre><code>fatal: [devqa_mongod_single]: FAILED! =&gt; {&quot;changed&quot;: false, &quot;msg&quot;: &quot;Unable to connect to database: Unknown option directconnection&quot;} </code></pre>
[ { "answer_id": 74635338, "author": "Code Spirit", "author_id": 6770305, "author_profile": "https://Stackoverflow.com/users/6770305", "pm_score": 2, "selected": false, "text": "this load Window constructor() {\n // bind this inside init to current object\n this.init = this.init.bind(this);\n\n addEventListener('load', this.init);\n}\n" }, { "answer_id": 74635415, "author": "Hashbrown", "author_id": 2518317, "author_profile": "https://Stackoverflow.com/users/2518317", "pm_score": 1, "selected": false, "text": "init() { init = () => { this .apply()" }, { "answer_id": 74635710, "author": "Mark Schultheiss", "author_id": 125981, "author_profile": "https://Stackoverflow.com/users/125981", "pm_score": 0, "selected": false, "text": "e.target this class BodyPixController {\n constructor(target) {\n this.target = target;\n console.log(this);\n this.target.addEventListener('load', this);\n }\n boundLoad = () => this.loadEvent()\n boundInit = this.init.bind(this)\n init(e) {\n console.log(e);\n const img = document.getElementById(e.target);\n console.log(img);\n async function loadAndPredict() {\n const net = await bodyPix.load( /** optional arguments, see below **/ );\n const segmentation = await net.segmentPerson(img);\n console.log(segmentation);\n }\n loadAndPredict();\n }\n loadEvent(e){\n // Some action related to the event (e)\n console.log(e.target);\n console.log(\"loadEvent:\",this);\n console.log(\"What:\",e.target.innerText);\n }\n handleEvent(e) {\n switch (e.type) {\n case \"load\":\n this.loadEvent(e);\n break;\n case \"init\":\n this.init(e);\n break;\n }\n }\n}\nvar target = document.querySelector(\".fun-target\");\nvar myInstance = new BodyPixController(target);\ntarget.dispatchEvent(new CustomEvent('load'), {}) <div class=\"fun-target\">howdy</div>" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74635358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11107951/" ]
74,635,385
<p>I am writing a div right now that will hold multiple lines of text but I need to remove the spacing after every text item. Is there a way to do this in CSS?</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>h3 { font-family: BelyDisplay; display: flex; padding: 0px; margin-left: 3rem; margin-right: 3rem; text-align: left; font: normal normal bold 25px/55px Montserrat; letter-spacing: 0px; color: #F0532D; opacity: 1; } h4 { font-family: BelyDisplay; display: flex; padding: 0px; margin-left: 3rem; margin-right: 3rem; align-items: center; text-align: left; letter-spacing: 0px; opacity: 1; font: normal normal bold 18px/22px Montserrat; color: #483735; .role-text{ font-family: Montserrat-Regular; margin-left: 3rem; margin-right: 3rem; padding-top: 1rem; padding-bottom: 1rem; text-align: left; letter-spacing: 0px; opacity: 1; font: normal normal normal 18px/22px Montserrat; color: #483735; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="textbox"&gt; &lt;span id="close" onclick="this.parentNode.remove(); location.reload(); return false;" class="btn btn-default large"&gt; &lt;img src="/src/Esc X.svg" height="33" width="33"&gt;&lt;/img&gt; &lt;/span&gt; &lt;h2&gt;${roleTypes[role]?.title ?? 'none'}&lt;/h2&gt; &lt;div id="card-div"&gt; &lt;p class="role-subtitle"&gt;${roleTypes[role]?.subtitle ?? 'none'}&lt;/p&gt; &lt;h3&gt;CHARGE&lt;/h3&gt; &lt;h4&gt;${roleTypes[role]?.chargesubtitle ?? 'none'}&lt;/h4&gt; &lt;p class="role-text"&gt;${roleTypes[role]?.chargebody ?? 'none'}&lt;/p&gt; &lt;h3&gt;SCOPE&lt;/h3&gt; &lt;h4&gt;${roleTypes[role]?.scopesubtitle ?? 'none'}&lt;/h4&gt; &lt;p class="role-text"&gt;${roleTypes[role]?.scopebody ?? 'none'}&lt;/p&gt; &lt;h3&gt;FORECASTING&lt;/h3&gt; &lt;h4&gt;${roleTypes[role]?.forecastingsubtitle ?? 'none'}&lt;/h4&gt; &lt;p class="role-text"&gt;${roleTypes[role]?.forecastingbody ?? 'none'}&lt;/p&gt; &lt;h3&gt;COMMUNICATION + RESPONSIBILITY&lt;/h3&gt; &lt;h4&gt;${roleTypes[role]?.communicationsubtitle ?? 'none'}&lt;/h4&gt; &lt;p class="role-text"&gt;${roleTypes[role]?.communicationbody ?? 'none'}&lt;/p&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Currently the text shows correctly based on the XD I've been given from UX/UI but the text should be stacked on top of each other with no spacing between them.</p>
[ { "answer_id": 74635836, "author": "tao", "author_id": 1891677, "author_profile": "https://Stackoverflow.com/users/1891677", "pm_score": 2, "selected": true, "text": "h4 {} h4 .role-text .role-text h4 .role-text 0 h3 h4 p h3, h4 {\n margin: 0 3rem;\n}\np {\n margin: 0;\n}\n" }, { "answer_id": 74635842, "author": "ChanHyeok-Im", "author_id": 6329353, "author_profile": "https://Stackoverflow.com/users/6329353", "pm_score": 0, "selected": false, "text": "h3 {\n font-family: BelyDisplay;\n display: flex;\n padding: 0px;\n margin: 0;\n margin-left: 3rem;\n margin-right: 3rem;\n text-align: left;\n font: normal normal bold 25px/55px Montserrat;\n letter-spacing: 0px;\n color: #F0532D;\n opacity: 1; \n}\n\nh4 {\n font-family: BelyDisplay;\n display: flex;\n padding: 0px;\n margin: 0;\n margin-left: 3rem;\n margin-right: 3rem;\n align-items: center;\n text-align: left;\n letter-spacing: 0px;\n opacity: 1; \n font: normal normal bold 18px/22px Montserrat;\n color: #483735;\n\n.role-text{\n font-family: Montserrat-Regular;\n margin-left: 3rem;\n margin-right: 3rem;\n padding-top: 1rem;\n padding-bottom: 1rem;\n text-align: left;\n letter-spacing: 0px;\n opacity: 1;\n font: normal normal normal 18px/22px Montserrat;\n color: #483735;\n} <div class=\"textbox\">\n <span id=\"close\" onclick=\"this.parentNode.remove(); location.reload(); return false;\" class=\"btn btn-default large\">\n <img src=\"/src/Esc X.svg\" height=\"33\" width=\"33\"></img>\n </span>\n <h2>${roleTypes[role]?.title ?? 'none'}</h2>\n <div id=\"card-div\">\n <p class=\"role-subtitle\">${roleTypes[role]?.subtitle ?? 'none'}</p>\n <h3>CHARGE</h3>\n <h4>${roleTypes[role]?.chargesubtitle ?? 'none'}</h4>\n <p class=\"role-text\">${roleTypes[role]?.chargebody ?? 'none'}</p>\n <h3>SCOPE</h3>\n <h4>${roleTypes[role]?.scopesubtitle ?? 'none'}</h4>\n <p class=\"role-text\">${roleTypes[role]?.scopebody ?? 'none'}</p>\n <h3>FORECASTING</h3>\n <h4>${roleTypes[role]?.forecastingsubtitle ?? 'none'}</h4>\n <p class=\"role-text\">${roleTypes[role]?.forecastingbody ?? 'none'}</p>\n <h3>COMMUNICATION + RESPONSIBILITY</h3>\n <h4>${roleTypes[role]?.communicationsubtitle ?? 'none'}</h4>\n <p class=\"role-text\">${roleTypes[role]?.communicationbody ?? 'none'}</p>\n </div>\n</div>" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74635385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20473091/" ]
74,635,425
<p>I have two tables:</p> <pre><code>restaurant | id | name | | -------- | -------- | | | | food_item | restaurant_id | name | price | | -------- | -------- | ----- | | | | | | | | | </code></pre> <p>I am trying to get the <strong>restaurnat name</strong>, <strong>item name</strong> and <strong>price</strong> where all the restaurants' items have a price higher than 10.</p> <p>Examaple result:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>restaurant</th> <th>item</th> <th>price</th> </tr> </thead> <tbody> <tr> <td>The King Fry</td> <td>item 1</td> <td>12.30</td> </tr> <tr> <td>THe King Fry</td> <td>item 2</td> <td>13.00</td> </tr> <tr> <td>The King Fry</td> <td>item 3</td> <td>10.60</td> </tr> </tbody> </table> </div> <p>All the items listed on their menu are &gt; 10</p> <p>So far I have:</p> <pre><code>SELECT restaurant.name, food_item.name, food_item.price FROM restaurant JOIN food_item ON restaurant.id = food_item.restaurant_id; WHERE food_item.price &gt; 10; </code></pre> <p>I managed to join the tables and show all the restaurants and its items where the price is &gt; 10. However, I do not know how to display only the restaurant where all menu items have a value higher than 10. If there is a restaurnat with item values both higher and lower that 10 - do not show. How can I get the result?</p>
[ { "answer_id": 74635836, "author": "tao", "author_id": 1891677, "author_profile": "https://Stackoverflow.com/users/1891677", "pm_score": 2, "selected": true, "text": "h4 {} h4 .role-text .role-text h4 .role-text 0 h3 h4 p h3, h4 {\n margin: 0 3rem;\n}\np {\n margin: 0;\n}\n" }, { "answer_id": 74635842, "author": "ChanHyeok-Im", "author_id": 6329353, "author_profile": "https://Stackoverflow.com/users/6329353", "pm_score": 0, "selected": false, "text": "h3 {\n font-family: BelyDisplay;\n display: flex;\n padding: 0px;\n margin: 0;\n margin-left: 3rem;\n margin-right: 3rem;\n text-align: left;\n font: normal normal bold 25px/55px Montserrat;\n letter-spacing: 0px;\n color: #F0532D;\n opacity: 1; \n}\n\nh4 {\n font-family: BelyDisplay;\n display: flex;\n padding: 0px;\n margin: 0;\n margin-left: 3rem;\n margin-right: 3rem;\n align-items: center;\n text-align: left;\n letter-spacing: 0px;\n opacity: 1; \n font: normal normal bold 18px/22px Montserrat;\n color: #483735;\n\n.role-text{\n font-family: Montserrat-Regular;\n margin-left: 3rem;\n margin-right: 3rem;\n padding-top: 1rem;\n padding-bottom: 1rem;\n text-align: left;\n letter-spacing: 0px;\n opacity: 1;\n font: normal normal normal 18px/22px Montserrat;\n color: #483735;\n} <div class=\"textbox\">\n <span id=\"close\" onclick=\"this.parentNode.remove(); location.reload(); return false;\" class=\"btn btn-default large\">\n <img src=\"/src/Esc X.svg\" height=\"33\" width=\"33\"></img>\n </span>\n <h2>${roleTypes[role]?.title ?? 'none'}</h2>\n <div id=\"card-div\">\n <p class=\"role-subtitle\">${roleTypes[role]?.subtitle ?? 'none'}</p>\n <h3>CHARGE</h3>\n <h4>${roleTypes[role]?.chargesubtitle ?? 'none'}</h4>\n <p class=\"role-text\">${roleTypes[role]?.chargebody ?? 'none'}</p>\n <h3>SCOPE</h3>\n <h4>${roleTypes[role]?.scopesubtitle ?? 'none'}</h4>\n <p class=\"role-text\">${roleTypes[role]?.scopebody ?? 'none'}</p>\n <h3>FORECASTING</h3>\n <h4>${roleTypes[role]?.forecastingsubtitle ?? 'none'}</h4>\n <p class=\"role-text\">${roleTypes[role]?.forecastingbody ?? 'none'}</p>\n <h3>COMMUNICATION + RESPONSIBILITY</h3>\n <h4>${roleTypes[role]?.communicationsubtitle ?? 'none'}</h4>\n <p class=\"role-text\">${roleTypes[role]?.communicationbody ?? 'none'}</p>\n </div>\n</div>" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74635425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13350520/" ]
74,635,451
<p><strong>issue</strong>: I am seeing 3 sets of console logs when I visit http://localhost:3000/</p> <p><strong>expected output</strong>: I should only be seeing two console.logs:: First middleware Second middleware</p> <p>I have the following two files:</p> <p>server.js ::</p> <pre><code>const http = require('http'); const app = require('./backend/app'); const port = process.env.PORT || 3000; app.set('port',port); const server = http.createServer(app); server.listen(port); </code></pre> <p>and app.js::</p> <pre><code>const express = require('express') // big chain of middle ware const app = express(); app.use( (req,res,next)=&gt;{ console.log('First middleware'); next(); }); app.use( (req,res,next)=&gt;{ console.log('Second middleware'); res.send('Hello from express'); }); // register what you want to export module.exports = app; </code></pre> <p>for some mysterious reason, I when I visit http://localhost:3000/ I see three sets of console logs in my sever console::</p> <pre><code>First middleware Second middleware First middleware Second middleware First middleware Second middleware </code></pre> <p>I page is not reloading 3 times lol</p> <p>I can see the output 'Hello from express' when I visit local host3000. but I am not sure why this code is running three times</p> <p>I tried to look for other similar questions like this but I did not see anything similar</p>
[ { "answer_id": 74636081, "author": "Finbar", "author_id": 17525834, "author_profile": "https://Stackoverflow.com/users/17525834", "pm_score": 1, "selected": false, "text": "<Request>.originalUrl" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74635451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17281101/" ]
74,635,452
<p>I am trying to run a pretty basic conditional to determine if a current element has a next sibling or not using ES6.</p> <p>I have tried to determine if nextElementSibling returns as <code>null</code> but this silently fails.</p> <pre><code>if (el.nextElementSibling == null) { // do something if there is no next sibling } else { // do something if there is a next sibling } </code></pre>
[ { "answer_id": 74636081, "author": "Finbar", "author_id": 17525834, "author_profile": "https://Stackoverflow.com/users/17525834", "pm_score": 1, "selected": false, "text": "<Request>.originalUrl" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74635452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20650607/" ]
74,635,491
<p>How to prevent this error, I am trying what ever I can, not possible to add return inside map.</p> <p>Error:<br /> Line 32:26: Array.prototype.map() expects a return value from arrow function array-callback-return</p> <pre><code> const parseChartData = (field: string, data: string[][]) =&gt; { let chartData = [[field, 'count']]; data.map((item: any) =&gt; { chartData.push([item._id, item._count]) }); return chartData; }; </code></pre>
[ { "answer_id": 74636081, "author": "Finbar", "author_id": 17525834, "author_profile": "https://Stackoverflow.com/users/17525834", "pm_score": 1, "selected": false, "text": "<Request>.originalUrl" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74635491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2062973/" ]
74,635,522
<p>I have an array of ids that determines the desired order of elements, which looks like this:</p> <pre><code>var desired_order = [0,4,2,1,3,...] </code></pre> <p>In my case it is much longer, so performance is to be considered.</p> <p>I also have an array of objects with those ids, like this one:</p> <pre><code>var objects = [{name:&quot;cat&quot;,id:0},{name:&quot;dog&quot;,id:1},{name:&quot;bird&quot;,id:2},{name:&quot;elephant&quot;,id:3}, {name:&quot;giraffe&quot;,id:4},...] </code></pre> <p>I need to create a new array <code>var = objects_in_desired_order</code> where these objects will be in the order determined by the <code>desired_order</code> array.</p> <p>How to do that efficiently?</p> <p>The only way I can think of is a double <code>for</code> loop where it goes over all possible ids in chronological order and pushes them where they belong. I would use this method if I wouldn't have such big arrays of data.</p> <p>Thanks in advance!</p>
[ { "answer_id": 74635601, "author": "gog", "author_id": 3494774, "author_profile": "https://Stackoverflow.com/users/3494774", "pm_score": 3, "selected": true, "text": "id => object let m = new Map(objects.map(o => [o.id, o]))\n let objects_in_desired_order = desired_order.map(id => m.get(id))\n var" }, { "answer_id": 74635605, "author": "Pointy", "author_id": 182668, "author_profile": "https://Stackoverflow.com/users/182668", "pm_score": 0, "selected": false, "text": "var orderMap = desired_order.reduce(function(map, value, index) {\n map[value] = index;\n return map;\n}, {});\n objects.sort(function(o1, o2) {\n return orderMap[o1.id] - orderMap[o2.id];\n});\n objects objects.slice()" }, { "answer_id": 74648778, "author": "Scott Sauyet", "author_id": 1243641, "author_profile": "https://Stackoverflow.com/users/1243641", "pm_score": 0, "selected": false, "text": "const reorder = (xs, is, idx = new Map (xs .map (x => [x .id, x]))) =>\n is .map (i => idx .get (i))\n\nconst desired_order = [0, 4, 2, 1, 3]\nconst objects = [{name: \"cat\", id: 0}, {name: \"dog\", id: 1}, {name: \"bird\", id: 2},{name: \"elephant\", id: 3}, {name: \"giraffe\", id: 4}]\n\nconsole .log (reorder (objects, desired_order)) .as-console-wrapper {max-height: 100% !important; top: 0}" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74635522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13941802/" ]
74,635,526
<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>.titlebar { font-family:'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif; width: 100%; display: inline-block; margin: 0; height: 125px; background-color: rgb(0, 0, 0); vertical-align: top; } .slogan { text-align: right; color: white; font-size: 20px; vertical-align: top; padding: 10px; } .assets { text-align: left; color: white; font-size: 20px; vertical-align: top; padding: 10px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="default.css"&gt; &lt;/head&gt; &lt;div class="titlebar"&gt; &lt;div class="assets"&gt; 123 &lt;/div&gt; &lt;div class="slogan"&gt; Hello &lt;/div&gt; &lt;/div&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>When adding more than one child to a parent div, the positions start offsetting. How can I make them level? I've tried vertical-align in both the children and the parents, but they remain offset.</p>
[ { "answer_id": 74635601, "author": "gog", "author_id": 3494774, "author_profile": "https://Stackoverflow.com/users/3494774", "pm_score": 3, "selected": true, "text": "id => object let m = new Map(objects.map(o => [o.id, o]))\n let objects_in_desired_order = desired_order.map(id => m.get(id))\n var" }, { "answer_id": 74635605, "author": "Pointy", "author_id": 182668, "author_profile": "https://Stackoverflow.com/users/182668", "pm_score": 0, "selected": false, "text": "var orderMap = desired_order.reduce(function(map, value, index) {\n map[value] = index;\n return map;\n}, {});\n objects.sort(function(o1, o2) {\n return orderMap[o1.id] - orderMap[o2.id];\n});\n objects objects.slice()" }, { "answer_id": 74648778, "author": "Scott Sauyet", "author_id": 1243641, "author_profile": "https://Stackoverflow.com/users/1243641", "pm_score": 0, "selected": false, "text": "const reorder = (xs, is, idx = new Map (xs .map (x => [x .id, x]))) =>\n is .map (i => idx .get (i))\n\nconst desired_order = [0, 4, 2, 1, 3]\nconst objects = [{name: \"cat\", id: 0}, {name: \"dog\", id: 1}, {name: \"bird\", id: 2},{name: \"elephant\", id: 3}, {name: \"giraffe\", id: 4}]\n\nconsole .log (reorder (objects, desired_order)) .as-console-wrapper {max-height: 100% !important; top: 0}" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74635526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20482298/" ]
74,635,549
<p>I have created a C# function to execute a PowerShell script to download and unzip a file from a remote computer. It runs successfully, but nothing is downloaded.</p> <p>Below is my current code:</p> <pre><code> public static string RemotePSExecution(string ipAddress, string username, string password, string psFilePath) { string result = string.Empty; var securePassword = new SecureString(); foreach (Char c in password) { securePassword.AppendChar(c); } PSCredential creds = new PSCredential(username, securePassword); WSManConnectionInfo connectionInfo = new WSManConnectionInfo(); connectionInfo.ComputerName = ipAddress; connectionInfo.Credential = creds; String psProg = File.ReadAllText(psFilePath); Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo); runspace.Open(); using (PowerShell ps = PowerShell.Create()) { ps.Runspace = runspace; ps.AddScript(psProg); StringBuilder sb = new StringBuilder(); try { var results = ps.Invoke(); foreach (var x in results) { sb.AppendLine(x.ToString()); } result = sb.ToString().Trim(); } catch (Exception e) { throw new Exception(&quot;Error occurred in PowerShell script&quot;, e.InnerException); } } runspace.Close(); return result; } </code></pre> <p>And my PowerShell script:</p> <pre><code>$url = &quot;https://&lt;internal website&gt;/xp.zip&quot; $zipFile = &quot;Downloads\xp.zip&quot; $targetDir = &quot;Downloads\UnZipFiles\&quot; Invoke-WebRequest -Uri $url -OutFile $zipFile Expand-Archive $zipFile -DestinationPath $targetDir -Force </code></pre> <p>If I run the PowerShell script directly on the remote VM, then the file is downloaded and unzipped successfully. But if I run the script using C# then nothing is downloaded.</p> <p>Another thing, the C# function works for the below PowerShell script:</p> <pre><code>(Get-Service -DisplayName &quot;*Service&quot;).Status </code></pre> <p>Does anyone know what's wrong with my code?</p>
[ { "answer_id": 74635601, "author": "gog", "author_id": 3494774, "author_profile": "https://Stackoverflow.com/users/3494774", "pm_score": 3, "selected": true, "text": "id => object let m = new Map(objects.map(o => [o.id, o]))\n let objects_in_desired_order = desired_order.map(id => m.get(id))\n var" }, { "answer_id": 74635605, "author": "Pointy", "author_id": 182668, "author_profile": "https://Stackoverflow.com/users/182668", "pm_score": 0, "selected": false, "text": "var orderMap = desired_order.reduce(function(map, value, index) {\n map[value] = index;\n return map;\n}, {});\n objects.sort(function(o1, o2) {\n return orderMap[o1.id] - orderMap[o2.id];\n});\n objects objects.slice()" }, { "answer_id": 74648778, "author": "Scott Sauyet", "author_id": 1243641, "author_profile": "https://Stackoverflow.com/users/1243641", "pm_score": 0, "selected": false, "text": "const reorder = (xs, is, idx = new Map (xs .map (x => [x .id, x]))) =>\n is .map (i => idx .get (i))\n\nconst desired_order = [0, 4, 2, 1, 3]\nconst objects = [{name: \"cat\", id: 0}, {name: \"dog\", id: 1}, {name: \"bird\", id: 2},{name: \"elephant\", id: 3}, {name: \"giraffe\", id: 4}]\n\nconsole .log (reorder (objects, desired_order)) .as-console-wrapper {max-height: 100% !important; top: 0}" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74635549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20323871/" ]
74,635,553
<p>Is there a way to center the &quot;Open Tray&quot; figure in the bottom row?</p> <p>I am trying to use <code>sfplot &lt;- ggarrange(Cf, Ff, Of, labels = c(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;))</code>, but obviously it won't automatically center it. Thanks in advance!</p> <p><img src="https://i.stack.imgur.com/S3plV.png" alt="image" /></p>
[ { "answer_id": 74635601, "author": "gog", "author_id": 3494774, "author_profile": "https://Stackoverflow.com/users/3494774", "pm_score": 3, "selected": true, "text": "id => object let m = new Map(objects.map(o => [o.id, o]))\n let objects_in_desired_order = desired_order.map(id => m.get(id))\n var" }, { "answer_id": 74635605, "author": "Pointy", "author_id": 182668, "author_profile": "https://Stackoverflow.com/users/182668", "pm_score": 0, "selected": false, "text": "var orderMap = desired_order.reduce(function(map, value, index) {\n map[value] = index;\n return map;\n}, {});\n objects.sort(function(o1, o2) {\n return orderMap[o1.id] - orderMap[o2.id];\n});\n objects objects.slice()" }, { "answer_id": 74648778, "author": "Scott Sauyet", "author_id": 1243641, "author_profile": "https://Stackoverflow.com/users/1243641", "pm_score": 0, "selected": false, "text": "const reorder = (xs, is, idx = new Map (xs .map (x => [x .id, x]))) =>\n is .map (i => idx .get (i))\n\nconst desired_order = [0, 4, 2, 1, 3]\nconst objects = [{name: \"cat\", id: 0}, {name: \"dog\", id: 1}, {name: \"bird\", id: 2},{name: \"elephant\", id: 3}, {name: \"giraffe\", id: 4}]\n\nconsole .log (reorder (objects, desired_order)) .as-console-wrapper {max-height: 100% !important; top: 0}" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74635553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20650833/" ]
74,635,581
<p>I have a question, I have a node element like below:</p> <pre><code>&lt;div&gt; &lt;span&gt;1&lt;/span&gt; &lt;span&gt;2&lt;/span&gt; &lt;span&gt;3&lt;/span&gt; &lt;/div&gt; </code></pre> <p>I want to clone all span elements and adding to this new prop like onClick but also keep parent element. How I can do that with React?</p> <p>Example:</p> <pre><code>React.Children.map(children, child =&gt; { React.cloneElement(child, { onClick: handleClick }) }) </code></pre> <p>no problem if there is no <code>div</code> outside. But in my case I have div is a parent element outside.</p>
[ { "answer_id": 74635631, "author": "dbonev", "author_id": 4200334, "author_profile": "https://Stackoverflow.com/users/4200334", "pm_score": 2, "selected": true, "text": "const spanElement = <span>1</span>;\n\n<div>\n {spanElement}\n {React.cloneElement(spanElement)}\n <span>2</span>\n <span>3</span>\n</div>\n" }, { "answer_id": 74640480, "author": "saurav Bhooriya 041", "author_id": 20607633, "author_profile": "https://Stackoverflow.com/users/20607633", "pm_score": 0, "selected": false, "text": "const spanElem = <span>1</span>;\n\n<div>\n {spanElem}\n {React.cloneElement(this.props.children,{spanElem})}\n <span>2</span>\n <span>3</span>\n</div>\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74635581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20206220/" ]
74,635,590
<p>How to remove duplicate entries from a JSON file using python?</p> <p>I have a JSON file that looks like this:</p> <p>appreciate some one can help to provide a solution for fixing it</p> <pre><code>json_data = [ { &quot;authType&quot;: &quot;ldap&quot;, &quot;password&quot;: &quot;&quot;, &quot;permissions&quot;: [ { &quot;collections&quot;: [ &quot;aks9099&quot;, &quot;aks9099&quot;, &quot;aks9098&quot;, &quot;aks9100&quot;, &quot;aks9100&quot;, &quot;aks9101&quot;, &quot;aks9102&quot;, &quot;aks9103&quot;, &quot;aks9103&quot; ], &quot;project&quot;: &quot;Central Project&quot; } ], &quot;role&quot;: &quot;devSecOps&quot;, &quot;username&quot;: &quot;chinq.n@example.com&quot; }, { &quot;authType&quot;: &quot;ldap&quot;, &quot;password&quot;: &quot;&quot;, &quot;permissions&quot;: [ { &quot;collections&quot;: [ &quot;aks9099&quot;, &quot;aks9098&quot;, &quot;aks9098&quot;, &quot;aks9100&quot;, &quot;aks9101&quot;, &quot;aks9102&quot;, &quot;aks9102&quot;, &quot;aks9103&quot; ], &quot;project&quot;: &quot;Central Project&quot; } ], &quot;role&quot;: &quot;devSecOps&quot;, &quot;username&quot;: &quot;chinw.d@example.com&quot; }, { &quot;authType&quot;: &quot;ldap&quot;, &quot;password&quot;: &quot;&quot;, &quot;permissions&quot;: [ { &quot;collections&quot;: [ &quot;aks9099&quot;, &quot;aks9098&quot;, &quot;aks9100&quot;, &quot;aks9100&quot;, &quot;aks9101&quot;, &quot;aks9102&quot;, &quot;aks9102&quot;, &quot;aks9103&quot; ], &quot;project&quot;: &quot;Central Project&quot; } ], &quot;role&quot;: &quot;devSecOps&quot;, &quot;username&quot;: &quot;chins.b@example.com&quot; } ] </code></pre> <p>I would like to remove duplicate entries from the list and expected result should be looks like this:</p> <p>Appreciate you can help to provide a solution for fixing it</p> <pre><code>json_data = [ { &quot;authType&quot;: &quot;ldap&quot;, &quot;password&quot;: &quot;&quot;, &quot;permissions&quot;: [ { &quot;collections&quot;: [ &quot;aks9099&quot;, &quot;aks9098&quot;, &quot;aks9100&quot;, &quot;aks9101&quot;, &quot;aks9102&quot;, &quot;aks9103&quot; ], &quot;project&quot;: &quot;Central Project&quot; } ], &quot;role&quot;: &quot;devSecOps&quot;, &quot;username&quot;: &quot;chinq.n@example.com&quot; }, { &quot;authType&quot;: &quot;ldap&quot;, &quot;password&quot;: &quot;&quot;, &quot;permissions&quot;: [ { &quot;collections&quot;: [ &quot;aks9099&quot;, &quot;aks9098&quot;, &quot;aks9100&quot;, &quot;aks9101&quot;, &quot;aks9102&quot;, &quot;aks9103&quot; ], &quot;project&quot;: &quot;Central Project&quot; } ], &quot;role&quot;: &quot;devSecOps&quot;, &quot;username&quot;: &quot;chinw.d@example.com&quot; }, { &quot;authType&quot;: &quot;ldap&quot;, &quot;password&quot;: &quot;&quot;, &quot;permissions&quot;: [ { &quot;collections&quot;: [ &quot;aks9099&quot;, &quot;aks9098&quot;, &quot;aks9100&quot;, &quot;aks9101&quot;, &quot;aks9102&quot;, &quot;aks9103&quot; ], &quot;project&quot;: &quot;Central Project&quot; } ], &quot;role&quot;: &quot;devSecOps&quot;, &quot;username&quot;: &quot;chins.b@example.com&quot; } ] </code></pre>
[ { "answer_id": 74635631, "author": "dbonev", "author_id": 4200334, "author_profile": "https://Stackoverflow.com/users/4200334", "pm_score": 2, "selected": true, "text": "const spanElement = <span>1</span>;\n\n<div>\n {spanElement}\n {React.cloneElement(spanElement)}\n <span>2</span>\n <span>3</span>\n</div>\n" }, { "answer_id": 74640480, "author": "saurav Bhooriya 041", "author_id": 20607633, "author_profile": "https://Stackoverflow.com/users/20607633", "pm_score": 0, "selected": false, "text": "const spanElem = <span>1</span>;\n\n<div>\n {spanElem}\n {React.cloneElement(this.props.children,{spanElem})}\n <span>2</span>\n <span>3</span>\n</div>\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74635590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20252882/" ]
74,635,592
<p>I have an array with data separated by a comma. I need to transpose it so the first part before the comma for each line is joined together by a delimiter as one line and the same for a second part. Example:</p> <pre><code>AC-2.22,CCI-000012 AC-5.1,CCI-000036 AC-5.3,CCI-001380 </code></pre> <p>I want to have 2 separate variables like so:</p> <pre><code>variable 1 = AC-2.22; AC-5.1; AC-5.3 Variable 2 = CCI-000012; CCI-000036; CCI-001380 </code></pre> <p>I know this should be simple but I've been staring at code all day and I just want to go eat dinner and goto sleep.</p> <p>Thanks in advance</p>
[ { "answer_id": 74636801, "author": "Santiago Squarzon", "author_id": 15339544, "author_profile": "https://Stackoverflow.com/users/15339544", "pm_score": 2, "selected": false, "text": ".Where Split $array = @(\n 'AC-2.22,CCI-000012'\n 'AC-5.1,CCI-000036'\n 'AC-5.3,CCI-001380'\n)\n\n$i = $false\n$var1, $var2 = $array.Split(',').Where({ ($i = -not $i) }, 'Split')\n$var1 -join '; '\n$var2 -join '; '\n .Split .Split" }, { "answer_id": 74638485, "author": "iRon", "author_id": 1701026, "author_profile": "https://Stackoverflow.com/users/1701026", "pm_score": 3, "selected": true, "text": "$array ConvertFrom-Csv $data = ConvertFrom-Csv $Array -Header var1, var2\n$data.var1 -Join ';'\nAC-2.22;AC-5.1;AC-5.3\n$data.var2 -Join ';'\nCCI-000012;CCI-000036;CCI-001380\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74635592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2282445/" ]
74,635,606
<p>I have a dataset with 1 key and two values, like below:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Column A</th> <th>Column B</th> <th>Column C</th> </tr> </thead> <tbody> <tr> <td>Anh</td> <td>6</td> <td>8</td> </tr> <tr> <td>Zavier</td> <td>2</td> <td>3</td> </tr> <tr> <td>Trey</td> <td>5</td> <td>5</td> </tr> <tr> <td>Zavier</td> <td>5</td> <td>9</td> </tr> <tr> <td>Anh</td> <td>1</td> <td>2</td> </tr> </tbody> </table> </div> <p>I would like the to create a table that groups A by the sums of B &amp; C like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Column A</th> <th>Column B</th> <th>Column C</th> </tr> </thead> <tbody> <tr> <td>Anh</td> <td>7</td> <td>10</td> </tr> <tr> <td>Zavier</td> <td>7</td> <td>12</td> </tr> <tr> <td>Trey</td> <td>5</td> <td>5</td> </tr> </tbody> </table> </div> <p>The following code groups A by the sum of B:</p> <pre><code>var nationalSummary = new google.visualization.ChartWrapper({ 'chartType': 'Table', 'containerId': 'nationalSummary_div', dataTable: data, 'options': { 'width': '100%', 'rowCount': 'enable', 'allowHtml': true, 'alternatingRowStyle': true, 'cssClassNames': { tableCell: 'large-font', headerCell: 'nsHeaderCell', } }, 'view': { 'columns': [0,1]} }); var container = document.getElementById('buildingDetail_div'); google.visualization.events.addListener(table, 'ready', function () { var nationalSummaryNew = table.getDataTable(); var nationalSummaryArray = google.visualization.data.group(nationalSummaryNew,[{ column: 0, type: 'string', label: 'Column A' }], [{ column: 1, type: 'number', label: 'Column B', aggregation: google.visualization.data.sum }]); </code></pre> <p>When I try to modify the code to include Col C, I modify the end of &quot;nationalSummary&quot; from:</p> <pre><code> 'view': { 'columns': [0,1]} </code></pre> <p>to</p> <pre><code> 'view': { 'columns': [0,1,2]} </code></pre> <p>and &quot;nationalSummaryArray&quot; to:</p> <pre><code> var nationalSummaryArray = google.visualization.data.group(nationalSummaryNew,[{ column: 0, type: 'string', label: 'Column A' }], [{ column: 1, type: 'number', label: 'Column B', aggregation: google.visualization.data.sum }], [{ column: 2, type: 'number', label: 'Column C', aggregation: google.visualization.data.sum }]); </code></pre> <p>I get the following error:</p> <pre><code>Invalid column index 2. Should be an integer in the range [0-1]. </code></pre> <p>How do I add Column C? Thank you in advance.</p>
[ { "answer_id": 74636801, "author": "Santiago Squarzon", "author_id": 15339544, "author_profile": "https://Stackoverflow.com/users/15339544", "pm_score": 2, "selected": false, "text": ".Where Split $array = @(\n 'AC-2.22,CCI-000012'\n 'AC-5.1,CCI-000036'\n 'AC-5.3,CCI-001380'\n)\n\n$i = $false\n$var1, $var2 = $array.Split(',').Where({ ($i = -not $i) }, 'Split')\n$var1 -join '; '\n$var2 -join '; '\n .Split .Split" }, { "answer_id": 74638485, "author": "iRon", "author_id": 1701026, "author_profile": "https://Stackoverflow.com/users/1701026", "pm_score": 3, "selected": true, "text": "$array ConvertFrom-Csv $data = ConvertFrom-Csv $Array -Header var1, var2\n$data.var1 -Join ';'\nAC-2.22;AC-5.1;AC-5.3\n$data.var2 -Join ';'\nCCI-000012;CCI-000036;CCI-001380\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74635606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8748741/" ]
74,635,614
<p>I am trying to create an empty list and for some reason it is telling me it's invalid syntax? it also flags the next line with the same error, saying that while count&lt;amount: is invalid. am i wrong for thinking this doesnt make sense? using vsc. thanks in advance. my code looks like this.</p> <pre><code>list=[] count=0 while count &lt; amount : s=int(input&quot;enter a number:&quot;) list.append(s) count= count+1 </code></pre> <p>i tried to use list={}, list=() even though i know those are wrong. it also flags lines like list4=[1,3] ??</p>
[ { "answer_id": 74635642, "author": "MrDiamond", "author_id": 15364728, "author_profile": "https://Stackoverflow.com/users/15364728", "pm_score": 2, "selected": false, "text": "amount list input () input(\"enter number: \")" }, { "answer_id": 74635650, "author": "Leo Ward", "author_id": 20421592, "author_profile": "https://Stackoverflow.com/users/20421592", "pm_score": 2, "selected": false, "text": "amount = 5\n\nnumberList = []\ncount = 0\nwhile count < amount:\n s = int(input(\"enter a number:\"))\n numberList.append(s)\n count += 1\n" }, { "answer_id": 74635681, "author": "notPatern", "author_id": 20639250, "author_profile": "https://Stackoverflow.com/users/20639250", "pm_score": 0, "selected": false, "text": "int(input(\"Enter a number: \"))\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74635614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20650870/" ]
74,635,640
<p>I am practicing on a database on SQL server where the date column in the table is <code>Nvarchar(255)</code> thereby presenting the dates as five digit numbers eg <code>40542</code>,<code>40046</code> etc. How do I change the dates in the column to actual dates?</p> <p>The articles I checked only helped me to change rows but I can't change all of them individually as that will take time.</p>
[ { "answer_id": 74635704, "author": "Gaël James", "author_id": 5405174, "author_profile": "https://Stackoverflow.com/users/5405174", "pm_score": 0, "selected": false, "text": "UPDATE TableName\n SET NewDateColName = ConvertionFunction(OldDateColName)\n CAST(OldDateColName as Date)\n UPDATE TableName\n SET NewDateColName = CONVERT(numeric(18,4),OldDateColName,101)\n" }, { "answer_id": 74635776, "author": "John Cappelletti", "author_id": 1570000, "author_profile": "https://Stackoverflow.com/users/1570000", "pm_score": 1, "selected": false, "text": "Declare @YourTable Table ([SomeCol] nvarchar(255)) Insert Into @YourTable Values \n ('40542')\n,('40043')\n \nSelect *\n ,AsDate1 = try_convert(datetime,try_convert(float,SomeCol)-2.0)\n ,AsDate2 = dateadd(day,try_convert(int,SomeCol),'1899-12-30') -- Note Start Date\n From @YourTable\n SomeCol AsDate1 AsDate2\n40542 2010-12-30 2010-12-30\n40043 2009-08-18 2009-08-18\n" }, { "answer_id": 74635788, "author": "Nicholas Carey", "author_id": 467473, "author_profile": "https://Stackoverflow.com/users/467473", "pm_score": 0, "selected": false, "text": "40452 40046 create view dbo.my_improved_view\nas\nselect t.* ,\n some_date = date_add( day,\n convert( int , t.funky_date_column ),\n convert( date , '1900-01-01' )\n )\nfrom dbo.table_with_funky_date_column t\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74635640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20070824/" ]
74,635,677
<p>I am having an error when refreshing my browser.</p> <blockquote> <p>Uncaught TypeError: Cannot read properties of undefined (reading 'title')</p> </blockquote> <p>And it keeps on repeating for all of my states (<code>title</code>, <code>content</code>, <code>id</code>) until I delete them from code down below... And also it works fine until I refresh the page.</p> <pre><code>import React, { FC, useEffect } from 'react'; import { useLocation, useParams } from 'react-router-dom'; import AddComment from 'src/components/ui/AddComment/AddComment'; import CommentSection from 'src/components/ui/CommentSection/CommentSection'; import PostContent from 'src/components/ui/PostContent/PostContent'; import PostHeader from 'src/components/ui/PostHeader/PostHeader'; import {useAppSelector } from 'src/store/app/hooks'; const Post: FC = () =&gt; { const { id } = useParams(); const { posts } = useAppSelector((state) =&gt; state.post); return ( &lt;div&gt; &lt;PostHeader header={&lt;h2&gt;{posts.find(p =&gt; p.id === parseInt(id)).title}&lt;/h2&gt;} &gt; &lt;div&gt; {posts.find(p =&gt; p.id === parseInt(id)).content} &lt;/div&gt; &lt;/PostHeader&gt; &lt;PostContent content={&lt;div&gt;{posts.find(p =&gt; p.id === parseInt(id)).content}&lt;/div&gt;} /&gt; &lt;AddComment id={id} /&gt; &lt;CommentSection id={id} /&gt; &lt;/div&gt; ) }; export default Post; </code></pre> <p>I also want to stop posts from dissapearing after refresh.</p>
[ { "answer_id": 74635704, "author": "Gaël James", "author_id": 5405174, "author_profile": "https://Stackoverflow.com/users/5405174", "pm_score": 0, "selected": false, "text": "UPDATE TableName\n SET NewDateColName = ConvertionFunction(OldDateColName)\n CAST(OldDateColName as Date)\n UPDATE TableName\n SET NewDateColName = CONVERT(numeric(18,4),OldDateColName,101)\n" }, { "answer_id": 74635776, "author": "John Cappelletti", "author_id": 1570000, "author_profile": "https://Stackoverflow.com/users/1570000", "pm_score": 1, "selected": false, "text": "Declare @YourTable Table ([SomeCol] nvarchar(255)) Insert Into @YourTable Values \n ('40542')\n,('40043')\n \nSelect *\n ,AsDate1 = try_convert(datetime,try_convert(float,SomeCol)-2.0)\n ,AsDate2 = dateadd(day,try_convert(int,SomeCol),'1899-12-30') -- Note Start Date\n From @YourTable\n SomeCol AsDate1 AsDate2\n40542 2010-12-30 2010-12-30\n40043 2009-08-18 2009-08-18\n" }, { "answer_id": 74635788, "author": "Nicholas Carey", "author_id": 467473, "author_profile": "https://Stackoverflow.com/users/467473", "pm_score": 0, "selected": false, "text": "40452 40046 create view dbo.my_improved_view\nas\nselect t.* ,\n some_date = date_add( day,\n convert( int , t.funky_date_column ),\n convert( date , '1900-01-01' )\n )\nfrom dbo.table_with_funky_date_column t\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74635677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19407011/" ]
74,635,688
<p>I have an Ansible task where I navigate to a YAML variable file in GitHub, download the file, and add the variables as Ansible Facts where they're later used.</p> <p>My YAML file looks like:</p> <pre class="lang-yaml prettyprint-override"><code>--- foo: bar hello: world </code></pre> <p>I have a method where I loop over this file, and individually add the key/value pairs as the facts:</p> <pre class="lang-yaml prettyprint-override"><code>- name: Grab contents of variable file win_shell: cat '{{ playbook_dir }}/DEV1.yml' register: raw_config - name: Add variables to workspace vars: config: &quot;{{ raw_config.stdout | from_yaml }}&quot; set_fact: &quot;{{ item.key }}&quot;: &quot;{{ item.value }}&quot; loop: &quot;{{ config | dict2items }}&quot; </code></pre> <p>This works but generates much larger log outputs that look like:</p> <pre><code> ok: [localhost] =&gt; (item={u'key': u'foo', u'value': u'bar'}) =&gt; { &quot;ansible_facts&quot;: { &quot;foo&quot;: &quot;bar&quot; }, &quot;ansible_loop_var&quot;: &quot;item&quot;, &quot;changed&quot;: false, &quot;item&quot;: { &quot;key&quot;: &quot;foo&quot;, &quot;value&quot;: &quot;bar&quot; } } ok: [localhost] =&gt; (item={u'key': u'hello', u'value': u'world'}) =&gt; { &quot;ansible_facts&quot;: { &quot;hello&quot;: &quot;world&quot; }, &quot;ansible_loop_var&quot;: &quot;item&quot;, &quot;changed&quot;: false, &quot;item&quot;: { &quot;key&quot;: &quot;hello&quot;, &quot;value&quot;: &quot;world&quot; } } </code></pre> <p>I was wondering if it was possible to add the entire variable file as Ansible Facts instead of needing to loop through it. The way I tried was like:</p> <pre class="lang-yaml prettyprint-override"><code>- name: Grab contents of variable file win_shell: cat '{{ playbook_dir }}/DEV1.yml' register: raw_config - name: Add variables to workspace vars: config: '{{ raw_config.stdout | from_yaml }}' set_fact: '{{ config }}' </code></pre> <p>This almost works, but it looks like this:</p> <pre><code> ok: [msf1vpom04d.corp.tjxcorp.net] =&gt; { &quot;ansible_facts&quot;: { &quot;_raw_params&quot;: { &quot;foo&quot;: &quot;bar&quot;, &quot;hello&quot;: &quot;world&quot; … </code></pre> <p>Can I add the entire object as Ansible Facts without generating this <code>_raw_params</code> object?</p>
[ { "answer_id": 74638882, "author": "U880D", "author_id": 6771046, "author_profile": "https://Stackoverflow.com/users/6771046", "pm_score": 0, "selected": false, "text": "curl --silent --user \"${ACCOUNT}:${PASSWORD}\" -X GET \"https://${REPOSITORY_URL}/raw/group_vars/test?at=refs%2Fheads%2Fmaster\" -o group_vars/test && \\\nsshpass -p ${PASSWORD} ansible-playbook --user ${ACCOUNT} --ask-pass test.yml\n include_vars" }, { "answer_id": 74639856, "author": "D P", "author_id": 20622893, "author_profile": "https://Stackoverflow.com/users/20622893", "pm_score": -1, "selected": false, "text": "# Ubuntu-18.yml\npackage_name: apache2\nservice_name: apache2\ndocument_root: /var/www/html\n # CentOS-8.yml\npackage_name: httpd\nservice_name: httpd\ndocument_root: /var/www/html/\n ---\n- name: \"Install webserver\"\nhosts: webserver\ntasks:\n- name: \"Test variables\"\ndebug:\nmsg: \"{{ ansible_distribution }}-{{ \nansible_distribution_major_version }}.yml\"\n $ ansible-playbook main.yml ---\n- name: \"Install webserver\"\nhosts: all\nvars_files:\n- \"{{ ansible_distribution }}-{{ \nansible_distribution_major_version }}.yml\"\n\ntasks:\n- name: \"Install the web server\"\n package:\n name: \" {{ package_name }}\"\n state: present\n\n- name: \"Create document root directory\"\n file: \n path: \"{{document_root }}\"\n state: directory\n recurse: yes\n- name: \"Create index.htm page in document \nroot\"\n copy:\n content: \"<h1> Welcome to {{ \nansible_distribution }} server !! </h1>\"\n dest: \"{{ document_root \n}}/index.html\"\n\n- name: \"Start the service\"\n service:\n name: \"{{ service_name }}\"\n state: started\n- name: \"Test the servers\"\nhosts: localhost\ntasks:\n - name: \"HealthCheck the servers\"\n uri:\n url: \"http://{{item}}\"\n return_content: yes\n with_items: \"{{ groups['webserver'] \n}}\"\n register: output\n failed_when: '\"Welcome\" not in \noutput.content'\n $ ansible-playbook main.yml\n" }, { "answer_id": 74641675, "author": "Zeitounator", "author_id": 9401096, "author_profile": "https://Stackoverflow.com/users/9401096", "pm_score": 0, "selected": false, "text": "vars_files empty.yml ---\n- hosts: localhost\n gather_facts: false\n\n vars:\n external_vars_uri: https://raw.githubusercontent.com/ansible-ThoTeam/nexus3-oss/main/defaults/main.yml\n external_vars_file: /tmp/external_vars.yml\n\n vars_files:\n - \"{{ lookup('first_found', [external_vars_file, 'empty.yml']) }}\"\n\n tasks:\n - name: make sure we have our external file\n get_url:\n url: \"{{ external_vars_uri }}\"\n dest: \"{{ external_vars_file }}\"\n # Note: we're only using localhost here so the below\n # parameters are useless. But they will be necessary\n # if you target other (groups of) hosts.\n run_once: true\n delegate_to: localhost\n\n\n - name: debug a var we know is in the external file\n debug:\n var: nexus_repos_maven_proxy\n $ ansible-playbook play.yml\n\nPLAY [localhost] **************************************************************************************************************************************************************************************************\n\nTASK [make sure we have our external file] ************************************************************************************************************************************************************************\nchanged: [localhost]\n\nTASK [debug a var we know is in the external file] ****************************************************************************************************************************************************************************\nok: [localhost] => {\n \"nexus_repos_maven_proxy\": [\n {\n \"layout_policy\": \"permissive\",\n \"name\": \"central\",\n \"remote_url\": \"https://repo1.maven.org/maven2/\"\n },\n {\n \"name\": \"jboss\",\n \"remote_url\": \"https://repository.jboss.org/nexus/content/groups/public-jboss/\"\n }\n ]\n}\n\nPLAY RECAP ********************************************************************************************************************************************************************************************************\nlocalhost : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 \n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74635688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16484106/" ]
74,635,702
<p>Silly newbe here. So I'm banging my head on this: Can't quite figure out the parameterized query and if it's properly formatted.</p> <pre><code>import sqlite3 def readSqliteTable(): try: sqliteConnection = sqlite3.connect('testDB.sqlite') cursor = sqliteConnection.cursor() print(&quot;Connected to SQLite&quot;) startdate = &quot;2022-11-05&quot; enddate = &quot;2022-11-25&quot; print(&quot;startdate =&quot;, startdate, &quot;enddate =&quot;, enddate) cursor.execute(&quot;SELECT * FROM tz WHERE UL_Time BETWEEN '%s' AND '%s'&quot; % (startdate, enddate)) print(cursor.fetchall()) records = cursor.fetchall() print(&quot;Total rows are: &quot;, len(records)) print(&quot;Printing each row&quot;) for row in records: print(&quot;Id: &quot;, row[0]) print(&quot;Updated: &quot;, row[1]) print(&quot;Title: &quot;, row[2]) print(&quot;UL_Time: &quot;, row[3]) print(&quot;Size: &quot;, row[4]) print(&quot;\n&quot;) cursor.close() except sqlite3.Error as error: print(&quot;Failed to read data from sqlite table&quot;, error) finally: if sqliteConnection: sqliteConnection.close() print(&quot;The SQLite connection is closed&quot;) </code></pre> <p>It works fine if I substitute arbitrary dates as:</p> <pre><code>cursor.execute(&quot;SELECT * FROM tz WHERE UL_Time BETWEEN 2022-11-01 AND 2022-11-25&quot;) </code></pre> <p>but won't work in this form</p>
[ { "answer_id": 74638882, "author": "U880D", "author_id": 6771046, "author_profile": "https://Stackoverflow.com/users/6771046", "pm_score": 0, "selected": false, "text": "curl --silent --user \"${ACCOUNT}:${PASSWORD}\" -X GET \"https://${REPOSITORY_URL}/raw/group_vars/test?at=refs%2Fheads%2Fmaster\" -o group_vars/test && \\\nsshpass -p ${PASSWORD} ansible-playbook --user ${ACCOUNT} --ask-pass test.yml\n include_vars" }, { "answer_id": 74639856, "author": "D P", "author_id": 20622893, "author_profile": "https://Stackoverflow.com/users/20622893", "pm_score": -1, "selected": false, "text": "# Ubuntu-18.yml\npackage_name: apache2\nservice_name: apache2\ndocument_root: /var/www/html\n # CentOS-8.yml\npackage_name: httpd\nservice_name: httpd\ndocument_root: /var/www/html/\n ---\n- name: \"Install webserver\"\nhosts: webserver\ntasks:\n- name: \"Test variables\"\ndebug:\nmsg: \"{{ ansible_distribution }}-{{ \nansible_distribution_major_version }}.yml\"\n $ ansible-playbook main.yml ---\n- name: \"Install webserver\"\nhosts: all\nvars_files:\n- \"{{ ansible_distribution }}-{{ \nansible_distribution_major_version }}.yml\"\n\ntasks:\n- name: \"Install the web server\"\n package:\n name: \" {{ package_name }}\"\n state: present\n\n- name: \"Create document root directory\"\n file: \n path: \"{{document_root }}\"\n state: directory\n recurse: yes\n- name: \"Create index.htm page in document \nroot\"\n copy:\n content: \"<h1> Welcome to {{ \nansible_distribution }} server !! </h1>\"\n dest: \"{{ document_root \n}}/index.html\"\n\n- name: \"Start the service\"\n service:\n name: \"{{ service_name }}\"\n state: started\n- name: \"Test the servers\"\nhosts: localhost\ntasks:\n - name: \"HealthCheck the servers\"\n uri:\n url: \"http://{{item}}\"\n return_content: yes\n with_items: \"{{ groups['webserver'] \n}}\"\n register: output\n failed_when: '\"Welcome\" not in \noutput.content'\n $ ansible-playbook main.yml\n" }, { "answer_id": 74641675, "author": "Zeitounator", "author_id": 9401096, "author_profile": "https://Stackoverflow.com/users/9401096", "pm_score": 0, "selected": false, "text": "vars_files empty.yml ---\n- hosts: localhost\n gather_facts: false\n\n vars:\n external_vars_uri: https://raw.githubusercontent.com/ansible-ThoTeam/nexus3-oss/main/defaults/main.yml\n external_vars_file: /tmp/external_vars.yml\n\n vars_files:\n - \"{{ lookup('first_found', [external_vars_file, 'empty.yml']) }}\"\n\n tasks:\n - name: make sure we have our external file\n get_url:\n url: \"{{ external_vars_uri }}\"\n dest: \"{{ external_vars_file }}\"\n # Note: we're only using localhost here so the below\n # parameters are useless. But they will be necessary\n # if you target other (groups of) hosts.\n run_once: true\n delegate_to: localhost\n\n\n - name: debug a var we know is in the external file\n debug:\n var: nexus_repos_maven_proxy\n $ ansible-playbook play.yml\n\nPLAY [localhost] **************************************************************************************************************************************************************************************************\n\nTASK [make sure we have our external file] ************************************************************************************************************************************************************************\nchanged: [localhost]\n\nTASK [debug a var we know is in the external file] ****************************************************************************************************************************************************************************\nok: [localhost] => {\n \"nexus_repos_maven_proxy\": [\n {\n \"layout_policy\": \"permissive\",\n \"name\": \"central\",\n \"remote_url\": \"https://repo1.maven.org/maven2/\"\n },\n {\n \"name\": \"jboss\",\n \"remote_url\": \"https://repository.jboss.org/nexus/content/groups/public-jboss/\"\n }\n ]\n}\n\nPLAY RECAP ********************************************************************************************************************************************************************************************************\nlocalhost : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 \n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74635702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20650903/" ]
74,635,719
<p>How can I change the JavaScript to change the style to &quot;none&quot; of all the <code>&lt;div class=&quot;class1&quot;&gt;</code> that have an <code>&lt;img&gt;</code> with the <code>alt=&quot;long&quot;</code> and not the other ones.</p> <p>I don't want to use JQuery.</p> <p>Example HTML:</p> <pre><code>&lt;div class=&quot;class1&quot;&gt; &lt;img alt=&quot;long&quot; &gt; &lt;/div&gt; &lt;div class=&quot;class1&quot;&gt; &lt;img alt=&quot;short&quot; &gt; &lt;/div&gt; </code></pre> <p>JavaScript:</p> <pre><code>ar = document.getElementsByClassName('class1'); for (i = 0; i &lt; ar.length; ++i) ar[i].style.display = &quot;none&quot;; </code></pre> <p>This Changes both div above... How can I modify the <code>getElementsByClassName()</code> to only include the ones with <code>&lt;img alt=&quot;long&quot;&gt;</code></p>
[ { "answer_id": 74638882, "author": "U880D", "author_id": 6771046, "author_profile": "https://Stackoverflow.com/users/6771046", "pm_score": 0, "selected": false, "text": "curl --silent --user \"${ACCOUNT}:${PASSWORD}\" -X GET \"https://${REPOSITORY_URL}/raw/group_vars/test?at=refs%2Fheads%2Fmaster\" -o group_vars/test && \\\nsshpass -p ${PASSWORD} ansible-playbook --user ${ACCOUNT} --ask-pass test.yml\n include_vars" }, { "answer_id": 74639856, "author": "D P", "author_id": 20622893, "author_profile": "https://Stackoverflow.com/users/20622893", "pm_score": -1, "selected": false, "text": "# Ubuntu-18.yml\npackage_name: apache2\nservice_name: apache2\ndocument_root: /var/www/html\n # CentOS-8.yml\npackage_name: httpd\nservice_name: httpd\ndocument_root: /var/www/html/\n ---\n- name: \"Install webserver\"\nhosts: webserver\ntasks:\n- name: \"Test variables\"\ndebug:\nmsg: \"{{ ansible_distribution }}-{{ \nansible_distribution_major_version }}.yml\"\n $ ansible-playbook main.yml ---\n- name: \"Install webserver\"\nhosts: all\nvars_files:\n- \"{{ ansible_distribution }}-{{ \nansible_distribution_major_version }}.yml\"\n\ntasks:\n- name: \"Install the web server\"\n package:\n name: \" {{ package_name }}\"\n state: present\n\n- name: \"Create document root directory\"\n file: \n path: \"{{document_root }}\"\n state: directory\n recurse: yes\n- name: \"Create index.htm page in document \nroot\"\n copy:\n content: \"<h1> Welcome to {{ \nansible_distribution }} server !! </h1>\"\n dest: \"{{ document_root \n}}/index.html\"\n\n- name: \"Start the service\"\n service:\n name: \"{{ service_name }}\"\n state: started\n- name: \"Test the servers\"\nhosts: localhost\ntasks:\n - name: \"HealthCheck the servers\"\n uri:\n url: \"http://{{item}}\"\n return_content: yes\n with_items: \"{{ groups['webserver'] \n}}\"\n register: output\n failed_when: '\"Welcome\" not in \noutput.content'\n $ ansible-playbook main.yml\n" }, { "answer_id": 74641675, "author": "Zeitounator", "author_id": 9401096, "author_profile": "https://Stackoverflow.com/users/9401096", "pm_score": 0, "selected": false, "text": "vars_files empty.yml ---\n- hosts: localhost\n gather_facts: false\n\n vars:\n external_vars_uri: https://raw.githubusercontent.com/ansible-ThoTeam/nexus3-oss/main/defaults/main.yml\n external_vars_file: /tmp/external_vars.yml\n\n vars_files:\n - \"{{ lookup('first_found', [external_vars_file, 'empty.yml']) }}\"\n\n tasks:\n - name: make sure we have our external file\n get_url:\n url: \"{{ external_vars_uri }}\"\n dest: \"{{ external_vars_file }}\"\n # Note: we're only using localhost here so the below\n # parameters are useless. But they will be necessary\n # if you target other (groups of) hosts.\n run_once: true\n delegate_to: localhost\n\n\n - name: debug a var we know is in the external file\n debug:\n var: nexus_repos_maven_proxy\n $ ansible-playbook play.yml\n\nPLAY [localhost] **************************************************************************************************************************************************************************************************\n\nTASK [make sure we have our external file] ************************************************************************************************************************************************************************\nchanged: [localhost]\n\nTASK [debug a var we know is in the external file] ****************************************************************************************************************************************************************************\nok: [localhost] => {\n \"nexus_repos_maven_proxy\": [\n {\n \"layout_policy\": \"permissive\",\n \"name\": \"central\",\n \"remote_url\": \"https://repo1.maven.org/maven2/\"\n },\n {\n \"name\": \"jboss\",\n \"remote_url\": \"https://repository.jboss.org/nexus/content/groups/public-jboss/\"\n }\n ]\n}\n\nPLAY RECAP ********************************************************************************************************************************************************************************************************\nlocalhost : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 \n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74635719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3011784/" ]
74,635,727
<pre><code>a &lt;- as.character(readline(&quot; Please input a text: &quot;)) most_repeated_character &lt;- function(x) { a &lt;- gsub(&quot;\\s+&quot;, &quot;&quot;, a) lets &lt;- strsplit(a, &quot;&quot;)[[1]] tbl &lt;- sort(table(lets), decreasing=TRUE) print(paste(&quot;most frequently occurring: (&quot;, names(tbl)[1], &quot;, &quot;, tbl[[1]], &quot;)&quot;)) print(paste(&quot;second most frequently occurring: (&quot;, names(tbl)[2], &quot;, &quot;, tbl[[2]], &quot;)&quot;)) } most_repeated_character(a) </code></pre> <p>I just want to get the most repeated letters, not characters. So for example if I input &quot;Hello world &amp;&amp;&amp;&amp;&quot;, I will get 'l' as the most repeated, not '&amp;'.</p>
[ { "answer_id": 74635811, "author": "PatrickdC", "author_id": 18703712, "author_profile": "https://Stackoverflow.com/users/18703712", "pm_score": 2, "selected": false, "text": "[^a-zA-Z] a <- gsub(\"\\\\s+\", \"\", a)\n a <- gsub(\"[^a-zA-Z]\", \"\", a)\n" }, { "answer_id": 74637275, "author": "rral", "author_id": 2857542, "author_profile": "https://Stackoverflow.com/users/2857542", "pm_score": 1, "selected": false, "text": "tolower() toupper() librabry(tidyverse)\n\na <- \"HolA MaMA &&&& $$$$ %%%%\"\n\nmost_repeated_character <- function(x) {\n x <- gsub(\"[^a-zA-Z]\", \"\", x) %>% \n tolower() %>% \n strsplit(\"\") %>% \n table() %>% \n sort(decreasing = TRUE)\n \n print(paste(\"most frequently occurring: (\", names(x)[1], \", \", x[[1]], \")\"))\n print(paste(\"second most frequently occurring: (\", names(x)[2], \", \", x[[2]], \")\"))\n}\nmost_repeated_character(a)\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74635727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20287224/" ]
74,635,733
<p>This is the situation:</p> <p>I'm using Compose, Hilt, Navigation and ViewModel. I'm trying to get an instance of my ViewModel within a Composable Screen via Hilt:</p> <pre class="lang-kotlin prettyprint-override"><code>@Composable fun HomeScreen( modifier: Modifier = Modifier, homeViewModel: HomeViewModel = viewModel() ) { ... } </code></pre> <pre class="lang-kotlin prettyprint-override"><code>@HiltViewModel class HomeViewModel @Inject constructor( private val updateCaptureUseCase: UpdateCaptureUseCase ) : ViewModel() { ... } </code></pre> <pre class="lang-kotlin prettyprint-override"><code>class UpdateCaptureUseCase @Inject constructor(private val captureRepository: CaptureRepository) { ... } </code></pre> <p>I get an instance of <strong>CaptureRepository</strong> by defining it inside a Module:</p> <pre><code>@Module @InstallIn(ViewModelComponent::class) abstract class CaptureModule { @Binds abstract fun bindCaptureLocalDataSource( captureLocalDataSourceImpl: CaptureLocalDataSourceImpl ): CaptureLocalDataSource @Binds abstract fun bindCaptureRepository( captureRepositoryImpl: CaptureRepositoryImpl ): CaptureRepository } </code></pre> <p>The problem is that <strong>CaptureModule</strong> appears in Android Studio as if it had no usages.</p> <p>I can build and run the app with no problems, but when it is supposed to show <strong>HomeScreen</strong> it crashes. What stresses me out and makes it hard to figure out a solution is that there are no errors in the <em>Run</em> tab nor the <em>Logcat</em>.</p> <p>If I remove <strong>updateCaptureUseCase</strong> from the constructor of <strong>HomeViewModel</strong>, then the app works correctly and is able to reach <strong>HomeScreen</strong> without errors. Since <strong>updateCaptureUseCase</strong> depends on <strong>CaptureRepository</strong> and it is being defined in <strong>CaptureModule</strong>, but this Module shows no usages, I suspect the error comes from Hilt and ViewModel</p>
[ { "answer_id": 74636207, "author": "z.y", "author_id": 19023745, "author_profile": "https://Stackoverflow.com/users/19023745", "pm_score": 2, "selected": false, "text": "ViewModel CaptureRepository @Bind @Inject class CaptureRepositoryImpl @Inject constructor(): CaptureRepository\n provide @Inject @Module\n@InstallIn(ViewModelComponent::class)\nabstract class CaptureModule {\n \n ...\n companion object {\n\n @Provides\n fun provideHomePresenter(): CaptureRepository {\n return CaptureRepositoryImpl()\n }\n }\n}\n" }, { "answer_id": 74647179, "author": "AlbertSawZ", "author_id": 6845721, "author_profile": "https://Stackoverflow.com/users/6845721", "pm_score": 0, "selected": false, "text": "@AndroidEntryPoint" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74635733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6845721/" ]
74,635,735
<p>I saw a sql code using the isNull function in the where clause, similar like below:<code>date&gt;isNull(date1,date2)</code></p> <p>Can someone explain what this means?</p> <p>Many Thanks! Michelle</p>
[ { "answer_id": 74635914, "author": "LordBaconPants", "author_id": 4595472, "author_profile": "https://Stackoverflow.com/users/4595472", "pm_score": 1, "selected": false, "text": " declare @date1 datetime = null\n declare @date2 datetime = getdate()\n\n select isNull(@date1,@date2)\n" }, { "answer_id": 74637110, "author": "Jonas Metzler", "author_id": 18794826, "author_profile": "https://Stackoverflow.com/users/18794826", "pm_score": 1, "selected": true, "text": "ISNULL ISNULL NULL COALESCE SELECT COALESCE(column1, column2, column3,...,0) FROM yourtable;\n NOT NULL NULL ISNULL ISNULL COALESCE" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74635735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14260569/" ]
74,635,793
<p>I'm looking to store a txt file with 52 characters that have no spaces into a char array. What I have below only outputs garbage. I would appreciate on some insight on how to solve this.</p> <p>`</p> <pre><code>int main() { fstream fin, fout; int maxSize = 9999; // Max length for text file. int sizeArray = 0; //Stores length of message.txt file. char storeCharacter[maxSize]; //Array that stores each individual character. fin.open(&quot;message.txt&quot;); if(fin.fail()) { cout &lt;&lt; &quot;Input file failed to open (wrong file name/other error)&quot; &lt;&lt; endl; exit(0); } sizeArray = fileLength(fin, storeCharacter, maxSize); //Assigns size using fileLength function. cout &lt;&lt; sizeArray &lt;&lt; endl; char txtCharacters[sizeArray]; storeInArray(fin, txtCharacters, sizeArray); for(int i=0; i&lt;=sizeArray; i++) { cout &lt;&lt; txtCharacters[i]; } fin.close(); fout.close(); return 0; } int fileLength(fstream&amp; fin, char storeCharacter[], int length) { char nextIn; int i = 0; fin &gt;&gt; nextIn; while(!fin.eof()) { storeCharacter[i] = nextIn; i++; fin &gt;&gt; nextIn; } return i; //returns the file size. } void storeInArray(fstream&amp; fin, char arr[], int length) { int i = 0; char nextIn; while(!fin.eof() &amp;&amp; i!=length ) { fin &gt;&gt; nextIn; arr[i] = nextIn; i++; } } </code></pre> <p>`</p> <p>I tried to use a while and for loop to store the txt file characters into a char array. I was expecting it to work since I have done a similar thing with a txt file full of integers. Instead garbage gets outputted instead of the contents of the text file.</p>
[ { "answer_id": 74635914, "author": "LordBaconPants", "author_id": 4595472, "author_profile": "https://Stackoverflow.com/users/4595472", "pm_score": 1, "selected": false, "text": " declare @date1 datetime = null\n declare @date2 datetime = getdate()\n\n select isNull(@date1,@date2)\n" }, { "answer_id": 74637110, "author": "Jonas Metzler", "author_id": 18794826, "author_profile": "https://Stackoverflow.com/users/18794826", "pm_score": 1, "selected": true, "text": "ISNULL ISNULL NULL COALESCE SELECT COALESCE(column1, column2, column3,...,0) FROM yourtable;\n NOT NULL NULL ISNULL ISNULL COALESCE" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74635793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18935759/" ]
74,635,795
<p>I'm confusing. I read diferents opinions about main. The first one says that main (as it's the principal section) could contain header and footer as direct children.</p> <pre><code>&lt;main&gt; &lt;header&gt;&lt;/header&gt; &lt;section&gt;for the content&lt;/section&gt; &lt;/main&gt; </code></pre> <p>Others says that main can't contain header as direct children, instead use article or section as parent. So the result would be:</p> <pre><code>&lt;main&gt; &lt;article&gt; &lt;header&gt;&lt;/header&gt; &lt;section&gt;for the content&lt;/section&gt; &lt;/article&gt; &lt;/main&gt; </code></pre> <p>Currently I have this layout, but I'm confused if It's necessary to add an article or a section to wrapp the header and the content:</p> <p><a href="https://i.stack.imgur.com/LJKVQ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LJKVQ.jpg" alt="enter image description here" /></a></p>
[ { "answer_id": 74635914, "author": "LordBaconPants", "author_id": 4595472, "author_profile": "https://Stackoverflow.com/users/4595472", "pm_score": 1, "selected": false, "text": " declare @date1 datetime = null\n declare @date2 datetime = getdate()\n\n select isNull(@date1,@date2)\n" }, { "answer_id": 74637110, "author": "Jonas Metzler", "author_id": 18794826, "author_profile": "https://Stackoverflow.com/users/18794826", "pm_score": 1, "selected": true, "text": "ISNULL ISNULL NULL COALESCE SELECT COALESCE(column1, column2, column3,...,0) FROM yourtable;\n NOT NULL NULL ISNULL ISNULL COALESCE" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74635795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16889666/" ]
74,635,799
<p>Not able to use property of Array which exists in array for showing data</p> <p><a href="https://i.stack.imgur.com/7QBC0.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7QBC0.jpg" alt="enter image description here" /></a></p> <p>Error in accessing the property</p> <p><a href="https://i.stack.imgur.com/9WDGR.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9WDGR.jpg" alt="enter image description here" /></a></p> <p>Assigning the values to array <a href="https://i.stack.imgur.com/wqcsZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wqcsZ.jpg" alt="enter image description here" /></a></p> <p>Error on Page <a href="https://i.stack.imgur.com/PjHeA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PjHeA.png" alt="enter image description here" /></a></p> <p>I want to access the property in loop which will display the category name</p>
[ { "answer_id": 74635914, "author": "LordBaconPants", "author_id": 4595472, "author_profile": "https://Stackoverflow.com/users/4595472", "pm_score": 1, "selected": false, "text": " declare @date1 datetime = null\n declare @date2 datetime = getdate()\n\n select isNull(@date1,@date2)\n" }, { "answer_id": 74637110, "author": "Jonas Metzler", "author_id": 18794826, "author_profile": "https://Stackoverflow.com/users/18794826", "pm_score": 1, "selected": true, "text": "ISNULL ISNULL NULL COALESCE SELECT COALESCE(column1, column2, column3,...,0) FROM yourtable;\n NOT NULL NULL ISNULL ISNULL COALESCE" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74635799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20651055/" ]
74,635,810
<p>By printing the array &quot;total&quot;, I can see that the values are appending correctly. And yet when I print(linked_list_values(a)), it returns None.</p> <pre><code>a = Node(5) b = Node(3) c = Node(9) total = [] def linked_list_values(head): print(total) if head == None: return None total.append(head.num) linked_list_values(head.next) print(linked_list_values(a)) </code></pre>
[ { "answer_id": 74635824, "author": "Lone Lunatic", "author_id": 7694279, "author_profile": "https://Stackoverflow.com/users/7694279", "pm_score": 2, "selected": false, "text": "None return total total >>> linked_list_values(a)\nNone\n>>> total\n[5, 3, 9] # Assuming a.next == b and b.next == c\n" }, { "answer_id": 74635884, "author": "Sriram M.", "author_id": 19073682, "author_profile": "https://Stackoverflow.com/users/19073682", "pm_score": 0, "selected": false, "text": "a = Node(5)\nb = Node(3) \nc = Node(9) \ntotal = [] \ndef linked_list_values(head): \n if head == None: \n return None \n total.append(head.num) \n linked_list_values(head.next)\n return total \nprint(linked_list_values(a))\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74635810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17084891/" ]
74,635,839
<p>I think it would be a simple question but I really stuck on it! how can I use for loop to make my statement more complex and short? I need the output be the exactly<a href="https://i.stack.imgur.com/ltNAx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ltNAx.png" alt="enter image description here" /></a> same format this is a code</p> <pre><code>courses_data = pd.read_csv('.........') selected_features = ['course_name','course_link','university_name','course_type', 'university_logo', 'time_required', 'course_language', 'course_subtitles', 'course_skills', 'course_rating', 'category', 'sub_category', 'course_level'] combined_features = courses_data['course_name']+' '+courses_data['course_link']+' '+courses_data['university_name']+' '+courses_data['course_type']+' '+courses_data['university_logo']+' '+courses_data['time_required']+' '+courses_data['course_language']+' '+courses_data['course_subtitles']+' '+courses_data['course_skills']+' '+courses_data['course_rating']+' '+courses_data['category']+' '+courses_data['sub_category']+' '+courses_data['course_level'] print(combined_features) </code></pre>
[ { "answer_id": 74635824, "author": "Lone Lunatic", "author_id": 7694279, "author_profile": "https://Stackoverflow.com/users/7694279", "pm_score": 2, "selected": false, "text": "None return total total >>> linked_list_values(a)\nNone\n>>> total\n[5, 3, 9] # Assuming a.next == b and b.next == c\n" }, { "answer_id": 74635884, "author": "Sriram M.", "author_id": 19073682, "author_profile": "https://Stackoverflow.com/users/19073682", "pm_score": 0, "selected": false, "text": "a = Node(5)\nb = Node(3) \nc = Node(9) \ntotal = [] \ndef linked_list_values(head): \n if head == None: \n return None \n total.append(head.num) \n linked_list_values(head.next)\n return total \nprint(linked_list_values(a))\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74635839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11588912/" ]