qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,371,461
<p>There have already been written lots of stuff about unsubscribing from observables in standard Angular workflow, but not so much about unsubscribing on page refresh (at least I haven't found much).</p> <p>So, what can be done with subscriptions which should be unsubscribed in <code>ngOnDestroy</code> (which is never called on page refresh)? The only material I came across during investigation was <a href="https://stackoverflow.com/a/50761501/4741929">this</a>, it uses javascript <code>onbeforeunload</code> function.</p> <pre><code>ngOnInit(){ //Some stuff window.onbeforeunload = () =&gt; this.ngOnDestroy(); } ngOnDestroy(){ //Some stuff } </code></pre> <p>This is quite an old answer, so maybe some things have moved further - is there currently any 'more Angular' way how to handle such subscriptions on page refresh?</p>
[ { "answer_id": 74371730, "author": "N.F.", "author_id": 4052858, "author_profile": "https://Stackoverflow.com/users/4052858", "pm_score": 1, "selected": false, "text": "ngOnDestroy" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74371461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4741929/" ]
74,371,516
<p>I'm doing a simple blog app to practice vue.js. I'm using composition API. I have stored data that get filled in in a form. This data I want to print out in another component <code>homePosts</code> where you can see the written blogpost with writer, headline and blogtext. I have used v-model, stored data to <code>localStorage</code>, in <code>homePosts</code> I have used v-for and <code>{{ }}</code> syntax to get data. But nothing shows in <code>homePosts</code>.<br /> Can someone please see what im missing.</p> <p><strong>writePost.vue</strong></p> <pre class="lang-js prettyprint-override"><code> &lt;template&gt; &lt;div&gt; &lt;form class=&quot;form&quot;&gt; &lt;label for=&quot;writer&quot;&gt;Writer name: &lt;/label&gt; &lt;input v-model=&quot;newWriter&quot; type=&quot;text&quot; max=&quot;500&quot; /&gt; &lt;br /&gt; &lt;label for=&quot;img&quot;&gt;Select image:&lt;/label&gt; &lt;input type=&quot;file&quot; id=&quot;img&quot; name=&quot;img&quot; accept=&quot;image/*&quot; /&gt; &lt;br /&gt; &lt;label for=&quot;headline&quot;&gt;Headline &lt;/label&gt; &lt;input v-model=&quot;newHeadline&quot; type=&quot;text&quot; max=&quot;500&quot; /&gt; &lt;label&gt;Your blogtext: &lt;/label&gt; &lt;textarea v-model=&quot;newNote&quot; name=&quot;&quot; id=&quot;&quot; cols=&quot;30&quot; rows=&quot;30&quot;&gt;&lt;/textarea&gt; &lt;button type=&quot;submit&quot; @click=&quot;addNote&quot; class=&quot;button&quot;&gt;&lt;router-link to=&quot;/homePosts&quot; class=&quot;link&quot;&gt;Post blog&lt;/router-link&gt;&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; &lt;/template&gt; &lt;script setup&gt; import { ref } from &quot;vue&quot;; const newNote = ref(&quot;&quot;); const newWriter = ref(&quot;&quot;); const newHeadline = ref(&quot;&quot;); const notes = ref([]); const addNote = () =&gt; { notes.value.push({ id: Math.floor(Math.random() * 1000000), text: newNote.value, writer: newWriter.value, headline: newHeadline.value, }); addLocalStorage(notes) }; const addLocalStorage = (notes) =&gt; { localStorage.setItem(&quot;notes&quot;, JSON.stringify(notes)) JSON.parse(localStorage.getItem(&quot;notes&quot;)); } &lt;/script&gt; </code></pre> <p><strong>homePosts.vue</strong></p> <pre class="lang-js prettyprint-override"><code> &lt;template&gt; &lt;div class=&quot;post-container&quot;&gt; &lt;h1&gt;Blog Posts&lt;/h1&gt; &lt;div class=&quot;post-mini-container&quot; &gt; &lt;div class=&quot;post&quot; v-for=&quot;note in notes&quot; :key=&quot;note.id&quot;&gt; &lt;!-- &lt;img class=&quot;img-post&quot; src=&quot;@/assets/person1.jpg&quot;&gt; --&gt; &lt;p class=&quot;writer&quot;&gt; {{ note.writer }}&lt;/p&gt; &lt;p class=&quot;headline&quot;&gt; {{ note.headline }}&lt;/p&gt; &lt;p class=&quot;blog-text&quot; &gt; {{ note.text }}&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; export default { name: 'homePosts' } &lt;/script&gt; </code></pre>
[ { "answer_id": 74371730, "author": "N.F.", "author_id": 4052858, "author_profile": "https://Stackoverflow.com/users/4052858", "pm_score": 1, "selected": false, "text": "ngOnDestroy" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74371516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19224482/" ]
74,371,543
<p>So I am now learning html, and I was just wondering why tags such as <strong>cite</strong> even exist. When I open a website as a user, I still see the text as <em>italic</em> when the code is written as <strong>cite</strong>.</p> <p>I found that the tags are useful when it comes to screen readers, so basically for users that have problems with their vision.</p> <p>Are there any more reasons for these tags? Thank you so much in advance!</p>
[ { "answer_id": 74371614, "author": "Santheep Madhavan", "author_id": 19672487, "author_profile": "https://Stackoverflow.com/users/19672487", "pm_score": 3, "selected": true, "text": "cite" }, { "answer_id": 74371707, "author": "Blye", "author_id": 5726956, "author_profile": "https://Stackoverflow.com/users/5726956", "pm_score": 1, "selected": false, "text": "cite" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74371543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19477821/" ]
74,371,571
<p>I have an array of prices</p> <p>I would like to group these prices into ranges if they are within 2 of each other</p> <p>How do I achieve this</p> <pre><code>// present array const array = [ '3','5','6','12','17','22' ] // the result I want const array_ranges = [ '3-6', '12', '17','22' ] </code></pre>
[ { "answer_id": 74371953, "author": "mplungjan", "author_id": 295783, "author_profile": "https://Stackoverflow.com/users/295783", "pm_score": 2, "selected": false, "text": "const array = ['3', '5', '6', '12', '14', '17', '22'],\n rangeGap = 2,\n arrRange = array.reduce((acc, num) => {\n const range = acc.at(-1).split(\"-\"), last = range.at(-1);\n if ((num - last) <= rangeGap) {\n if (range.length === 1) range.push(num); // new range\n else range[range.length-1] = num; // rewrite last slot\n acc[acc.length-1] = range.join(\"-\"); // save the range\n } else acc.push(num);\n return acc;\n }, [array[0]]); // initialise with first entry\nconsole.log(arrRange)" }, { "answer_id": 74371955, "author": "Nina Scholz", "author_id": 1447675, "author_profile": "https://Stackoverflow.com/users/1447675", "pm_score": 2, "selected": true, "text": "2" }, { "answer_id": 74373295, "author": "Peter Seliger", "author_id": 2627243, "author_profile": "https://Stackoverflow.com/users/2627243", "pm_score": 0, "selected": false, "text": "threshold" }, { "answer_id": 74463234, "author": "Scott Sauyet", "author_id": 1243641, "author_profile": "https://Stackoverflow.com/users/1243641", "pm_score": 0, "selected": false, "text": "2" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74371571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14286754/" ]
74,371,576
<p>Below is my code:<br> The issue I'm facing =&gt; first button updating the second button state as well.</p> <p>But it should be working differently:<br><strong>first</strong> with just <strong>first</strong>,<br> <strong>second</strong> with just <strong>second</strong></p> <p>I just want to achieve the state of the second button as independent from others what should i need to update thankyou, any suggestion will be great for me</p> <pre><code>class _LinearProgressBar extends State&lt;LinearProgressBar&gt; { bool loadingLinear = false; bool loadingCircular = false; @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text(&quot;CheckBox and Radio Button Stateful&quot;), ), body: Center( child: Column( children: [ Container( child: loadingLinear ? const LinearProgressIndicator() : const Text(&quot;Click to download &quot;), ), //Here is my first button which reflects the second button state as well ElevatedButton( style: ElevatedButton.styleFrom( primary: Colors.red, // background onPrimary: Colors.white, // foreground ), onPressed: () { setState(() { // when I click here it also updates the second set state of SecondBtn loadingLinear = !loadingLinear; }); }, child: const Text('FirstBtn'), ), Container( child: loadingLinear ? CircularProgressBar_() : const Text(&quot;Click to download&quot;), ), // Here is my second button which doesn't work ElevatedButton( style: ElevatedButton.styleFrom( primary: Colors.red, // background onPrimary: Colors.white, // foreground ), onPressed: () { setState(() { // this state is not working even on clicking... loadingCircular = !loadingCircular; }); }, child: const Text('SecondBtn'), ) ], ), ))); } } </code></pre>
[ { "answer_id": 74371651, "author": "VincentDR", "author_id": 19540575, "author_profile": "https://Stackoverflow.com/users/19540575", "pm_score": 4, "selected": true, "text": "Container(\n child: loadingCircular // not loadingLinear\n ? CircularProgressBar_()\n : const Text(\"Click to download\"),\n),\n" }, { "answer_id": 74372175, "author": "Mohamed Gawdat", "author_id": 15586963, "author_profile": "https://Stackoverflow.com/users/15586963", "pm_score": 2, "selected": false, "text": "loadingCircular" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74371576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14190819/" ]
74,371,585
<p>I use Selenium with Python to extract some data from a website. My question is simple, I click on a link which opens with <code>target=&quot;__blank&quot;</code>, and the problem is that I want to get the current URL of the just opened page. Unfortunately, neither the page URL is changed, nor the page source. I found that changing the element attribute to <code>target=&quot;__self&quot;</code> does the trick. However, I don't see this trick quite often when I searched around the Internet and that leads me to the question is that the only way?</p>
[ { "answer_id": 74371651, "author": "VincentDR", "author_id": 19540575, "author_profile": "https://Stackoverflow.com/users/19540575", "pm_score": 4, "selected": true, "text": "Container(\n child: loadingCircular // not loadingLinear\n ? CircularProgressBar_()\n : const Text(\"Click to download\"),\n),\n" }, { "answer_id": 74372175, "author": "Mohamed Gawdat", "author_id": 15586963, "author_profile": "https://Stackoverflow.com/users/15586963", "pm_score": 2, "selected": false, "text": "loadingCircular" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74371585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13060913/" ]
74,371,615
<p>Schema:</p> <pre><code>const orderSchema = mongoose.Schema( { orderStatus: { type: String, enum: [&quot;pending&quot;, &quot;preparing&quot;, &quot;completed&quot;, &quot;declined&quot;], default: &quot;pending&quot;, }, products: [ { product: { productId: { type: mongoose.Schema.Types.ObjectId, ref: &quot;Product&quot;, }, productName: String, productPrice: Number, categoryName: String, }, quantity: { type: Number, required: true, } }, ], totalPrice: { type: Number }, acceptDeclineTime: { type: Date, default: Date.now, }, } ); </code></pre> <p>I want a yearly sales report with number of orders accepted and declined, with total price for each.</p> <p>I tried:</p> <pre><code>orderSchema.aggregate( [ { $unwind: { path: &quot;$products&quot;, }, }, { $group: { _id: { $year: { date: &quot;$acceptDeclineTime&quot;, timezone: &quot;+03:00&quot; } }, totalCompletedPrice: { $sum: { $cond: [{ $eq: [&quot;$orderStatus&quot;, &quot;completed&quot;] }, &quot;$totalPrice&quot;, 0], }, }, totalDeclinedPrice: { $sum: { $cond: [{ $eq: [&quot;$orderStatus&quot;, &quot;declined&quot;] }, &quot;$totalPrice&quot;, 0], }, }, totalItems: { $sum: &quot;$products.quantity&quot;, }, completedSales: { $sum: { $cond: [{ $eq: [&quot;$orderStatus&quot;, &quot;completed&quot;] }, &quot;$products.quantity&quot;, 0], }, }, cancelledSales: { $sum: { $cond: [{ $eq: [&quot;$orderStatus&quot;, &quot;declined&quot;] }, &quot;$products.quantity&quot;, 0], }, }, }, }, ]); </code></pre> <p>But the price calculation is wrong as the <code>$unwind</code> stage duplicates total price of products which will be problematic on the <code>$sum</code> operation.</p>
[ { "answer_id": 74371651, "author": "VincentDR", "author_id": 19540575, "author_profile": "https://Stackoverflow.com/users/19540575", "pm_score": 4, "selected": true, "text": "Container(\n child: loadingCircular // not loadingLinear\n ? CircularProgressBar_()\n : const Text(\"Click to download\"),\n),\n" }, { "answer_id": 74372175, "author": "Mohamed Gawdat", "author_id": 15586963, "author_profile": "https://Stackoverflow.com/users/15586963", "pm_score": 2, "selected": false, "text": "loadingCircular" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74371615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11383947/" ]
74,371,624
<p>I'm trying to make ul menu with :before pseudoelement on li tags. Text inside :before's content is a different text for different rows. I want make this text right-aligned for each li, like this:</p> <pre><code> pseudo_x li pseudo_xx li pseudo_xxx li </code></pre> <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>li:nth-child(n):before { content: "==="; border: 1px dotted red; } li:nth-child(2n):before { content: "-----------"; border: 1px dotted red; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;ul&gt; &lt;li&gt;First&lt;/li&gt; &lt;li&gt;Second&lt;/li&gt; &lt;li&gt;Third&lt;/li&gt; &lt;li&gt;Fourth&lt;/li&gt; &lt;/ul&gt;</code></pre> </div> </div> </p> <p>*** Update</p> <p>Thanks for answers. But I can't use list-style-type because I will format the :before's content. Also I can't use one width for all contents. Because the idea I writing all this, is to use content for display count of rows inside li tags, like this:</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>var rows = document.getElementsByTagName('li'); for(var i=0;i&lt;rows.length;i++) rows[i].setAttribute("c", "rows: "+"1".repeat(Math.random()*10|0))</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>li{ list-style-type: none; } li:before{ color: white; content: attr(c); } .red:before{background:red} .orange:before{background:orange} .blue:before{background:blue} .green:before{background:green}</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;ul&gt; &lt;li class="red"&gt;First&lt;/li&gt; &lt;li class="orange"&gt;Second&lt;/li&gt; &lt;li class="blue"&gt;Third&lt;/li&gt; &lt;li class="green"&gt;Fourth&lt;/li&gt; &lt;/ul&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74371688, "author": "Cédric", "author_id": 17684809, "author_profile": "https://Stackoverflow.com/users/17684809", "pm_score": 1, "selected": false, "text": "list-style-type" }, { "answer_id": 74372310, "author": "David Thomas", "author_id": 82548, "author_profile": "https://Stackoverflow.com/users/82548", "pm_score": 2, "selected": false, "text": "@counter-style" }, { "answer_id": 74377273, "author": "Temani Afif", "author_id": 8620333, "author_profile": "https://Stackoverflow.com/users/8620333", "pm_score": 1, "selected": false, "text": "var rows = document.getElementsByTagName('li');\nfor (var i = 0; i < rows.length; i++)\n rows[i].setAttribute(\"c\", \"rows: \" + \"1\".repeat(Math.random() * 10 | 0))" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74371624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6713230/" ]
74,371,628
<p>example code:</p> <pre><code>import numpy as np a=np.ones((1,4,4)) shape1=a[0,:,[0,1,2]].shape shape2=a[0][:,[0,1,2]].shape </code></pre> <p>result:</p> <p>shape1 is (3,4) and shape2 is (4,3)</p> <p>Need help! I think they should have same results.</p>
[ { "answer_id": 74371688, "author": "Cédric", "author_id": 17684809, "author_profile": "https://Stackoverflow.com/users/17684809", "pm_score": 1, "selected": false, "text": "list-style-type" }, { "answer_id": 74372310, "author": "David Thomas", "author_id": 82548, "author_profile": "https://Stackoverflow.com/users/82548", "pm_score": 2, "selected": false, "text": "@counter-style" }, { "answer_id": 74377273, "author": "Temani Afif", "author_id": 8620333, "author_profile": "https://Stackoverflow.com/users/8620333", "pm_score": 1, "selected": false, "text": "var rows = document.getElementsByTagName('li');\nfor (var i = 0; i < rows.length; i++)\n rows[i].setAttribute(\"c\", \"rows: \" + \"1\".repeat(Math.random() * 10 | 0))" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74371628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8731846/" ]
74,371,670
<p>'This code snippet has two types of insertion and deletion methods. I tried to fill the methods but i don't get the desired output. the print functions output is not as required. the output has to be 3 2 1 4 but instead i get 3 3 3 4. Please help me to solve this'</p> <pre><code>&quot;&quot;&quot;Add a couple methods to our LinkedList class, and use that to implement a Stack. You have 4 functions below to fill in: insert_first, delete_first, push, and pop. Think about this while you're implementing: why is it easier to add an &quot;insert_first&quot; function than just use &quot;append&quot;?&quot;&quot;&quot; class Element(object): def __init__(self, value): self.value = value self.next = None class LinkedList(object): def __init__(self, head=None): self.head = head def append(self, new_element): current = self.head if self.head: while current.next: current = current.next current.next = new_element else: self.head = new_element def insert_first(self, new_element): &quot;Insert new element as the head of the LinkedList&quot; pass def delete_first(self): &quot;Delete the first (head) element in the LinkedList as return it&quot; pass class Stack(object): def __init__(self,top=None): self.ll = LinkedList(top) def push(self, new_element): &quot;Push (add) a new element onto the top of the stack&quot; pass def pop(self): &quot;Pop (remove) the first element off the top of the stack and return it&quot; pass # Test cases # Set up some Elements e1 = Element(1) e2 = Element(2) e3 = Element(3) e4 = Element(4) # Start setting up a Stack stack = Stack(e1) # Test stack functionality stack.push(e2) stack.push(e3) print (stack.pop().value) print (stack.pop().value) print (stack.pop().value) print (stack.pop()) stack.push(e4) print (stack.pop().value) </code></pre> <pre><code>class Element(object): def __init__(self, value): self.value = value self.next = None class LinkedList(object): def __init__(self, head=None): self.head = head def append(self, new_element): current = self.head if self.head: while current.next: current = current.next current.next = new_element else: self.head = new_element def insert_first(self, new_element): &quot;Insert new element as the head of the LinkedList&quot; self.head = new_element pass def delete_first(self): &quot;Delete the first (head) element in the LinkedList as return it&quot; return self.head class Stack(object): def __init__(self,top=None): self.ll = LinkedList(top) def push(self, new_element): &quot;Push (add) a new element onto the top of the stack&quot; if self.ll.head is None: self.ll.insert_first(new_element) else: self.ll.head.next = new_element new_element.next = self.ll.head self.ll.head = new_element self.ll.insert_first(new_element) pass def pop(self): &quot;Pop (remove) the first element off the top of the stack and return it&quot; if self.ll.head: deleted = self.ll.head self.ll.head.next = self.ll.head deleted.next = None return self.ll.delete_first() # Test cases # Set up some Elements e1 = Element(1) e2 = Element(2) e3 = Element(3) e4 = Element(4) # Start setting up a Stack stack = Stack(e1) # Test stack functionality stack.push(e2) stack.push(e3) print stack.pop().value print stack.pop().value print stack.pop().value print stack.pop() stack.push(e4) print stack.pop().value </code></pre> <p>'This code snippet has two types of insertion and deletion methods. I tried to fill the methods but i don't get the desired output. the print functions output is not as required. the output has to be 3 2 1 4 but instead i get 3 3 3 4. Please help me to solve this'</p>
[ { "answer_id": 74371688, "author": "Cédric", "author_id": 17684809, "author_profile": "https://Stackoverflow.com/users/17684809", "pm_score": 1, "selected": false, "text": "list-style-type" }, { "answer_id": 74372310, "author": "David Thomas", "author_id": 82548, "author_profile": "https://Stackoverflow.com/users/82548", "pm_score": 2, "selected": false, "text": "@counter-style" }, { "answer_id": 74377273, "author": "Temani Afif", "author_id": 8620333, "author_profile": "https://Stackoverflow.com/users/8620333", "pm_score": 1, "selected": false, "text": "var rows = document.getElementsByTagName('li');\nfor (var i = 0; i < rows.length; i++)\n rows[i].setAttribute(\"c\", \"rows: \" + \"1\".repeat(Math.random() * 10 | 0))" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74371670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16418700/" ]
74,371,697
<p>Based on <a href="https://stackoverflow.com/questions/6672834/specifying-blob-encoding-in-google-chrome">this</a> thread I tried to create a blob with utf 32 encoding and BOM of FF FE 00 00(UTF-32LE representation) as follows:</p> <pre><code>var BOM = new Uint8Array([0xFF,0xFE,0x00,0x00]); var b = new Blob([ BOM, &quot;➀➁➂ Test&quot; ]); var url = URL.createObjectURL(b); open(url); </code></pre> <p>But the file content gets corrupted and gets changed to a different language. What is the correct way to convert a string to a file with utf-32le format?</p> <p>Edit: Im trying this in browser environment</p>
[ { "answer_id": 74372044, "author": "Silent observer", "author_id": 4547909, "author_profile": "https://Stackoverflow.com/users/4547909", "pm_score": 0, "selected": false, "text": "var fs = require('fs');\nvar iconv = require('iconv-lite');\n\nvar str = '你好,世界';\nvar buf = iconv.encode(str, 'utf-32le');\nfs.writeFileSync('test.txt', buf);\n\n" }, { "answer_id": 74372163, "author": "T.J. Crowder", "author_id": 157247, "author_profile": "https://Stackoverflow.com/users/157247", "pm_score": 3, "selected": true, "text": "TextEncoder" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74371697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10508655/" ]
74,371,701
<p>I'd like to create kind of dependency between R and database and for that I'm trying to create a loop which is checking if a date in one column from a database is equal to today's date, if yes then run main statement, if not wait 5mins and try again (max 24 times) then break. I'm stucked with the latter, if someone could advice that would be helpful, thanks!</p> <pre><code>if(lubridate::date(table$db_date) == Sys.Date()){ print(1) } else { Sys.sleep(300) # and repeat the loop 24 times until statement is TRUE, if not then break } </code></pre>
[ { "answer_id": 74372044, "author": "Silent observer", "author_id": 4547909, "author_profile": "https://Stackoverflow.com/users/4547909", "pm_score": 0, "selected": false, "text": "var fs = require('fs');\nvar iconv = require('iconv-lite');\n\nvar str = '你好,世界';\nvar buf = iconv.encode(str, 'utf-32le');\nfs.writeFileSync('test.txt', buf);\n\n" }, { "answer_id": 74372163, "author": "T.J. Crowder", "author_id": 157247, "author_profile": "https://Stackoverflow.com/users/157247", "pm_score": 3, "selected": true, "text": "TextEncoder" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74371701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15125859/" ]
74,371,714
<p>Im trying to upload a file from the client to the server in chunks. Is been ten years since I have tried to code a chunk uploader myself, this is harder then I remember.</p> <h1>upload.proto</h1> <pre><code>syntax = &quot;proto3&quot;; option csharp_namespace = &quot;GrpcService1&quot;; package upload; // The FileDownload service definition. service Uploader { // Download a file rpc UploadFileStream(stream UploadFileRequest) returns (UploadFileResponse) {} } // The request message containing file data, and file name message UploadFileRequest { bytes data = 1; string fileName = 2; } // The response from the upload containing the filePath message UploadFileResponse { string filePath =1; } </code></pre> <h1>UploaderService</h1> <pre><code>using Grpc.Core; namespace GrpcService1.Services; public class UploaderService : Uploader.UploaderBase { private readonly ILogger&lt;GreeterService&gt; _logger; public UploaderService(ILogger&lt;GreeterService&gt; logger) { _logger = logger; } public override async Task&lt;UploadFileResponse&gt; UploadFileStream(IAsyncStreamReader&lt;UploadFileRequest&gt; request, ServerCallContext context) { while (await request.MoveNext()) { Console.WriteLine(request.Current.Data); } return new UploadFileResponse(){ FilePath = @&quot;c:\uploaded\file1.txt&quot;}; } } </code></pre> <h1>client upload test method</h1> <pre><code> public static async Task Upload(GrpcChannel channel, string filePath) { var clientUpFile = new Uploader.UploaderClient(channel); using var uploadStream = clientUpFile.UploadFileStream(); var x = File.Exists(filePath); using (FileStream fileStream = File.OpenRead(filePath) ) { var bufferSize = 512000; var buffer = new byte[bufferSize]; var lastBytesRead = 0; var byteCount = 0; while ((lastBytesRead = fileStream.Read(buffer, 0, bufferSize)) != 0) { Console.WriteLine(lastBytesRead); if (lastBytesRead &gt; 0) { await uploadStream.RequestStream.WriteAsync(new UploadFileRequest() { Data = await ByteString.FromStreamAsync(fileStream, CancellationToken.None), FileName = filePath }); } } } </code></pre> <h1>Issue</h1> <p>The client seems to be uploading the chunks by look at its console. log</p> <blockquote> <p>Hello World<br> [ { &quot;name&quot;: &quot;Files\DaimtoLogo.jpg&quot; } ]<br> 512<br></p> </blockquote> <p>However the server seems to get a single chunk, which makes sense as there appears to be only one. Then it throws an error reading the stream.</p> <blockquote> <p>Google.Protobuf.ByteString info: Grpc.AspNetCore.Server.ServerCallHandler[14] Error reading message. System.IO.IOException: The request stream was aborted. ---&gt; Microsoft.AspNetCore.Connections.ConnectionAbortedException: The HTTP/2 connection faulted. ---&gt; Microsoft.AspNetCore.Connections.ConnectionResetException: An existing connection was forcibly closed by the remote host. ---&gt; System.Net.Sockets.SocketException (10054): An existing connection was forcibly closed by the remote host. at Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.Internal.SocketConnection.DoReceive() --- End of inner exception stack trace --- at System.IO.Pipelines.Pipe.GetReadResult(ReadResult&amp; result) at System.IO.Pipelines.Pipe.GetReadAsyncResult() at System.IO.Pipelines.Pipe.DefaultPipeReader.GetResult(Int16 token) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.DuplexPipeStream.ReadAsyncInternal(Memory<code>1 destination, CancellationToken cancellationToken) at System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder</code>1.StateMachineBox<code>1.System.Threading.Tasks.Sources.IValueTaskSource&lt;TResult&gt;.GetResult(Int16 token) at System.Net.Security.SslStream.ReadAsyncInternal[TIOAdapter](TIOAdapter adapter, Memory</code>1 buffer) at System.IO.Pipelines.StreamPipeReader.g__Core|36_0(StreamPipeReader reader, CancellationTokenSource tokenSource, CancellationToken cancellationToken) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2.Http2Connection.ReadInputAsync() at System.IO.Pipelines.Pipe.GetReadResult(ReadResult&amp; result) at System.IO.Pipelines.Pipe.GetReadAsyncResult() at System.IO.Pipelines.Pipe.DefaultPipeReader.GetResult(Int16 token) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2.Http2Connection.ProcessRequestsAsync[TContext](IHttpApplication<code>1 application) --- End of inner exception stack trace --- --- End of inner exception stack trace --- at System.IO.Pipelines.Pipe.GetReadResult(ReadResult&amp; result) at System.IO.Pipelines.Pipe.GetReadAsyncResult() at System.IO.Pipelines.Pipe.DefaultPipeReader.GetResult(Int16 token) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2.Http2MessageBody.ReadAsync(CancellationToken cancellationToken) at System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder</code>1.StateMachineBox<code>1.System.Threading.Tasks.Sources.IValueTaskSource&lt;TResult&gt;.GetResult(Int16 token) at Grpc.AspNetCore.Server.Internal.PipeExtensions.ReadStreamMessageAsync[T](PipeReader input, HttpContextServerCallContext serverCallContext, Func</code>2 deserializer, CancellationToken cancellationToken) fail: Grpc.AspNetCore.Server.ServerCallHandler[6] Error when executing service method 'UploadFileStream'. System.IO.IOException: The request stream was aborted. ---&gt; Microsoft.AspNetCore.Connections.ConnectionAbortedException: The HTTP/2 connection faulted. ---&gt; Microsoft.AspNetCore.Connections.ConnectionResetException: An existing connection was forcibly closed by the remote host. ---&gt; System.Net.Sockets.SocketException (10054): An existing connection was forcibly closed by the remote host. at Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.Internal.SocketConnection.DoReceive() --- End of inner exception stack trace --- at System.IO.Pipelines.Pipe.GetReadResult(ReadResult&amp; result) at System.IO.Pipelines.Pipe.GetReadAsyncResult() at System.IO.Pipelines.Pipe.DefaultPipeReader.GetResult(Int16 token) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.DuplexPipeStream.ReadAsyncInternal(Memory<code>1 destination, CancellationToken cancellationToken) at System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder</code>1.StateMachineBox<code>1.System.Threading.Tasks.Sources.IValueTaskSource&lt;TResult&gt;.GetResult(Int16 token) at System.Net.Security.SslStream.ReadAsyncInternal[TIOAdapter](TIOAdapter adapter, Memory</code>1 buffer) at System.IO.Pipelines.StreamPipeReader.g__Core|36_0(StreamPipeReader reader, CancellationTokenSource tokenSource, CancellationToken cancellationToken) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2.Http2Connection.ReadInputAsync() at System.IO.Pipelines.Pipe.GetReadResult(ReadResult&amp; result) at System.IO.Pipelines.Pipe.GetReadAsyncResult() at System.IO.Pipelines.Pipe.DefaultPipeReader.GetResult(Int16 token) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2.Http2Connection.ProcessRequestsAsync[TContext](IHttpApplication<code>1 application) --- End of inner exception stack trace --- --- End of inner exception stack trace --- at System.IO.Pipelines.Pipe.GetReadResult(ReadResult&amp; result) at System.IO.Pipelines.Pipe.GetReadAsyncResult() at System.IO.Pipelines.Pipe.DefaultPipeReader.GetResult(Int16 token) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2.Http2MessageBody.ReadAsync(CancellationToken cancellationToken) at System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder</code>1.StateMachineBox<code>1.System.Threading.Tasks.Sources.IValueTaskSource&lt;TResult&gt;.GetResult(Int16 token) at Grpc.AspNetCore.Server.Internal.PipeExtensions.ReadStreamMessageAsync[T](PipeReader input, HttpContextServerCallContext serverCallContext, Func</code>2 deserializer, CancellationToken cancellationToken) at Grpc.AspNetCore.Server.Internal.HttpContextStreamReader<code>1.&lt;MoveNext&gt;g__MoveNextAsync|9_0(ValueTask</code>1 readStreamTask) at GrpcService1.Services.UploaderService.UploadFileStream(IAsyncStreamReader<code>1 request, ServerCallContext context) in C:\Development\FreeLance\Glassix\gRCPTest\grcp-samaple\gRCPService\GrpcService1\Services\UploaderService.cs:line 16 at Grpc.Shared.Server.ClientStreamingServerMethodInvoker</code>3.Invoke(HttpContext httpContext, ServerCallContext serverCallContext, IAsyncStreamReader<code>1 requestStream) at Grpc.Shared.Server.ClientStreamingServerMethodInvoker</code>3.Invoke(HttpContext httpContext, ServerCallContext serverCallContext, IAsyncStreamReader<code>1 requestStream) at Grpc.AspNetCore.Server.Internal.CallHandlers.ClientStreamingServerCallHandler</code>3.HandleCallAsyncCore(HttpContext httpContext, HttpContextServerCallContext serverCallContext) at Grpc.AspNetCore.Server.Internal.CallHandlers.ServerCallHandlerBase<code>3.&lt;HandleCallAsync&gt;g__AwaitHandleCall|8_0(HttpContextServerCallContext serverCallContext, Method</code>2 method, Task handleCall)</p> </blockquote> <ol> <li>what is closing the stream</li> <li>shouldnt the stream stay open until it gets the response back from the server that the file was uploaded?</li> </ol> <p>Note: Updated to fix a few typos noted in answer below.</p>
[ { "answer_id": 74371876, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 0, "selected": false, "text": "await" }, { "answer_id": 74372455, "author": "DaImTo", "author_id": 1841839, "author_profile": "https://Stackoverflow.com/users/1841839", "pm_score": 2, "selected": false, "text": "await uploadStream.RequestStream.CompleteAsync();" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74371714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1841839/" ]
74,371,734
<p>I am using multiple X300/X310s to do a receive beamforming operation with synchronization to both Tx and all Rx devices with Octo-Clock. However I am seeing a constant but random phase shift across different USRPs, such phase shift is random upon each start-up/data collection but remains constant until I turn off the operation.</p> <p>I had doubled checked that my Octo-clock is functioning properly. I am using GNU radio to drive my devices, and for my USRP source I am having the following set-ups:</p> <p>Sync: to PC clock after next PPS (I also tried &quot;unknown PPS&quot; and it behaves the same)</p> <p>Mbx Clock Source: External</p> <p>Mbx Time Source: External</p> <p>I am using an ethernet switch to run all my USRPs using 1 PC. My Tx daughter board is SBX and Rx daughter boards are UBXs.</p> <p><a href="https://forums.ni.com/t5/LabVIEW-Communications-System/Sync-multiple-USRP-using-Octoclock/td-p/32030..." rel="nofollow noreferrer">This post</a> describes a very similar situation:</p> <blockquote> <p>With all of the above synchronization there will be a random amount of constant phase offset between the channels, as documented in figure 6 of: <a href="http://www.ettus.com/content/files/kb/mimo_and_sync_with_usrp_updated.pdf" rel="nofollow noreferrer">http://www.ettus.com/content/files/kb/mimo_and_sync_with_usrp_updated.pdf</a> This could be responsible for your consistent fractional offset. These needs to be signal processed to ensure alignment.</p> </blockquote> <p>Unfortunately, the link referring to the answer does not exist anymore and I would like to know the reason and a possible direction to the solution. My array is built on a flexible substrate so it is hard to compensate without knowing more information.</p> <p>Thanks in advance</p> <p>I sent a pilot tone of 5kHz with 2.45GHz carrier. At the receiver, I captured the raw data from USRP and directly saves into a file which I process it using MATLAB.</p>
[ { "answer_id": 74371876, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 0, "selected": false, "text": "await" }, { "answer_id": 74372455, "author": "DaImTo", "author_id": 1841839, "author_profile": "https://Stackoverflow.com/users/1841839", "pm_score": 2, "selected": false, "text": "await uploadStream.RequestStream.CompleteAsync();" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74371734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13932425/" ]
74,371,740
<p>I want to copy value of name and age into another array, below code is working fine, But I wanted to know better way to do it.</p> <pre><code>const users = [ { id: 0, name: 'John', age:34 }, { id: 1, name: 'Wayne', age:44 }, { id: 2, name: 'David', age:24 }, ]; let values=[]; users &amp;&amp; users.map(user =&gt; { values.push(user['name']) values.push(user['age']) }) console.log(values); </code></pre> <p>output</p> <pre><code>['John', 34, 'Wayne', 44, 'David', 24] </code></pre>
[ { "answer_id": 74371783, "author": "RenaudC5", "author_id": 11260991, "author_profile": "https://Stackoverflow.com/users/11260991", "pm_score": 3, "selected": true, "text": "const users = [\n { id: 0, name: 'John', age:34 },\n { id: 1, name: 'Wayne', age:44 },\n { id: 2, name: 'David', age:24 },\n];\n\nconst nameAndAges = users.flatMap(user => [user.name, user.age])\n\nconsole.log(nameAndAges)" }, { "answer_id": 74371920, "author": "Ahmed Saleh", "author_id": 12320320, "author_profile": "https://Stackoverflow.com/users/12320320", "pm_score": 0, "selected": false, "text": "const users = [\n { id: 0, name: 'John', age: 34 },\n { id: 1, name: 'Wayne', age: 44 },\n { id: 2, name: 'David', age: 24 },\n];\n\nconst result = mapArrayToProps(users, ['name', 'age']);\n\nfunction mapArrayToProps(arr, props) {\n return arr.flatMap(obj => mapObjectToProps(obj, props));\n}\n\nfunction mapObjectToProps(obj, props) {\n return props.map(prop => obj[prop])\n}\n\nconsole.log(result);" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74371740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8368511/" ]
74,371,770
<p>I have an excel data file with 2 sheet named &quot;Data&quot; and &quot;GL Data&quot;</p> <p>Both these sheets contain a column called &quot;Leader&quot; which has 4 different names - say D1, D2, D3 and D4</p> <p>I have 4 other workbooks named - Data_D1, Data_D2, Data_D3 and Data_D4 each with 2 sheet named &quot;Data&quot; and &quot;GL Data&quot;.</p> <p>I need to put each Leader's data in their sheet. That is :</p> <p>1- Apply a filter on Leader column in sheet &quot;data&quot; and select D1</p> <p>2- copy the filtered rows to &quot;data&quot; sheet of workbook Data_D1</p> <p>3- Apply a filter on Leader column in sheet &quot;GL data&quot; and select D1</p> <p>4- copy the filtered rows to &quot;GL data&quot; sheet of workbook Data_D1</p> <p>5- Repeat the above steps for D2, D3 and D4</p> <p>I am wondering if there's a better way of doing this quickly. I searched online but couldn't find anything. Any help would be useful. Thank you.</p> <p>EDIT: Wrote some VBA code (see answer below). Facing some problem with its working.</p>
[ { "answer_id": 74371783, "author": "RenaudC5", "author_id": 11260991, "author_profile": "https://Stackoverflow.com/users/11260991", "pm_score": 3, "selected": true, "text": "const users = [\n { id: 0, name: 'John', age:34 },\n { id: 1, name: 'Wayne', age:44 },\n { id: 2, name: 'David', age:24 },\n];\n\nconst nameAndAges = users.flatMap(user => [user.name, user.age])\n\nconsole.log(nameAndAges)" }, { "answer_id": 74371920, "author": "Ahmed Saleh", "author_id": 12320320, "author_profile": "https://Stackoverflow.com/users/12320320", "pm_score": 0, "selected": false, "text": "const users = [\n { id: 0, name: 'John', age: 34 },\n { id: 1, name: 'Wayne', age: 44 },\n { id: 2, name: 'David', age: 24 },\n];\n\nconst result = mapArrayToProps(users, ['name', 'age']);\n\nfunction mapArrayToProps(arr, props) {\n return arr.flatMap(obj => mapObjectToProps(obj, props));\n}\n\nfunction mapObjectToProps(obj, props) {\n return props.map(prop => obj[prop])\n}\n\nconsole.log(result);" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74371770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12645183/" ]
74,371,772
<pre><code> let storage = {}; storage.saveCredentials = (token:any, id:any) =&gt; { localStorage.setItem('token', token); localStorage.setItem('userId', id); } storage.saveStatus = (status:any) =&gt; { localStorage.setItem('status', JSON.stringify(status)); } export default storage; </code></pre> <p>I get the error that <code>Property 'saveCredentials' does not exist on type '{}'.</code></p>
[ { "answer_id": 74371895, "author": "mchl_bld", "author_id": 6805583, "author_profile": "https://Stackoverflow.com/users/6805583", "pm_score": 0, "selected": false, "text": "storage" }, { "answer_id": 74371981, "author": "Indraraj26", "author_id": 10842900, "author_profile": "https://Stackoverflow.com/users/10842900", "pm_score": -1, "selected": false, "text": "const saveCredentials = (token: any, id: any) => {\n localStorage.setItem('token', token);\n localStorage.setItem('userId', id);\n};\n\nconst saveStatus = (status: any) => {\n localStorage.setItem('status', JSON.stringify(status));\n};\n\nexport { saveCredentials, saveStatus };\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74371772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14769363/" ]
74,371,778
<p>I am trying to call a function which gets data from an API and after comaprison of received data with input it should return 0 or 1 which i may include in my code but the function is returning undefined. Can;t seem to get my head in the right place.</p> <pre class="lang-js prettyprint-override"><code> async function cloudVerify(y, x) { const url = `https://**myAPI**.execute-api.us-west-2.amazonaws.com/items/${y}`; console.log(url); await axios .get(url) .then((res) =&gt; { const headerDate = res.headers &amp;&amp; res.headers.date ? res.headers.date : &quot;no response date&quot;; console.log(&quot;Status Code:&quot;, res.status); console.log(&quot;Date in Response header:&quot;, headerDate); const receivedData = res.data; const receivedItem = receivedData.Item; // console.log(receivedItem); console.log( `Got user with id: ${receivedItem.id}, hash: ${receivedItem.hash}` ); console.log(`received item hash is ${receivedItem.hash}`); console.log(`meta is : ${x}, hash: ${receivedItem.hash}`); return 1; }) .catch((err) =&gt; { console.log(&quot;Error: &quot;, err.message); }); } </code></pre> <p><a href="https://i.stack.imgur.com/9DPAo.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9DPAo.jpg" alt="output in node js" /></a> I am returning 1 but instead it gives me undefined.</p>
[ { "answer_id": 74372035, "author": "hernanl", "author_id": 14329561, "author_profile": "https://Stackoverflow.com/users/14329561", "pm_score": 1, "selected": true, "text": "callingAxios = () => {\n axios.get().then()\n return 1\n}\n\ncloudVerify = (url) => {\n return callingAxios(url)\n}\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74371778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10591419/" ]
74,371,794
<p>I have a panel that makes use of the following promql query to monitor the ram usage of IIS Application Pools on a server:</p> <pre><code>windows_process_working_set_bytes{process=~&quot;w3wp_.*&quot;, instance=&quot;Server&quot;} </code></pre> <p>This returns the following results: (pseudo)</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Time</th> <th>process</th> <th>process_id</th> <th>value</th> </tr> </thead> <tbody> <tr> <td>2022-11-09 01:00</td> <td>w3wp_foobar</td> <td>1000</td> <td>500000</td> </tr> <tr> <td>2022-11-09 01:15</td> <td>w3wp_foobar</td> <td>1000</td> <td>100000</td> </tr> <tr> <td>2022-11-09 01:30</td> <td>w3wp_spam_ham_eggs</td> <td>1200</td> <td>700000</td> </tr> <tr> <td>2022-11-09 01:45</td> <td>w3wp_foobar</td> <td>1000</td> <td>300000</td> </tr> <tr> <td>2022-11-09 02:00</td> <td>w3wp_foobar</td> <td>1000</td> <td>500000</td> </tr> <tr> <td>2022-11-09 02:15</td> <td>w3wp_foobar</td> <td>1500</td> <td>300000</td> </tr> <tr> <td>2022-11-09 02:30</td> <td>w3wp_spam_ham_eggs</td> <td>1200</td> <td>600000</td> </tr> <tr> <td>2022-11-09 02:45</td> <td>w3wp_foobar</td> <td>1500</td> <td>700000</td> </tr> </tbody> </table> </div> <p>While this shows only two processes, it returns three series, because the <code>process_id</code> of <code>w3wp_foobar</code> changed. How can I completely omit <code>process_id</code> so that I only have two series? This change occurs when the application pool restarts. Because this panel tracks 20+ application pools, having multiple series for the same pool clouds the legend with double entries.</p> <p>I have already tried the merge transformation, but this merges everything into a single series, which doesn't work for me. Since this is a single metric, I can't perform a join either. (as far as I'm aware)</p>
[ { "answer_id": 74371900, "author": "Jan Garaj", "author_id": 3348604, "author_profile": "https://Stackoverflow.com/users/3348604", "pm_score": 1, "selected": false, "text": "max" }, { "answer_id": 74374232, "author": "Marcelo Ávila de Oliveira", "author_id": 4653675, "author_profile": "https://Stackoverflow.com/users/4653675", "pm_score": 2, "selected": false, "text": "max without (process_id) (windows_process_working_set_bytes{process=~\"w3wp_.*\", instance=\"Server\"})\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74371794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7533440/" ]
74,371,813
<p>I'm new to React and l’m reading the documentation of react navigation</p> <p>In this <a href="https://reactnavigation.org/docs/auth-flow/#implement-the-logic-for-restoring-the-token" rel="nofollow noreferrer">Section </a></p> <pre><code>const authContext = React.useMemo( () =&gt; ({ signIn: async (data) =&gt; { dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' }); }, signOut: () =&gt; dispatch({ type: 'SIGN_OUT' }), signUp: async (data) =&gt; { dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' }); }, }), [] ); </code></pre> <p>I dont understand the purpose of using useMemo since we can do the same thing using UseEffect</p> <p>is there any reason to use UseMemo over useEffect in this case ?</p>
[ { "answer_id": 74371900, "author": "Jan Garaj", "author_id": 3348604, "author_profile": "https://Stackoverflow.com/users/3348604", "pm_score": 1, "selected": false, "text": "max" }, { "answer_id": 74374232, "author": "Marcelo Ávila de Oliveira", "author_id": 4653675, "author_profile": "https://Stackoverflow.com/users/4653675", "pm_score": 2, "selected": false, "text": "max without (process_id) (windows_process_working_set_bytes{process=~\"w3wp_.*\", instance=\"Server\"})\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74371813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20055746/" ]
74,371,833
<p>Having a dataframe like this:</p> <pre><code>df &lt;- data.frame(id = c(1,2,3), date1 = c(&quot;2014-Dec 2018&quot;,&quot;2009-2010&quot;,&quot;Jan 2009-Aug 2010&quot;), date2 = c(&quot;Feb 2016-Dec 2018&quot;,&quot;2014-Dec 2018&quot;,&quot;Oct 2013-Dec 2018&quot;)) id date1 date2 1 1 2014-Dec 2018 Feb 2016-Dec 2018 2 2 2009-2010 2014-Dec 2018 3 3 Jan 2009-Aug 2010 Oct 2013-Dec 2018 </code></pre> <p>Is their any command which could check in every row if their is something different than this format &quot;Jan 2009-Aug 2010&quot; and keep it into a new dataframe? Meaning that check if there are 17 charcters including the spaces between month and year.</p> <p>Example of expected output</p> <pre><code>data.frame(id = c(1,2), date1 = c(&quot;2014-Dec 2018&quot;,&quot;2009-2010&quot;), date2 = c(&quot;Feb 2016-Dec 2018&quot;,&quot;2014-Dec 2018&quot;)) id date1 date2 1 1 2014-Dec 2018 Feb 2016-Dec 2018 2 2 2009-2010 2014-Dec 2018 </code></pre>
[ { "answer_id": 74371930, "author": "zx8754", "author_id": 680068, "author_profile": "https://Stackoverflow.com/users/680068", "pm_score": 1, "selected": false, "text": "df[ rowSums(sapply(df[ -1 ], nchar) == 17, na.rm = TRUE) < 2, ]\n# id date1 date2\n# 1 1 2014-Dec 2018 Feb 2016-Dec 2018\n# 2 2 2009-2010 2014-Dec 2018\n" }, { "answer_id": 74371977, "author": "Maël", "author_id": 13460602, "author_profile": "https://Stackoverflow.com/users/13460602", "pm_score": 3, "selected": true, "text": "split" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74371833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20224217/" ]
74,371,848
<p>I have been trying to debug this problem I am facing since 2 days now. I noticed this problem when I was trying to pull something from bitbucket. It says</p> <pre><code>git@code.pruconnect.net: Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. </code></pre> <p>I have tried every solution form deleting old ssh keys and adding new ones to adding the existing keys to the ssh-agent. Also, <code>ssh -T git@bitbucket.org</code> command again throws <code>git@bitbucket.org: Permission denied (publickey)</code> as the error and <code>ssh -vT git@bitbucket.org</code> throws the following as the error:</p> <pre><code>OpenSSH_9.0p1, LibreSSL 3.3.6 debug1: Reading configuration data /Users/amijeetthakur/.ssh/config debug1: /Users/amijeetthakur/.ssh/config line 1: Applying options for *bitbucket.org debug1: Reading configuration data /etc/ssh/ssh_config debug1: /etc/ssh/ssh_config line 21: include /etc/ssh/ssh_config.d/* matched no files debug1: /etc/ssh/ssh_config line 54: Applying options for * debug1: Authenticator provider $SSH_SK_PROVIDER did not resolve; disabling debug1: Connecting to bitbucket.org port 22. debug1: Connection established. debug1: identity file /Users/amijeetthakur/.ssh/id_rsa type 0 debug1: identity file /Users/amijeetthakur/.ssh/id_rsa-cert type -1 debug1: Local version string SSH-2.0-OpenSSH_9.0 debug1: Remote protocol version 2.0, remote software version conker_44eee6a33e b7cd6ff70e1a debug1: compat_banner: no match: conker_44eee6a33e b7cd6ff70e1a debug1: Authenticating to bitbucket.org:22 as 'git' debug1: load_hostkeys: fopen /Users/amijeetthakur/.ssh/known_hosts2: No such file or directory debug1: load_hostkeys: fopen /etc/ssh/ssh_known_hosts: No such file or directory debug1: load_hostkeys: fopen /etc/ssh/ssh_known_hosts2: No such file or directory debug1: SSH2_MSG_KEXINIT sent debug1: SSH2_MSG_KEXINIT received debug1: kex: algorithm: curve25519-sha256@libssh.org debug1: kex: host key algorithm: rsa-sha2-512 debug1: kex: server-&gt;client cipher: chacha20-poly1305@openssh.com MAC: &lt;implicit&gt; compression: none debug1: kex: client-&gt;server cipher: chacha20-poly1305@openssh.com MAC: &lt;implicit&gt; compression: none debug1: expecting SSH2_MSG_KEX_ECDH_REPLY debug1: SSH2_MSG_KEX_ECDH_REPLY received debug1: Server host key: ssh-rsa SHA256:zzXQOXSRBEiUtuE8AikJYKwbHaxvSc0ojez9YXaGp1A debug1: load_hostkeys: fopen /Users/amijeetthakur/.ssh/known_hosts2: No such file or directory debug1: load_hostkeys: fopen /etc/ssh/ssh_known_hosts: No such file or directory debug1: load_hostkeys: fopen /etc/ssh/ssh_known_hosts2: No such file or directory debug1: Host 'bitbucket.org' is known and matches the RSA host key. debug1: Found key in /Users/amijeetthakur/.ssh/known_hosts:1 debug1: rekey out after 134217728 blocks debug1: SSH2_MSG_NEWKEYS sent debug1: expecting SSH2_MSG_NEWKEYS debug1: SSH2_MSG_NEWKEYS received debug1: rekey in after 134217728 blocks debug1: get_agent_identities: bound agent to hostkey debug1: get_agent_identities: agent returned 2 keys debug1: Will attempt key: /Users/amijeetthakur/.ssh/id_rsa RSA SHA256:nux65XHIgoNnct40pwEJWQ+kLrA2W2r0oqm9PHGvH1Q explicit agent debug1: Will attempt key: amijeet.thakur@wedopulse.co.in RSA SHA256:1YofMNkb/JQpdGd8OZlyyjaX9RQR0h9c6ZWzZMDlWes agent debug1: SSH2_MSG_EXT_INFO received debug1: kex_input_ext_info: server-sig-algs=&lt;ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-rsa-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ssh-dss-cert-v01@openssh.com,ecdsa-sha2-nistp256-cert-v01@openssh.com,ssh-rsa,rsa-sha2-256,rsa-sha2-512,ssh-dss,ecdsa-sha2-nistp256&gt; debug1: SSH2_MSG_SERVICE_ACCEPT received debug1: Authentications that can continue: publickey debug1: Next authentication method: publickey debug1: Offering public key: /Users/amijeetthakur/.ssh/id_rsa RSA SHA256:nux65XHIgoNnct40pwEJWQ+kLrA2W2r0oqm9PHGvH1Q explicit agent debug1: Authentications that can continue: publickey debug1: Offering public key: amijeet.thakur@wedopulse.co.in RSA SHA256:1YofMNkb/JQpdGd8OZlyyjaX9RQR0h9c6ZWzZMDlWes agent debug1: Authentications that can continue: publickey debug1: No more authentication methods to try. git@bitbucket.org: Permission denied (publickey). </code></pre> <p>Note: I observed this error to come after updating my Mac to MacOs Ventura.</p>
[ { "answer_id": 74373012, "author": "dsastrusmploy", "author_id": 19957542, "author_profile": "https://Stackoverflow.com/users/19957542", "pm_score": 1, "selected": false, "text": "git remote set-url origin \"SSHURL\"\n" }, { "answer_id": 74373053, "author": "psq", "author_id": 2278206, "author_profile": "https://Stackoverflow.com/users/2278206", "pm_score": 1, "selected": false, "text": "$ chmod 700 ~/.ssh\n$ chmod 400 ~/.ssh/id_rsa\n$ chmod 400 ~/.ssh/id_rsa.pub\n" }, { "answer_id": 74451202, "author": "Renan Tomazoni Pinzon", "author_id": 2193232, "author_profile": "https://Stackoverflow.com/users/2193232", "pm_score": 0, "selected": false, "text": "/etc/ssh/ssh_config" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74371848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14917896/" ]
74,371,856
<p>Every day 3 new CSV-files are sent to 3 different paths. I want to copy these files to an archive within each path and then run a script which removes the first line of each file. The resulting files are then moved to another folder where a batch reads them.</p> <p>Example for a path1: &quot;Z:\Test\1\Script\Export1_2022-11-09.csv&quot; Example for an archive1: &quot;Z:\Test\1\Script\Archive\Export1_2022-11-09.csv&quot;</p> <p>Example for a path2: &quot;Z:\Test\2\Script\Export2_2022-11-09.csv&quot; Example for an archive2: &quot;Z:\Test\2\Script\Archive\Export2_2022-11-09.csv&quot;</p> <pre><code>$Files = @( &quot;Z:\Test\1\Script\Export1_2022-11-09.csv&quot;, &quot;Z:\Test\2\Script\Export2_2022-11-09.csv&quot;) $Files | ForEach-Object { Copy-Item $_ -Destination (Get-Content $_ | Select-Object -Skip 1) | Set-Content $_ } </code></pre> <p>The part where the first line of each file gets deleted works fine, but i can't think of a way to have each file copied to a specific and different path before. I would very much appreciate some help. Thank you in advance.</p> <p>@Theo: I edited my Question because i made a mistake, the files have different names.</p>
[ { "answer_id": 74373182, "author": "jdweng", "author_id": 5015238, "author_profile": "https://Stackoverflow.com/users/5015238", "pm_score": 0, "selected": false, "text": "Files = @( \"Z:\\Test\\1\\Script\\Export_2022-11-09.csv\", \"Z:\\Test\\2\\Script\\Export_2022-11-09.csv\")\nforeach($File in $Files)\n{\n $lastIndex = $File.LastIndexOf(\"\\\")\n $baseFilename = $File.Substring($lastIndex + 1)\n $newFilename = $File.Substring(0, $lastIndex + 1)\n $newFilename += \"Archive\\\" + $baseFileName\n Write-Host \"New File Name = \" $newFilename\n}\n" }, { "answer_id": 74376175, "author": "Theo", "author_id": 9898643, "author_profile": "https://Stackoverflow.com/users/9898643", "pm_score": 2, "selected": true, "text": "[System.IO.Path]::GetDirectoryName()" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74371856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20049627/" ]
74,371,891
<p>Looking for advice please.</p> <p>In my DF below, I would like to subract the 'difference' column value (red square), from the value in 'trailing sl' column (blue square), but shifted to lag .shift(1).</p> <p>So the new values would be:</p> <pre><code>1.08778 - 0.00115 1.08663 - 0.00077 1.08586 - 0.00059 etc </code></pre> <p>I've tried .loc with a .shift value, but that's not quite right.</p> <pre><code>df.loc[df.difference != np.nan, 'trailing_sl'] = df.trailing_sl.shift(1) - df.difference </code></pre> <p>I'm stuck tbh.</p> <p><a href="https://i.stack.imgur.com/HdbNN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HdbNN.jpg" alt="enter image description here" /></a></p> <p>Any advice on a route forward?</p>
[ { "answer_id": 74371914, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 2, "selected": false, "text": "Series.notna" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74371891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3316115/" ]
74,371,946
<p>i need some help with setstate asynchronous.</p> <p>i have this select</p> <pre><code>&lt;select id='province' onChange={handleProvince}&gt; &lt;option&gt;Select Province&lt;/option&gt; {province?.map(province=&gt;( &lt;option value={province.id}&gt;{province.name}&lt;/option&gt; ))} &lt;/select&gt; </code></pre> <p>and this is the onchange function</p> <pre><code>function handleProvince(e){ setProvinceID(e.target.value) axios.get(`http://192.168.18.46/api/regency/${provinceID}`).then((res)=&gt;{ setRegency(res.data.data) }) } </code></pre> <p>putting the <code>setProvinceID(e.target.value)</code> in the same function causes me to change the select element twice for it to pick the value.</p> <p>how do i anticipate it?</p> <p>any help would be much appreciated, thanks</p>
[ { "answer_id": 74372049, "author": "Paul-Marie", "author_id": 9603417, "author_profile": "https://Stackoverflow.com/users/9603417", "pm_score": 2, "selected": false, "text": "const handleProvince = ({ target }) => (\n axios.get(`http://192.168.18.46/api/regency/${target?.value}`).then(({ data }) => {\n setProvinceID(target.value);\n setRegency(data?.data);\n })\n );\n\n" }, { "answer_id": 74372165, "author": "xodeeq", "author_id": 13824776, "author_profile": "https://Stackoverflow.com/users/13824776", "pm_score": 1, "selected": true, "text": "// I imagine this is what your state declaration looks like\nconst [provinceID, setProvinceID] = useState(\"\");\n\nfunction handleProvince(e){\n setProvinceID(e.target.value)\n }\n\nuseEffect(() => {\n axios.get(`http://192.168.18.46/api/regency/${provinceID}`)\n .then((res)=>{\n setRegency(res.data.data)\n })\n}, [provinceID])\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74371946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19032485/" ]
74,371,956
<p>when I make responsive with media queries on CSS, I get auto zoomed in when opening the website on mobile, so how can I adjust the zoom or what are affecting my page?</p> <p>I tried this meta data here</p> <pre><code>&lt;link href=&quot;https://fonts.googleapis.com/css2?family=Rubik:wght@400;500;700&amp;family=Tajawal:wght@200;300;500;700&amp;display=swap&quot; rel=&quot;stylesheet&quot; /&gt; </code></pre> <p>and still get the same result</p>
[ { "answer_id": 74372049, "author": "Paul-Marie", "author_id": 9603417, "author_profile": "https://Stackoverflow.com/users/9603417", "pm_score": 2, "selected": false, "text": "const handleProvince = ({ target }) => (\n axios.get(`http://192.168.18.46/api/regency/${target?.value}`).then(({ data }) => {\n setProvinceID(target.value);\n setRegency(data?.data);\n })\n );\n\n" }, { "answer_id": 74372165, "author": "xodeeq", "author_id": 13824776, "author_profile": "https://Stackoverflow.com/users/13824776", "pm_score": 1, "selected": true, "text": "// I imagine this is what your state declaration looks like\nconst [provinceID, setProvinceID] = useState(\"\");\n\nfunction handleProvince(e){\n setProvinceID(e.target.value)\n }\n\nuseEffect(() => {\n axios.get(`http://192.168.18.46/api/regency/${provinceID}`)\n .then((res)=>{\n setRegency(res.data.data)\n })\n}, [provinceID])\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74371956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18179464/" ]
74,371,969
<p>I'm trying to use <code>\n</code> to add a new line in pandas dataframe</p> <p>Here is the sample data to test:</p> <pre><code>df = pd.DataFrame({'KEY': [4507,211,5294,2233,2260],'NAME':['kim young','laa eudong','kill gil','lee suk','No hee'],'FIND_DATE':[20130518,20140626,20140215,20141121,20140910],'EVENT_DTL':['A','B','C','D','E']}) df.loc[:3,'EVENT_DTL'] = np.nan </code></pre> <p>The dataframe looks like this:</p> <p>input:</p> <pre><code>df.loc[df.EVENT_DTL.isna(),['KEY','NAME','FIND_DATE','EVENT_DTL']] </code></pre> <p>output:</p> <pre><code> KEY NAME FIND_DATE EVENT_DTL 2143 4507 kim young 20130518 NaN 2386 211 Laa euong 20140626 NaN 2522 5294 Kim gil 20140215 NaN 3287 2233 Lee suk 20141121 NaN 3330 2260 No hee 20140910 NaN ... ... ... ... ... 62870 51632 Her yun 20170213 NaN 103829 38076 Lee jae 20150518 NaN 104560 9818 Yun young 20130812 NaN 104816 53838 Kang gae 20140818 NaN 104817 53840 Bae ssun 20141202 NaN 107 rows × 4 columns </code></pre> <p>So I tried this code to fill out <code>Nan</code> values in <code>EVENT_DTL</code> column</p> <pre><code># Let's test idx = df.EVENT_DTL.isna() df.loc[idx,'EVENT_DTL'] = ('1. 변사자 정보 : '+df.loc[idx,'NAME']+df.loc[idx,'FIND_DATE'].astype(str).str[:4]+'년'+df.loc[idx,'FIND_DATE'].astype(str).str[4:6]+'월'+' '+'\n3. 발견장소 : \n1) 수사기록 상 주소 \n주민등록상 주소 : ').str.split('\n') df = df.explode('EVENT_DTL') </code></pre> <p>And the output(When I run <code>df.loc[[2143,2386],['KEY','EVENT_DTL']]</code>to check if my code runs well); seems like it created other rows:</p> <pre><code>KEY EVENT_DTL 2143 4507 1. 변사자 정보 : kim young2013년05월 2143 4507 3. 발견장소 : 2143 4507 1) 수사기록 상 주소 2143 4507 주민등록상 주소 : 2386 211 1. 변사자 정보 : Laa euong2014년06월 2386 211 3. 발견장소 : 2386 211 1) 수사기록 상 주소 2386 211 주민등록상 주소 : </code></pre> <p>Here is the desired output:</p> <pre><code>KEY EVENT_DTL 2143 4507 1. 변사자 정보 : kim young2013년05월 3. 발견장소 : 1) 수사기록 상 주소 주민등록상 주소 : 2386 211 1. 변사자 정보 : Laa euong2014년06월 3. 발견장소 : 1) 수사기록 상 주소 주민등록상 주소 : </code></pre>
[ { "answer_id": 74372049, "author": "Paul-Marie", "author_id": 9603417, "author_profile": "https://Stackoverflow.com/users/9603417", "pm_score": 2, "selected": false, "text": "const handleProvince = ({ target }) => (\n axios.get(`http://192.168.18.46/api/regency/${target?.value}`).then(({ data }) => {\n setProvinceID(target.value);\n setRegency(data?.data);\n })\n );\n\n" }, { "answer_id": 74372165, "author": "xodeeq", "author_id": 13824776, "author_profile": "https://Stackoverflow.com/users/13824776", "pm_score": 1, "selected": true, "text": "// I imagine this is what your state declaration looks like\nconst [provinceID, setProvinceID] = useState(\"\");\n\nfunction handleProvince(e){\n setProvinceID(e.target.value)\n }\n\nuseEffect(() => {\n axios.get(`http://192.168.18.46/api/regency/${provinceID}`)\n .then((res)=>{\n setRegency(res.data.data)\n })\n}, [provinceID])\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74371969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20376341/" ]
74,371,986
<p>I have csv file with data , but there rows i dont need. So task is remove rows from table. For example:</p> <pre><code> 0 A 1 B 2 C 3 D 4 E * to delete 5 F * 6 G * 7 H * 8 I 9 J 10 k 11 L 12 M * 13 N * 14 O * 15 P * </code></pre> <p>So i want remove last 4 rows for each 8 rows in table . In table 3089 rows</p> <p>I try to slice table , but no good result</p>
[ { "answer_id": 74372015, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "import numpy as np\n\nmask = (np.arange(len(df))%8//4) == 0\n\nout = df[mask]\n" }, { "answer_id": 74372557, "author": "wwnde", "author_id": 8986975, "author_profile": "https://Stackoverflow.com/users/8986975", "pm_score": 0, "selected": false, "text": "df=df.assign(id=df.groupby(df.index//8).cumcount()).query('id<=4').drop(columns='id')\n\n item\n0 A\n1 B\n2 C\n3 D\n4 E\n8 I\n9 J\n10 k\n11 L\n12 M\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74371986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18810689/" ]
74,372,016
<p>I am trying to get the &quot;version&quot; from the <code>package.json</code> is nextjs application.</p> <p>I have tried <code>process.env.npm_package_version</code> like in node application but it's returning <code>undefined</code>.</p>
[ { "answer_id": 74372128, "author": "Paul-Marie", "author_id": 9603417, "author_profile": "https://Stackoverflow.com/users/9603417", "pm_score": 3, "selected": true, "text": "process.env.npm_package_version" }, { "answer_id": 74372166, "author": "abolfazl shamsollahi", "author_id": 11168409, "author_profile": "https://Stackoverflow.com/users/11168409", "pm_score": 0, "selected": false, "text": "NextJs" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14817835/" ]
74,372,022
<p>Is there a way to free the data leaked through <code>Box::leak</code>?</p> <p>I'm interfacing with C code, where one callback (called from C) needs to initialize and return a pointer to a specific data structure, I've used <code>Box::leak</code> for this, and later on in another callback I need to free that memory.</p> <p>Or is there another proper way to allocate and &quot;forget&quot; a rust structure on the heap, and later on free it?</p>
[ { "answer_id": 74372128, "author": "Paul-Marie", "author_id": 9603417, "author_profile": "https://Stackoverflow.com/users/9603417", "pm_score": 3, "selected": true, "text": "process.env.npm_package_version" }, { "answer_id": 74372166, "author": "abolfazl shamsollahi", "author_id": 11168409, "author_profile": "https://Stackoverflow.com/users/11168409", "pm_score": 0, "selected": false, "text": "NextJs" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1726544/" ]
74,372,036
<p>I have a list of objects stored in <code>socialmedias</code> variable. One parameter of SocialMedia class is called <code>username</code>. I want to create an array with all usernames from that list of objects <code>socialmedias</code> and I want to be sure I use the best way.</p> <pre><code>socialmedias = [obj1, obj2, obj3, ..., objN] usernames = [] for sm in socialmedias: usernames.append(sm.username) print(usernames) &gt;&gt; [username1, username2, username3, ..., usernameN] </code></pre> <p>Is there any other way to do it in less line of codes I used above?</p>
[ { "answer_id": 74372068, "author": "aleksandarbos", "author_id": 5736491, "author_profile": "https://Stackoverflow.com/users/5736491", "pm_score": 3, "selected": true, "text": "usernames = [sm.username for sm in socialmedias]" }, { "answer_id": 74372087, "author": "LoLo2207", "author_id": 8800752, "author_profile": "https://Stackoverflow.com/users/8800752", "pm_score": 0, "selected": false, "text": "usernames = [sm.username for sm in socialmedias] \n" }, { "answer_id": 74372119, "author": "Willy Lutz", "author_id": 18771355, "author_profile": "https://Stackoverflow.com/users/18771355", "pm_score": 0, "selected": false, "text": "socialmedias = [obj1, obj2, obj3, ..., objN]\nusernames = [sm.username for sm in socialmedias]\n\nprint(usernames)\n" }, { "answer_id": 74372575, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 0, "selected": false, "text": "list(map(lambda sm: sm.username, socialmedias))\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16815116/" ]
74,372,056
<p>I'm doing a dental function, I'm looking to sync data in a <code>many-to-many</code> relationship. I have the following:</p> <pre><code>tooth - id - name cost - id - name cost_tooth - id - tooth_id - cost_id - row_number </code></pre> <p>This is the data I got from input checkbox <code>tooth_id</code>, I have an array like this</p> <pre><code>[ 0 =&gt; [ 1 =&gt; [&quot;row_number&quot; =&gt; 1] 2 =&gt; [&quot;row_number&quot; =&gt; 1] 3 =&gt; [&quot;row_number&quot; =&gt; 1] 4 =&gt; [&quot;row_number&quot; =&gt; 1] ] 1 =&gt; [ 1 =&gt; [&quot;row_number&quot; =&gt; 2] 2 =&gt; [&quot;row_number&quot; =&gt; 2] 3 =&gt; [&quot;row_number&quot; =&gt; 2] 4 =&gt; [&quot;row_number&quot; =&gt; 2] ] ] </code></pre> <p>my code</p> <pre class="lang-php prettyprint-override"><code>foreach ($output as $key =&gt; $value) { $cost_id-&gt;tooths()-&gt;sync($value); } </code></pre> <p>I only get the last data but not all the data.</p> <p><a href="https://i.stack.imgur.com/p83Mo.jpg" rel="nofollow noreferrer">enter image description here</a></p> <p>I know <code>attach</code> method can solve for me but I want to try with <code>sync</code> method</p>
[ { "answer_id": 74386255, "author": "Ramil Huseynov", "author_id": 6711823, "author_profile": "https://Stackoverflow.com/users/6711823", "pm_score": 2, "selected": true, "text": "foreach ($output as $key => $value) {\n $cost_id->tooths()->syncWithoutDetaching($value);\n}\n\n" }, { "answer_id": 74386286, "author": "Le Xuan Phat", "author_id": 20097685, "author_profile": "https://Stackoverflow.com/users/20097685", "pm_score": 0, "selected": false, "text": "$output = [\n 0 => [\n 1 => [\"row_number\" => 1]\n 2 => [\"row_number\" => 1]\n 3 => [\"row_number\" => 1]\n 4 => [\"row_number\" => 1]\n ]\n 1 => [\n 1 => [\"row_number\" => 2]\n 2 => [\"row_number\" => 2]\n 3 => [\"row_number\" => 2]\n 4 => [\"row_number\" => 2]\n ]\n];\n\nforeach ($output as $key => $value) {\n $cost_id->tooths()->sync($value);\n}\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20097685/" ]
74,372,065
<p>I've been trying to use pyinstaller, but it never creates it. There is always this error: <a href="https://i.stack.imgur.com/OCvwv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OCvwv.png" alt="error" /></a></p> <p>I've found that if I put this, it should work, but it doesn't. Does somebody know how to do it? .\pyinstaller --onefile -w 'filename.py'</p>
[ { "answer_id": 74386255, "author": "Ramil Huseynov", "author_id": 6711823, "author_profile": "https://Stackoverflow.com/users/6711823", "pm_score": 2, "selected": true, "text": "foreach ($output as $key => $value) {\n $cost_id->tooths()->syncWithoutDetaching($value);\n}\n\n" }, { "answer_id": 74386286, "author": "Le Xuan Phat", "author_id": 20097685, "author_profile": "https://Stackoverflow.com/users/20097685", "pm_score": 0, "selected": false, "text": "$output = [\n 0 => [\n 1 => [\"row_number\" => 1]\n 2 => [\"row_number\" => 1]\n 3 => [\"row_number\" => 1]\n 4 => [\"row_number\" => 1]\n ]\n 1 => [\n 1 => [\"row_number\" => 2]\n 2 => [\"row_number\" => 2]\n 3 => [\"row_number\" => 2]\n 4 => [\"row_number\" => 2]\n ]\n];\n\nforeach ($output as $key => $value) {\n $cost_id->tooths()->sync($value);\n}\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20457435/" ]
74,372,079
<p>Write a function that takes three (str, c, n) arguments. Start with the end of 'str'. Insert character c after every n characters?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function three(str, c, n){ for(let i =0; i&lt;str.length; i= i+n){ str.slice(i, i+n); str = str + c; } return str; } console.log(three("apple", "c", 2));</code></pre> </div> </div> </p> <p>I think, I am using wrong method.</p>
[ { "answer_id": 74386255, "author": "Ramil Huseynov", "author_id": 6711823, "author_profile": "https://Stackoverflow.com/users/6711823", "pm_score": 2, "selected": true, "text": "foreach ($output as $key => $value) {\n $cost_id->tooths()->syncWithoutDetaching($value);\n}\n\n" }, { "answer_id": 74386286, "author": "Le Xuan Phat", "author_id": 20097685, "author_profile": "https://Stackoverflow.com/users/20097685", "pm_score": 0, "selected": false, "text": "$output = [\n 0 => [\n 1 => [\"row_number\" => 1]\n 2 => [\"row_number\" => 1]\n 3 => [\"row_number\" => 1]\n 4 => [\"row_number\" => 1]\n ]\n 1 => [\n 1 => [\"row_number\" => 2]\n 2 => [\"row_number\" => 2]\n 3 => [\"row_number\" => 2]\n 4 => [\"row_number\" => 2]\n ]\n];\n\nforeach ($output as $key => $value) {\n $cost_id->tooths()->sync($value);\n}\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20457243/" ]
74,372,088
<p>I have a function <code>getMeetingsPossibilities()</code> that return an array. For example is I have 4 teams it will return <code>['0-1', '0-2', '0-3', '1-2', '1-3', '2-3']</code>.</p> <p>I am trying to write a function that would return an array with a set of meetings for <code>n</code> time wanted.</p> <p>For example getSetsOfMeetings(3) (with 4 teams) would return something like <code>[['0-1','2-3'], ['0-2','1-3'], ['0-3','1-2']] </code></p> <p>I can not figure it out how to do this, I tried many time in vain...</p> <p>I was thinking of something like this :</p> <pre><code>let meetingsPossibilities = getMeetingsPossibilities(participantsList.length); //return for 4 teams : ['0-1', '0-2', '0-3', '1-2', '1-3', '2-3'] //Taking out a meeting from meetingPossibilities each time it is used let oneSetOfMeeting = []; oneSetOfMeeting.push(meetingPossibilities.splice(randomNumber, 1); </code></pre> <p>But I can't get the logic to have for each <code>oneSetOfMeeting </code> each teams playing only once. Would you have some idea of a way to do it ?</p>
[ { "answer_id": 74397793, "author": "Robby Cornelissen", "author_id": 3558960, "author_profile": "https://Stackoverflow.com/users/3558960", "pm_score": 3, "selected": false, "text": "n" }, { "answer_id": 74408749, "author": "Lord-JulianXLII", "author_id": 19529102, "author_profile": "https://Stackoverflow.com/users/19529102", "pm_score": 3, "selected": true, "text": "1 2 3 4 ... n/2\nn n-1 n-2 n-3 ... n/2+1\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19375171/" ]
74,372,158
<p>The problem set I am trying to solve: <a href="https://cs50.harvard.edu/python/2022/psets/3/grocery/" rel="nofollow noreferrer">CS50P 2022 psets/3/grocery/</a></p> <p>The code I wrote:</p> <pre><code> # Syntax of dict = {'key': value} mydict = {} # Infinite loop with break while True: try: item = input().upper() # Search if item matches a key inside the dict if item in mydict: mydict[item] = mydict[item] + 1 else: mydict[item] = 1 except EOFError: for i in mydict: print(mydict[i], i) break </code></pre> <p>The check50 results:</p> <pre><code>Results for cs50/problems/2022/python/grocery generated by check50 v3.3.7 :) grocery.py exists :) input of EOF halts program :) input of &quot;apple&quot; and &quot;banana&quot; yields &quot;1 APPLE 1 BANANA&quot; :) input of &quot;strawberry&quot; and &quot;strawberry&quot; yields &quot;2 STRAWBERRY&quot; :) input of &quot;mango&quot;, &quot;sugar&quot;, and &quot;mango&quot; yields &quot;2 MANGO 1 SUGAR&quot; :( input of &quot;tortilla&quot; and &quot;sweet potato&quot; yields &quot;1 SWEET POTATO 1 TORTILLA&quot; expected &quot;1 SWEET POTATO...&quot;, not &quot;\n\n1 TORTILLA...&quot; </code></pre> <p>As you can see above, check50 is failing:</p> <pre><code>:( input of &quot;tortilla&quot; and &quot;sweet potato&quot; yields &quot;1 SWEET POTATO 1 TORTILLA&quot; expected &quot;1 SWEET POTATO...&quot;, not &quot;\n\n1 TORTILLA...&quot; </code></pre> <p>But when I run python grocery.py the result seems to match the expected outcome:</p> <pre><code>tortilla sweet potato 1 TORTILLA 1 SWEET POTATO </code></pre> <p>I am having trouble understanding where I made the mistake. Please help.</p>
[ { "answer_id": 74397793, "author": "Robby Cornelissen", "author_id": 3558960, "author_profile": "https://Stackoverflow.com/users/3558960", "pm_score": 3, "selected": false, "text": "n" }, { "answer_id": 74408749, "author": "Lord-JulianXLII", "author_id": 19529102, "author_profile": "https://Stackoverflow.com/users/19529102", "pm_score": 3, "selected": true, "text": "1 2 3 4 ... n/2\nn n-1 n-2 n-3 ... n/2+1\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12078996/" ]
74,372,173
<p>I have a dataframe with a certain number of groups, containing a weight column and a list of values, which can be of arbitrary length, so for example:</p> <pre class="lang-py prettyprint-override"><code>df = pl.DataFrame( { &quot;Group&quot;: [&quot;Group1&quot;, &quot;Group2&quot;, &quot;Group3&quot;], &quot;Weight&quot;: [100.0, 200.0, 300.0], &quot;Vals&quot;: [[0.5, 0.5, 0.8],[0.5, 0.5, 0.8], [0.7, 0.9]] } ) </code></pre> <pre><code>┌────────┬────────┬─────────────────┐ │ Group ┆ Weight ┆ Vals │ │ --- ┆ --- ┆ --- │ │ str ┆ f64 ┆ list[f64] │ ╞════════╪════════╪═════════════════╡ │ Group1 ┆ 100.0 ┆ [0.5, 0.5, 0.8] │ ├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤ │ Group2 ┆ 200.0 ┆ [0.5, 0.5, 0.8] │ ├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤ │ Group3 ┆ 300.0 ┆ [0.7, 0.9] │ └────────┴────────┴─────────────────┘ </code></pre> <p>My goal is to calculate a 'weighted' column, which would be the multiple of each item in the values list with the value in the weight column:</p> <pre><code>┌────────┬────────┬─────────────────┬─────────────────┐ │ Group ┆ Weight ┆ Vals ┆ Weighted │ │ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ f64 ┆ list[f64] ┆ list[i64] │ ╞════════╪════════╪═════════════════╪═════════════════╡ │ Group1 ┆ 100.0 ┆ [0.5, 0.5, 0.8] ┆ [50, 50, 80] │ ├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤ │ Group2 ┆ 200.0 ┆ [0.5, 0.5, 0.8] ┆ [100, 100, 160] │ ├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤ │ Group3 ┆ 300.0 ┆ [0.7, 0.9] ┆ [210, 270] │ └────────┴────────┴─────────────────┴─────────────────┘ </code></pre> <p>I've tried a few different things:</p> <pre><code>df.with_columns([ pl.col(&quot;Vals&quot;).arr.eval(pl.element() * 3).alias(&quot;Weight1&quot;), #Multiplying with literal works pl.col(&quot;Vals&quot;).arr.eval(pl.element() * pl.col(&quot;Weight&quot;)).alias(&quot;Weight2&quot;), #Does not work pl.col(&quot;Vals&quot;).arr.eval(pl.element() * pl.col(&quot;Unknown&quot;)).alias(&quot;Weight3&quot;), #Unknown columns give same value pl.col(&quot;Vals&quot;).arr.eval(pl.col(&quot;Vals&quot;) * pl.col(&quot;Weight&quot;)).alias(&quot;Weight4&quot;), #Same effect # pl.col('Vals') * 3 -&gt; gives an error ] ) </code></pre> <pre><code>┌────────┬────────┬────────────┬────────────┬──────────────┬──────────────┬────────────────────┐ │ Group ┆ Weight ┆ Vals ┆ Weight1 ┆ Weight2 ┆ Weight3 ┆ Weight4 │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ f64 ┆ list[f64] ┆ list[f64] ┆ list[f64] ┆ list[f64] ┆ list[f64] │ ╞════════╪════════╪════════════╪════════════╪══════════════╪══════════════╪════════════════════╡ │ Group1 ┆ 100.0 ┆ [0.5, 0.5, ┆ [1.5, 1.5, ┆ [0.25, 0.25, ┆ [0.25, 0.25, ┆ [0.25, 0.25, 0.64] │ │ ┆ ┆ 0.8] ┆ 2.4] ┆ 0.64] ┆ 0.64] ┆ │ ├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤ │ Group2 ┆ 200.0 ┆ [0.5, 0.5, ┆ [1.5, 1.5, ┆ [0.25, 0.25, ┆ [0.25, 0.25, ┆ [0.25, 0.25, 0.64] │ │ ┆ ┆ 0.8] ┆ 2.4] ┆ 0.64] ┆ 0.64] ┆ │ ├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤ │ Group3 ┆ 300.0 ┆ [0.7, 0.9] ┆ [2.1, 2.7] ┆ [0.49, 0.81] ┆ [0.49, 0.81] ┆ [0.49, 0.81] │ └────────┴────────┴────────────┴────────────┴──────────────┴──────────────┴────────────────────┘ </code></pre> <p>Unless I'm not understanding it correctly, it seems like you're unable to access columns outside of the list from within the eval function. Perhaps there might be a way to use list comprehension within the statement, but that doesn't really seem like a neat solution.</p> <p>What would be the recommended approach here? Any help would be appreciated!</p>
[ { "answer_id": 74375312, "author": "alexp", "author_id": 10120952, "author_profile": "https://Stackoverflow.com/users/10120952", "pm_score": 0, "selected": false, "text": "import polars as pl\nimport numpy as np\n\ndef weighted_list(ls, weight):\n return(list(np.array(ls) * weight))\n\n(df.with_columns([pl.struct([\"Weight\", \"Vals\"])\n .apply(lambda x: weighted_list(x[\"Vals\"], x[\"Weight\"]))])\n)\n" }, { "answer_id": 74377523, "author": "MYK", "author_id": 17194313, "author_profile": "https://Stackoverflow.com/users/17194313", "pm_score": 2, "selected": true, "text": "(df\n .explode('Vals')\n .with_columns(Weighted = pl.col('Weight')*pl.col('Vals'))\n .groupby('Group')\n .agg([\n pl.col('Weight').first(), \n pl.col('Vals').list(),\n pl.col('Weighted').list()\n ]) \n)\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20451894/" ]
74,372,226
<p>Good morning community! i need to transform this jquery code to vanilla JS, In this case it uses: =&gt; :contains()</p> <p>this is the code in jquery</p> <pre><code>var hoveredProjectActive = $( &quot;#cursor-outer .project__caption:contains('&quot; + hoveredProject + &quot;')&quot; ); </code></pre> <p>This is the code i made in vanilla JS, i made a function to get that .textContent inside some selector, with no success..</p> <pre><code>function contains(selector, text) { var elements = document.querySelectorAll(selector); return [].filter.call(elements, function(element){ return RegExp(text).test(element.textContent); }); } const hoveredProjectActive = contains(&quot;#cursor-outer .project__caption&quot;, `${hoveredProject}`); </code></pre> <p>Is anyone able to help me to transform this code, thanks in advance :)</p>
[ { "answer_id": 74372552, "author": "ByGio1", "author_id": 18184792, "author_profile": "https://Stackoverflow.com/users/18184792", "pm_score": 0, "selected": false, "text": "`${hoveredProject}`\n" }, { "answer_id": 74373758, "author": "dvicemuse", "author_id": 1155184, "author_profile": "https://Stackoverflow.com/users/1155184", "pm_score": 2, "selected": true, "text": "function contains(selector, text) {\n var elements = document.querySelectorAll(selector);\n return [].filter.call(elements, function(element){\n return element.textContent.includes(text);\n });\n}\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18184792/" ]
74,372,241
<p>I have been trying to execute a GNU C project on ARM Cortex M3 Processor. The project runs happily on -Og optimisation level , but when I tried increasing the optimisation levels to -O2, -O3 , I encountered bus faults.</p> <p>The GNU tool chain was &quot;arm-none-eabi V10.3.1&quot;</p> <p>Tried reading the BFSR register and it suggested it was a PRECISERR &amp; STKERR. The fault was happening in a self implemented memset function and was done because the project didn't require the standard CLibs.</p> <pre><code>void* memset(void s, int c, size_t len){ unsigned char *dst; dst = (unsigned char) s; while (len &gt; 0) { *dst = (unsigned char) c; dst++; len--; } return s; } </code></pre> <p>Also after going through the Assembly for this function , noticed that this was completely different for the -Og option (which worked) and -O2/3/s option which crashed.</p> <p>I am copying the screenshot of the assembly for the two options here.</p> <p><a href="https://i.stack.imgur.com/rgOgd.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rgOgd.jpg" alt="-Og option" /></a> <a href="https://i.stack.imgur.com/SPRWi.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SPRWi.jpg" alt="-O2/3/s option" /></a></p> <p>Believe its the return from this function which causes the STKERR, And I have seen a BL instruction (in the -O2/O3/O4 option) which might be the root cause as it pushes the next the instruction address in the Link register and a subsequent pop PC's could fail ?</p> <p>But I was able to get around the issue by a small modification the code and making the variables as volatile. The new implementation below.</p> <pre><code>void* memset(void *s, int c, size_t len) { unsigned char * volatile dst; volatile size_t count = 0; dst = (unsigned char * volatile) s; while (count &lt; len) { dst[count] = (unsigned char) c; count++; } return s; } </code></pre> <p>Please wanted to know whether this is a bug in the GNU tool chain ?</p> <p>The assembly of the problematic memset function here (-O2/-O3/-Os) :-</p> <pre><code> .section .text.memset,&quot;ax&quot;,%progbits .align 1 .p2align 2,,3 .global memset .syntax unified .thumb .thumb_func .type memset, %function memset: .cfi_startproc @ args = 0, pretend = 0, frame = 0 @ frame_needed = 0, uses_anonymous_args = 0 push {r4, lr} mov r4, r0 cbz r2, .L34 uxtb r1, r1 bl memset mov r0, r4 pop {r4, pc} .cfi_endproc </code></pre> <p>Assembly of the memset function compiled with -Og option (which works)</p> <pre><code> .section .text.memset,&quot;ax&quot;,%progbits .align 1 .global memset .syntax unified .thumb .thumb_func .type memset, %function memset: .cfi_startproc @ args = 0, pretend = 0, frame = 0 @ frame_needed = 0, uses_anonymous_args = 0 @ link register save eliminated. mov r3, r0 .L20: strb r1, [r3], #1 subs r2, r2, #1 cmp r2, #0 bne .L20 bx lr .cfi_endproc .LFE81: .size memset, .-memset </code></pre>
[ { "answer_id": 74390714, "author": "Nate Eldredge", "author_id": 634919, "author_profile": "https://Stackoverflow.com/users/634919", "pm_score": 2, "selected": false, "text": "-ffreestanding" }, { "answer_id": 74391895, "author": "old_timer", "author_id": 16007, "author_profile": "https://Stackoverflow.com/users/16007", "pm_score": 0, "selected": false, "text": "typedef __SIZE_TYPE__ size_t;\nvoid* memset(void *s, int c, size_t len)\n{\n unsigned char *dst; \n dst = (unsigned char *)s;\n while (len > 0) {\n *dst = (unsigned char) c;\n dst++; \n len--;\n } \n return s; \n} \n\n\n\n00000000 <memset>:\n 0: b510 push {r4, lr}\n 2: 4604 mov r4, r0\n 4: b112 cbz r2, c <memset+0xc>\n 6: b2c9 uxtb r1, r1\n 8: f7ff fffe bl 0 <memset>\n c: 4620 mov r0, r4\n e: bd10 pop {r4, pc}\n\n\n\ntypedef __SIZE_TYPE__ size_t;\nvoid* fun(void *s, int c, size_t len)\n{\n unsigned char *dst; \n dst = (unsigned char *)s;\n while (len > 0) {\n *dst = (unsigned char) c;\n dst++; \n len--;\n } \n return s; \n} \n\n\n00000000 <fun>:\n 0: b510 push {r4, lr}\n 2: 4604 mov r4, r0\n 4: b112 cbz r2, c <fun+0xc>\n 6: b2c9 uxtb r1, r1\n 8: f7ff fffe bl 0 <memset>\n c: 4620 mov r0, r4\n e: bd10 pop {r4, pc}\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3786632/" ]
74,372,253
<p>Is my code correct? I just want to check. and is there a way that I can make it better.</p> <pre><code>import time import random string = &quot;The quick brown fox jumps over the lazy dog&quot; def TypeDelay(string): for i in range(len(string)): delay = random.uniform(0,1.1) time.sleep(delay) print(string[i], end=&quot;&quot;) TypeDelay(string) </code></pre>
[ { "answer_id": 74372336, "author": "Daweo", "author_id": 10785975, "author_profile": "https://Stackoverflow.com/users/10785975", "pm_score": 0, "selected": false, "text": "for i in string" }, { "answer_id": 74372695, "author": "Dan Nagle", "author_id": 2202018, "author_profile": "https://Stackoverflow.com/users/2202018", "pm_score": 1, "selected": false, "text": "flush" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19862700/" ]
74,372,263
<p>I am trying to write in a file N times in Prolog. I came up with this solution:</p> <pre><code>response(M,Out,N) :- write('How do you feel ?'), open('output.txt',write,Out), read(M), write(Out,M), close(Out), response(M,Out,S), S is N - 1. response(M,Out,0). </code></pre> <p>The basic idea is to read an emotion from keyboard and write it into a file called <code>output.txt</code>. It gives me this error:</p> <pre><code>ERROR: Uninstantiated argument expected, found &lt;stream&gt;(0x60000311fb00) (stream-argument) ERROR: In: ERROR: [12] open('/Users/dylan/Desktop/output.txt',write,&lt;stream&gt;(0x60000311fb00)) ERROR: [11] response(sad,&lt;stream&gt;(0x60000311fb00),_10234) at /Users/dylan/Desktop/suggestsong.pl:14 ERROR: [10] response(sad,&lt;stream&gt;(0x60000311fb00),3) at /Users/dylan/Desktop/suggestsong.pl:18 ERROR: [9] toplevel_call(user:user: ...) at /Applications/SWI- Prolog.app/Contents/swipl/boot/toplevel.pl:1158 Exception: (11) response(sad, &lt;stream&gt;(0x60000311fb00), _9654) ? creep Exception: (10) response(_9306, _9308, 3) ? creep </code></pre> <p>Thw predicate without the loop works fine, but it's just one time reading and is not good for the purpose.</p> <p>Can please someone help me ? Thank you all.</p>
[ { "answer_id": 74372336, "author": "Daweo", "author_id": 10785975, "author_profile": "https://Stackoverflow.com/users/10785975", "pm_score": 0, "selected": false, "text": "for i in string" }, { "answer_id": 74372695, "author": "Dan Nagle", "author_id": 2202018, "author_profile": "https://Stackoverflow.com/users/2202018", "pm_score": 1, "selected": false, "text": "flush" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17214298/" ]
74,372,276
<p>how can i await void of downloading in <a href="https://github.com/aalitor/AltoHttp" rel="nofollow noreferrer">alttohttp </a>library in c# .net?</p> <p>when I was using WebClient it was working to make await before the code and it awaits to finish the download but in <a href="https://github.com/aalitor/AltoHttp" rel="nofollow noreferrer">Alttohttp</a> library it doesn't await due to it's a void.</p> <p>this is the code :</p> <pre><code>httpdownloader = new HttpDownloader(uri, filename); httpdownloader.DownloadCompleted += htppdownloaderU_Completed; httpdownloader.ProgressChanged += httpdownloaderU_Progress; httpdownloader.StatusChanged += httpdownloader_StatusChanged; await httpdownloader.Start(); // then after finishing the whole download </code></pre> <p>i want this code to continue the void code after finishing the download by this library</p>
[ { "answer_id": 74372428, "author": "Joaco Ferroni", "author_id": 8837876, "author_profile": "https://Stackoverflow.com/users/8837876", "pm_score": 0, "selected": false, "text": " void httpdownloaderU_Completed(object sender, EventArgs e)\n {\n MessageBox.Show(\"Download comleted!\");\n ...\n }\n" }, { "answer_id": 74372520, "author": "Gerrie Pretorius", "author_id": 505558, "author_profile": "https://Stackoverflow.com/users/505558", "pm_score": -1, "selected": false, "text": "htppdownloaderU_Completed" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20159298/" ]
74,372,278
<p>I'm using <code>=importxml(&quot;URL-TO-SCRAPE&quot;;&quot;//html//body//text()&quot;)</code> to scrape the text of urls. However, this way the content from the header, navigation and footer is also included. How can i exclude this?</p>
[ { "answer_id": 74372428, "author": "Joaco Ferroni", "author_id": 8837876, "author_profile": "https://Stackoverflow.com/users/8837876", "pm_score": 0, "selected": false, "text": " void httpdownloaderU_Completed(object sender, EventArgs e)\n {\n MessageBox.Show(\"Download comleted!\");\n ...\n }\n" }, { "answer_id": 74372520, "author": "Gerrie Pretorius", "author_id": 505558, "author_profile": "https://Stackoverflow.com/users/505558", "pm_score": -1, "selected": false, "text": "htppdownloaderU_Completed" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3392296/" ]
74,372,307
<p>I have a list of custom objects that I want to group based on some values within the object. My code basically looks like this:</p> <pre><code>class Bar{ String someVal; int num; // group by this value Bar(this.someVal, this.num); } class Foo{ String someVal; List&lt;Bar&gt; bars; Foo(this.someVal, this.bars); } void main() { Bar bar1 = Bar(&quot;val1&quot;, 3); Bar bar2 = Bar(&quot;val2&quot;, 5); Bar bar3 = Bar(&quot;val3&quot;, 2); Foo foo1 = Foo(&quot;someString&quot;, [bar1, bar2, bar3]); Bar bar4 = Bar(&quot;val4&quot;, 2); Bar bar5 = Bar(&quot;val5&quot;, 3); Bar bar6 = Bar(&quot;val6&quot;, 1); Foo foo2 = Foo(&quot;someString&quot;, [bar4, bar5, bar6]); List&lt;Foo&gt; foos = [foo1, foo2]; // Desired result: explicit groups by attribute 'num' in Bar List&lt;Map&gt; groupedBars = [{&quot;num&quot;: 3, &quot;bar&quot;: [bar1, bar5]}, {&quot;num&quot;: 2, &quot;bar&quot;:[bar3, bar4]}, {&quot;num&quot;: 1, &quot;bar&quot;: [bar6]} ]; } </code></pre> <p>How to get these groups efficiently without looping multiple times over these nested structures? Thanks for your help!</p>
[ { "answer_id": 74372434, "author": "Christian", "author_id": 10847224, "author_profile": "https://Stackoverflow.com/users/10847224", "pm_score": 3, "selected": true, "text": "\n //Get all bars out of the foos list\n final bars = foos.map((foo) => foo.bars).expand((bars) => bars);\n \n //Get all unique numbers out of the list of bars\n final nums = bars.map((bar) => bar.num).toSet();\n \n \n //Create the desired map by finding the bars that match num\n final desiredMap= nums.map((num) => {\n \"num\" : num,\n \"bar\" : bars.where((bar) => bar.num == num).toList()\n });\n" }, { "answer_id": 74372465, "author": "VincentDR", "author_id": 19540575, "author_profile": "https://Stackoverflow.com/users/19540575", "pm_score": 0, "selected": false, "text": "List<Map> groupMyBars(List<Foo> myFoos) {\n Map<int, List<Bar>> groupedBarsMap = {};\n\n for (var foo in myFoos) {\n for (var bar in foo.bars) {\n groupedBarsMap.update(bar.num, (value) => [...value, bar], ifAbsent: () => [bar]);\n }\n }\n return groupedBarsMap.keys.fold<List<Map>>(\n [], (previousValue, element) => previousValue..add({\"num\": element, \"bar\": groupedBarsMap[element]}));\n}\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9564867/" ]
74,372,320
<p>I have this working function that takes 2 inputs as .csv files and shows chart of the data. What I would like to do is to turn function input into list instead of 2 files.</p> <p>This is the function:</p> <pre><code>def Graph(first_file,second_file): fig = make_subplots(rows=1, cols=3) list_of_atributes = [&quot;Total&quot;, &quot;Clean&quot;, &quot;Dirty&quot;] data = pd.read_csv(first_file) data2= pd.read_csv(second_file) df = pandas.DataFrame(data) df2 = pandas.DataFrame(data2) data_list = [] data_list2 = [] show_bar = df[df.Name == &quot;SUM&quot;] show_bar2 = df2[df2.Name == &quot;SUM&quot;] for n in list_of_atributes: data_list.append(int(show_bar[n])) data_list2.append(int(show_bar2[n])) fig.add_trace(go.Bar(name='File 1', x=list_of_atributes, y=data_list, marker=dict(color='red')), row=1, col=2) fig.add_trace(go.Bar(name='File 2', x=list_of_atributes, y=data_list2 ,marker=dict(color='blue')), row=1, col=1) fig.show() Grapfh(&quot;file1.csv&quot;, &quot;file2.csv&quot;) </code></pre>
[ { "answer_id": 74372542, "author": "Will", "author_id": 12829151, "author_profile": "https://Stackoverflow.com/users/12829151", "pm_score": 0, "selected": false, "text": "def Graph(files):\n \n for file in files:\n fig = make_subplots(rows=1, cols=3)\n list_of_atributes = [\"Total\", \"Clean\", \"Dirty\"]\n data = pd.read_csv(file)\n data_list = []\n show_bar = df[df.Name == \"SUM\"]\n for n in list_of_atributes:\n data_list.append(int(show_bar[n]))\n\n fig.add_trace(go.Bar(name='File 1', x=list_of_atributes, y=data_list, marker=dict(color='red')), row=1, col=2)\n fig.add_trace(go.Bar(name='File 2', x=list_of_atributes, y=data_list2 ,marker=dict(color='blue')), row=1, col=1)\n\n fig.show()\n \nGrapfh( [\"file1.csv\", \"file2.csv\"] )\n" }, { "answer_id": 74372547, "author": "Willy Lutz", "author_id": 18771355, "author_profile": "https://Stackoverflow.com/users/18771355", "pm_score": 2, "selected": true, "text": "def Graph(files):\n \n fig = make_subplots(rows=1, cols=len(files)+1)\n\n for file_idx in range(len(files)) :\n\n list_of_atributes = [\"Total\", \"Clean\", \"Dirty\"]\n data = pd.read_csv(files[file_idx])\n df = pandas.DataFrame(data)\n data_list = []\n \n show_bar = df[df.Name == \"SUM\"] \n for n in list_of_atributes:\n data_list.append(int(show_bar[n]))\n \n\n fig.add_trace(go.Bar(name=f'File {file_idx+1}', x=list_of_atributes, y=data_list, marker=dict(color='red')), row=1, col=file_idx+1)\n\n fig.show()\nGraph([\"file1.csv\", \"file2.csv\"] )\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11812842/" ]
74,372,323
<pre><code>{ metadata:{ eventcode:100 } power:on // this can be either on or off time:1667984669//unix timestamp } </code></pre> <p>My document looks something like this the power can be on or it can be off, given to and from time I have to calculate how many hours it was on, I am having trouble because in 1 day it can even have 100 on and 100 off values which means 200 documents, so how to calculate the number of operational hour(i.e time that the system was on) in mongodb query?</p>
[ { "answer_id": 74372542, "author": "Will", "author_id": 12829151, "author_profile": "https://Stackoverflow.com/users/12829151", "pm_score": 0, "selected": false, "text": "def Graph(files):\n \n for file in files:\n fig = make_subplots(rows=1, cols=3)\n list_of_atributes = [\"Total\", \"Clean\", \"Dirty\"]\n data = pd.read_csv(file)\n data_list = []\n show_bar = df[df.Name == \"SUM\"]\n for n in list_of_atributes:\n data_list.append(int(show_bar[n]))\n\n fig.add_trace(go.Bar(name='File 1', x=list_of_atributes, y=data_list, marker=dict(color='red')), row=1, col=2)\n fig.add_trace(go.Bar(name='File 2', x=list_of_atributes, y=data_list2 ,marker=dict(color='blue')), row=1, col=1)\n\n fig.show()\n \nGrapfh( [\"file1.csv\", \"file2.csv\"] )\n" }, { "answer_id": 74372547, "author": "Willy Lutz", "author_id": 18771355, "author_profile": "https://Stackoverflow.com/users/18771355", "pm_score": 2, "selected": true, "text": "def Graph(files):\n \n fig = make_subplots(rows=1, cols=len(files)+1)\n\n for file_idx in range(len(files)) :\n\n list_of_atributes = [\"Total\", \"Clean\", \"Dirty\"]\n data = pd.read_csv(files[file_idx])\n df = pandas.DataFrame(data)\n data_list = []\n \n show_bar = df[df.Name == \"SUM\"] \n for n in list_of_atributes:\n data_list.append(int(show_bar[n]))\n \n\n fig.add_trace(go.Bar(name=f'File {file_idx+1}', x=list_of_atributes, y=data_list, marker=dict(color='red')), row=1, col=file_idx+1)\n\n fig.show()\nGraph([\"file1.csv\", \"file2.csv\"] )\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19893594/" ]
74,372,331
<p>\ I've created a practice project for my test and I can't seem to get around this problem. I need a function that grabs the input and when called in another function, the input will be used to solve a problem. \ here is my code</p> <pre><code> #include &lt;stdio.h&gt; int get() { int one,two,three,four; scanf(&quot;%d %d %d %d&quot;, &amp;one, &amp;two, &amp;three, &amp;four); return one,two,three,four; } int add() { int one,two,three,four; int result1, result2, result3; get(); result1 = one + two; if (result1 == three) { result2 = four - three; result3 = result2 + four; printf(&quot;Added %d, 5th number is %d&quot;, result2, result3); } else { printf(&quot;error, %d %d %d %d&quot;, one, two, three, four); } } int main() { add(); return 0; } </code></pre> <p>When I put the scanf statement inside the function, it works. But when I use the function to get the input, I get different numbers</p>
[ { "answer_id": 74372404, "author": "Vlad from Moscow", "author_id": 2877241, "author_profile": "https://Stackoverflow.com/users/2877241", "pm_score": 2, "selected": true, "text": "get" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20423580/" ]
74,372,349
<p>I have following Code which will not select a Element, when loading the Component.</p> <pre><code> &lt;option (click)=&quot;getSelectdDropdown(1, 'Python'); addNewItemFramework(1); checkForm()&quot; [selected]=&quot;this.formGroup.controls['frameworkControl'].value=='1'&quot;&gt;Python&lt;/option&gt; &lt;option (click)=&quot;getSelectdDropdown(2, 'Ruby'); addNewItemFramework(2); checkForm()&quot; [selected]=&quot;this.formGroup.controls['frameworkControl'].value=='2'&quot;&gt;Ruby&lt;/option&gt; &lt;option (click)=&quot;getSelectdDropdown(3, 'C#'); addNewItemFramework(3); checkForm()&quot; [selected]=&quot;this.formGroup.controls['frameworkControl'].value=='3'&quot;&gt;C#&lt;/option&gt; </code></pre> <p><a href="https://i.stack.imgur.com/jUnu9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jUnu9.png" alt="enter image description here" /></a></p> <p>When I use *ngFor It always select the first Element. How should be the Code with ngFor?</p> <pre><code>&lt;option *ngFor=&quot;let title of frameworkArray&quot; &gt;{{title}} {{this.frameworkArray.indexOf(title)}}&lt;/option&gt; </code></pre> <p>The Framework Array is filled in the TypeScript Code. So there are Elements in it</p> <p><a href="https://i.stack.imgur.com/LKHh2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LKHh2.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74372400, "author": "MGX", "author_id": 20059754, "author_profile": "https://Stackoverflow.com/users/20059754", "pm_score": 3, "selected": true, "text": "export class AppComponent {\n name = 'Angular ' + VERSION.major;\n\n options = [\n { value: 0, label: 'Javascript' },\n { value: 1, label: 'Rust' },\n { value: 2, label: 'Python' },\n { value: 3, label: 'Golang' },\n ];\n\n control = new FormControl(this.options[0].value);\n}\n" }, { "answer_id": 74372714, "author": "TheMrK", "author_id": 19479665, "author_profile": "https://Stackoverflow.com/users/19479665", "pm_score": 1, "selected": false, "text": "<option *ngFor=\"let title of frameworkArray\" >\n{{title}} {{this.frameworkArray.indexOf(title)}}</option>\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18203720/" ]
74,372,405
<p>I'm not sure if it is a real problem or just lack of documentations. You can put conditions for documents in foreign collection in a lookup <code>$match</code>. You can also put conditions for the documents of original collection in a lookup <code>$match</code> with <code>$expr</code>.</p> <p>But when I want to use both of those features, it doesn't work. This is sample lookup in aggregation</p> <pre><code> { $lookup: { from: 'books', localField: 'itemId', foreignField: '_id', let: { &quot;itemType&quot;: &quot;$itemType&quot; }, pipeline: [ { $match: { $expr: { $eq: [&quot;$$itemType&quot;, &quot;book&quot;] } }} ], as: 'bookData' } } </code></pre> <p><code>$expr</code> is putting condition for original documents. But what if I want to get only foreign documents with <code>status: 'OK'</code> ? Something like:</p> <pre><code>{ $match: { status: &quot;OK&quot;, $expr: { $eq: [&quot;$$itemType&quot;, &quot;book&quot;] } }} </code></pre> <p>Does not work.</p>
[ { "answer_id": 74384199, "author": "Robert junior", "author_id": 6434717, "author_profile": "https://Stackoverflow.com/users/6434717", "pm_score": 2, "selected": true, "text": "$expr" }, { "answer_id": 74391002, "author": "user20042973", "author_id": 20042973, "author_profile": "https://Stackoverflow.com/users/20042973", "pm_score": 0, "selected": false, "text": "$match" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17344899/" ]
74,372,433
<p>Can we create a Power automate flow from a json file? Something like we do for customer connector.</p>
[ { "answer_id": 74384199, "author": "Robert junior", "author_id": 6434717, "author_profile": "https://Stackoverflow.com/users/6434717", "pm_score": 2, "selected": true, "text": "$expr" }, { "answer_id": 74391002, "author": "user20042973", "author_id": 20042973, "author_profile": "https://Stackoverflow.com/users/20042973", "pm_score": 0, "selected": false, "text": "$match" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7649568/" ]
74,372,445
<p>I want users to be able to download a Django model which is being displayed in the app. There can be many types of models, therefore I want to generalize my code. Currently I let users download the model in excel by means of the following code in HTML:</p> <pre><code>&lt;form id=&quot;downloadfile&quot; method=&quot;post&quot; action=&quot;{% url 'download_file' filename='Irrelevant.xlsx'%}&quot;&gt; {% csrf_token %} &lt;input type=&quot;hidden&quot; value=&quot;Plant&quot; name=&quot;database&quot; /&gt; &lt;input type=&quot;submit&quot; name=&quot;downloadfile&quot; class=&quot;btn btn-success&quot; value=&quot;Download Plant&quot;&gt; &lt;/form&gt; </code></pre> <p>My views.py:</p> <pre><code># Define function to download excel file using template from database.models import Plant def download_file(request, filename=''): if 'downloadfile' in request.POST: db_name = request.POST.get('database') #How to specify Plant database? response = xlsx_generator(Plant, db_name) #db_name is used to name the .xlsx file and is just a string. return response else: #some other things to do for other post requests </code></pre> <p>As you can see, I import the Plant model from <code>database.models</code>, and refer to it manually in the xlsx_generator. What I would like to do is refer to this imported model from the posted form so that I don't have to refer to it manually anymore. e.g. <code>db_model = request.POST.get('database')</code> and then <code>response = xlsx_generator(db_model, db_name)</code> where db_model refers to Plant model. Can this be achieved? And if yes, how?</p>
[ { "answer_id": 74373127, "author": "Md.Imam Hossain Roni", "author_id": 6342245, "author_profile": "https://Stackoverflow.com/users/6342245", "pm_score": 2, "selected": true, "text": "from django.conf import settings\nfrom django.apps import apps\n\n\ndef get_all_models():\n model_name_list = []\n installed_apps = settings.INSTALLED_APPS[6:]\n # just exclude system app that is not installed by you\n for app in installed_apps:\n app_config = apps.get_app_config(app)\n for model in app_config.get_models():\n model_dict = dict()\n model_dict['name']: model.__name__\n model_dict['value']: model.__name__.lower()\n model_name_list.append(model_dict)\n return model_name_list\n" }, { "answer_id": 74376910, "author": "Rivered", "author_id": 9536233, "author_profile": "https://Stackoverflow.com/users/9536233", "pm_score": 0, "selected": false, "text": "from django.apps import apps\nfrom django.conf import settings\nfrom database.utils import xlsx_generator\nfrom django.http import HttpResponse\n\ndef get_all_models():\n installed_apps = settings.INSTALLED_APPS[6:]\n model_dict={}\n # just exclude system app that is not installed by you\n for app in installed_apps:\n app_config = apps.get_app_config(app)\n for model in app_config.get_models():\n model_dict[model.__name__] = model\n return model_dict\n\n# Define function to download excel file using template\ndef download_file(request, filename=''):\n if 'downloadfile' in request.POST:\n db_name = request.POST.get('database')\n model_name_list=get_all_models()\n response = xlsx_generator(model_name_list[db_name], db_name)\n return response\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9536233/" ]
74,372,458
<p>The code is creating a random number from a low value and a high value supplied by the user. Why, when printing the value of the comp_num inside the function it returns the correct value but when printing it at the end of the sequence it is 0.</p> <pre><code>import random comp_num = 0 def generateNumber(): comp_num = random.randint(low_number,high_number) print(comp_num) low_number = int(input(&quot;Please select the minimum number&quot;)) high_number = int(input(&quot;Please select the high number&quot;)) generateNumber() print(f&quot;The comp_num is {comp_num}&quot;) </code></pre>
[ { "answer_id": 74372490, "author": "Will", "author_id": 12829151, "author_profile": "https://Stackoverflow.com/users/12829151", "pm_score": 2, "selected": true, "text": "comp_num" }, { "answer_id": 74372650, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 0, "selected": false, "text": "import random \n\ndef generateNumber(low: int, high: int) -> int:\n return random.randint(low,high)\n\nlow_number = int(input(\"Please select the minimum number\"))\nhigh_number = int(input(\"Please select the high number\"))\n\n\ncomp_num = generateNumber(low_number, high_number)\nprint(f\"The comp_num is {comp_num}\")\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2898217/" ]
74,372,493
<p>I have a WCF service (.NET C#) that sometimes returns for example <code>&amp;#xD;</code> and <code>&amp;#x1E;</code> which is not correct XML.</p> <p>I guess I could build a translator that are applied on each string field before sending response but it feels a bit sketchy, I do not know what to look for(more then the above) or what to translate it into. Maybe there is a existing solution for this?</p>
[ { "answer_id": 74372490, "author": "Will", "author_id": 12829151, "author_profile": "https://Stackoverflow.com/users/12829151", "pm_score": 2, "selected": true, "text": "comp_num" }, { "answer_id": 74372650, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 0, "selected": false, "text": "import random \n\ndef generateNumber(low: int, high: int) -> int:\n return random.randint(low,high)\n\nlow_number = int(input(\"Please select the minimum number\"))\nhigh_number = int(input(\"Please select the high number\"))\n\n\ncomp_num = generateNumber(low_number, high_number)\nprint(f\"The comp_num is {comp_num}\")\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/365624/" ]
74,372,506
<p>How can you programatically perform a button click in Flutter? I basically want to bind a number of buttons to keys on the keyboard, the most important part is that after a key is pressed the corresponding button the visual state of the button is triggered to inform the user which button was pressed.</p> <p>I am aware you can invoke the <code>onTap</code> function, but that by itself doesn't update the visual state of button. Is there a way to simulate this kind of behavior, I tried to look into <code>MaterialStateController</code> but doesn't feel like it's the right approach.</p>
[ { "answer_id": 74372490, "author": "Will", "author_id": 12829151, "author_profile": "https://Stackoverflow.com/users/12829151", "pm_score": 2, "selected": true, "text": "comp_num" }, { "answer_id": 74372650, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 0, "selected": false, "text": "import random \n\ndef generateNumber(low: int, high: int) -> int:\n return random.randint(low,high)\n\nlow_number = int(input(\"Please select the minimum number\"))\nhigh_number = int(input(\"Please select the high number\"))\n\n\ncomp_num = generateNumber(low_number, high_number)\nprint(f\"The comp_num is {comp_num}\")\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/356630/" ]
74,372,550
<p>I have swift code that looks like this:</p> <pre class="lang-swift prettyprint-override"><code>var jsFriendlyFreinds = [JSObject]() for friend in friends { let jsFriend = await FriendsPlugin.createFriendResult(friend) jsFriendlyFreinds.append(jsFriend) } </code></pre> <p>I'd like for all the async calls to happen at the same time, like how javascript's <code>Promise.all</code> works. For one-offs I know you can use <code>async let</code>, but I'm not sure how to do this in the context of a loop or map. Thanks!</p>
[ { "answer_id": 74372890, "author": "popeinvestor", "author_id": 14148255, "author_profile": "https://Stackoverflow.com/users/14148255", "pm_score": 0, "selected": false, "text": "for friend in friends async throws {\n" }, { "answer_id": 74373434, "author": "workingdog support Ukraine", "author_id": 11969817, "author_profile": "https://Stackoverflow.com/users/11969817", "pm_score": 0, "selected": false, "text": "await withTaskGroup(...)" }, { "answer_id": 74416553, "author": "Rob", "author_id": 1271826, "author_profile": "https://Stackoverflow.com/users/1271826", "pm_score": 2, "selected": true, "text": "withTaskGroup" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3090664/" ]
74,372,577
<p>I have the column:</p> <p><a href="https://i.stack.imgur.com/RJKbf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RJKbf.png" alt="period_column" /></a></p> <p>and I want to format it so I can obtain the year and the month separated by a dot like this: <a href="https://i.stack.imgur.com/dc1YB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dc1YB.png" alt="final_result" /></a>.</p> <p>The steps were the following:</p> <ol> <li>I converted the value into a text format: =TEXT($A2; &quot;000000&quot;)</li> <li>I used left and right functions to separate the year, respectively the month</li> <li>I concatenated them all and I put a dot between them</li> </ol> <p>My question is (because I spent some time): isn't it a simpler method to do all this stuff?</p>
[ { "answer_id": 74372648, "author": "JvdV", "author_id": 9758194, "author_profile": "https://Stackoverflow.com/users/9758194", "pm_score": 3, "selected": true, "text": "=TEXT(A2,\"0000\\.00\")\n" }, { "answer_id": 74372946, "author": "Robert Mearns", "author_id": 5050, "author_profile": "https://Stackoverflow.com/users/5050", "pm_score": 0, "selected": false, "text": "=DATE(LEFT(A2,4),RIGHT(A2,2),1)\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20050412/" ]
74,372,607
<p>I would like to use command</p> <pre><code>sencha web -port 3888 start </code></pre> <p>But how can I point to a specified url, for example:</p> <pre><code>http://localhost/WebContent/My.cgi?lang=en&amp;test=true </code></pre> <p>?</p>
[ { "answer_id": 74372648, "author": "JvdV", "author_id": 9758194, "author_profile": "https://Stackoverflow.com/users/9758194", "pm_score": 3, "selected": true, "text": "=TEXT(A2,\"0000\\.00\")\n" }, { "answer_id": 74372946, "author": "Robert Mearns", "author_id": 5050, "author_profile": "https://Stackoverflow.com/users/5050", "pm_score": 0, "selected": false, "text": "=DATE(LEFT(A2,4),RIGHT(A2,2),1)\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4195212/" ]
74,372,615
<p>I have a web app where the user can choose some products to buy. He could interrupts the configuration process restart it after. Now I'm using localStorage to save the info about products, price...</p> <p>I have a page where there is a table with the user's offers and he can click and continue configuring the products, but I have a problem here.</p> <p>Imagine you have start a configuration for a product, and then interrupt this. Now you go to the table page (the page with all the offers ) and when you click on the button to resume another configuration for another product and the sytesm make calls to rebuild the product's info, once all the calls have been made I save info in the localStorage and I use <code>this.router.navigate ([/destination)]</code></p> <p>Now in the page where I arrive I have:</p> <pre><code>constructor(){ this.offer = JSON.parse(localStorage.getItem(&quot;OFFER&quot;)); } ngOnInit() { this.offer = JSON.parse(localStorage.getItem(&quot;OFFER&quot;)); // I have tried to put the localStorage.getItem also in the constructor. } </code></pre> <p>Now if I check my localstorage I have the info about right product, but the page where I arrive show the info of the old one. To fix this problem i need to refresh the page.</p> <p>Now the problem is that I don't want to refresh the page to show the right info, how can I do, when I arrive in the page to show the right information about product without reload the page?</p>
[ { "answer_id": 74372771, "author": "Fabian Strathaus", "author_id": 17298437, "author_profile": "https://Stackoverflow.com/users/17298437", "pm_score": 0, "selected": false, "text": "this.router.navigate (['/destination')]" }, { "answer_id": 74374109, "author": "Puneet Sharma", "author_id": 7609791, "author_profile": "https://Stackoverflow.com/users/7609791", "pm_score": 2, "selected": true, "text": "RouterModule.forRoot(appRoutes, {\n // ..\n onSameUrlNavigation: 'reload',\n // ..\n})\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11604252/" ]
74,372,621
<p>I tried to create a slightly more complex SQL UDF that initialises a counter variable used in a while loop and then returns it.</p> <pre class="lang-sql prettyprint-override"><code>CREATE OR REPLACE FUNCTION test_func() RETURNS NUMBER AS $$ begin let counter := 0; while (counter &lt; 5) do counter := counter + 1; end while; return counter; end; $$; </code></pre> <p>I kept it simple with <a href="https://docs.snowflake.com/en/developer-guide/snowflake-scripting/loops.html#while-loop" rel="nofollow noreferrer">an example loop from documentation</a>. But I can't get it to compile despite trying out a few different variations, such as putting counter in declare:</p> <pre><code>declare counter NUMBER; </code></pre> <p>I tried a JavaScript version and that compiles and runs successfully.</p> <pre class="lang-sql prettyprint-override"><code>CREATE OR REPLACE FUNCTION test_func_js() RETURNS VARCHAR LANGUAGE JAVASCRIPT AS $$ let counter = 0; while (counter &lt; 5) { counter += 1; } return counter; $$; </code></pre> <p>I think an answer to this already lies in <a href="https://docs.snowflake.com/en/sql-reference/udf-overview.html#sql" rel="nofollow noreferrer">documentation</a>, but I just want to check if I'm missing something or someone has more experience with SQL UDFs in Snowflake.</p> <p>Am I really just limited to SQL expressions? There is no support for <a href="https://docs.snowflake.com/en/developer-guide/snowflake-scripting/index.html" rel="nofollow noreferrer">Snowflake scripting</a> inside UDFs in Snowflake?</p>
[ { "answer_id": 74372771, "author": "Fabian Strathaus", "author_id": 17298437, "author_profile": "https://Stackoverflow.com/users/17298437", "pm_score": 0, "selected": false, "text": "this.router.navigate (['/destination')]" }, { "answer_id": 74374109, "author": "Puneet Sharma", "author_id": 7609791, "author_profile": "https://Stackoverflow.com/users/7609791", "pm_score": 2, "selected": true, "text": "RouterModule.forRoot(appRoutes, {\n // ..\n onSameUrlNavigation: 'reload',\n // ..\n})\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15256436/" ]
74,372,624
<p>I'm using the following code to draw text onto a Canvas, but the text as you can see from the photo is going off the screen, rather than adhering to the width parameters i issue to the Canvas, why is this happening?</p> <p>This doesn't seem to happen if i use the older android canvas, possible compose bug?</p> <pre><code> Box( modifier = Modifier .fillMaxWidth() ) { Canvas( modifier = Modifier.width(500.dp), onDraw = { drawIntoCanvas { it.nativeCanvas.drawText( text, 0f, 120.dp.toPx(), textPaintStroke(context = context) ) it.nativeCanvas.drawText( text, 0f, 120.dp.toPx(), textPaint(context = context) ) } } ) } fun textPaintStroke( context: Context ): NativePaint { val customTypeface = ResourcesCompat.getFont(context, R.font.baloo2_semi_bold) return Paint().asFrameworkPaint().apply { isAntiAlias = true style = android.graphics.Paint.Style.STROKE textSize = 64f color = android.graphics.Color.BLACK strokeWidth = 12f strokeMiter= 10f strokeJoin = android.graphics.Paint.Join.ROUND typeface = customTypeface } } fun textPaint( context: Context ): NativePaint { val customTypeface = ResourcesCompat.getFont(context, R.font.baloo2_semi_bold) return Paint().asFrameworkPaint().apply { isAntiAlias = true style = android.graphics.Paint.Style.FILL textSize = 64f color = android.graphics.Color.WHITE typeface = customTypeface } } </code></pre> <p><a href="https://i.stack.imgur.com/w8KMt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/w8KMt.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74376742, "author": "Vahid Garousi", "author_id": 5909910, "author_profile": "https://Stackoverflow.com/users/5909910", "pm_score": 0, "selected": false, "text": "import androidx.compose.foundation.Canvas\nimport androidx.compose.foundation.background\nimport androidx.compose.foundation.layout.Box\nimport androidx.compose.foundation.layout.fillMaxSize\nimport androidx.compose.foundation.layout.width\nimport androidx.compose.runtime.Composable\nimport androidx.compose.runtime.getValue\nimport androidx.compose.runtime.mutableStateOf\nimport androidx.compose.runtime.remember\nimport androidx.compose.ui.Modifier\nimport androidx.compose.ui.graphics.Color\nimport androidx.compose.ui.text.AnnotatedString\nimport androidx.compose.ui.text.ExperimentalTextApi\nimport androidx.compose.ui.text.SpanStyle\nimport androidx.compose.ui.text.drawText\nimport androidx.compose.ui.text.rememberTextMeasurer\nimport androidx.compose.ui.unit.dp\nimport androidx.compose.ui.unit.sp\n\n@OptIn(ExperimentalTextApi::class)\n@Composable\nfun Test() {\n val text by remember {\n mutableStateOf(\"Choose the flash with matechest!\")\n }\n Box(\n modifier = Modifier\n .fillMaxSize()\n .background(Color.Green)\n ) {\n val textMeasurer = rememberTextMeasurer()\n Canvas(\n modifier = Modifier.width(10.dp),\n onDraw = {\n val textResult = textMeasurer.measure(\n AnnotatedString(\n text, spanStyle = SpanStyle(\n fontSize = 24.sp\n )\n )\n )\n drawText(textResult)\n }\n )\n }\n}\n" }, { "answer_id": 74420429, "author": "Thracian", "author_id": 5457853, "author_profile": "https://Stackoverflow.com/users/5457853", "pm_score": 0, "selected": false, "text": "DrawScope" }, { "answer_id": 74436364, "author": "Gabriele Mariotti", "author_id": 2016562, "author_profile": "https://Stackoverflow.com/users/2016562", "pm_score": 4, "selected": true, "text": "1.4.0-alpha01" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11541512/" ]
74,372,636
<p>I downloaded a a prepared dataset for YoloV7. Also I cloned yoloV7 Repo.</p> <p>I want to train a model with this downloaded dataset, for this I use this command.</p> <pre><code>python train.py --workers 8 --device 0 --batch-size 16 --data data.yaml --img 640 640 --cfg cfg/training/yolov7.yaml --weights yolov7x.pt --name yolov7 --hyp data/hyp.scratch.p5.yaml </code></pre> <p>I got this RuntimeError</p> <pre><code>autoanchor: Analyzing anchors... anchors/target = 5.50, Best Possible Recall (BPR) = 1.0000 Image sizes 640 train, 640 test Using 8 dataloader workers Logging results to runs\train\yolov74 Starting training for 300 epochs... Epoch gpu_mem box obj cls total labels img_size 0%| | 0/372 [00:03&lt;?, ?it/s] Traceback (most recent call last): File &quot;D:\projects\yolov7\train.py&quot;, line 618, in &lt;module&gt; train(hyp, opt, device, tb_writer) File &quot;D:\projects\yolov7\train.py&quot;, line 363, in train loss, loss_items = compute_loss_ota(pred, targets.to(device), imgs) # loss scaled by batch_size File &quot;D:\projects\yolov7\utils\loss.py&quot;, line 585, in __call__ bs, as_, gjs, gis, targets, anchors = self.build_targets(p, targets, imgs) File &quot;D:\projects\yolov7\utils\loss.py&quot;, line 759, in build_targets from_which_layer = from_which_layer[fg_mask_inboxes] RuntimeError: indices should be either on cpu or on the same device as the indexed tensor (cpu) </code></pre> <p>My System contains 1xCpu, 1x Cuda GPU (its a default gaming pc)</p>
[ { "answer_id": 74383094, "author": "anactualtoaster", "author_id": 14077571, "author_profile": "https://Stackoverflow.com/users/14077571", "pm_score": 4, "selected": true, "text": "utils/loss.py" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3290745/" ]
74,372,652
<p>Sorry for any miswording of anything here I am not a native english speaker I have been trying to randomly pick a number between 1 - 6 in c# and for whatever reason it says System.Func`1[System.Int32] every time I try to print it out (i know usually this is done in main but this is my homework and I was ordered not to put it in main)</p> <pre><code>namespace ConsoleApp9 { internal class Program { static Random random = new Random(); static void Main(string[] args) { Console.WriteLine(GetDice); } public static int GetDice() { Random random = new Random(); int dice = random.Next(1, 100); return dice; } } } </code></pre>
[ { "answer_id": 74383094, "author": "anactualtoaster", "author_id": 14077571, "author_profile": "https://Stackoverflow.com/users/14077571", "pm_score": 4, "selected": true, "text": "utils/loss.py" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14705533/" ]
74,372,665
<p>How can I extend y-axis in the way that line in the top don't finish sharply with the end of graph. In this case would be fine to extend y-axis to 8 or even 9, note that I can't set limit to 8 because speed value will be always different. It's only about visual effect.</p> <p>Second question, also estetic, graph start with double 0, how can I delete one of them but still keep graph in same way</p> <p><a href="https://i.stack.imgur.com/QX2aL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QX2aL.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74372904, "author": "James Hinkley", "author_id": 11398693, "author_profile": "https://Stackoverflow.com/users/11398693", "pm_score": 2, "selected": true, "text": "ax = plt.gca()\nax.set_xlim([xmin, xmax])\nax.set_ylim([ymin, ymax])\n" }, { "answer_id": 74373220, "author": "Marcin Kamienski", "author_id": 6125812, "author_profile": "https://Stackoverflow.com/users/6125812", "pm_score": 0, "selected": false, "text": "ymax = round(max(y))+1" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6125812/" ]
74,372,679
<p>I am trying to remove all words from a string except certain words, for example I want to retain 'red' and 'black' including all combinations it has and remove all other strings.</p> <p>For example inputstring = &quot;red =&gt; white =&gt; green =&gt; black,magenta&quot; outputstring = &quot;red =&gt; black,magenta&quot;</p> <p>I have tried to replace string using regex pattern as = &quot;^red|^black&quot; but it does not change anything in the string.</p> <p>I am using X query and am unable to figure out pattern to be used in Regex <code>let $pattern := &quot;^red|^black&quot; let $pattern := &quot;&quot; let $y := replace($inputstring,$pattern,$replacement)</code></p>
[ { "answer_id": 74372911, "author": "JohnyCapo", "author_id": 19335841, "author_profile": "https://Stackoverflow.com/users/19335841", "pm_score": 1, "selected": false, "text": "=>" }, { "answer_id": 74373640, "author": "zephryl", "author_id": 17303805, "author_profile": "https://Stackoverflow.com/users/17303805", "pm_score": 0, "selected": false, "text": "\" => \"" }, { "answer_id": 74374496, "author": "Michael Kay", "author_id": 415448, "author_profile": "https://Stackoverflow.com/users/415448", "pm_score": 0, "selected": false, "text": "$input \n => tokenize('\\s?=>\\s?') \n => filter(matches(?, 'red|black'))\n => string-join(' => ')\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9372847/" ]
74,372,686
<p><strong>Project Details:</strong> In this <strong>WPF</strong> project, video is displayed on the number of structures. In fact, it is a kind of simulator that simulates the display of video on the LEDs installed on the structure or building.</p> <pre><code>private async Task PlayBinAsync() { InitBinList(); if (animPlayingMode == AnimPlayingMode.ParallelSynchronous) { List&lt;Task&gt; runningTasks = new List&lt;Task&gt;(); Coordinator.Clear(); for (int i = 0; i &lt; Products.Count; i++) { Coordinator.Add(0); Task runningTask = ReadDisplayBinFrames(Products[i], true); runningTasks.Add(runningTask); #if DEBUG Debug.WriteLine($&quot;LedProducts Count: {Products[i].LastFrameRead} of Product {i}&quot;); #endif } await Task.WhenAll(runningTasks); } } public async Task ReadDisplayBinFrames(Product product, bool PlayMode) { BinFile.SetPlayMode(PlayMode); while (BinFile.IsPlayMode) { for (int currentFrameNumber = product.LastFrameRead; currentFrameNumber &lt;= product.BinFiles.TotalGame; currentFrameNumber++) { await Task.Run(() =&gt; { product.BinFiles.GetSphereColorFromBin(product.BinFiles.GetFrame(currentFrameNumber), product.Wiring); product.LastFrameRead = currentFrameNumber; #if DEBUG Debug.WriteLine($&quot;LastFrameRead {product.LastFrameRead}&quot;); #endif product.Wiring.SetSphereColor(product.DelayPlay); }); Coordinator[product.ProductId] += 1; await AllowPlayAsync(Coordinator); if (currentFrameNumber &gt;= product.BinFiles.TotalGame) { product.LastFrameRead = 0; } if (animPlayingMode == AnimPlayingMode.SerialAsync) { BinFile.SetPlayMode(false); } } } } private async Task AllowPlayAsync(List&lt;int&gt; input) { if (input.All(o =&gt; o == input[0])) { signal.Release(); } else { await signal.WaitAsync(); } } List&lt;int&gt; Coordinator = new List&lt;int&gt;(); private SemaphoreSlim signal = new SemaphoreSlim(0, 1); </code></pre> <p><strong>Project requirements:</strong></p> <p>1- I want all the structures or buildings to run the videos in unison and not even one frame behind or one frame forward. 2- The project should run continuously and should not stop playing the video until it stops.</p> <p>In order for the frames to be executed together on the structures, I store the number of executed frames in a list and wait for all the frames to meet and become one using the AllowPlayAsync method. It is equalized, the work continues.</p> <p>But unfortunately it does not work properly!</p>
[ { "answer_id": 74431083, "author": "KeyvanSFX", "author_id": 3202916, "author_profile": "https://Stackoverflow.com/users/3202916", "pm_score": 1, "selected": true, "text": "private volatile static SemaphoreSlim signal = new SemaphoreSlim(0);\npublic volatile static ObservableCollection<Product> Products;\n\nprivate void ImportProducts()\n {\n // After Import Products\n // The number of members in the Products Collection should be equal to the number of members in the Products list.\n Products = new ObservableCollection<Product>();\n }\n\npublic async Task ReadDisplayBinFrames(Product product, bool PlayMode)\n {\n product.BinFiles.IsPlayMode = PlayMode;\n for (int currentFrameNumber = product.LastFrameRead; currentFrameNumber <= product.BinFiles.TotalGame && product.BinFiles.IsPlayMode; currentFrameNumber++)\n {\n await Task.Run(() =>\n {\n product.LastFrameRead = currentFrameNumber;\n AllowPlayAsync();\n\n product.BinFiles.GetSphereColorFromBin(product.BinFiles.GetFrame(currentFrameNumber), product.Wiring);\n#if DEBUG\n Debug.WriteLine($\"LastFrameRead {product.LastFrameRead} - PlayMode: {product.BinFiles.IsPlayMode}\");\n#endif\n\n SetSphereColor(product.Wiring,product.DelayPlay);\n\n if (currentFrameNumber >= product.BinFiles.TotalGame)\n {\n product.LastFrameRead = currentFrameNumber = -1;\n }\n\n Application.Current.Dispatcher.InvokeAsync(() =>\n {\n if (animPlayingMode == AnimPlayingMode.SerialAsync)\n {\n product.BinFiles.IsPlayMode = false;\n }\n });\n });\n }\n }\n\n\nprivate void AllowPlayAsync()\n {\n while (true)\n {\n if (Coordinator.ToList().All(o => o == Coordinator[0]))\n {\n signal.Release();\n return;\n }\n else\n {\n signal.Wait();\n }\n }\n }\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3202916/" ]
74,372,694
<p>I want to get rid of repeated measures in my data file. The idea is that people pressed the space bar and I want to eliminate rows when participants pressed the key more frequently than once in 3 seconds. I created this loop, but I see that it doesn't remove all the cases and it throws an error because the number of rows changes all the time.</p> <p>Do you have an idea, of how to change this loop to make it serve its purpose correctly?</p> <pre><code>df_window_rem &lt;- df_window for (i in 2:nrow(df_window_rem)) { p &lt;- df_window_rem[[i,3]] ##cell with time people presses q &lt;- df_window_rem[[i-1,3]] ##cell with the previous click x &lt;- df_window_rem[[i,4]] ##score 0/1 for this cell y &lt;- df_window_rem[[i-1,4]] ##score 0/1 for previous cell if((p-q)&lt;3){ if (x == 1 &amp; y == 0) { df_window_rem &lt;- df_window_rem[-(i-1)] } else if (x == 0 &amp; y == 1){ df_window_rem &lt;- df_window_rem[-i] } else if (x == 1 &amp; y == 1) { df_window_rem&lt;- df_window_rem[-i] } } } </code></pre>
[ { "answer_id": 74431083, "author": "KeyvanSFX", "author_id": 3202916, "author_profile": "https://Stackoverflow.com/users/3202916", "pm_score": 1, "selected": true, "text": "private volatile static SemaphoreSlim signal = new SemaphoreSlim(0);\npublic volatile static ObservableCollection<Product> Products;\n\nprivate void ImportProducts()\n {\n // After Import Products\n // The number of members in the Products Collection should be equal to the number of members in the Products list.\n Products = new ObservableCollection<Product>();\n }\n\npublic async Task ReadDisplayBinFrames(Product product, bool PlayMode)\n {\n product.BinFiles.IsPlayMode = PlayMode;\n for (int currentFrameNumber = product.LastFrameRead; currentFrameNumber <= product.BinFiles.TotalGame && product.BinFiles.IsPlayMode; currentFrameNumber++)\n {\n await Task.Run(() =>\n {\n product.LastFrameRead = currentFrameNumber;\n AllowPlayAsync();\n\n product.BinFiles.GetSphereColorFromBin(product.BinFiles.GetFrame(currentFrameNumber), product.Wiring);\n#if DEBUG\n Debug.WriteLine($\"LastFrameRead {product.LastFrameRead} - PlayMode: {product.BinFiles.IsPlayMode}\");\n#endif\n\n SetSphereColor(product.Wiring,product.DelayPlay);\n\n if (currentFrameNumber >= product.BinFiles.TotalGame)\n {\n product.LastFrameRead = currentFrameNumber = -1;\n }\n\n Application.Current.Dispatcher.InvokeAsync(() =>\n {\n if (animPlayingMode == AnimPlayingMode.SerialAsync)\n {\n product.BinFiles.IsPlayMode = false;\n }\n });\n });\n }\n }\n\n\nprivate void AllowPlayAsync()\n {\n while (true)\n {\n if (Coordinator.ToList().All(o => o == Coordinator[0]))\n {\n signal.Release();\n return;\n }\n else\n {\n signal.Wait();\n }\n }\n }\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19852988/" ]
74,372,749
<p>I wonder if it is still not possible to pass an actual row as a parameter to a function or procedure in oracle. I saw already some questions according to this topic but haven't found an answer which is good for me. I need doing something like this:</p> <pre><code>function my_func(myrow t%rowtype)AS BEGIN END; </code></pre> <p>So the function would get the row as parameter.</p> <pre><code>Select t.c1, my_func(t.*) -- where t.* is actual row processed. from t; </code></pre> <p>And in the select I would love to pass the single row, which is actually proccesed. I wish to avoid to pass many parameters, which would be a case if I would pass them separately like this:</p> <pre><code>Select t.c1, my_func(t.c1,... t.c10) from t; </code></pre> <p>I also don't want to pass an actual id as I don't want to do an additional select in a function.</p>
[ { "answer_id": 74373875, "author": "Thorsten Kettner", "author_id": 2270762, "author_profile": "https://Stackoverflow.com/users/2270762", "pm_score": 2, "selected": false, "text": "ROWID" }, { "answer_id": 74374151, "author": "Alex Poole", "author_id": 266304, "author_profile": "https://Stackoverflow.com/users/266304", "pm_score": 2, "selected": false, "text": "rowid" }, { "answer_id": 74375617, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 1, "selected": false, "text": "%ROWTYPE" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16964468/" ]
74,372,761
<p>Example : The last name is 'Daniel Thomas Kon'<br /> Output is expecting based on this condition - &gt; if less than or equal to 3 put 1st word in last name and remaining will be in firstname</p> <p>Here the output will be--</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>last name</th> <th>first name</th> </tr> </thead> <tbody> <tr> <td>Daniel</td> <td>Thomas Kon</td> </tr> </tbody> </table> </div> <p>Here the output will be--</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>last name</th> <th>first name</th> </tr> </thead> <tbody> <tr> <td>Daniel</td> <td>Thomas Kon</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74373091, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 0, "selected": false, "text": "SELECT REGEXP_SUBSTR(name, '^(\\S+(\\s+\\S+)*?)\\s+(\\S+(\\s+\\S+)?)$', 1, 1, NULL, 1) AS last_names,\n REGEXP_SUBSTR(name, '^(\\S+(\\s+\\S+)*?)\\s+(\\S+(\\s+\\S+)?)$', 1, 1, NULL, 3) AS first_names\nFROM table_name\n" }, { "answer_id": 74373348, "author": "sanjay patel", "author_id": 20299485, "author_profile": "https://Stackoverflow.com/users/20299485", "pm_score": -1, "selected": false, "text": "DECLARE @Table VARCHAR(100) = 'Daniel Thomas Kon'\nDECLARE @PartialString VARCHAR(100) = SUBSTRING(@Table, CHARINDEX(' ', @Table) + 1, len(@Table))\n\nSELECT CHARINDEX(' ', SUBSTRING(@Table, CHARINDEX(' ', @Table) + 1, len(@Table))) + 1\n ,CASE \n WHEN (len(@Table) - len(replace(@Table, ' ', '')) + 1) = 3\n THEN SUBSTRING(@Table, CHARINDEX(' ', @Table) + 1, len(@Table))\n WHEN (len(@Table) - len(replace(@Table, ' ', '')) + 1) > 3\n THEN SUBSTRING(@PartialString, CHARINDEX(' ', @PartialString) + 1, len(@PartialString))\n END AS firstname\n ,CASE \n WHEN (len(@Table) - len(replace(@Table, ' ', '')) + 1) = 3\n THEN SUBSTRING(@Table, 0, CHARINDEX(' ', @Table) + 1)\n WHEN (len(@Table) - len(replace(@Table, ' ', '')) + 1) > 3\n THEN SUBSTRING(@Table, 0, len(@PartialString) - 1)\n END AS lastname\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20457834/" ]
74,372,780
<p>Prior to 4 November it was working fine and now when I am trying to build it by running yarn android but it is showing me</p> <pre><code>Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081 /Users/dev/Desktop/Abc Projects/aargee/node_modules/react-native-webrtc/android/src/main/java/com/oney/WebRTCModule/VideoTrackAdapter.java:5: error: cannot access VideoFrame import org.webrtc.VideoFrame; ^ bad class file: /Users/dev/.gradle/caches/transforms-2/files-2.1/8af035e80c335f19cef40762b46ee77a/jetified-libwebrtc.jar(org/webrtc/VideoFrame.class) class file has wrong version 55.0, should be 52.0 Please remove or make sure it appears in the correct subdirectory of the classpath. FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':react-native-webrtc:compileDebugJavaWithJavac'. &gt; Compilation failed; see the compiler error output for details. * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. </code></pre> <p>&quot;react-native&quot;: &quot;^0.66.3&quot;, &quot;react-native-webrtc&quot;: &quot;^1.94.1&quot;,</p> <p>I have tried solution from <a href="https://stackoverflow.com/questions/74370367/my-react-native-was-working-fine-upto-4-november-but-now-throwing-an-exception-w">My React Native was working fine upto 4 November but now throwing an exception while Running yarn android</a> but no luck. Any help will be appreciated.</p>
[ { "answer_id": 74372862, "author": "ZFloc Technologies", "author_id": 10657559, "author_profile": "https://Stackoverflow.com/users/10657559", "pm_score": 1, "selected": false, "text": "android/.idea" }, { "answer_id": 74385634, "author": "SHINDE RAHUL DNYANESHWAR", "author_id": 13880248, "author_profile": "https://Stackoverflow.com/users/13880248", "pm_score": 0, "selected": false, "text": "allprojects {\n repositories {\n mavenCentral()\n google()\n jcenter()\n maven {\n // Android JSC is installed from npm\n url(\"$rootDir/../node_modules/jsc-android/dist\")\n }\n maven { url 'https://www.jitpack.io' }\n exclusiveContent {\n filter {\n includeGroup \"com.facebook.react\"\n }\n forRepository {\n maven {\n url \"$rootDir/../node_modules/react-native/android\"\n }\n }\n }\n }\n}\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13884276/" ]
74,372,835
<p>I had an issue in Swift 5.5 and I don't really understand the solution.</p> <pre class="lang-swift prettyprint-override"><code>import Foundation func testAsync() async { var animal = &quot;Dog&quot; DispatchQueue.main.asyncAfter(deadline: .now() + 2) { animal = &quot;Cat&quot; print(animal) } print(animal) } Task { await testAsync() } </code></pre> <p>This piece of code results in an error</p> <pre class="lang-none prettyprint-override"><code>Mutation of captured var 'animal' in concurrently-executing code </code></pre> <p>However, if you move the <code>animal</code> variable away from the context of this async function,</p> <pre class="lang-swift prettyprint-override"><code>import Foundation var animal = &quot;Dog&quot; func testAsync() async { DispatchQueue.main.asyncAfter(deadline: .now() + 2) { animal = &quot;Cat&quot; print(animal) } print(animal) } Task { await testAsync() } </code></pre> <p>it will compile. I understand this error is to prevent data races but why does moving the variable make it safe?</p>
[ { "answer_id": 74393379, "author": "Rob", "author_id": 1271826, "author_profile": "https://Stackoverflow.com/users/1271826", "pm_score": 3, "selected": true, "text": "actor AnimalActor {\n var animal = \"Dog\"\n \n func setAnimal(newAnimal: String) {\n animal = newAnimal\n }\n}\n\nfunc testAsync() async {\n let animalActor = AnimalActor()\n \n Task {\n try await Task.sleep(nanoseconds: 2 * NSEC_PER_SEC)\n await animalActor.setAnimal(newAnimal: \"Cat\")\n print(await animalActor.animal)\n }\n\n print(await animalActor.animal)\n}\n\nTask {\n await testAsync()\n}\n" }, { "answer_id": 74408406, "author": "Cheezzhead", "author_id": 2542661, "author_profile": "https://Stackoverflow.com/users/2542661", "pm_score": 0, "selected": false, "text": "async" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14014307/" ]
74,372,851
<p>Input Table</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">index</th> <th style="text-align: center;">income</th> <th style="text-align: right;">Education</th> <th style="text-align: right;">age1to_20</th> <th style="text-align: right;">pcd</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">1</td> <td style="text-align: center;">income_1</td> <td style="text-align: right;">Education_0</td> <td style="text-align: right;">1</td> <td style="text-align: right;">A5009</td> </tr> <tr> <td style="text-align: left;">2</td> <td style="text-align: center;">income_2</td> <td style="text-align: right;">Education_2</td> <td style="text-align: right;">1</td> <td style="text-align: right;">A3450</td> </tr> <tr> <td style="text-align: left;">3</td> <td style="text-align: center;">income_1</td> <td style="text-align: right;">Education_0</td> <td style="text-align: right;">1</td> <td style="text-align: right;">A5009</td> </tr> <tr> <td style="text-align: left;">4</td> <td style="text-align: center;">income_3</td> <td style="text-align: right;">Education_1</td> <td style="text-align: right;">0</td> <td style="text-align: right;">A3450</td> </tr> </tbody> </table> </div> <p>How do I convert this table into</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">index</th> <th style="text-align: center;">income_1</th> <th style="text-align: right;">income_2</th> <th style="text-align: right;">INCOME_3</th> <th style="text-align: right;">Education_0</th> <th style="text-align: right;">Education_1</th> <th style="text-align: right;">Education_2</th> <th style="text-align: right;">age1to_20</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">1</td> <td style="text-align: center;">A5009</td> <td style="text-align: right;">0</td> <td style="text-align: right;">0</td> <td style="text-align: right;">A5009</td> <td style="text-align: right;">0</td> <td style="text-align: right;">0</td> <td style="text-align: right;">A5009</td> </tr> <tr> <td style="text-align: left;">2</td> <td style="text-align: center;">0</td> <td style="text-align: right;">A3450</td> <td style="text-align: right;">0</td> <td style="text-align: right;">0</td> <td style="text-align: right;">0</td> <td style="text-align: right;">A3450</td> <td style="text-align: right;">A3450</td> </tr> <tr> <td style="text-align: left;">3</td> <td style="text-align: center;">A5009</td> <td style="text-align: right;">0</td> <td style="text-align: right;">0</td> <td style="text-align: right;">A5009</td> <td style="text-align: right;">0</td> <td style="text-align: right;">0</td> <td style="text-align: right;">A5009</td> </tr> <tr> <td style="text-align: left;">4</td> <td style="text-align: center;">0</td> <td style="text-align: right;">0</td> <td style="text-align: right;">A3450</td> <td style="text-align: right;">0</td> <td style="text-align: right;">A3450</td> <td style="text-align: right;">0</td> <td style="text-align: right;">0</td> </tr> </tbody> </table> </div> <p><strong>UPDATED THE OUTPUT TABLE</strong></p>
[ { "answer_id": 74372884, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "melt" }, { "answer_id": 74373084, "author": "PaulS", "author_id": 11564487, "author_profile": "https://Stackoverflow.com/users/11564487", "pm_score": 2, "selected": false, "text": "(pd.concat([\n df.pivot(index=['index', 'age1to_20'], columns=['income'], values='pcd'),\n df.pivot(index=['index', 'age1to_20'], columns=['Education'], values='pcd')], axis=1)\n .fillna(0).reset_index())\n" }, { "answer_id": 74374161, "author": "sammywemmy", "author_id": 7175713, "author_profile": "https://Stackoverflow.com/users/7175713", "pm_score": 1, "selected": false, "text": "out = df.pivot(index=['index', 'age1to_20'], \n columns=['income', 'Education'], \n values = 'pcd')\n\nout = [out.droplevel(axis=1,level=n) \n for n in range(out.columns.nlevels)]\n\npd.concat(out, axis = 1).fillna(0, downcast='infer').reset_index()\n\n index age1to_20 Education_0 Education_2 Education_1 income_1 income_2 income_3\n0 1 1 A5009 0 0 A5009 0 0\n1 2 1 0 A3450 0 0 A3450 0\n2 3 1 A5009 0 0 A5009 0 0\n3 4 0 0 0 A3450 0 0 A3450\n" }, { "answer_id": 74377070, "author": "Gonçalo Peres", "author_id": 7109869, "author_profile": "https://Stackoverflow.com/users/7109869", "pm_score": 0, "selected": false, "text": "pandas.get_dummies" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13106084/" ]
74,372,880
<p>I have these values in dataset in a pandas dataframe column</p> <pre><code>col1 0.74 0.77 0.72 0.65 0.24 0.07 0.21 0.05 0.09 </code></pre> <p>I want to get a new column of six elements as list in new columns as rows (by shifting one values at a time in list)</p> <p>This is the col that I want to get.</p> <pre><code>col2 [0.74,0.77,0.72,0.65,0.24,0.07] [0.77,0.72,0.65,0.24,0.07,0.21] [0.72,0.65,0.24,0.07,0.21,0.05] [0.65,0.24,0.07,0.21,0.05,0.09] [0.24,0.07,0.21,0.05,0.09,NaN] [0.07,0.21,0.05,0.09,NaN,NaN] </code></pre>
[ { "answer_id": 74372986, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "sliding_window_view" }, { "answer_id": 74373014, "author": "Piotr Żak", "author_id": 9455902, "author_profile": "https://Stackoverflow.com/users/9455902", "pm_score": 0, "selected": false, "text": "s = pd.Series([0.74,\n0.77,\n0.72,\n0.65,\n0.24,\n0.07,\n0.21,\n0.05,\n0.09])\n\n\narr = []\nindex = 6\nfor i in range(index):\n arr.append(s.values[i:index+i])\nprint (arr)\n" }, { "answer_id": 74373170, "author": "James Hinkley", "author_id": 11398693, "author_profile": "https://Stackoverflow.com/users/11398693", "pm_score": 2, "selected": false, "text": "import pandas as pd\nimport numpy as np\ndf = pd.DataFrame({'col1': [0.74,0.77,0.72,0.65,0.24,0.07,0.21,0.05,0.09]})\ndf[\"col2\"] = \"\"\nfor i in range(len(df)):\n lst = df[\"col1\"].iloc[i:i+6].to_list()\n length = len(lst)\n# Only if you need the list to be the same length\n while length<6:\n lst.append(np.nan)\n length +=1\n print(lst)\n df.at[i, 'col2'] = lst\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5506647/" ]
74,372,922
<p>Once I split the variable and assign it to proxyset. How do I travers proxyset array with for in. In the below example print var only return 1 2</p> <pre><code>PROXY_PASS_MAPPING=abc|123,xyz|456 awk -v rep=$PROXY_PASS_MAPPING ' BEGIN { split(rep,proxyset,&quot;,&quot;) print proxyset[1] for(var in proxyset ){ print var split(var,a,&quot;|&quot;) site[a[1]]=a[2] } print site[&quot;abc&quot;] } ' </code></pre>
[ { "answer_id": 74372986, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "sliding_window_view" }, { "answer_id": 74373014, "author": "Piotr Żak", "author_id": 9455902, "author_profile": "https://Stackoverflow.com/users/9455902", "pm_score": 0, "selected": false, "text": "s = pd.Series([0.74,\n0.77,\n0.72,\n0.65,\n0.24,\n0.07,\n0.21,\n0.05,\n0.09])\n\n\narr = []\nindex = 6\nfor i in range(index):\n arr.append(s.values[i:index+i])\nprint (arr)\n" }, { "answer_id": 74373170, "author": "James Hinkley", "author_id": 11398693, "author_profile": "https://Stackoverflow.com/users/11398693", "pm_score": 2, "selected": false, "text": "import pandas as pd\nimport numpy as np\ndf = pd.DataFrame({'col1': [0.74,0.77,0.72,0.65,0.24,0.07,0.21,0.05,0.09]})\ndf[\"col2\"] = \"\"\nfor i in range(len(df)):\n lst = df[\"col1\"].iloc[i:i+6].to_list()\n length = len(lst)\n# Only if you need the list to be the same length\n while length<6:\n lst.append(np.nan)\n length +=1\n print(lst)\n df.at[i, 'col2'] = lst\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/584239/" ]
74,372,937
<p>I cannot stop the android system navigation bar (3 buttons at the bottom) from appearing when interacting with objects such as a Picker or Popup (from community toolkit). We're planning on running this app on a device that has Kiosk mode enabled, hence why we want to remove the system navigation bars.</p> <pre><code> var pwdPopup = new SettingsPwdPopup(); // Creates popup and waits for popup to finish object? pwd = await this.ShowPopupAsync(pwdPopup).ConfigureAwait(false); return pwd?.ToString(); </code></pre> <p>However, I am attempting to run this app in Kiosk mode and removing the status bar AND navigation bar. I've managed to stop the status bar from appearing but the navigation bar I've had no luck with. This is with the intent of hiding the system navigation bar</p> <p>I've attempted the following:</p> <ul> <li>Using <code>Shell.Current.GoToAsync();</code> instead of navigation stack</li> <li>Setting the Flags &amp; SystemUiVisibility as shown below (1)</li> <li>Adding <code>NavigationPage.HasNavigationBar=&quot;False&quot;</code> (when I was using NavigationPages)</li> <li>In the AppShell.xaml setting the <code>&lt;Shell ... Shell.NavBarVisible=&quot;False&quot;&gt;</code></li> <li>In the AppShell.xaml setting adding the following below (2)</li> </ul> <p>(1):</p> <pre><code> Window.SetFlags(WindowManagerFlags.Fullscreen, WindowManagerFlags.Fullscreen); Window.SetFlags(WindowManagerFlags.LayoutInScreen, WindowManagerFlags.LayoutInScreen); this.Window.DecorView.SystemUiVisibility = (StatusBarVisibility) (SystemUiFlags.ImmersiveSticky | SystemUiFlags.HideNavigation | SystemUiFlags.Fullscreen | SystemUiFlags.Immersive | SystemUiFlags.LayoutHideNavigation | SystemUiFlags.LayoutStable | SystemUiFlags.LowProfile); </code></pre> <p>(2):</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt; &lt;Shell ... Shell.NavBarIsVisible=&quot;False&quot;&gt; &lt;Shell.BackButtonBehavior&gt; &lt;BackButtonBehavior IsVisible=&quot;False&quot; IsEnabled=&quot;False&quot;/&gt; &lt;/Shell.BackButtonBehavior&gt; &lt;ShellContent ... /&gt; &lt;/Shell&gt; </code></pre> <p>Also tried:</p> <pre><code> WindowCompat.SetDecorFitsSystemWindows(Window, false); WindowInsetsControllerCompat windowInsetsControllerCompat = ViewCompat.GetWindowInsetsController(Window.DecorView); windowInsetsControllerCompat.Hide(WindowInsetsCompat.Type.SystemBars() | WindowInsetsCompat.Type.NavigationBars()); windowInsetsControllerCompat.SystemBarsBehavior = WindowInsetsControllerCompat.BehaviorShowBarsBySwipe; </code></pre> <p>However, with Android API 31, I've had no luck.</p> <p>I'll also add the versions of stuff that I am currently using here:</p> <p>Versions:</p> <ul> <li>Android API 31</li> <li>.NET MAUI 6.0.541</li> <li>CommunityToolkit.Maui 1.2.0</li> </ul>
[ { "answer_id": 74372986, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "sliding_window_view" }, { "answer_id": 74373014, "author": "Piotr Żak", "author_id": 9455902, "author_profile": "https://Stackoverflow.com/users/9455902", "pm_score": 0, "selected": false, "text": "s = pd.Series([0.74,\n0.77,\n0.72,\n0.65,\n0.24,\n0.07,\n0.21,\n0.05,\n0.09])\n\n\narr = []\nindex = 6\nfor i in range(index):\n arr.append(s.values[i:index+i])\nprint (arr)\n" }, { "answer_id": 74373170, "author": "James Hinkley", "author_id": 11398693, "author_profile": "https://Stackoverflow.com/users/11398693", "pm_score": 2, "selected": false, "text": "import pandas as pd\nimport numpy as np\ndf = pd.DataFrame({'col1': [0.74,0.77,0.72,0.65,0.24,0.07,0.21,0.05,0.09]})\ndf[\"col2\"] = \"\"\nfor i in range(len(df)):\n lst = df[\"col1\"].iloc[i:i+6].to_list()\n length = len(lst)\n# Only if you need the list to be the same length\n while length<6:\n lst.append(np.nan)\n length +=1\n print(lst)\n df.at[i, 'col2'] = lst\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20171074/" ]
74,372,960
<p>I'm creating a multipage quizz, so I need the user not to be able to go back to the previous page. So I wrote:</p> <pre class="lang-js prettyprint-override"><code>const router = createRouter({ history: createMemoryHistory(), routes }); </code></pre> <p>It's working (navigation is disabled), but it the user hits back a few times, it ends up leaving the page without warning.</p> <p>Is there a way to add a warning for the user?</p> <p>Thanks in advance</p> <p>Regards</p>
[ { "answer_id": 74373366, "author": "Ninowis", "author_id": 3245139, "author_profile": "https://Stackoverflow.com/users/3245139", "pm_score": 1, "selected": false, "text": "router.beforeEach((to, from) => {\n const route = this.$router.resolve(to)\n\n if (route.resolved.matched.length) {\n // the route exists, return true to proceed with the navigation\n return true\n }else{\n //the route does not exists, prompt for confirmation\n return confirm(\"Are you sure you want to leave this site?\")\n }\n})\n\n" }, { "answer_id": 74373540, "author": "greg", "author_id": 422331, "author_profile": "https://Stackoverflow.com/users/422331", "pm_score": 0, "selected": false, "text": "window.addEventListener('beforeunload', function (e) {\n e.preventDefault();\n e.returnValue = '';\n});\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/422331/" ]
74,372,992
<p>I have a player in unity with the movement controlled by a rigidbody. The movement on the Z axis is kept contstant by the game to keep the player moving forward. However, this means that the rigidbody keeps speeding up so its speed at the start of the game is much slower than the speed at the end of the game. Here is my script:</p> <pre><code>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.InputSystem; using UnityEngine.SceneManagement; public class Controller : MonoBehaviour { [Tooltip(&quot;Rigidbody component attached to the player&quot;)] public Rigidbody rb; public float forwardMax; public float slowBy; private float movementX; private float movementY; private float gravity = -9.81f; private bool isJumping = false; private bool isSlowing = false; private bool isSpeeding = false; private float speedX = 100; private float speedY = 150000; private float speedZ = 60; // Start is called before the first frame update void Start() { rb = GetComponent&lt;Rigidbody&gt;(); } void Update() { // if(!controller.isGrounded) // { // Vector3 gravityVector = new Vector3(0.0f, gravity, 0.0f); // rb.AddForce(gravityVector * Time.deltaTime); // } } void OnCollisionEnter(Collision collision) { // SceneManager.LoadScene(1); } // Update is called once per frame void OnMove(InputValue movementValue) { Vector2 movementVector = movementValue.Get&lt;Vector2&gt;(); movementX = movementVector.x; movementY = movementVector.y; } void OnJump() { isJumping = true; } void CalculateMovement() { if(rb.velocity.z &gt; 20) { rb.drag = 20; } else { rb.drag = 0; } Vector3 movement = new Vector3(movementX * speedX, 0.0f, speedZ); if(isJumping) { movement.y += Mathf.Sqrt(speedY * -3.0f * gravity); isJumping = false; } rb.AddForce(movement); Debug.Log(&quot;Speed is &quot; + rb.velocity.z); } void FixedUpdate() { CalculateMovement(); } } </code></pre> <p>Is there a way to keep the forward velocity constant? The problem is worse when the player jumps.</p> <p>First I tried clamping the forward (z-axis) vector but that had no effect. Then, I tried adding a backward vector onto the total when the forward velocity was above a certain number but this led to it speeding up and slowing down all the time. Then I tried the same thing with the <code>drag</code> on the <code>rigidbody</code> but that had the same effect.</p>
[ { "answer_id": 74385916, "author": "Willard Peng", "author_id": 10259001, "author_profile": "https://Stackoverflow.com/users/10259001", "pm_score": 1, "selected": true, "text": "......\n\nvoid FixedUpdate()\n{\n CalculateMovementWithoutZMovement();\n rb.velocity = new Vector3 (rb.velocity.x, rb.velocity.y, ConstantZValue);\n}\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19445483/" ]
74,372,993
<p>I have a struct containing three numbers: number1, number2, number3. Then, I want to perform division operators on them: (number1)/(number2+number3).</p> <pre><code>typedef struct { int number1; int number2; int number3; double ratio; } table; </code></pre> <p>I tried to divide them like this:</p> <pre><code>for(int a = 0; a &lt; 5; a++) { for(int b = 0; b &lt; 3; b++) { table[a][b].ratio = ((table[a][b].number1)/(table[a][b].number2 + data[a][b].number3)); } } </code></pre> <p>Should I divide structures using a repeated subtraction of dividend and divisor till the dividend becomes less than the divisor? Or is there any other approaches? I need to get double values, for example:</p> <pre><code>table[0][0].number1 = 1; table[0][0].number2 = 2; table[0][0].num3 = 3; </code></pre> <p>Then,</p> <pre><code>table[0][0].ration = 1/5=0.2 </code></pre>
[ { "answer_id": 74385916, "author": "Willard Peng", "author_id": 10259001, "author_profile": "https://Stackoverflow.com/users/10259001", "pm_score": 1, "selected": true, "text": "......\n\nvoid FixedUpdate()\n{\n CalculateMovementWithoutZMovement();\n rb.velocity = new Vector3 (rb.velocity.x, rb.velocity.y, ConstantZValue);\n}\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74372993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20457970/" ]
74,373,058
<p>I have come across some nasty dependencies.</p> <p>Looking around I found solutions like upgrade this, downgrade that...</p> <p>Some solutions work for some but not for others.</p> <p>Is there a more 'rounded' way to tackle this issue?</p>
[ { "answer_id": 74385916, "author": "Willard Peng", "author_id": 10259001, "author_profile": "https://Stackoverflow.com/users/10259001", "pm_score": 1, "selected": true, "text": "......\n\nvoid FixedUpdate()\n{\n CalculateMovementWithoutZMovement();\n rb.velocity = new Vector3 (rb.velocity.x, rb.velocity.y, ConstantZValue);\n}\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4752223/" ]
74,373,073
<p>Problem: i cant find the minimum, it's always zero! why? how should i fix the code?</p> <p>** now it's done.</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main(){ // input n numbers &amp; show max &amp; min int n, x, max = x, min = x; cin&gt;&gt;n; for(int i = 1; i &lt;= n; i++){ cin&gt;&gt;x; if (x&gt;max){ max = x; }else if (x&lt;min){ min = x; } } cout&lt;&lt;&quot;max: &quot;&lt;&lt;max&lt;&lt;endl&lt;&lt;&quot;min: &quot;&lt;&lt;min; return 0; } </code></pre> <p>I try to give n inputs and find the maximum &amp; minimum between them with my codes.</p>
[ { "answer_id": 74385916, "author": "Willard Peng", "author_id": 10259001, "author_profile": "https://Stackoverflow.com/users/10259001", "pm_score": 1, "selected": true, "text": "......\n\nvoid FixedUpdate()\n{\n CalculateMovementWithoutZMovement();\n rb.velocity = new Vector3 (rb.velocity.x, rb.velocity.y, ConstantZValue);\n}\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20457869/" ]
74,373,096
<p>I want to insert multiple rows from one column.</p> <p>For my POS system like this.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Item Code</th> <th>Total Qty</th> <th>Qty of Pallets</th> <th>Quantity Of A PalleT/Per Box</th> <th>Date</th> </tr> </thead> <tbody> <tr> <td>00001</td> <td>Item 1</td> <td>384</td> <td>4</td> <td>96</td> <td>12/07/2014</td> </tr> </tbody> </table> </div> <p>After that I want to see this in my table for each pallet</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Item Code</th> <th>Qty in Box</th> <th>Date</th> </tr> </thead> <tbody> <tr> <td>00001</td> <td>Item 1</td> <td>96</td> <td>12/07/2014</td> </tr> <tr> <td>00001</td> <td>Item 1</td> <td>96</td> <td>12/07/2014</td> </tr> <tr> <td>00001</td> <td>Item 1</td> <td>96</td> <td>12/07/2014</td> </tr> <tr> <td>00001</td> <td>Item 1</td> <td>96</td> <td>12/07/2014</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74385916, "author": "Willard Peng", "author_id": 10259001, "author_profile": "https://Stackoverflow.com/users/10259001", "pm_score": 1, "selected": true, "text": "......\n\nvoid FixedUpdate()\n{\n CalculateMovementWithoutZMovement();\n rb.velocity = new Vector3 (rb.velocity.x, rb.velocity.y, ConstantZValue);\n}\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20261200/" ]
74,373,103
<p>how is it possible for me to count the word &quot;OFFLINE&quot; in the Following List with Python? The List is in a .txt File so i need to open that first i guess and then look after the specific word.</p> <p><code>MPP MPP Fault MPP Fault MPP MPP MPP MPP MPP MPP MPP MPP MPP MPP MPP MPP MPP MPP MPP MPP MPP MPP MPP MPP OFFLINE OFFLINE OFFLINE OFFLINE OFFLINE OFFLINE OFFLINE OFFLINE OFFLINE OFFLINE OFFLINE OFFLINE OFFLINE OFFLINE</code></p> <p>The values as under each another.</p> <p>I already tried this:</p> <pre><code> def word_count(str): counts = dict() words = str.split() for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 return counts print( word_count(open(info).read())) </code></pre>
[ { "answer_id": 74385916, "author": "Willard Peng", "author_id": 10259001, "author_profile": "https://Stackoverflow.com/users/10259001", "pm_score": 1, "selected": true, "text": "......\n\nvoid FixedUpdate()\n{\n CalculateMovementWithoutZMovement();\n rb.velocity = new Vector3 (rb.velocity.x, rb.velocity.y, ConstantZValue);\n}\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20229777/" ]
74,373,109
<p>I have two tables, and I want to use a value from primary table (here: <code>person.ref</code>) to extract some data from a <code>json</code> field in a secondary table (here: <code>person_details</code>):</p> <pre><code>create table person ( id int(8), ref varchar(20), primary key (id) ); create table person_details ( id int(8), details json, primary key (id) ); SELECT JSON_EXTRACT(details, CONCAT('$.', p.ref)) FROM person p JOIN person_details d using (id); </code></pre> <p>The person_details data is like:</p> <pre><code>{ &quot;ref1&quot;: { ... } } </code></pre> <p>But that does not matter, because the sql statement itself seems to be invalid:</p> <p>Result:</p> <pre><code>#3143 - Invalid JSON path expression. The error is around character position 12. </code></pre> <p>Why?</p>
[ { "answer_id": 74373827, "author": "Valeriu Ciuca", "author_id": 4527645, "author_profile": "https://Stackoverflow.com/users/4527645", "pm_score": 2, "selected": false, "text": "CREATE TABLE `person` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `ref` varchar(255) DEFAULT NULL,\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8;\n\nCREATE TABLE `person_details` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `details` json,\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8;\n\nINSERT INTO `person` (`id`, `ref`) VALUES (1, 'ref1');\nINSERT INTO `person` (`id`, `ref`) VALUES (2, 'ref1');\nINSERT INTO `person_details` (`id`, `details`) VALUES (1, '{\"ref1\": {\"name\": \"Barney\"}}');\nINSERT INTO `person_details` (`id`, `details`) VALUES (2, '{\"ref1\": {\"name\": \"Willma\"}}');\n\nSELECT JSON_EXTRACT(details, CONCAT('$.', p.ref))\nFROM person p\nJOIN person_details d using (id);\n" }, { "answer_id": 74375147, "author": "membersound", "author_id": 1194415, "author_profile": "https://Stackoverflow.com/users/1194415", "pm_score": 0, "selected": false, "text": "p.ref" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1194415/" ]
74,373,166
<p>What is the best way to convert a string to dictionary with value of dictionary as a list</p> <p>for example <code>str = &quot;abc=1,abc=2,abc=3,xyz=5,xyz=6&quot;</code> i need the output as: <code>d = {&quot;abc&quot;:[&quot;1&quot;,&quot;2&quot;,&quot;3&quot;],&quot;xyz&quot;:[&quot;5&quot;,&quot;6&quot;]}</code></p> <p>I'm very new to python.</p> <p>my code: <code>d = {k: [v] for k, v in map(lambda item: item.split('='), s.split(&quot;,&quot;))}</code></p>
[ { "answer_id": 74373253, "author": "Abdul Niyas P M", "author_id": 6699447, "author_profile": "https://Stackoverflow.com/users/6699447", "pm_score": 3, "selected": true, "text": "dict.setdefault" }, { "answer_id": 74373304, "author": "Vin", "author_id": 7955271, "author_profile": "https://Stackoverflow.com/users/7955271", "pm_score": 0, "selected": false, "text": "s1 = \"abc=1,abc=2,abc=3,xyz=5,xyz=6\"\nlist1 = [(each.split('=')) for each in s1.split(',')]\nd = {}\nfor key, val in list1:\n if key in d.keys():\n d[key].append(val)\n else:\n d[key] = [val]\nprint (d)\n#result: {'abc': ['1', '2', '3'], 'xyz': ['5', '6']}\n" }, { "answer_id": 74373548, "author": "koding_buse", "author_id": 20166777, "author_profile": "https://Stackoverflow.com/users/20166777", "pm_score": 0, "selected": false, "text": "# initialize a dictionary\nd = {}\n# split the string (my_str) according to \",\" in order to get pairs such as 'abc/1' and 'xyz/5' in a list\nfor elt in my_str.split(\",\") : \n# for each string of the list, split according to '/' to get the pairs ['abc', 1]\n# complete the dictionary \n if elt.split('/')[0] not in d.keys():\n d[elt.split('/')[0]] = [elt.split('/')[1]]\n else : \n d[elt.split('/')[0]].append(elt.split('/')[1])\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20035511/" ]
74,373,181
<p>I try to change one value inside the list but all values change for all keys.</p> <pre><code>vertex_list = ['a','b'] distance_dict = dict.fromkeys(vertex_list, [10, 'None']) distance_dict['a'][0] = 1 print(distance_dict) </code></pre> <p>output:</p> <pre><code>{'a': [1, 'None'], 'b': [1, 'None']} </code></pre> <p>when I built the dictionary with traditional { } it works fine. I guess the problem is for the list inside <strong>dict.fromkeys</strong>, which creates one list for all dictionary keys. is there a solution to fix it. without using ''for'' and { } to build the dictionary?</p>
[ { "answer_id": 74373532, "author": "Abdul Niyas P M", "author_id": 6699447, "author_profile": "https://Stackoverflow.com/users/6699447", "pm_score": 2, "selected": false, "text": "fromkeys()" }, { "answer_id": 74373559, "author": "Will", "author_id": 12829151, "author_profile": "https://Stackoverflow.com/users/12829151", "pm_score": 0, "selected": false, "text": "vertex_list = ['a','b']\ndistance_dict = {x: [10, 'None'] for x in vertex_list}\ndistance_dict['a'][0] = 1\nprint(distance_dict)\n" }, { "answer_id": 74373849, "author": "Я T", "author_id": 18790524, "author_profile": "https://Stackoverflow.com/users/18790524", "pm_score": 1, "selected": false, "text": "dict.fromkeys" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19776016/" ]
74,373,184
<p>A dataframe I am working on contains an address line, from which I wish to extract the different variables (street name, number, postal code and country). The address line is filled according to the following template: <strong>&quot;street number, postal code city, country&quot;</strong>.</p> <p>Using .str.split(), I can get invividual elements from the string. Returning multiple elements however does not work.</p> <p>So, extracting the country is easy enough. But when I try to get the street and number I run into some troubles. The street can contain one or more whitespaces, but after the last whitespace there is always the number. So I try to do this:</p> <pre><code>df[&quot;street_and_number&quot;]=df[&quot;address&quot;].str.split(&quot;,&quot;).str[0] </code></pre> <p>which creates a column with the street <em>and</em> the number. So far so good.</p> <p>If I want to get the street, splitting on whitespaces and extracting everything but the last element seems (to me) a pretty straightforward option:</p> <pre><code>df[&quot;street&quot;]=df[&quot;street_and_number&quot;].str.split().str[:-1] </code></pre> <p>But this returns a list, see example below:</p> <pre><code>1541 [Burgemeester, Roelenweg] Name: straat_en_nr, dtype: object </code></pre> <p>I would like to get a string, instead of a list with all the elements. Using the expand option doesn't produce the required result either:</p> <pre><code>df[&quot;street&quot;]=df[&quot;street_and_number&quot;].str.split(expand=True)[:-1] </code></pre> <p>Output:</p> <pre><code> 0 1 2 </code></pre> <p>What am I doing wrong?</p>
[ { "answer_id": 74373532, "author": "Abdul Niyas P M", "author_id": 6699447, "author_profile": "https://Stackoverflow.com/users/6699447", "pm_score": 2, "selected": false, "text": "fromkeys()" }, { "answer_id": 74373559, "author": "Will", "author_id": 12829151, "author_profile": "https://Stackoverflow.com/users/12829151", "pm_score": 0, "selected": false, "text": "vertex_list = ['a','b']\ndistance_dict = {x: [10, 'None'] for x in vertex_list}\ndistance_dict['a'][0] = 1\nprint(distance_dict)\n" }, { "answer_id": 74373849, "author": "Я T", "author_id": 18790524, "author_profile": "https://Stackoverflow.com/users/18790524", "pm_score": 1, "selected": false, "text": "dict.fromkeys" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20457603/" ]
74,373,192
<p>I have three <code>views</code> A,B and C. User can navigate from A to B and from A to C. User can navigate from B to C. Now I want to differentiate if the user have come from A to C or from B to C so I was looking in how to pass extra data in NavigationStack which can help me differentiate</p> <p>Below is my code</p> <pre><code>import SwiftUI @main struct SampleApp: App { @State private var path: NavigationPath = .init() var body: some Scene { WindowGroup { NavigationStack(path: $path){ A(path: $path) .navigationDestination(for: ViewOptions.self) { option in option.view($path) } } } } enum ViewOptions { case caseB case caseC @ViewBuilder func view(_ path: Binding&lt;NavigationPath&gt;) -&gt; some View{ switch self{ case .caseB: B(path: path) case .caseC: C(path: path) } } } } struct A: View { @Binding var path: NavigationPath var body: some View { VStack { Text(&quot;A&quot;) Button { path.append(SampleApp.ViewOptions.caseB) } label: { Text(&quot;Go to B&quot;) } Button { path.append(SampleApp.ViewOptions.caseC) } label: { Text(&quot;Go to C&quot;) } } } } struct B: View { @Binding var path: NavigationPath var body: some View { VStack { Text(&quot;B&quot;) Button { path.append(SampleApp.ViewOptions.caseC) } label: { Text(&quot;Go to C&quot;) } } } } struct C: View { @Binding var path: NavigationPath var body: some View { VStack { Text(&quot;C&quot;) } } } </code></pre>
[ { "answer_id": 74373532, "author": "Abdul Niyas P M", "author_id": 6699447, "author_profile": "https://Stackoverflow.com/users/6699447", "pm_score": 2, "selected": false, "text": "fromkeys()" }, { "answer_id": 74373559, "author": "Will", "author_id": 12829151, "author_profile": "https://Stackoverflow.com/users/12829151", "pm_score": 0, "selected": false, "text": "vertex_list = ['a','b']\ndistance_dict = {x: [10, 'None'] for x in vertex_list}\ndistance_dict['a'][0] = 1\nprint(distance_dict)\n" }, { "answer_id": 74373849, "author": "Я T", "author_id": 18790524, "author_profile": "https://Stackoverflow.com/users/18790524", "pm_score": 1, "selected": false, "text": "dict.fromkeys" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9552485/" ]
74,373,193
<p>I have a text file that I need to read and perform an FFT onto.</p> <p>Basically, the file reads something like this:</p> <pre><code>1458 1499 1232 1232 1888 ... 2022-09-11 09:32:51.076 1459 1323 1999 1323 1823 ... 2022-09-11 09:32:51.199 </code></pre> <p>and so on. Each row has 200 columns, and I want to basically read each row, up to each column while ignoring the last column that has the time.</p> <p>So far I've tried this:</p> <pre class="lang-py prettyprint-override"><code>with open('file') as f: w, h = [int(x) for x in next(f).split()] # read first line array = [] for line in f: # read rest of lines array.append([int(x) for x in line.split()]) </code></pre> <p>But I don't know how to remove the last characters.</p> <p>Thank you</p>
[ { "answer_id": 74373322, "author": "StephanT", "author_id": 10895042, "author_profile": "https://Stackoverflow.com/users/10895042", "pm_score": 1, "selected": false, "text": "a = [1,2,3]\nb = a[:-1]\nprint b\n" }, { "answer_id": 74373427, "author": "Prakash Dahal", "author_id": 13573168, "author_profile": "https://Stackoverflow.com/users/13573168", "pm_score": 3, "selected": false, "text": "array = []\nwith open('file.txt','r') as tf:\n for lines in tf.readlines():\n array.append(' '.join(lines.split()[:-2]))\n\nprint(array)\n" }, { "answer_id": 74373436, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 3, "selected": false, "text": "with open('file') as f:\n w, h = [int(x) for x in next(f).split()] # read first line\n array = []\n for line in f: # read rest of lines\n array.append([int(x) for x in line.split()[:-2])\n" }, { "answer_id": 74373466, "author": "pyrifo", "author_id": 12926588, "author_profile": "https://Stackoverflow.com/users/12926588", "pm_score": 1, "selected": false, "text": "array = []\nwith open('file.txt') as f:\n for line in f:\n w = [x for x in line.split()] # read first line\n array.append(w[:-1])\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12005115/" ]
74,373,194
<p><a href="https://i.stack.imgur.com/1VdJr.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1VdJr.jpg" alt="Date Fromat" /></a></p> <p>Edited: Want to convert the format.</p> <p>I am kinda new in BigQuery, recently I was working on a project. I want to convert above type of format into yyyy/mm/dd format. How will I do that?</p>
[ { "answer_id": 74373712, "author": "itroulli", "author_id": 7903159, "author_profile": "https://Stackoverflow.com/users/7903159", "pm_score": 2, "selected": true, "text": "SELECT FORMAT_DATE(\"%Y/%m/%d\",PARSE_DATE(\"%B %d, %Y\",\"June 10, 2014\")) AS date_str\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20436654/" ]
74,373,230
<p>If I write a long sentence the text doesn't fit the container. Why does the text overflow the container?</p> <p>But when I write a long sentence but use spaces (write more than 1 sentence), the text finally fits the container.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;p&gt;no spaces:&lt;/p&gt; &lt;div style="height:50px;width: 200px;border: 4px solid red;"&gt;helloooooooooooooooooooooooooooooooo&lt;/div&gt; &lt;br&gt; &lt;p&gt;with spaces:&lt;/p&gt; &lt;div style="height:50px;width: 200px;border: 4px solid red; "&gt;hello ooooooo ooooo ooooooo ooooooooo oooooooo&lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74373339, "author": "Matteo Maestri", "author_id": 20262119, "author_profile": "https://Stackoverflow.com/users/20262119", "pm_score": 2, "selected": true, "text": "overflow-wrap: break-word;" }, { "answer_id": 74373391, "author": "florballa", "author_id": 14960732, "author_profile": "https://Stackoverflow.com/users/14960732", "pm_score": 0, "selected": false, "text": "<p>no spaces:</p>\n<div style=\"height:50px;width: 200px;border: 4px solid red; word-wrap: break-word;\">helloooooooooooooooooooooooooooooooo</div>\n<br>\n<p>with spaces:</p>\n<div style=\"height:50px;width: 200px;border: 4px solid red; \">hello ooooooo ooooo ooooooo ooooooooo oooooooo</div>" }, { "answer_id": 74373418, "author": "tacoshy", "author_id": 14072420, "author_profile": "https://Stackoverflow.com/users/14072420", "pm_score": 0, "selected": false, "text": "word-break: normal" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19811641/" ]
74,373,234
<p>I have the following input</p> <blockquote> </blockquote> <pre><code>[ { &quot;id&quot;: &quot;abc&quot;, &quot;data1&quot;: 3, &quot;data2&quot;: &quot;test1&quot;, }, { &quot;id&quot;: &quot;abc&quot;, &quot;data1&quot;: 4, &quot;data2&quot;: &quot;test1&quot;, }, { &quot;id&quot;: &quot;xyz&quot;, &quot;data1&quot;: 2, &quot;data2&quot;: &quot;test2&quot;, } ] </code></pre> <p>I would like to parse this list, convert the data1 to list and add all the data1 with similar id into it like the following to create new list.</p> <blockquote> </blockquote> <pre><code>[ { &quot;id&quot;: &quot;abc&quot;, &quot;data1&quot;: [3,4], &quot;data2&quot;: &quot;test1&quot;, }, { &quot;id&quot;: &quot;abc&quot;, &quot;data1&quot;: [2], &quot;data2&quot;: &quot;test2&quot;, } ] </code></pre> <p>I have tried a few ways like using map/reduce but none of my solution worked.</p>
[ { "answer_id": 74373339, "author": "Matteo Maestri", "author_id": 20262119, "author_profile": "https://Stackoverflow.com/users/20262119", "pm_score": 2, "selected": true, "text": "overflow-wrap: break-word;" }, { "answer_id": 74373391, "author": "florballa", "author_id": 14960732, "author_profile": "https://Stackoverflow.com/users/14960732", "pm_score": 0, "selected": false, "text": "<p>no spaces:</p>\n<div style=\"height:50px;width: 200px;border: 4px solid red; word-wrap: break-word;\">helloooooooooooooooooooooooooooooooo</div>\n<br>\n<p>with spaces:</p>\n<div style=\"height:50px;width: 200px;border: 4px solid red; \">hello ooooooo ooooo ooooooo ooooooooo oooooooo</div>" }, { "answer_id": 74373418, "author": "tacoshy", "author_id": 14072420, "author_profile": "https://Stackoverflow.com/users/14072420", "pm_score": 0, "selected": false, "text": "word-break: normal" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15995650/" ]
74,373,237
<p>I need to extract all the lines from file2.txt that do not match the string until the first dot in any line in file1.txt. I am interested in a solution that stays as close to my current approach as possible so it is easy for me to understand, and uses only sed and/or awk in linux bash.</p> <p>file1.h</p> <pre><code>apple.sweet banana apple.tasty banana apple.brown banana orange_mvp.rainy day.here orange_mvp.ear nose.png lemon_mvp.ear ring tarte_mvp_rainy day.here </code></pre> <p>file2.h</p> <pre><code>orange_mvp lemon_mvp lemon_mvp tarte_mvp cake_mvp </code></pre> <p>result desired</p> <pre><code>tarte_mvp cake_mvp </code></pre> <p>current wrong approach</p> <pre><code>$ awk ' NR==FNR { sub(/mvp(\..*)$/,&quot;&quot;); a[$0]; next } { f=$0; sub(/mvp(\..*)$/,&quot;&quot;, f) } !(f in a) ' file2.h file1.h apple.sweet banana apple.tasty banana apple.brown banana orange_mvp.rainy day.here orange_mvp.ear nose.png lemon_mvp.ear ring tarte_mvp_rainy day.here </code></pre>
[ { "answer_id": 74373339, "author": "Matteo Maestri", "author_id": 20262119, "author_profile": "https://Stackoverflow.com/users/20262119", "pm_score": 2, "selected": true, "text": "overflow-wrap: break-word;" }, { "answer_id": 74373391, "author": "florballa", "author_id": 14960732, "author_profile": "https://Stackoverflow.com/users/14960732", "pm_score": 0, "selected": false, "text": "<p>no spaces:</p>\n<div style=\"height:50px;width: 200px;border: 4px solid red; word-wrap: break-word;\">helloooooooooooooooooooooooooooooooo</div>\n<br>\n<p>with spaces:</p>\n<div style=\"height:50px;width: 200px;border: 4px solid red; \">hello ooooooo ooooo ooooooo ooooooooo oooooooo</div>" }, { "answer_id": 74373418, "author": "tacoshy", "author_id": 14072420, "author_profile": "https://Stackoverflow.com/users/14072420", "pm_score": 0, "selected": false, "text": "word-break: normal" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19017877/" ]
74,373,282
<p>Assume <code>data.php</code> has three variables like below:</p> <pre><code>$first = 1; $second = 1; $third = 1; </code></pre> <p>My question is how to get the <code>1</code> from <code>$second</code> and change it to <code>3</code>? So it becomes:</p> <pre><code>$first = 1; $second = 3; $third = 1; </code></pre> <p>I'm trying to do this from another file, let's say <code>index.php</code>. I have refer to the below answer but I don't know what should I put in the <code>find</code> of the method below? ( The below code is from <code>index.php</code> )</p> <p><code>file_put_contents ( $file, str_replace( 'find', 3, file_get_contents ( $file ) ) );</code></p> <p>( <a href="https://stackoverflow.com/a/3575012/20454874">https://stackoverflow.com/a/3575012/20454874</a> )</p> <p><code>str_replace('$second = 1;', '$second = 3')</code> only works for the first time. Because the value to search for is different already after the first time.</p> <p>The reason behind it is that I have an HTML input and I want to save the value into the file <code>data.php</code>, that's why the <code>find</code> ( the first parameter <code>search</code> ) is dynamic.</p>
[ { "answer_id": 74373339, "author": "Matteo Maestri", "author_id": 20262119, "author_profile": "https://Stackoverflow.com/users/20262119", "pm_score": 2, "selected": true, "text": "overflow-wrap: break-word;" }, { "answer_id": 74373391, "author": "florballa", "author_id": 14960732, "author_profile": "https://Stackoverflow.com/users/14960732", "pm_score": 0, "selected": false, "text": "<p>no spaces:</p>\n<div style=\"height:50px;width: 200px;border: 4px solid red; word-wrap: break-word;\">helloooooooooooooooooooooooooooooooo</div>\n<br>\n<p>with spaces:</p>\n<div style=\"height:50px;width: 200px;border: 4px solid red; \">hello ooooooo ooooo ooooooo ooooooooo oooooooo</div>" }, { "answer_id": 74373418, "author": "tacoshy", "author_id": 14072420, "author_profile": "https://Stackoverflow.com/users/14072420", "pm_score": 0, "selected": false, "text": "word-break: normal" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20454874/" ]
74,373,342
<p>I have a <code>data.frame</code> similar to this:</p> <pre><code>mydf=data.frame(LETTERS=LETTERS, rev_letters=rev(letters), var1=c(rep('a',10),rep('b',10),rep('c',6)), value=1:26) &gt; head(mydf) LETTERS rev_letters var1 value 1 A z a 1 2 B y a 2 3 C x a 3 4 D w a 4 5 E v a 5 6 F u a 6 </code></pre> <p>I want to select the row indexes that correspond to the columns and values stored in a list, like this one:</p> <pre><code>mylist=list(LETTERS=c('A','M','X'), var1='b') &gt; mylist $LETTERS [1] &quot;A&quot; &quot;M&quot; &quot;X&quot; $var1 [1] &quot;b&quot; </code></pre> <p>I would like to do something like the following, but for all columns and values at once:</p> <pre><code>&gt; which(mydf[,names(mylist)[1]] %in% mylist[[1]]) [1] 1 13 24 </code></pre> <p>... or even better as a TRUE/FALSE variable:</p> <pre><code>&gt; mydf[,names(mylist)[1]] %in% mylist[[1]] [1] TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE [13] TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE [25] FALSE FALSE </code></pre> <p>The idea is to end up with a single variable of all the indexes for all the columns and values in the list; in the example above, the result would be:</p> <pre><code>&gt; indexes [1] 1 11 12 13 14 15 16 17 18 19 20 24 </code></pre> <p>... or the TRUE/FALSE counterpart:</p> <pre><code>&gt; indexes [1] TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE [13] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE FALSE FALSE TRUE [25] FALSE FALSE </code></pre> <p>Thanks!</p>
[ { "answer_id": 74373339, "author": "Matteo Maestri", "author_id": 20262119, "author_profile": "https://Stackoverflow.com/users/20262119", "pm_score": 2, "selected": true, "text": "overflow-wrap: break-word;" }, { "answer_id": 74373391, "author": "florballa", "author_id": 14960732, "author_profile": "https://Stackoverflow.com/users/14960732", "pm_score": 0, "selected": false, "text": "<p>no spaces:</p>\n<div style=\"height:50px;width: 200px;border: 4px solid red; word-wrap: break-word;\">helloooooooooooooooooooooooooooooooo</div>\n<br>\n<p>with spaces:</p>\n<div style=\"height:50px;width: 200px;border: 4px solid red; \">hello ooooooo ooooo ooooooo ooooooooo oooooooo</div>" }, { "answer_id": 74373418, "author": "tacoshy", "author_id": 14072420, "author_profile": "https://Stackoverflow.com/users/14072420", "pm_score": 0, "selected": false, "text": "word-break: normal" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2573168/" ]
74,373,355
<p>I Want To Prevent Oracle Database User To Write Operation On Specific Column ( Only Hibernate Connections Allowed To Write On That column) In Other Words If You Want To Change Specific Column Only Spring Transactions Allowed To Do That Not Database User</p> <p>update:<br /> I Dont Want A Database User Allowed To Write On Column Because In My App Every Thing Should Work Under System Transactions</p> <p>Exception : God Database User Is Ok :)</p>
[ { "answer_id": 74373643, "author": "Simon Martinelli", "author_id": 1045142, "author_profile": "https://Stackoverflow.com/users/1045142", "pm_score": 1, "selected": false, "text": "grant update (col1, col2) on mytab to fred;\n" }, { "answer_id": 74385297, "author": "Jon Heller", "author_id": 409172, "author_profile": "https://Stackoverflow.com/users/409172", "pm_score": 0, "selected": false, "text": "SQL> select sys_context('userenv', 'client_program_name') program from dual;\n\nPROGRAM\n-----------\nsqlplus.exe\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10147317/" ]
74,373,377
<pre><code>dic = {'A':'D','N':'Q','B':'E','O':'R','C':'F','P':'S','D':'G','Q':'T','E':'H','R':'U','F':'I','S':'V','G':'J','T':'W', 'H':'K','U':'X','I':'L','V':'Y','J':'M','W':'Z','K':'N','X':'A','L':'O','Y':'B','M':'P','Z':'C'} user_input = input(&quot;Enter the word: &quot;).upper() Key=str(user_input) print (dic.get(Key)) </code></pre> <p>This is my dictionary but the only answer I get is <code>None</code></p> <p>I tried to change the end to this but problem stayed :(</p> <pre><code>user_input = input(&quot;Enter the word: &quot;).upper() print (dic.get(user_input)) </code></pre> <p>does anyone know how to do it?</p>
[ { "answer_id": 74373676, "author": "AveragePythonEnjoyer", "author_id": 16293191, "author_profile": "https://Stackoverflow.com/users/16293191", "pm_score": 1, "selected": false, "text": "dict_a={'A':'D','N':'Q','B':'E','O':'R','C':'F','P':'S','D':'G','Q':'T','E':'H','R':'U','F':'I','S':'V','G':'J','T':'W',\n 'H':'K','U':'X','I':'L','V':'Y','J':'M','W':'Z','K':'N','X':'A','L':'O','Y':'B','M':'P','Z':'C'}\nuser_input =(input(\"Enter the word: \")).upper()\nkey=user_input\nprint(''.join([dict_a.get(k) for k in key]))\n" }, { "answer_id": 74373679, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "DEFG" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20458142/" ]
74,373,421
<p>I read this portion of the book on Async programming in Rust <a href="https://rust-lang.github.io/async-book/03_async_await/01_chapter.html" rel="nofollow noreferrer">https://rust-lang.github.io/async-book/03_async_await/01_chapter.html</a></p> <p>I see the mention of the <code>.await</code> syntax,</p> <p>and then I later saw a blog where <code>reqwest</code> is being used to fetch a url. The code looks like this:</p> <pre><code>let resp200 = client.get(&quot;https://httpbin.org/ip&quot;) .header(CONTENT_TYPE, &quot;application/json&quot;) .send() .await? .json::&lt;GETAPIResponse&gt;() .await?; </code></pre> <p>I do not understand the <code>.await?</code>. I know <code>?</code> is a shorthand for extracting the <code>Ok</code> case or returning from the function with an Error. But as far as I am aware, <code>.await</code> does not return <code>Result</code> so how is it possible to do <code>.await</code> with <code>?</code></p>
[ { "answer_id": 74373495, "author": "cameron1024", "author_id": 9186783, "author_profile": "https://Stackoverflow.com/users/9186783", "pm_score": 3, "selected": true, "text": ".await" }, { "answer_id": 74373512, "author": "Oussama Gammoudi", "author_id": 3978243, "author_profile": "https://Stackoverflow.com/users/3978243", "pm_score": 1, "selected": false, "text": "?" }, { "answer_id": 74373524, "author": "Michael Savchenko", "author_id": 6700017, "author_profile": "https://Stackoverflow.com/users/6700017", "pm_score": 1, "selected": false, "text": "await" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12303851/" ]
74,373,425
<p>I have 2 data frames with different lengths: len(df1) 10104 len(df2) 15560</p> <p>I want to merge these based on a common column (taskID) on both data frames. The Task ID has repeated IDs each ID represent an item belongs to the same task.</p> <p>example:</p> <p>df1:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>TaskID</th> <th>task duration</th> </tr> </thead> <tbody> <tr> <td>task 45</td> <td>2 mins</td> </tr> <tr> <td>task 45</td> <td>5 mins</td> </tr> <tr> <td>task 45</td> <td>7 mins</td> </tr> <tr> <td>task 67</td> <td>8 mins</td> </tr> <tr> <td>task 67</td> <td>9 mins</td> </tr> </tbody> </table> </div> <p>df2:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>TaskID</th> <th>gender</th> </tr> </thead> <tbody> <tr> <td>task 45</td> <td>male</td> </tr> <tr> <td>task 45</td> <td>male</td> </tr> <tr> <td>task 45</td> <td>male</td> </tr> <tr> <td>task 67</td> <td>female</td> </tr> <tr> <td>task 67</td> <td>female</td> </tr> </tbody> </table> </div> <p>when I use Pandas merge function I get an output with a length of 471437 which is greater than the length of both data frames.</p> <p>I think this is because of the repeated values of TaskID, and I can't remove the duplicates as each row represent different item.</p> <p>I tried:</p> <p>merged=pd.merge(df1,df2, on='TaskID', how='inner')</p> <p>I get an output with a length of 471437</p> <p>Can you please help with this issue ?</p>
[ { "answer_id": 74373470, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "groupby.cumcount" }, { "answer_id": 74376193, "author": "Azhar Khan", "author_id": 2847330, "author_profile": "https://Stackoverflow.com/users/2847330", "pm_score": 0, "selected": false, "text": "df1 = pd.DataFrame(data=[[\"task 45\",\"2 mins\"],[\"task 45\",\"5 mins\"],[\"task 45\",\"7 mins\"],[\"task 67\",\"8 mins\"],[\"task 67\",\"9 mins\"]], columns=[\"TaskID\",\"task duration\"])\ndf2 = pd.DataFrame(data=[[\"task 45\",\"male\"],[\"task 45\",\"male\"],[\"task 45\",\"male\"],[\"task 67\",\"female\"],[\"task 67\",\"female\"]], columns=[\"TaskID\",\"gender\"])\nresult_df = df1.merge(df2)\ncols = ['TaskID','task duration','gender']\nresult_df[['task duration','gender']] = result_df[cols].mask(result_df[cols].duplicated())[['task duration','gender']]\nresult_df = result_df.dropna().reset_index(drop=True)\n\n[Out]:\n TaskID task duration gender\n0 task 45 2 mins male\n1 task 45 5 mins male\n2 task 45 7 mins male\n3 task 67 8 mins female\n4 task 67 9 mins female\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20457995/" ]
74,373,440
<p>I'm reading <a href="https://www.amazon.com.au/Effective-Java-Joshua-Bloch/dp/0134685997/" rel="nofollow noreferrer">Effective Java by Joshua Bloch</a>. In <em>Item 7: Eliminate Obsolete Object References</em> of chapter 2 he states:</p> <blockquote> <p>A third common source of memory leaks is listeners and other callbacks. If you implement an API where clients register callbacks but don’t deregister them explicitly, they will accumulate unless you take some action. One way to ensure that callbacks are garbage collected promptly is to store only weak references to them, for instance, by storing them only as keys in a WeakHashMap.</p> </blockquote> <p>I understand the concept of a <code>WeakHashMap</code>. I implemented one for a mock cache:</p> <pre><code>/** Example courtesy of Baeldung */ public class WeakHashMapDemo { public static void main(String[] args) { /** Ideally, we want a Map implementation that allows GC to automatically delete unused objects. * When a key of a big image object is not in use in our application in any place, * that entry will be deleted from memory. */ WeakHashMap&lt;UniqueImageName, BigImage&gt; wMap = new WeakHashMap&lt;&gt;(); HashMap&lt;UniqueImageName, BigImage&gt; map = new HashMap&lt;&gt;(); BigImage bigImage = new BigImage(&quot;image_id&quot;); UniqueImageName imageName = new UniqueImageName(&quot;name_of_big_image&quot;); /** We are putting a BigImage object as a value and an imageName object reference as a key. */ wMap.put(imageName, bigImage); System.out.println(&quot;Map does not contain imageName -&gt; &quot; + wMap.containsKey(imageName)); wMap.put(imageName, bigImage); /** The key is set to null. */ imageName = null; /** Forcing JVM to GC. */ System.gc(); System.out.println(&quot;Weak Map is empty -&gt; &quot; + wMap); } private static class UniqueImageName { public UniqueImageName(String name_of_big_image) { } } private static class BigImage { public BigImage(String image_id) { } } } </code></pre> <p>I also read this excellent <a href="https://www.baeldung.com/java-weakhashmap#3-weak-references:%7E:text=2.3.-,Weak%20References,-The%20objects%20that" rel="nofollow noreferrer">article</a> on weak references. However, I still don't understand using these concepts in the context of callbacks. How can I ensure memory leaks don't happen with a given API, using a <code>WeakHashMap</code>, if clients don't explicitly deregister them?</p> <p>I appreciate any help you can provide.</p> <p>UPDATE:</p> <p>It seems a few people need more clarity on the question. When I mean by &quot;How can I ensure memory leaks don't happen with a given API, using a <code>WeakHashMap</code>, if clients don't explicitly deregister them?&quot; is how this can be implemented with code as I only seem to have a conceptual understanding at the moment. So I'd really appreciate it if someone could show me a code snippet on how this would be implemented on a mock API. Thanks again!</p>
[ { "answer_id": 74375515, "author": "Ingo Kegel", "author_id": 936832, "author_profile": "https://Stackoverflow.com/users/936832", "pm_score": 2, "selected": true, "text": "class ApiUser {\n Listener listener;\n void registerListener() {\n listener = new Listener() {\n @Override\n public void event() {\n // TODO\n }\n };\n Api.registerListener(listener);\n }\n}\n\nclass Api {\n static WeakHashMap<Listener, Object> listeners = new WeakHashMap<>();\n static void registerListener(Listener listener) {\n listeners.put(listener, null);\n } \n\n static void fireListeners() {\n for (Listener listener : listeners.keySet()) {\n if (listener != null) {\n listener.event();\n }\n }\n }\n}\n\ninterface Listener {\n void event();\n}\n" }, { "answer_id": 74386184, "author": "Holger", "author_id": 2711488, "author_profile": "https://Stackoverflow.com/users/2711488", "pm_score": 2, "selected": false, "text": "WeakHashMap" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6367109/" ]
74,373,456
<p>Is it possible to access a javascript variable with Cypress? I want to geht the value of foo with Cypress.</p> <pre><code>$(document).ready(function() { ... var foo='xyz'; ... } </code></pre> <pre><code>cy.visit('abc.example.com') cy.window().then((win) =&gt; { let foo=win.foo; cy.log(foo); }); </code></pre>
[ { "answer_id": 74375515, "author": "Ingo Kegel", "author_id": 936832, "author_profile": "https://Stackoverflow.com/users/936832", "pm_score": 2, "selected": true, "text": "class ApiUser {\n Listener listener;\n void registerListener() {\n listener = new Listener() {\n @Override\n public void event() {\n // TODO\n }\n };\n Api.registerListener(listener);\n }\n}\n\nclass Api {\n static WeakHashMap<Listener, Object> listeners = new WeakHashMap<>();\n static void registerListener(Listener listener) {\n listeners.put(listener, null);\n } \n\n static void fireListeners() {\n for (Listener listener : listeners.keySet()) {\n if (listener != null) {\n listener.event();\n }\n }\n }\n}\n\ninterface Listener {\n void event();\n}\n" }, { "answer_id": 74386184, "author": "Holger", "author_id": 2711488, "author_profile": "https://Stackoverflow.com/users/2711488", "pm_score": 2, "selected": false, "text": "WeakHashMap" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20111643/" ]
74,373,467
<p>I'm having a bit of an issue rendering a JSON object in a React component. I want to get the meaning of a random word and then render it in page.</p> <p>My App.js;</p> <pre><code>function App() { const [meaning,setMeaning] = useState([]); }; useEffect(()=&gt;{ getMeaning() }, []) const getMeaning = async ()=&gt;{ const response = await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${word}`) const data = await response.json(); setMeaning(data) } &lt;AppContext.Provider value={{word,setWord, meaning,setMeaning}} </code></pre> <p>my Meaning.js</p> <pre><code>function Meaning(){ const{ meaning, setMeaning, } = useContext(AppContext); if (!meaning.length) return &lt;div&gt;loading&lt;/div&gt; return{meaning} // tried return json.stringify{meaning} as well // } </code></pre> <p>I do receive the object as I can console.log it. How can I render it on page? Where am I going wrong?</p> <p>Thanks in advance,</p>
[ { "answer_id": 74375515, "author": "Ingo Kegel", "author_id": 936832, "author_profile": "https://Stackoverflow.com/users/936832", "pm_score": 2, "selected": true, "text": "class ApiUser {\n Listener listener;\n void registerListener() {\n listener = new Listener() {\n @Override\n public void event() {\n // TODO\n }\n };\n Api.registerListener(listener);\n }\n}\n\nclass Api {\n static WeakHashMap<Listener, Object> listeners = new WeakHashMap<>();\n static void registerListener(Listener listener) {\n listeners.put(listener, null);\n } \n\n static void fireListeners() {\n for (Listener listener : listeners.keySet()) {\n if (listener != null) {\n listener.event();\n }\n }\n }\n}\n\ninterface Listener {\n void event();\n}\n" }, { "answer_id": 74386184, "author": "Holger", "author_id": 2711488, "author_profile": "https://Stackoverflow.com/users/2711488", "pm_score": 2, "selected": false, "text": "WeakHashMap" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4377207/" ]