qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,437,772
<p>In the background does the app still running even though I'm not currently on that tab, or when I move between tabs, the current tab I was, in is getting paused and after I open that tab again it makes a request to the server to get the newer changes from the database?</p> <p>Edit: The problem which I currently have is: I have an expiration timer where the reservation needs to be closed after 5 min if there is no activity, now if I open a new tab and come back after e.g. 10 min, the reservation sometimes is closed and it shows good on the front end and back end, sometimes the reservation will close on the backend but the front end will not be updated.</p> <p>If I'm on that tab then everything works, but when I switch tabs and come back after some time I have a problem.</p>
[ { "answer_id": 74473852, "author": "Николай", "author_id": 9098414, "author_profile": "https://Stackoverflow.com/users/9098414", "pm_score": 2, "selected": true, "text": "$posts = get_posts([\n 'post_mime_type' => 'image',\n 'post_type' => 'attachment',\n 'post_status' => 'inherit',\n 'posts_per_page' => -1,\n]);\n\nforeach ($posts as $post) {\n // Here you can compare the file extension\n // and, using your code, convert the image (by creating another one)\n // and delete the original jpg/png file :)\n}\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74437772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13814476/" ]
74,437,776
<p>If the data is to be removed, I find the element with findIndex and discard it as a null value in isInArray. If there is no such data, how do I add it to the empty element starting from the first element? For example, if the element in the first data is full, it should know that the second element is empty and add it to it.</p> <pre><code>&lt;template&gt; &lt;input type=&quot;text&quot; v-model=&quot;name&quot;&gt; &lt;input type=&quot;text&quot; v-model=&quot;surname&quot;&gt; &lt;button @click=&quot;addCustomer&quot;&gt;&lt;/button&gt; &lt;/template&gt; &lt;script&gt; import Vue from &quot;vue&quot;; export default { data(){ return{ name:null, surname:null, customers:[{},{},{}], currentIndex:null } }, methods:{ addCustomer(){ let findIndex = this.customers.findIndex((customer) =&gt; customer.name === this.name ); let isInArray = findIndex !== -1; if(isInArray){ Vue.set(this,&quot;currentIndex&quot;,findIndex) Vue.set(this.customers[this.currentIndex], 'name', null) }else{ // What Should I write here? } } } } &lt;/script&gt; </code></pre>
[ { "answer_id": 74473852, "author": "Николай", "author_id": 9098414, "author_profile": "https://Stackoverflow.com/users/9098414", "pm_score": 2, "selected": true, "text": "$posts = get_posts([\n 'post_mime_type' => 'image',\n 'post_type' => 'attachment',\n 'post_status' => 'inherit',\n 'posts_per_page' => -1,\n]);\n\nforeach ($posts as $post) {\n // Here you can compare the file extension\n // and, using your code, convert the image (by creating another one)\n // and delete the original jpg/png file :)\n}\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74437776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19301566/" ]
74,437,796
<p><em>New to OOP and python</em>, I am <em>struggling enormously</em> to grasp what good <em>classes actually are for</em>. I tried to ask <em>help from a lecturer</em> who said &quot;oh, then you should read about general methods to classes&quot;. <em>Been putting in a days work but get no where</em>.</p> <p>I get it that a class allow you to collect an instance structure and methods to it, like this:</p> <pre><code>class Items: def __init__(self, item_id, item_name): self.item_id = item_id self.item_name = item_name def show_list(self): print(self.item_id, self.item_name) idA = Items(&quot;idA&quot;, &quot;A&quot;) idA.show_list() </code></pre> <p><strong>But what is even the point</strong> of a class if there were not MANY instances you would classify? If I have a method within the class, I must hard code the actual instance to call the class for. What if you want a user to search and select an instance, to then do operations to (e.g. print, compute or whatever)??</p> <p>I thought of doing it like this:</p> <pre><code>class Items: def __init__(self, item_id, item_name): self.item_id = item_id self.item_name = item_name def show_list(self): print(self.item_id, self.item_name) idA = Items(&quot;idA&quot;, &quot;A&quot;) idB = Items(&quot;idB&quot;, &quot;B&quot;) select_item = input(&quot;enter item id&quot;) select_item.show_list() </code></pre> <p>Replacing hard coded variable with input variable doesn't work, probably logically. I then played with the idea of doing it like this:</p> <pre><code>class Items: def __init__(self, item_id, item_name): self.item_id = item_id self.item_name = item_name iL = [Items('idA', 'A'), Items('idB', 'B')] selected_item = input(&quot;enter item id&quot;) for selected_item in iL: print(f'{selected_item.item_id} {selected_item.item_name}') </code></pre> <p>Now all are called thanks to making it a list instead of separate instances, but how do I actually apply code to filter and only use one instance in the list (dynamically, based on input)?</p> <p>I would love the one who brought me sense to classes. You guys who work interactively with large data sets must do something what I today believe exist in another dimension.</p> <p>See examples above^^</p>
[ { "answer_id": 74473852, "author": "Николай", "author_id": 9098414, "author_profile": "https://Stackoverflow.com/users/9098414", "pm_score": 2, "selected": true, "text": "$posts = get_posts([\n 'post_mime_type' => 'image',\n 'post_type' => 'attachment',\n 'post_status' => 'inherit',\n 'posts_per_page' => -1,\n]);\n\nforeach ($posts as $post) {\n // Here you can compare the file extension\n // and, using your code, convert the image (by creating another one)\n // and delete the original jpg/png file :)\n}\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74437796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20504169/" ]
74,437,809
<p>I am trying add an local image on my svelte project. But it's giving 404 error. How can i fix it?</p> <p>``</p> <pre><code>&lt;script&gt; const src = './image/Banner.png' &lt;/script&gt; &lt;main&gt; &lt;header&gt; &lt;div class=&quot;Banner&quot;&gt; &lt;div class=&quot;banner-img&quot;&gt; &lt;img src=&quot;{src}&quot; alt=&quot;&quot;&gt; &lt;/div&gt; &lt;div class=&quot;banner-text&quot;&gt;&lt;/div&gt; &lt;/div&gt; &lt;/header&gt; &lt;/main&gt; </code></pre> <p>``</p> <p>This the error</p> <blockquote> <p>[23:51:25] 404 ─ 0.20ms ─ /image/Banner.png</p> </blockquote> <p>I am trying add an local image on my svelte project. But it's giving 404 error<code>your text</code></p>
[ { "answer_id": 74439359, "author": "Nico", "author_id": 8760866, "author_profile": "https://Stackoverflow.com/users/8760866", "pm_score": 0, "selected": false, "text": "<script>\n import bannerImg from \"$lib/Banner.png\"; // The href of the image\n</script>\n\n<main>\n <header>\n <div class=\"Banner\">\n <div class=\"banner-img\">\n <img src={bannerImg} alt=\"\">\n </div>\n <div class=\"banner-text\"></div>\n </div>\n </header>\n</main>\n" }, { "answer_id": 74472022, "author": "Toni BCN", "author_id": 5939260, "author_profile": "https://Stackoverflow.com/users/5939260", "pm_score": 2, "selected": true, "text": "<img src=\"assets/pdf_icon.gif\" alt=\"Pdf\">\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74437809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14015433/" ]
74,437,825
<p>I made LazyColumn with vertical scroll bar and it's work good, but when i scroll mouse, column just jumping(not smooth), but when I scroll vert. bar, it's smooth</p> <pre><code>@ExperimentalFoundationApi @OptIn(ExperimentalMaterial3Api::class, ExperimentalComposeUiApi::class) @Composable fun App() { Box(modifier = Modifier.fillMaxSize().padding(10.dp) ) { val animatedpr = remember { androidx.compose.animation.core.Animatable(initialValue = 0.8f) } val stateVertical = rememberLazyListState(0) LaunchedEffect(Unit){animatedpr.animateTo(targetValue = 1f, animationSpec = tween(300, easing = LinearEasing))} LazyColumn(modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, state = stateVertical) { items(1100) { OutlinedCard(modifier = Modifier.size(500.dp, 100.dp).padding(20.dp).animateItemPlacement().graphicsLayer(scaleY = animatedpr.value, scaleX = animatedpr.value)) { } } } VerticalScrollbar( modifier = Modifier.align(Alignment.CenterEnd).fillMaxHeight(), adapter = rememberScrollbarAdapter( scrollState = stateVertical ) ) } } </code></pre>
[ { "answer_id": 74449135, "author": "nevrozq", "author_id": 19536890, "author_profile": "https://Stackoverflow.com/users/19536890", "pm_score": 0, "selected": false, "text": "val scope = rememberCoroutineScope() // coroutine for scroling(idk, i know coroutines very bad)\nval stateVertical = rememberLazyListState(0)\n.....\nLazyColumn(modifier = Modifier.fillMaxSize().onPointerEvent(PointerEventType.Scroll){\n var currentItem = stateVertical.layoutInfo.visibleItemsInfo[0].index\n val itemsToScrolling = stateVertical.layoutInfo.visibleItemsInfo.size/2 // how many items we scrolling\n if(it.changes.first().scrollDelta.y == 1.0f){ // scroll down\n scope.launch { stateVertical.animateScrollToItem(currentItem+itemsToScrolling) }\n }\n else{ // scroll up\n if(currentItem < itemsToScrolling){currentItem = itemsToScrolling} // because we cannot animate to negative number\n scope.launch { stateVertical.animateScrollToItem(currentItem-itemsToScrolling) }\n }\n }, state = stateVertical){\n *items*\n}\n" }, { "answer_id": 74462924, "author": "nevrozq", "author_id": 19536890, "author_profile": "https://Stackoverflow.com/users/19536890", "pm_score": 2, "selected": false, "text": "if(it.changes.first().scrollDelta.y == 1.0f){\n scope.launch { stateVertical.animateScrollBy(200.0f) }\n }\n else{\n scope.launch {\n scope.launch { stateVertical.animateScrollBy(-200.0f) }\n }\n }\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74437825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19536890/" ]
74,437,826
<p>The title might be quite vague, but here is the code: <a href="https://github.com/amorfis/why-no-implicit" rel="nofollow noreferrer">https://github.com/amorfis/why-no-implicit</a></p> <p>So there is a tool to transform <code>Map[String, Any]</code> to a simple case class. The tests pass and this piece of code illustrates what it is all about:</p> <pre><code> case class TargetData( groupId: String, validForAnalysis: Boolean, applicationId: Int ) val map = Map( &quot;groupId&quot; -&gt; &quot;123456712345&quot;, &quot;applicationId&quot; -&gt; 31, &quot;validForAnalysis&quot; -&gt; true ) val transformed: TargetData = MapDecoder.to[TargetData](map).transform </code></pre> <p>This code works. It nicely creates the case class instance when provided the simple <code>map</code></p> <p>However, the <code>transform</code> method has to be called &quot;outside&quot; - just like in the example. When I try to move it to the <code>MapDecoder.to</code> method - the compiler complains about the missing implicit.</p> <p>So I change the code in <code>MapDecoder.to</code> from this:</p> <pre><code>def to[A](map: Map[String, Any]) = new MapDecoderH[A](map) </code></pre> <p>to this:</p> <pre><code>def to[A](map: Map[String, Any]) = new MapDecoderH[A](map).transform </code></pre> <p>and it stops working. Why is that? Why the implicit is provided in one case but not in the other? All that changes is that I want to call the <code>transform</code> method in other place to have <code>MapDecoder.to</code> returning the case class not some transformer.</p> <p>UPDATE:</p> <p>What if I want to implement <code>to[A]</code> method inside an object I want to transform? Let's call it <code>DataFrame</code>, and I want this code to work:</p> <pre><code>val df: DataFrame = ... df.to[TargetData] // There is no apply called here </code></pre> <p>The problem is in such case there is nothing to pass to <code>apply</code>. It is also not feasible to call it with parens (<code>df.to[TargetData]()</code>) because then the compiler requires implicits in parens. Is it even possible to solve it without using macros?</p>
[ { "answer_id": 74438478, "author": "Mateusz Kubuszok", "author_id": 1305121, "author_profile": "https://Stackoverflow.com/users/1305121", "pm_score": 4, "selected": true, "text": "def to" }, { "answer_id": 74439731, "author": "Dmytro Mitin", "author_id": 5249621, "author_profile": "https://Stackoverflow.com/users/5249621", "pm_score": 2, "selected": false, "text": "def to[A](map: Map[String, Any]) = new MapDecoderH[A](map).transform\n\n// ===>\n\ndef to[A, R <: HList](map: Map[String, Any])(implicit\n gen: LabelledGeneric.Aux[A, R],\n transformer: MapDecoder[R]\n) = new MapDecoderH[A](map).transform\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74437826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/121595/" ]
74,437,830
<p>How do I end a program that reads an input line by line and it ends when there's a period (whitespace doesn't matter)?</p> <p>For example:</p> <pre><code>input = &quot;HI bye .&quot; </code></pre> <p>the program should end after it reaches the period.</p> <p>I tried doing two things:</p> <pre><code>if line == &quot;.&quot;: break if &quot;.&quot; in line: break </code></pre> <p>but the first one doesn't consider whitespace, and the second one doesn't consider &quot;.&quot; in numbers like <em>2.1</em>.</p>
[ { "answer_id": 74437856, "author": "S.B", "author_id": 13944524, "author_profile": "https://Stackoverflow.com/users/13944524", "pm_score": 2, "selected": false, "text": ".strip()" }, { "answer_id": 74437873, "author": "Luis Rubiano", "author_id": 19039059, "author_profile": "https://Stackoverflow.com/users/19039059", "pm_score": 2, "selected": false, "text": "if line.replace(\" \", \"\")[-1] == \".\":\n break\n" }, { "answer_id": 74437904, "author": "StonedTensor", "author_id": 6023918, "author_profile": "https://Stackoverflow.com/users/6023918", "pm_score": 0, "selected": false, "text": "endswith" }, { "answer_id": 74437908, "author": "Grismar", "author_id": 4390160, "author_profile": "https://Stackoverflow.com/users/4390160", "pm_score": 0, "selected": false, "text": "from io import StringIO\n\n# you need triple double quotes to have a multiline string like this\n# also, don't name it `input`, that shadows the `input()` function\ntext = \"\"\"HI\n bye\n .\"\"\"\n\nfor line in StringIO(text):\n if line.strip()[-1] == \".\":\n print('found the end')\n break\n" }, { "answer_id": 74446706, "author": "Jethy11", "author_id": 20440485, "author_profile": "https://Stackoverflow.com/users/20440485", "pm_score": -1, "selected": false, "text": "input = '''HI\n bye\n .\n hello\n bye'''\n\nindex = input.find('.') # gets the index of the dot\n\nprint(input[:index+1])\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74437830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20106966/" ]
74,437,889
<p>I have tried to use double indexing but this has not worked for me.</p> <p>P.S check my work below</p> <p>As you can see my code is not replacing only the digit at x,y position but every position at x.</p> <p>Example variables for solution</p> <pre><code>field =[[0, 1, 1],[1, 0, 1],[0, 0, 1]] x_axis = 1 y_axis = 1 </code></pre> <p>Input</p> <pre><code>def solution(field, x, y): arr = [[-1] * len(field)]*len(field) print(arr) total_mines = 0 for array in field: temp_mines = array[x-1] + array[x] + array[x+1] total_mines += temp_mines arr[y][x]) = int(total_mines) print(arr) </code></pre> <p>Output</p> <pre><code>[[-1, -1, -1], [-1, -1, -1], [-1, -1, -1]] [[-1, 5, -1], [-1, 5, -1], [-1, 5, -1]] </code></pre>
[ { "answer_id": 74437856, "author": "S.B", "author_id": 13944524, "author_profile": "https://Stackoverflow.com/users/13944524", "pm_score": 2, "selected": false, "text": ".strip()" }, { "answer_id": 74437873, "author": "Luis Rubiano", "author_id": 19039059, "author_profile": "https://Stackoverflow.com/users/19039059", "pm_score": 2, "selected": false, "text": "if line.replace(\" \", \"\")[-1] == \".\":\n break\n" }, { "answer_id": 74437904, "author": "StonedTensor", "author_id": 6023918, "author_profile": "https://Stackoverflow.com/users/6023918", "pm_score": 0, "selected": false, "text": "endswith" }, { "answer_id": 74437908, "author": "Grismar", "author_id": 4390160, "author_profile": "https://Stackoverflow.com/users/4390160", "pm_score": 0, "selected": false, "text": "from io import StringIO\n\n# you need triple double quotes to have a multiline string like this\n# also, don't name it `input`, that shadows the `input()` function\ntext = \"\"\"HI\n bye\n .\"\"\"\n\nfor line in StringIO(text):\n if line.strip()[-1] == \".\":\n print('found the end')\n break\n" }, { "answer_id": 74446706, "author": "Jethy11", "author_id": 20440485, "author_profile": "https://Stackoverflow.com/users/20440485", "pm_score": -1, "selected": false, "text": "input = '''HI\n bye\n .\n hello\n bye'''\n\nindex = input.find('.') # gets the index of the dot\n\nprint(input[:index+1])\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74437889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20504390/" ]
74,437,902
<pre><code>#include &lt;stdio.h&gt; int main(){ int number[]; scanf(&quot;%d&quot;, &amp;number); int counter = 0; while (counter &lt; number){ printf(&quot;%d\n&quot;, counter); counter += 1; } } </code></pre> <p>I am getting an error saying that an integer cant be compared with a pointer but im not sure how to fix it and dont understand why it doesnt work,.</p> <pre><code>type here </code></pre>
[ { "answer_id": 74437920, "author": "Vlad from Moscow", "author_id": 2877241, "author_profile": "https://Stackoverflow.com/users/2877241", "pm_score": 2, "selected": true, "text": "int number[];\n" }, { "answer_id": 74438004, "author": "Asheesh Kumar", "author_id": 18127734, "author_profile": "https://Stackoverflow.com/users/18127734", "pm_score": 0, "selected": false, "text": "int number[];\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74437902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20432396/" ]
74,437,909
<pre><code>public function storeProject() { $this-&gt;validate(); $fileName = $this-&gt;files-&gt;store('uploads'); Project::create([ 'title' =&gt; $this-&gt;title, 'description' =&gt; $this-&gt;description, 'files' =&gt; $fileName, 'skills' =&gt; $this-&gt;skills, ]); session()-&gt;flash('message', 'Your Project has been posted Successfully!'); } </code></pre> <p>My View</p> <pre><code>@section('title', 'Post a job') &lt;div&gt; &lt;div class=&quot;py-12 font-sans&quot;&gt; &lt;div class=&quot;max-w-5xl mx-auto sm:px-6 lg:px-8&quot;&gt; &lt;div class=&quot;m-4 p-4 bg-gradient-to-r from-blue-800 via-blue-700 to-blue-600 text-white rounded-md&quot;&gt; &lt;h2 class=&quot;text-4xl&quot;&gt;Tell us what you need done!&lt;/h2&gt; &lt;p class=&quot;break-words mt-5&quot;&gt;Within minutes, get in touch with knowledgeable independent contractors. View their profiles, give them feedback, look at their portfolios, and talk with them. Only pay the freelancer once you are completely satisfied with their job. &lt;/p&gt; &lt;/div&gt; &lt;div&gt; {{-- Form is located here --}} &lt;form enctype=&quot;multipart/form-data&quot;&gt; &lt;div class=&quot;mb-6&quot;&gt; &lt;label for=&quot;title&quot;&gt;Choose a Title for your Project&lt;/label&gt; &lt;input type=&quot;title&quot; id=&quot;title&quot; name=&quot;title&quot; wire:model.lazy=&quot;title&quot; placeholder=&quot;e.g. Build me a website&quot;&gt; &lt;/div&gt; &lt;div class=&quot;mb-6&quot;&gt; &lt;label for=&quot;message&quot;&gt;Tells more about your project&lt;/label&gt; &lt;textarea id=&quot;description&quot; name=&quot;description&quot; rows=&quot;4&quot; wire:model.lazy=&quot;description&quot; placeholder=&quot;Describe your project here...&quot; maxlength=&quot;4000&quot;&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;div class=&quot;mb-6&quot;&gt; &lt;label for=&quot;user_avatar&quot;&gt;Upload file&lt;/label&gt; &lt;input wire:model=&quot;files&quot; aria-describedby=&quot;user_avatar_help&quot; id=&quot;user_avatar&quot; name=&quot;files&quot; type=&quot;file&quot;&gt; &lt;/div&gt; &lt;div class=&quot;mb-6&quot;&gt; &lt;label for=&quot;skills&quot;&gt; What skills are required&lt;/label&gt; &lt;p class=&quot;break-words mt-2&quot;&gt;Enter up to 5 skills that best describe your project. Freelancers will use these skills to find projects they are most interested and experienced in.&lt;/p&gt; &lt;input type=&quot;text&quot; id=&quot;skills&quot; name=&quot;skills&quot; data-role=&quot;tags-input&quot; wire:model.lazy=&quot;skills&quot; placeholder=&quot;Enter skills here separated by commas...&quot;&gt; &lt;/div&gt; &lt;button type=&quot;submit&quot; wire:click=&quot;storeProject&quot;&gt; Submit &lt;/button&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>After clicking on submit, this is my url <code>http://127.0.0.1:8000/post-project?title=Iphone+XR+Mini+Updated&amp;description=I+need+it&amp;files=Gilles+Ashley%27s+CV.pdf&amp;skills=Mysql%2C+C%2B%2B+etc</code>. What is wrong with my codes please? Any help? After clicking on submit, this is my url <code>http://127.0.0.1:8000/post-project?title=Iphone+XR+Mini+Updated&amp;description=I+need+it&amp;files=Gilles+Ashley%27s+CV.pdf&amp;skills=Mysql%2C+C%2B%2B+etc</code>. What is wrong with my codes please? Any help? After clicking on submit, this is my url <code>http://127.0.0.1:8000/post-project?title=Iphone+XR+Mini+Updated&amp;description=I+need+it&amp;files=Gilles+Ashley%27s+CV.pdf&amp;skills=Mysql%2C+C%2B%2B+etc</code>. This is my blade code. After clicking on submit, this is my url <code>http://127.0.0.1:8000/post-project?title=Iphone+XR+Mini+Updated&amp;description=I+need+it&amp;files=Gilles+Ashley%27s+CV.pdf&amp;skills=Mysql%2C+C%2B%2B+etc</code>. What is wrong with my codes please? Any help? After clicking on submit, this is my url <code>http://127.0.0.1:8000/post-project?title=Iphone+XR+Mini+Updated&amp;description=I+need+it&amp;files=Gilles+Ashley%27s+CV.pdf&amp;skills=Mysql%2C+C%2B%2B+etc</code>. What is wrong with my codes please? Any help? After clicking on submit, this is my url <code>http://127.0.0.1:8000/post-project?title=Iphone+XR+Mini+Updated&amp;description=I+need+it&amp;files=Gilles+Ashley%27s+CV.pdf&amp;skills=Mysql%2C+C%2B%2B+etc</code>. What is wrong with my codes please? Any help?</p>
[ { "answer_id": 74441477, "author": "raimondsL", "author_id": 4354065, "author_profile": "https://Stackoverflow.com/users/4354065", "pm_score": 0, "selected": false, "text": "storeProject()" }, { "answer_id": 74442833, "author": "Ray C", "author_id": 10257689, "author_profile": "https://Stackoverflow.com/users/10257689", "pm_score": 2, "selected": false, "text": "<form wire:submit.prevent=\"storeProject\">\n\n<button type=\"submit\">\n Submit\n</button>\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74437909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15311198/" ]
74,437,910
<p>Given the following list:</p> <pre><code>dbset = [[{'id': '10556', 'nation': 'France', 'worth': '70'}], [{'id': '14808', 'nation': 'France', 'worth': '65'}], [{'id': '11446', 'nation': 'Ghana', 'worth': '69'}], [{'id': '11419', 'nation': 'France', 'worth': '69'}], [{'id': '11185', 'nation': 'Ghana', 'worth': '69'}], [{'id': '1527', 'nation': 'Ghana', 'worth': '64'}], [{'id': '12714', 'nation': 'Moldova', 'worth': '67'}], [{'id': '2855', 'nation': 'Moldova', 'worth': '63'}], [{'id': '9620', 'nation': 'Moldova', 'worth': '71'}]] </code></pre> <p>I know how to find all permutations of length 4 with:</p> <pre><code>from itertools import permutations perms = permutations(dbset,4) </code></pre> <p>Now comes the part where I struggle; I want the maximum times a nation is in the permutation to be equal to 2 and I also would like the total worth to be above 300.</p> <p><strong>---Update---</strong></p> <p>I managed to get this working for the limited sample with limited permutations. The sample size however, is a set with over 16000 records and the permutation size is 11. As of yet, I am still executing it for the first time with 2 criteria: avg worth = 80 and nation occurrence &lt;= 5.</p> <p>It's been running for over an hour now... any way to improve?</p>
[ { "answer_id": 74438074, "author": "QWERTYL", "author_id": 11777402, "author_profile": "https://Stackoverflow.com/users/11777402", "pm_score": 2, "selected": true, "text": "perms = list(permutations(dbset,4))\nout = [x in perms if CONDITION]\n" }, { "answer_id": 74438082, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 0, "selected": false, "text": "from collections import Counter\n\ndef valid_permutation(perm):\n if sum(int(p['worth']) for p in perm) <= 300:\n return False\n counts = Counter(p['nation'] for p in perm)\n return counts.most_common()[0][1] <= 2\n\nperms = filter(valid_permutation, permutations([d[0] for d in dbset], 4))\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74437910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/828017/" ]
74,437,933
<p>I have a bunch of sentences that I want to break into an array. Right now, I'm splitting every time \n appears in the string.</p> <pre><code>@chapters = @script.split('\n') </code></pre> <p>What I'd like to do is .split ever OTHER &quot;.&quot; in the string. Is that possible in Ruby?</p>
[ { "answer_id": 74438074, "author": "QWERTYL", "author_id": 11777402, "author_profile": "https://Stackoverflow.com/users/11777402", "pm_score": 2, "selected": true, "text": "perms = list(permutations(dbset,4))\nout = [x in perms if CONDITION]\n" }, { "answer_id": 74438082, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 0, "selected": false, "text": "from collections import Counter\n\ndef valid_permutation(perm):\n if sum(int(p['worth']) for p in perm) <= 300:\n return False\n counts = Counter(p['nation'] for p in perm)\n return counts.most_common()[0][1] <= 2\n\nperms = filter(valid_permutation, permutations([d[0] for d in dbset], 4))\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74437933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3462069/" ]
74,437,964
<p>I have 2 tables</p> <p><code>tableA</code>:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>dateA</th> <th>colA</th> <th>...</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>2022-11-11 12:00:00</td> <td>A</td> <td></td> </tr> <tr> <td>2</td> <td>2022-11-12 12:00:00</td> <td>B</td> <td></td> </tr> <tr> <td>3</td> <td>2022-11-14 12:00:00</td> <td>C</td> <td></td> </tr> </tbody> </table> </div> <p><code>tableB</code>:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>dateB</th> <th>colB</th> <th>...</th> </tr> </thead> <tbody> <tr> <td>3</td> <td>2022-11-05 12:00:00</td> <td>D</td> <td></td> </tr> <tr> <td>4</td> <td>2022-11-06 12:00:00</td> <td>E</td> <td></td> </tr> <tr> <td>5</td> <td>2022-11-13 12:00:00</td> <td>F</td> <td></td> </tr> </tbody> </table> </div> <p>and I want put all rows to one result and sort it by column <code>date</code></p> <p>Wanted result (rows from both tables sorted by column <code>date DESC</code>):</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>date</th> <th>colA</th> <th>colB</th> <th>...</th> <th>...</th> </tr> </thead> <tbody> <tr> <td>3</td> <td>2022-11-14 12:00:00</td> <td>C</td> <td></td> <td></td> <td></td> </tr> <tr> <td>5</td> <td>2022-11-13 12:00:00</td> <td></td> <td>F</td> <td></td> <td></td> </tr> <tr> <td>2</td> <td>2022-11-12 12:00:00</td> <td>B</td> <td></td> <td></td> <td></td> </tr> <tr> <td>1</td> <td>2022-11-11 12:00:00</td> <td>A</td> <td></td> <td></td> <td></td> </tr> <tr> <td>4</td> <td>2022-11-06 12:00:00</td> <td></td> <td>E</td> <td></td> <td></td> </tr> <tr> <td>3</td> <td>2022-11-05 12:00:00</td> <td></td> <td>D</td> <td></td> <td></td> </tr> </tbody> </table> </div> <p>I can combine tables, but tables are &quot;squashed&quot;...</p> <pre class="lang-sql prettyprint-override"><code>SELECT COALESCE(a.id, b.id) AS id, COALESCE(a.dateA, b.dateB) AS date, a.colA, b.colB FROM tableA AS a, tableB AS b ORDER BY date DESC </code></pre>
[ { "answer_id": 74438006, "author": "GMB", "author_id": 10676716, "author_profile": "https://Stackoverflow.com/users/10676716", "pm_score": 2, "selected": true, "text": "UNION ALL" }, { "answer_id": 74442214, "author": "slaakso", "author_id": 1052130, "author_profile": "https://Stackoverflow.com/users/1052130", "pm_score": 0, "selected": false, "text": "id" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74437964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11251712/" ]
74,438,010
<p>i have a nested tuple like this one :</p> <pre><code>this_one = (w,h,(1,2,4,8,16),(0,2,3,4,6),(&quot;0&quot;),(&quot;0&quot;),(0,1)) </code></pre> <p>It will be used to feed: <code>itertools.product(*this_one)</code></p> <p><code>w</code> and <code>h</code> have to be both generators.</p> <p>Generated values from <code>h</code> depends on generated values from <code>w</code> as in this function:</p> <pre><code>def This_Function(maxvalue): for i in range(maxvalue): w_must_generate = i for j in range(i+1): h_must_generate = j </code></pre> <p>Iv tried using a yield in <code>This_function(maxvalue)</code>:</p> <pre><code>def This_Function(maxvalue): for i in range(maxvalue): for j in range(i+1): yield i,j </code></pre> <p>Returning a single generator object which gives:</p> <pre><code> which_gives = itertools.product(*this_one) for result in which_gives: print(result) ... ((23,22),(16),(6),(0),(0),(0)) ((23,22),(16),(6),(0),(0),(1)) ((23,23),(1),(0),(0),(0),(0)) ... </code></pre> <p>A single tuple at <code>result[0]</code> holding 2 values.</p> <p>And this is not what i want .</p> <p>The result i want has to be like the following:</p> <pre><code>the_following = itertools.product(*this_one) for result in the_following: print(result) ... ((23),(22),(16),(6),(0),(0),(0)) ((23),(22),(16),(6),(0),(0),(1)) ((23),(23),(1),(0),(0),(0),(0)) ... </code></pre> <p><strong>Without</strong> having to do something like :</p> <pre><code>the_following = itertools.product(*this_one) for result in the_following: something_like = tuple(result[0][0],result[0][1],result[1],...,result[5]) print(something_like) ... ((23),(22),(16),(6),(0),(0),(0)) ((23),(22),(16),(6),(0),(0),(1)) ((23),(23),(1),(0),(0),(0),(0)) ... </code></pre> <p>Any ideas ?</p>
[ { "answer_id": 74438172, "author": "Grismar", "author_id": 4390160, "author_profile": "https://Stackoverflow.com/users/4390160", "pm_score": 1, "selected": false, "text": "from itertools import product\n\nmaxvalue = 5\nw = (i for i in range(maxvalue) for j in range(i + 1))\nh = (j for i in range(maxvalue) for j in range(i + 1))\n\nthis_one = (w, h, (1, 2, 4, 8, 16), (0, 2, 3, 4, 6), (\"0\"), (\"0\"), (0, 1))\n\nresult = product(*this_one)\n" }, { "answer_id": 74438220, "author": "tzaman", "author_id": 257465, "author_profile": "https://Stackoverflow.com/users/257465", "pm_score": 3, "selected": true, "text": "product" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16256760/" ]
74,438,095
<p>I want to replace every string in and number in an object with an empty string of empty number.</p> <p>For example:</p> <pre><code>const test = { a: &quot;asdf&quot;, b: 2, c: [ { lala: &quot;more strings&quot;, d: &quot;saaa&quot; } ] } </code></pre> <p>with</p> <pre><code>const test = { a: &quot;&quot;, b: 0, c: [ { lala: &quot;&quot;, d: &quot;&quot; } ] } </code></pre> <p>I can't think of an easy way to iterate over all the values in the object/array recursively. Is there a library (maybe lodash) that does this already?</p>
[ { "answer_id": 74438172, "author": "Grismar", "author_id": 4390160, "author_profile": "https://Stackoverflow.com/users/4390160", "pm_score": 1, "selected": false, "text": "from itertools import product\n\nmaxvalue = 5\nw = (i for i in range(maxvalue) for j in range(i + 1))\nh = (j for i in range(maxvalue) for j in range(i + 1))\n\nthis_one = (w, h, (1, 2, 4, 8, 16), (0, 2, 3, 4, 6), (\"0\"), (\"0\"), (0, 1))\n\nresult = product(*this_one)\n" }, { "answer_id": 74438220, "author": "tzaman", "author_id": 257465, "author_profile": "https://Stackoverflow.com/users/257465", "pm_score": 3, "selected": true, "text": "product" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1078829/" ]
74,438,112
<p>I been kinda stumped for a couple hours trying to figure out what to set as my default value on my createContext function. This is my code.</p> <pre><code>// PetTypeProvider.tsx import { useState, createContext, useContext } from 'react'; const PetTypeContext = createContext(''); const UpdatePetTypeContext = createContext((event:React.MouseEvent&lt;HTMLElement&gt;) =&gt; event); export function usePetType() { return useContext(PetTypeContext) } export function useUpdatePetType() { return useContext(UpdatePetTypeContext) } interface PetTypeProviderProps { children: JSX.Element|JSX.Element[]; } export const PetTypeProvider: React.FC&lt;PetTypeProviderProps&gt; = ({children}) =&gt; { const [petType, setPetType] = useState('Dogs'); const togglePet = (event:React.MouseEvent&lt;HTMLElement&gt;) =&gt; setPetType(event.currentTarget.innerText); return ( &lt;PetTypeContext.Provider value={petType}&gt; &lt;UpdatePetTypeContext.Provider value={togglePet}&gt; {children} &lt;/UpdatePetTypeContext.Provider&gt; &lt;/PetTypeContext.Provider&gt; ); }; </code></pre> <p>On my &lt;UpdatePetTypeContext.Provider&gt; I set the value to my toggle function, which switches the pet type to which ever is selected.</p> <pre><code> const togglePet = (event:React.MouseEvent&lt;HTMLElement&gt;) =&gt; setPetType(event.currentTarget.innerText); </code></pre> <p>TS compiler is yelling at me with this</p> <pre><code>Type '(event: React.MouseEvent&lt;HTMLElement&gt;) =&gt; void' is not assignable to type '(event: React.MouseEvent&lt;HTMLElement&gt;) =&gt; React.MouseEvent&lt;HTMLElement, MouseEvent&gt;'. Type 'void' is not assignable to type 'MouseEvent&lt;HTMLElement, MouseEvent&gt;'.ts(2322) index.d.ts(329, 9): The expected type comes from property 'value' which is declared here on type 'IntrinsicAttributes &amp; ProviderProps&lt;(event: MouseEvent&lt;HTMLElement, MouseEvent&gt;) =&gt; MouseEvent&lt;HTMLElement, MouseEvent&gt;&gt;' </code></pre> <p>Thanks for taking the time to read my issue</p> <p>I have tried setting the to <code>const PetTypeContext = createContext(MouseEvent);</code> which didn't work. I honestly just need the correct default value and data type for TS and I am just lost. The code works, but TS compiler doesn't like it since no default value is given.</p>
[ { "answer_id": 74438172, "author": "Grismar", "author_id": 4390160, "author_profile": "https://Stackoverflow.com/users/4390160", "pm_score": 1, "selected": false, "text": "from itertools import product\n\nmaxvalue = 5\nw = (i for i in range(maxvalue) for j in range(i + 1))\nh = (j for i in range(maxvalue) for j in range(i + 1))\n\nthis_one = (w, h, (1, 2, 4, 8, 16), (0, 2, 3, 4, 6), (\"0\"), (\"0\"), (0, 1))\n\nresult = product(*this_one)\n" }, { "answer_id": 74438220, "author": "tzaman", "author_id": 257465, "author_profile": "https://Stackoverflow.com/users/257465", "pm_score": 3, "selected": true, "text": "product" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13759712/" ]
74,438,143
<p>How to Calculate total price of a List of items in <code>FutureBuilder</code> ? i try this</p> <pre><code>FutureBuilder&lt;ProModel&gt;( future: futurePro, builder: (context, snapshot){ if(snapshot.hasData){ snapshot.data.pro.forEach((element) { subTotal = subTotal + int.parse(element.amount); }); } } </code></pre> <p>but <code>subTotal</code> in a continuous increasing (to infinity) when i add <code> Text('$subTotal')</code> snapshot.data.pro is list from json</p> <pre><code>{ &quot;pro&quot;:[ {&quot;id&quot;:&quot;1&quot;, &quot;amount&quot;:&quot;1784&quot;,} {&quot;id&quot;:&quot;2&quot;, &quot;amount&quot;:&quot;1643&quot;,} ] } </code></pre>
[ { "answer_id": 74438628, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 0, "selected": false, "text": "subTotal = subTotal + int.parse(element.amount);\n" }, { "answer_id": 74438793, "author": "RobDil", "author_id": 410996, "author_profile": "https://Stackoverflow.com/users/410996", "pm_score": 2, "selected": true, "text": "subTotal" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15015485/" ]
74,438,148
<p>I have a dataframe shown below:</p> <p>I would like to count how many time the &quot;code&quot; column has a different character from the Key column group: Ex: in this example the first group has two S but one Q then will count one. The second group it does not have a different char. The third group has three F but one N then will count the total 2</p> <p>The loop should look at the the Key column and count 1 if there is any different char, then calculate the total number of counts.</p> <p>The result is a new datframe that has two rows ( inside the red line circles )</p> <p><a href="https://i.stack.imgur.com/zfAqD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zfAqD.png" alt="enter image description here" /></a></p> <pre><code> # initialize data of lists. data = {'Key': ['111*1', '111*2','111*3', '222*1','222*2', '333*1','333*2', '333*3','333*4', '444*1'], 'code': ['S', 'S','Q', 'M','M', 'F','F', 'F','N', 'C']} # Create DataFrame data = pd.DataFrame(data) data </code></pre>
[ { "answer_id": 74438628, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 0, "selected": false, "text": "subTotal = subTotal + int.parse(element.amount);\n" }, { "answer_id": 74438793, "author": "RobDil", "author_id": 410996, "author_profile": "https://Stackoverflow.com/users/410996", "pm_score": 2, "selected": true, "text": "subTotal" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10973494/" ]
74,438,203
<p>I have a collection that pulls state data from an HRIS on a daily basis. We can use state data for all kinds of interesting things, like predictive analytics.</p> <p>However, state change data grows boundlessly (currently, that's another piece of tech debt that we need to tackle). I would like to start however by creating a view that takes only the most recent record from the collection. So I have the following view creation code:</p> <pre><code>db.rawEmployeeStatus.aggregate().match({dateOfStateCapture: db.rawEmployeeStatus.find({}) .sort({$natural : -1}) .limit(1) .toArray()[0] .dateOfStateCapture}) .saveAsView(&quot;employeeStatusCurrentState&quot;,{dropIfExists:false}) </code></pre> <p>However, the problem with this view, is that it gets most recent record <em>at the time the view is created</em>, then uses that data for the view. When ideally, the data in the view should always be populated from the most recent records in the collection.</p>
[ { "answer_id": 74500769, "author": "user20042973", "author_id": 20042973, "author_profile": "https://Stackoverflow.com/users/20042973", "pm_score": 1, "selected": false, "text": "dateOfStateCapture" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1055516/" ]
74,438,219
<p>I am trying to complete some coursework, our exercise is focused around using data structures. I am trying to write a new method to print out each element in the array I have created but my for loop is not recognising the existence of the array that has been created above it. It is giving me an error at the 'students.Length' part.</p> <p>I'm sorry if this is a really stupid question because I feel like there's a very simple answer to this but I just can't understand why it's telling me the 'students' array doesn't exist?</p> <pre><code>public struct student_data { public string forename; public string surname; public int id_number; public float averageGrade; } static void populateStruct(out student_data student, string fname, string surname, int id_number) { student.forename = fname; student.surname = surname; student.id_number = id_number; student.averageGrade = 0.0F; } public static void Main(string[] args) { student_data[] students = new student_data[4]; populateStruct(out students[0], &quot;Mark&quot;, &quot;Anderson&quot;, 1); populateStruct(out students[1], &quot;Max&quot;, &quot;Fisher&quot;, 2); populateStruct(out students[2], &quot;Tom&quot;, &quot;Jones&quot;, 3); populateStruct(out students[3], &quot;Ewan&quot;, &quot;Evans&quot;, 4); } static void printAllStudent(student_data student) { for(int i = 0; i &lt; students.Length; i++) } </code></pre>
[ { "answer_id": 74438306, "author": "Mike Hofer", "author_id": 47580, "author_profile": "https://Stackoverflow.com/users/47580", "pm_score": 1, "selected": false, "text": "printAllStudent" }, { "answer_id": 74438974, "author": "Rufus L", "author_id": 2052655, "author_profile": "https://Stackoverflow.com/users/2052655", "pm_score": 0, "selected": false, "text": "printAllStudent" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20504616/" ]
74,438,234
<p>I added an image to my windows form app, using a picture box. I have it saved in the resources folder . I can't seem to delete it because when I try to, it says that it couldn't find the file.</p> <p>I have tried other solutions but can't seem to get them working, and don't understand how they are supposed to work.<img src="https://i.stack.imgur.com/lyrGo.png" alt="The error:" /></p> <p><img src="https://i.stack.imgur.com/SYPoI.png" alt="My resources folder:" /></p> <p>I tried to use the dispose method, but I couldn't get it working.</p>
[ { "answer_id": 74438306, "author": "Mike Hofer", "author_id": 47580, "author_profile": "https://Stackoverflow.com/users/47580", "pm_score": 1, "selected": false, "text": "printAllStudent" }, { "answer_id": 74438974, "author": "Rufus L", "author_id": 2052655, "author_profile": "https://Stackoverflow.com/users/2052655", "pm_score": 0, "selected": false, "text": "printAllStudent" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18054055/" ]
74,438,272
<p>I have the following code:</p> <pre><code>Text(welcome) </code></pre> <p>Where 'welcome' is a String from another page.</p> <pre><code> String welcome = &quot;Welcome&quot; </code></pre> <p>Basic. But what I would like was to be able to request some value of this String for example the username that way when using the String 'welcome' I should pass the value 'username'.</p> <p>It is possible?</p>
[ { "answer_id": 74438644, "author": "Robert Sandberg", "author_id": 13263384, "author_profile": "https://Stackoverflow.com/users/13263384", "pm_score": 1, "selected": false, "text": "Text(\"$welcome $username\")\n" }, { "answer_id": 74438756, "author": "tmp", "author_id": 19166990, "author_profile": "https://Stackoverflow.com/users/19166990", "pm_score": 0, "selected": false, "text": " String welcome = 'Welcome';\n String userName = 'Tom';\n String space = ' ';\n \n String concatenated = welcome + space+ userName;\n \n print(concatenated);\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12793541/" ]
74,438,283
<p>I could not find a way to run a T-SQL Script using <a href="https://pypi.org/project/pyodbc/" rel="nofollow noreferrer">pyodbc</a> without having to change the script content.</p> <p>Here's the simple SQL script file I'm trying to run:</p> <pre><code>SET NOCOUNT ON USE db_test GO CREATE OR ALTER FUNCTION usf_test() RETURNS NVARCHAR(10) BEGIN DECLARE @var NVARCHAR(10) SELECT @var = 'TEST' RETURN @var END </code></pre> <p>and this is the python code I'm using:</p> <pre><code>cursor.execute(file_content) cursor.fetchall() </code></pre> <p>This is the error message: <code>pyodbc.ProgrammingError: ('42000', &quot;[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near 'GO'. (102) (SQLExecDirectW)&quot;)</code> and yes, this runs with no errors directly on SSMS.</p> <p>Is there a way to run a T-SQL script using pyodbc (or any other lib that supports SQL Server) in Python?</p> <p>Notice I can't change the script content, so splitting it into multiple statements is not an option. I have to run the script just as it is on the file.</p>
[ { "answer_id": 74440270, "author": "ASH", "author_id": 5212614, "author_profile": "https://Stackoverflow.com/users/5212614", "pm_score": -1, "selected": false, "text": "cnxn_str = (\"Driver={SQL Server Native Client 11.0};\"\n \"Server=USXXX00345,67800;\"\n \"Database=DB02;\"\n \"Trusted_Connection=yes;\")\ncnxn = pyodbc.connect(cnxn_str)\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6576653/" ]
74,438,284
<p>A colleague wrote some Perl code (v5.30.0) that does all of this:</p> <pre><code>#!/usr/bin/perl use warnings; use strict; use Data::Dumper; package main; sub processScalarHash { my $bar = $_[0]; printf &quot;A subroutine can access the scalar hash: \&quot;%s\&quot;\n&quot;, $bar-&gt;{'key3'}; } # Build the &quot;Scalar Hash&quot;: my $scalarHash = {}; $scalarHash-&gt;{'key1'} = 'dog'; $scalarHash-&gt;{'key2'} = 'cat'; $scalarHash-&gt;{'key3'} = 'fish'; bless $scalarHash; printf &quot;I can examine the scalar hash:\n&quot;; print Dumper(\$scalarHash); printf &quot;I can access the scalar hash: \&quot;%s\&quot;\n&quot;, $scalarHash-&gt;{'key1'}; my $tmpStr = 'key2'; printf &quot;I can access the scalar hash: \&quot;%s\&quot;\n&quot;, $scalarHash-&gt;{$tmpStr}; processScalarHash($scalarHash); </code></pre> <p>Output is:</p> <pre><code>me@ubuntu01$ ./ScalarHash.perl I can examine the scalar hash: $VAR1 = \bless( { 'key3' =&gt; 'fish', 'key1' =&gt; 'dog', 'key2' =&gt; 'cat' }, 'main' ); I can access the scalar hash: &quot;dog&quot; I can access the scalar hash: &quot;cat&quot; A subroutine can access the scalar hash: &quot;fish&quot; me@ubuntu01$ </code></pre> <p>I'm just learning Perl myself, and what strikes me here is that I never see any documentation about referencing hashes with scalar ($) variables. With hash (%) and array (@) variables, yes, but never scalars ($)! I don't know why my colleague coded like this, but I have a sinking feeling that using &quot;scalar hashes&quot; is a very bad practice.</p> <p>Asking as a Perl newbie: Is this bad coding? The last thing I want to do is perpetuate bad habits that could bite me later.</p>
[ { "answer_id": 74439410, "author": "ikegami", "author_id": 589924, "author_profile": "https://Stackoverflow.com/users/589924", "pm_score": 4, "selected": true, "text": "sub f {\n my $h = shift; # Ref to hash\n for my $k ( keys( %$h ) ) {\n say \"$k: $h->{ $k }\";\n }\n}\n\nmy %h = ( a => 123, b => 456 ); # Hash\n$h{ c } = 789;\nf( \\%h );\n" }, { "answer_id": 74447961, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 1, "selected": false, "text": "my $hash_reference = {\n key1 => 'dog',\n key2 => 'cat',\n key3 => 'fish',\n};\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4040743/" ]
74,438,298
<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* bankAccount() { let balance = 0; while (balance &gt;= 0) { balance += yield balance; } return 'bankrupt! '; } let userAccount = bankAccount(); console.log(userAccount.next()); console.log(userAccount.next(10)); console.log(userAccount.next(-15));</code></pre> </div> </div> </p> <p>...this code works - I've run it and after the third call of next(), it returns bankrupt - but why? Surely when next() is called the third time, the loop will check the balance (which will still be 10 at that point), and then add -15 to the balance, and yield out -5...leaving the next iteration to yield bankrupt.</p> <p>But thats obviously not the case, the balance seems to be updated with the yield value before the loop checks the current balance, but if that line of code is running first, then why is the loop running at all? wouldn't it just be yielding out the updated balance instantly?...so, which code is being run when?</p>
[ { "answer_id": 74438382, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 3, "selected": true, "text": "let balance = 0;" }, { "answer_id": 74438389, "author": "Robin Zigmond", "author_id": 8475054, "author_profile": "https://Stackoverflow.com/users/8475054", "pm_score": 2, "selected": false, "text": "next" }, { "answer_id": 74438445, "author": "Warm Red", "author_id": 14209943, "author_profile": "https://Stackoverflow.com/users/14209943", "pm_score": 0, "selected": false, "text": "yield" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7217840/" ]
74,438,303
<p>Hi I am trying to automatically save the customer on post without having to list it in the forms. It currently shows the drop down and saves correctly but if I remove customer from forms.py it doesn't save anymore. views.py</p> <pre><code> @login_required(login_url='login') def createInfringer(request): customer=request.user.customer form = InfringerForm(customer=customer) if request.method == 'POST': form = InfringerForm(customer, request.POST) if form.is_valid(): form.save() return redirect('infringer-list') context ={'form': form} return render (request, 'base/infringement_form.html', context) </code></pre> <p>forms.py</p> <pre><code> class InfringerForm(ModelForm): def __init__(self, customer, *args, **kwargs): super(InfringerForm,self).__init__(*args, **kwargs) self.fields['customer'].queryset = Customer.objects.filter(name=customer) self.fields['status'].queryset = Status.objects.filter(customer=customer) class Meta: model = Infringer fields = ['name', 'brand_name','status','customer'] </code></pre> <p>UPDATE suggestion below was added but it still doesn't save customer.</p>
[ { "answer_id": 74438382, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 3, "selected": true, "text": "let balance = 0;" }, { "answer_id": 74438389, "author": "Robin Zigmond", "author_id": 8475054, "author_profile": "https://Stackoverflow.com/users/8475054", "pm_score": 2, "selected": false, "text": "next" }, { "answer_id": 74438445, "author": "Warm Red", "author_id": 14209943, "author_profile": "https://Stackoverflow.com/users/14209943", "pm_score": 0, "selected": false, "text": "yield" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20453400/" ]
74,438,322
<p>So - if I try to access a writeable within a +page.js then it just returns empty.</p> <pre class="lang-js prettyprint-override"><code>import { isAuthenticated, user } from '../../authstore'; export const load = async ({ fetch }) =&gt; { console.log ('doing load') console.log('is auth = ', isAuthenticated) if (! isAuthenticated) { throw redirect(302, '/'); } return {test:''}; } </code></pre> <p>As you can see, I'm adding this to a +page.js to check logged in status and if not, redirecting them to the root.</p> <p>However - isAuthenticated isn't accessible. Is this because it's running on the server rather than the client?</p>
[ { "answer_id": 74439405, "author": "H.B.", "author_id": 546730, "author_profile": "https://Stackoverflow.com/users/546730", "pm_score": 1, "selected": false, "text": "+page.server.js" }, { "answer_id": 74443113, "author": "Rob", "author_id": 119655, "author_profile": "https://Stackoverflow.com/users/119655", "pm_score": 0, "selected": false, "text": "let authed = false;\nisAuthenticated.subscribe(v => {\n authed = v\n})\nconsole.log('authuser', authuser)\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/119655/" ]
74,438,324
<p>I'm working through 99 scheme problems and I have a solution for P16 (Drop every N'th element from a list.) using recursion, but I'm trying to practice more functional methods. Is there a clean way to filter by index in mit-scheme?</p> <pre><code>(display (drop '(a b c d e f g h i j k) 3))) =&gt; (a b d e g h k) </code></pre> <p>In Python I could use enumerate:</p> <pre><code>import string lst = list(string.ascii_lowercase[:11]) fltr = filter(lambda item: (item[0]+1)%3, enumerate(lst)) mp = map(lambda item: item[1], fltr) print(list(mp)) =&gt; ['a', 'b', 'd', 'e', 'g', 'h', 'j', 'k'] </code></pre> <p>or list comprehensions</p> <pre><code>print([value for index, value in enumerate(lst) if (index+1)%3]) =&gt; ['a', 'b', 'd', 'e', 'g', 'h', 'j', 'k'] </code></pre> <p>Thanks!</p>
[ { "answer_id": 74464852, "author": "Dinay Kingkiller", "author_id": 20504471, "author_profile": "https://Stackoverflow.com/users/20504471", "pm_score": 1, "selected": false, "text": "zip" }, { "answer_id": 74655139, "author": "alinsoar", "author_id": 1419272, "author_profile": "https://Stackoverflow.com/users/1419272", "pm_score": 0, "selected": false, "text": "(define drop-each-nth\n (lambda (l n)\n ((lambda (s) (s s l (- n 1) (lambda (x) x)))\n (lambda (s l* k ret)\n (cond ((null? l*)\n (ret '()))\n ((zero? k)\n (s s (cdr l*)\n (- n 1)\n (lambda (x)\n (ret x))))\n (else\n (s s (cdr l*)\n (- k 1)\n (lambda (x)\n (ret (cons (car l*) x))))))))))\n\n(drop-each-nth '(a b c d e f g h i j k) 3)\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20504471/" ]
74,438,348
<p>I want to have a graph with a color scale, however the graph has certain deviations, where the first category is missing and then the color scale does not work any more. Is there a method to skip the first discrete color in a color scale?</p> <p>I provide an example that does not work below. The first graph has category A in light blue, and the second B. But also in the second B should be dark blue.</p> <p>I also found this question: <a href="https://stackoverflow.com/questions/53750310/how-to-change-default-color-scheme-in-ggplot2/53750568?noredirect=1#comment131401446_53750568">How to change default color scheme in ggplot2?</a></p> <pre><code>if (!require(&quot;pacman&quot;)) install.packages(&quot;pacman&quot;) pacman::p_load('tidyverse') first_column &lt;- c(&quot;value_1&quot;, &quot;value_3&quot;, &quot;value_2&quot;) second_column &lt;- c(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;) freq &lt;-c(23, 41, 32, 58, 11, 16, 19, 38) df2 &lt;- data.frame(first_column, second_column, freq) ggplot(df2, aes(x = first_column, y = freq, fill = second_column )) + geom_bar(stat = &quot;identity&quot;) + scale_fill_brewer(palette=&quot;Paired&quot;) df3 &lt;-df2 df3$second_column &lt;- ifelse(df3$second_column == &quot;A&quot;, &quot;C&quot;, df3$second_column) ggplot(df3, aes(x = first_column, y = freq, fill = second_column )) + geom_bar(stat = &quot;identity&quot;) + scale_fill_brewer(palette=&quot;Paired&quot;) </code></pre>
[ { "answer_id": 74438591, "author": "zephryl", "author_id": 17303805, "author_profile": "https://Stackoverflow.com/users/17303805", "pm_score": 2, "selected": false, "text": "second_column" }, { "answer_id": 74438608, "author": "stefan", "author_id": 12993861, "author_profile": "https://Stackoverflow.com/users/12993861", "pm_score": 1, "selected": false, "text": "scale_fill_manual" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6473874/" ]
74,438,362
<p>I'm trying to figure out what I need to do in order to have lib/graphql recognise the mutations I have made.</p> <p>I have an issue.tsx (which is a form). It imports:</p> <pre><code>import { IssueInput, useUpdateIssueMutation, useAllIssuesQuery, useCreateIssueMutation, useDeleteIssueMutation, Issue as IssueGQLType, } from &quot;lib/graphql&quot; </code></pre> <p>Other than IssueInput and Issue, I'm getting errors in my terminal that say these queries and mutations are not exported members.</p> <p>However when I try to load the issue page in local host, I get an error that says:</p> <blockquote> <p>error - GraphQLError [Object]: Syntax Error: Expected Name, found . It points to the line where Issue is imported.</p> </blockquote> <p>I made all of these queries and mutations in my resolver as follows:</p> <pre><code>import { Arg, Mutation, Query, Resolver } from &quot;type-graphql&quot; import { Issue } from &quot;./issue.model&quot; import { IssueService } from &quot;./issue.service&quot; import { IssueInput } from &quot;./inputs/create.input&quot; import { Inject, Service } from &quot;typedi&quot; import { UseAuth } from &quot;../shared/middleware/UseAuth&quot; import { Role } from &quot;@generated&quot; @Service() @Resolver(() =&gt; Issue) export default class IssueResolver { @Inject(() =&gt; IssueService) issueService: IssueService @Query(() =&gt; [Issue]) async allIssues() { return await this.issueService.getAllIssues() } @Query(() =&gt; [Issue]) async futureRiskIssues() { return await this.issueService.getFutureRiskIssues() } @Query(() =&gt; Issue) async issue(@Arg(&quot;id&quot;) id: string) { return await this.issueService.getIssue(id) } @UseAuth([Role.ADMIN]) @Mutation(() =&gt; Issue) async createIssue(@Arg(&quot;data&quot;) data: IssueInput) { return await this.issueService.createIssue(data) } @UseAuth([Role.ADMIN]) @Mutation(() =&gt; Issue) async deleteIssue(@Arg(&quot;id&quot;) id: string) { return await this.issueService.deleteIssue(id) } @UseAuth([Role.ADMIN]) @Mutation(() =&gt; Issue) async updateIssue(@Arg(&quot;id&quot;) id: string, @Arg(&quot;data&quot;) data: IssueInput) { return await this.issueService.updateIssue(id, data) } } </code></pre> <p>I can also see from my graphql.tsx file, that these functions are recognised as follows:</p> <pre><code>export type Mutation = { __typename?: 'Mutation'; createIssue: Issue; createUser: User; deleteIssue: Issue; destroyAccount: Scalars['Boolean']; forgotPassword: Scalars['Boolean']; getBulkSignedS3UrlForPut?: Maybe&lt;Array&lt;SignedResponse&gt;&gt;; getSignedS3UrlForPut?: Maybe&lt;SignedResponse&gt;; login: AuthResponse; register: AuthResponse; resetPassword: Scalars['Boolean']; updateIssue: Issue; updateMe: User; }; export type MutationCreateUserArgs = { data: UserCreateInput; }; export type MutationDeleteIssueArgs = { id: Scalars['String']; }; export type MutationUpdateIssueArgs = { data: IssueInput; id: Scalars['String']; }; </code></pre> <p>I have run the codegen several times and can't think of anything else to try to force these mutations and queries to be recognised. Can anyone see a way to trouble shoot this?</p> <p>My codegen.yml has:</p> <pre><code>schema: http://localhost:5555/graphql documents: - &quot;src/components/**/*.{ts,tsx}&quot; - &quot;src/lib/**/*.{ts,tsx}&quot; - &quot;src/pages/**/*.{ts,tsx}&quot; overwrite: true generates: src/lib/graphql.tsx: config: withMutationFn: false addDocBlocks: false scalars: DateTime: string plugins: - add: content: &quot;/* eslint-disable */&quot; - typescript - typescript-operations - typescript-react-apollo </code></pre> <p>When I look at the mutations available on the authentication objects (that are provided with the [boilerplate app][1] that I am trying to use), I can see that there are mutations and queries that are differently represented in the lib/graphql file. I just can't figure out how to force the ones I write to be included in this way:</p> <pre><code>export function useLoginMutation(baseOptions?: Apollo.MutationHookOptions&lt;LoginMutation, LoginMutationVariables&gt;) { const options = {...defaultOptions, ...baseOptions} return Apollo.useMutation&lt;LoginMutation, LoginMutationVariables&gt;(LoginDocument, options); } </code></pre> <p>Instead, I get all of these things, but none of them look like the above and I can't figure out which one to import into my front end form so that I can make an entry in the database. None of them look like the queries or mutations I defined in my resolver</p> <pre><code>export type IssueInput = { description: Scalars['String']; issueGroup: Scalars['String']; title: Scalars['String']; }; export type IssueListRelationFilter = { every?: InputMaybe&lt;IssueWhereInput&gt;; none?: InputMaybe&lt;IssueWhereInput&gt;; some?: InputMaybe&lt;IssueWhereInput&gt;; }; export type IssueRelationFilter = { is?: InputMaybe&lt;IssueWhereInput&gt;; isNot?: InputMaybe&lt;IssueWhereInput&gt;; }; export type IssueWhereInput = { AND?: InputMaybe&lt;Array&lt;IssueWhereInput&gt;&gt;; NOT?: InputMaybe&lt;Array&lt;IssueWhereInput&gt;&gt;; OR?: InputMaybe&lt;Array&lt;IssueWhereInput&gt;&gt;; createdAt?: InputMaybe&lt;DateTimeFilter&gt;; description?: InputMaybe&lt;StringFilter&gt;; id?: InputMaybe&lt;UuidFilter&gt;; issueGroup?: InputMaybe&lt;IssueGroupRelationFilter&gt;; issueGroupId?: InputMaybe&lt;UuidFilter&gt;; subscribers?: InputMaybe&lt;UserIssueListRelationFilter&gt;; title?: InputMaybe&lt;StringFilter&gt;; updatedAt?: InputMaybe&lt;DateTimeFilter&gt;; }; export type IssueWhereUniqueInput = { id?: InputMaybe&lt;Scalars['String']&gt;; }; </code></pre> <p>I do have this record in my graphql.tsx file:</p> <pre><code>export type Mutation = { __typename?: 'Mutation'; createIssue: Issue; createIssueGroup: IssueGroup; createUser: User; deleteIssue: Issue; deleteIssueGroup: IssueGroup; destroyAccount: Scalars['Boolean']; forgotPassword: Scalars['Boolean']; getBulkSignedS3UrlForPut?: Maybe&lt;Array&lt;SignedResponse&gt;&gt;; getSignedS3UrlForPut?: Maybe&lt;SignedResponse&gt;; login: AuthResponse; register: AuthResponse; resetPassword: Scalars['Boolean']; updateIssue: Issue; updateIssueGroup: IssueGroup; updateMe: User; }; </code></pre> <p>but I can't say: createIssueMutation as an import in my issue.tsx where I'm trying to make a form to use to post to the database. [1]: <a href="https://github.com/NoQuarterTeam/boilerplate" rel="nofollow noreferrer">https://github.com/NoQuarterTeam/boilerplate</a></p> <p>In the issue form, I get an error that says:</p> <blockquote> <p>&quot;resource&quot;: &quot;/.../src/pages/issue.tsx&quot;, &quot;owner&quot;: &quot;typescript&quot;, &quot;code&quot;: &quot;2305&quot;, &quot;severity&quot;: 8, &quot;message&quot;: &quot;Module '&quot;lib/graphql&quot;' has no exported member 'useCreateIssueMutation'.&quot;, &quot;source&quot;: &quot;ts&quot;, &quot;startLineNumber&quot;: 7, &quot;startColumn&quot;: 27, &quot;endLineNumber&quot;: 7, &quot;endColumn&quot;: 54 }]</p> </blockquote> <p>and the same thing for the query</p>
[ { "answer_id": 74532530, "author": "ani chan", "author_id": 18066948, "author_profile": "https://Stackoverflow.com/users/18066948", "pm_score": 1, "selected": false, "text": "overwrite: true\nschema: \"http://localhost:4000/graphql\"\ndocuments: \"src/graphql/**/*.graphql\"\ngenerates:\n src/generated/graphql.tsx:\n plugins:\n - \"typescript\"\n - \"typescript-operations\"\n - \"typescript-react-apollo\"\n ./graphql.schema.json:\n plugins:\n - \"introspection\"\n\n" }, { "answer_id": 74658543, "author": "Friedrich", "author_id": 2689500, "author_profile": "https://Stackoverflow.com/users/2689500", "pm_score": 0, "selected": false, "text": "codegen.yml" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2860931/" ]
74,438,413
<p>I am new to react and am trying to build a simple app however am having trouble accessing objects within objects.</p> <p>I have tried to replace the FlatList with a VirtualizedList like the documentation suggests when the data is not a plain array, however this also did not work. Is there a proper way of tackling this issue or do I just have to get creative with how I format my data?</p> <p>Code:</p> <pre><code>const Owe = ({navigation, route}) =&gt; { return ( &lt;SafeAreaView&gt; &lt;FlatList data={information} renderItem={({item}) =&gt; &lt;View style={flatListStyle.container}&gt; &lt;Text style={titleBar.Text}&gt;{route.data.message}&lt;/Text&gt; &lt;/View&gt;} /&gt; &lt;/SafeAreaView&gt; ); } var information = [ {nme:&quot;Joe&quot;, data: [ {owed:true, amount: 10, message:&quot;Beer Money&quot;}, {owed:false,amount: 5, message:&quot;Lunch&quot;} ]}, {nme:&quot;Ben&quot;, data:[ {owed:true, amount: 50, message:&quot;Broke bitch&quot;}, {owed:false, amount: 12.50, message:&quot;Milk&quot;} ]} ]; </code></pre> <p>Error message: &quot;undefined is not an object (evaluating route.data.message)&quot;</p>
[ { "answer_id": 74532530, "author": "ani chan", "author_id": 18066948, "author_profile": "https://Stackoverflow.com/users/18066948", "pm_score": 1, "selected": false, "text": "overwrite: true\nschema: \"http://localhost:4000/graphql\"\ndocuments: \"src/graphql/**/*.graphql\"\ngenerates:\n src/generated/graphql.tsx:\n plugins:\n - \"typescript\"\n - \"typescript-operations\"\n - \"typescript-react-apollo\"\n ./graphql.schema.json:\n plugins:\n - \"introspection\"\n\n" }, { "answer_id": 74658543, "author": "Friedrich", "author_id": 2689500, "author_profile": "https://Stackoverflow.com/users/2689500", "pm_score": 0, "selected": false, "text": "codegen.yml" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18259036/" ]
74,438,416
<p>I am new to Java and was trying to write code that would tell you how much change you would receive for a given amount of money (in minimum number of coins). For example <strong>$0.31</strong> would give <strong>1 quarters, 0 dimes, 1 nickels, 1 pennies</strong>.</p> <p>I got to a point where my code seemed to work. However, while most values work, specifically any multiple of 0.41 doesn't work (ex. 0.41, 0.82 ...). For example <strong>$0.41</strong> results in <strong>1 quarters, 1 dimes, 1 nickels, 0 pennies</strong>, which only adds up to $0.40.</p> <p>Here is my code:</p> <pre><code>import java.util.Scanner; public class Cash { public static void main(String[] args){ Scanner scanner_obj = new Scanner(System.in); System.out.print(&quot;Enter Amount: $&quot;); double amount = Double.parseDouble(scanner_obj.nextLine()); double[] change = calc_Change(amount); System.out.println(change[0] + &quot; Quarters&quot;); System.out.println(change[1] + &quot; Dimes&quot;); System.out.println(change[2] + &quot; Nickels&quot;); System.out.println(change[3] + &quot; Pennies&quot;); System.out.println(check_Change(amount, change)); } public static double[] calc_Change(double amount){ double[] change = {0, 0, 0, 0}; while (amount &gt;= 0.25){amount -= 0.25; change[0] += 1;} while (amount &gt;= 0.10){amount -= 0.10; change[1] += 1;} while (amount &gt;= 0.05){amount -= 0.05; change[2] += 1;} while (amount &gt;= 0.01){amount -= 0.01; change[3] += 1;} return change; } public static boolean check_Change(double amount, double[] change){ double total = change[0]*0.25 + change[1]*0.10 + change[2]*0.05 + change[3]*0.01; System.out.println(amount + &quot; vs &quot; + total); return (amount == total); } } </code></pre> <p>I was using the check_Change function to check my results.</p> <p>I don't know why this doesn't work and why it is only certain numbers.</p>
[ { "answer_id": 74438720, "author": "synapticloop", "author_id": 20489149, "author_profile": "https://Stackoverflow.com/users/20489149", "pm_score": 2, "selected": true, "text": "0.41\n0.15999999999999998\n0.05999999999999997\n0.009999999999999967\n" }, { "answer_id": 74438844, "author": "sic-sic", "author_id": 5318914, "author_profile": "https://Stackoverflow.com/users/5318914", "pm_score": 0, "selected": false, "text": "public class Cash {\n public static void main(String[] args){\n Scanner scanner_obj = new Scanner(System.in);\n\n System.out.print(\"Enter Amount: $\");\n BigDecimal amount = new BigDecimal(scanner_obj.nextLine());\n double[] change = calc_Change(amount);\n\n System.out.println(change[0] + \" Quarters\");\n System.out.println(change[1] + \" Dimes\");\n System.out.println(change[2] + \" Nickels\");\n System.out.println(change[3] + \" Pennies\");\n\n System.out.println(check_Change(amount, change));\n }\n\n public static double[] calc_Change(BigDecimal amount){\n double[] change = {0, 0, 0, 0};\n\n while (amount.doubleValue() >= 0.25){\n amount = amount.subtract(new BigDecimal(\"0.25\")); change[0]+=1;\n }\n while (amount.doubleValue() >= 0.10){\n amount = amount.subtract(new BigDecimal(\"0.10\")); change[1] += 1;\n }\n while (amount.doubleValue() >= 0.05){\n amount = amount.subtract(new BigDecimal(\"0.05\")); change[2] += 1;\n }\n while (amount.doubleValue() >= 0.01){\n amount = amount.subtract(new BigDecimal(\"0.01\")); change[3] += 1;\n }\n\n return change;\n }\n\n public static boolean check_Change(BigDecimal amount, double[] change){\n double v1 = change[0] * 0.25;\n double v2 = change[1] * 0.10;\n double v3 = change[2] * 0.05;\n double v4 = change[3] * 0.01;\n double total = v1 + v2 + v3 + v4;\n System.out.println(amount + \" vs \" + total);\n\n return (amount.doubleValue() == total);\n }\n}\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20504678/" ]
74,438,430
<p>I created this custom hook to fetch (in this case listen to) a document in firestore:</p> <pre><code>import { doc, onSnapshot } from 'firebase/firestore'; import { useEffect, useState } from 'react'; import { db, auth } from '../../firebase'; function useCurrentUser() { const userId = auth.currentUser.uid; const [user, setUser] = useState({}); const [isUserLoading, setIsUserLoading] = useState(false); const [isUserError, setIsUserError] = useState(null); useEffect(() =&gt; { const getUser = async () =&gt; { try { setIsUserLoading(true); const userRef = doc(db, 'users', userId); const unsub = await onSnapshot(userRef, doc =&gt; { setUser(doc.data()); }); } catch (error) { setIsUserError(error); } finally { setIsUserLoading(false); } }; getUser(); }, []); return { user, isUserLoading, isUserError }; } export default useCurrentUser; </code></pre> <p>The problem is: <code>isUserLoading</code> is always returning <code>false</code> even though in the <code>try</code> statement, I'm setting it to <code>true</code></p> <p>Any idea why this is happening?</p>
[ { "answer_id": 74438475, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 2, "selected": true, "text": "onSnapshot" }, { "answer_id": 74438493, "author": "Temba", "author_id": 3593621, "author_profile": "https://Stackoverflow.com/users/3593621", "pm_score": 0, "selected": false, "text": "true" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15637129/" ]
74,438,498
<p>I want to write a function that finds certain word combinations in text and tells it belongs to which list. Example:</p> <pre><code>my_list1 = [&quot;Peter Parker&quot;, &quot;Eddie Brock&quot;] my_list2 = [&quot;Harry Potter&quot;, &quot;Severus Snape&quot;, &quot;Dumbledore&quot;] Example input: &quot;Harry Potter was very sad&quot; Example output: my_list1 </code></pre>
[ { "answer_id": 74438475, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 2, "selected": true, "text": "onSnapshot" }, { "answer_id": 74438493, "author": "Temba", "author_id": 3593621, "author_profile": "https://Stackoverflow.com/users/3593621", "pm_score": 0, "selected": false, "text": "true" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7775099/" ]
74,438,540
<p>I wanted to print each individual element of a list that's in nested list. it should also print symbols to show where the different lists end. There are only going to be 3 lists total in the big list.</p> <p>For Example,</p> <pre><code>list1 = [['assign1', 'assign2'], ['final,'assign4'], ['exam','study']] </code></pre> <p>Output should be:</p> <pre><code>###################### assign1 assign2 ###################### ---------------------- final assign4 ---------------------- ************************* exam study ************************* </code></pre> <p>I know that to print an element in a normal list it is: for element in list1: print element</p> <p>I am unaware of what steps to take next.</p>
[ { "answer_id": 74438475, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 2, "selected": true, "text": "onSnapshot" }, { "answer_id": 74438493, "author": "Temba", "author_id": 3593621, "author_profile": "https://Stackoverflow.com/users/3593621", "pm_score": 0, "selected": false, "text": "true" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20495138/" ]
74,438,555
<p>I'm a complete novice at python and am trying to list the first n positive numbers, where n is an inputted value. E.g. when n=5, I want to output 5, 4, 3, 2 and 1.</p> <p>This is my code which doesn't work:</p> <pre><code>n= int(input(&quot;Please enter a number: &quot;)) i=0 while i&lt;n: print(n) n=n-1 i=i+1 </code></pre> <p>I know I can answer the question with this code:</p> <pre><code>n= int(input(&quot;Please enter a number: &quot;)) i=n while i&gt;0: print(i) i=i-1 </code></pre> <p>but would like to understand why what I tried at the beginning is not working.</p>
[ { "answer_id": 74438612, "author": "ChrisSc", "author_id": 16872665, "author_profile": "https://Stackoverflow.com/users/16872665", "pm_score": 2, "selected": false, "text": "False" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16824530/" ]
74,438,566
<p>I have a dataframe (df) that has three columns (user, vector, and group name), the vector column with multiple comma-separated values in each row.</p> <pre><code>df = pd.DataFrame({'user': ['user_1', 'user_2', 'user_3', 'user_4', 'user_5', 'user_6'], 'vector': [[1, 0, 2, 0], [1, 8, 0, 2],[6, 2, 0, 0], [5, 0, 2, 2], [3, 8, 0, 0],[6, 0, 0, 2]], 'group': ['A', 'B', 'C', 'B', 'A', 'A']}) </code></pre> <p>I would like to calculate for each group, the sum of dimensions in all rows divided by the total number of rows for this group.</p> <p>For example: For group, A is <code>[(1+3+6)/3, (0+8+0)/3, (2+0+0)/3, (0+0+2)/3] = [3.3, 2.6, 0.6, 0.6]</code>.</p> <p><a href="https://i.stack.imgur.com/hC0Kx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hC0Kx.png" alt="enter image description here" /></a></p> <p>For group, B is <code>[(1+5)/2, (8+0)/2, (0+2)/2, (2+2)/2] = [3,4,1,2].</code></p> <p>For group, C is <code>[6, 2, 0, 0]</code></p> <p>So, the expected result is an array:</p> <pre><code>group A: [3.3, 2.6, 0.6, 0.6] group B: [3,4,1,2] group C: [6, 2, 0, 0] </code></pre>
[ { "answer_id": 74438706, "author": "markd227", "author_id": 13650733, "author_profile": "https://Stackoverflow.com/users/13650733", "pm_score": 1, "selected": false, "text": "for group in df.group.unique():\n print(f'Group {group} results: ')\n tmp_df = pd.DataFrame(df[df.group==group]['vector'].tolist())\n print(tmp_df.mean().values)\n" }, { "answer_id": 74438849, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 0, "selected": false, "text": "import numpy as np\n\nout = (df.groupby('group')['vector']\n .agg(lambda x: np.vstack(x).mean(0).round(2))\n )\n\nprint(out)\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17289012/" ]
74,438,649
<p>Need to prevent the main image on the product page from lazy loading.</p> <p>The main product image is loaded in 'woocommerce/single-product/product-image.php'</p> <p>It uses: wp_get_attachment_image( $attachment_id, $size, $icon, $attr ); to get the image.</p> <p>Inside the function above, there is:</p> <pre><code>// Add `loading` attribute. if ( wp_lazy_loading_enabled( 'img', 'wp_get_attachment_image' ) ) { $default_attr['loading'] = wp_get_loading_attr_default( 'wp_get_attachment_image' ); } $attr = wp_parse_args( $attr, $default_attr ); // If the default value of `lazy` for the `loading` attribute is overridden // to omit the attribute for this image, ensure it is not included. if ( array_key_exists( 'loading', $attr ) &amp;&amp; ! $attr['loading'] ) { unset( $attr['loading'] ); } </code></pre> <p>So clearly it's possible to not lazy load it, but I just don't fully understand how I can do this?</p>
[ { "answer_id": 74438706, "author": "markd227", "author_id": 13650733, "author_profile": "https://Stackoverflow.com/users/13650733", "pm_score": 1, "selected": false, "text": "for group in df.group.unique():\n print(f'Group {group} results: ')\n tmp_df = pd.DataFrame(df[df.group==group]['vector'].tolist())\n print(tmp_df.mean().values)\n" }, { "answer_id": 74438849, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 0, "selected": false, "text": "import numpy as np\n\nout = (df.groupby('group')['vector']\n .agg(lambda x: np.vstack(x).mean(0).round(2))\n )\n\nprint(out)\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19337048/" ]
74,438,653
<p>When launching a JNLP application with Java 8 update 351, the following error is received:</p> <blockquote> <p>**``` ERROR: Unsigned application requesting unrestricted access to system Unsigned resoured: xyz.jar</p> <pre><code></code></pre> </blockquote> <p>The release notes for update 351 include &quot;JARs signed with SHA-1 algorithms are now restricted by default and treated as if they were unsigned.&quot;</p> <p>There is a suggested workaround of &quot;set allow_weak_crypto = true in the krb5.conf configuration file to re-enable them&quot;, but there is no krb5.conf file anywhere to be found (Windows 10 install).</p> <p>Has anyone encountered and resolved this issue? Thank you.</p> <p>Looked for krb5.conf file, could not find any.</p>
[ { "answer_id": 74438706, "author": "markd227", "author_id": 13650733, "author_profile": "https://Stackoverflow.com/users/13650733", "pm_score": 1, "selected": false, "text": "for group in df.group.unique():\n print(f'Group {group} results: ')\n tmp_df = pd.DataFrame(df[df.group==group]['vector'].tolist())\n print(tmp_df.mean().values)\n" }, { "answer_id": 74438849, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 0, "selected": false, "text": "import numpy as np\n\nout = (df.groupby('group')['vector']\n .agg(lambda x: np.vstack(x).mean(0).round(2))\n )\n\nprint(out)\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8786514/" ]
74,438,656
<p>I'm working on a school assignment. I am writing a program that utilizes <code>union</code>s to convert a given IP address in &quot;192.168.1.10&quot; format into its 32-bit single value, two 16-bit values, and four 8-bit values.</p> <p>I'm having trouble with implementing my <code>struct</code>s and <code>union</code>s appropriately, and am looking for insight on the subject. To my understanding, <code>union</code>s point to the same location as the referenced <code>struct</code>, but can look at specified pieces.</p> <p>Any examples showing how a <code>struct</code> with four 8-bit values and a <code>union</code> can be used together would help. Also, any articles or books that might help me would also be appreciated.</p> <p>Below is the assignment outline:</p> <blockquote> <p>Create a program that manages an IP address. Allow the user to enter the IP address as four 8 bit unsigned integer values (just use 4 sequential CIN statements). The program should output the IP address upon the users request as any of the following. As a single 32 bit unsigned integer value, or as four 8 bit unsigned integer values, or as 32 individual bit values which can be requested as a single bit by the user (by entering an integer 0 to 31). Or as all 32 bits assigned into 2 variable sized groups (host group and network group) and outputted as 2 unsigned integer values from 1 bit to 31 bits each.</p> </blockquote> <p>I was going to <code>cin</code> to <code>int pt1,pt2,pt3,pt4</code> and assign them to the <code>IP_Adress.pt1</code>, .... etc.</p> <pre><code>struct IP_Adress { unsigned int pt1 : 8; unsigned int pt2 : 8; unsigned int pt3 : 8; unsigned int pt4 : 8; }; </code></pre> <p>I have not gotten anything to work appropriately yet. I think I am lacking a true understanding of the implementation of <code>union</code>s.</p>
[ { "answer_id": 74439099, "author": "Remy Lebeau", "author_id": 65863, "author_profile": "https://Stackoverflow.com/users/65863", "pm_score": 2, "selected": false, "text": "union" }, { "answer_id": 74439100, "author": "user4581301", "author_id": 4581301, "author_profile": "https://Stackoverflow.com/users/4581301", "pm_score": 1, "selected": false, "text": "union bad_idea\n{\n uint32_t ints; // 32 bit unsigned integer\n uint8_t bytes[sizeof(uint32_t)]; // 4 8 bit unsigned integers\n};\n" }, { "answer_id": 74587462, "author": "Danial", "author_id": 4488770, "author_profile": "https://Stackoverflow.com/users/4488770", "pm_score": 0, "selected": false, "text": "#define word8 uint8_t\n#define word16 uint16_t\n#define word32 uint32_t\n\nchar *sIP = \"192.168.0.11\";\n\nmain(){\n word32 ip, *pIP;\n\n pIP = &ip;\n inet_pton(AF_INET, sIP, pIP);\n printf(\"32bit:%u %x\\n\", *pIP, *pIP);\n printf(\"16bit:%u %u\\n\", *(word16*)pIP, *(((word16*)pIP)+1));\n printf(\"8bit:%u %u %u %u\\n\", *(word8*)pIP, *(((word8*)pIP)+1),*(((word8*)pIP)+2),*(((word8*)pIP)+3));\n}\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10714478/" ]
74,438,678
<p>I have a dataframe called teams. Each column is a team in the NFL, each row is how much a given fan would pay to attend a team's game. Looks like:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">team1</th> <th style="text-align: center;">team2</th> <th style="text-align: right;">team3</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">40</td> <td style="text-align: center;">NaN</td> <td style="text-align: right;">50</td> </tr> <tr> <td style="text-align: left;">NaN</td> <td style="text-align: center;">NaN</td> <td style="text-align: right;">80</td> </tr> <tr> <td style="text-align: left;">75</td> <td style="text-align: center;">30</td> <td style="text-align: right;">NaN</td> </tr> </tbody> </table> </div> <p>I want to compare the standard deviations of each column, so obviously I need to remove the NaNs. I want to do this column-wise though, so that I don't just remove all rows where one value is NaN because I'll lose a lot of data. What's the best way to do this? I have a lot of columns, otherwise I would just make a numpy array representing each column.</p>
[ { "answer_id": 74438732, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": true, "text": "std" }, { "answer_id": 74506887, "author": "chitown88", "author_id": 7752296, "author_profile": "https://Stackoverflow.com/users/7752296", "pm_score": 0, "selected": false, "text": "pandas" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14276370/" ]
74,438,687
<p>I'm trying to add a button to a customization screen in Acumatica that will run a small JavaScript function when clicked.</p> <p>I am able to type the function inside a <strong>JavaScript control</strong>, which will be called from the button's <strong>Click</strong> or <strong>MouseDown</strong> events. I can also directly type the function into any of these 2 button events, without the need of the JavaScript control.</p> <p>Using a basic <code>alert(&quot;test&quot;);</code> for testing, I can confirm the code runs, with any of the 2 methods I described above.</p> <h3>The problem:</h3> <p>Clicking on the button doesn't run the code. Instead, the message pops up right after the screen loads, and it actually does it 2 times, so it seems the function runs automatically twice on screen load.</p> <ul> <li>Is this possibly a bug? or am I doing something wrong?</li> <li>Is there a &quot;correct&quot; way or a specific set of steps to follow in order to include JavaScript code into a Customization Screen?</li> </ul> <p><em><strong>Notes:</strong></em></p> <ul> <li><em>Currently testing on Acumatica 2022 R1.</em></li> <li><em>I have tested this prior to and after publishing the screen, getting the same results.</em></li> </ul>
[ { "answer_id": 74438732, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": true, "text": "std" }, { "answer_id": 74506887, "author": "chitown88", "author_id": 7752296, "author_profile": "https://Stackoverflow.com/users/7752296", "pm_score": 0, "selected": false, "text": "pandas" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11331427/" ]
74,438,689
<p>I was just wondering if anyone can help me with this problem.</p> <p>I have two tables - Table 1 &amp; Table 2.</p> <p>What I'm trying to do is to find 2 timestamps before and after 'date' from Table 1, so everything highlighted in pink in Table 2.</p> <p>How can I do this in Microsoft SQL Server? ideally without using CTE. Unfortunately, CTE is not supported by Tableau.</p> <p>Thank you in advance.</p> <p><a href="https://i.stack.imgur.com/DQIyX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DQIyX.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74438976, "author": "John Cappelletti", "author_id": 1570000, "author_profile": "https://Stackoverflow.com/users/1570000", "pm_score": 1, "selected": false, "text": "Select Date\n ,Value\n ,ID\n From (\n Select A.Date\n ,A.Value\n ,B.ID\n ,RN1 = row_number() over (order by datediff(second,a.date,b.date) desc) \n ,RN2 = row_number() over (order by datediff(second,a.date,b.date) asc) \n From Table2 A\n Cross Join Table1 B \n ) A\n Where RN1 in (2,3)\n or RN2 in (2,3)\n Order By Date\n" }, { "answer_id": 74439048, "author": "GMB", "author_id": 10676716, "author_profile": "https://Stackoverflow.com/users/10676716", "pm_score": 0, "selected": false, "text": "table2" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18707638/" ]
74,438,697
<p>I have an array that looks like this:</p> <pre class="lang-js prettyprint-override"><code>const arr = [ { parent: 'A', children: ['B'], }, { parent: 'B', children: ['C'], }, { parent: 'C', children: ['D'] }]; </code></pre> <p>and I want to create a function that will take this array and result in the following object:</p> <pre class="lang-js prettyprint-override"><code>const result = { parent: 'A', children: [{ parent: 'B', children: [{ parent: 'C', children: [{ parent: 'D', children: [] }] }] }] }; </code></pre> <p>so the result type would look like:</p> <pre class="lang-js prettyprint-override"><code>type Result = { parent: string; children: Result[]; }; </code></pre> <p>What I've tried so far:</p> <pre class="lang-js prettyprint-override"><code>type TInput = { parent: string; children: string[]; }; type Result = { parent: string; children: Result[]; }; // can assume we know initial parent is 'A' const fn = (parent: string, inputArr: TInput[]) =&gt; { const result: TResult[] = []; let newParent: string[] = []; while (newParent.length !== 0) { const index = inputArr.findIndex( (input) =&gt; input.parent === parent ); result.push({ parent: inputArr[index].parent, children: [], // need to populate on next pass? }); newParent = inputArr[index].children; } return result; }; </code></pre> <p>I don't know how many objects will be in the input array, but can assume first object is known to be initial parent/child ('A' in the example). Any help much appreciated. Thanks</p>
[ { "answer_id": 74439273, "author": "Lucasbk38", "author_id": 20480528, "author_profile": "https://Stackoverflow.com/users/20480528", "pm_score": -1, "selected": false, "text": "ts" }, { "answer_id": 74439559, "author": "Albair", "author_id": 5179608, "author_profile": "https://Stackoverflow.com/users/5179608", "pm_score": 1, "selected": true, "text": "const arr = [\n {\n parent: 'A',\n children: ['B'],\n },\n {\n parent: 'B',\n children: ['C'],\n },\n {\n parent: 'C',\n children: ['D']\n },\n {\n parent: 'D',\n children: []\n }\n ];\n\nconst makeTree = (manyParents,rootName) => {\n // copy parent objects into a map.\n let mapIt = new Map(manyParents.map(pObject => {\n return [pObject.parent, pObject];\n }));\n \n // recreate children arrays for each parents.\n mapIt.forEach((oneParent) => {\n let newChildrenArray = [];\n //find every children objects.\n oneParent.children.forEach((oneChild) => {\n newChildrenArray.push(mapIt.get(oneChild));\n });\n //replace children array.\n oneParent.children = newChildrenArray;\n });\n return mapIt.get(rootName);\n}\n\nlet tree = makeTree(arr,'A');\nconsole.log(tree)" }, { "answer_id": 74448735, "author": "PeterKA", "author_id": 3558931, "author_profile": "https://Stackoverflow.com/users/3558931", "pm_score": 0, "selected": false, "text": "Array#reverse" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11929034/" ]
74,438,710
<pre><code>import random q = random.randint(10, 100) w = random.randint(10, 100) e = (q, &quot; * &quot;, w) r = int(input(e)) </code></pre> <p>This outputs (i.e):</p> <pre><code>&gt;&gt;&gt; (60, ' * ', 24) </code></pre> <p>I tried following <a href="https://stackoverflow.com/questions/30666310/python-removing-quotation-marks-from-called-string-in-input">this</a> post but I faced an error.</p> <p>I want output to atleast look like:</p> <pre><code>&gt;&gt;&gt; (60 * 24) </code></pre> <p>What I tried was doing</p> <pre><code>import random q = random.randint(10, 100) w = random.randint(10, 100) **e = (q + &quot; * &quot; + w)** r = int(input(e)) </code></pre> <p>Which gave me the error.</p>
[ { "answer_id": 74438735, "author": "Temba", "author_id": 3593621, "author_profile": "https://Stackoverflow.com/users/3593621", "pm_score": 3, "selected": true, "text": "e = f\"{q} * {w}\"\n" }, { "answer_id": 74438781, "author": "Tristan Bodding-Long", "author_id": 4683076, "author_profile": "https://Stackoverflow.com/users/4683076", "pm_score": 2, "selected": false, "text": "e" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20503795/" ]
74,438,744
<pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;unordered_map&gt; #include &lt;string&gt; class Solution { public: std::vector&lt;std::vector&lt;std::string&gt;&gt; groupAna(std::vector&lt;std::string&gt; strs) { std::unordered_map&lt;std::string, std::vector&lt;std::string&gt;&gt; ana; for (int i {0}; i &lt; strs.size(); ++i) { std::string key = getKey(strs[i]); ana[key].push_back(strs[i]); } std::vector&lt;std::vector&lt;std::string&gt;&gt; results; for (auto it = ana.begin(); it != ana.end(); ++it) { results.push_back(it-&gt;second); } // for (int i {0}; i &lt; results.size(); ++i) // { // for (int j {0}; j &lt; results[i].size(); ++j) // { // std::cout &lt;&lt; results[i][j] &lt;&lt; &quot; &quot;; // } // } return results; } private: std::string getKey(std::string str) { std::vector&lt;int&gt; count(26); for (int i {0}; i &lt; str.length(); ++i) { ++count[str[i] - 'a']; } std::string key {&quot;&quot;}; for (int j {0}; j &lt; 26; ++j) { key.append(std::to_string(count[j] + 'a')); } return key; } }; int main() { std::vector&lt;std::string&gt; strs ({&quot;eat&quot;,&quot;tea&quot;,&quot;tan&quot;,&quot;ate&quot;,&quot;nat&quot;,&quot;bat&quot;}); Solution obj; std::cout &lt;&lt; obj.groupAna(strs); return 0; } </code></pre> <p>I receive this error:</p> <blockquote> <p>Invalid operands to binary expression ('std::ostream' (aka 'basic_ostream&lt;char&gt;') and 'std::vector&lt;std::vector&lt;std::string&gt;&gt;' (aka 'vector&lt;vector&lt;basic_string&lt;char, char_traits&lt;char&gt;, allocator&lt;char&gt;&gt;&gt;&gt;'))</p> </blockquote> <p>This solution is for <a href="https://leetcode.com/problems/group-anagrams/" rel="nofollow noreferrer">Group Anagrams</a> on Leetcode. I'm just using XCode to practice writing out all the code needed, instead of using what Leetcode gives.</p> <p>My issue comes when calling and trying to print the <code>groupAna()</code> function in class <code>Solution</code>. I believe the error is telling me what I want to print isn't something you can print, but I have no idea if that's entirely correct.</p> <p>I'm ultimately trying to print each string inside its respective <code>vector</code>. What's commented out was a workaround that gives me what I want, but it doesn't show each word in a <code>vector</code>, so how can I tell if it's in the <code>vector</code> it's suppose to be in, other than it being in the correct order?</p> <p>Output is <code>bat tan nat eat tea ate</code></p>
[ { "answer_id": 74438822, "author": "Ted Lyngmo", "author_id": 7582247, "author_profile": "https://Stackoverflow.com/users/7582247", "pm_score": 1, "selected": false, "text": "groupAna" }, { "answer_id": 74439046, "author": "rturrado", "author_id": 260313, "author_profile": "https://Stackoverflow.com/users/260313", "pm_score": 0, "selected": false, "text": "groupAnagrams" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20504851/" ]
74,438,797
<p>So i'am working around an exercise that should be a very basic and easy function</p> <p>Whish takes as argument a string and a list and should return None if there string is not in the list and return some list where the string has been removed from the list. This is an 2015 exam set i am practising and using List. functions is not allowed</p> <p>So far i've managed to come up with this</p> <pre><code>let rec fromShelf bs ls = match ls with |[] -&gt; None |h::tl when h=bs -&gt; Some tl |h::tl -&gt; Some (h::Option.get(fromShelf bs tl)) </code></pre> <p>However this loop will run forever in case the string is not in the list and i'am suppose to preserve the list while iterating so i am really stuck.. would appreciate any help or hints.</p>
[ { "answer_id": 74439853, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 1, "selected": false, "text": "None" }, { "answer_id": 74445713, "author": "MrD at KookerellaLtd", "author_id": 2088029, "author_profile": "https://Stackoverflow.com/users/2088029", "pm_score": 0, "selected": false, "text": "let weirdFilter bs ls =\n let rec weirdFilterInner bs ls isFound =\n match ls with\n | [] when isFound = true -> \n Some []\n | [] -> \n None\n | h :: tl when h = bs -> \n weirdFilterInner bs tl true\n | h :: tl -> \n match weirdFilterInner bs tl isFound with\n | None -> \n None\n | Some xs -> \n Some (h :: xs)\n weirdFilterInner bs ls false\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20478173/" ]
74,438,807
<p>I tried this code:</p> <pre><code>string Input = TextBox1.Text; string[] splitX = Regex.Split(Input, @&quot;(?&lt;=[|if|and|but|so|when|])&quot;); </code></pre> <p>Often this regular expression is applied @&quot;(?&lt;=[.?!])&quot;) to split a text into sentences. But I need to use words as a delimiter to split the text..</p>
[ { "answer_id": 74438904, "author": "wlyles", "author_id": 2494394, "author_profile": "https://Stackoverflow.com/users/2494394", "pm_score": 1, "selected": false, "text": "[]" }, { "answer_id": 74439164, "author": "flyte", "author_id": 3618341, "author_profile": "https://Stackoverflow.com/users/3618341", "pm_score": 0, "selected": false, "text": "string[] delimiters = {\"if\", \"and\", \"but\", \"so\", \"when\" };\nvar parts = srcString.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20465780/" ]
74,438,823
<p>I am unable to get a connection working using <a href="https://github.com/aws-samples/cloud9-to-power-vscode-blog/blob/main/scripts/ssm-proxy.sh" rel="nofollow noreferrer">this ssm-proxy.sh script</a> to remote connect to AWS Cloud9 from Visual Studio Code. I am following <a href="https://aws.amazon.com/blogs/architecture/field-notes-use-aws-cloud9-to-power-your-visual-studio-code-ide/" rel="nofollow noreferrer">this article</a> on how to use AWS Cloud9 to power my Visual Studio Code IDE. I am able to connect by SSH but not when invoking the proxy script.</p> <p>This works:</p> <pre><code>Host test1 HostName xx.xxx.xxx.xx User ec2-user IdentityFile ~/.ssh/vscloud9 </code></pre> <p>However, this doesn't:</p> <pre><code>Host cloud9 IdentityFile ~/.ssh/vscloud9 User ec2-user HostName i-xxxxxxxxxxxxx ProxyCommand sh -c &quot;~/.ssh/ssm-proxy.sh %h %p&quot; </code></pre> <p>Using the AWS CLI I have configured the default named profile with an access key and secret and output of json. Despite it being bad practice, the access key and secret is for the root user so permissions are not causing an issue. This is then detailed in ssm-proxy.sh:</p> <pre><code>AWS_PROFILE='default' AWS_REGION='eu-west-2' MAX_ITERATION=5 SLEEP_DURATION=5 </code></pre> <p>SSH from anywhere is enabled in security groups.</p> <p>Since plain SSH works with the vscloud9 key, the key pair isn't the issue. I am thinking that the problem is either the AWS profile or the ssm-proxy.sh script itself.</p> <p>I am using the Remote - SSH VSCode extension.</p> <p>I need to get this working so I'm wondering if anyone has any idea why this wouldn't work?</p> <p>SSH output in response to Anton in comments:</p> <pre><code>OpenSSH_9.0p1, LibreSSL 3.3.6 debug1: Reading configuration data /Users/myname/.ssh/config debug1: /Users/myname/.ssh/config line 6: Applying options for cloud9 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: Executing proxy command: exec sh -c &quot;~/.ssh/ssm-proxy.sh i-xxxxxxxxxxxxxx 22&quot; debug1: identity file /Users/myname/.ssh/vscloud9 type 0 debug1: identity file /Users/myname/.ssh/vscloud9-cert type -1 debug1: Local version string SSH-2.0-OpenSSH_9.0 debug1: kex_exchange_identification: banner line 0: { debug1: kex_exchange_identification: banner line 1: &quot;StartingInstances&quot;: [ debug1: kex_exchange_identification: banner line 2: { debug1: kex_exchange_identification: banner line 3: &quot;CurrentState&quot;: { debug1: kex_exchange_identification: banner line 4: &quot;Code&quot;: 0, debug1: kex_exchange_identification: banner line 5: &quot;Name&quot;: &quot;pending&quot; debug1: kex_exchange_identification: banner line 6: }, debug1: kex_exchange_identification: banner line 7: &quot;InstanceId&quot;: &quot;i-xxxxxxxxxxxxxx&quot;, debug1: kex_exchange_identification: banner line 8: &quot;PreviousState&quot;: { debug1: kex_exchange_identification: banner line 9: &quot;Code&quot;: 80, debug1: kex_exchange_identification: banner line 10: &quot;Name&quot;: &quot;stopped&quot; debug1: kex_exchange_identification: banner line 11: } debug1: kex_exchange_identification: banner line 12: } debug1: kex_exchange_identification: banner line 13: ] debug1: kex_exchange_identification: banner line 14: } kex_exchange_identification: Connection closed by remote host Connection closed by UNKNOWN port 65535 </code></pre>
[ { "answer_id": 74614622, "author": "Aniruddh Parihar", "author_id": 8031784, "author_profile": "https://Stackoverflow.com/users/8031784", "pm_score": 0, "selected": false, "text": "type: All traffic, Protocol: All, Ports: All, Destination: 0.0.0.0/0\n" }, { "answer_id": 74614656, "author": "Kia", "author_id": 17338535, "author_profile": "https://Stackoverflow.com/users/17338535", "pm_score": -1, "selected": false, "text": "Host cloud9\n HostName xx.xxx.xxx.xx\n User ec2-user\n IdentityFile ~/.ssh/vscloud9\n ProxyCommand sh -c \"~/.ssh/ssm-proxy.sh %h %p\"\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1788377/" ]
74,438,840
<p>The Excel formula XMATCH has a third argument that returns a value if the value being tested is EITHER greater OR less than the list of values. I need it to return a numeric value in all cases - Less than the minimum (7 in the example below), within the values (1-7 in the example) or greater than the maximum (1 in the example) .</p> <p>Example <a href="https://i.stack.imgur.com/cdnyV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cdnyV.png" alt="enter image description here" /></a></p> <p>I'm trying to avoid an IF that tests for #N/A. The real use of the XMATCH in this case is inside an INDEX function and it gets hard to read / debug with extra IF logic. <a href="https://i.stack.imgur.com/ku2iX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ku2iX.png" alt="enter image description here" /></a></p> <p>Any suggestions?</p>
[ { "answer_id": 74614622, "author": "Aniruddh Parihar", "author_id": 8031784, "author_profile": "https://Stackoverflow.com/users/8031784", "pm_score": 0, "selected": false, "text": "type: All traffic, Protocol: All, Ports: All, Destination: 0.0.0.0/0\n" }, { "answer_id": 74614656, "author": "Kia", "author_id": 17338535, "author_profile": "https://Stackoverflow.com/users/17338535", "pm_score": -1, "selected": false, "text": "Host cloud9\n HostName xx.xxx.xxx.xx\n User ec2-user\n IdentityFile ~/.ssh/vscloud9\n ProxyCommand sh -c \"~/.ssh/ssm-proxy.sh %h %p\"\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1591729/" ]
74,438,860
<p>I have this code:</p> <pre><code>arr=pd.date_range(start='1/1/2021', end='12/31/2021 23:00:00', freq='h') df = pd.DataFrame({'year': arr.year}) dg = pd.DataFrame({'month': arr.month}) dh = pd.DataFrame({'day': arr.day}) di = pd.DataFrame({'hour': arr.hour,'minute': arr.minute,'second': arr.second}) </code></pre> <p>I would like to get a csv format with an hourly frequency like this: &quot;day,month,year,hour am&quot; or &quot;day,month,year,hour pm&quot;</p>
[ { "answer_id": 74438899, "author": "AD DAB", "author_id": 19599752, "author_profile": "https://Stackoverflow.com/users/19599752", "pm_score": 2, "selected": false, "text": "timevalue_12hour = time.strftime( \"%I:%M %p\", t )\n" }, { "answer_id": 74438911, "author": "D.Manasreh", "author_id": 7509907, "author_profile": "https://Stackoverflow.com/users/7509907", "pm_score": 0, "selected": false, "text": ".strftime" }, { "answer_id": 74438937, "author": "Alexandr Abramov", "author_id": 2594844, "author_profile": "https://Stackoverflow.com/users/2594844", "pm_score": 0, "selected": false, "text": "df = pd.DataFrame({\n \"year\": arr.strftime(\"%Y\"),\n \"month\": arr.strftime(\"%m\"),\n \"day\": arr.strftime(\"%d\"),\n \"hour pm\": arr.strftime(\"%H:%M:%S %p\"),\n})\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20293646/" ]
74,438,879
<p>I have an iframe that changes src pages when the page would normally switch to another page so that my main JS file can continue running in the background. For the first page, the one defined in the HTML src for the Iframe, I can access the inner document just fine by using iframe.contentDocument.</p> <p>However, when I change the src, the contentDocument does not change with it, and I cannot access the Iframe's document in the JS at all.</p> <p>So is there any way to access the new document of an Iframe after changing its source in JS? Or is there an easier alternative for the way I am doing things? Thanks.</p> <p>How I've tried:</p> <pre><code>iframe.src = &quot;pages/home/home.html&quot; innerDoc = iframe.contentDocument || iframe.contentWindow.document </code></pre> <p>and the innerDoc does not change from the original page. I've even tried making an entirely new Iframe that never had the original page as its src</p> <pre><code>document.body.removeChild(iframe) let i = document.createElement('iframe') i.src='pages/home/home.html' document.body.appendChild(i) innerDoc = i.contentDocument || i.contentWindow.document </code></pre> <p>This just makes innerDoc an empty HTML document with an empty head and body.</p>
[ { "answer_id": 74449934, "author": "Mister Jojo", "author_id": 10669010, "author_profile": "https://Stackoverflow.com/users/10669010", "pm_score": 0, "selected": false, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <title>main Page</title>\n <style>\n body { font-size: 16px; font-family: Arial, Helvetica, sans-serif; }\n iframe { width: 24em; height: 15em; border:3px solid blue; }\n #get-iframe-info { width: 24em; border: 1px solid orange; padding: .5em; }\n </style>\n </head>\n<body>\n <h4>main page</h4>\n\n <p>parent input :\n <input id=\"in-txt\" type=\"text\" placeholder=\"type something\">\n <button id=\"Bt-Send2iFrame\">Send2iFrame</button>\n </p>\n\n <p> iframe part : <br>\n <iframe id=\"iFrame-01\" src=\"page_iFrame.html\" frameborder=\"0\"></iframe>\n </p>\n\n <p id=\"get-iframe-info\">iframe return: <br>> &nbsp; \n <span></span> \n </p>\n\n <script>\n const\n inTxt = document.querySelector('#in-txt')\n , btSend = document.querySelector('#Bt-Send2iFrame')\n , iFrame01_ct = document.querySelector('#iFrame-01').contentWindow\n , sp_getiFram = document.querySelector('#get-iframe-info span')\n ;\n btSend.onclick =_=>\n {\n let info = { txt: inTxt.value }\n iFrame01_ct.postMessage( JSON.stringify(info), \"*\")\n }\n window.onmessage=e=>\n {\n let info = JSON.parse( e.data )\n sp_getiFram.textContent = info.txt \n }\n </script>\n</body>\n</html> \n" }, { "answer_id": 74450217, "author": "Ryan Wheale", "author_id": 264794, "author_profile": "https://Stackoverflow.com/users/264794", "pm_score": 1, "selected": false, "text": "contentWindow" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20055980/" ]
74,438,887
<p>I need to parse the line similar to the:</p> <pre><code>'''Object{identifier='d6e461c5-fd55-42cb-b3e8-40072670fd0f', name='some_name2', identifier='d6e461c5-fd55-42cb-b3e8-40072670fd0f', name='some_name3', value=value_without_quotes}''' </code></pre> <p>The line is much longer, but the pattern is the same.</p> <p>Basically, I need a list (or dict) with key, value. Something like:</p> <pre><code>[&quot;'identifier', ''d6e461c5-fd55-42cb-b3e8-40072670fd0f''&quot;, &quot;'name', ''some_name2''&quot;, &quot;'identifier', ''d6e461c5-fd55-42cb-b3e8-40072670fd0f''&quot;, &quot;'name', ''some_name3''&quot;, &quot;'value', 'value_without_quotes'&quot;] </code></pre> <p>I ended up with the following regular expression:</p> <pre><code>r'Object{(+?)=(+?)}' </code></pre> <p>It works only if I need the only one object. I'm expecting something like</p> <pre><code>((+?)=(+?),)+ </code></pre> <p>to be worked, but it's not. For example,</p> <pre><code>re.match(r'Object{((.+?)=(.+?),?)+}', line3).groups() </code></pre> <p>Gives me:</p> <pre><code>(&quot;some_name3', value=value_without_quotes&quot;, &quot;some_name3', value&quot;, 'value_without_quotes') </code></pre> <p>As you can see 'value=value_without_quotes' appeared. r'Object{(([^=]+?)=(.+?),?)+}' doesn't work also.</p> <p>So the question is how to repeat the above in sequence? The thing is that I don't if the value contains quotes, symbols or digits.</p> <p>Thank you</p>
[ { "answer_id": 74439007, "author": "HoliSimo", "author_id": 10419454, "author_profile": "https://Stackoverflow.com/users/10419454", "pm_score": 3, "selected": true, "text": "sentence = '''Object{identifier='d6e461c5-fd55-42cb-b3e8-40072670fd0f', name='some_name2', identifier='d6e461c5-fd55-42cb-b3e8-40072670fd0f', name='some_name3', value=value_without_quotes}'''\nlisting = [couple.split(\"=\") for couple in sentence.split(\",\")]\n" }, { "answer_id": 74439381, "author": "Ignatius Reilly", "author_id": 15032126, "author_profile": "https://Stackoverflow.com/users/15032126", "pm_score": 1, "selected": false, "text": "line3 = '''Object{identifier='d6e461c5-fd55-42cb-b3e8-40072670fd0f', name='some_name2', identifier='d6e461c5-fd55-42cb-b3e8-40072670fd0f', name='some_name3', value=value_without_quotes}'''\n\npattern = r'[{\\s](.+?)=(.+?)[}\\s,]'\nmatch = re.findall(pattern, line3)\n[item for key_value_pair in match for item in key_value_pair]\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19070565/" ]
74,438,906
<p>I have a dataset where I would like to remove all rows where the date is 4/1/2022 within a column in my dataset. The Date column is datetime64ns</p> <p><strong>Data</strong></p> <pre><code>ID Date AA 1/1/2022 BB 1/1/2022 CC 4/1/2022 </code></pre> <p><strong>Desired</strong></p> <pre><code>ID Date AA 1/1/2022 BB 1/1/2022 </code></pre> <p><strong>Doing</strong></p> <pre><code> new = df[df['Date'].str.contains('4/1/2022')==False] </code></pre> <p>However, this is not a string, it is datetime. This is not removing the rows at all. I am still researching. Any suggestion is appreciated.</p>
[ { "answer_id": 74439037, "author": "wwnde", "author_id": 8986975, "author_profile": "https://Stackoverflow.com/users/8986975", "pm_score": 1, "selected": false, "text": "df[~df['Date'].astype(str).str.contains('4/1/2022')]\n" }, { "answer_id": 74439041, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "df[df['Date'].ne('2022-04-01')]\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5942100/" ]
74,438,914
<p>Ok so i am making a gen bot for me and my friends and i wanted to know how do i make my bot reply to the message with a account from a .txt file that i put in the folder with the bot please help me thank you</p> <p>i tried `</p> <pre><code>import random @client.command() async def color(ctx): responses = ['red', 'blue', 'green', 'purple', 'Add more',] await ctx.send(f'Color: {random.choice(responses)}') </code></pre> <p>` but i didnt want to put it all in one line in the responses</p>
[ { "answer_id": 74439037, "author": "wwnde", "author_id": 8986975, "author_profile": "https://Stackoverflow.com/users/8986975", "pm_score": 1, "selected": false, "text": "df[~df['Date'].astype(str).str.contains('4/1/2022')]\n" }, { "answer_id": 74439041, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "df[df['Date'].ne('2022-04-01')]\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18887131/" ]
74,438,929
<p>I am creating a stored procedure in Snowflake that returns number of rows in a table. Here is the code for the procedure and the result.</p> <pre><code>CREATE OR REPLACE PROCEDURE CDS_EXTRACT_CHECK_ROWCOUNT(STAGE_DATABASE varchar, STAGE_SCHEMA varchar, STAGE_TABLE varchar) RETURNS table (a int) LANGUAGE SQL AS DECLARE stmt string; res resultset; rowcount int; BEGIN stmt := 'SELECT COUNT(*) FROM ' || :STAGE_DATABASE || '.' || :STAGE_SCHEMA || '.' || :STAGE_TABLE || ';'; res := (EXECUTE IMMEDIATE :stmt); RETURN TABLE(res); END ; </code></pre> <p><a href="https://i.stack.imgur.com/FzzUI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FzzUI.png" alt="Result after calling the procedure" /></a></p> <p>I want to execute this stored procedure within another procedure and store the returned value to a variable:</p> <pre><code>rowcount := CALL CDS_EXTRACT_CHECK_ROWCOUNT(:STAGE_DATABASE, :STAGE_SCHEMA, :STAGE_TABLE); </code></pre> <p>Thanks in advance</p>
[ { "answer_id": 74439037, "author": "wwnde", "author_id": 8986975, "author_profile": "https://Stackoverflow.com/users/8986975", "pm_score": 1, "selected": false, "text": "df[~df['Date'].astype(str).str.contains('4/1/2022')]\n" }, { "answer_id": 74439041, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "df[df['Date'].ne('2022-04-01')]\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13711883/" ]
74,438,930
<p>I am very very new to Swift programming and I am growing to dislike it very much. I am not grasping it aa easily as other languages.</p> <p>I have a project I am working on and I cannot figure out what is wrong or why its isn't working.</p> <p>In one view, I have a table view that has a cell. I am using an array to store all the values that I want to be stored in the corresponding elements in the table view.</p> <p>When the user clicks on an individual cell in the table view, it will bring them to another view displaying other elements of the movie (runtime, image, director and year).</p> <p>I have a template that I am using to code this and I think I have done everything correctly, but when I run the app, nothing shows.</p> <p>I just want the table cells to show on startup, when I run the app. I can even troubleshoot myself if I can just have the table cells show.</p> <p>Since I am so new to this language and XCode, I am having trouble navigating the IDE to find my issues. On top of much I am already struggling with Swift.</p> <p>I could really use the help, if possible!</p> <p>Here is all the code I have done:</p> <pre><code> import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { let movieList = [&quot;Step Brothers&quot;, &quot;Pulp Fiction&quot;, &quot;Ali&quot;, &quot;Harry Potter&quot;] let yearList = [&quot;2008&quot;, &quot;1994&quot;, &quot;2001&quot;, &quot;2001&quot;] let images = [&quot;step_brothers&quot;, &quot;pulp_fiction&quot;, &quot;ali&quot;, &quot;harry_potter3&quot;] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int { return movieList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell { let tempCell: TableViewCell = tableView.dequeueReusableCell(withIdentifier: &quot;cell&quot;) as! TableViewCell tempCell.movieTitleLabel.text = movieList[indexPath.row] tempCell.movieYearLabel.text = yearList[indexPath.row] tempCell.movieImage.image = UIImage(named: images[indexPath.row] + &quot;.jpeg&quot;) return tempCell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let detailVC:MovieDetailViewController = self.storyboard?.instantiateViewController(withIdentifier: &quot;MovieDetailViewController&quot;) as! MovieDetailViewController // assign the values to the local variable declared in ProductDetailViewController Class detailVC.movieImage = UIImage(named: images[indexPath.row] + &quot;.jpeg&quot;)! // make it navigate to ProductDetailViewController self.navigationController?.pushViewController(detailVC, animated: true) } } </code></pre> <p>This is for the individual cell in the table view:</p> <pre><code>import UIKit class TableViewCell: UITableViewCell { @IBOutlet weak var movieTitleLabel: UILabel! @IBOutlet weak var movieYearLabel: UILabel! @IBOutlet weak var movieImage: UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } </code></pre> <p>This is the MovieDetailViewController:</p> <pre><code>class MovieDetailViewController: UIViewController { @IBOutlet weak var movieDetailImage: UIImageView! @IBOutlet weak var runtimeLabel: UILabel! @IBOutlet weak var yearDetailLabel: UILabel! @IBOutlet weak var directorDetailLabel: UILabel! var runtime: String! // holds the product name var year: String! // holds the price var movieImage: UIImage! // holds the product image var director: String! override func viewDidLoad() { super.viewDidLoad() movieDetailImage.image = movieImage runtimeLabel.text = runtime yearDetailLabel.text = year directorDetailLabel.text = director // Do any additional setup after loading the view. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ } </code></pre> <p>This is the error shown in the terminal, but there are no actual errors in the code:</p> <p><code>2022-11-14 17:39:28.232645-0500 Exercise01[25678:1217794] [Storyboard] Unable to find method -[(null) TableViewCell] 2022-11-14 17:39:28.259975-0500 Exercise01[25678:1217794] [Assert] UINavigationBar decoded as unlocked for UINavigationController, or navigationBar delegate set up incorrectly. Inconsistent configuration may cause problems. navigationController=&lt;UINavigationController: 0x141012400&gt;, navigationBar=&lt;UINavigationBar: 0x142106160; frame = (0 47; 0 50); opaque = NO; autoresize = W; layer = &lt;CALayer: 0x600001d72280&gt;&gt; delegate=0x141012400</code></p> <p>I can throw in the AppDelegate and SceneDelegate if you need it, just let me know.</p> <p>Thank you everyone, again! I greatly appreciate the help!</p>
[ { "answer_id": 74439037, "author": "wwnde", "author_id": 8986975, "author_profile": "https://Stackoverflow.com/users/8986975", "pm_score": 1, "selected": false, "text": "df[~df['Date'].astype(str).str.contains('4/1/2022')]\n" }, { "answer_id": 74439041, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "df[df['Date'].ne('2022-04-01')]\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19802615/" ]
74,438,949
<pre><code>&lt;MyComponent&gt; &lt;button&gt;Click me&lt;/button&gt; &lt;/MyComponent&gt; interface MyComponentProps { children: ???; } const MyComponent: FC&lt;MyComponentProps&gt; = ({children}) =&gt; { const string = children.??? //I want the string to be &quot;Click me&quot; } </code></pre> <p>I tried so many combinations but I always get undefined, thank you so much for your help.</p>
[ { "answer_id": 74439219, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 1, "selected": false, "text": "children" }, { "answer_id": 74439352, "author": "Benjamin", "author_id": 1830563, "author_profile": "https://Stackoverflow.com/users/1830563", "pm_score": 3, "selected": true, "text": "const isElement = (child: React.ReactNode): child is React.ReactElement =>\n (child as React.ReactElement)?.props !== undefined;\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9630194/" ]
74,438,958
<p>I'm trying to add an array to a dictionary in Matlab.</p> <p>In Python it's very simple, just make a dictionary and for a key assign an array, but in Matlab I get this error:</p> <blockquote> <p>Error using () Dimensions of the key and value must be compatible, or the value must be scalar.</p> </blockquote> <p>Basically all I want to do is:</p> <pre><code>d = dictionary arr = [1 0.2 7 0.3] d('key') = arr </code></pre> <p>But it doesn't work and I don't understand what I am supposed to do.</p>
[ { "answer_id": 74439138, "author": "Cris Luengo", "author_id": 7328782, "author_profile": "https://Stackoverflow.com/users/7328782", "pm_score": 3, "selected": true, "text": "d(\"key\") = {arr};\n" }, { "answer_id": 74439313, "author": "Chris Ze Third", "author_id": 19392385, "author_profile": "https://Stackoverflow.com/users/19392385", "pm_score": 0, "selected": false, "text": "% create an array\narray = [1, 2, 3];\n\n% create a dictionary\ndictionary = containers.Map;\n\n% add the array to the dictionary\ndictionary('array') = array;\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19392385/" ]
74,438,995
<p>I installed successfully Odoo 16 on Ubuntu 22. (Yenthe script) When I run Odoo directly with the IP address on port 8069 everything functions. But when I run it with a domain name with a server block several things happen: The initial website generation gets stuck in an endless loop. After letting it run for a long time when I refresh the screen the website is created but I cannot edit it. I can click on the frontend editor button in the top left area but the edit mode does not appear. The editible area changes into dark grey with a large circle circling endlessly. When I alternate the same app wit the Ip number it works without a problem.</p> <p>I am using cloudflare.</p> <p>First I suspected the server block but I have been using suggested variations but no changes. The error log does not show obvious errors.</p> <p>Does anyone out there have a similar experience? Are there solutions?</p>
[ { "answer_id": 74439138, "author": "Cris Luengo", "author_id": 7328782, "author_profile": "https://Stackoverflow.com/users/7328782", "pm_score": 3, "selected": true, "text": "d(\"key\") = {arr};\n" }, { "answer_id": 74439313, "author": "Chris Ze Third", "author_id": 19392385, "author_profile": "https://Stackoverflow.com/users/19392385", "pm_score": 0, "selected": false, "text": "% create an array\narray = [1, 2, 3];\n\n% create a dictionary\ndictionary = containers.Map;\n\n% add the array to the dictionary\ndictionary('array') = array;\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74438995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5964689/" ]
74,439,008
<p>I was working with VS Code and everything was fine, now out of nowhere there is a problem with the intellisense caused by Omnisharp in my opinion. I'm with Macbook Air M1 (2020) with Ventura 13.0.1, also I'm with the latest .Net SDK 6.0.402. The intellisense is not working at all, I reinstalled the C# extension from Microsoft, but it didn't fix the problem. What can cause this issue ?!</p> <p>Thanks in advance to all of you!!</p> <blockquote> <p>Starting OmniSharp server at 11/15/2022, 1:12:50 AM Target: /Users/kalinstoev/Dev/Reactivities/API</p> <p>OmniSharp server started with .NET 6.0.402 . Path: /Users/kalinstoev/.vscode/extensions/ms-dotnettools.csharp-1.25.2-darwin-arm64/.omnisharp/1.39.2-net6.0/OmniSharp.dll PID: 952</p> <p>[STDERR] Unhandled exception. [ERROR] A .NET 6 SDK for arm64 was not found. Please install the latest arm64 SDK from <a href="https://dotnet.microsoft.com/en-us/download/dotnet/6.0" rel="nofollow noreferrer">https://dotnet.microsoft.com/en-us/download/dotnet/6.0</a>. [ERROR] Error: OmniSharp server load timed out. Use the 'omnisharp.projectLoadTimeout' setting to override the default delay (one minute).</p> </blockquote> <p><strong>UPDATE 15.11.22</strong></p> <p>After Reinstalling VS Code for Mac and manually deleted the Omnisharp folders from inside the .vscode folder, there is no change. Also downgrading the version of the C# Extension to 1.25.1 didn't change anything... This is the new error when I add the new SDK..</p> <blockquote> <p>Unhandled exception. System.BadImageFormatException: Could not load file or assembly '/usr/local/share/dotnet/x64/sdk/6.0.403/dotnet.dll'. An attempt was made to load a program with an incorrect format.</p> <pre><code>Unhandled exception. System.BadImageFormatException: Could not load file or assembly </code></pre> <p>'/usr/local/share/dotnet/x64/sdk/6.0.403/dotnet.dll'. An attempt was made to load a program with an incorrect format.</p> <pre><code>File name: '/usr/local/share/dotnet/x64/sdk/6.0.403/dotnet.dll' </code></pre> </blockquote>
[ { "answer_id": 74439138, "author": "Cris Luengo", "author_id": 7328782, "author_profile": "https://Stackoverflow.com/users/7328782", "pm_score": 3, "selected": true, "text": "d(\"key\") = {arr};\n" }, { "answer_id": 74439313, "author": "Chris Ze Third", "author_id": 19392385, "author_profile": "https://Stackoverflow.com/users/19392385", "pm_score": 0, "selected": false, "text": "% create an array\narray = [1, 2, 3];\n\n% create a dictionary\ndictionary = containers.Map;\n\n% add the array to the dictionary\ndictionary('array') = array;\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74439008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14541604/" ]
74,439,019
<p>I have a dataframe with rows as dictionaries as below:</p> <pre><code>Col1 A B {'A': 1, 'B': 23} apple carrot {'A': 3, 'B': 35} banana spinach </code></pre> <p>I want to expand Col1 such that the dataframe looks like this:</p> <pre><code>Col1.A Col2.B A B 1 23 apple carrot 3 35 banana spinach </code></pre> <p>How can I do this using pandas in python? Please let me know if there is any other way as well.</p> <p>I tried using pd.explode but the new column names are being duplicated. How to avoid this?</p>
[ { "answer_id": 74439089, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 2, "selected": false, "text": "df[\"Col1.A\"] = df[\"Col1\"].map(lambda x: x[\"A\"])\ndf[\"Col1.B\"] = df[\"Col1\"].map(lambda x: x[\"B\"])\ndf.drop(\"Col1\", axis=1, inplace=True)\n" }, { "answer_id": 74439131, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "df = (pd.json_normalize(df.pop('Col1'))\n .add_prefix('Col1.').join(df)\n )\n" }, { "answer_id": 74439133, "author": "D.Manasreh", "author_id": 7509907, "author_profile": "https://Stackoverflow.com/users/7509907", "pm_score": 2, "selected": false, "text": "Col1 = df['Col1'].apply(pd.Series)\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74439019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20505088/" ]
74,439,029
<p>This is an example of my data frame with a list in it.</p> <pre><code>df &lt;- data.frame(x = 1:2, y = c(&quot;A&quot;, &quot;B&quot;)) df$z &lt;- rep(list(1:3), 2) df &gt; df x y z 1 1 A 1, 2, 3 2 2 B 1, 2, 3 </code></pre> <p>I would like to kind of <code>unlist</code> the list and rearrange the data frame as following:</p> <pre><code> x y z 1 1 A 1 2 1 A 2 3 1 A 3 4 2 B 1 5 2 B 2 6 2 B 3 </code></pre> <p>Tried <code>unlist(df)</code> but could not get it right.</p>
[ { "answer_id": 74439049, "author": "onyambu", "author_id": 8380272, "author_profile": "https://Stackoverflow.com/users/8380272", "pm_score": 2, "selected": true, "text": "tidyr::unnest(df,z) # or even unnest_longer(df, z)\n\n# A tibble: 6 × 3\n x y z\n <int> <chr> <int>\n1 1 A 1\n2 1 A 2\n3 1 A 3\n4 2 B 1\n5 2 B 2\n6 2 B 3\n" }, { "answer_id": 74439061, "author": "cbowers", "author_id": 12945433, "author_profile": "https://Stackoverflow.com/users/12945433", "pm_score": 0, "selected": false, "text": "require(dplyr)\ndf %>% \n apply(1, function(x) expand.grid(x[1][[1]], x[2][[1]], x[3][[1]])) %>% \n reduce(rbind)\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74439029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11741943/" ]
74,439,065
<p>I'm adding a new server action to my Odoo, but is not working ok. It's supposed to check the n selected items, but only is checking the first one. What I'm missing?</p> <p><a href="https://i.stack.imgur.com/jfH1t.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jfH1t.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/H00Ov.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/H00Ov.png" alt="enter image description here" /></a></p> <p>XML</p> <pre><code>&lt;record id=&quot;action_server_validate&quot; model=&quot;ir.actions.server&quot;&gt; &lt;field name=&quot;name&quot;&gt;Validate / Unvalidate&lt;/field&gt; &lt;field name=&quot;type&quot;&gt;ir.actions.server&lt;/field&gt; &lt;field name=&quot;model_id&quot; ref=&quot;model_account_voucher&quot;/&gt; &lt;field name=&quot;binding_model_id&quot; ref=&quot;model_account_voucher&quot;/&gt; &lt;field name=&quot;state&quot;&gt;code&lt;/field&gt; &lt;field name=&quot;code&quot;&gt; for obj in object: obj.validate_invalidate() &lt;/field&gt; &lt;/record&gt; </code></pre> <p>Python</p> <pre><code>class AccountVoucher(models.Model): _inherit = 'account.voucher' validated = fields.Boolean('Validated', default=False) payment_mode_id = fields.Many2one(related='payment_line_ids.payment_mode_id') @api.multi def validate_invalidate(self): for rec in self: if not rec.validated: rec.validated = True else: rec.validated = False </code></pre>
[ { "answer_id": 74439310, "author": "Bhavesh Odedra", "author_id": 2926754, "author_profile": "https://Stackoverflow.com/users/2926754", "pm_score": 0, "selected": false, "text": "for obj in object:\n obj.validate_invalidate()\n" }, { "answer_id": 74449183, "author": "Kenly", "author_id": 5471709, "author_profile": "https://Stackoverflow.com/users/5471709", "pm_score": 2, "selected": true, "text": "object" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74439065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19883757/" ]
74,439,075
<p>I have a dataframe, where the variable top10 has either value 0 (not in top 10) and 1 (in top 10). And a categorical variable label (Independent, Warner Music, Sony music, Universal music).</p> <p><a href="https://i.stack.imgur.com/89SYX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/89SYX.png" alt="enter image description here" /></a></p> <p>What would be an appropriate plot to visualize the relationship between these variables?</p> <p>I was thinking about to visualize the probabilities of each label of being in top 10 (top10 == 1). But I have no idea how to do it...</p> <p>That is what I started to do:</p> <p><a href="https://i.stack.imgur.com/pJsmM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pJsmM.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74439310, "author": "Bhavesh Odedra", "author_id": 2926754, "author_profile": "https://Stackoverflow.com/users/2926754", "pm_score": 0, "selected": false, "text": "for obj in object:\n obj.validate_invalidate()\n" }, { "answer_id": 74449183, "author": "Kenly", "author_id": 5471709, "author_profile": "https://Stackoverflow.com/users/5471709", "pm_score": 2, "selected": true, "text": "object" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74439075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14695152/" ]
74,439,083
<p>I'm having a problem when running the npx prisma migrate dev command. Docker desktop tells me that the database is running correctly on port 5432 but I still can't see the problem. I tried to put <code>connect_timeout=300</code> to the connection string, tried many versions of postgres and docker, but I can't get it to work. I leave you the link of the repo and photos so you can see the detail of the code. I would greatly appreciate your help, since I have been lost for a long time with this.</p> <p>Repo: <a href="https://github.com/gabrielmcreynolds/prisma-vs-typeorm/tree/master/prisma-project" rel="nofollow noreferrer">https://github.com/gabrielmcreynolds/prisma-vs-typeorm/tree/master/prisma-project</a> Docker-compose.yml</p> <pre class="lang-yaml prettyprint-override"><code>version: &quot;3.1&quot; services: postgres: image: postgres container_name: postgresprisma restart: always environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=santino2002 ports: - &quot;5432:5432&quot; volumes: - postgres:/var/lib/postgresql/data volumes: postgres: </code></pre> <p>Error:</p> <blockquote> <p>Error: P1001: Can't reach database server at <code>localhost</code>:<code>5432</code> Please make sure your database server is running at <code>localhost</code>:<code>5432</code>.</p> </blockquote> <p>Docker ps show this: <a href="https://i.stack.imgur.com/Tepu2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Tepu2.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74441624, "author": "Abhishek S", "author_id": 9754109, "author_profile": "https://Stackoverflow.com/users/9754109", "pm_score": 1, "selected": false, "text": "localhost:5432" }, { "answer_id": 74457010, "author": "Mansur", "author_id": 10530420, "author_profile": "https://Stackoverflow.com/users/10530420", "pm_score": 0, "selected": false, "text": "docker ps" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74439083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20488789/" ]
74,439,086
<pre><code>&lt;html&gt; &lt;!-- ... (other page content) ... --&gt; &lt;script src=&quot;common.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;homepage.js&quot;&gt;&lt;/script&gt; &lt;/html&gt; </code></pre> <p>On every page on my website, I have one common.js file for stuff that is always needed on every single page. And then I have one js file specifically for that page.</p> <p>My problem is that variables declared in the common.js file needs to be accessed in the second js file as well, but I am running into some issues because the script is not waiting for the data variable to be declared, and it is not allowed to use await in the top level of the script.</p> <pre><code>// common.js let data; async function get_data() { data = await fetch('/get-data').then(res =&gt; res.json()) console.log(data) // works!!! } get_data(); console.log(data) // does not work!!! </code></pre> <pre><code>// homepage.js console.log(data) // does not work!!! </code></pre> <p>So what I am asking is how can I make the two <code>console.log(data)</code> calls that aren't working, work!</p>
[ { "answer_id": 74439113, "author": "CertainPerformance", "author_id": 9515207, "author_profile": "https://Stackoverflow.com/users/9515207", "pm_score": 1, "selected": false, "text": "data" }, { "answer_id": 74439114, "author": "Phil", "author_id": 283366, "author_profile": "https://Stackoverflow.com/users/283366", "pm_score": 1, "selected": false, "text": "// common.js\nasync function get_data() {\n const res = await fetch('/get-data');\n if (!res.ok) {\n throw res;\n }\n return res.json(); // return the data\n}\n\n// Assign to a variable\nconst dataPromise = get_data();\n\ndataPromise.then(console.log);\n" }, { "answer_id": 74439247, "author": "Joel", "author_id": 2902996, "author_profile": "https://Stackoverflow.com/users/2902996", "pm_score": 0, "selected": false, "text": "window" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74439086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19643541/" ]
74,439,102
<p>I don't speak Russian, so I'm having trouble validating whether the months are correctly spelled, etc. To be honest, I'm not fully sure that my input is in Russian (Russian is the language detected by Google translate)</p> <p>I have some code in Kotlin which does a best-effort to parse dates specified in various formats and languages. I'm struggling with parsing Russian dates, however. Here's the relevant part of my code:</p> <pre class="lang-kotlin prettyprint-override"><code>sequenceOf( &quot;ru-RU&quot;, // Russian &quot;sr&quot;, // Serbian ).forEach { val format = DateTimeFormatter.ofPattern(&quot;d MMM. yyyy&quot;) .withLocale(Locale.forLanguageTag(it)) try { return listOf(LocalDate.parse(dateString, format)) } catch (e: Exception) { //Ignore and move on } } </code></pre> <p>This code correctly parses <code>&quot;27 апр. 2018&quot;</code> and <code>&quot;24 мая. 2013&quot;</code>, but fails on <code>&quot;28 фев. 2019&quot;</code>.</p> <p>What's special about <code>&quot;28 фев. 2019&quot;</code> and/or how can I parse this value correctly?</p> <p>If you provide answers in Java, I can translate it to Kotlin fairly easily.</p> <hr /> <p><strong>EDIT</strong>: Here's an SSCCE in Kotlin:</p> <pre class="lang-kotlin prettyprint-override"><code>import java.time.LocalDate import java.time.format.DateTimeFormatter import java.util.* println(&quot;System.getProperty - &quot; + System.getProperty(&quot;java.version&quot;)); println(&quot;Runtime.version - &quot; + Runtime.version()); val dateString = &quot;28 фев. 2019&quot; sequenceOf( &quot;ru-RU&quot;, // Russian &quot;sr&quot;, // Serbian ).forEach { val format = DateTimeFormatter.ofPattern(&quot;d MMM. yyyy&quot;) .withLocale(Locale.forLanguageTag(it)) try { println(&quot;Parse successful - &quot; + LocalDate.parse(dateString, format)) } catch (e: Exception) { println(&quot;Parse failed - &quot; + e) } } </code></pre> <p>Output on my system:</p> <pre><code>System.getProperty - 17.0.4.1 Runtime.version - 17.0.4.1+7-b469.62 Parse failed - java.time.format.DateTimeParseException: Text '28 фев. 2019' could not be parsed at index 3 Parse failed - java.time.format.DateTimeParseException: Text '28 фев. 2019' could not be parsed at index 3 </code></pre>
[ { "answer_id": 74439113, "author": "CertainPerformance", "author_id": 9515207, "author_profile": "https://Stackoverflow.com/users/9515207", "pm_score": 1, "selected": false, "text": "data" }, { "answer_id": 74439114, "author": "Phil", "author_id": 283366, "author_profile": "https://Stackoverflow.com/users/283366", "pm_score": 1, "selected": false, "text": "// common.js\nasync function get_data() {\n const res = await fetch('/get-data');\n if (!res.ok) {\n throw res;\n }\n return res.json(); // return the data\n}\n\n// Assign to a variable\nconst dataPromise = get_data();\n\ndataPromise.then(console.log);\n" }, { "answer_id": 74439247, "author": "Joel", "author_id": 2902996, "author_profile": "https://Stackoverflow.com/users/2902996", "pm_score": 0, "selected": false, "text": "window" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74439102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2518281/" ]
74,439,117
<p>I would like to add the <code>data</code> parameter only when it has value if not then don't add data in the parameter string.</p> <p>Currently, it is throwing unexpected token <code>if</code> and data values shows <code>undefined</code></p> <pre><code>function Data() { if ($(&quot;#data&quot;).val().length != 0) { &quot;&amp;data=&quot; + $(&quot;#data&quot;).val(); } } function check() { launch += &amp; firstname = &quot; + $(&quot;# first &quot;).val() + &quot; &amp; data = &quot; + Data(); } </code></pre> <p>Adding the parameter in this way</p> <pre><code>&quot;&amp;data=&quot; + Data(); </code></pre>
[ { "answer_id": 74439215, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 3, "selected": true, "text": "check()" }, { "answer_id": 74439237, "author": "Phil", "author_id": 283366, "author_profile": "https://Stackoverflow.com/users/283366", "pm_score": 1, "selected": false, "text": "const params = {\n firstname: $(\"#first\").val(),\n};\nconst data = $(\"#data\").val();\nif (data) {\n params.data = data;\n}\n\nconst launch = (new URLSearchParams(params)).toString();\n// or = $.param(params)\n\nconsole.log(\"launch:\", launch)" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74439117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20505175/" ]
74,439,139
<p>I have a HTML input and onClick with a button, I get the value of text input and store in a varibale in Javascipt. Now how can I use this varibale as a paramter to a python function?</p> <p>In JavaScript I have:</p> <pre><code>var text = document.getElementById(&quot;text&quot;).value; </code></pre> <p>and in Python I have:</p> <pre><code>someFunction(text): print(text) # text is what I want to be passed from javascript </code></pre> <p>I am using pyscript to run my python codes</p>
[ { "answer_id": 74439215, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 3, "selected": true, "text": "check()" }, { "answer_id": 74439237, "author": "Phil", "author_id": 283366, "author_profile": "https://Stackoverflow.com/users/283366", "pm_score": 1, "selected": false, "text": "const params = {\n firstname: $(\"#first\").val(),\n};\nconst data = $(\"#data\").val();\nif (data) {\n params.data = data;\n}\n\nconst launch = (new URLSearchParams(params)).toString();\n// or = $.param(params)\n\nconsole.log(\"launch:\", launch)" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74439139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20504613/" ]
74,439,175
<p><strong>Situation:</strong></p> <p>C++ app developed with Visual Studio 2022 dies in Release mode only when debugger is detached. Now, while I may know the typical scenarios where this might be happening the code base is too immense for me to do any per-line code reviews. So, I set Windbg as post-mortem debugger in hopes of finding where it dies.</p> <p>Now, shed some light onto me, please.</p> <p><strong>Question</strong>:</p> <p>How do I see the exact reason why a fatal exception was thrown? Any way to browse through the recent exceptions?</p> <p><strong>Discussion</strong></p> <p>The funny thing in my case is that, this multi-threaded app, after the exception is caught by WinDbg launching in post-mortem mode.. the app continues to run.... I need to pause execution.. so I wonder what throws the exception.. and why does the app continue code execution after it was caught by WindDBG (without WindDBG set as post-mortem debugger and thus without it catching the exception - the app simply dies).</p> <p><strong>Update:</strong></p> <p>The only suspicious thing I am shown by WinDbg right after it is invoked is:</p> <blockquote> <p>WARNING: Continuing a non-continuable exception</p> </blockquote>
[ { "answer_id": 74439215, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 3, "selected": true, "text": "check()" }, { "answer_id": 74439237, "author": "Phil", "author_id": 283366, "author_profile": "https://Stackoverflow.com/users/283366", "pm_score": 1, "selected": false, "text": "const params = {\n firstname: $(\"#first\").val(),\n};\nconst data = $(\"#data\").val();\nif (data) {\n params.data = data;\n}\n\nconst launch = (new URLSearchParams(params)).toString();\n// or = $.param(params)\n\nconsole.log(\"launch:\", launch)" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74439175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1549596/" ]
74,439,190
<p>say I have something like this in nextjs, when I run it I get the error</p> <p>'Module not found: Can't resolve './${game.image}'</p> <pre><code>const Categories = () =&gt; { const Games = [ { name: &quot;World of warcraft&quot;, image: &quot;/assets/wow.png&quot;, }, { name: &quot;League of Legends&quot;, image: &quot;/assets/lol.png&quot;, } ] return ( &lt;div&gt; {Games.map((game, index) =&gt; ( &lt;div key={index} className={`flex w-full h-full bg-cover bg-center bg-[url('${game.image}')]`}&gt; &lt;/div&gt; ))} &lt;/div&gt; )} export default Categories </code></pre> <p>how do I go about doing this?</p>
[ { "answer_id": 74439322, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 1, "selected": false, "text": "const Games = \n [\n name: \"World of warcraft\",\n image: \"/assets/wow.png\",\n ],\n [\n name: \"League of Legends\",\n image: \"/assets/lol.png\",\n ]\n" }, { "answer_id": 74455421, "author": "Sombre Dreamer", "author_id": 16409634, "author_profile": "https://Stackoverflow.com/users/16409634", "pm_score": 0, "selected": false, "text": "const Games = [\n {\n name: \"World of warcraft\",\n image: \"bg-[url('/assets/wow.png')]\",\n }\n]\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74439190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16409634/" ]
74,439,197
<p>I have this dict that was provided by ansible_facts</p> <pre class="lang-yaml prettyprint-override"><code> ansible_facts.lvm.lvs: lv-something-1: size_g: '70.00' vg: blockchains lv-something2-2: size_g: '45.00' vg: blockchains lv-something3-3: size_g: '250.00' vg: blockchains lv-something4-4: size_g: '4610.00' vg: blockchains lv-something5-5: size_g: '500.00' vg: blockchains lv-something6-6: size_g: '25.00' vg: blockchains lvthinpool: size_g: '10666.11' vg: blockchains </code></pre> <p>First, I tried a lot to remove the <code>thinpool</code> item, but I was not successful, I tried to convert this dict to a list, tried to use <code>reject, rejectattr</code>, but they give just the names.. like this I even tried to create two lists and make a concat but no success, lol</p> <pre class="lang-yaml prettyprint-override"><code> ansible_facts.lvm.lvs | reject('search', 'thinpool'): - lv-something-1 - lv-something2-2 - lv-something3-3 - lv-something4-4 - lv-something5-5 - lv-something6-6 </code></pre> <p>but I wanna catch the size of my volumes.. I wanna just remove <code>lvthinpool</code> to the dict, there is a way? and after that I will catch all size_g and I'll add up all your value</p> <p>my dict expect output is:</p> <pre class="lang-yaml prettyprint-override"><code> ansible_facts.lvm.lvs: lv-something-1: size_g: '70.00' vg: blockchains lv-something2-2: size_g: '45.00' vg: blockchains lv-something3-3: size_g: '250.00' vg: blockchains lv-something4-4: size_g: '4610.00' vg: blockchains lv-something5-5: size_g: '500.00' vg: blockchains lv-something6-6: size_g: '25.00' vg: blockchains </code></pre> <p>I've be tried to use set_fact to convert this dict to a list and manipulate date with <code>reject</code> or <code>rejectattr</code>, then create two dict, and tried to union these values.. I've be tried to put the content to a file and delete it using regex with the <code>linefile</code> module</p>
[ { "answer_id": 74439322, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 1, "selected": false, "text": "const Games = \n [\n name: \"World of warcraft\",\n image: \"/assets/wow.png\",\n ],\n [\n name: \"League of Legends\",\n image: \"/assets/lol.png\",\n ]\n" }, { "answer_id": 74455421, "author": "Sombre Dreamer", "author_id": 16409634, "author_profile": "https://Stackoverflow.com/users/16409634", "pm_score": 0, "selected": false, "text": "const Games = [\n {\n name: \"World of warcraft\",\n image: \"bg-[url('/assets/wow.png')]\",\n }\n]\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74439197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15945364/" ]
74,439,199
<p>I have made a list of all number from 0 to 500 and then I am looking for all number that end with a certain integer. The thing is I don't under stand how its working.</p> <p>I am new to coding so don't know what to expect here or how it is working.</p> <pre><code>x = 0 y = [] while x &lt;= 500: y.append(x) x = x + 1 a = 0 b = [] c = 0 # if i remove c from this or change c from 0 to 1 or any other number it just appends with that value # but if c is as i have it, it some how appends the list with the values i am pulling with my if statment while a &lt;= 500: if int(repr(y[a])[-1]) == 0: b.append(c) a = a + 1 c = c + 1 print(len(b)) print(b) </code></pre>
[ { "answer_id": 74439322, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 1, "selected": false, "text": "const Games = \n [\n name: \"World of warcraft\",\n image: \"/assets/wow.png\",\n ],\n [\n name: \"League of Legends\",\n image: \"/assets/lol.png\",\n ]\n" }, { "answer_id": 74455421, "author": "Sombre Dreamer", "author_id": 16409634, "author_profile": "https://Stackoverflow.com/users/16409634", "pm_score": 0, "selected": false, "text": "const Games = [\n {\n name: \"World of warcraft\",\n image: \"bg-[url('/assets/wow.png')]\",\n }\n]\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74439199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20505191/" ]
74,439,218
<pre><code>import csv #working with csv files from datetime import datetime #this will allow accessing time for later use #initialize class for every output class InventoryReports: def __init__(self, item_list): self.item_list = item_list #provide list to create new file #Part a #Create FullInventory.csv for entire inventory #Following order ID, manufacture name, item type, price, service date, damaged def fullInventory(self): with open('FullInventory.csv', 'w') as file: items = self.item_list keys = sorted(items.keys(), key=lambda x: items[x]['manufacturer']) #sorted alphabetically by manufacture for item in keys: id = item manufacture = items[item]['manufacturer'] itemType = items[item]['item_type'] price = items[item]['price'] serviceDate = items[item]['service_date'] damaged = items[item]['damaged'] file.write('{},{},{},{},{},{}\n'.format(id, manufacture, itemType, price, serviceDate, damaged)) </code></pre>
[ { "answer_id": 74439322, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 1, "selected": false, "text": "const Games = \n [\n name: \"World of warcraft\",\n image: \"/assets/wow.png\",\n ],\n [\n name: \"League of Legends\",\n image: \"/assets/lol.png\",\n ]\n" }, { "answer_id": 74455421, "author": "Sombre Dreamer", "author_id": 16409634, "author_profile": "https://Stackoverflow.com/users/16409634", "pm_score": 0, "selected": false, "text": "const Games = [\n {\n name: \"World of warcraft\",\n image: \"bg-[url('/assets/wow.png')]\",\n }\n]\n" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74439218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20497304/" ]
74,439,230
<pre><code>void addNumbers(vector&lt;double&gt; &amp;vec) { double add_num {}; cout &lt;&lt; &quot;Enter an integer to add: &quot;; cin &gt;&gt; add_num; vec.push_back(add_num); cout &lt;&lt; add_num &lt;&lt; &quot; added&quot; &lt;&lt; endl; } </code></pre> <p>The vector is empty, and I only want people to be able to add numbers into it, and whenever they try anything else it says &quot;Invalid number&quot;.</p> <p>The full code is below, and currently it just loops over and over saying &quot;0.00 added&quot; if I put something other than a number in lol</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;bits/stdc++.h&gt; #include &lt;iomanip&gt; #include &lt;cctype&gt; using namespace std; char choice {}; char menu(); void print(vector&lt;double&gt;); void mean(vector&lt;double&gt;); void addNumbers(vector&lt;double&gt; &amp;vec); void smallest(vector&lt;double&gt;); void largest(vector&lt;double&gt;); char menu() { cout &lt;&lt; &quot;\nP - Print numbers&quot; &lt;&lt; endl; cout &lt;&lt; &quot;A - Add a number&quot; &lt;&lt; endl; cout &lt;&lt; &quot;M - Display mean of the numbers&quot; &lt;&lt; endl; cout &lt;&lt; &quot;S - Display the smallest number&quot; &lt;&lt; endl; cout &lt;&lt; &quot;L - Display the largest number&quot; &lt;&lt; endl; cout &lt;&lt; &quot;Q - Quit&quot; &lt;&lt; endl; cout &lt;&lt; &quot;\nEnter your choice: &quot;; cin &gt;&gt; choice; choice = toupper(choice); return choice; } void print(vector&lt;double&gt; vec) { if (vec.size() != 0) { cout &lt;&lt; &quot;[ &quot;; for (auto i : vec) { cout &lt;&lt; i &lt;&lt; &quot; &quot;; } cout &lt;&lt; &quot;]&quot;; } else { cout &lt;&lt; &quot;[] - the list is empty&quot; &lt;&lt; endl; } } void addNumbers(vector&lt;double&gt; &amp;vec) { double add_num {}; cout &lt;&lt; &quot;Enter an integer to add: &quot;; cin &gt;&gt; add_num; vec.push_back(add_num); cout &lt;&lt; add_num &lt;&lt; &quot; added&quot; &lt;&lt; endl; } void mean(vector&lt;double&gt; vec) { if (vec.size() != 0) { double result {}; for (auto i : vec) { result += i; } cout &lt;&lt; &quot;The mean is &quot; &lt;&lt; result / vec.size() &lt;&lt; endl; } else { cout &lt;&lt; &quot;Unable to calculate the mean - no data&quot; &lt;&lt; endl; } } void smallest(vector&lt;double&gt; vec) { if (vec.size() != 0) { cout &lt;&lt; &quot;The smallest number is &quot; &lt;&lt; *min_element(vec.begin(), vec.end()) &lt;&lt; endl; } else { cout &lt;&lt; &quot;Unable to determine the smallest number - list is empty&quot; &lt;&lt; endl; } } void largest(vector&lt;double&gt; vec) { if (vec.size() != 0) { cout &lt;&lt; &quot;The largest number is &quot; &lt;&lt; *max_element(vec.begin(), vec.end()) &lt;&lt; endl; } else { cout &lt;&lt; &quot;Unable to determine the largest number - list is empty&quot; &lt;&lt; endl; } } int main() { vector&lt;double&gt; vec {}; bool done {true}; cout &lt;&lt; fixed &lt;&lt; setprecision(2); do { menu(); switch (choice) { case 'P': print(vec); break; case 'A': { addNumbers(vec); break; } case 'M': { mean(vec); break; } case 'S': { smallest(vec); break; } case 'L': largest(vec); break; case 'Q': cout &lt;&lt; &quot;Goodbye&quot; &lt;&lt; endl; done = false; break; default: cout &lt;&lt; &quot;Unknown selection, please try again&quot; &lt;&lt; endl; } } while (done == true); return 0; } </code></pre>
[ { "answer_id": 74440020, "author": "sxu", "author_id": 19694882, "author_profile": "https://Stackoverflow.com/users/19694882", "pm_score": -1, "selected": false, "text": "void addNumbers(vector<double> &vec) {\n int add_num=0;\n std::cout << \"Enter an integer to add: \";\n if( std::cin >> add_num ) {\n vec.push_back((double)add_num);\n std::cout << add_num << \" added\" << std::endl;\n } else {\n std::cout << \"It's not a valid number.\" << std::endl;\n std::cin.clear(); // to clear error status\n std::cin.ignore(1000,'\\n'); // to ignore characters in buffer entered.\n return;\n }\n}\n" }, { "answer_id": 74440185, "author": "shy45", "author_id": 20313707, "author_profile": "https://Stackoverflow.com/users/20313707", "pm_score": 0, "selected": false, "text": "void addNumbers(vector<double>& vec) {\n double add_num{};\n string s;\n cout << \"Enter an integer to add: \";\n cin >> s;\n try {\n add_num = stof(s);\n }catch (exception& e) {\n printf(\"error=%s\\n\", e.what());\n return;\n }\n vec.push_back(add_num);\n cout << add_num << \" added\" << endl;\n}\n" }, { "answer_id": 74443325, "author": "A M", "author_id": 9666018, "author_profile": "https://Stackoverflow.com/users/9666018", "pm_score": 1, "selected": true, "text": "cin >> add_num" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74439230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20505174/" ]
74,439,235
<pre><code>import java.util.Scanner; class Assignment4 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println(&quot;Type the message to be shortened&quot;); String msg = scan.nextLine(); msg = msg.toLowerCase(); String alg1 = &quot;&quot;; int vowelC = 0; int repeatC = 0; System.out.println(&quot;Algorithm 1&quot;); for (int i = 0; i&lt;msg.length();i++){ if(msg.substring(i-1,i).equals(&quot; &quot;)){ alg1+=msg.substring(i,i+1); } else{ if (msg.substring(i,i+1).equals(&quot;a&quot;) || msg.substring(i,i+1).equals(&quot;e&quot;) || msg.substring(i,i+1).equals(&quot;i&quot;) || msg.substring(i,i+1).equals(&quot;o&quot;) || msg.substring(i,i+1).equals(&quot;i&quot;)){ vowelC++; } else if (msg.substring(i,i+1).equals(msg.substring(i-1,i))){ repeatC++; } else{ alg1+=msg.substring(i,i+1); } } } System.out.print(alg1); } } </code></pre> <p>This results in a index out of range, -1. I understand why this is,that is not the issue, but when I tweak it by having the control of the for loop be i&lt;msg.length()-1, it works but does not print the last letter. I also tried changing i to start at 1, but that cut off the first letter. Just not sure how to get the whole message with no error. Thanks!</p>
[ { "answer_id": 74440020, "author": "sxu", "author_id": 19694882, "author_profile": "https://Stackoverflow.com/users/19694882", "pm_score": -1, "selected": false, "text": "void addNumbers(vector<double> &vec) {\n int add_num=0;\n std::cout << \"Enter an integer to add: \";\n if( std::cin >> add_num ) {\n vec.push_back((double)add_num);\n std::cout << add_num << \" added\" << std::endl;\n } else {\n std::cout << \"It's not a valid number.\" << std::endl;\n std::cin.clear(); // to clear error status\n std::cin.ignore(1000,'\\n'); // to ignore characters in buffer entered.\n return;\n }\n}\n" }, { "answer_id": 74440185, "author": "shy45", "author_id": 20313707, "author_profile": "https://Stackoverflow.com/users/20313707", "pm_score": 0, "selected": false, "text": "void addNumbers(vector<double>& vec) {\n double add_num{};\n string s;\n cout << \"Enter an integer to add: \";\n cin >> s;\n try {\n add_num = stof(s);\n }catch (exception& e) {\n printf(\"error=%s\\n\", e.what());\n return;\n }\n vec.push_back(add_num);\n cout << add_num << \" added\" << endl;\n}\n" }, { "answer_id": 74443325, "author": "A M", "author_id": 9666018, "author_profile": "https://Stackoverflow.com/users/9666018", "pm_score": 1, "selected": true, "text": "cin >> add_num" } ]
2022/11/14
[ "https://Stackoverflow.com/questions/74439235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20505242/" ]
74,439,252
<p>What I'm trying to achieve is that when a row in col2 has a 1, it will copy that 1 onto all the other values in col2 as long as the rows in col1 have the same name. As an example, if the dataframe looks like this</p> <pre><code>col1 col2 xx 1 xx 0 xx 0 xx 0 yy 0 yy 0 yy 0 zz 0 zz 0 zz 1 </code></pre> <p>The output would be</p> <pre><code>col1 col2 xx 1 xx 1 xx 1 xx 1 yy 0 yy 0 yy 0 zz 1 zz 1 zz 1 </code></pre>
[ { "answer_id": 74439318, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 4, "selected": true, "text": "groupby.transform('max')" }, { "answer_id": 74439328, "author": "Cameron Riddell", "author_id": 14278448, "author_profile": "https://Stackoverflow.com/users/14278448", "pm_score": 0, "selected": false, "text": ".groupby" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74439252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20505209/" ]
74,439,257
<p><a href="https://i.stack.imgur.com/WO7bZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WO7bZ.png" alt="display cut-out screenshot" /></a></p> <p>I still want the bottom navigation bar to remain the same length, but I want to add some padding in the container to the left to shift the cards over to the right a bit. I have the following code in my <code>MainActivity.kt</code> right now:</p> <pre><code>WindowCompat.setDecorFitsSystemWindows(window, false) ViewCompat.setOnApplyWindowInsetsListener(binding.root) { view, windowInsets -&gt; val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()) view.updateLayoutParams&lt;ViewGroup.MarginLayoutParams&gt; { topMargin = insets.top } binding.bottomNavigationView.updatePadding(bottom = insets.bottom) WindowInsetsCompat.CONSUMED } </code></pre> <p>My <code>activity_main.xml</code> is composed of a <code>ConstraintLayout</code> that encloses two elements: <code>BottomNavigationView</code> and <code>FragmentContainerView</code>.</p>
[ { "answer_id": 74439470, "author": "Zain", "author_id": 9851608, "author_profile": "https://Stackoverflow.com/users/9851608", "pm_score": 1, "selected": false, "text": "<item name=\"android:windowLayoutInDisplayCutoutMode\">default</item>\n" }, { "answer_id": 74483309, "author": "dem", "author_id": 13965988, "author_profile": "https://Stackoverflow.com/users/13965988", "pm_score": 1, "selected": true, "text": "private var cutoutDepth = 0\n\noverride fun onCreate(savedInstanceState: Bundle?) {\n [...]\n ViewCompat.setOnApplyWindowInsetsListener(binding.root) { view, windowInsets ->\n val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars())\n cutoutDepth = insets.top\n [...]\n }\n [...]\n}\n\noverride fun onResume() {\n super.onResume()\n // Starts the orientation listener\n if (orientationListener.canDetectOrientation())\n orientationListener.enable()\n}\n\noverride fun onPause() {\n super.onPause()\n // Stops the orientation listener\n orientationListener.disable()\n}\n\nprivate val orientationListener by lazy {\n object : OrientationEventListener(applicationContext, SensorManager.SENSOR_DELAY_NORMAL) {\n override fun onOrientationChanged(orientation: Int) {\n if (orientation == ORIENTATION_UNKNOWN)\n return\n when (display?.rotation) {\n Surface.ROTATION_0 -> {\n // Bottom - reset the padding in portrait\n binding.navHostFragmentActivityMain.setPadding(0, 0, 0, 0)\n }\n Surface.ROTATION_90 -> {\n // Left\n binding.navHostFragmentActivityMain.setPadding(cutoutDepth, 0, 0, 0)\n }\n Surface.ROTATION_180 -> {\n // Top - reset the padding if upside down\n binding.navHostFragmentActivityMain.setPadding(0, 0, 0, 0)\n }\n Surface.ROTATION_270 -> {\n // Right\n binding.navHostFragmentActivityMain.setPadding(0, 0, cutoutDepth, 0)\n }\n }\n }\n }\n}\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74439257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13965988/" ]
74,439,263
<p>So i am trying to build this website and as i go on i decided to use a bootstrap carousel, i already had a dropdown button in the navbar and a collapse menu when on smaller viewports and it all worked fine, but when i was implementing the carousel it had a delay between images. It was almost like a white page between them and i wasnt sure if my website was simply slow or if it was a feature of the carousel but since the other features worked fine then i doubted it was the website speed problem, also it has almost no code whatsoever. So i had a bunch of script codes for bootstrap css and js and i decided to delete them all and put simply the 2 that are on the official bootstrap website and since then not just the carousel problem persists (the huge delay between images with a blank white space) and also the other features stoped working. Can someone help me implement bootstrap correctly?</p> <p>heres the full code:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;styles.css&quot;&gt; &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.googleapis.com&quot;&gt; &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.gstatic.com&quot; crossorigin&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css&quot; integrity=&quot;sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N&quot; crossorigin=&quot;anonymous&quot;&gt; &lt;title&gt;Name&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;!--------------------------------------------- NAVIGATION BAr ---------------------------------------------------&gt; &lt;nav class=&quot;navbar navbar-expand-lg navbar-dark fixed-top &quot;&gt; &lt;a class=&quot;navbar-brand &quot; href=&quot;#&quot;&gt;Name&lt;/a&gt; &lt;button class=&quot;navbar-toggler&quot; type=&quot;button&quot; data-toggle=&quot;collapse&quot; data-target=&quot;#navbarSupportedContent&quot; aria-controls=&quot;navbarSupportedContent&quot; aria-expanded=&quot;false&quot; aria-label=&quot;Toggle navigation&quot;&gt; &lt;span class=&quot;navbar-toggler-icon&quot;&gt;&lt;/span&gt; &lt;/button&gt; &lt;div class=&quot;collapse navbar-collapse&quot; id=&quot;navbarSupportedContent&quot;&gt; &lt;ul class=&quot;navbar-nav mr-auto&quot;&gt; &lt;li class=&quot;nav-item&quot;&gt; &lt;a class=&quot;nav-link&quot; href=&quot;/index.html&quot;&gt;Home &lt;span class=&quot;sr-only&quot;&gt;&lt;/span&gt;&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item&quot;&gt; &lt;a class=&quot;nav-link&quot; href=&quot;/test.html&quot;&gt;&lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; width=&quot;16&quot; height=&quot;16&quot; fill=&quot;currentColor&quot; class=&quot;bi bi-telephone-fill&quot; viewBox=&quot;0 0 16 16&quot;&gt; &lt;path fill-rule=&quot;evenodd&quot; d=&quot;M1.885.511a1.745 1.745 0 0 1 2.61.163L6.29 2.98c.329.423.445.974.315 1.494l-.547 2.19a.678.678 0 0 0 .178.643l2.457 2.457a.678.678 0 0 0 .644.178l2.189-.547a1.745 1.745 0 0 1 1.494.315l2.306 1.794c.829.645.905 1.87.163 2.611l-1.034 1.034c-.74.74-1.846 1.065-2.877.702a18.634 18.634 0 0 1-7.01-4.42 18.634 18.634 0 0 1-4.42-7.009c-.362-1.03-.037-2.137.703-2.877L1.885.511z&quot;/&gt; &lt;/svg&gt;&lt;/i&gt; Contact&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item dropdown&quot;&gt; &lt;a class=&quot;nav-link dropdown-toggle&quot; href=&quot;#&quot; id=&quot;navbarDropdown&quot; role=&quot;button&quot; data-toggle=&quot;dropdown&quot; aria-haspopup=&quot;true&quot; aria-expanded=&quot;false&quot;&gt; Services &lt;/a&gt; &lt;div class=&quot;dropdown-menu&quot; aria-labelledby=&quot;navbarDropdown&quot;&gt; &lt;a class=&quot;dropdown-item&quot; href=&quot;#&quot;&gt;&lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; width=&quot;16&quot; height=&quot;16&quot; fill=&quot;currentColor&quot; class=&quot;bi bi-calendar&quot; viewBox=&quot;0 0 16 16&quot;&gt; &lt;path d=&quot;M3.5 0a.5.5 0 0 1 .5.5V1h8V.5a.5.5 0 0 1 1 0V1h1a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V3a2 2 0 0 1 2-2h1V.5a.5.5 0 0 1 .5-.5zM1 4v10a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V4H1z&quot;/&gt; &lt;/svg&gt; Booking&lt;/a&gt; &lt;a class=&quot;dropdown-item&quot; href=&quot;#&quot;&gt;Another action&lt;/a&gt; &lt;a class=&quot;dropdown-item&quot; href=&quot;#&quot;&gt;Something else here&lt;/a&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; &lt;span class=&quot;navbar-text&quot;&gt; Name o slogan &lt;/span&gt; &lt;/div&gt; &lt;/nav&gt; &lt;!--------------------------------------------- NAVIGATION BAr ---------------------------------------------------&gt; &lt;!-------------------------------------------- HERO -----------------------------------------------------&gt; &lt;div class=&quot;p-5 text-center bg-image&quot; style=&quot; height: 700px; &quot;&gt; &lt;div class=&quot;d-flex justify-content-center align-items-center h-100&quot;&gt; &lt;div class=&quot;text-white&quot;&gt; &lt;h1 class=&quot;nomeEmpresa&quot;&gt;Daniela Gonçalves Manicure&lt;/h1&gt; &lt;h4 class=&quot;mb-3&quot;&gt;Frontignan&lt;/h4&gt; &lt;a class=&quot;btn btn-* btn-lg &quot; href=&quot;#!&quot; role=&quot;button&quot;&gt;Prendez a rendevouz&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-------------------------------------------- HERO -----------------------------------------------------&gt; &lt;div class=&quot;separador&quot;&gt;&lt;/div&gt; &lt;!-------------------------------------------- Carroussel -------------------------------------------------------&gt; &lt;div id=&quot;carouselExampleControls&quot; class=&quot;carousel slide&quot; data-bs-ride=&quot;carousel&quot;&gt; &lt;div class=&quot;carousel-inner&quot;&gt; &lt;div class=&quot;carousel-item active&quot; style=&quot;background-color: aqua;&quot;&gt; &lt;img src=&quot;...&quot; class=&quot;d-block w-100&quot; alt=&quot;...&quot;&gt; &lt;/div&gt; &lt;div class=&quot;carousel-item&quot; style=&quot;background-color: black;&quot;&gt; &lt;img src=&quot;...&quot; class=&quot;d-block w-100&quot; alt=&quot;...&quot;&gt; &lt;/div&gt; &lt;div class=&quot;carousel-item&quot; style=&quot;background-color: rgb(250, 0, 0);&quot;&gt; &lt;img src=&quot;...&quot; class=&quot;d-block w-100&quot; alt=&quot;...&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;button class=&quot;carousel-control-prev&quot; type=&quot;button&quot; data-bs-target=&quot;#carouselExampleControls&quot; data-bs-slide=&quot;prev&quot;&gt; &lt;span class=&quot;carousel-control-prev-icon&quot; aria-hidden=&quot;true&quot;&gt;&lt;/span&gt; &lt;span class=&quot;visually-hidden&quot;&gt;Previous&lt;/span&gt; &lt;/button&gt; &lt;button class=&quot;carousel-control-next&quot; type=&quot;button&quot; data-bs-target=&quot;#carouselExampleControls&quot; data-bs-slide=&quot;next&quot;&gt; &lt;span class=&quot;carousel-control-next-icon&quot; aria-hidden=&quot;true&quot;&gt;&lt;/span&gt; &lt;span class=&quot;visually-hidden&quot;&gt;Next&lt;/span&gt; &lt;/button&gt; &lt;/div&gt; &lt;!-- JavaScript Bundle with Popper --&gt; &lt;script src=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js&quot;&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>i tried different versions cdn and it still does not work</p>
[ { "answer_id": 74439470, "author": "Zain", "author_id": 9851608, "author_profile": "https://Stackoverflow.com/users/9851608", "pm_score": 1, "selected": false, "text": "<item name=\"android:windowLayoutInDisplayCutoutMode\">default</item>\n" }, { "answer_id": 74483309, "author": "dem", "author_id": 13965988, "author_profile": "https://Stackoverflow.com/users/13965988", "pm_score": 1, "selected": true, "text": "private var cutoutDepth = 0\n\noverride fun onCreate(savedInstanceState: Bundle?) {\n [...]\n ViewCompat.setOnApplyWindowInsetsListener(binding.root) { view, windowInsets ->\n val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars())\n cutoutDepth = insets.top\n [...]\n }\n [...]\n}\n\noverride fun onResume() {\n super.onResume()\n // Starts the orientation listener\n if (orientationListener.canDetectOrientation())\n orientationListener.enable()\n}\n\noverride fun onPause() {\n super.onPause()\n // Stops the orientation listener\n orientationListener.disable()\n}\n\nprivate val orientationListener by lazy {\n object : OrientationEventListener(applicationContext, SensorManager.SENSOR_DELAY_NORMAL) {\n override fun onOrientationChanged(orientation: Int) {\n if (orientation == ORIENTATION_UNKNOWN)\n return\n when (display?.rotation) {\n Surface.ROTATION_0 -> {\n // Bottom - reset the padding in portrait\n binding.navHostFragmentActivityMain.setPadding(0, 0, 0, 0)\n }\n Surface.ROTATION_90 -> {\n // Left\n binding.navHostFragmentActivityMain.setPadding(cutoutDepth, 0, 0, 0)\n }\n Surface.ROTATION_180 -> {\n // Top - reset the padding if upside down\n binding.navHostFragmentActivityMain.setPadding(0, 0, 0, 0)\n }\n Surface.ROTATION_270 -> {\n // Right\n binding.navHostFragmentActivityMain.setPadding(0, 0, cutoutDepth, 0)\n }\n }\n }\n }\n}\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74439263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20505229/" ]
74,439,269
<p>I'm working in Google Sheets and am trying to find a more elegant way to return a value if a number in a referenced cell falls between two other values in the table. For example:</p> <p><a href="https://i.stack.imgur.com/0cQlN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0cQlN.jpg" alt="Min Max and Return Values" /></a></p> <p>In this case elsewhere I would like to show the return value based on the value from another cell. Such as:</p> <p><a href="https://i.stack.imgur.com/YbODa.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YbODa.jpg" alt="Example Data" /></a></p> <p>I could do a long IF statement but would prefer something that I can expand more readily if we update the columns.</p>
[ { "answer_id": 74439468, "author": "ztiaa", "author_id": 17887301, "author_profile": "https://Stackoverflow.com/users/17887301", "pm_score": 0, "selected": false, "text": "=ARRAYFORMULA(LOOKUP(E2:E5,A2:A6,C2:C6))\n" }, { "answer_id": 74439872, "author": "Ping", "author_id": 20288037, "author_profile": "https://Stackoverflow.com/users/20288037", "pm_score": 0, "selected": false, "text": "=QUERY(LAMBDA(REF,CASES,\n BYROW(CASES,LAMBDA(CASE,\n LAMBDA(MIN,MAX,RETURN,\n IF(CASE=\"\",\"\",FILTER(RETURN,CASE>=MIN,CASE<=MAX))\n )(INDEX(REF,,1),INDEX(REF,,2),INDEX(REF,,3))\n ))\n)($A$1:$C$,$E$2:E),\"WHERE Col1 IS NOT NULL\")\n" }, { "answer_id": 74439913, "author": "Harun24hr", "author_id": 5514747, "author_profile": "https://Stackoverflow.com/users/5514747", "pm_score": 1, "selected": false, "text": "BYROW()" }, { "answer_id": 74444147, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 0, "selected": false, "text": "=INDEX(VLOOKUP(E2:E5; A2:C; 3))\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74439269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1790492/" ]
74,439,284
<p>I have a nested list that has certain elements with an [x] at the beginning. I want the function to remove those elements and move them to the last list in <code>list1</code> (at index 2). But it should remove the [x] from it before placing it in the last list. It should also count how many were removed from each list.</p> <p>For example:</p> <pre class="lang-py prettyprint-override"><code>list1 = [['[x]homework', '[x]eat','stretch'], ['[x]final', 'school'], ['sleep','midterm'] # After: list1 = [['stretch'], ['school'], ['sleep','midterm', 'homework', 'eat', 'final']] # Output: # 2 removed from 1st list # 1 removed from 2nd list </code></pre>
[ { "answer_id": 74439468, "author": "ztiaa", "author_id": 17887301, "author_profile": "https://Stackoverflow.com/users/17887301", "pm_score": 0, "selected": false, "text": "=ARRAYFORMULA(LOOKUP(E2:E5,A2:A6,C2:C6))\n" }, { "answer_id": 74439872, "author": "Ping", "author_id": 20288037, "author_profile": "https://Stackoverflow.com/users/20288037", "pm_score": 0, "selected": false, "text": "=QUERY(LAMBDA(REF,CASES,\n BYROW(CASES,LAMBDA(CASE,\n LAMBDA(MIN,MAX,RETURN,\n IF(CASE=\"\",\"\",FILTER(RETURN,CASE>=MIN,CASE<=MAX))\n )(INDEX(REF,,1),INDEX(REF,,2),INDEX(REF,,3))\n ))\n)($A$1:$C$,$E$2:E),\"WHERE Col1 IS NOT NULL\")\n" }, { "answer_id": 74439913, "author": "Harun24hr", "author_id": 5514747, "author_profile": "https://Stackoverflow.com/users/5514747", "pm_score": 1, "selected": false, "text": "BYROW()" }, { "answer_id": 74444147, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 0, "selected": false, "text": "=INDEX(VLOOKUP(E2:E5; A2:C; 3))\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74439284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20495138/" ]
74,439,314
<p>I need to check when a new process with a new visible main window handle is started (as the mouse hook of my app is lost on some applications and is restored only on a short internal restart).</p> <p>I have tried to use <code>EnumWindows</code> and <code>EnumDesktopWindows</code> but those give me many many windows and child windows I do not need. I only need the visible main window handles. Therefore (and to find out if they are belonging to a new process) I decided to directly check the processes within an own update-check-thread. But this approach (as well as to permanently check EnumWindows) is extremely cpu consuming (1-3 % at Ryzen 5600X) and in my opinion, completely overblown.</p> <p>Therefore I'd like to know if there is any other, slick approach to find out whenever any new process is started or window is opened to only execute the check when it is necessary.</p>
[ { "answer_id": 74440561, "author": "Anders", "author_id": 3501, "author_profile": "https://Stackoverflow.com/users/3501", "pm_score": 1, "selected": false, "text": "WH_SHELL" }, { "answer_id": 74463839, "author": "tar", "author_id": 12622162, "author_profile": "https://Stackoverflow.com/users/12622162", "pm_score": 1, "selected": true, "text": "ApplicationWatcher" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74439314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12622162/" ]
74,439,329
<p>Basically I just want to change nested dictionaries but in my code I change multiple sublevel dictionaries at once.</p> <p>So I have a nested dictionary which looks this way</p> <pre><code>d1 = {'a': {0: [1,2], 1: [1,2]}, 'b': {0: [1,2], 1: [1,2]}} </code></pre> <p>Then I want to add an entry</p> <pre><code>d1['a'][2] = [2,2] </code></pre> <p>And then I get what I want</p> <pre><code>{'a': {0: [1, 2], 1: [1, 2], 2: [2, 2]}, 'b': {0: [1, 2], 1: [1, 2]}} </code></pre> <p>But when I want to create my dictionary like this (and I need it that way, because my dict has to have different lengths and so on)</p> <pre><code>d2 = dict.fromkeys(['a','b'], dict.fromkeys([0,1], [1,2])) </code></pre> <p>I will get</p> <pre><code>{'a': {0: [1, 2], 1: [1, 2], 2: [2, 2]}, 'b': {0: [1, 2], 1: [1, 2], 2: [2, 2]}} </code></pre> <p>so it will add the new dictionary entry to both lower level dictionaries. Why does it do this and how can I prevent this? I tried now a lot of stuff but I cant manage to solve this... Maybe you can help?</p>
[ { "answer_id": 74439439, "author": "RunnersNum45", "author_id": 7675722, "author_profile": "https://Stackoverflow.com/users/7675722", "pm_score": -1, "selected": false, "text": "dict.fromkeys(keys, default)" }, { "answer_id": 74439452, "author": "Thomas", "author_id": 10619758, "author_profile": "https://Stackoverflow.com/users/10619758", "pm_score": 1, "selected": true, "text": "dict.fromkeys(['a','b'], object())\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74439329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20478359/" ]
74,439,336
<p>I have a service that subscribes to an observable field of a dependency in the constructor. I am trying to write unit tests for this service, and in doing so, am trying to ignore the subscription to that observable. In other words, for some of these tests, I never want to emit a value, as I'm testing an unrelated function. How can I create a mock/spy of my service that simply does nothing with that observable?</p> <p><strong>Service</strong></p> <pre><code>export class MyService { constructor(private authService: AuthService) { this.authService.configure(); this.authService.events.subscribe(async (event) =&gt; { await this.authService.refreshToken(); }); } </code></pre> <p><strong>AuthService dependency</strong></p> <p>This is a snippet of the 3rd party service that my service depends on.</p> <pre><code>export declare class AuthService implements OnDestroy { events: Observable&lt;Event&gt;; // ... other fields/functions } </code></pre> <p><strong>Spec</strong></p> <pre><code>describe('MyService', () =&gt; { let authServiceSpy: jasmine.SpyObj&lt;AuthService&gt;; beforeEach(() =&gt; { authServiceSpy = jasmine.createSpyObj&lt;AuthService&gt;( ['configure', 'refreshToken'], { get events() { return defer(() =&gt; Promise.resolve(new Event('some_event'))); } } ); TestBed.configureTestingModule({}); }); it('should create service and configure authService', () =&gt; { const myService = new myService(authServiceSpy); expect(myService).toBeTruthy(); expect(authServiceSpy.configure).toHaveBeenCalledOnce(); }); }); </code></pre> <p>Whenever I run this test, the expectation is met but it also runs the callback in the observable subscription, and I haven't mocked the <code>refreshToken</code> call (and don't want to have to).</p>
[ { "answer_id": 74439439, "author": "RunnersNum45", "author_id": 7675722, "author_profile": "https://Stackoverflow.com/users/7675722", "pm_score": -1, "selected": false, "text": "dict.fromkeys(keys, default)" }, { "answer_id": 74439452, "author": "Thomas", "author_id": 10619758, "author_profile": "https://Stackoverflow.com/users/10619758", "pm_score": 1, "selected": true, "text": "dict.fromkeys(['a','b'], object())\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74439336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/491319/" ]
74,439,395
<p>so I don't know if I'm doing it right, but I wanted to make a button with a link in the submit input, but I don't know how to do that, the code is like this</p> <pre><code>&lt;form class=&quot;box&quot; action=&quot;index.html&quot; method=&quot;post&quot;&gt; &lt;h1&gt;Login&lt;/h1&gt; &lt;input type=&quot;text&quot; name=&quot;&quot; placeholder=&quot;Usuario&quot;&gt; &lt;input type=&quot;password&quot; name=&quot;&quot; placeholder=&quot;Insira Sua Senha&quot;&gt; &lt;input type=&quot;submit&quot; name=&quot;&quot; value=&quot;Login&quot;&gt;`in this part` </code></pre> <p>I tried to make a link with href and ul, I tried to create the button with div button, but it didn't stay in the position it was when I use the input.</p>
[ { "answer_id": 74439510, "author": "DotBased - Josh", "author_id": 20505455, "author_profile": "https://Stackoverflow.com/users/20505455", "pm_score": 2, "selected": true, "text": "<form class=\"box\" action=\"index.html\" method=\"post\" id=\"form\">\n <h1>Login</h1>\n <input type=\"text\" name=\"\" placeholder=\"Usuario\">\n <input type=\"password\" name=\"\" placeholder=\"Insira Sua Senha\">\n <div class=\"submit-button\" onclick=\"document.getElementById(\"form\").submit()\">\n <p>Login</p>\n <a href=\"link.html\">Link</a>\n </div>\n</form>\n" }, { "answer_id": 74439621, "author": "Afif Solahudin", "author_id": 20454883, "author_profile": "https://Stackoverflow.com/users/20454883", "pm_score": 2, "selected": false, "text": " <form class=\"box\" action=\"index.html\" method=\"post\">\n <h1>Login</h1>\n <input type=\"text\" name=\"\" placeholder=\"Usuario\">\n <input type=\"password\" name=\"\" placeholder=\"Insira Sua Senha\">\n <input type=\"button\" name=\"\" value=\"Login\" onclick=\"functionHere()\">`in this part`" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74439395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20505394/" ]
74,439,423
<p>I've seen a lot of times code like this:</p> <pre class="lang-scala prettyprint-override"><code>... val aString: String = someFunctionDataReturnsAString() ... if (someCondition) Some(aString) else ... </code></pre> <p>Is it right to create a new <code>Option</code> using <code>Some(aString)</code>? What if for some reason turns out the value of <code>aString</code> is <code>null</code>? Wouldn't be good replacing the <code>if</code> sentence with:</p> <pre class="lang-scala prettyprint-override"><code>if (someCondition) Option(aString) </code></pre> <p>Because:</p> <pre class="lang-scala prettyprint-override"><code>val a = Some(&quot;hello&quot;) val b: String = null val c = Some(b) val d = Option(b) println(a) println(c) println(d) </code></pre> <p>Will print in the console:</p> <pre><code>Some(hello) Some(null) None </code></pre> <p>Looks like a better idea to use <code>Option</code> when passing a string as parameter, so in case the string is <code>null</code> the value of the <code>Option</code> will be <code>None</code>.</p> <p>I've seen code to be reviewed and I think with cases like this a comment should be added asking for replacing <code>Some(aString)</code> with <code>Option(aString)</code>.</p>
[ { "answer_id": 74439775, "author": "Alin Gabriel Arhip", "author_id": 2205089, "author_profile": "https://Stackoverflow.com/users/2205089", "pm_score": 3, "selected": false, "text": "Option(aString)" }, { "answer_id": 74439908, "author": "Dmytro Mitin", "author_id": 5249621, "author_profile": "https://Stackoverflow.com/users/5249621", "pm_score": 2, "selected": false, "text": "Some.apply" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74439423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12806640/" ]
74,439,428
<p>I need to type some text inside a box but the text needs to be like typing but the box to just be thare. I also need it to be yellow.</p> <p>My code:</p> <pre><code> from termcolor import colored import sys, time, random import os os.system('clear') def print_slow(str): for letter in str: sys.stdout.write(letter) sys.stdout.flush() time.sleep(0.1) print(colored('----------------', 'yellow')) print_slow(' | something. |') print(colored('| |', 'yellow')) print(colored('----------------', 'yellow')) </code></pre> <p>I tried adding the two together but did not work.</p> <p>*I can get the color part to work just I need to print the text slowly and the box not.</p>
[ { "answer_id": 74439775, "author": "Alin Gabriel Arhip", "author_id": 2205089, "author_profile": "https://Stackoverflow.com/users/2205089", "pm_score": 3, "selected": false, "text": "Option(aString)" }, { "answer_id": 74439908, "author": "Dmytro Mitin", "author_id": 5249621, "author_profile": "https://Stackoverflow.com/users/5249621", "pm_score": 2, "selected": false, "text": "Some.apply" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74439428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19278203/" ]
74,439,437
<p>I'm working on a calculator that needs to calculate the date of birth from 3 inputs: the age in years, months and days:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> const arrDatas = []; const elmDataNasc = document.querySelector('#dataNasc'); function setDataAnos (e) { // store at position 0 of arrDates the years arrDatas[0] = e; setDataNasc(); } function setDataMeses (e) { // store in position 1 of arrDatas the months arrDatas[1] = e; setDataNasc(); } function setDataDias (e) { // store in position 2 of arrDatas the days arrDatas[2] = e; setDataNasc(); } function setDataNasc () { let anosDias = arrDatas[0] * 365; // convert years to days let mesesDias = arrDatas[1] * 30.417; // convert months to days (30,417 is the average of days per month) let diasDias = arrDatas[2]; // Days let totalDias = anosDias + mesesDias + diasDias; // add the total number of days and assign it to a variable let dataData = new Date(); // current date dataData.setDate( dataData.getDate() - totalDias); // subtract total days from the current date let data = dataData.toLocaleDateString("pt-BR", { year: "numeric", month: "2-digit", day: "2-digit",}); // format to DD/MM/YYYY elmDataNasc.value = data; // assign date to birthdate input }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;form&gt; &lt;p&gt;Enter data to calculate date of birth:&lt;/p&gt; &lt;label for="years"&gt;Years&lt;/label&gt; &lt;input onchange="setDataAnos(this.value)" type="number" name="years" min="0" max="31"&gt; &lt;label for="months"&gt;Months&lt;/label&gt; &lt;input onchange="setDataMeses(this.value)" type="number" name="months" min="0" max="11"&gt; &lt;label for="days"&gt;Days&lt;/label&gt; &lt;input onchange="setDataDias(this.value)" type="number" name="days" min="0" max="31"&gt; &lt;br&gt; &lt;br&gt; &lt;label for="dateBirth"&gt;Date of birth:&lt;/label&gt; &lt;input id="dataNasc" type="text" name="dataNasc" value="" disabled&gt; &lt;/form&gt;</code></pre> </div> </div> </p> <p>This script only allows you to calculate an approximate date, as it does not take into account the exact number of days in each month or leap years. I would like her to calculate the exact date of birth but I have no idea how to do that, I've racked my brains and searched the internet but nothing. Any light?</p>
[ { "answer_id": 74439597, "author": "Benjamin Penney", "author_id": 6545526, "author_profile": "https://Stackoverflow.com/users/6545526", "pm_score": -1, "selected": false, "text": "let arrDatas = [39, 4, 19];\n\nconst isLeapYear = year => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\nconst daysInYear = year => 365 + (isLeapYear(year) ? 1 : 0);\nconst daysInMonth = (year, month) => [31, 28 + (isLeapYear(year) ? 1 : 0), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];\n\nlet when = new Date();\nlet year = when.getFullYear();\nlet month = when.getMonth();\nlet day = when.getDate();\n\nlet totalDias = 0;\n\nif(month < 2)\n year--;\nfor(let i = 0; i < arrDatas[0]; i++)\n{\n totalDias += daysInYear(year);\n year--;\n}\nmonth--;\nfor(let i = 0; i < arrDatas[1]; i++)\n{\n totalDias += daysInMonth(year, month);\n month--;\n}\ntotalDias += arrDatas[2];\n\nlet dataData = new Date();\ndataData.setDate(dataData.getDate() - totalDias);\n\nconsole.log(\"You were born on\", dataData);" }, { "answer_id": 74439750, "author": "user3425506", "author_id": 3425506, "author_profile": "https://Stackoverflow.com/users/3425506", "pm_score": 0, "selected": false, "text": "const days = 22;\nconst months = 4;\nconst years = 63;\n\nlet d = new Date();\nd.setDate(d.getDate() - days);\nd.setMonth(d.getMonth() - months);\nd.setFullYear(d.getFullYear() - years);\nconsole.log(d);" }, { "answer_id": 74443638, "author": "RobG", "author_id": 257182, "author_profile": "https://Stackoverflow.com/users/257182", "pm_score": 3, "selected": true, "text": "function calcBirthday(y=0, m=0, d=0, datum = new Date()) {\n return new Date(\n datum.getFullYear() - y, \n datum.getMonth() - m,\n datum.getDate() - d);\n}\n\n// Someone who is 62 years, 11 months and 3 days old on 31 Jan 2020\n// was born on 28 Feb 1957\nconsole.log(calcBirthday(62, 11, 3, new Date(2020,0,31))\n .toDateString());\n\n// Someone who is 62 years, 11 months old on 29 Feb 2020\n// was born on 29 Mar 1957\nconsole.log(calcBirthday(62, 11, 0, new Date(2020,1,29))\n .toDateString());\n\n// Someone who is 62 years, 10 months, 29 days old on 29 Feb 2020\n// was born on 31 Mar 1957\nconsole.log(calcBirthday(62, 10, 29, new Date(2020,1,29))\n .toDateString());\n\n// Someone who is 1 year, 1 month and 1 day old today was\n// was born on…\nconsole.log(calcBirthday(1, 1, 1).toDateString());\n\n// Someone who is 1 year old on 29 Feb 2020 was\n// was born on…\nconsole.log(calcBirthday(1, 0, 0, new Date(2020,1,29))\n .toDateString());" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74439437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4154939/" ]
74,439,442
<p><a href="https://i.stack.imgur.com/kf67G.jpg" rel="nofollow noreferrer">enter image description here</a>Given a line of text as input, output the number of characters excluding spaces, periods, or commas.</p> <p>Ex: If the input is: <code>Listen, Mr. Jones, calm down.</code> the output is: <code>21</code></p> <p>Note: Account for all characters that aren't spaces, periods, or commas (Ex: &quot;r&quot;, &quot;2&quot;, &quot;!&quot;).</p> <p>I don't know what I am doing wrong. I have added a picture</p>
[ { "answer_id": 74439474, "author": "Noscere", "author_id": 10728583, "author_profile": "https://Stackoverflow.com/users/10728583", "pm_score": -1, "selected": false, "text": "print(len(string.replace(',','').replace(' ','').replace('.','')))\n" }, { "answer_id": 74453198, "author": "OneMadGypsy", "author_id": 10292330, "author_profile": "https://Stackoverflow.com/users/10292330", "pm_score": 1, "selected": false, "text": "sum" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74439442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20384092/" ]
74,439,443
<p>I am trying to upload a CSV file to my database in laravel. But my CSV file is pretty big, I almost have 500 million rows that I want to import. (I am using Maatwebsite to do this)</p> <p>And when I try to import it I am getting:</p> <pre><code>Maximum execution time of 300 seconds exceeded </code></pre> <p>As you can see I already changed the &quot;max_input_time&quot; in the php.init file. 300 seconds would be enough because datagrip takes only 3 minutes. And even if it would take longer in laravel there has to be another way than increasing the &quot;max_input_time&quot;</p> <p>this is the code that's converting the data in a model and evantually putting it in de database:</p> <pre><code>public function model(array $row) { return new DutchPostalcode([ 'postalcode' =&gt; $row['PostcodeID'], 'street' =&gt; $row['Straat'], 'place' =&gt; $row['Plaats'], 'government' =&gt; $row['Gemeente'], 'province' =&gt; $row['Provincie'], 'latitude' =&gt; $row['Latitude'], 'longtitude' =&gt; $row['Longitude'], ]); } </code></pre> <p>this is my controller:</p> <pre><code>public function writeDutchPostalCodes(){ Excel::import(new DutchPostalcodes, 'C:\Users\Moeme\Documents\Projects\ahmo apps\Apps\freshness\Freshness - be\FreshnessBE\resources\postalcodes\postcodetabel_1.csv'); } </code></pre>
[ { "answer_id": 74439474, "author": "Noscere", "author_id": 10728583, "author_profile": "https://Stackoverflow.com/users/10728583", "pm_score": -1, "selected": false, "text": "print(len(string.replace(',','').replace(' ','').replace('.','')))\n" }, { "answer_id": 74453198, "author": "OneMadGypsy", "author_id": 10292330, "author_profile": "https://Stackoverflow.com/users/10292330", "pm_score": 1, "selected": false, "text": "sum" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74439443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12274354/" ]
74,439,444
<p>I have two container buttons (blue and red) that alternate being visible when pressed. plus a counter that ticks up each time the blue button is pressed.</p> <pre><code>class Test extends StatefulWidget { const Test({Key? key}) : super(key: key); @override State&lt;Test&gt; createState() =&gt; _TestState(); } class _TestState extends State&lt;Test&gt; { int counter = 0; bool blueVisibility = true; bool redVisibility = false; @override Widget build(BuildContext context) { return Scaffold( body: Column( children: [ Expanded( child: Row( children: [ Expanded( child: Container( child: Visibility( visible: blueVisibility, child: InkWell( onTap: () { setState(() { redVisibility = true; blueVisibility = false; counter++; }); }, child: Container( margin: EdgeInsets.all(10), color: Colors.blue, height: 80, width: 50, ), ), ), ), ), Expanded( child: Container( child: Visibility( visible: redVisibility, child: InkWell( onTap: () { setState(() { redVisibility = false; blueVisibility = true; }); }, child: Container( margin: EdgeInsets.all(10), color: Colors.red, height: 80, width: 50, ), ), ), ), ), ], ), ), Container( height: 50, width: 50, color: Colors.blueGrey, alignment: Alignment.center, child: Text( '$counter', style: TextStyle( fontSize: 40, ), ), ), ], ), ); } } </code></pre> <p>Is it possible to make it so the blue box only adds to the counter the first time it is pressed and then not again after that while still retaining the ability to press the boxes to make them visible/invisible?</p> <p>thanks so much</p>
[ { "answer_id": 74439474, "author": "Noscere", "author_id": 10728583, "author_profile": "https://Stackoverflow.com/users/10728583", "pm_score": -1, "selected": false, "text": "print(len(string.replace(',','').replace(' ','').replace('.','')))\n" }, { "answer_id": 74453198, "author": "OneMadGypsy", "author_id": 10292330, "author_profile": "https://Stackoverflow.com/users/10292330", "pm_score": 1, "selected": false, "text": "sum" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74439444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20373623/" ]
74,439,490
<p>I'm new to Haskell and I'm currently trying to solve a little problem.</p> <p>I want to create a function <code>occurrences</code> that is defined as such:</p> <pre><code>occurrences:: Int -&gt; String -&gt; [[(Char, Int)]] </code></pre> <p>The function accepts an Int and String as its parameters; where Int represents the number of occurrence lists to be printed. The number of occurrences for each character should be sorted in descending order.</p> <p>For example, <code>occurrences 2 'hi'</code> should return <code>[[('h', 1), ('i', 1)], [('h', 1), ('i', 1)]]</code> and <code>occurrences 3 'foo'</code> would return <code>[[('o', 2), ('f', 1)], [('o', 2), ('f', 1)], [('o', 2), ('f', 1)]]</code></p> <p>So far I've added the below as part of my implementation for the occurrences function.</p> <pre><code>occurrences str = map (\x -&gt; [(head x, length x)]) $ group $ sort str </code></pre> <p>But this just prints <code>[[('h',1)],[('i',1)]]</code> rather than <code>[[('h', 1), ('i', 1)]]</code> and I'm not sure how to return <code>n</code> number of lists according to the input as I'm new to Haskell.</p> <p>Can I get help on this please?</p>
[ { "answer_id": 74439474, "author": "Noscere", "author_id": 10728583, "author_profile": "https://Stackoverflow.com/users/10728583", "pm_score": -1, "selected": false, "text": "print(len(string.replace(',','').replace(' ','').replace('.','')))\n" }, { "answer_id": 74453198, "author": "OneMadGypsy", "author_id": 10292330, "author_profile": "https://Stackoverflow.com/users/10292330", "pm_score": 1, "selected": false, "text": "sum" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74439490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10412970/" ]
74,439,491
<p>I have a sample dataframe:</p> <pre><code>| ID | SampleColumn1| SampleColumn2 | SampleColumn3 | |:-- |:------------:| ------------ :| ------------ | | 1 |sample Apple | sample Cherry |sample Lime | | 2 |sample Cherry | sample lemon | sample Grape | </code></pre> <p>I would like to create a new DataFrame based off of this initial dataframe. Should one of several values in a list [Apple, Lime, Cherry] be in any of the columns for a row, it would appear as a 1 in the new dataframe for its column. In this case, the output should be:</p> <pre><code>| ID | Apple | Lime | Cherry | | 1 | 1 | 1 | 1 | | 2 | 0 | 0 | 1 | </code></pre> <p>Currently I have tried in going about in using the find function for a string, transforming a series into a string for each row then using an if condition if the value has returned and equals the column name of the new dataframe. I am getting a logic error in this regard.</p>
[ { "answer_id": 74439910, "author": "crx91", "author_id": 11016395, "author_profile": "https://Stackoverflow.com/users/11016395", "pm_score": 0, "selected": false, "text": "fruits = ['Apple', 'Lime', 'Cherry']\ndef replace_fruit(string):\n for fruit in fruits:\n if fruit in string:\n return fruit\n return None\n\npd.get_dummies(df.set_index('ID').applymap(replace_fruit), prefix='', prefix_sep='').groupby(level=0, axis=1).sum().reset_index()\n" }, { "answer_id": 74439949, "author": "ziying35", "author_id": 16755671, "author_profile": "https://Stackoverflow.com/users/16755671", "pm_score": 1, "selected": false, "text": "keywords = ['Apple', 'Lime', 'Cherry']\ntmp = (df.melt(ignore_index=False)\n .value.str.extract(\n f'({\"|\".join(keywords)})',\n expand=False)\n .dropna())\n\nres = (pd.crosstab(index=tmp.index, columns=tmp)\n .rename_axis(index=None, columns=None))\nprint(res)\n>>>\n Apple Cherry Lime\n1 1 1 1\n2 0 1 0\n" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74439491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10981685/" ]
74,439,509
<p>Here is my data</p> <pre><code># Create the data frame. mydataframe &lt;- data.frame( emp_id = c (100,101,100,200,150,200,600,100,150,600), value = c(5,3,2,1,6,7,8,3,2,1) ) # Print the data frame. print(mydataframe) </code></pre> <p>I want to write a function to replace id's that occur multiple time in the id column by giving it a unique number, such as 100 will be P1, and 200 will be P2.</p> <pre><code> mydataframe %&gt;% mutate(emp_id = as.integer(factor(emp_id, levels = unique(emp_id)))) mydataframe %&gt;% mutate(emp_id = match(emp_id, unique(emp_id))) library(dplyr) mydataframe %&gt;% group_by(emp_id = factor(emp_id, levels = unique(emp_id))) %&gt;% mutate(emp_id = cur_group_id()) </code></pre> <p>I tried all these and it's working fine. But I still want to see P1, P2 , ...etc instead of 1, 2,3.</p> <p>Note: I call P1,P2, ...etc genrate names; maybe there is a better way to call this, but I just make it simple for better understanding</p> <pre><code>expected results will be emp_id ID value 1 1 P1 5 2 2 P2 3 3 1 P1 2 4 3 P3 1 5 4 P4 6 6 3 P3 7 7 5 P5 8 8 1 P1 3 9 4 P4 2 10 5 P5 1 </code></pre> <p>Thank you</p>
[ { "answer_id": 74439640, "author": "Nicolás Velásquez", "author_id": 8391095, "author_profile": "https://Stackoverflow.com/users/8391095", "pm_score": 2, "selected": false, "text": "library(tidyverse)\n\nmydataframe %>% \n left_join(x = . ,\n y = select( . , emp_id) %>% unique() %>% \n mutate(id = paste0(\"P\", row_number())), \n by = \"emp_id\") %>% \n relocate(id, .after = emp_id)\n\n emp_id id value\n1 100 P1 5\n2 101 P2 3\n3 100 P1 2\n4 200 P3 1\n5 150 P4 6\n6 200 P3 7\n7 600 P5 8\n8 100 P1 3\n9 150 P4 2\n10 600 P5 1\n" }, { "answer_id": 74439761, "author": "zephryl", "author_id": 17303805, "author_profile": "https://Stackoverflow.com/users/17303805", "pm_score": 2, "selected": true, "text": "dplyr::dense_rank()" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74439509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12096959/" ]
74,439,537
<p>The program is supposed to take two inputted strings, concatenate them, then print. This is the code I have right now and I am wondering how to go about this. I'm still new, so bear with me. Thanks in advance.</p> <pre><code>.586 .MODEL FLAT .STACK 4096 INCLUDE io.h .DATA Inputstr BYTE 100 DUP (?) Inputstr2 BYTE 100 DUP (?) Outputstr BYTE 100 DUP (?) prompt BYTE &quot;Enter a string&quot;, 0 displayLbl BYTE &quot;Concatinated string&quot;, 0 .CODE _MainProc PROC input prompt, Inputstr, 100 lea esi, Inputstr lea edi, Outputstr push esi push edi cld input prompt, Inputstr2, 100 lea esi, Inputstr2 lea edi, Outputstr push esi push edi cld whileNoNul: cmp BYTE PTR [esi], 0 je endWhileNoNul movsb loop whileNoNul endWhileNoNul: mov BYTE PTR [edi], 0 pop esi pop edi output displayLbl, Outputstr mov eax, 0 ret _MainProc ENDP END </code></pre> <p>My code is only printing my second input which is <em>Inputstr2</em>. It is supposed to print out both <em>Inputstr</em> and <em>Inputstr2</em> together.</p>
[ { "answer_id": 74439640, "author": "Nicolás Velásquez", "author_id": 8391095, "author_profile": "https://Stackoverflow.com/users/8391095", "pm_score": 2, "selected": false, "text": "library(tidyverse)\n\nmydataframe %>% \n left_join(x = . ,\n y = select( . , emp_id) %>% unique() %>% \n mutate(id = paste0(\"P\", row_number())), \n by = \"emp_id\") %>% \n relocate(id, .after = emp_id)\n\n emp_id id value\n1 100 P1 5\n2 101 P2 3\n3 100 P1 2\n4 200 P3 1\n5 150 P4 6\n6 200 P3 7\n7 600 P5 8\n8 100 P1 3\n9 150 P4 2\n10 600 P5 1\n" }, { "answer_id": 74439761, "author": "zephryl", "author_id": 17303805, "author_profile": "https://Stackoverflow.com/users/17303805", "pm_score": 2, "selected": true, "text": "dplyr::dense_rank()" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74439537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19862077/" ]
74,439,553
<pre><code>my_name = &quot;Ali&quot; my_age = 22 place_of_work = &quot; TD Bank&quot; introduction = 'Hi, my name is ' + my_name + ' and I am' , my_age , 'years old.' + ' I work at' + place_of_work + '.' print (introduction) </code></pre> <p>It prints with brackets and quotations. It works well when I change the variable introduction to print() but I just wanted to know why it doesn't work this way?</p>
[ { "answer_id": 74439640, "author": "Nicolás Velásquez", "author_id": 8391095, "author_profile": "https://Stackoverflow.com/users/8391095", "pm_score": 2, "selected": false, "text": "library(tidyverse)\n\nmydataframe %>% \n left_join(x = . ,\n y = select( . , emp_id) %>% unique() %>% \n mutate(id = paste0(\"P\", row_number())), \n by = \"emp_id\") %>% \n relocate(id, .after = emp_id)\n\n emp_id id value\n1 100 P1 5\n2 101 P2 3\n3 100 P1 2\n4 200 P3 1\n5 150 P4 6\n6 200 P3 7\n7 600 P5 8\n8 100 P1 3\n9 150 P4 2\n10 600 P5 1\n" }, { "answer_id": 74439761, "author": "zephryl", "author_id": 17303805, "author_profile": "https://Stackoverflow.com/users/17303805", "pm_score": 2, "selected": true, "text": "dplyr::dense_rank()" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74439553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20505542/" ]
74,439,556
<p>I have a list of times and I want to make a list of lists where the elements of the larger list is a list where the first element is the time and the second element is the number of minutes from a set time. So for example, this is what I have</p> <pre><code>['2022-04-08, 1:05 pm', '2022-04-09, 4:05 pm', '2022-04-10, 7:08 pm', '2022-04-11, 7:05 pm', '2022-04-12, 7:05 pm', '2022-04-13, 7:05 pm', '2022-04-14, 7:05 pm', '2022-04-22, 7:05 pm', '2022-04-23, 1:05 pm', '2022-04-24, 1:35 pm', '2022-04-26, 7:05 pm', '2022-04-27, 7:05 pm'] </code></pre> <p>I'd like to have a list like this:</p> <pre><code>[[['2022-04-08'], ['1:05 pm'],[(minutes after 11:00 A.M)]] [['2022-04-09'], ['4:05 pm'],[(minutes after 11:00 A.M)]], [['2022-04-10'], ['7:08 pm'],[(minutes after 11:00 A.M)]], [['2022-04-11'], ['7:05 pm'],[(minutes after 11:00 A.M)]], [['2022-04-12'], ['7:05 pm'],[(minutes after 11:00 A.M)]],etc. </code></pre>
[ { "answer_id": 74439640, "author": "Nicolás Velásquez", "author_id": 8391095, "author_profile": "https://Stackoverflow.com/users/8391095", "pm_score": 2, "selected": false, "text": "library(tidyverse)\n\nmydataframe %>% \n left_join(x = . ,\n y = select( . , emp_id) %>% unique() %>% \n mutate(id = paste0(\"P\", row_number())), \n by = \"emp_id\") %>% \n relocate(id, .after = emp_id)\n\n emp_id id value\n1 100 P1 5\n2 101 P2 3\n3 100 P1 2\n4 200 P3 1\n5 150 P4 6\n6 200 P3 7\n7 600 P5 8\n8 100 P1 3\n9 150 P4 2\n10 600 P5 1\n" }, { "answer_id": 74439761, "author": "zephryl", "author_id": 17303805, "author_profile": "https://Stackoverflow.com/users/17303805", "pm_score": 2, "selected": true, "text": "dplyr::dense_rank()" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74439556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20494739/" ]
74,439,568
<p>I have been doing a bit of brushing up on my Linear Algebra basics and figured a fun way to do so would be with code. I am trying to create a function that performs Vector addition given two vectors of different lengths. For example if we have two vectors v1 = 0, 7, 3 and v2 = 1, 2, 4 our sum would be 1, 9, 7. My end goal is to be able to create a function that accepts n number of vectors of any numeric type and perform traditional vector addition on them.</p> <p>So far I am able to naively do so by just traversing the first vector and adding each element to the corresponding element of second vector.</p> <pre><code>int main() { // create vectors std::vector&lt;int&gt; v1 = {0, 7, 3, 4}; std::vector&lt;int&gt; v2 = {1, 2, 4, 1, 6}; int i = 0; // iterate over v1 adding to the corresponding element in v2 for (i; i &lt; v1.size(); i++) { int sum = v1[i] + v2[i]; printf(&quot;sum - %d\n&quot;, sum); } return 0; } </code></pre> <p>What would the logic look like to add the elements of two vectors of different sizes?</p>
[ { "answer_id": 74439619, "author": "sxu", "author_id": 19694882, "author_profile": "https://Stackoverflow.com/users/19694882", "pm_score": 2, "selected": false, "text": "vector<int> sum;\nfor (int i=0; i < std::min(v1.size(),v2.size()); i++) {\n sum.push_back(v1[i] + v2[i]);\n}\n" }, { "answer_id": 74439820, "author": "David Wu", "author_id": 1299917, "author_profile": "https://Stackoverflow.com/users/1299917", "pm_score": 1, "selected": false, "text": "lhs" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74439568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19002577/" ]
74,439,569
<p>I'm trying to build a quick and simple webpage to test an HTTP Requests service that I'm building, and Flask seems to be making it way harder than it should be. All I want is to display any incoming HTTP Requests on the page, and then return the received payload to the service that called the webpage.</p> <p>Copying the Flask tutorial (plus the code for collecting HTTP requests) left me with this <code>app.py</code> file:</p> <pre class="lang-py prettyprint-override"><code>from flask import Flask, request, abort, jsonify, render_template, Response, stream_with_context, url_for, redirect app = Flask(__name__, template_folder = '') responses = [] @app.route('/') def index(): return render_template('index.html', resps = responses) @app.route('/request', methods = ['GET', 'POST']) def add_message(): print(&quot;Request dictionary: {}&quot;.format(request.json)) responses.append(request.json) return redirect('') app.run(host = '0.0.0.0', port = 81, debug = True) </code></pre> <p>I understand that <code>request.json</code> does not actually display all of the incoming data, but that is <a href="https://stackoverflow.com/questions/10434599/get-the-data-received-in-a-flask-request">easily solvable</a> assuming that the dynamic display of requests is at all possible.</p> <p>And here's my <code>index.html</code>:</p> <pre class="lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;title&gt;Flask Response Test Page&lt;/title&gt; &lt;/head&gt; &lt;body&gt; Web App with Python Flask!&lt;br&gt;&lt;br&gt; &lt;label id=&quot;value_lable&quot;&gt; {% for resp in resps %} {{ resp }}&lt;br&gt; {% endfor %} &lt;/label&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>My service that sends Python requests is really simple and works great. Basically, users type in the endpoint, payload, and output variable, and my service will send the request to <code>endpoint</code> and store the response in <code>variable</code>. I know it works because I can reload my Flask test page and it will show the list of received requests, and my service is printing out the input JSON as the request response. This code runs inside a Docker container so I am using <code>http://host.docker.internal:81/request</code> as my endpoint for the purposes of this test as per <a href="https://stackoverflow.com/a/72188215/8705841">this answer</a>.</p> <pre class="lang-py prettyprint-override"><code>import requests class JSONGETRequest(): def on_start(self, executive): # dict.get() returns None if the dict doesn't have the requested key endpoint = self.node.data.get(&quot;url&quot;) payload = self.node.data.get(&quot;payload&quot;) variable = self.node.data.get(&quot;variable&quot;) out = requests.get(endpoint, json = payload, headers = {&quot;User-Agent&quot;: &quot;&quot;}).json() executive.set_context(variable, out) executive.next(self.node, &quot;output_1&quot;) </code></pre> <h1>TL;DR:</h1> <p>I've tried a <em>bunch</em> of different answers posted on StackOverflow that are related to this question and none of them worked. Everything after this is the various things I tried already.</p> <hr /> <p>I attempted to use this page (<a href="https://stackoverflow.com/questions/40963401/flask-dynamic-data-update-without-reload-page">Flask Dynamic data update without reload page</a>) but that uses a button to force the page to reload, and I cannot find anything that indicates AJAX can activate/run a function whenever the page receives a Request. The vast majority of questions I've found relating to &quot;flask update page data without refresh&quot; all use a button but I really just want a streamed output of the requests as they come in.</p> <p>Edit: Based on NoCommandLine's comment I was able to fix my implementation of this answer, but it still fails to update the page in real-time, and requires a page reload in order to update the displayed data. I tried to use <a href="https://stackoverflow.com/a/64974111/8705841">this answer</a> ~~but got the error <code>werkzeug.routing.exceptions.BuildError: Could not build url for endpoint 'request'. Did you mean 'static' instead?</code> when using~~ with the following code:</p> <pre class="lang-py prettyprint-override"><code>@app.route('/requests', methods = ['GET', 'POST']) def add_message(): print(&quot;Request dictionary: {}&quot;.format(request.json)) responses.append(request.json) def inner(): # simulate a long process to watch for i in responses: # this value should be inserted into an HTML template yield i + '&lt;br/&gt;\n' return Response(inner(), mimetype = 'text/html') </code></pre> <pre class="lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;title&gt;Flask Response Test Page&lt;/title&gt; &lt;/head&gt; &lt;body&gt; Web App with Python Flask!&lt;br&gt;&lt;br&gt; &lt;div&gt; &lt;!-- url_for() is based off of the target method name, not the page name--&gt; &lt;iframe frameborder=&quot;0&quot; onresize=&quot;noresize&quot; src=&quot;{{ url_for('add_message')}}&quot; style='background: transparent; width: 100%; height:100%;'&gt; &lt;/iframe&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>~~Which honestly makes no sense since the <code>request</code> page <em>should</em> exist since I created the <code>@app.route('/request')</code>- it fails with both <code>url_for('request')</code> and <code>url_for('/request')</code>.~~</p> <hr /> <p>Supposedly there is &quot;quite a few tutorials&quot; on how to use AJAX but not a single on that I've found that even <em>MENTIONS</em> HTTP requests.</p> <p>How is there not a website or service that already does this? Just take in any incoming requests and print them out. There's no reason this should be this hard.</p> <hr /> <p>I tried using <code>@app.after_request</code> but it seems to be useless. And for some reason <code>render_template</code> is just a completely useless function that does absolutely nothing helpful:</p> <pre class="lang-py prettyprint-override"><code>@app.route('/request', methods = ['GET', 'POST']) def add_message(): print(&quot;Request dictionary: {}&quot;.format(request.json)) responses.append(request.json) return request.json @app.after_request def update(response): render_template('index.html', resps = responses) return response </code></pre> <p><a href="https://stackoverflow.com/questions/55763277/flask-how-to-automatically-render-template-when-receiving-post-request">This question</a> is basically a duplicate but has no (useful) answers.</p>
[ { "answer_id": 74439619, "author": "sxu", "author_id": 19694882, "author_profile": "https://Stackoverflow.com/users/19694882", "pm_score": 2, "selected": false, "text": "vector<int> sum;\nfor (int i=0; i < std::min(v1.size(),v2.size()); i++) {\n sum.push_back(v1[i] + v2[i]);\n}\n" }, { "answer_id": 74439820, "author": "David Wu", "author_id": 1299917, "author_profile": "https://Stackoverflow.com/users/1299917", "pm_score": 1, "selected": false, "text": "lhs" } ]
2022/11/15
[ "https://Stackoverflow.com/questions/74439569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8705841/" ]