qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,467,436
<p>I'm relatively uninitiated when it comes to Python, and I'm trying to figure out how to take an output I'm getting from a sensor into proper day, month, year and hour, minute, second format.</p> <p>An example of the output, which also includes a basic counter (the first output), and a timestamp (the third output) is shown below:</p> <pre><code>(305, struct_time(tm_year=2022, tm_mon=11, tm_mday=9, tm_hour=16, tm_min=42, tm_sec=8, tm_wday=2, tm_yday=313, tm_isdst=-1), 7.036) </code></pre> <p>I've seen a lot of questions and answers for this, but I'm left feeling kind of stumped on all of them because I'm not sure how to take the output I have (real_time, which gives a struct_time output) and turn it into this format. Any help (and understanding about my lack of fluency in this field) would be really appreciated!</p>
[ { "answer_id": 74467539, "author": "brebs", "author_id": 17628336, "author_profile": "https://Stackoverflow.com/users/17628336", "pm_score": 3, "selected": true, "text": "out(A, B, C) :-\n maplist(between(1, 2), [A, B, C]).\n" }, { "answer_id": 74467774, "author": "Enigmativity", "author_id": 259769, "author_profile": "https://Stackoverflow.com/users/259769", "pm_score": 2, "selected": false, "text": "fact(1).\nfact(2).\n\nout(A,B,C) :- fact(A), fact(B), fact(C).\n" }, { "answer_id": 74480436, "author": "Nicholas Carey", "author_id": 467473, "author_profile": "https://Stackoverflow.com/users/467473", "pm_score": 1, "selected": false, "text": "out(A,B,C) :-\n between(1,2,A),\n between(1,2,B),\n between(1,2,C).\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20524103/" ]
74,467,452
<p>This is the PCI CONFIG_ADDRESS register from <a href="http://pds5.egloos.com/pds/200709/07/88/pci21.pdf" rel="nofollow noreferrer">http://pds5.egloos.com/pds/200709/07/88/pci21.pdf</a> :</p> <p><a href="https://i.stack.imgur.com/1ZQzJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1ZQzJ.png" alt="The PCI CONFIG_ADDRESS register" /></a></p> <p>It shows the register number as bits [7-2]. This tells me I should left shift the register value by 2 when forming a CONFIG_ADDRESS value. So</p> <pre class="lang-py prettyprint-override"><code>(1 &lt;&lt; 31) | (bus &lt;&lt; 16) | (device &lt;&lt; 11) | (function &lt;&lt; 8) | (register &lt;&lt; 2) </code></pre> <p>Seen here: <a href="https://anadoxin.org/blog/pci-device-enumeration-using-ports-0xcf8-0xcfc.html/" rel="nofollow noreferrer">https://anadoxin.org/blog/pci-device-enumeration-using-ports-0xcf8-0xcfc.html/</a></p> <p>But I've also seen ANDing the register value with 0xFC like so:</p> <pre class="lang-py prettyprint-override"><code>(1 &lt;&lt; 31) | (bus &lt;&lt; 16) | (device &lt;&lt; 11) | (function &lt;&lt; 8) | (register &amp; 0xFC) </code></pre> <p>Seen here: <a href="https://wiki.osdev.org/Pci#Configuration_Space_Access_Mechanism_.231" rel="nofollow noreferrer">https://wiki.osdev.org/Pci#Configuration_Space_Access_Mechanism_.231</a> in pciConfigReadWord.</p> <p>These two methods produce different values for the CONFIG_ADDRESS register, so which one is correct?</p>
[ { "answer_id": 74467873, "author": "user363406", "author_id": 15210335, "author_profile": "https://Stackoverflow.com/users/15210335", "pm_score": 0, "selected": false, "text": "register >> 2" }, { "answer_id": 74470797, "author": "Brendan", "author_id": 559737, "author_profile": "https://Stackoverflow.com/users/559737", "pm_score": 2, "selected": false, "text": "(1 << 31) | (bus << 16) | (device << 11) | (function << 8) | (offset & 0xFC)\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15210335/" ]
74,467,454
<p>By &quot;independent 1&quot; I mean 1 that has no other 1 next to it (&quot;010&quot; or &quot;10&quot; and &quot;01&quot; at the ends of the num.) If the 1 doesn´t have any 1 next to it, it will change to 0.</p> <p>For example:</p> <p>11010 = 11000</p> <p>10101 = 00000</p> <p>1111 = 1111</p> <p>I can´t use for or while loops. Only bitwise operators.</p> <p>I tried something like this:</p> <pre><code>num = 0b11010 count = 0 if num &amp; 1 == 1: if (num &gt;&gt; 1) &amp; 1 == 1 or (num &lt;&lt; 1) &amp; 1 == 1: count += 1 else: count += 0 if (num &gt;&gt; 1) &amp; 1 == 1: if (num &gt;&gt; 2) &amp; 1 == 1 or (num &gt;&gt; 0) &amp; 1 == 1: count += 2 else: count += 0 . . . #(Same principle) </code></pre> <p>But the code will get too long when I try to implement it for bigger numbers.</p>
[ { "answer_id": 74467610, "author": "Ramazan Şen", "author_id": 20523910, "author_profile": "https://Stackoverflow.com/users/20523910", "pm_score": -1, "selected": false, "text": "a = [3, 5, 8, 1, 2, 7]\nb = [2, 6, 8]\nlenA, lenB = len(a), len(b)\n# Getting the absolute value of abs\ndiff = abs(lenA - lenB)\nif lenA < lenB:\n # extend expands the list. will add an absolute value of zero to the end\n a.extend([0]*diff)\nelse:\n b.extend([0]*diff)\nprint(b)\n" }, { "answer_id": 74469327, "author": "greenerpastures", "author_id": 15279460, "author_profile": "https://Stackoverflow.com/users/15279460", "pm_score": 2, "selected": true, "text": "num = 0b11010\n\n# Assume 32 bit, make sure only zeros are shifted in on either side\nnum_l1 = (num<<1)&(~0x1) # make sure the new right bit is zero\nnum_r1 = (num>>1)&(~0x80000000) # make sure the new left bit is zero\n\n# Print the left and right shifted numbers along with num. As we can see, we\n# are looking for bits which are a 1 in the num, but a 0 in both left and right\n# shift.\nprint(f' Left Shifted Number: {\"{:032b}\".format((num<<1)&(~0x1))}')\nprint(f' Number: {\"{:032b}\".format(num)}')\nprint(f'Right Shifted Number: {\"{:032b}\".format((num>>1)&(~0x80000000))}')\n\n# XORing with left and right will highlight values that are either 010 or 101 in\n# the original num. We only want 010, so we then AND the new sequence with\n# the original num to only allow 010 sequences to pass.\nfind_lonely_ones = num & ((num^num_l1) & (num^num_r1))\n\n# We can then invert the lonely bits and AND with the original num\nnew_num = num & (~find_lonely_ones)\nprint()\nprint(f' Number: {\"{:0b}\".format(num)}')\nprint(f'Final Answer: {\"{:0b}\".format(new_num)}')\n\n\n# We can print each step for clarification\nprint()\nprint(f' Left Shifted Number XOR Number: {\"{:032b}\".format(num^num_l1)}')\nprint(f'Right Shifted Number XOR Number: {\"{:032b}\".format(num^num_r1)}')\nprint(f' AND of the above operations: {\"{:032b}\".format((num^num_l1) & (num^num_r1))}')\nprint(f' The above value AND Number: {\"{:032b}\".format(find_lonely_ones)}')\nprint(f' NOT the above value AND Number: {\"{:032b}\".format(num & (~find_lonely_ones))}')\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20524079/" ]
74,467,465
<p>Suppose you have an Optional and you want to consume the Optional multiple times. You could now save the Optional to a variable; and then use <code>ifPresent</code> two times on it:</p> <pre class="lang-java prettyprint-override"><code>Optional&lt;Animal&gt; optionalAnimal = animalService.getAllAnimals().findFirst(); optionalAnimal.ifPresent(Animal::eat); optionalAnimal.ifPresent(Animal::drink); </code></pre> <p>Another solution would be to ditch method references and use a lambda that does both:</p> <pre class="lang-java prettyprint-override"><code>animalService.getAllAnimals().findFirst() .ifPresent(animal -&gt; { animal.drink(); animal.eat(); }); </code></pre> <p>If I have control over the class that is used in the Optional, I could simply change the methods to use a factory like pattern. So that <code>animal.drink()</code> would return itself. Then I could write:</p> <pre class="lang-java prettyprint-override"><code>animalService.getAllAnimals().findFirst() .map(Animal::drink) .ifPresent(Animal::eat); </code></pre> <p>But this would be semantically weird. And I don’t always have control over every class that I use in Optionals. And some classes are final, so I could not even extend them to have a factory styled method.</p> <p>Furthermore, the Optional class is also final, so extending Optional itself is no option either. All of this makes very little sense to me. <code>ifPresent()</code> returns void. If <code>ifPresent()</code> returned the Optional itself (similar to <code>peek()</code> for streams) it would be closer to my goal.</p> <p>Is there another solution that I did not think of?</p> <hr /> <p>What I would like to have is something like this:</p> <pre class="lang-java prettyprint-override"><code>animalService.getAllAnimals().findFirst() .ifPresent(Animal::drink) .ifPresent(Animal::eat); </code></pre>
[ { "answer_id": 74467588, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 4, "selected": true, "text": "Consumer.andThen()" }, { "answer_id": 74511082, "author": "cyberbrain", "author_id": 2846138, "author_profile": "https://Stackoverflow.com/users/2846138", "pm_score": 0, "selected": false, "text": "Optional" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17133024/" ]
74,467,471
<p>I cant have 2 init methods in one class because of function overloading. However, why is it possible that when initializing a subclass, im able to define a new <code>__init__</code> method, and use the <code>super().__init__</code> method or the parentclass init method within the subclass <code>__init__</code> method. i'm just a little confused by the concept of 2 <code>__init__</code> methods functioning at the same time</p> <pre class="lang-py prettyprint-override"><code>class Employee: emps = 0 def __init__(self,name,age,pay): self.name = name self.age = age self.pay = pay class Developer(Employee): def __init__(self,name,age,pay,level): Employee.__init__(self,name,age,pay) self.level = level </code></pre>
[ { "answer_id": 74467534, "author": "Harez", "author_id": 20352132, "author_profile": "https://Stackoverflow.com/users/20352132", "pm_score": 0, "selected": false, "text": "super()" }, { "answer_id": 74504251, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 2, "selected": true, "text": "__init__" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20389571/" ]
74,467,540
<p>I am trying to count the number of occurrences of each character within a large dateset. For example, if the data was the numpy array ['A', 'AB', 'ABC'] then I would want {'A': 3, 'B': 2, 'C': 1} as the output. I currently have an implementation that looks like this:</p> <pre><code>char_count = {} for c in string.printable: char_count[c] = np.char.count(data, c).sum() </code></pre> <p>The issue I am having is that this takes too long for my data. I have ~14,000,000 different strings that I would like to count and this implementation is not efficient for that amount of data. Any help is appreciated!</p>
[ { "answer_id": 74467637, "author": "Dani Mesejo", "author_id": 4001592, "author_profile": "https://Stackoverflow.com/users/4001592", "pm_score": 1, "selected": false, "text": "import numpy as np\nfrom collections import defaultdict\n\ndata = np.array(['A', 'AB', 'ABC'])\n\ncounts = defaultdict(int)\nfor e in data:\n for c in e:\n counts[c] += 1\n\nprint(counts)\n" }, { "answer_id": 74467663, "author": "wwii", "author_id": 2823755, "author_profile": "https://Stackoverflow.com/users/2823755", "pm_score": 3, "selected": true, "text": "import collections\nc = collections.Counter()\nfor thing in data:\n c.update(thing)\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19407888/" ]
74,467,546
<p>Imagine I have an ordered std::vector <code>A = {x1, x2, ..., xn}</code> and I want to perform an operation on every subsequent pair of items, e.g. <code>f(x1, x2); f(x2, x3); ... f(xn-1, xn); f(xn, x1)</code>.</p> <p>I could iterate like I normally would, while tracking the previous item:</p> <pre><code>for (auto x : A) { ... f(previous_x, x); previous_x = x; } f(previous_x, first_x); </code></pre> <p>But is there a better way to iterate through this vector? Are there features in the language that can streamline this?</p> <p>Tried the solution provided. It works, but curious to know if there is a cleaner and more concise way.</p>
[ { "answer_id": 74467631, "author": "Ted Lyngmo", "author_id": 7582247, "author_profile": "https://Stackoverflow.com/users/7582247", "pm_score": 2, "selected": false, "text": "A.size()" }, { "answer_id": 74467672, "author": "Vlad from Moscow", "author_id": 2877241, "author_profile": "https://Stackoverflow.com/users/2877241", "pm_score": 3, "selected": false, "text": " std::vector<int> v = { 1, 2, 3, 4, 5 };\n\n for (std::vector<int>::size_type i = 0, n = std::size( v ); i < n; i++)\n {\n std::cout << v[i] + v[( i + 1 ) % n] << ' ';\n }\n std::cout << '\\n';\n" }, { "answer_id": 74467832, "author": "rturrado", "author_id": 260313, "author_profile": "https://Stackoverflow.com/users/260313", "pm_score": 2, "selected": false, "text": "[1, 2, 3, 4, 5]" }, { "answer_id": 74468318, "author": "Pete Becker", "author_id": 1593860, "author_profile": "https://Stackoverflow.com/users/1593860", "pm_score": 1, "selected": false, "text": "A.push_back(A[0]); // copy first element to end\nfor (int j = 0; j < A.size() - 1; ++j)\n f(A[j], A[j+1]);\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3120880/" ]
74,467,567
<p>My problems or rather my misunderstanding are next.</p> <p><strong>First one:</strong></p> <p>Basically i made my linked list class, and now as you can see in following code in constructor i called append method before it was actually created and the code run without an error, so i am really interested to know why i didn't encountered any error there.</p> <pre><code>class Node: def __init__(self, value): self.value = value self.next = None class Linkedlist: def __init__(self, *value): if len(value) == 1: new_node = Node(value[0]) self.head = new_node self.tail = new_node self.lenght = 1 else: self.__init__(value[0]) other_values = value[1::] for i in other_values: self.append(i) print('test1') def append(self, *value): for i in value: new_node = Node(i) if self.head == None: self.head = new_node self.tail = new_node else: self.tail.next = new_node self.tail = new_node self.lenght += 1 print('test2') return True </code></pre> <p>Second one:</p> <p>As you can see i left print function in both constructor and append method in order to see how things are going. when i execute next code:</p> <pre><code>my_linked_list = Linkedlist(3, 2, 7, 9) </code></pre> <p>i get the output as following: test1, test2, test2, test2, test1 and i was expecting only test2, test2, test2, test1, i am curious why does it print test1 first.</p> <p>Sorry if my question was too long. I am quite new to programming and really curious about a lot of things. Answer would be greatly appreciated.</p>
[ { "answer_id": 74467712, "author": "Edward Peters", "author_id": 6016064, "author_profile": "https://Stackoverflow.com/users/6016064", "pm_score": 1, "selected": false, "text": "__init__" }, { "answer_id": 74467799, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 0, "selected": false, "text": "Linkedlist.__init__" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18693937/" ]
74,467,604
<p>I'm new to Vue and done a little bit of html and css, i want to use a variable as the image directory but the image never loads, the variable is being updated by a tauri function which works and i need the image to change as well.</p> <p>this is a bit of my code</p> <pre class="lang-html prettyprint-override"><code>&lt;template&gt; &lt;img v-bind:src=getimg()&gt; -- and -- &lt;img :src = {{data}}}&gt; -- and -- &lt;img src = {{data}}&gt; -- and much more ... -- &lt;/template&gt; &lt;script setup&gt; var data = ref(&quot;./assets/4168-376.png&quot;) function getimg() { console.log(data1.value) return require(data1.value) } &lt;/setup&gt; </code></pre>
[ { "answer_id": 74467646, "author": "Vasyl", "author_id": 17099154, "author_profile": "https://Stackoverflow.com/users/17099154", "pm_score": 0, "selected": false, "text": "<img :src=\"data\">\n" }, { "answer_id": 74468156, "author": "Ezra Siton", "author_id": 9291557, "author_profile": "https://Stackoverflow.com/users/9291557", "pm_score": 0, "selected": false, "text": "v-bind:src /*or :src */\n" }, { "answer_id": 74470040, "author": "Remicaster", "author_id": 18665782, "author_profile": "https://Stackoverflow.com/users/18665782", "pm_score": 1, "selected": false, "text": "<img :src=\"variable\"> // just use : in front of an attribute and it will consider as v-bind\n<img v-bind:src=\"variable\"> // or you directly use v-bind, less commonly used\n<img :src=\"'static string'\"> // no point doing this, but just a reference of how it works\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18187543/" ]
74,467,623
<p>I am trying to convert a column called <code>Month_Next</code> from a dataframe called <code>df_actual</code> from the last day of one month to the first day of the next. The column looks like this:</p> <p><a href="https://i.stack.imgur.com/5IRm7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5IRm7.png" alt="enter image description here" /></a></p> <p>And I'm using</p> <pre><code>df_actual.Month_Next = pd.to_datetime(df_actual.Month_Next) + relativedelta(months=1, day=1) </code></pre> <p>and getting this error.</p> <pre><code>TypeError: unsupported operand type(s) for +: 'DatetimeArray' and 'relativedelta' </code></pre> <p>Which makes no sense to me since this exact code works in a different notebook where <code>Month_Next</code> comes in as I believe a Timestamp object like so</p> <p><a href="https://i.stack.imgur.com/VFEDa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VFEDa.png" alt="enter image description here" /></a></p> <p>Any ideas as to what's going on here?</p>
[ { "answer_id": 74467646, "author": "Vasyl", "author_id": 17099154, "author_profile": "https://Stackoverflow.com/users/17099154", "pm_score": 0, "selected": false, "text": "<img :src=\"data\">\n" }, { "answer_id": 74468156, "author": "Ezra Siton", "author_id": 9291557, "author_profile": "https://Stackoverflow.com/users/9291557", "pm_score": 0, "selected": false, "text": "v-bind:src /*or :src */\n" }, { "answer_id": 74470040, "author": "Remicaster", "author_id": 18665782, "author_profile": "https://Stackoverflow.com/users/18665782", "pm_score": 1, "selected": false, "text": "<img :src=\"variable\"> // just use : in front of an attribute and it will consider as v-bind\n<img v-bind:src=\"variable\"> // or you directly use v-bind, less commonly used\n<img :src=\"'static string'\"> // no point doing this, but just a reference of how it works\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19980284/" ]
74,467,639
<p>I need a Regular Expression for Javascript that replaces a string (for example &gt;//&lt;) if its inside any type of quotes. For example</p> <pre><code>&gt;This is a test &quot;With a text including // and more&quot; for replacement&lt; </code></pre> <p>I cant get the combination of Reg Expression rules working Im not good at that and its easy for some of you ;)</p>
[ { "answer_id": 74467646, "author": "Vasyl", "author_id": 17099154, "author_profile": "https://Stackoverflow.com/users/17099154", "pm_score": 0, "selected": false, "text": "<img :src=\"data\">\n" }, { "answer_id": 74468156, "author": "Ezra Siton", "author_id": 9291557, "author_profile": "https://Stackoverflow.com/users/9291557", "pm_score": 0, "selected": false, "text": "v-bind:src /*or :src */\n" }, { "answer_id": 74470040, "author": "Remicaster", "author_id": 18665782, "author_profile": "https://Stackoverflow.com/users/18665782", "pm_score": 1, "selected": false, "text": "<img :src=\"variable\"> // just use : in front of an attribute and it will consider as v-bind\n<img v-bind:src=\"variable\"> // or you directly use v-bind, less commonly used\n<img :src=\"'static string'\"> // no point doing this, but just a reference of how it works\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12795379/" ]
74,467,641
<p>I'm having troubles getting chrome storage API to work in MV3. I've tried this so far and even in the service worker console it returns an undefined result</p> <pre><code>chrome.storage.local.set({ 'test': 'test' }, function() { chrome.storage.local.get('test', function(result) { console.log('Value currently is ' + result); }); }); </code></pre> <p>Here is my manifest I'm not sure if that's an issue</p> <pre><code>{ &quot;manifest_version&quot;: 3, &quot;name&quot;: &quot;NAME&quot;, &quot;description&quot;: &quot;Description&quot;, &quot;version&quot;: &quot;0.0.3&quot;, &quot;background&quot;: { &quot;service_worker&quot;: &quot;background.js&quot; }, &quot;content_security_policy&quot;: { &quot;extension_pages&quot;: &quot;script-src 'self'; object-src 'self'&quot; }, &quot;action&quot;: { &quot;default_icon&quot;: { &quot;16&quot;: &quot;favicon.ico&quot; }, &quot;default_title&quot;: &quot;Outboundly&quot;, &quot;default_popup&quot;: &quot;index.html&quot; }, &quot;permissions&quot;: [ &quot;storage&quot;, &quot;scripting&quot;, &quot;activeTab&quot;, &quot;tabs&quot;, &quot;unlimitedStorage&quot; ], &quot;host_permissions&quot;: [&quot;&lt;all_urls&gt;&quot;] } </code></pre> <p>I've also tried it in the content script and within the popup context as well.</p>
[ { "answer_id": 74467646, "author": "Vasyl", "author_id": 17099154, "author_profile": "https://Stackoverflow.com/users/17099154", "pm_score": 0, "selected": false, "text": "<img :src=\"data\">\n" }, { "answer_id": 74468156, "author": "Ezra Siton", "author_id": 9291557, "author_profile": "https://Stackoverflow.com/users/9291557", "pm_score": 0, "selected": false, "text": "v-bind:src /*or :src */\n" }, { "answer_id": 74470040, "author": "Remicaster", "author_id": 18665782, "author_profile": "https://Stackoverflow.com/users/18665782", "pm_score": 1, "selected": false, "text": "<img :src=\"variable\"> // just use : in front of an attribute and it will consider as v-bind\n<img v-bind:src=\"variable\"> // or you directly use v-bind, less commonly used\n<img :src=\"'static string'\"> // no point doing this, but just a reference of how it works\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15788211/" ]
74,467,642
<p>I recently upgraded to Entity Framework Core 7 in development and I'm getting an exception, &quot;A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.)&quot; I am using Microsoft SQL Server Developer (64-bit). I have tried to make changes in the VS2022 Server Explorer to disable encryption and to trust the server certificate, I don't have one installed, but the exception remains. How can this be mitigated in development?</p>
[ { "answer_id": 74516640, "author": "MeTaLiKiD", "author_id": 3105574, "author_profile": "https://Stackoverflow.com/users/3105574", "pm_score": 0, "selected": false, "text": "Microsoft.EntityFrameworkCore.SqlServer" }, { "answer_id": 74577373, "author": "hassane", "author_id": 11715549, "author_profile": "https://Stackoverflow.com/users/11715549", "pm_score": 1, "selected": false, "text": "Encrypt=False" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3802434/" ]
74,467,653
<p>I'm attempting to use Outh authentication for my PHP request to Salesforce but I can't get my ClientID and SecretID for my app.<br> I normally have an option to View these values but for some reason I'm unable to view them with an administrator login.<br> I created a new App and was able to get the credentials successfully, so I know it's not the account permissions preventing me from accessing this information.<br> Does anyone with experience of Salesforce have any experience with an inability to get these details?<br> Thanks!</p>
[ { "answer_id": 74516640, "author": "MeTaLiKiD", "author_id": 3105574, "author_profile": "https://Stackoverflow.com/users/3105574", "pm_score": 0, "selected": false, "text": "Microsoft.EntityFrameworkCore.SqlServer" }, { "answer_id": 74577373, "author": "hassane", "author_id": 11715549, "author_profile": "https://Stackoverflow.com/users/11715549", "pm_score": 1, "selected": false, "text": "Encrypt=False" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9203605/" ]
74,467,660
<p>I am working on a project for which I have to parse and query a relatively large xml file in python. I am using a dataset with data about scientific articles. The dataset can be found via this link (<a href="https://dblp.uni-trier.de/xml/dblp.xml.gz" rel="nofollow noreferrer">https://dblp.uni-trier.de/xml/dblp.xml.gz</a>). There are 7 types of entries in the dataset: <code>article</code>, <code>inproceedings</code>, <code>proceedings</code>, <code>book</code>, <code>incollection</code>, <code>phdthesis</code> and <code>masterthesis</code>. An entry has the following attributes: <code>author</code>, <code>title</code>, <code>year</code> and either <code>journal</code> or <code>booktitle</code>.</p> <p>I am looking for the best way to parse this and consequently perform queries on the dataset. Examples of queries that I would like to perform are:</p> <ul> <li>retrieve articles that have a certain author</li> <li>retrieve articles if the title contains a certain word</li> <li>retrieve articles to which author x and author y both contributed.</li> <li>...</li> </ul> <p>Herewith a snapshot of an entry in the xml file:</p> <pre><code>&lt;article mdate=&quot;2020-06-25&quot; key=&quot;tr/meltdown/s18&quot; publtype=&quot;informal&quot;&gt; &lt;author&gt;Paul Kocher&lt;/author&gt; &lt;author&gt;Daniel Genkin&lt;/author&gt; &lt;author&gt;Daniel Gruss&lt;/author&gt; &lt;author&gt;Werner Haas 0004&lt;/author&gt; &lt;author&gt;Mike Hamburg&lt;/author&gt; &lt;author&gt;Moritz Lipp&lt;/author&gt; &lt;author&gt;Stefan Mangard&lt;/author&gt; &lt;author&gt;Thomas Prescher 0002&lt;/author&gt; &lt;author&gt;Michael Schwarz 0001&lt;/author&gt; &lt;author&gt;Yuval Yarom&lt;/author&gt; &lt;title&gt;Spectre Attacks: Exploiting Speculative Execution.&lt;/title&gt; &lt;journal&gt;meltdownattack.com&lt;/journal&gt; &lt;year&gt;2018&lt;/year&gt; &lt;ee type=&quot;oa&quot;&gt;https://spectreattack.com/spectre.pdf&lt;/ee&gt; &lt;/article&gt; </code></pre> <p>Does anybody have an idea on how to do to this efficiently?</p> <p>I have experimented with using the ElementTree. However, when parsing the file I get the following error:</p> <pre><code>xml.etree.ElementTree.ParseError: undefined entity &amp;Ouml;: line 90, column 17 </code></pre> <p>Additionally, I am not sure if using the ElementTree will be the most efficient way for querying this xml file.</p>
[ { "answer_id": 74516640, "author": "MeTaLiKiD", "author_id": 3105574, "author_profile": "https://Stackoverflow.com/users/3105574", "pm_score": 0, "selected": false, "text": "Microsoft.EntityFrameworkCore.SqlServer" }, { "answer_id": 74577373, "author": "hassane", "author_id": 11715549, "author_profile": "https://Stackoverflow.com/users/11715549", "pm_score": 1, "selected": false, "text": "Encrypt=False" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14604882/" ]
74,467,682
<p>I have a list</p> <pre><code>flat_list =['53295,-46564.2', '53522.6,-46528.4', '54792.9,-46184', '55258.7,-46512.9', '55429.4,-48356.9', '53714.5,-50762.8'] </code></pre> <p>How can I convert it into</p> <pre><code>[[53295,-46564.2], [53522.6,-46528.4], [54792.9,-46184], [55258.7,-46512.9], [55429.4,-48356.9], [53714.5,-50762.8]] </code></pre> <p>I tried</p> <pre><code>l = [i.strip(&quot;'&quot;) for i in flat_list] </code></pre> <p>nothing works.</p> <pre><code>l = [i.strip(&quot;'&quot;) for i in flat_list] </code></pre> <pre><code> coords = [map(float,i.split(&quot;,&quot;)) for i in flat_list] </code></pre> <pre><code>print(coords) </code></pre> <p>gives me &lt;map object at 0x7f7a7715d2b0&gt;</p>
[ { "answer_id": 74467801, "author": "payloc91", "author_id": 8524301, "author_profile": "https://Stackoverflow.com/users/8524301", "pm_score": 2, "selected": false, "text": "list2 = [[float(f) for f in el.split(\",\")] for el in flat_list]\n" }, { "answer_id": 74467835, "author": "Ersin Nurtin", "author_id": 19982983, "author_profile": "https://Stackoverflow.com/users/19982983", "pm_score": 0, "selected": false, "text": " flat_list =['53295,-46564.2', '53522.6,-46528.4', '54792.9,-46184', '55258.7,-46512.9', '55429.4,-48356.9', '53714.5,-50762.8']\ncoordinates = []\nfor pair in flat_list:\n coordinates.extend(pair.split(','))\nresult = [float(x) for x in coordinates]\n" }, { "answer_id": 74467864, "author": "rv.kvetch", "author_id": 10237506, "author_profile": "https://Stackoverflow.com/users/10237506", "pm_score": 4, "selected": true, "text": "map" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3499052/" ]
74,467,684
<p>It's my first time using Firestore Cloud Messaging and I want to get the FCM token for each specific device. For quick development, I added the firebase_auth_ui package, which basically outsources the firebase auth login and registration flow. To capture the user's id and store in their doc, I use a simple function that works fine: and gets the job done:</p> <pre><code>Future&lt;void&gt; addUserDataToFireStore() async { CollectionReference users = FirebaseFirestore.instance.collection('users'); String uid = FirebaseAuth.instance.currentUser!.uid; users.doc(uid).set({ 'userId': uid, // 'displayName': currentUser!.displayName!, }); } </code></pre> <p>Now, for some reason when I try to access the registration token, my userId gets deleted. When I try to add the token to the same user doc, the userId gets deleted and the fcm token stays. I generate the token as follows:</p> <pre><code>generateDeviceToken() async { String? fcmToken = await FirebaseMessaging.instance.getToken(); final userId = FirebaseAuth.instance.currentUser!.uid; await FirebaseFirestore.instance .collection('users') .doc(userId) .set({'fcmToken': fcmToken}); } </code></pre> <p>The issue is when I try to call them both. I can't get the two. The doc will fill with either UserId or FCM, but now both. This is what happens when I try to call both, <a href="https://i.stack.imgur.com/h7WJl.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/h7WJl.gif" alt="enter image description here" /></a></p> <p>Perhaps I should make a method that updates fcm token and not set it everytimg?</p>
[ { "answer_id": 74468548, "author": "Maniak", "author_id": 20006884, "author_profile": "https://Stackoverflow.com/users/20006884", "pm_score": 1, "selected": false, "text": "generateDeviceToken() async {\nString? fcmToken = await FirebaseMessaging.instance.getToken();\nfinal userId = FirebaseAuth.instance.currentUser!.uid;\nawait FirebaseFirestore.instance\n .collection('users')\n .doc(userId)\n .update({'fcmToken': fcmToken});\n }\n" }, { "answer_id": 74489586, "author": "Hunter Books", "author_id": 16922954, "author_profile": "https://Stackoverflow.com/users/16922954", "pm_score": 0, "selected": false, "text": "Future<void> addUserDataToFireStore() async {\n final userId = FirebaseAuth.instance.currentUser!.uid;\n final userDocRef = FirebaseFirestore.instance.collection('users').doc(userId);\n final doc = await userDocRef.get();\n\n if (doc.exists) {\n return;\n } else {\n userDocRef.set({\n 'userId': userId,\n });\n }\n}\n\nFuture<void> generateDeviceToken() async {\n String? fcmToken = await FirebaseMessaging.instance.getToken();\n final userId = FirebaseAuth.instance.currentUser!.uid;\n await FirebaseFirestore.instance\n .collection('users')\n .doc(userId)\n .update({'fcmToken': fcmToken});\n}\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16922954/" ]
74,467,688
<p><code>create table DogLicense ( License int IDENTITY(1,1) PRIMARY KEY, Expires date NOT NULL CHECK(Expires &gt; '1990-01-01') , Sex char(2) NOT NULL CONSTRAINT check_Sex_M_F_NM_SF CHECK (Sex IN ('M','F','NM','SF')), PetName char(50) NOT NULL , Breed char(50) , OwnerLastName char(50) NOT NULL , OwnerFirstName char(50) NOT NULL , Address char(50) , Zip Char(5) NOT NULL CHECK(Zip &gt;= 99201 and zip &lt;= 99212), Phone char(10) , )</code></p> <p>So I have created the table above and when attempting to enter my first row of data I get the error</p> <p><code>Msg 241, Level 16, State 1, Line 1 Conversion failed when converting date and/or time from character string.</code></p> <p>My insert into statement is as follows. From everything I have read so far I'm using the correct format. Any idea why this isn't working?</p> <p><code>insert into DogLicense values ('2023-21-06','NM', 'Rosco', 'St. Bernard','Freeman','Mark', '123 Medow Ln.','99207','5095551212' )</code></p> <p>I have tried not using quotes but I get</p> <p>`Msg 206, Level 16, State 2, Line 1 Operand type clash: int is incompatible with date'</p>
[ { "answer_id": 74467813, "author": "DanielT", "author_id": 20400287, "author_profile": "https://Stackoverflow.com/users/20400287", "pm_score": 0, "selected": false, "text": "insert into DogLicense values ('2023-06-21','NM', 'Rosco', 'St. Bernard','Freeman','Mark', '123 Medow Ln.','99207','5095551212' )\n" }, { "answer_id": 74467828, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 1, "selected": false, "text": "create table DogLicense \n ( License int IDENTITY(1,1) PRIMARY KEY\n , Expires date NOT NULL CHECK(Expires > '1990-01-01') \n , Sex char(2) NOT NULL CONSTRAINT check_Sex_M_F_NM_SF CHECK (Sex IN ('M','F','NM','SF'))\n , PetName char(50) NOT NULL \n , Breed char(50) \n , OwnerLastName char(50) NOT NULL \n , OwnerFirstName char(50) NOT NULL \n , Address char(50) \n , Zip Char(5) NOT NULL CHECK(Zip >= 99201 and zip <= 99212)\n , Phone char(10) )\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20524254/" ]
74,467,699
<p>I installed Laravel UI using this tutorial <a href="https://www.itsolutionstuff.com/post/laravel-9-authentication-using-breeze-tutorialexample.html" rel="nofollow noreferrer">https://www.itsolutionstuff.com/post/laravel-9-authentication-using-breeze-tutorialexample.html</a></p> <p>The login and register forms are there <a href="http://localhost:8000/login" rel="nofollow noreferrer">http://localhost:8000/login</a> but after login if I go to my route (<a href="http://localhost:8000/api/categories" rel="nofollow noreferrer">http://localhost:8000/api/categories</a>) inside the middleware I am redirected to the home page. If I have the route outside the middleware it works but without requiring a login.</p> <p>** Works ** (at least the 'Category' view shows)</p> <pre><code> Route::controller(App\Http\Controllers\API\CategoryController::class)-&gt;group(function(){ Route::get('categories', 'index')-&gt;name('categories.index') }); </code></pre> <p>** Does Not work ** (redirects to home view)</p> <pre><code>Route::group(['middleware' =&gt; 'auth:api'], function(){ Route::controller(App\Http\Controllers\API\CategoryController::class)-&gt;group(function(){ Route::get('categories', 'index')-&gt;name('categories.index') }); }); </code></pre> <p>** CategoryController**</p> <pre><code>&lt;?php namespace App\Http\Controllers\API; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Models\Category; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Log; class CategoryController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $cat = $this-&gt;getCategories(); return response()-&gt;json($cat); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $cat = $this-&gt;getCategories(); return view('create-category',compact('cat')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { return Auth::user(); $category = Category::firstOrCreate( ['name' =&gt; $role_name], ['guard_name' =&gt; 'api'] ); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $cat = $this-&gt;getCategories($id); // $cat = Category::where('id', $id)-&gt;get()-&gt;keyBy('id'); return response()-&gt;json($cat); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } public function getParentCategory($id) { $cat = Category::where('id', $id)-&gt;get()-&gt;keyBy('id'); return $cat; } public function getChildCategory($id, $keyBy = null) { // return $keyBy; $cat = Category::where('parent_id', $id)-&gt;get()-&gt;keyBy('id'); return $cat; } private function setKeyBy($collection, $name) { $collection = $collection-&gt;keyBy($name); return $collection; } public function getCategories($category_id = null) { $cat = Category::where('id', '&gt;', 0); if(!is_null($category_id)) { $cat = $cat-&gt;where('id', $category_id)-&gt;get()-&gt;keyBy('id'); } else { $cat = $cat-&gt;whereNull('parent_id')-&gt;get()-&gt;keyBy('id'); foreach($cat as $catID=&gt;$catArray) { $subCat = $this-&gt;getChildCategory($catID, 'id'); // $subCat = $subCat-&gt;keyBy('id'); if ($subCat-&gt;first()) { $cat[$catID]['subcat'] = $subCat; } } } return $cat; } public function createCategoryForm() { $cat = $this-&gt;getCategories(); return view('create-category',compact('cat')); } public function categoryDropown($child_id = null) { $cat = $this-&gt;getCategories(); } public function categoryChildDropown($child_id) { $cat = Category::where('parent_id', $child_id)-&gt;get(); return $cat; } } </code></pre> <p>I have used Laravel for a while now but this is the first time creating an app from scratch with Auth. I do not know what I am missing. TIA</p>
[ { "answer_id": 74467813, "author": "DanielT", "author_id": 20400287, "author_profile": "https://Stackoverflow.com/users/20400287", "pm_score": 0, "selected": false, "text": "insert into DogLicense values ('2023-06-21','NM', 'Rosco', 'St. Bernard','Freeman','Mark', '123 Medow Ln.','99207','5095551212' )\n" }, { "answer_id": 74467828, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 1, "selected": false, "text": "create table DogLicense \n ( License int IDENTITY(1,1) PRIMARY KEY\n , Expires date NOT NULL CHECK(Expires > '1990-01-01') \n , Sex char(2) NOT NULL CONSTRAINT check_Sex_M_F_NM_SF CHECK (Sex IN ('M','F','NM','SF'))\n , PetName char(50) NOT NULL \n , Breed char(50) \n , OwnerLastName char(50) NOT NULL \n , OwnerFirstName char(50) NOT NULL \n , Address char(50) \n , Zip Char(5) NOT NULL CHECK(Zip >= 99201 and zip <= 99212)\n , Phone char(10) )\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1198563/" ]
74,467,704
<p>I want to use the project name from the path as an input to main.tf. For example I have the file path as follows</p> <pre><code>/env/nonprod/overlay/prj-npe-02/main.tf </code></pre> <p>and in my main.tf can the input var.project_name be taken from the file path which is &quot;../prj-npe-02/..&quot;</p> <pre><code>main.tf data &quot;google_project&quot; &quot;project&quot; { project_id = var.project_name } </code></pre>
[ { "answer_id": 74467813, "author": "DanielT", "author_id": 20400287, "author_profile": "https://Stackoverflow.com/users/20400287", "pm_score": 0, "selected": false, "text": "insert into DogLicense values ('2023-06-21','NM', 'Rosco', 'St. Bernard','Freeman','Mark', '123 Medow Ln.','99207','5095551212' )\n" }, { "answer_id": 74467828, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 1, "selected": false, "text": "create table DogLicense \n ( License int IDENTITY(1,1) PRIMARY KEY\n , Expires date NOT NULL CHECK(Expires > '1990-01-01') \n , Sex char(2) NOT NULL CONSTRAINT check_Sex_M_F_NM_SF CHECK (Sex IN ('M','F','NM','SF'))\n , PetName char(50) NOT NULL \n , Breed char(50) \n , OwnerLastName char(50) NOT NULL \n , OwnerFirstName char(50) NOT NULL \n , Address char(50) \n , Zip Char(5) NOT NULL CHECK(Zip >= 99201 and zip <= 99212)\n , Phone char(10) )\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19840332/" ]
74,467,723
<p>New to react so any help would be appreciated! I have a table of users that I've mapped out from an API call. I also needed an Edit button so I could edit a user in a separate form. But when I pass the object into my handleEditShow function on the onclick function of that edit button, I get an error: &quot;Too many re-renders. React limits the number of renders to prevent an infinite loop.&quot;</p> <pre><code> const [showEdit, setShowEdit] = useState(false); const handleEditShow = (user) =&gt; { console.log(user); setShowEdit(true); setEditUser({person: &quot;&quot; }) }; const handleEditClose = () =&gt; setShowEdit(false); const [editUser, setEditUser] = useState({userEdit:[]}); </code></pre> <p>My plan was to set the edited user into its own state and then pass that into a different component(form in a modal).</p> <pre><code>&lt;Table striped&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Login&lt;/th&gt; &lt;th&gt;Last Active&lt;/th&gt; &lt;th&gt;Email&lt;/th&gt; &lt;th&gt;Supervisor&lt;/th&gt; &lt;th&gt;Active&lt;/th&gt; &lt;th&gt;Language&lt;/th&gt; &lt;th&gt;Edit&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; { users.person &amp;&amp; users.person.map((item)=&gt;( &lt;tr key={item.id}&gt; &lt;td&gt;{item.name}&lt;/td&gt; &lt;td&gt;{item.login}&lt;/td&gt; &lt;td&gt;{item.lastActive}&lt;/td&gt; &lt;td&gt;{item.email}&lt;/td&gt; &lt;td&gt;{item.supervisor}&lt;/td&gt; &lt;td&gt;{item.active}&lt;/td&gt; &lt;td&gt;{item.language}&lt;/td&gt; &lt;td&gt;&lt;Button variant=&quot;secondary&quot; id={item.id} onClick={handleEditShow(item)}&gt; Edit &lt;/Button&gt; &lt;/td&gt; &lt;/tr&gt; )) } &lt;/tbody&gt; </code></pre> <p>I was thinking of passing the user that needs to be edited like this:</p> <pre><code>&lt;Modal show={showEdit} onHide={handleEditClose}&gt; &lt;Modal.Header closeButton&gt; &lt;Modal.Title&gt;User Editor&lt;/Modal.Title&gt; &lt;/Modal.Header&gt; &lt;Modal.Body&gt; &lt;EditForm user={editUser} /&gt; &lt;/Modal.Body&gt; &lt;Modal.Footer&gt; &lt;/Modal.Footer&gt; &lt;/Modal&gt; </code></pre>
[ { "answer_id": 74467813, "author": "DanielT", "author_id": 20400287, "author_profile": "https://Stackoverflow.com/users/20400287", "pm_score": 0, "selected": false, "text": "insert into DogLicense values ('2023-06-21','NM', 'Rosco', 'St. Bernard','Freeman','Mark', '123 Medow Ln.','99207','5095551212' )\n" }, { "answer_id": 74467828, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 1, "selected": false, "text": "create table DogLicense \n ( License int IDENTITY(1,1) PRIMARY KEY\n , Expires date NOT NULL CHECK(Expires > '1990-01-01') \n , Sex char(2) NOT NULL CONSTRAINT check_Sex_M_F_NM_SF CHECK (Sex IN ('M','F','NM','SF'))\n , PetName char(50) NOT NULL \n , Breed char(50) \n , OwnerLastName char(50) NOT NULL \n , OwnerFirstName char(50) NOT NULL \n , Address char(50) \n , Zip Char(5) NOT NULL CHECK(Zip >= 99201 and zip <= 99212)\n , Phone char(10) )\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16557274/" ]
74,467,727
<p>I have a polydata structure and its extracted edges but computed with <code>extract_feature_edges</code> function as unconnected cells (separated lines).</p> <p>Is it possible to connect those cells (lines) from their common points and then get the different features (lands, islands such as what you can see in the image - Antartica, Australia, ... - BTW they are paleo continents)?</p> <p>In resume, I would like to extract from my grid and its edges the different land parts as separate polydata. I have tried with the python module shapely and the polygonize function, it works but not with 3D coordinates (<a href="https://shapely.readthedocs.io/en/latest/reference/shapely.polygonize.html" rel="nofollow noreferrer">https://shapely.readthedocs.io/en/latest/reference/shapely.polygonize.html</a>).</p> <pre><code>import pyvista as pv ! wget -q -nc https://thredds-su.ipsl.fr/thredds/fileServer/ipsl_thredds/brocksce/pyvista/mesh.vtk mesh = pv.PolyData('mesh.vtk') edges = mesh.extract_feature_edges(boundary_edges=True) pl = pv.Plotter() pl.add_mesh(pv.Sphere(radius=0.999, theta_resolution=360, phi_resolution=180)) pl.add_mesh(mesh, show_edges=True, edge_color=&quot;gray&quot;) pl.add_mesh(edges, color=&quot;red&quot;, line_width=2) viewer = pl.show(jupyter_backend='pythreejs', return_viewer=True) display(viewer) </code></pre> <p><a href="https://i.stack.imgur.com/OmT1i.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OmT1i.png" alt="enter image description here" /></a></p> <p>Any idea?</p>
[ { "answer_id": 74467813, "author": "DanielT", "author_id": 20400287, "author_profile": "https://Stackoverflow.com/users/20400287", "pm_score": 0, "selected": false, "text": "insert into DogLicense values ('2023-06-21','NM', 'Rosco', 'St. Bernard','Freeman','Mark', '123 Medow Ln.','99207','5095551212' )\n" }, { "answer_id": 74467828, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 1, "selected": false, "text": "create table DogLicense \n ( License int IDENTITY(1,1) PRIMARY KEY\n , Expires date NOT NULL CHECK(Expires > '1990-01-01') \n , Sex char(2) NOT NULL CONSTRAINT check_Sex_M_F_NM_SF CHECK (Sex IN ('M','F','NM','SF'))\n , PetName char(50) NOT NULL \n , Breed char(50) \n , OwnerLastName char(50) NOT NULL \n , OwnerFirstName char(50) NOT NULL \n , Address char(50) \n , Zip Char(5) NOT NULL CHECK(Zip >= 99201 and zip <= 99212)\n , Phone char(10) )\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2772805/" ]
74,467,742
<p>I have a moderate amount of experience in python and a little experience in C++ and c#.</p> <p>I am currently doing an optimization challenge where I am gated by efficiency, and am hoping to use a C library in python to increase efficiency. I have no experience using C in python, but I won't need to marshall many variables. I will need to call a function in python, then from there it can be entirely C.</p> <p>An example of what I am hoping the code would look like is:</p> <p>import cLibrary as C</p> <p>#start python code</p> <p>def runFunction(string):</p> <p>#start C</p> <p>run function in C, have to marshall string</p> <p>#end C</p> <p>runFunction(string)</p> <p>#end python</p> <p>I am confident with the C/C++ code itself, primary issue is what library/module to use, how to call that library, and how to convert the string from python to C.</p>
[ { "answer_id": 74467813, "author": "DanielT", "author_id": 20400287, "author_profile": "https://Stackoverflow.com/users/20400287", "pm_score": 0, "selected": false, "text": "insert into DogLicense values ('2023-06-21','NM', 'Rosco', 'St. Bernard','Freeman','Mark', '123 Medow Ln.','99207','5095551212' )\n" }, { "answer_id": 74467828, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 1, "selected": false, "text": "create table DogLicense \n ( License int IDENTITY(1,1) PRIMARY KEY\n , Expires date NOT NULL CHECK(Expires > '1990-01-01') \n , Sex char(2) NOT NULL CONSTRAINT check_Sex_M_F_NM_SF CHECK (Sex IN ('M','F','NM','SF'))\n , PetName char(50) NOT NULL \n , Breed char(50) \n , OwnerLastName char(50) NOT NULL \n , OwnerFirstName char(50) NOT NULL \n , Address char(50) \n , Zip Char(5) NOT NULL CHECK(Zip >= 99201 and zip <= 99212)\n , Phone char(10) )\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20454104/" ]
74,467,744
<p>What I have is the following input data for a function in a piece of scala code I'm writing:</p> <pre class="lang-scala prettyprint-override"><code>List( (1,SubScriptionState(CNN,ONLINE,Seq(12))), (1,SubScriptionState(SKY,ONLINE,Seq(12))), (1,SubScriptionState(FOX,ONLINE,Seq(12))), (2,SubScriptionState(CNN,ONLINE,Seq(12))), (2,SubScriptionState(SKY,ONLINE,Seq(12))), (2,SubScriptionState(FOX,ONLINE,Seq(12))), (2,SubScriptionState(CNN,OFFLINE,Seq(13))), (2,SubScriptionState(SKY,ONLINE,Seq(13))), (2,SubScriptionState(FOX,ONLINE,Seq(13))), (3,SubScriptionState(CNN,OFFLINE,Seq(13))), (3,SubScriptionState(SKY,ONLINE,Seq(13))), (3,SubScriptionState(FOX,ONLINE,Seq(13))) ) </code></pre> <p><code>SubscriptionState</code> is just a case class here:</p> <pre class="lang-scala prettyprint-override"><code>case class SubscriptionState(channel: Channel, state: ChannelState, subIds: Seq[Long]) </code></pre> <p>I want to transform it into this:</p> <pre class="lang-scala prettyprint-override"><code> Map( 1 -&gt; Map( SubScriptionState(SKY,ONLINE,Seq(12)) -&gt; 1, SubScriptionState(CNN,ONLINE,Seq(12)) -&gt; 1, SubScriptionState(FOX,ONLINE,Seq(12)) -&gt; 1), 2 -&gt; Map( SubScriptionState(SKY,ONLINE,Seq(12,13)) -&gt; 2, SubScriptionState(CNN,ONLINE,Seq(12)) -&gt; 1, SubScriptionState(FOX,ONLINE,Seq(12,13)) -&gt; 2, SubScriptionState(CNN,OFFLINE,Seq(13)) -&gt; 1), 3 -&gt; Map( SubScriptionState(SKY,ONLINE,Seq(13)) -&gt; 1, SubScriptionState(FOX,ONLINE,Seq(13)) -&gt; 1, SubScriptionState(CNN,OFFLINE,Seq(13)) -&gt; 1) ) </code></pre> <p>How would I go about doing this in scala?</p>
[ { "answer_id": 74468442, "author": "ofnero", "author_id": 10568780, "author_profile": "https://Stackoverflow.com/users/10568780", "pm_score": 3, "selected": true, "text": " val result: Map[Int, Map[SubscriptionState, Int]] = list\n .groupBy(_._1)\n .view\n .mapValues { statesById =>\n statesById\n .groupBy { case (_, subscriptionState) => (subscriptionState.channel, subscriptionState.state) }\n .map { case (_, groupedStatesById) =>\n val subscriptionState = groupedStatesById.head._2 // groupedStatesById should contain at least one element\n val allSubIds = groupedStatesById.flatMap(_._2.subIds)\n val updatedSubscriptionState = subscriptionState.copy(subIds = allSubIds)\n updatedSubscriptionState -> allSubIds.size\n }\n }.toMap\n" }, { "answer_id": 74472316, "author": "Tim", "author_id": 7662670, "author_profile": "https://Stackoverflow.com/users/7662670", "pm_score": 2, "selected": false, "text": "groupMap" }, { "answer_id": 74475661, "author": "Johny T Koshy", "author_id": 757071, "author_profile": "https://Stackoverflow.com/users/757071", "pm_score": 1, "selected": false, "text": "foldLeft" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443960/" ]
74,467,777
<p>I need to dynamically access the values of different entry fields that are built using a collection view in Maui.</p> <p>I know using the OnEntryCompleted function you are able to get the text from an entry field but I am not sure the best way to store it if you have text from multiple entry fields coming from a collection view. I was thinking of using a dictionary or array to store the values but wasnt sure if there was a better way to do it.</p>
[ { "answer_id": 74468714, "author": "ToolmakerSteve", "author_id": 199364, "author_profile": "https://Stackoverflow.com/users/199364", "pm_score": 0, "selected": false, "text": "CollectionView.ItemsSource" }, { "answer_id": 74469230, "author": "Liqun Shen-MSFT", "author_id": 20118901, "author_profile": "https://Stackoverflow.com/users/20118901", "pm_score": 0, "selected": false, "text": "<CollectionView x:Name=\"collcn\"\n ItemsSource=\"{Binding ItemCollection}\"\n ...>\n \n <CollectionView.ItemTemplate>\n <DataTemplate >\n <StackLayout>\n <Entry Text=\"{Binding Text}\" BackgroundColor=\"Yellow\" TextColor=\"Black\"/>\n </StackLayout> \n </DataTemplate>\n </CollectionView.ItemTemplate>\n</CollectionView>\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20461779/" ]
74,467,808
<p>I am getting a nested JSON off of an API. When I try to convert the JSON into CSV, I get attribute errors for keys. How do I only write the records from the sample data to csv?</p> <pre><code> {&quot;result&quot;:{&quot;total_records&quot;:3471,&quot;offset&quot;:0.0,&quot;size&quot;:100.0,&quot;records&quot;:[{&quot;hr_case_number&quot;:&quot;HRC0177303&quot;,&quot;requested_by&quot;:&quot;Test Emp 1&quot;,&quot;employee_name&quot;:&quot;Test Emp2&quot;,&quot;employee_id&quot;:&quot;99991&quot;,&quot;artifact_type&quot;:&quot;Competency Assessment&quot;,&quot;artifact_subtype&quot;:&quot;Transfer Competency Assessment&quot;,&quot;artifact_date&quot;:&quot;2022-10-30&quot;,&quot;status&quot;:&quot;uploaded&quot;},{&quot;hr_case_number&quot;:&quot;HRC0177302&quot;,&quot;requested_by&quot;:&quot;test emp 3&quot;,&quot;employee_name&quot;:&quot;Test Emp 4&quot;,&quot;employee_id&quot;:&quot;192499&quot;,&quot;artifact_type&quot;:&quot;Orientation&quot;,&quot;artifact_subtype&quot;:&quot;Acknowledgement of Mandated Reporter Status&quot;,&quot;artifact_date&quot;:&quot;2022-10-28&quot;,&quot;status&quot;:&quot;uploaded&quot;}]}} </code></pre> <p>This is what I have so far:</p> <pre><code>import requests, json import csv url = &quot;https://some.com/api?offset=0&amp;size=10000&quot; headers = { 'Authorization': 'Basic c3ZjX2RhdGF', 'Cookie': 'BIGipServerpool_sometest=a728; JSESSIONID=26D6FA5703B691409AA3E44E6825C816; glide_user_route=glide.a50e06d87c4640335db5b2b40400f955; glide_session_store=D9F021AC1BE6D1103FB41F87B04BCB49', 'Content-Type':'application/json','Accept':'application/json' } payload={} response = requests.request(&quot;GET&quot;, url, headers=headers, data=payload) with open('outputfile.json', 'wb') as outf: outf.write(response.content) outf.close() #Open JSON load the data into the variable data with open('C:\Python\outputfile.json', 'r') as json_file: data = json.load(json_file) result = data['result'] # open a file for writing data_file = open('C:\Python\outputfile.csv', 'w', newline='') # create the csv writer csv_writer = csv.writer(data_file) # header count = 0 for records in result: if count == 0: # Writing headers of CSV file header = records.keys() csv_writer.writerow(header) count += 1 # Writing data of CSV file csv_writer.writerow(records.values()) data_file.close() </code></pre>
[ { "answer_id": 74468714, "author": "ToolmakerSteve", "author_id": 199364, "author_profile": "https://Stackoverflow.com/users/199364", "pm_score": 0, "selected": false, "text": "CollectionView.ItemsSource" }, { "answer_id": 74469230, "author": "Liqun Shen-MSFT", "author_id": 20118901, "author_profile": "https://Stackoverflow.com/users/20118901", "pm_score": 0, "selected": false, "text": "<CollectionView x:Name=\"collcn\"\n ItemsSource=\"{Binding ItemCollection}\"\n ...>\n \n <CollectionView.ItemTemplate>\n <DataTemplate >\n <StackLayout>\n <Entry Text=\"{Binding Text}\" BackgroundColor=\"Yellow\" TextColor=\"Black\"/>\n </StackLayout> \n </DataTemplate>\n </CollectionView.ItemTemplate>\n</CollectionView>\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/684899/" ]
74,467,811
<p>I need to show/hide two floating buttons on page scrolling for <strong>back to top</strong> and <strong>back to bottom</strong>. Here is my code.</p> <p>It should shows, back to top button while scrolling page to bottom (it works) and shows back to bottom button while scrolling page to top.(not working properly)</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>// When the user scrolls down 20px from the top of the document, show the button window.onscroll = function() { scrollFunction() }; function scrollFunction() { if (document.body.scrollTop &gt; 300 || document.documentElement.scrollTop &gt; 300) { document.getElementById("toTop").style.display = "inline"; document.getElementById("toBottom").style.display = "none"; } else { document.getElementById("toTop").style.display = "none"; document.getElementById("toBottom").style.display = "inline"; } } // When the user clicks on the button, scroll to the top of the document function topFunction() { document.body.scrollTop = 0; document.documentElement.scrollTop = 0; } // When the user clicks on the button, scroll to the bottom of the document function botFunction() { let height = document.body.clientHeight; document.body.scrollTop = height; document.documentElement.scrollTop = height; }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { font-family : Arial, Helvetica, sans-serif; font-size : 20px; } #toTop { display : none; position : fixed; bottom : 20px; right : 30px; z-index : 99; font-size : 18px; border : none; outline : none; background-color : red; color : white; cursor : pointer; padding : 15px; border-radius : 4px; } #toTop:hover { background-color : #555; } #toBottom { display : none; position : fixed; top : 20px; right : 30px; z-index : 99; font-size : 18px; border : none; outline : none; background-color : red; color : white; cursor : pointer; padding : 15px; border-radius : 4px; } #toBottom:hover { background-color : #555; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>0&lt;br&gt;&lt;br&gt; 1&lt;br&gt;&lt;br&gt; 2&lt;br&gt;&lt;br&gt; 3&lt;br&gt;&lt;br&gt; 4&lt;br&gt;&lt;br&gt; 5&lt;br&gt;&lt;br&gt; 6&lt;br&gt;&lt;br&gt; 7&lt;br&gt;&lt;br&gt; 8&lt;br&gt;&lt;br&gt; 9&lt;br&gt;&lt;br&gt; 0&lt;br&gt;&lt;br&gt; 1&lt;br&gt;&lt;br&gt; 2&lt;br&gt;&lt;br&gt; 3&lt;br&gt;&lt;br&gt; 4&lt;br&gt;&lt;br&gt; 5&lt;br&gt;&lt;br&gt; 6&lt;br&gt;&lt;br&gt; 7&lt;br&gt;&lt;br&gt; 8&lt;br&gt;&lt;br&gt; 9&lt;br&gt;&lt;br&gt; 0&lt;br&gt;&lt;br&gt; 1&lt;br&gt;&lt;br&gt; 2&lt;br&gt;&lt;br&gt; 3&lt;br&gt;&lt;br&gt; 4&lt;br&gt;&lt;br&gt; 5&lt;br&gt;&lt;br&gt; 6&lt;br&gt;&lt;br&gt; 7&lt;br&gt;&lt;br&gt; 8&lt;br&gt;&lt;br&gt; 9&lt;br&gt;&lt;br&gt; 0&lt;br&gt;&lt;br&gt; 1&lt;br&gt;&lt;br&gt; 2&lt;br&gt;&lt;br&gt; 3&lt;br&gt;&lt;br&gt; 4&lt;br&gt;&lt;br&gt; 5&lt;br&gt;&lt;br&gt; 6&lt;br&gt;&lt;br&gt; 7&lt;br&gt;&lt;br&gt; 8&lt;br&gt;&lt;br&gt; 9&lt;br&gt;&lt;br&gt; 0&lt;br&gt;&lt;br&gt; 1&lt;br&gt;&lt;br&gt; 2&lt;br&gt;&lt;br&gt; 3&lt;br&gt;&lt;br&gt; 4&lt;br&gt;&lt;br&gt; 5&lt;br&gt;&lt;br&gt; 6&lt;br&gt;&lt;br&gt; 7&lt;br&gt;&lt;br&gt; 8&lt;br&gt;&lt;br&gt; 9&lt;br&gt;&lt;br&gt; 0&lt;br&gt;&lt;br&gt; 1&lt;br&gt;&lt;br&gt; 2&lt;br&gt;&lt;br&gt; 3&lt;br&gt;&lt;br&gt; 4&lt;br&gt;&lt;br&gt; 5&lt;br&gt;&lt;br&gt; 6&lt;br&gt;&lt;br&gt; 7&lt;br&gt;&lt;br&gt; 8&lt;br&gt;&lt;br&gt; 9&lt;br&gt;&lt;br&gt; 0&lt;br&gt;&lt;br&gt; 1&lt;br&gt;&lt;br&gt; 2&lt;br&gt;&lt;br&gt; 3&lt;br&gt;&lt;br&gt; 4&lt;br&gt;&lt;br&gt; 5&lt;br&gt;&lt;br&gt; 6&lt;br&gt;&lt;br&gt; 7&lt;br&gt;&lt;br&gt; 8&lt;br&gt;&lt;br&gt; 9&lt;br&gt;&lt;br&gt; 0&lt;br&gt;&lt;br&gt; 1&lt;br&gt;&lt;br&gt; 2&lt;br&gt;&lt;br&gt; 3&lt;br&gt;&lt;br&gt; 4&lt;br&gt;&lt;br&gt; 5&lt;br&gt;&lt;br&gt; 6&lt;br&gt;&lt;br&gt; 7&lt;br&gt;&lt;br&gt; 8&lt;br&gt;&lt;br&gt; 9&lt;br&gt;&lt;br&gt; &lt;button onclick="topFunction()" id="toTop" title="Go to top"&gt;↑&lt;/button&gt; &lt;button onclick="botFunction()" id="toBottom" title="Go to top"&gt;↓&lt;/button&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74468157, "author": "Alvin", "author_id": 9239975, "author_profile": "https://Stackoverflow.com/users/9239975", "pm_score": 1, "selected": false, "text": "let previousScrollY = 0; //Store previous scroll to detect if the next one is going up or down\n\n// When the user scrolls down 20px from the top of the document, show the button\nwindow.onscroll = function() {\n if (previousScrollY > this.scrollY) {\n return scrollFunction('up'); // Or just scrollFunction() as we are not using \"up\"\n }\n previousScrollY = this.scrollY\n return scrollFunction('down');\n};\n\nfunction scrollFunction(direction) {\n if ( \n (document.body.scrollTop > 300 || document.documentElement.scrollTop > 300) &&\n direction === 'down' \n ) {\n document.getElementById(\"toTop\").style.display = \"inline\";\n document.getElementById(\"toBottom\").style.display = \"none\";\n } else {\n document.getElementById(\"toTop\").style.display = \"none\";\n document.getElementById(\"toBottom\").style.display = \"inline\";\n }\n}\n\n// When the user clicks on the button, scroll to the top of the document\nfunction topFunction() {\n document.body.scrollTop = 0;\n document.documentElement.scrollTop = 0;\n}\n\n// When the user clicks on the button, scroll to the bottom of the document \nfunction botFunction() {\n let height = document.body.clientHeight;\n document.body.scrollTop = height;\n document.documentElement.scrollTop = height;\n\n}" }, { "answer_id": 74468672, "author": "Mister Jojo", "author_id": 10669010, "author_profile": "https://Stackoverflow.com/users/10669010", "pm_score": 0, "selected": false, "text": "const\n scope = document.documentElement\n, btGoBot = document.querySelector('#toBottom')\n, btGoTop = document.querySelector('#toTop')\n, borderDelta = 300\n ;\nwindow.onscroll = btTopBotShow;\nwindow.onresize = btTopBotShow;\n\nbtTopBotShow(); // on page load...\n\nbtGoBot.onclick = () =>\n {\n scope.scrollTop = scope.scrollHeight - window.innerHeight;\n }\nbtGoTop.onclick = () =>\n {\n scope.scrollTop = 0;\n }\n\nfunction btTopBotShow()\n {\n let bottomDelta = scope.scrollHeight - window.innerHeight - scope.scrollTop;\n\n btGoBot.classList.toggle('noDisplay', bottomDelta < borderDelta )\n btGoTop.classList.toggle('noDisplay', scope.scrollTop < borderDelta )\n }" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1906322/" ]
74,467,816
<p>My metal default library does not contain the vertex and shader functions from the .metal file of the same directory.</p> <p>Then the library.makeFunction(name: ..) returns nil for both the vertex and shader functions that should be assigned to pipelineDescriptor vars.</p> <p>The metal file &amp; headers are copied from the Apple Sample App &quot;BasicTexturing&quot; (<a href="https://developer.apple.com/documentation/metal/textures/creating_and_sampling_textures" rel="nofollow noreferrer">Creating and Sampling Textures</a>).</p> <p>The file APPLShaders.metal and APPLShaderTypes.h contain a vertexShader and samplingShader functions that are loaded by an AAPLRenderer.m</p> <p>In the sample it's really straightforward</p> <pre><code> id&lt;MTLLibrary&gt; defaultLibrary = [_device newDefaultLibrary]; id&lt;MTLFunction&gt; vertexFunction = [defaultLibrary newFunctionWithName:@&quot;vertexShader&quot;]; id&lt;MTLFunction&gt; fragmentFunction = [defaultLibrary newFunctionWithName:@&quot;samplingShader&quot;]; </code></pre> <p>I have copied these files to a RayWenderlich Swift tutorial and used the swift version There is an init to set the library</p> <pre><code>Renderer.library = device.makeDefaultLibrary() </code></pre> <p>then</p> <pre><code> let library = Renderer.library let importVertexFunction = library?.makeFunction(name: &quot;vertexShader&quot;) let importShaderFunction = library?.makeFunction(name: &quot;samplingShader&quot;) </code></pre> <p>This works just fine!</p> <p>Same thing in my app with the same files copied over and it does not load the functions.</p> <p>I have checked compileSources in build settings - it lists the metal file. Comparing everything in settings and don't see a difference between the working apps and my app.</p> <p>I don't see any error messages or log messages to indicate a syntax or path problem.</p> <p>Any ideas?</p> <p>The Apple sample code AAPLShaders.metal</p> <pre><code>/* See LICENSE folder for this sample’s licensing information. Abstract: Metal shaders used for this sample */ #include &lt;metal_stdlib&gt; #include &lt;simd/simd.h&gt; using namespace metal; // Include header shared between this Metal shader code and C code executing Metal API commands #import &quot;AAPLShaderTypes.h&quot; // Vertex shader outputs and per-fragment inputs. Includes clip-space position and vertex outputs // interpolated by rasterizer and fed to each fragment generated by clip-space primitives. typedef struct { // The [[position]] attribute qualifier of this member indicates this value is the clip space // position of the vertex wen this structure is returned from the vertex shader float4 clipSpacePosition [[position]]; // Since this member does not have a special attribute qualifier, the rasterizer will // interpolate its value with values of other vertices making up the triangle and // pass that interpolated value to the fragment shader for each fragment in that triangle; float2 textureCoordinate; } RasterizerData; // Vertex Function vertex RasterizerData vertexShader(uint vertexID [[ vertex_id ]], constant AAPLVertex *vertexArray [[ buffer(AAPLVertexInputIndexVertices) ]], constant vector_uint2 *viewportSizePointer [[ buffer(AAPLVertexInputIndexViewportSize) ]]) { RasterizerData out; // Index into our array of positions to get the current vertex // Our positions are specified in pixel dimensions (i.e. a value of 100 is 100 pixels from // the origin) float2 pixelSpacePosition = vertexArray[vertexID].position.xy; // Get the size of the drawable so that we can convert to normalized device coordinates, float2 viewportSize = float2(*viewportSizePointer); // The output position of every vertex shader is in clip space (also known as normalized device // coordinate space, or NDC). A value of (-1.0, -1.0) in clip-space represents the // lower-left corner of the viewport whereas (1.0, 1.0) represents the upper-right corner of // the viewport. // In order to convert from positions in pixel space to positions in clip space we divide the // pixel coordinates by half the size of the viewport. out.clipSpacePosition.xy = pixelSpacePosition / (viewportSize / 2.0); // Set the z component of our clip space position 0 (since we're only rendering in // 2-Dimensions for this sample) out.clipSpacePosition.z = 0.0; // Set the w component to 1.0 since we don't need a perspective divide, which is also not // necessary when rendering in 2-Dimensions out.clipSpacePosition.w = 1.0; // Pass our input textureCoordinate straight to our output RasterizerData. This value will be // interpolated with the other textureCoordinate values in the vertices that make up the // triangle. out.textureCoordinate = vertexArray[vertexID].textureCoordinate; return out; } // Fragment function fragment float4 samplingShader(RasterizerData in [[stage_in]], texture2d&lt;half&gt; colorTexture [[ texture(AAPLTextureIndexBaseColor) ]]) { constexpr sampler textureSampler (mag_filter::linear, min_filter::linear); // Sample the texture to obtain a color const half4 colorSample = colorTexture.sample(textureSampler, in.textureCoordinate); // We return the color of the texture return float4(colorSample); } </code></pre> <p>The Apple Sample code header AAPLShaderTypes.h</p> <pre><code>/* See LICENSE folder for this sample’s licensing information. Abstract: Header containing types and enum constants shared between Metal shaders and C/ObjC source */ #ifndef AAPLShaderTypes_h #define AAPLShaderTypes_h #include &lt;simd/simd.h&gt; // Buffer index values shared between shader and C code to ensure Metal shader buffer inputs match // Metal API buffer set calls typedef enum AAPLVertexInputIndex { AAPLVertexInputIndexVertices = 0, AAPLVertexInputIndexViewportSize = 1, } AAPLVertexInputIndex; // Texture index values shared between shader and C code to ensure Metal shader buffer inputs match // Metal API texture set calls typedef enum AAPLTextureIndex { AAPLTextureIndexBaseColor = 0, } AAPLTextureIndex; // This structure defines the layout of each vertex in the array of vertices set as an input to our // Metal vertex shader. Since this header is shared between our .metal shader and C code, // we can be sure that the layout of the vertex array in the code matches the layout that // our vertex shader expects typedef struct { // Positions in pixel space (i.e. a value of 100 indicates 100 pixels from the origin/center) vector_float2 position; // 2D texture coordinate vector_float2 textureCoordinate; } AAPLVertex; #endif /* AAPLShaderTypes_h */ </code></pre> <p>Debug print of my library</p> <pre><code>Printing description of self.library: (MTLLibrary?) library = (object = 0x00006000004af7b0) { object = 0x00006000004af7b0 { baseNSObject@0 = { isa = CaptureMTLLibrary } </code></pre> <p>Debug print of working library from RayWenderlich sample app The new added sampleShader and vertexShader are shown in the library along with the existing fragment and vertex functions.</p> <pre><code>▿ Optional&lt;MTLLibrary&gt; - some : &lt;CaptureMTLLibrary: 0x600000f54210&gt; -&gt; &lt;MTLDebugLibrary: 0x600002204050&gt; -&gt; &lt;_MTLLibrary: 0x600001460280&gt; label = &lt;none&gt; device = &lt;MTLSimDevice: 0x15a5069d0&gt; name = Apple iOS simulator GPU functionNames: fragment_main vertex_main samplingShader vertexShader </code></pre>
[ { "answer_id": 74468157, "author": "Alvin", "author_id": 9239975, "author_profile": "https://Stackoverflow.com/users/9239975", "pm_score": 1, "selected": false, "text": "let previousScrollY = 0; //Store previous scroll to detect if the next one is going up or down\n\n// When the user scrolls down 20px from the top of the document, show the button\nwindow.onscroll = function() {\n if (previousScrollY > this.scrollY) {\n return scrollFunction('up'); // Or just scrollFunction() as we are not using \"up\"\n }\n previousScrollY = this.scrollY\n return scrollFunction('down');\n};\n\nfunction scrollFunction(direction) {\n if ( \n (document.body.scrollTop > 300 || document.documentElement.scrollTop > 300) &&\n direction === 'down' \n ) {\n document.getElementById(\"toTop\").style.display = \"inline\";\n document.getElementById(\"toBottom\").style.display = \"none\";\n } else {\n document.getElementById(\"toTop\").style.display = \"none\";\n document.getElementById(\"toBottom\").style.display = \"inline\";\n }\n}\n\n// When the user clicks on the button, scroll to the top of the document\nfunction topFunction() {\n document.body.scrollTop = 0;\n document.documentElement.scrollTop = 0;\n}\n\n// When the user clicks on the button, scroll to the bottom of the document \nfunction botFunction() {\n let height = document.body.clientHeight;\n document.body.scrollTop = height;\n document.documentElement.scrollTop = height;\n\n}" }, { "answer_id": 74468672, "author": "Mister Jojo", "author_id": 10669010, "author_profile": "https://Stackoverflow.com/users/10669010", "pm_score": 0, "selected": false, "text": "const\n scope = document.documentElement\n, btGoBot = document.querySelector('#toBottom')\n, btGoTop = document.querySelector('#toTop')\n, borderDelta = 300\n ;\nwindow.onscroll = btTopBotShow;\nwindow.onresize = btTopBotShow;\n\nbtTopBotShow(); // on page load...\n\nbtGoBot.onclick = () =>\n {\n scope.scrollTop = scope.scrollHeight - window.innerHeight;\n }\nbtGoTop.onclick = () =>\n {\n scope.scrollTop = 0;\n }\n\nfunction btTopBotShow()\n {\n let bottomDelta = scope.scrollHeight - window.innerHeight - scope.scrollTop;\n\n btGoBot.classList.toggle('noDisplay', bottomDelta < borderDelta )\n btGoTop.classList.toggle('noDisplay', scope.scrollTop < borderDelta )\n }" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5596126/" ]
74,467,833
<p>I have an SQL query that creates an array with 9 entries, I want to create a table with Numpy and append data as rows</p> <p>The following code gives me an error</p> <p><code>ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 1 dimension(s)</code></p> <p>How can initialize the numpy array correctly, and append the array as a row to the table,</p> <pre class="lang-py prettyprint-override"><code>sql_query = &quot;select top 100 Passed, f.ID, Yld, Line, Location, Type, Name, ErrorID, Site from dw.table1 f join dw.table2 d on f.ID = d.ID where Type like '%test%'&quot; table_array = numpy.empty((0, 9)) cursor.execute(sql_query) row = cursor.fetchone() while row: table_array = numpy.append(table_array, row, axis=0) row = cursor.fetchone() </code></pre>
[ { "answer_id": 74468157, "author": "Alvin", "author_id": 9239975, "author_profile": "https://Stackoverflow.com/users/9239975", "pm_score": 1, "selected": false, "text": "let previousScrollY = 0; //Store previous scroll to detect if the next one is going up or down\n\n// When the user scrolls down 20px from the top of the document, show the button\nwindow.onscroll = function() {\n if (previousScrollY > this.scrollY) {\n return scrollFunction('up'); // Or just scrollFunction() as we are not using \"up\"\n }\n previousScrollY = this.scrollY\n return scrollFunction('down');\n};\n\nfunction scrollFunction(direction) {\n if ( \n (document.body.scrollTop > 300 || document.documentElement.scrollTop > 300) &&\n direction === 'down' \n ) {\n document.getElementById(\"toTop\").style.display = \"inline\";\n document.getElementById(\"toBottom\").style.display = \"none\";\n } else {\n document.getElementById(\"toTop\").style.display = \"none\";\n document.getElementById(\"toBottom\").style.display = \"inline\";\n }\n}\n\n// When the user clicks on the button, scroll to the top of the document\nfunction topFunction() {\n document.body.scrollTop = 0;\n document.documentElement.scrollTop = 0;\n}\n\n// When the user clicks on the button, scroll to the bottom of the document \nfunction botFunction() {\n let height = document.body.clientHeight;\n document.body.scrollTop = height;\n document.documentElement.scrollTop = height;\n\n}" }, { "answer_id": 74468672, "author": "Mister Jojo", "author_id": 10669010, "author_profile": "https://Stackoverflow.com/users/10669010", "pm_score": 0, "selected": false, "text": "const\n scope = document.documentElement\n, btGoBot = document.querySelector('#toBottom')\n, btGoTop = document.querySelector('#toTop')\n, borderDelta = 300\n ;\nwindow.onscroll = btTopBotShow;\nwindow.onresize = btTopBotShow;\n\nbtTopBotShow(); // on page load...\n\nbtGoBot.onclick = () =>\n {\n scope.scrollTop = scope.scrollHeight - window.innerHeight;\n }\nbtGoTop.onclick = () =>\n {\n scope.scrollTop = 0;\n }\n\nfunction btTopBotShow()\n {\n let bottomDelta = scope.scrollHeight - window.innerHeight - scope.scrollTop;\n\n btGoBot.classList.toggle('noDisplay', bottomDelta < borderDelta )\n btGoTop.classList.toggle('noDisplay', scope.scrollTop < borderDelta )\n }" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2056201/" ]
74,467,834
<p>I have no idea what would fix this.</p> <p><a href="https://jsfiddle.net/eL5gn73s/" rel="nofollow noreferrer">https://jsfiddle.net/eL5gn73s/</a></p> <p>That big one is a div, the small ones are the buttons that have shrunk.</p> <p>The button should be the same size as the div, not the other way around.</p> <p>After changing from a div to a button, the button shrunk smaller than the size of the div that was 47px.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.box { position: relative; background: red; width: 47px; height: 47px; border-radius: 4px; border-width: 4px; border-style: solid; border-top-color: rgba(255, 255, 255, 0.5); border-left-color: rgba(0, 0, 0, 0.3); border-right-color: rgba(0, 0, 0, 0.3); border-bottom-color: rgba(0, 0, 0, 0.8); } .box.box2 { background: red; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;button class="box box2" type="button"&gt;&lt;/button&gt; &lt;button class="box " type="button"&gt;&lt;/button&gt; &lt;div class="box"&gt;&lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74467928, "author": "schoolacountbygrayson", "author_id": 20523693, "author_profile": "https://Stackoverflow.com/users/20523693", "pm_score": -1, "selected": false, "text": ".exit.exitPage2 {\n background: red;\n width: 50px;\n height: 50px;\n}\n" }, { "answer_id": 74467931, "author": "Mark Schultheiss", "author_id": 125981, "author_profile": "https://Stackoverflow.com/users/125981", "pm_score": 3, "selected": true, "text": "display:block" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17631451/" ]
74,467,843
<p>I have a table that has following text in a column and I need to convert the texts into multiple columns.</p> <pre><code>create table Test ( resource_type varchar(300) ); insert into Test (resource_type) values ('Number of reservations: 1'), ('Number of reservations: 2  ¶ Perf ID: Event : 51680'), ('Number of reservations: 3  ¶ Perf ID: Event : 51683'); </code></pre> <p>and I have converted this into columns by doing</p> <pre><code>Select A.* ,Pos1 = xDim.value('/x[1]' ,'varchar(100)') ,Pos2 = xDim.value('/x[2]' ,'varchar(100)') From Test A Cross Apply ( values (convert(xml,'&lt;x&gt;' + replace(A.resource_type,'¶','&lt;/x&gt;&lt;x&gt;')+'&lt;/x&gt;')) )B(xDim) </code></pre> <p>Output of the code is</p> <p><a href="https://i.stack.imgur.com/9G1Hd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9G1Hd.png" alt="enter image description here" /></a></p> <p>Instead, I need Number of reservations and PerfID as columns and under the number of reservations values as 1, 2, and 3 and under perf id null, 51680, and 51683...</p> <p>Please help me how to proceed further!</p>
[ { "answer_id": 74468031, "author": "Yitzhak Khabinsky", "author_id": 1932311, "author_profile": "https://Stackoverflow.com/users/1932311", "pm_score": 1, "selected": false, "text": "DECLARE @tbl TABLE (resource_type VARCHAR(300));\nINSERT INTO @tbl (resource_type) VALUES\n('Number of reservations: 1'),\n('Number of reservations: 2 ¶ Perf ID: Event : 51680'),\n('Number of reservations: 3 ¶ Perf ID: Event : 51683');\n\nDECLARE @separator CHAR(1) = ':';\n\nSELECT t.* -- , c \n ,Pos1 = TRIM(c.value('(/root/r[2]/text())[1]' ,'varchar(100)'))\n ,Pos2 = TRIM(c.value('(/root/r[5]/text())[1]' ,'varchar(100)'))\nFROM @tbl AS t\nCROSS APPLY (SELECT TRY_CAST('<root><r><![CDATA[' + \n REPLACE(REPLACE(resource_type,'¶',@separator), @separator, ']]></r><r><![CDATA[') + \n ']]></r></root>' AS XML)) AS t1(c);\n" }, { "answer_id": 74468100, "author": "Stu", "author_id": 15332650, "author_profile": "https://Stackoverflow.com/users/15332650", "pm_score": 0, "selected": false, "text": "select resource_type, \n Substring(resource_type, p1.p, IsNull(NullIf(p2.p,0) - p1.p - 1, Len(resource_type))) Pos1,\n Substring(resource_type, p3.p, Len(resource_type)) Pos2\nfrom test\ncross apply(values(CharIndex(':', resource_type) + 2))p1(p)\ncross apply(values(CharIndex('¶', resource_type) ))p2(p)\ncross apply(values(NullIf(CharIndex('Event', resource_type, p1.p), 0) + 8))p3(p);\n" }, { "answer_id": 74468378, "author": "John Cappelletti", "author_id": 1570000, "author_profile": "https://Stackoverflow.com/users/1570000", "pm_score": 0, "selected": false, "text": "FAR MORE PERFORMANT" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2564812/" ]
74,467,867
<p>I've got a for loop which iterates through three elements in a list: [&quot;123&quot;, &quot;456&quot;, &quot;789&quot;]. So, with the first iteration, it will perform a calculation on each digit within the first element, then add the digits back up. This repeats for the other two elements. The outputs are then converted into strings and outputted.</p> <pre><code>for x in digits: if len(x) == 3: result1 = int(x[0]) * 8 ** (3 - 1) result2 = int(x[1]) * 8 ** (2 - 1) result3 = int(x[2]) * 8 ** (1 - 1) result = result1 + result2 + result decimal = [] decimal.append(result) string = &quot; &quot;.join(str(i) for i in decimal) return string </code></pre> <p>Problem is, when outputting the results of the calculations, it outputs them on separate lines, but I need them to be on the same line.</p> <p>For example:</p> <ul> <li>123</li> <li>456</li> <li>789</li> </ul> <p>I need them to be like this:</p> <ul> <li>123 456 789</li> </ul> <p>I've tried putting the results of the calculations into a list, which is then converted to a string and outputted, but no dice - it still returns the values on separate lines instead of one.</p> <p>EDIT:</p> <p>I know how to do this using the print function:</p> <pre><code>print(str(result), end=&quot; &quot;) </code></pre> <p>But need to use the return function. Is there any way to do this?</p>
[ { "answer_id": 74468031, "author": "Yitzhak Khabinsky", "author_id": 1932311, "author_profile": "https://Stackoverflow.com/users/1932311", "pm_score": 1, "selected": false, "text": "DECLARE @tbl TABLE (resource_type VARCHAR(300));\nINSERT INTO @tbl (resource_type) VALUES\n('Number of reservations: 1'),\n('Number of reservations: 2 ¶ Perf ID: Event : 51680'),\n('Number of reservations: 3 ¶ Perf ID: Event : 51683');\n\nDECLARE @separator CHAR(1) = ':';\n\nSELECT t.* -- , c \n ,Pos1 = TRIM(c.value('(/root/r[2]/text())[1]' ,'varchar(100)'))\n ,Pos2 = TRIM(c.value('(/root/r[5]/text())[1]' ,'varchar(100)'))\nFROM @tbl AS t\nCROSS APPLY (SELECT TRY_CAST('<root><r><![CDATA[' + \n REPLACE(REPLACE(resource_type,'¶',@separator), @separator, ']]></r><r><![CDATA[') + \n ']]></r></root>' AS XML)) AS t1(c);\n" }, { "answer_id": 74468100, "author": "Stu", "author_id": 15332650, "author_profile": "https://Stackoverflow.com/users/15332650", "pm_score": 0, "selected": false, "text": "select resource_type, \n Substring(resource_type, p1.p, IsNull(NullIf(p2.p,0) - p1.p - 1, Len(resource_type))) Pos1,\n Substring(resource_type, p3.p, Len(resource_type)) Pos2\nfrom test\ncross apply(values(CharIndex(':', resource_type) + 2))p1(p)\ncross apply(values(CharIndex('¶', resource_type) ))p2(p)\ncross apply(values(NullIf(CharIndex('Event', resource_type, p1.p), 0) + 8))p3(p);\n" }, { "answer_id": 74468378, "author": "John Cappelletti", "author_id": 1570000, "author_profile": "https://Stackoverflow.com/users/1570000", "pm_score": 0, "selected": false, "text": "FAR MORE PERFORMANT" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20523923/" ]
74,467,875
<p>I may have messed up some environmental path variables.</p> <p>I was tinkering around VS Code while learning about Django and virtual environments, and changing the directory path of my Python install. While figuring out how to point VS Code's default Python path, I deleted some User path variables.</p> <p>Then, isort began to refuse to run.</p> <p>I've tried uninstalling the extension(s), deleting the ms-python.'s, and uninstalling VS Code itself, clearing the Python Workspace Interpreter Settings, and restarting my computer.</p> <p>Even if it's not my path variables, anyone know the defaults that should be in the &quot;user&quot; paths variables?</p>
[ { "answer_id": 74469210, "author": "MingJie-MSFT", "author_id": 18359438, "author_profile": "https://Stackoverflow.com/users/18359438", "pm_score": 1, "selected": false, "text": "C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python310\\" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5203583/" ]
74,467,878
<p>Does anyone know if a function is supposed to end after it returns something? I have my recursion function written below, but whenever it reaches the else statement and after it returns a value (steps),</p> <p>it runs the &quot;if (new_number % 2 == 1)&quot; statement,</p> <p>which does not make sense since the function should end when it reaches the else statement and should not repeat.</p> <p>It works fine until it returns &quot;steps&quot; for the first time.</p> <p>This is what happens after the first return: It doesn't even fully run the &quot;if (new_number % 2 == 1)&quot; statement, it just jumps to that line and decreases the value of &quot;steps&quot; and &quot;input_steps&quot; by 1. &quot;new_number&quot; and &quot;number&quot; just get completely random values</p> <p>Then it returns &quot;steps&quot;, then it jumps to &quot;if (new_number % 2 == 1)&quot; statement and decreases the value of &quot;steps&quot; and &quot;input_steps&quot; by 1. &quot;new_number&quot; and &quot;number&quot; just get completely random values again.</p> <p>It repeats that cycle until &quot;new_steps&quot; and &quot;steps&quot; equal 0, then it returns 0 (because &quot;steps&quot; = 0) and ends the function.</p> <p>Does anyone know why it does this????</p> <p>Here is my code:</p> <pre><code>int step_recursion(int number, int input_steps) { int new_number = number; int steps = input_steps; if (new_number != 1) { if (new_number % 2 == 0) { if (new_number != 1) { step_recursion(new_number / 2, steps + 1); } } if ((new_number % 2) == 1) { if (new_number != 1) { step_recursion(new_number * 3 + 1, steps + 1); } } } return steps; } </code></pre> <p>I was expecting the function to end after returning &quot;steps,&quot; but for some reason it doesn't. I already described the problem fully so go read that.</p>
[ { "answer_id": 74468168, "author": "autistic", "author_id": 1989425, "author_profile": "https://Stackoverflow.com/users/1989425", "pm_score": 0, "selected": false, "text": "if (new_number % 2 == 0)\n{\n if (new_number != 1)\n {\n // if your intent is to control flow such that execution doesn't continue beyond here, you'd surely want a `return` statement here...\n /* return step_recursion(new_number / 2, steps + 1); */\n step_recursion(new_number / 2, steps + 1);\n }\n}\nif ((new_number % 2) == 1)\n{\n if (new_number != 1)\n {\n /* ditto here */\n step_recursion(new_number * 3 + 1, steps + 1);\n }\n}\n" }, { "answer_id": 74468182, "author": "Veselin Yotov", "author_id": 17191923, "author_profile": "https://Stackoverflow.com/users/17191923", "pm_score": 2, "selected": false, "text": "int step_recursion(int number, int steps) {\n if (number == 1) {\n return steps;\n }\n\n if (number % 2 == 0) {\n return step_recursion(number / 2, steps + 1);\n } else {\n return step_recursion(number * 3 + 1, steps + 1);\n }\n\n return steps;\n}\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20524344/" ]
74,467,888
<p>I'm trying to work with bit manipulation, and am struggling modifying the bits directly.</p> <p>I have something as follows:</p> <pre><code>unsigned char myBits = 128; // 10000000 in binary myBits = myBits &gt;&gt; 1; // Right shift, so we get 64, or 01000000 in binary </code></pre> <p>Now, how would I use bit manipulation to modify the first bit after the right shift (01000000) to a 1 (11000000)?</p>
[ { "answer_id": 74467927, "author": "dbush", "author_id": 1687119, "author_profile": "https://Stackoverflow.com/users/1687119", "pm_score": 1, "selected": false, "text": "signed char" }, { "answer_id": 74468005, "author": "0___________", "author_id": 6110094, "author_profile": "https://Stackoverflow.com/users/6110094", "pm_score": 0, "selected": false, "text": "myBits |= myBits >> 1;\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20044158/" ]
74,467,909
<p>I have the following expressions -</p> <pre><code>x &gt; 4.5 2x + y == 4.5 </code></pre> <p>I would like to get rid of the floating point numbers in the coefficients and convert them into integers. How can I do this using Sympy? (or any other python library for that matter). I have been racking my brains for hours now.</p> <p>BTW, the expected output should be -</p> <pre><code>2x &gt; 9 4x + 2y == 9 </code></pre> <p>Thanks in Advance!</p>
[ { "answer_id": 74467927, "author": "dbush", "author_id": 1687119, "author_profile": "https://Stackoverflow.com/users/1687119", "pm_score": 1, "selected": false, "text": "signed char" }, { "answer_id": 74468005, "author": "0___________", "author_id": 6110094, "author_profile": "https://Stackoverflow.com/users/6110094", "pm_score": 0, "selected": false, "text": "myBits |= myBits >> 1;\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6790591/" ]
74,467,918
<p>I have problem that I have been trying to find a solution for. You would think that it wouldn't be that hard to figure out.</p> <p>I have a pandas DataFrame with the below format:</p> <pre><code> Id Name Now Then There Sold Needed 0 1 Caden 8.1 3.40 3.95 NaN NaN 1 7 Bankist NaN 2.45 2.20 NaN NaN 2 1 Artistes 8.1 3.40 3.95 NaN NaN 0 1 NaN NaN NaN NaN 33.75 670,904 1 7 NaN NaN NaN NaN 33.75 670,904 </code></pre> <p>I would like to have the DataFrame merge its rows based on the 'Id' column so that it looks like this:</p> <pre><code> Id Name Now Then There Sold Needed 0 1 Caden 8.1 3.40 3.95 33.75 670,904 1 7 Bankist NaN 2.45 2.20 33.75 670,904 2 1 Artistes 8.1 3.40 3.95 33.75 670,904 </code></pre> <p>As you can see, the 'Id' column has two Id# 1 that each have a unique 'Name'. I have not been able to figure out how to ask the question that might provide some sample code. So far I have tried different methods, and have failed, including different combinations of merge, join, and concat. The best result has lead to the current DataFrame with NaN values.</p> <p>I am trying to accomplish having the 'Sold' and 'Needed' columns (which have only one value) aligned with the appropriate 'Id' row when there are repeating Ids.</p>
[ { "answer_id": 74467927, "author": "dbush", "author_id": 1687119, "author_profile": "https://Stackoverflow.com/users/1687119", "pm_score": 1, "selected": false, "text": "signed char" }, { "answer_id": 74468005, "author": "0___________", "author_id": 6110094, "author_profile": "https://Stackoverflow.com/users/6110094", "pm_score": 0, "selected": false, "text": "myBits |= myBits >> 1;\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4888870/" ]
74,467,965
<p>Consider the following data set that records the product sold, year, and revenue from that particular product in thousands of dollars. This data table (YEARLY_PRODUCT_REVENUE) is stored in SQL and has many more rows.</p> <pre><code>Year | Product | Revenue 2000 Table 100 2000 Chair 200 2000 Bed 150 2010 Table 120 2010 Chair 190 2010 Bed 390 </code></pre> <p>Using SQL, for every year I would like to find the product that has the maximum revenue. That is, I would like my output to be the following:</p> <pre><code>Year | Product | Revenue 2000 Chair 200 2010 Bed 390 </code></pre> <p>My attempt so far has been this:</p> <pre><code>SELECT year, product, MIN(revenue) FROM YEARLY_PRODUCT_REVENUE GROUP BY article, month; </code></pre> <p>But when I do this, I get multiple-year values for distinct products. For instance, I'm getting the output below which is an error. I'm not entirely sure what the error here is. Any help would be much appreciated!</p> <pre><code>Year | Product | Revenue 2000 Table 100 2000 Bed 150 2010 Table 120 2010 Chair 190 </code></pre>
[ { "answer_id": 74467927, "author": "dbush", "author_id": 1687119, "author_profile": "https://Stackoverflow.com/users/1687119", "pm_score": 1, "selected": false, "text": "signed char" }, { "answer_id": 74468005, "author": "0___________", "author_id": 6110094, "author_profile": "https://Stackoverflow.com/users/6110094", "pm_score": 0, "selected": false, "text": "myBits |= myBits >> 1;\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13630719/" ]
74,467,984
<p>In ASP.NET, what is the best way to display field/property names in form validation error messages in lower case?</p> <p>For example, if I have a <code>Price</code> property on a model, and <code>Price</code> is not nullable, and I leave the <code>Price</code> field blank when filling out a form for this model, then I will get this error message on the form:</p> <blockquote> <p>The Price field is required.</p> </blockquote> <p>&quot;Price&quot; is capitalised. Is there any easy way to make it lower case, like the following?</p> <blockquote> <p>The price field is required.</p> </blockquote> <p>There must be a way of making these property names show in lower case for every error message. Because yes, if I just wanted it for one property, then I could set a custom error message using the <code>Required</code> attribute:</p> <pre><code>[Required(ErrorMessage = &quot;The price field is required.&quot;)] public decimal Price { get; set; } </code></pre> <p>But I'm wondering if there is a way to make these property names show in lower case by default for every error message?</p> <p>I did find <a href="https://stackoverflow.com/questions/53855740/asp-net-mvc-validation-return-lowercase-property-name">this question with some answers</a>, but the solutions seem pretty complex, and also that person is talking about JSON serialisation, which is a bit different to my case.</p> <p>Thanks if anyone can share any info on this problem.</p>
[ { "answer_id": 74467927, "author": "dbush", "author_id": 1687119, "author_profile": "https://Stackoverflow.com/users/1687119", "pm_score": 1, "selected": false, "text": "signed char" }, { "answer_id": 74468005, "author": "0___________", "author_id": 6110094, "author_profile": "https://Stackoverflow.com/users/6110094", "pm_score": 0, "selected": false, "text": "myBits |= myBits >> 1;\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20524280/" ]
74,467,997
<p>Dataset contains &quot;two friends&quot; and coded &quot;interaction&quot; (all factors). I want to plot the frequency of type of interactions between two friends using a stacked bar. I tried the following code.</p> <pre><code>Friend1 &lt;- c(&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;) Friend2 &lt;- c(&quot;1&quot;,&quot;1&quot;,&quot;2&quot;,&quot;2&quot;,&quot;1&quot;,&quot;1&quot;,&quot;2&quot;,&quot;2&quot;,&quot;1&quot;,&quot;1&quot;,&quot;2&quot;,&quot;2&quot;,&quot;1&quot;,&quot;1&quot;,&quot;2&quot;,&quot;2&quot;) Interaction &lt;- c(&quot;O&quot;,&quot;X&quot;,&quot;D&quot;,&quot;D&quot;,&quot;D&quot;,&quot;X&quot;,&quot;X&quot;,&quot;D/R&quot;,&quot;O&quot;,&quot;X&quot;,&quot;D&quot;,&quot;D&quot;,&quot;D&quot;,&quot;X&quot;,&quot;X&quot;,&quot;D/R&quot;) df &lt;- data.frame(Friend1, Friend2, Interaction) df$Friend1 &lt;- as.factor(as.character(df$Friend1)) df$Friend2 &lt;- as.factor(as.character(df$Friend2)) df$Interaction &lt;- as.factor(as.character(df$Interaction)) ggplot(df, aes(fill=Interaction, y=count(Interaction), x=Friend2)) + geom_bar(position=&quot;fill&quot;, stat=&quot;identity&quot;, color = &quot;white&quot;) + theme_classic() + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_rect(colour = &quot;black&quot;, size=1)) + theme(strip.background = element_blank()) + facet_grid(.~Friend1) Erorr: Error in UseMethod(&quot;count&quot;) : no applicable method for 'count' applied to an object of class &quot;character&quot; </code></pre> <p>How do I &quot;count&quot; these factors to visualize frequency of interactions?</p>
[ { "answer_id": 74468058, "author": "stefan", "author_id": 12993861, "author_profile": "https://Stackoverflow.com/users/12993861", "pm_score": 2, "selected": false, "text": "dplyr::count" }, { "answer_id": 74468346, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 1, "selected": false, "text": "ggplot(df, aes(x = 1, fill = Interaction)) +\n geom_bar(width = 1, color = \"white\", size = 1, alpha = 0.8) +\n geom_text(stat = \"count\", aes(label = after_stat(count)), size = 7,\n position = position_stack(vjust = 0.5), color = \"white\",\n fontface = 2) +\n facet_grid(Friend1 ~ Friend2, switch = \"both\") +\n scale_fill_brewer(palette = \"Set1\") +\n coord_polar(theta = \"y\") +\n labs(x = \"Friend1\", y = \"Friend2\") +\n theme_bw(base_size = 20) +\n theme(panel.grid = element_blank(),\n strip.background = element_blank(),\n strip.placement = \"outside\",\n axis.text.x = element_blank(),\n panel.border = element_rect(color = \"gray90\", fill = NA),\n panel.spacing = unit(0, \"mm\"),\n axis.text = element_blank(),\n axis.ticks = element_blank())\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6820344/" ]
74,467,999
<p>I was trying to convert a datetime from one timezone to another. I'm in the process of updating our Python codebase to stop relying on utilities we don't need anymore. In particular, I'm deprecating our use of <code>arrow</code> and <code>pytz</code>. In doing so, I noticed some strange behavior from <code>ZoneInfo(&quot;UTC&quot;)</code>.</p> <pre class="lang-py prettyprint-override"><code>from datetime import datetime, timezone jan1_in_utc = datetime.fromisoformat('2022-01-01T08:00').replace(tzinfo=ZoneInfo(&quot;UTC&quot;)) # This gives datetime.datetime(2022, 1, 1, 8, 0, tzinfo=zoneinfo.ZoneInfo(key='UTC')) # Let's say I try to convert it to America/Toronto timezone jan1_in_utc.astimezone(ZoneInfo(&quot;America/Toronto&quot;)) # This gives me the SAME date time ?!?!? # datetime.datetime(2022, 1, 1, 8, 0, tzinfo=zoneinfo.ZoneInfo(key='America/Toronto')) # However, if I use timezone.utc instead jan1_in_utc = datetime.fromisoformat('2022-01-01T08:00').replace(tzinfo=timezone.utc) # This works as expected jan1_in_utc.astimezone(ZoneInfo(&quot;America/Toronto&quot;)) # this correctly calculates a -5 offset # datetime.datetime(2022, 1, 1, 3, 0, tzinfo=zoneinfo.ZoneInfo(key='America/Toronto')) </code></pre> <p>I'm not sure what I'm doing wrong. &quot;UTC&quot; is in the list of <code>zoneinfo.available_timezones()</code>. Using &quot;utc&quot; raises an error.</p> <p>I also noticed this oddity. Calculating the <code>utcoffset</code> from the <code>ZoneInfo(&quot;UTC&quot;)</code> isn't <code>0</code>.</p> <pre class="lang-py prettyprint-override"><code>jan1_in_utc = datetime.fromisoformat('2022-01-01T08:00').replace(tzinfo=ZoneInfo(&quot;UTC&quot;)) ZoneInfo(&quot;UTC&quot;).utcoffset(jan1_in_utc) </code></pre> <p>Where as if I use <code>timezone.utc</code>, there's no time difference.</p> <pre class="lang-py prettyprint-override"><code>jan1_in_utc = datetime.fromisoformat('2022-01-01T08:00').replace(tzinfo=timezone.utc) timezone.utc.utcoffset(jan1_in_utc) # This gives datetime.timedelta(0) </code></pre> <p>Now I'm unsure if I should use <code>ZoneInfo</code> at all, or if I should still rely on <code>pytz</code> and <code>arrow</code>. Any thoughts? Clearly, I'm missing something!</p>
[ { "answer_id": 74468058, "author": "stefan", "author_id": 12993861, "author_profile": "https://Stackoverflow.com/users/12993861", "pm_score": 2, "selected": false, "text": "dplyr::count" }, { "answer_id": 74468346, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 1, "selected": false, "text": "ggplot(df, aes(x = 1, fill = Interaction)) +\n geom_bar(width = 1, color = \"white\", size = 1, alpha = 0.8) +\n geom_text(stat = \"count\", aes(label = after_stat(count)), size = 7,\n position = position_stack(vjust = 0.5), color = \"white\",\n fontface = 2) +\n facet_grid(Friend1 ~ Friend2, switch = \"both\") +\n scale_fill_brewer(palette = \"Set1\") +\n coord_polar(theta = \"y\") +\n labs(x = \"Friend1\", y = \"Friend2\") +\n theme_bw(base_size = 20) +\n theme(panel.grid = element_blank(),\n strip.background = element_blank(),\n strip.placement = \"outside\",\n axis.text.x = element_blank(),\n panel.border = element_rect(color = \"gray90\", fill = NA),\n panel.spacing = unit(0, \"mm\"),\n axis.text = element_blank(),\n axis.ticks = element_blank())\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74467999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1267625/" ]
74,468,019
<p>I have two images, one is a RGB image and the other is a mask image that contains 0 and 1 to segment a specified object. (both images are of the same object) I want to extract the RBG values of the initial image only at the indexes where the second matrix is 1, so that the final value is an image of just the object with a black background. is there a simple way to achieve this in numpy?</p> <p>I would like to solve this problem without using too many for loops, I think there should be a straight forward way in numpy but I have not had any luck so far</p>
[ { "answer_id": 74468239, "author": "Yosef.Schwartz", "author_id": 15633731, "author_profile": "https://Stackoverflow.com/users/15633731", "pm_score": 0, "selected": false, "text": "img = np.array([\n [[1,2],[3,4]],\n [[5,6],[7,8]],\n [[9,10],[11,12]]\n ])\n\nmask = np.array(\n [[0,1],[0,1]]\n )\n\nprint(np.array([\n np.multiply(img[0],mask),\n np.multiply(img[1],mask),\n np.multiply(img[2],mask)]\n ))\n# Res: \n\n\n #[[[ 0 2]\n # [ 0 4]]\n #\n # [[ 0 6]\n # [ 0 8]]\n #\n # [[ 0 10]\n # [ 0 12]]]\n" }, { "answer_id": 74471999, "author": "ShlomiF", "author_id": 5024514, "author_profile": "https://Stackoverflow.com/users/5024514", "pm_score": 1, "selected": false, "text": "numpy" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20524446/" ]
74,468,026
<p>I want to reference Azure CI Build.BuildNumber variable in my Angular app, but need a way to inject the build number into the environment file.</p> <p>I have tried referencing the Azure environment variables but these are not replaced automatically on build.</p>
[ { "answer_id": 74468239, "author": "Yosef.Schwartz", "author_id": 15633731, "author_profile": "https://Stackoverflow.com/users/15633731", "pm_score": 0, "selected": false, "text": "img = np.array([\n [[1,2],[3,4]],\n [[5,6],[7,8]],\n [[9,10],[11,12]]\n ])\n\nmask = np.array(\n [[0,1],[0,1]]\n )\n\nprint(np.array([\n np.multiply(img[0],mask),\n np.multiply(img[1],mask),\n np.multiply(img[2],mask)]\n ))\n# Res: \n\n\n #[[[ 0 2]\n # [ 0 4]]\n #\n # [[ 0 6]\n # [ 0 8]]\n #\n # [[ 0 10]\n # [ 0 12]]]\n" }, { "answer_id": 74471999, "author": "ShlomiF", "author_id": 5024514, "author_profile": "https://Stackoverflow.com/users/5024514", "pm_score": 1, "selected": false, "text": "numpy" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3530591/" ]
74,468,037
<p>Some values of my object are sometimes not in the domain and thus have a null value. How can I filter out the null values from this object when trying to iterate through it?</p> <p>That's the code I wrote but it doesnt do anything.</p> <pre><code>function enLanguage(){ let value1 = Object.values(dicEnglish); let key1 = Object.keys(dicEnglish); for (let y=0; y&lt;50; y++){ if ((typeof key1[y] === &quot;object&quot;) || (typeof value1[y] ===&quot;object&quot;)){ continue; }else{ let text1 = value1[y]; document.getElementById(key1[y]).textContent = text1; key1[y].textContent=value1[y]}}} </code></pre>
[ { "answer_id": 74468202, "author": "Albert Logic Einstein", "author_id": 14274392, "author_profile": "https://Stackoverflow.com/users/14274392", "pm_score": 0, "selected": false, "text": "null" }, { "answer_id": 74468220, "author": "Nazar Nintendo", "author_id": 20524194, "author_profile": "https://Stackoverflow.com/users/20524194", "pm_score": 3, "selected": true, "text": "typeof key1[y] === \"object\"" }, { "answer_id": 74468567, "author": "traktor", "author_id": 5217142, "author_profile": "https://Stackoverflow.com/users/5217142", "pm_score": 0, "selected": false, "text": "null" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20524425/" ]
74,468,042
<p>I'm trying to adjust the sizes and locations of the tiles in this DCL dialog box. Basically, I want to make the <code>edit-box</code>es in the <em>Client</em> box, <em>Job</em> box, and <em>Miscellaneous</em> box to be the same width. However, they each start at different widths due to the different sizes of the <code>text</code> tile's labels. Just setting the width to a fixed value for both <code>edit-box</code> and <code>text</code> tiles doesn't seem to be fixing the issue for me. How do I need to change this code to make the tiles within this dialog box uniform?</p> <p>As a bonus, I want to also adjust the tiles in the <em>Revision</em> box. I'm assuming this will be using the same solution. I want to have the widths of the <code>edit-box</code>es of different widths with the labels centered above them.</p> <p>I have found that DCL files are a slow and painful process for me. Any help with building this dialog box would be helpful. Thank you for your time.</p> <p><a href="https://i.stack.imgur.com/KPKZd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KPKZd.png" alt="Current DCL file layout" /></a></p> <p><strong>AutoLisp Code:</strong></p> <pre class="lang-lisp prettyprint-override"><code>(defun C:Test01 (/ sPathAndName sDCLModuleName dclFile bContinue) ;; Initializing (setq sPathAndName &quot;[File's location and name]&quot;) (setq sDCLModuleName &quot;TitleRevUpdate&quot;) (setq bContinue T) ;; File Exists (if (not (findfile sPathAndName))(progn (princ &quot;\nError: The DCL file was not found.\n&quot;) (setq bContinue nil) ));if&lt;-progn ;; DCL File (if bContinue (progn (setq dclFile (load_dialog sPathAndName)) (if (&gt;= 0 dclFile)(progn (princ &quot;\nError: DCL file cannot be loaded.\n&quot;) (setq bContinue nil) ));if&lt;-progn ));if&lt;-progn ;; Creating a new module (if bContinue (setq bContinue (new_dialog sDCLModuleName dclFile &quot;&quot; '(-1 -1))) );if ;; Build and run DCL module (if bContinue (progn ;; User Form (princ &quot;\nstart_dialog : &quot;)(princ (start_dialog))(terpri) (unload_dialog dclFile) ));if&lt;-progn );C:Test01 </code></pre> <p><strong>DCL Code:</strong></p> <pre class="lang-lisp prettyprint-override"><code> TitleRevUpdate : dialog { key = &quot;Title&quot; ; label = &quot;Update Title Block and Revision&quot; ; // Title : boxed_column { key = &quot;Column_TitleBoxes&quot; ; label = &quot;Title&quot; ; // Client : boxed_column { key = &quot;Client_Box&quot; ; label = &quot;Client&quot; ; : row { // Row 01 - Name key = &quot;Row_Client_Name&quot; ; width = 15 ; : text { key = &quot;txt_Client_Name&quot; ; alignment = right ; label = &quot;Client's Name&quot; ; width = 10 ; }// text : edit_box { key = &quot;edbx_Client_Name&quot; ; alignment = left ; width = 10 ; }// edit_box } //row : row { // Row 02 - Location key = &quot;Row_Client_Loc&quot; ; : text { key = &quot;txt_Client_Loc&quot; ; alignment = right ; label = &quot;Client's Location&quot; ; width = 10 ; }// text : edit_box { key = &quot;edbx_Client_Loc&quot; ; alignment = left ; width = 10 ; }// edit_box } //row } //boxed_column : spacer { }// spacer // Job : boxed_column { key = &quot;Job_Box&quot; ; label = &quot;Job&quot; ; : row { // Row 03 - Name key = &quot;Row_Job_Name&quot; ; : text { key = &quot;txt_Job_Name&quot; ; label = &quot;Job's Name&quot; ; }// text : edit_box { key = &quot;edbx_Job_Name&quot; ; }// edit_box } //row : row { // Row 04 - Number key = &quot;Row_Job_Number&quot; ; : text { key = &quot;txt_Job_Number&quot; ; label = &quot;Job's Number&quot; ; }// text : edit_box { key = &quot;edbx_Job_Number&quot; ; }// edit_box } //row } //boxed_column : spacer { }// spacer // Miscellaneous : boxed_column { key = &quot;Miscellaneous_Box&quot; ; label = &quot;Miscellaneous&quot; ; : row { // Row 05 - Creator's Initials key = &quot;Row_Creator_Name&quot; ; : text { key = &quot;txt_Creator_Name&quot; ; label = &quot;Creator's Name&quot; ; }// text : edit_box { key = &quot;edbx_Creator_Name&quot; ; }// edit_box } //row : row { // Row 06 - Date of Creation key = &quot;Row_Date&quot; ; : text { key = &quot;txt_TitleDate&quot; ; label = &quot;Date&quot; ; }// text : edit_box { key = &quot;edbx_TitleDate&quot; ; }// edit_box } //row : row { // Row 07 - Issued For key = &quot;Row_Issued_For&quot; ; : text { key = &quot;txt_Issued_For&quot; ; label = &quot;Issued For&quot; ; }// text : edit_box { key = &quot;edbx_Issued_For&quot; ; }// edit_box } //row } //boxed_column } //boxed_column : spacer { }// spacer // Revision : boxed_column { key = &quot;Column_Revision&quot; ; label = &quot;Revision&quot; ; : row { // Row 08 - Quick Choices key = &quot;Row_Buttons&quot; ; : button { key = &quot;btn_IFC&quot; ; label = &quot;Issued for Construction&quot; ; }// button : button { key = &quot;tbn_AB&quot; ; label = &quot;As Built&quot; ; }// button : radio_column { key = &quot;RadioCol_WriteMethod&quot; ; : radio_button { key = &quot;rbtn_Owt&quot; ; label = &quot;Clear &amp;&amp; Overwrite&quot; ; }// radio_button : radio_button { key = &quot;rbtn_Apnd&quot; ; label = &quot;Append / New Line&quot; ; }// radio_button } //radio_column } //row : spacer { }// spacer : row { // Row 09 - Rev Labels key = &quot;Row_Labels&quot; ; : text { key = &quot;txt_Rev&quot; ; label = &quot;Rev&quot; ; }// text : text { key = &quot;txt_Initials&quot; ; label = &quot;Initials&quot; ; }// text : text { key = &quot;txt_Description&quot; ; label = &quot;Description&quot; ; }// text : text { key = &quot;txt_RevDate&quot; ; label = &quot;Date&quot; ; }// text } //row : row { // Row 10 - Rev Edit Boxes key = &quot;Row_Rev&quot; ; : edit_box { key = &quot;edbx_Rev&quot; ; }// edit_box : edit_box { key = &quot;edbx_Initials&quot; ; }// edit_box : edit_box { key = &quot;edbx_Date&quot; ; }// edit_box : edit_box { key = &quot;edbx_RevDate&quot; ; }// edit_box } //row } //boxed_column : spacer { }// spacer // Return Commands : row { // Row 11 - Buttons key = &quot;Row_Return&quot; ; : button { key = &quot;btn_DWGs&quot; ; action = &quot;(done_dialog 2)&quot; ; label = &quot;Show Drawings&quot; ; }// button : button { key = &quot;btn_Confirm&quot; ; action = &quot;(done_dialog 1)&quot; ; is_enabled = true ; label = &quot;Confirm&quot; ; }// button : button { key = &quot;btn_Cancel&quot; ; action = &quot;(done_dialog 0)&quot; ; is_default = true ; label = &quot;Cancel&quot; ; }// button } //row : spacer { }// spacer } // TitleRevUpdate </code></pre>
[ { "answer_id": 74470262, "author": "CAD Developer", "author_id": 5796526, "author_profile": "https://Stackoverflow.com/users/5796526", "pm_score": 1, "selected": false, "text": "width = 10 ; \n" }, { "answer_id": 74476352, "author": "Lee Mac", "author_id": 7531598, "author_profile": "https://Stackoverflow.com/users/7531598", "pm_score": 3, "selected": true, "text": "width" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8543948/" ]
74,468,043
<p>My list has 12000 entries. Each entry consists of 16 columns and 8 rows. I would like to create a data frame for every single entry. I'm interested in 3 of the 16 columns (X,Y and Z coordinates)</p> <p>I already tried this:</p> <pre><code>data_frame12000 &lt;- as.data.frame(do.call(cbind, list_small_read_laz)) </code></pre> <p>This and other functions only create one big data.frame with all the 16 columns for each entry.</p> <p>Can anybody help me?</p> <p>Thank You in advance!</p>
[ { "answer_id": 74470262, "author": "CAD Developer", "author_id": 5796526, "author_profile": "https://Stackoverflow.com/users/5796526", "pm_score": 1, "selected": false, "text": "width = 10 ; \n" }, { "answer_id": 74476352, "author": "Lee Mac", "author_id": 7531598, "author_profile": "https://Stackoverflow.com/users/7531598", "pm_score": 3, "selected": true, "text": "width" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20524469/" ]
74,468,114
<p>Issue with Google Sheets:</p> <p>I have the CONCATENATE function combining text from several cells into 1 &quot;copypastable&quot; block. I'm inserting line breaks using CHAR(10).</p> <p><a href="https://i.stack.imgur.com/BRb9i.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BRb9i.jpg" alt="enter image description here" /></a></p> <p>So it looks fine in Google Sheets itself, and functions perfectly when copied to other Google apps.</p> <p>But copying it out to other programs (CorelDRAW, Illustrator, or AutoCAD) causes 2 issues:</p> <p>1.) Adds unwanted double quotes around the entire text. 2.) Destroys all line breaks.</p> <p><a href="https://i.stack.imgur.com/BUqqi.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BUqqi.jpg" alt="enter image description here" /></a></p> <p>So I have to manually edit every text block, to delete the quotes and add line breaks. Huge waste of time. How can I make it work properly?</p> <p>Interestingly enough, it works more properly in Notepad:</p> <p><a href="https://i.stack.imgur.com/XnWcc.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XnWcc.jpg" alt="enter image description here" /></a></p> <p>Still adds the double quotes, but at least the line breaks work.</p> <p>But having to copy/paste everything into Notepad, deleting the double-quotes, and then copy/pasting it into Corel/Illustrator/AutoCAD - STILL has the issue with the deleted line breaks.</p>
[ { "answer_id": 74468170, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 1, "selected": false, "text": "={\"\"; CONCATENATE(...)}\n" }, { "answer_id": 74468252, "author": "GC Ross", "author_id": 9986115, "author_profile": "https://Stackoverflow.com/users/9986115", "pm_score": 2, "selected": false, "text": "CHAR(13)" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3776654/" ]
74,468,115
<p>I am trying to implement this ear clipping algorithm (from the pseudocode) <a href="https://arxiv.org/ftp/arxiv/papers/1212/1212.6038.pdf#:%7E:text=The%20ear%20clipping%20triangulation%20algorithm,newly%20formed%20triangle%20is%20valid." rel="nofollow noreferrer">here</a> Currently at the point in the algorithm where I am trying to calculate the angle of each vertex in a polygon. I also got the idea of how to calculate the angles with vectors here: <a href="https://devforum.roblox.com/t/triangulating-polygons-using-the-ear-clipping-algorithm/1875449" rel="nofollow noreferrer">here</a> This way I can also determine convexity/concavity. Also my vertices are in counter clockwise order.</p> <p>This is a helper function I wrote to help in calculating the angle of each vertex:</p> <pre><code>void calcConvexity(Node&amp;* prev, Node&amp;* curr, Node&amp;* next) { glm::vec2 u(0.0f), v(0.0f); u.x = curr-&gt;x - prev-&gt;x; u.y = curr-&gt;y - prev-&gt;y; v.x = curr-&gt;x - next-&gt;x; v.y = curr-&gt;y - next-&gt;y; // Calculating angle (in radians) curr-&gt;Angle = ((u.x * v.y) - (u.y * v.x)) / std::sqrt((std::pow(u.x, 2.0f) + std::pow(u.y, 2.0f)) * std::sqrt(std::pow(v.x, 2.0f) + std::pow(v.y, 2.0f)); // Convert to degrees curr-&gt;Angle = (180 / 3.141592653589793238463) * curr-&gt;Angle; if (curr-&gt;Angle &lt; 180.0f) curr-&gt;isConvex = true; // The vertex is convex else curr-&gt;isConvex = false; } </code></pre> <p>I was expecting most of the angles to come out between 0 and 360 but they did not. I am not sure what further calculations or corrections I need to make. Also, in the node class I have a boolean attribute called isConvex. I know something wrong is happening because every vertex is having there isConvex attribute set to true even when there degree is greater than 180.0f (in the example below).</p> <p>Here is an actual example output as well: (The blue arrows are suppose to be facing in towards the nodes I just cant update the picture on here) <a href="https://i.stack.imgur.com/szsil.png" rel="nofollow noreferrer">Polygon With vectors to each vertice</a> as well as the isConvex values for each node: <a href="https://i.stack.imgur.com/Iea0X.png" rel="nofollow noreferrer">Node isConvex Values</a> and the angles: <a href="https://i.stack.imgur.com/9PkzH.png" rel="nofollow noreferrer">Node angle values</a></p> <p>I have tried facing the vectors in different directions as well as using the GLM library for vector operations.</p> <p>I apologize if any of what I have supplied is confusing, this is my first time messing with computational geometry in general. So I am just wondering what am I doing wrong in my calcConvexity method?</p> <p>UPDATED CODE:</p> <pre><code>void calcConvexity(Node&amp;* prev, Node&amp;* curr, Node&amp;* next) { glm::vec2 u(0.0f), v(0.0f); u.x = curr-&gt;x - prev-&gt;x; u.y = curr-&gt;y - prev-&gt;y; v.x = curr-&gt;x - next-&gt;x; v.y = curr-&gt;y - next-&gt;y; float CrossProduct = ((u.x * v.y) - (u.y * v.x)); if (CrossProduct &lt; 0) curr-&gt;isConvex = true; // The vertex is convex else curr-&gt;isConvex = false; // Otherwise concave curr-&gt;Angle = (CrossProduct) / std::sqrt((std::pow(u.x, 2.0f) + std::pow(u.y, 2.0f)) * std::sqrt(std::pow(v.x, 2.0f) + std::pow(v.y, 2.0f)); curr-&gt;Angle = glm::degrees(std::asin(curr-&gt;Angle)); } </code></pre> <p>So the solution I came up with is this: I use the Cross product to determine convexity and then I use a slightly different angle formula: cos(curr-&gt;Angle) = (u.b) / (|u||v|) My main problem was the the formula with sin was outputting between -90 and 90 while the formula with cos outputs between 0 and 180 Code that works:</p> <pre><code>void Graph::calcConvexity(Node*&amp; prev, Node*&amp; curr, Node*&amp; next) { glm::vec2 u(0.0f), v(0.0f); u.x = curr-&gt;x - prev-&gt;x; u.y = curr-&gt;y - prev-&gt;y; v.x = curr-&gt;x - next-&gt;x; v.y = curr-&gt;y - next-&gt;y; float CrossProduct = ((u.x * v.y) - (u.y * v.x)); if (CrossProduct &lt; 0) curr-&gt;isConvex = true; // The vertex is convex else curr-&gt;isConvex = false; // Otherwise concave float dotProduct = (u.x * v.x) + (u.y * v.y); curr-&gt;Angle = std::acos(dotProduct / (std::sqrt(std::pow(u.x, 2.0f) + std::pow(u.y, 2.0f)) * std::sqrt(std::pow(v.x, 2.0f) + std::pow(v.y, 2.0f)))); curr-&gt;Angle = glm::degrees(curr-&gt;Angle); } </code></pre>
[ { "answer_id": 74469652, "author": "radof", "author_id": 20349343, "author_profile": "https://Stackoverflow.com/users/20349343", "pm_score": 1, "selected": true, "text": "curr->Angle" }, { "answer_id": 74486846, "author": "Yves Daoust", "author_id": 1196549, "author_profile": "https://Stackoverflow.com/users/1196549", "pm_score": 2, "selected": false, "text": "atan2" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18900864/" ]
74,468,124
<p>I'm trying to speed up my code and right now I have a &quot;for&quot; loop to sum numbers in an array. It's set up like this:</p> <pre><code>a1=np.zeros(5) a2=[1,2,3,4,5,6,7,8,9,10] </code></pre> <p>And what I want to do is sum the values of <code>a2[:5]</code> + <code>a2[5:]</code>, to end up with</p> <pre><code>a1=[7,9,11,13,15] </code></pre> <p>So I've made a loop that goes:</p> <pre><code>for ii in range(2): a1+=a2[5*ii:5*(ii+1)] </code></pre> <p>However, this is taking really long. Does anyone have any ideas on how to get around this or how to restructure my code?</p> <p>I want to do:</p> <pre><code>i=np.range(2) a1+=a2[5*i:5*(i+1)] </code></pre> <p>But can't, since you can't use arrays as indices in Python. That's the only other idea I've had besides the loop.</p> <p>Edit: the 2 here is just an example, in my code I'm planning on having it do this like 50-100 times.</p>
[ { "answer_id": 74468341, "author": "Kristian K", "author_id": 13505403, "author_profile": "https://Stackoverflow.com/users/13505403", "pm_score": 0, "selected": false, "text": "a2 = np.array([1,2,3,4,5,6,7,8,9,10])\na1 = a2[:5] + np.roll(a2, -5)[:5]\n" }, { "answer_id": 74468688, "author": "DYZ", "author_id": 4492932, "author_profile": "https://Stackoverflow.com/users/4492932", "pm_score": 2, "selected": false, "text": "np.array(a2).reshape(2,5).sum(axis=0)\n# array([ 7, 9, 11, 13, 15])\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7906642/" ]
74,468,129
<p>I am trying to run Pentaho Data Integration (ver. 8.3) in my Windows machine and it is not working. These are the steps I tried to make it work:</p> <ul> <li>Tried rebooting the machine without success.</li> <li>Also tried to run the <strong>Spoon.bat</strong> command directly from the directory where Pentaho is located, but it did not work.</li> <li>Checked if my java installation changed since the last time it worked, it did not, what can be happening?</li> </ul> <p>In a support chat I read someone was able to fix the problem by clearing the cache, but did not explain how to do it, how do I clean the cache?</p>
[ { "answer_id": 74468341, "author": "Kristian K", "author_id": 13505403, "author_profile": "https://Stackoverflow.com/users/13505403", "pm_score": 0, "selected": false, "text": "a2 = np.array([1,2,3,4,5,6,7,8,9,10])\na1 = a2[:5] + np.roll(a2, -5)[:5]\n" }, { "answer_id": 74468688, "author": "DYZ", "author_id": 4492932, "author_profile": "https://Stackoverflow.com/users/4492932", "pm_score": 2, "selected": false, "text": "np.array(a2).reshape(2,5).sum(axis=0)\n# array([ 7, 9, 11, 13, 15])\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4123038/" ]
74,468,138
<p>I have no idea what all of the terminology means in the Laravel/Eloquent docs for relationships like <a href="https://laravel.com/api/5.5/Illuminate/Database/Eloquent/Relations/HasOne.html" rel="nofollow noreferrer">hasOne</a> or <a href="https://laravel.com/api/5.8/Illuminate/Database/Eloquent/Relations/BelongsTo.html" rel="nofollow noreferrer">belongsTo</a>.</p> <p>The hasOne class has the properties $parent, $related, $foreignKey, and $localKey among others.</p> <p>The belongsTo class has the properties $parent, $related, $child, $foreignKey, and $ownerKey among others.</p> <p>I wish I had a cheat sheet that had example relationships like</p> <pre> Given a one to one relationship between users and phones: user hasOne phone. phone belongsTo user hasOne class properties: $parent = a $related = b $foreignKey = c $localKey = d ... maybe more hasOne properties here belongsTo class properties: $parent = a $related = b $child = c $foreignKey = d $ownerKey = e ... maybe more belongsTo properties here </pre> <p>Except with a, b, c, d, etc filled in.</p> <p>I'd love have these kinds of examples for all relationship types. hasMany class properties and belongsToMany class properties in one to many and many to many relationships, etc. Every combination.</p> <p>The following quote (which is probably wrong) from my notes highlights a confusion I have:</p> <p>&quot;if a hasOne b or a hasMany b: a is called the parent model and b is called the related model, but I think b is also called the child model, so idk.&quot; - I'm pretty sure this quote is wrong, but I wish I knew the distinction between the different terms like child model and related model, etc.</p>
[ { "answer_id": 74468341, "author": "Kristian K", "author_id": 13505403, "author_profile": "https://Stackoverflow.com/users/13505403", "pm_score": 0, "selected": false, "text": "a2 = np.array([1,2,3,4,5,6,7,8,9,10])\na1 = a2[:5] + np.roll(a2, -5)[:5]\n" }, { "answer_id": 74468688, "author": "DYZ", "author_id": 4492932, "author_profile": "https://Stackoverflow.com/users/4492932", "pm_score": 2, "selected": false, "text": "np.array(a2).reshape(2,5).sum(axis=0)\n# array([ 7, 9, 11, 13, 15])\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3470632/" ]
74,468,140
<p>I'm trying to create an if statement in a for loop to look at an element in a list and compare it to the next element with enumerate().</p> <pre><code>arr = [&quot;NORTH&quot;, &quot;SOUTH&quot;, &quot;SOUTH&quot;, &quot;EAST&quot;, &quot;WEST&quot;, &quot;NORTH&quot;, &quot;WEST&quot;] liste = [] for idx,i in enumerate(arr): if (i == 'NORTH' and arr[idx+1] == 'SOUTH') or (i == 'SOUTH' and arr[idx+1] == 'NORTH') or (i == 'EAST' and arr[idx+1] == 'WEST') or (i == 'WEST' and arr[idx+1] == 'EAST'): liste.append(idx) liste.append(idx+1) print(liste) </code></pre> <p>expected</p> <pre><code>[0, 1, 3, 4] </code></pre> <p>got</p> <pre><code>--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Input In [44], in &lt;cell line: 2&gt;() 1 liste = [] 2 for idx,i in enumerate(arr): ----&gt; 3 if (i == 'NORTH' and arr[idx+1] == 'SOUTH') or (i == 'SOUTH' and arr[idx+1] == 'NORTH') or (i == 'EAST' and arr[idx+1] == 'WEST') or (i == 'WEST' and arr[idx+1] == 'EAST'): 4 liste.append(idx) 5 liste.append(idx+1) IndexError: list index out of range </code></pre> <p>but if the original if is (without the last &quot;or&quot;)</p> <pre><code>for idx,i in enumerate(arr): if (i == 'NORTH' and arr[idx+1] == 'SOUTH') or (i == 'SOUTH' and arr[idx+1] == 'NORTH') or (i == 'EAST' and arr[idx+1] == 'WEST'): </code></pre> <p>it goes through fine and gives the expected outcome (this case has no reversed west/east anyway, but I of course want it to work for random lists).</p> <p>What's up with that? It's a codewars problem and I can come up with a workaround myself, so I don't want the solution to the whole problem, I'm just trying to understand why it's behaving this way. EDIT: I just realized it's because the last element in the list is actually &quot;WEST&quot; so then it's checking idx+1 which for the last element is not in the list. In that case I would be interested in how to avoid that!</p>
[ { "answer_id": 74468198, "author": "BrokenBenchmark", "author_id": 17769815, "author_profile": "https://Stackoverflow.com/users/17769815", "pm_score": 0, "selected": false, "text": "i == 'WEST' and arr[idx+1] == 'EAST'\n" }, { "answer_id": 74468253, "author": "Devin Sag", "author_id": 20388932, "author_profile": "https://Stackoverflow.com/users/20388932", "pm_score": 1, "selected": false, "text": "arr = [\"NORTH\", \"SOUTH\", \"SOUTH\", \"EAST\", \"WEST\", \"NORTH\", \"WEST\"]\nliste = []\nfor idx,i in enumerate(arr[:len(arr)-1]):\n if (i == 'NORTH' and arr[idx+1] == 'SOUTH') or (i == 'SOUTH' and arr[idx+1] == 'NORTH') or (i == 'EAST' and arr[idx+1] == 'WEST') or (i == 'WEST' and arr[idx+1] == 'EAST'):\n liste.append(idx)\n liste.append(idx+1)\nprint(liste)\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20524551/" ]
74,468,174
<p>How to turn two subscribe into one? Do I need to use any rxjs operator?</p> <pre><code>ngOnInit(){ this.aService.aa.subscribe((data) =&gt; { this.data = data; this.bService.bb.subscribe(data =&gt; { this.data2 = data.map(AA.AAFromDefinition); }); }); } </code></pre>
[ { "answer_id": 74468198, "author": "BrokenBenchmark", "author_id": 17769815, "author_profile": "https://Stackoverflow.com/users/17769815", "pm_score": 0, "selected": false, "text": "i == 'WEST' and arr[idx+1] == 'EAST'\n" }, { "answer_id": 74468253, "author": "Devin Sag", "author_id": 20388932, "author_profile": "https://Stackoverflow.com/users/20388932", "pm_score": 1, "selected": false, "text": "arr = [\"NORTH\", \"SOUTH\", \"SOUTH\", \"EAST\", \"WEST\", \"NORTH\", \"WEST\"]\nliste = []\nfor idx,i in enumerate(arr[:len(arr)-1]):\n if (i == 'NORTH' and arr[idx+1] == 'SOUTH') or (i == 'SOUTH' and arr[idx+1] == 'NORTH') or (i == 'EAST' and arr[idx+1] == 'WEST') or (i == 'WEST' and arr[idx+1] == 'EAST'):\n liste.append(idx)\n liste.append(idx+1)\nprint(liste)\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20211948/" ]
74,468,188
<p>I'm working on an assignment for my introduction to SQL class and have been having trouble getting certain information to output correctly.</p> <pre><code>CREATE TABLE PRODUCT( ProductID CHAR(5) NOT NULL, ProductName CHAR(20) NOT NULL, ProductPrice MONEY NOT NULL, VendorID CHAR(5) NOT NULL, CategoryID CHAR(5) NOT NULL, CONSTRAINT Product_PK PRIMARY KEY (ProductID), CONSTRAINT Product_FK1 FOREIGN KEY (VendorID) REFERENCES VENDOR(VendorID), CONSTRAINT Product_FK2 FOREIGN KEY (CategoryID) REFERENCES CATEGORY(CategoryID) ); INSERT INTO PRODUCT VALUES ('1X1', 'Zzz Bag', '$100', 'PG', 'CP'), ('2X2', 'Easy Boot', '$70', 'MK', 'FW'), ('3X3', 'Cosy Sock', '$15', 'MK', 'FW'), ('4X4', 'Dura Boot', '$90', 'PG', 'FW'), ('5X5', 'Tiny Tent', '$150', 'MK', 'CP'), ('6X6', 'Biggy Tent', '$250', 'MK', 'CP') ; </code></pre> <p>I've written out my code above but when I run the select query:</p> <pre><code>SELECT * FROM PRODUCT; </code></pre> <p>The output I get is:</p> <pre><code>1X1 Zzz Bag 100.00 PG CP 2X2 Easy Boot 70.00 MK FW 3X3 Cosy Sock 15.00 MK FW 4X4 Dura Boot 90.00 PG FW 5X5 Tiny Tent 150.00 MK CP 6X6 Biggy Tent 250.00 MK CP </code></pre> <p>and I am hoping to get</p> <pre><code>1X1 Zzz Bag $100.00 PG CP 2X2 Easy Boot $70.00 MK FW 3X3 Cosy Sock $15.00 MK FW 4X4 Dura Boot $90.00 PG FW 5X5 Tiny Tent $150.00 MK CP 6X6 Biggy Tent $250.00 MK CP </code></pre> <p>As you can see the $ does not appear for some reason. Any help would be appreciated.</p>
[ { "answer_id": 74468198, "author": "BrokenBenchmark", "author_id": 17769815, "author_profile": "https://Stackoverflow.com/users/17769815", "pm_score": 0, "selected": false, "text": "i == 'WEST' and arr[idx+1] == 'EAST'\n" }, { "answer_id": 74468253, "author": "Devin Sag", "author_id": 20388932, "author_profile": "https://Stackoverflow.com/users/20388932", "pm_score": 1, "selected": false, "text": "arr = [\"NORTH\", \"SOUTH\", \"SOUTH\", \"EAST\", \"WEST\", \"NORTH\", \"WEST\"]\nliste = []\nfor idx,i in enumerate(arr[:len(arr)-1]):\n if (i == 'NORTH' and arr[idx+1] == 'SOUTH') or (i == 'SOUTH' and arr[idx+1] == 'NORTH') or (i == 'EAST' and arr[idx+1] == 'WEST') or (i == 'WEST' and arr[idx+1] == 'EAST'):\n liste.append(idx)\n liste.append(idx+1)\nprint(liste)\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20524578/" ]
74,468,211
<p>I know I could iteratively pop the elements into an array, but would prefer to directly cast it if possible.</p>
[ { "answer_id": 74468198, "author": "BrokenBenchmark", "author_id": 17769815, "author_profile": "https://Stackoverflow.com/users/17769815", "pm_score": 0, "selected": false, "text": "i == 'WEST' and arr[idx+1] == 'EAST'\n" }, { "answer_id": 74468253, "author": "Devin Sag", "author_id": 20388932, "author_profile": "https://Stackoverflow.com/users/20388932", "pm_score": 1, "selected": false, "text": "arr = [\"NORTH\", \"SOUTH\", \"SOUTH\", \"EAST\", \"WEST\", \"NORTH\", \"WEST\"]\nliste = []\nfor idx,i in enumerate(arr[:len(arr)-1]):\n if (i == 'NORTH' and arr[idx+1] == 'SOUTH') or (i == 'SOUTH' and arr[idx+1] == 'NORTH') or (i == 'EAST' and arr[idx+1] == 'WEST') or (i == 'WEST' and arr[idx+1] == 'EAST'):\n liste.append(idx)\n liste.append(idx+1)\nprint(liste)\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7674028/" ]
74,468,280
<p>I am trying to build a Dataproc cluster, with Spark NLP installed in it, then quick test it by reading some CoNLL 2003 data. First, I used this <a href="https://codelabs.developers.google.com/codelabs/spark-nlp#3" rel="nofollow noreferrer">codelab</a> as inspiration, to build my own smaller cluster (<code>project</code> name has been edited for safety purposes):</p> <pre><code>gcloud dataproc clusters create s17-sparknlp-experiments \ --enable-component-gateway \ --region us-west1 \ --metadata 'PIP_PACKAGES=google-cloud-storage spark-nlp==2.5.5' \ --zone us-west1-a \ --single-node \ --master-machine-type n1-standard-4 \ --master-boot-disk-size 35 \ --image-version 1.5-debian10 \ --initialization-actions gs://dataproc-initialization-actions/python/pip-install.sh \ --optional-components JUPYTER,ANACONDA \ --project my-project </code></pre> <p>I started the previous cluster via JupyterLab, then downloaded <a href="https://github.com/JohnSnowLabs/spark-nlp/tree/master/src/test/resources/conll2003" rel="nofollow noreferrer">these CoNLL 2003 files</a> in <code>~/original</code> directory, existing in root . If done correctly, when you run these commands:</p> <pre><code>cd / &amp;&amp; head -n 5 original/eng.train </code></pre> <p>The following result should obtained:</p> <pre><code>-DOCSTART- -X- -X- O EU NNP B-NP B-ORG rejects VBZ B-VP O German JJ B-NP B-MISC </code></pre> <p>This means these files should be able to be read in the following Python code, existing in a single-celled Jupyter Notebook:</p> <pre class="lang-py prettyprint-override"><code>from pyspark.ml import Pipeline from pyspark.sql import SparkSession from sparknlp.annotator import * from sparknlp.base import * from sparknlp.common import * from sparknlp.training import CoNLL import sparknlp spark = sparknlp.start() print(&quot;Spark NLP version: &quot;, sparknlp.version()) # 2.4.4 print(&quot;Apache Spark version: &quot;, spark.version) # 2.4.8 # Other info of possible interest: # Python 3.6.13 :: Anaconda, Inc. # openjdk version &quot;1.8.0_312&quot; # OpenJDK Runtime Environment (Temurin)(build 1.8.0_312-b07) # OpenJDK 64-Bit Server VM (Temurin)(build 25.312-b07, mixed mode) training_data = CoNLL().readDataset(spark, 'original/eng.train') # The exact same path used before... training_data.show() </code></pre> <p>Instead, the following error gets triggered:</p> <pre><code>--------------------------------------------------------------------------- Py4JJavaError Traceback (most recent call last) &lt;ipython-input-4-2b145ab3b733&gt; in &lt;module&gt; ----&gt; 1 training_data = CoNLL().readDataset(spark, 'original/eng.train') 2 training_data.show() /opt/conda/anaconda/lib/python3.6/site-packages/sparknlp/training.py in readDataset(self, spark, path, read_as) 32 jSession = spark._jsparkSession 33 ---&gt; 34 jdf = self._java_obj.readDataset(jSession, path, read_as) 35 return DataFrame(jdf, spark._wrapped) 36 /opt/conda/anaconda/lib/python3.6/site-packages/py4j/java_gateway.py in __call__(self, *args) 1255 answer = self.gateway_client.send_command(command) 1256 return_value = get_return_value( -&gt; 1257 answer, self.gateway_client, self.target_id, self.name) 1258 1259 for temp_arg in temp_args: /usr/lib/spark/python/pyspark/sql/utils.py in deco(*a, **kw) 61 def deco(*a, **kw): 62 try: ---&gt; 63 return f(*a, **kw) 64 except py4j.protocol.Py4JJavaError as e: 65 s = e.java_exception.toString() /opt/conda/anaconda/lib/python3.6/site-packages/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name) 326 raise Py4JJavaError( 327 &quot;An error occurred while calling {0}{1}{2}.\n&quot;. --&gt; 328 format(target_id, &quot;.&quot;, name), value) 329 else: 330 raise Py4JError( Py4JJavaError: An error occurred while calling o87.readDataset. : java.io.FileNotFoundException: file or folder: original/eng.train not found at com.johnsnowlabs.nlp.util.io.ResourceHelper$SourceStream.&lt;init&gt;(ResourceHelper.scala:44) at com.johnsnowlabs.nlp.util.io.ResourceHelper$.parseLines(ResourceHelper.scala:215) at com.johnsnowlabs.nlp.training.CoNLL.readDocs(CoNLL.scala:31) at com.johnsnowlabs.nlp.training.CoNLL.readDataset(CoNLL.scala:198) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244) at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357) at py4j.Gateway.invoke(Gateway.java:282) at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132) at py4j.commands.CallCommand.execute(CallCommand.java:79) at py4j.GatewayConnection.run(GatewayConnection.java:238) at java.lang.Thread.run(Thread.java:748) </code></pre> <p>QUESTION: What could be possibly going wrong here?</p>
[ { "answer_id": 74468198, "author": "BrokenBenchmark", "author_id": 17769815, "author_profile": "https://Stackoverflow.com/users/17769815", "pm_score": 0, "selected": false, "text": "i == 'WEST' and arr[idx+1] == 'EAST'\n" }, { "answer_id": 74468253, "author": "Devin Sag", "author_id": 20388932, "author_profile": "https://Stackoverflow.com/users/20388932", "pm_score": 1, "selected": false, "text": "arr = [\"NORTH\", \"SOUTH\", \"SOUTH\", \"EAST\", \"WEST\", \"NORTH\", \"WEST\"]\nliste = []\nfor idx,i in enumerate(arr[:len(arr)-1]):\n if (i == 'NORTH' and arr[idx+1] == 'SOUTH') or (i == 'SOUTH' and arr[idx+1] == 'NORTH') or (i == 'EAST' and arr[idx+1] == 'WEST') or (i == 'WEST' and arr[idx+1] == 'EAST'):\n liste.append(idx)\n liste.append(idx+1)\nprint(liste)\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16706763/" ]
74,468,289
<p>Lets say I have two arrays as follows:</p> <pre><code>const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr'] const B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa'] </code></pre> <p>I want to subtract array A from array B. With the result looking like this:</p> <pre><code>const result = ['Mo', 'Mo', 'Sa'] </code></pre> <p>How can this be achieved? It seems so simple but I cannot get it working.</p> <p>Essentially this should remove everything from B once that is in A.</p>
[ { "answer_id": 74468402, "author": "Mauricio Cárdenas", "author_id": 7560262, "author_profile": "https://Stackoverflow.com/users/7560262", "pm_score": -1, "selected": false, "text": "const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr']\nconst B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa']\nlet res = B;\nA.forEach(val => {\n for(let i = 0; i < res.length; i++) {\n if(res[i] === val) {\n res.splice(res.indexOf(val), 1);\n break;\n }\n }\n});\n" }, { "answer_id": 74468410, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 3, "selected": true, "text": "const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr']\nconst B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa']\n\nconsole.log(A.reduce((b, a)=>\n (b.includes(a) && b.splice(b.indexOf(a),1), b), [...B]))" }, { "answer_id": 74468419, "author": "Mohamed Oraby", "author_id": 11242930, "author_profile": "https://Stackoverflow.com/users/11242930", "pm_score": 0, "selected": false, "text": "const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr']\nconst B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa']\n\nconst C = B.map(el => {\n const elIndexInA = A.findIndex(e => e === el)\n if (elIndexInA === -1) {\n return el\n }\n A.splice(elIndexInA, 1)\n}).filter(el => el)\n\nconsole.log(C)" }, { "answer_id": 74468583, "author": "pilchard", "author_id": 13762301, "author_profile": "https://Stackoverflow.com/users/13762301", "pm_score": 2, "selected": false, "text": "filter()" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5203853/" ]
74,468,321
<p>I have an issue where I'm attempting to order multiple distinct streams from a time series database. Assuming that all the data in each stream is sorted by timestamp, given the following code how would I modify streams <code>dataA$</code> and <code>dataB$</code> such that each of them emitted values in order of the timestamped value WITHOUT waiting until the entire stream has completed:</p> <pre><code>import { delayWhen, of, timer } from &quot;rxjs&quot;; const dataA = [{&quot;data&quot;:&quot;b&quot;,&quot;timestamp&quot;:6672},{&quot;data&quot;:&quot;c&quot;,&quot;timestamp&quot;:7404},{&quot;data&quot;:&quot;a&quot;,&quot;timestamp&quot;:7922},{&quot;data&quot;:&quot;b&quot;,&quot;timestamp&quot;:8885},{&quot;data&quot;:&quot;c&quot;,&quot;timestamp&quot;:9111},{&quot;data&quot;:&quot;a&quot;,&quot;timestamp&quot;:9245},{&quot;data&quot;:&quot;c&quot;,&quot;timestamp&quot;:10168},{&quot;data&quot;:&quot;b&quot;,&quot;timestamp&quot;:10778},{&quot;data&quot;:&quot;c&quot;,&quot;timestamp&quot;:11504},{&quot;data&quot;:&quot;a&quot;,&quot;timestamp&quot;:12398},{&quot;data&quot;:&quot;a&quot;,&quot;timestamp&quot;:12745},{&quot;data&quot;:&quot;a&quot;,&quot;timestamp&quot;:13648},{&quot;data&quot;:&quot;a&quot;,&quot;timestamp&quot;:14233},{&quot;data&quot;:&quot;a&quot;,&quot;timestamp&quot;:14943},{&quot;data&quot;:&quot;b&quot;,&quot;timestamp&quot;:15869},{&quot;data&quot;:&quot;c&quot;,&quot;timestamp&quot;:16043},{&quot;data&quot;:&quot;a&quot;,&quot;timestamp&quot;:16169},{&quot;data&quot;:&quot;a&quot;,&quot;timestamp&quot;:16242},{&quot;data&quot;:&quot;a&quot;,&quot;timestamp&quot;:17058},{&quot;data&quot;:&quot;b&quot;,&quot;timestamp&quot;:17885},{&quot;data&quot;:&quot;a&quot;,&quot;timestamp&quot;:18252},{&quot;data&quot;:&quot;a&quot;,&quot;timestamp&quot;:18711},{&quot;data&quot;:&quot;c&quot;,&quot;timestamp&quot;:18883},{&quot;data&quot;:&quot;b&quot;,&quot;timestamp&quot;:19618},{&quot;data&quot;:&quot;a&quot;,&quot;timestamp&quot;:20183}]; const dataB = [{&quot;data&quot;:&quot;b&quot;,&quot;timestamp&quot;:821},{&quot;data&quot;:&quot;b&quot;,&quot;timestamp&quot;:1357},{&quot;data&quot;:&quot;b&quot;,&quot;timestamp&quot;:2108},{&quot;data&quot;:&quot;b&quot;,&quot;timestamp&quot;:3001},{&quot;data&quot;:&quot;a&quot;,&quot;timestamp&quot;:3995},{&quot;data&quot;:&quot;b&quot;,&quot;timestamp&quot;:4475},{&quot;data&quot;:&quot;c&quot;,&quot;timestamp&quot;:5357},{&quot;data&quot;:&quot;c&quot;,&quot;timestamp&quot;:5373},{&quot;data&quot;:&quot;b&quot;,&quot;timestamp&quot;:6199},{&quot;data&quot;:&quot;c&quot;,&quot;timestamp&quot;:6207},{&quot;data&quot;:&quot;b&quot;,&quot;timestamp&quot;:6896},{&quot;data&quot;:&quot;b&quot;,&quot;timestamp&quot;:7410},{&quot;data&quot;:&quot;a&quot;,&quot;timestamp&quot;:8335},{&quot;data&quot;:&quot;a&quot;,&quot;timestamp&quot;:9191},{&quot;data&quot;:&quot;b&quot;,&quot;timestamp&quot;:10007},{&quot;data&quot;:&quot;b&quot;,&quot;timestamp&quot;:10703},{&quot;data&quot;:&quot;c&quot;,&quot;timestamp&quot;:11225},{&quot;data&quot;:&quot;c&quot;,&quot;timestamp&quot;:11453},{&quot;data&quot;:&quot;c&quot;,&quot;timestamp&quot;:12131},{&quot;data&quot;:&quot;c&quot;,&quot;timestamp&quot;:12599},{&quot;data&quot;:&quot;c&quot;,&quot;timestamp&quot;:13567},{&quot;data&quot;:&quot;a&quot;,&quot;timestamp&quot;:13726},{&quot;data&quot;:&quot;b&quot;,&quot;timestamp&quot;:14161},{&quot;data&quot;:&quot;b&quot;,&quot;timestamp&quot;:14224},{&quot;data&quot;:&quot;b&quot;,&quot;timestamp&quot;:14666}]; const dataA$ = of(dataA).pipe( delayWhen(() =&gt; timer(Math.random() * 5000)), ??? ); const dataB$ = of(dataB).pipe( delayWhen(() =&gt; timer(Math.random() * 5000)), ??? ); let lastTimestamp = -Infinity; dataA$.subscribe(({ timestamp }) =&gt; { expect(timestamp &gt; lastTimestamp).toBe(true); lastTimestamp = timestamp; }); dataB$.subscribe(({ timestamp }) =&gt; { expect(timestamp &gt; lastTimestamp).toBe(true); lastTimestamp = timestamp; }); </code></pre> <p>Follow up question: How can you extend that solution to dynamically support any number of data streams once a stream was created?</p>
[ { "answer_id": 74468402, "author": "Mauricio Cárdenas", "author_id": 7560262, "author_profile": "https://Stackoverflow.com/users/7560262", "pm_score": -1, "selected": false, "text": "const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr']\nconst B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa']\nlet res = B;\nA.forEach(val => {\n for(let i = 0; i < res.length; i++) {\n if(res[i] === val) {\n res.splice(res.indexOf(val), 1);\n break;\n }\n }\n});\n" }, { "answer_id": 74468410, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 3, "selected": true, "text": "const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr']\nconst B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa']\n\nconsole.log(A.reduce((b, a)=>\n (b.includes(a) && b.splice(b.indexOf(a),1), b), [...B]))" }, { "answer_id": 74468419, "author": "Mohamed Oraby", "author_id": 11242930, "author_profile": "https://Stackoverflow.com/users/11242930", "pm_score": 0, "selected": false, "text": "const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr']\nconst B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa']\n\nconst C = B.map(el => {\n const elIndexInA = A.findIndex(e => e === el)\n if (elIndexInA === -1) {\n return el\n }\n A.splice(elIndexInA, 1)\n}).filter(el => el)\n\nconsole.log(C)" }, { "answer_id": 74468583, "author": "pilchard", "author_id": 13762301, "author_profile": "https://Stackoverflow.com/users/13762301", "pm_score": 2, "selected": false, "text": "filter()" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2832365/" ]
74,468,338
<p>I'm coding this password manager program and keep getting this error message when I use the view function:</p> <pre><code> File &quot;c:\Users\user\Desktop\password_manager.py&quot;, line 7, in view user, passw = data.split(&quot;|&quot;) ValueError: too many values to unpack (expected 2) </code></pre> <p>This is the program so far:</p> <pre><code>master_pwd = input(&quot;What is the master password?&quot;) def view(): with open(&quot;passwords.txt&quot;, &quot;r&quot;) as f: for line in f.readlines(): data = line.rstrip() user, passw = data.split(&quot;|&quot;) print(&quot;User:&quot;, user, &quot;Password:&quot;, passw) def add(): name = input(&quot;Account name: &quot;) pwd = input(&quot;Password: &quot;) with open(&quot;passwords.txt&quot;, &quot;a&quot;) as f: f.write(name + &quot;|&quot; + pwd + &quot;\n&quot;) while True: mode = input(&quot;Would you like to add a new password or view existing ones (view, add)? Press q to quit. &quot;).lower() if mode == &quot;q&quot;: break if mode == &quot;view&quot;: view() elif mode == &quot;add&quot;: add() else: print(&quot;Invalid mode.&quot;) continue </code></pre> <p>I tried using the .split() method to one variable at a time but it also resulted in the error. I thought the problem could be caused by the comma in <code>user, passw = data.split(&quot;|&quot;)</code> being deprecated, but I failed to find an alternative.</p>
[ { "answer_id": 74468402, "author": "Mauricio Cárdenas", "author_id": 7560262, "author_profile": "https://Stackoverflow.com/users/7560262", "pm_score": -1, "selected": false, "text": "const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr']\nconst B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa']\nlet res = B;\nA.forEach(val => {\n for(let i = 0; i < res.length; i++) {\n if(res[i] === val) {\n res.splice(res.indexOf(val), 1);\n break;\n }\n }\n});\n" }, { "answer_id": 74468410, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 3, "selected": true, "text": "const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr']\nconst B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa']\n\nconsole.log(A.reduce((b, a)=>\n (b.includes(a) && b.splice(b.indexOf(a),1), b), [...B]))" }, { "answer_id": 74468419, "author": "Mohamed Oraby", "author_id": 11242930, "author_profile": "https://Stackoverflow.com/users/11242930", "pm_score": 0, "selected": false, "text": "const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr']\nconst B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa']\n\nconst C = B.map(el => {\n const elIndexInA = A.findIndex(e => e === el)\n if (elIndexInA === -1) {\n return el\n }\n A.splice(elIndexInA, 1)\n}).filter(el => el)\n\nconsole.log(C)" }, { "answer_id": 74468583, "author": "pilchard", "author_id": 13762301, "author_profile": "https://Stackoverflow.com/users/13762301", "pm_score": 2, "selected": false, "text": "filter()" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13119431/" ]
74,468,369
<p>I have a simple Python program with multiple functions that displays a menu, takes an input, loops through and formats a CSV file then outputs information from that CSV file based on the user's input.</p> <p>The Menu options look like</p> <pre class="lang-none prettyprint-override"><code>1: Call menu again 2: Create a default Report 3: More specified report 4: More specified Report 5: Exit program </code></pre> <p>I am using a while loop to loop over these menu options so I can call the menu repeatedly while the user continues to input a 1.</p> <p>here is a look at the while loop</p> <pre><code>def main(): banner() while True: choice = menu() #if the choice = 1, we call the menu function again if choice == 1: menu() elif choice == 2: defaultReport() break elif choice == 3: #elif statement for a function not yet created in part 1 pass elif choice == 4: #elif statement for a function not yet created in part 1 pass elif choice ==5: print('\nExiting Program') break </code></pre> <p>The goal is to be able to call the menu function while the input (choice) = 1, then as soon as the input equals something else the program executes the code corresponding to the input without calling/displaying the menu again</p> <p>Examp. of current problem:</p> <ol> <li>1 - calls/displays menu again 1st input</li> <li>1 - calls/displays menuagain 2nd input</li> <li>2 - should show a default report, but calls the menu/displays it once more 3rd input</li> <li>2- shows default output 4th input</li> </ol> <p>Goal:</p> <ol> <li>1 - calls/displays menu again 1st input</li> <li>1 - calls/displays menu again 2nd input</li> <li>2- shows default output 3rd input</li> </ol> <p>Menu function for those interested:</p> <pre><code>def menu(): print('''\nMortality Rate Comparison Menu 1. Show This Menu Again 2. Full Mortality Report by State 3. Mortality for a Single State, by Date Range 4. Mortality Summary for all States 5. Exit \n ''') choice = input('Make your selection from the menu: ') while True: try: int(choice) break except: choice = input('Make your selection from the menu: ') while int(choice) &gt; 5 or int(choice) &lt; 1: choice = input('Make your selection from the menu: ') return int(choice) </code></pre>
[ { "answer_id": 74468543, "author": "thebjorn", "author_id": 75103, "author_profile": "https://Stackoverflow.com/users/75103", "pm_score": 0, "selected": false, "text": "while True:\n ...\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20524598/" ]
74,468,377
<p>I'm trying to deserialize a JSON response from an API and get the NAME of what in this example is &quot;af&quot; (country code of Afghanistan) inside &quot;iso&quot;, but the name of the field will be different everytime based on the country code, how can i read the name of the field and retrieve each country code in the api response? thanks!</p> <p>Example response:</p> <pre><code>{ &quot;afghanistan&quot;:{ &quot;iso&quot;:{ &quot;af&quot;:1 }, &quot;prefix&quot;:{ &quot;+93&quot;:1 }, &quot;text_en&quot;:&quot;Afghanistan&quot;, &quot;text_ru&quot;:&quot;Афганистан&quot;, &quot;virtual21&quot;:{ &quot;activation&quot;:1 }, &quot;virtual23&quot;:{ &quot;activation&quot;:1 }, &quot;virtual29&quot;:{ &quot;activation&quot;:1 }, &quot;virtual30&quot;:{ &quot;activation&quot;:1 }, &quot;virtual31&quot;:{ &quot;activation&quot;:1 }, &quot;virtual32&quot;:{ &quot;activation&quot;:1 }, &quot;virtual4&quot;:{ &quot;activation&quot;:1 } } } </code></pre> <p>This goes on for a very large list of countries</p> <p>this is how i am currently deserializing:</p> <pre><code> var response = JsonConvert.DeserializeObject&lt;Dictionary&lt;string, ResponseFields&gt;&gt;(json); </code></pre> <p>And this is the VS-generated ResponseFields class:</p> <pre><code>public class ResponseFields { public Iso iso { get; set; } public Prefix prefix { get; set; } public string text_en { get; set; } public string text_ru { get; set; } public Virtual21 virtual21 { get; set; } public Virtual23 virtual23 { get; set; } public Virtual29 virtual29 { get; set; } public Virtual30 virtual30 { get; set; } public Virtual31 virtual31 { get; set; } public Virtual32 virtual32 { get; set; } public Virtual4 virtual4 { get; set; } } public class Iso { public int af { get; set; } } public class Prefix { public int _93 { get; set; } } public class Virtual21 { public int activation { get; set; } } public class Virtual23 { public int activation { get; set; } } public class Virtual29 { public int activation { get; set; } } public class Virtual30 { public int activation { get; set; } } public class Virtual31 { public int activation { get; set; } } public class Virtual32 { public int activation { get; set; } } public class Virtual4 { public int activation { get; set; } } </code></pre> <p>Printing to console as follows:</p> <pre><code>foreach (var field in response) { Console.WriteLine($&quot;Name: {(field.Key)} \nCode: {field.Value.iso}&quot;); } </code></pre> <p>Produces:</p> <pre><code>Name: afghanistan Code: Iso Name: albania Code: Iso Name: algeria Code: Iso </code></pre> <p>vs Expected output:</p> <pre><code>Name: afghanistan Code: af Name: albania Code: al ... </code></pre> <p><a href="https://stackoverflow.com/questions/38688570/deserializing-json-with-unknown-object-names">this is the closest post on SO i could manage to pull from google</a></p>
[ { "answer_id": 74468565, "author": "Babak Naffas", "author_id": 120753, "author_profile": "https://Stackoverflow.com/users/120753", "pm_score": 1, "selected": false, "text": "iso" }, { "answer_id": 74468773, "author": "Guru Stron", "author_id": 2501279, "author_profile": "https://Stackoverflow.com/users/2501279", "pm_score": 1, "selected": false, "text": "Dictionary<string, int>" }, { "answer_id": 74469217, "author": "NineBerry", "author_id": 101087, "author_profile": "https://Stackoverflow.com/users/101087", "pm_score": 1, "selected": false, "text": "string input = @\"\n {\n \"\"afghanistan\"\":{\n \"\"iso\"\":{\n \"\"af\"\":1\n },\n \"\"prefix\"\":{\n \"\"+93\"\":1\n },\n \"\"text_en\"\":\"\"Afghanistan\"\",\n \"\"text_ru\"\":\"\"Афганистан\"\",\n \"\"virtual21\"\":{\n \"\"activation\"\":1\n },\n \"\"virtual23\"\":{\n \"\"activation\"\":1\n },\n \"\"virtual29\"\":{\n \"\"activation\"\":1\n },\n \"\"virtual30\"\":{\n \"\"activation\"\":1\n },\n \"\"virtual31\"\":{\n \"\"activation\"\":1\n },\n \"\"virtual32\"\":{\n \"\"activation\"\":1\n },\n \"\"virtual4\"\":{\n \"\"activation\"\":1\n }\n },\n \"\"albania\"\":{\n \"\"iso\"\":{\n \"\"al\"\":1\n },\n \"\"prefix\"\":{\n \"\"+98\"\":1\n },\n \"\"text_en\"\":\"\"Albania\"\",\n \"\"virtual21\"\":{\n \"\"activation\"\":1\n },\n \"\"virtual23\"\":{\n \"\"activation\"\":1\n },\n \"\"virtual29\"\":{\n \"\"activation\"\":1\n },\n \"\"virtual30\"\":{\n \"\"activation\"\":1\n },\n \"\"virtual31\"\":{\n \"\"activation\"\":1\n },\n \"\"virtual32\"\":{\n \"\"activation\"\":1\n },\n \"\"virtual4\"\":{\n \"\"activation\"\":1\n }\n }\n }\n\";\n\nJObject o = JObject.Parse(input);\n\n// Foreach property of the root\nforeach(JProperty country in o.Children())\n{\n // Country name is name of the property\n string countryName = country.Name;\n\n // Get ISO Node below the country node\n JToken? iso = country.SelectToken(\"$..iso\");\n\n // Get First property within iso Node\n JProperty? code = iso?.Value<JObject>()?.Properties().First();\n\n // Get Name of property\n string isoCode = code?.Name ?? \"\";\n\n Console.WriteLine($\"Name: {countryName} \\nCode: {isoCode}\");\n}\n" }, { "answer_id": 74469600, "author": "Serge", "author_id": 11392290, "author_profile": "https://Stackoverflow.com/users/11392290", "pm_score": 3, "selected": true, "text": "var countries = JObject.Parse(json).Properties()\n .Select(jo => new\n {\n name = jo.Name,\n code = ((JObject)jo.Value[\"iso\"]).Properties().First().Name\n }).ToList();\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20524613/" ]
74,468,404
<p>Here is the code:</p> <pre><code>string[] wordsX ={&quot;word1&quot;, &quot;word2&quot;,&quot;word3&quot;} </code></pre> <p>with foreach loop want to get the item value and pass to a label</p> <pre><code>foreach (string w in wordsX) { Label1.Text = w[1].ToString(); Label2.Text = w[2].ToString(); } </code></pre> <p>It gives an error: Index was outside the bounds of the array.</p>
[ { "answer_id": 74468565, "author": "Babak Naffas", "author_id": 120753, "author_profile": "https://Stackoverflow.com/users/120753", "pm_score": 1, "selected": false, "text": "iso" }, { "answer_id": 74468773, "author": "Guru Stron", "author_id": 2501279, "author_profile": "https://Stackoverflow.com/users/2501279", "pm_score": 1, "selected": false, "text": "Dictionary<string, int>" }, { "answer_id": 74469217, "author": "NineBerry", "author_id": 101087, "author_profile": "https://Stackoverflow.com/users/101087", "pm_score": 1, "selected": false, "text": "string input = @\"\n {\n \"\"afghanistan\"\":{\n \"\"iso\"\":{\n \"\"af\"\":1\n },\n \"\"prefix\"\":{\n \"\"+93\"\":1\n },\n \"\"text_en\"\":\"\"Afghanistan\"\",\n \"\"text_ru\"\":\"\"Афганистан\"\",\n \"\"virtual21\"\":{\n \"\"activation\"\":1\n },\n \"\"virtual23\"\":{\n \"\"activation\"\":1\n },\n \"\"virtual29\"\":{\n \"\"activation\"\":1\n },\n \"\"virtual30\"\":{\n \"\"activation\"\":1\n },\n \"\"virtual31\"\":{\n \"\"activation\"\":1\n },\n \"\"virtual32\"\":{\n \"\"activation\"\":1\n },\n \"\"virtual4\"\":{\n \"\"activation\"\":1\n }\n },\n \"\"albania\"\":{\n \"\"iso\"\":{\n \"\"al\"\":1\n },\n \"\"prefix\"\":{\n \"\"+98\"\":1\n },\n \"\"text_en\"\":\"\"Albania\"\",\n \"\"virtual21\"\":{\n \"\"activation\"\":1\n },\n \"\"virtual23\"\":{\n \"\"activation\"\":1\n },\n \"\"virtual29\"\":{\n \"\"activation\"\":1\n },\n \"\"virtual30\"\":{\n \"\"activation\"\":1\n },\n \"\"virtual31\"\":{\n \"\"activation\"\":1\n },\n \"\"virtual32\"\":{\n \"\"activation\"\":1\n },\n \"\"virtual4\"\":{\n \"\"activation\"\":1\n }\n }\n }\n\";\n\nJObject o = JObject.Parse(input);\n\n// Foreach property of the root\nforeach(JProperty country in o.Children())\n{\n // Country name is name of the property\n string countryName = country.Name;\n\n // Get ISO Node below the country node\n JToken? iso = country.SelectToken(\"$..iso\");\n\n // Get First property within iso Node\n JProperty? code = iso?.Value<JObject>()?.Properties().First();\n\n // Get Name of property\n string isoCode = code?.Name ?? \"\";\n\n Console.WriteLine($\"Name: {countryName} \\nCode: {isoCode}\");\n}\n" }, { "answer_id": 74469600, "author": "Serge", "author_id": 11392290, "author_profile": "https://Stackoverflow.com/users/11392290", "pm_score": 3, "selected": true, "text": "var countries = JObject.Parse(json).Properties()\n .Select(jo => new\n {\n name = jo.Name,\n code = ((JObject)jo.Value[\"iso\"]).Properties().First().Name\n }).ToList();\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20465780/" ]
74,468,433
<p>I have the following code to get users from a group:</p> <pre><code>var response = await graphClient .Groups[groupId] .TransitiveMembers .Request() .Top(999) .GetAsync(); </code></pre> <p>How do I update the code to get the request id from the response?</p> <p>UPDATE:</p> <p>What about from this api call:</p> <pre><code>var response = await graphClient .Groups .Delta() .Request() .Select(&quot;members&quot;) .Filter($&quot;id eq '{groupId}'&quot;) .GetAsync(); </code></pre>
[ { "answer_id": 74468697, "author": "vicky kumar", "author_id": 18106676, "author_profile": "https://Stackoverflow.com/users/18106676", "pm_score": -1, "selected": false, "text": "" }, { "answer_id": 74477437, "author": "user2250152", "author_id": 2250152, "author_profile": "https://Stackoverflow.com/users/2250152", "pm_score": 2, "selected": true, "text": "request-id" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3693060/" ]
74,468,434
<pre><code>String abc = &quot;ABC\n\rDEF\rGHI\nJKL\n\rMNO\r\tPQR\t&quot;; String cde = abc.replaceAll(&quot;[^\n]\r[^\t]&quot;, &quot;\n\r&quot;); System.out.println(cde); </code></pre> <p>The \r should be not be surrounded by \n or \t. For instance, I do not want to replace \n\r to \n\n\r.</p> <p>Expected: &quot;ABC\n\rDEF\n\rGHI\nJKL\n\rMNO\r\tPQR\t&quot; <br> Actual: &quot;ABC\n\rDE\n\rHI\nJKL\n\rMNO\r\tPQR\t&quot;</p>
[ { "answer_id": 74468697, "author": "vicky kumar", "author_id": 18106676, "author_profile": "https://Stackoverflow.com/users/18106676", "pm_score": -1, "selected": false, "text": "" }, { "answer_id": 74477437, "author": "user2250152", "author_id": 2250152, "author_profile": "https://Stackoverflow.com/users/2250152", "pm_score": 2, "selected": true, "text": "request-id" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20524726/" ]
74,468,435
<p>I apologize if the redaction of my problem is not good.</p> <p>Code I'm running:</p> <pre><code>x=int(input(&quot;Escribe cantidad de artículos deseas comprar: &quot;)) suma=0 seleccion=0 precio=0 while x&gt;0: seleccion=(input(&quot;Dame el nombre de un artículo que deseas comprar: &quot;)) precio=int(input(&quot;Dame el precio de dicho artículo: &quot;)) z=precio x=x-1 if seleccion==1: suma = z + z if seleccion &gt; 1: print (&quot;Listo. Haz anotado todos los artículos que deseas comprar&quot;) print (&quot;El pago total que tienes que hacer es: &quot;, suma) </code></pre> <p>Result of code:</p> <blockquote> <pre><code> Escribe cantidad de artículos deseas comprar: 2 Dame el nombre de un artículo que deseas comprar: camisa Dame el precio de dicho artículo: 12 Dame el nombre de un artículo que deseas comprar: short Dame el precio de dicho artículo: 33 El pago total que tienes que hacer es: 0 </code></pre> </blockquote> <p>*That last 0, I want it to be (12+33) 45. How can I accomplish this?</p> <p>I tried writing the sum of price (precio) plus price, but it just gives me the last price times two.</p>
[ { "answer_id": 74468697, "author": "vicky kumar", "author_id": 18106676, "author_profile": "https://Stackoverflow.com/users/18106676", "pm_score": -1, "selected": false, "text": "" }, { "answer_id": 74477437, "author": "user2250152", "author_id": 2250152, "author_profile": "https://Stackoverflow.com/users/2250152", "pm_score": 2, "selected": true, "text": "request-id" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20524743/" ]
74,468,449
<p>How can I write the output of a bash script to another file based on a condition in the script? for example, I need something like this</p> <pre><code>writeToFile=false read -p &quot;Enter (1-4): &quot; echo &quot;foo&quot; if [ $REPLY == &quot;1&quot; ]; then echo &quot;writing to file&quot; writeToFile=true fi </code></pre> <p>if they enter 1, then it should write everything that was outputted to a file. If not, then nothing should be written to a file.</p> <p>From my research it seem like using tee is the correct way to go, but I cant figure out how to structure it. I have tried ending the file in | tee like so,</p> <pre><code>{ ... } | tee -a file.txt </code></pre> <p>but that writes everything every time. If I do</p> <pre><code>{ ... } | if [ &quot;$writeToFile&quot; = true ]; then tee -a $(date +%F).txt fi </code></pre> <p>however that does not work. What is the correct way to do this?</p>
[ { "answer_id": 74468473, "author": "Diego Torres Milano", "author_id": 236465, "author_profile": "https://Stackoverflow.com/users/236465", "pm_score": 1, "selected": false, "text": "file='/dev/null'\nif [[ \"$writeToFile\" == true ]]; then\n file='file.txt'\nfi\n\n{\n...\n} | tee -a \"$file\"\n" }, { "answer_id": 74468503, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 3, "selected": true, "text": "exec" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14040069/" ]
74,468,471
<p>I need help with processing an unsorted dataset. Sry, if I am a complete noob. I never did anything like that before. So as you can see, each conversation is identified by a dialogueID which consists of multiple rows of &quot;from&quot; &amp; &quot;to&quot;, as well as text messages. I would like to concatenate the text messages from the same sender of a dialogueID to one column and from the receiver to another column. This way, I could have a new csv-file with just [dialogueID, sender, receiver].</p> <p><a href="https://i.stack.imgur.com/L5JDq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L5JDq.png" alt="dataset" /></a> the new dataset should look like this <a href="https://i.stack.imgur.com/3wuNB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3wuNB.png" alt="new dataset" /></a></p> <p>I watched multiple tutorials and really struggle to figure out how to do it. I read in this <a href="https://stackoverflow.com/questions/16476924/how-to-iterate-over-rows-in-a-dataframe-in-pandas">9-year-old post</a> that iterating through data frames are not a good idea. Could someone help me out with a code snippet or give me a hint on how to properly do it without overcomplicating things? I thought something like this pseudo code below, but the performance with 1 million rows is not great, right?</p> <pre><code>while !endOfFile for dialogueID in range (0, 1038324) if dialogueID+1 == dialogueID and toValue.isnull() concatenate textFromPrevRow + &quot; &quot; + textFromCurrentRow add new string to table column sender else add text to column receiver </code></pre>
[ { "answer_id": 74468539, "author": "Nazar Nintendo", "author_id": 20524194, "author_profile": "https://Stackoverflow.com/users/20524194", "pm_score": 2, "selected": true, "text": "dialogueID" }, { "answer_id": 74468655, "author": "Yuri Feldman", "author_id": 2131957, "author_profile": "https://Stackoverflow.com/users/2131957", "pm_score": 0, "selected": false, "text": "DataFrame.apply" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8789802/" ]
74,468,493
<p>Getting this error on mobile safari:</p> <pre class="lang-js prettyprint-override"><code>Fetch API cannot load https://firestore.googleapis.com/google.firestore.v1.Firestore/Write/channel?gsessionid=&amp;database=&amp;RID=&amp;AID&amp;TYPE=xmlhttp&amp;zx=&amp;t=1 due to access control checks. </code></pre> <p>(I stripped out some of the param values)</p> <p>The app is working though, and the domain is whitelisted in the firestore settings. But I want to resolve this error anyway.</p> <p>It's not a security rules issue, because those throw specific errors. I opened all the documents anyway to check, but this error persisted:</p> <pre class="lang-js prettyprint-override"><code>rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /{document=**} { // This does not fix the issue allow read, write: if true; } } } </code></pre> <p>Search results for this error generally refer to <code>cors</code> issues, but doesn't make sense for this case. Any ideas appreciated...</p> <p><code>&quot;firebase&quot;: &quot;^9.10.0&quot;</code></p>
[ { "answer_id": 74468539, "author": "Nazar Nintendo", "author_id": 20524194, "author_profile": "https://Stackoverflow.com/users/20524194", "pm_score": 2, "selected": true, "text": "dialogueID" }, { "answer_id": 74468655, "author": "Yuri Feldman", "author_id": 2131957, "author_profile": "https://Stackoverflow.com/users/2131957", "pm_score": 0, "selected": false, "text": "DataFrame.apply" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9573055/" ]
74,468,500
<p>I am having a little trouble with the logic of this sql, I don't know why it's given me an error but the error is at line 4 &quot;the start of the first AND&quot;. What I am trying to do is to check if the given start and end time are valid to book a room. I wanna show the user all the bookings that will overlap with the period he wanna book the room in.</p> <pre><code>select * from `bookings` where ( `room_id` = 4 and (`starting_time` &lt; 2022-11-16 23:07:55 and `ending_time` &gt; 2022-11-16 23:07:55 and `starting_time` &lt; 2022-11-17 00:07:55 and `ending_time` &gt; 2022-11-17 00:07:55) or (`starting_time` &lt; 2022-11-16 23:07:55 and `ending_time` &gt; 2022-11-16 23:07:55 and `starting_time` &lt; 2022-11-17 00:07:55 and `ending_time` &lt; 2022-11-17 00:07:55) or ( `starting_time` &gt; 2022-11-16 23:07:55 and `ending_time` &gt; 2022-11-16 23:07:55 and `starting_time` &lt; 2022-11-17 00:07:55 and `ending_time` &gt; 2022-11-17 00:07:55) ) </code></pre> <pre><code> $bookings = Booking::where('room_id', $room_id) -&gt;Where(function ($query) use ($times) { $query-&gt;where('starting_time', '&lt;', $times[0]) -&gt;where('ending_time', '&gt;', $times[0]) -&gt;where('starting_time', '&lt;', $times[1]) -&gt;where('ending_time', '&gt;', $times[1]); }) -&gt;orWhere(function ($query) use ($times) { $query-&gt;where('starting_time', '&lt;', $times[0]) -&gt;where('ending_time', '&gt;', $times[0]) -&gt;where('starting_time', '&lt;', $times[1]) -&gt;where('ending_time', '&lt;', $times[1]); }) -&gt;orWhere(function ($query) use ($times) { $query-&gt;where('starting_time', '&gt;', $times[0]) -&gt;where('ending_time', '&gt;', $times[0]) -&gt;where('starting_time', '&lt;', $times[1]) -&gt;where('ending_time', '&gt;', $times[1]); }) -&gt;get(); </code></pre> <pre><code> Schema::create('bookings', function (Blueprint $table) { $table-&gt;bigIncrements('id'); $table-&gt;datetime('starting_time'); $table-&gt;datetime('ending_time')-&gt;nullable(); $table-&gt;string('guest_name')-&gt;nullable(); $table-&gt;string('guest_phone')-&gt;nullable(); $table-&gt;longText('comments')-&gt;nullable(); $table-&gt;timestamps(); $table-&gt;softDeletes(); }); Schema::table('bookings', function (Blueprint $table) { $table-&gt;unsignedBigInteger('room_id')-&gt;nullable(); $table-&gt;foreign('room_id', 'room_fk_7600582')-&gt;references('id')-&gt;on('rooms'); $table-&gt;unsignedBigInteger('team_id')-&gt;nullable(); $table-&gt;foreign('team_id', 'team_fk_7547221')-&gt;references('id')-&gt;on('teams'); }); </code></pre>
[ { "answer_id": 74468797, "author": "N69S", "author_id": 4369919, "author_profile": "https://Stackoverflow.com/users/4369919", "pm_score": 2, "selected": true, "text": "$time[0]" }, { "answer_id": 74469345, "author": "nnichols", "author_id": 1191247, "author_profile": "https://Stackoverflow.com/users/1191247", "pm_score": 0, "selected": false, "text": "$startingTime = $times[0];\n$endingTime = $times[1];\n$bookings = Booking::where('room_id', $room_id)\n ->where(function ($query) use ($startingTime, $endingTime) {\n $query->where(function ($query) use ($startingTime, $endingTime) {\n $query->where('starting_time', '>=', $startingTime)\n ->where('ending_time', '<=', $endingTime);\n })\n ->orWhere(function ($query) use ($startingTime) {\n $query->where('starting_time', '<=', $startingTime)\n ->where('ending_time', '>', $startingTime);\n })\n ->orWhere(function ($query) use ($endingTime) {\n $query->where('starting_time', '<', $endingTime)\n ->where('ending_time', '>=', $endingTime);\n })\n })\n ->get();\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20477829/" ]
74,468,510
<p>Idk if what I said makes sense, if not, here's an example of what I mean:</p> <p>I created a method which performs &quot;scalar-matrix&quot; multiplication, aka every element of a 2d array gets multiplied by a scalar (by a decimal). Now, it doesn't matter if you do array * decimal or decimal * array, either way you should get the same answer. So far this is what I have:</p> <pre><code>public static double[,] ScalarMatrixMult(double[,] A, double n) { for (int i = 0; i &lt; A.GetLength(0); i++) { for (int j = 0; j &lt; A.GetLength(1); j++) { A[i, j] = A[i, j] * n ; } } return A; } public static double[,] ScalarMatrixMult2(double n, double[,] A) { for (int i = 0; i &lt; A.GetLength(0); i++) { for (int j = 0; j &lt; A.GetLength(1); j++) { A[i, j] = A[i, j] * n; } } return A; } </code></pre> <p>I have 2 different methods for doing the exact same thing... Because they care about the location of the parameters.</p> <p>Can I somehow capture that idea of &quot;not caring about the location of parameters&quot; in 1 method? Or maybe I can use one of them inside the other? I really want to avoid having to use 2 different names for essentially the same thing (and copy-pasting code snippets).</p>
[ { "answer_id": 74468612, "author": "Idle_Mind", "author_id": 2330053, "author_profile": "https://Stackoverflow.com/users/2330053", "pm_score": 3, "selected": true, "text": "public static double[,] ScalarMatrixMult(double n, double[,] A)\n{\n return ScalarMatrixMult(A, n);\n}\n \npublic static double[,] ScalarMatrixMult(double[,] A, double n)\n{\n for (int i = 0; i < A.GetLength(0); i++)\n {\n for (int j = 0; j < A.GetLength(1); j++)\n {\n A[i, j] = A[i, j] * n ;\n }\n }\n\n return A;\n}\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15323416/" ]
74,468,520
<p>I'm in the process of using Google Sheets to make a Secret Santa Generator, but have come across a problem that I can't seem to get around. How do you ensure that people aren't given a giftee that is part of the same family group?</p> <p>Currently I have a working system that looks at the first names of people and checks to see whether someone has been allocated themselves. But can this be done by taking into account first and last names to ensure that someone from the same family isn't given their partner?</p> <p>Currently my formulas are as below;</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>A</th> <th>B</th> <th>C</th> <th>D</th> <th>E</th> <th>F</th> </tr> </thead> <tbody> <tr> <td><strong>1</strong></td> <td></td> <td><strong>Person</strong></td> <td><strong>Rand No.</strong></td> <td><strong>Rank</strong></td> <td><strong>Giftee</strong></td> <td><strong>Run Again?</strong></td> </tr> <tr> <td><strong>2</strong></td> <td>1</td> <td>Louise H.</td> <td><em>=RAND()</em></td> <td><em>=RANK(C2,C2:C5)</em></td> <td><em>=VLOOKUP(D2,A2:B5,2,0)</em></td> <td><em>=IF(B2=E2,&quot;Error - Run Again&quot;,&quot;&quot;)</em></td> </tr> <tr> <td><strong>3</strong></td> <td>2</td> <td>Matt H.</td> <td><em>=RAND()</em></td> <td><em>=RANK(C3,C3:C5)</em></td> <td><em>=VLOOKUP(D3,A2:B5,2,0)</em></td> <td><em>=IF(B3=E3,&quot;Error - Run Again&quot;,&quot;&quot;)</em></td> </tr> <tr> <td><strong>4</strong></td> <td>3</td> <td>Matt C.</td> <td><em>=RAND()</em></td> <td><em>=RANK(C4,C3:C5)</em></td> <td><em>=VLOOKUP(D4,A2:B5,2,0)</em></td> <td><em>=IF(B4=E4,&quot;Error - Run Again&quot;,&quot;&quot;)</em></td> </tr> <tr> <td><strong>5</strong></td> <td>4</td> <td>Liz C.</td> <td><em>=RAND()</em></td> <td><em>=RANK(C5,C3:C5)</em></td> <td><em>=VLOOKUP(D5,A2:B5,2,0)</em></td> <td><em>=IF(B5=E5,&quot;Error - Run Again&quot;,&quot;&quot;)</em></td> </tr> <tr> <td><strong>6</strong></td> <td>5</td> <td>Barbara D.</td> <td><em>=RAND()</em></td> <td><em>=RANK(C6,C3:C5)</em></td> <td><em>=VLOOKUP(D6,A2:B5,2,0)</em></td> <td><em>=IF(B6=E6,&quot;Error - Run Again&quot;,&quot;&quot;)</em></td> </tr> <tr> <td><strong>7</strong></td> <td>6</td> <td>Barbara D.</td> <td><em>=RAND()</em></td> <td><em>=RANK(C7,C3:C5)</em></td> <td><em>=VLOOKUP(D7,A2:B5,2,0)</em></td> <td><em>=IF(B7=E7,&quot;Error - Run Again&quot;,&quot;&quot;)</em></td> </tr> </tbody> </table> </div> <p>And so on and so on for as many other people as required.</p> <p>Anyone have some ideas to take the family situation into account?</p>
[ { "answer_id": 74468716, "author": "Martín", "author_id": 20363318, "author_profile": "https://Stackoverflow.com/users/20363318", "pm_score": 0, "selected": false, "text": "=byrow(B2:B,lambda(each,if(each=\"\",\"\",if(REGEXEXTRACT(each,\"\\s+[^\\s]+\")=REGEXEXTRACT(offset(each,0,3),\"\\s+[^\\s]+\"),\"Same family - Run again\",\"\"))))\n" }, { "answer_id": 74468903, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 1, "selected": false, "text": "=INDEX(LAMBDA(x, SINGLE(QUERY(SORT({x, REGEXEXTRACT(x, \"\\b\\w+\\b$\")}, \n RANDARRAY(ROWS(x)), ), \"select Col1 where not Col2 ends with '\"&\n REGEXEXTRACT(A2, \"\\b\\w+\\b$\")&\"'\"&IF(ROW()=2,,\" and not Col1 matches '\"&\n TEXTJOIN(\"|\", 1, C1:C$2)&\"'\"), )))(A$2:INDEX(A:A, MAX(ROW(A:A)*(A:A<>\"\")))))\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12147587/" ]
74,468,560
<p>We are trying to use asyncio to run a straightforward client/server. The server is an echo server with two possible commands sent by the client, <em>&quot;quit&quot;</em> and <em><strong>&quot;timer&quot;</strong></em>. The <strong>timer</strong> command starts a timer that will print a message in the console every second (at the server and client), and the <em>quit</em> command closes the connection.</p> <p>The actual problem is the following:</p> <p>When we run the server and the client, and we start the timer, the result of the <em>timer</em> is not sent to the client. It blocks the server and the client. I believe that the problem is on the client's side. However, I was not able to detect it.</p> <h2>Server</h2> <pre><code>import asyncio import time HOST = &quot;127.0.0.1&quot; PORT = 9999 class Timer(object): '''Simple timer class that can be started and stopped.''' def __init__(self, writer: asyncio.StreamWriter, name = None, interval = 1) -&gt; None: self.name = name self.interval = interval self.writer = writer async def _tick(self) -&gt; None: while True: await asyncio.sleep(self.interval) delta = time.time() - self._init_time self.writer.write(f&quot;Timer {delta} ticked\n&quot;.encode()) self.writer.drain() print(&quot;Delta time: &quot;, delta) async def start(self) -&gt; None: self._init_time = time.time() self.task = asyncio.create_task(self._tick()) async def stop(self) -&gt; None: self.task.cancel() print(&quot;Delta time: &quot;, time.time() - self._init_time) async def msg_handler(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -&gt; None: '''Handle the echo protocol.''' # timer task that the client can start: timer_task = False try: while True: data = await reader.read(1024) # Read 256 bytes from the reader. Size of the message msg = data.decode() # Decode the message addr, port = writer.get_extra_info(&quot;peername&quot;) # Get the address of the client print(f&quot;Received {msg!r} from {addr}:{port!r}&quot;) send_message = &quot;Message received: &quot; + msg writer.write(send_message.encode()) # Echo the data back to the client await writer.drain() # This will wait until everything is clear to move to the next thing. if data == b&quot;quit&quot; and timer_task is True: # cancel the timer_task (if any) if timer_task: timer_task.cancel() await timer_task writer.close() # Close the connection await writer.wait_closed() # Wait for the connection to close elif data == b&quot;quit&quot; and timer_task is False: writer.close() # Close the connection await writer.wait_closed() # Wait for the connection to close elif data == b&quot;start&quot; and timer_task is False: print(&quot;Starting timer&quot;) t = Timer(writer) timer_task = True await t.start() elif data == b&quot;stop&quot; and timer_task is True: print(&quot;Stopping timer&quot;) await t.stop() timer_task = False except ConnectionResetError: print(&quot;Client disconnected&quot;) async def run_server() -&gt; None: # Our awaitable callable. # This callable is ran when the server recieves some data server = await asyncio.start_server(msg_handler, HOST, PORT) async with server: await server.serve_forever() if __name__ == &quot;__main__&quot;: loop = asyncio.new_event_loop() # new_event_loop() is for python 3.10. For older versions, use get_event_loop() loop.run_until_complete(run_server()) </code></pre> <h2>Client</h2> <pre><code>import asyncio HOST = '127.0.0.1' PORT = 9999 async def run_client() -&gt; None: # It's a coroutine. It will wait until the connection is established reader, writer = await asyncio.open_connection(HOST, PORT) while True: message = input('Enter a message: ') writer.write(message.encode()) await writer.drain() data = await reader.read(1024) if not data: raise Exception('Socket not communicating with the client') print(f&quot;Received {data.decode()!r}&quot;) if (message == 'quit'): writer.write(b&quot;quit&quot;) writer.close() await writer.wait_closed() exit(2) # break # Don't know if this is necessary if __name__ == '__main__': loop = asyncio.new_event_loop() loop.run_until_complete(run_client()) </code></pre>
[ { "answer_id": 74482040, "author": "nunodsousa", "author_id": 3152047, "author_profile": "https://Stackoverflow.com/users/3152047", "pm_score": 0, "selected": false, "text": "import asyncio\nimport websockets\nimport time\n\nclass Timer(object):\n '''Simple timer class that can be started and stopped.'''\n\n def __init__(self, websocket, name=None, interval=1) -> None:\n self.websocket = websocket\n self.name = name\n self.interval = interval\n\n async def _tick(self) -> None:\n while True:\n await asyncio.sleep(self.interval)\n await self.websocket.send(\"tick\")\n print(\"Delta time: \", time.time() - self._init_time)\n\n async def start(self) -> None:\n self._init_time = time.time()\n self.task = asyncio.create_task(self._tick())\n\n async def stop(self) -> None:\n self.task.cancel()\n print(\"Delta time: \", time.time() - self._init_time)\n\nasync def handler(websocket):\n print(\"[WS-SERVER] client connected\")\n while True:\n try:\n msg = await websocket.recv()\n print(f\"<: {msg}\")\n await websocket.send(\"Message received. {}\".format(msg))\n if(msg == \"start\"):\n timer = Timer(websocket)\n await timer.start()\n\n except websockets.ConnectionClosed:\n print(\"[WS-SERVER] client disconnected\")\n break\n\nasync def main():\n async with websockets.serve(handler, \"localhost\", 8765):\n print(\"[WS-SERVER] ready\")\n await asyncio.Future() # run forever\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n" }, { "answer_id": 74489875, "author": "nunodsousa", "author_id": 3152047, "author_profile": "https://Stackoverflow.com/users/3152047", "pm_score": 2, "selected": true, "text": "import asyncio\nimport websockets\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nasync def send_msg(websocket):\n while True:\n imp = await asyncio.get_event_loop().run_in_executor(None, lambda: input(\"Enter something: \"))\n print(\"MESSAGE: \", imp)\n await websocket.send(imp)\n #return imp\n\nasync def recv_msg(websocket):\n while True:\n msg = await websocket.recv()\n print(f\":> {msg}\")\n\n\nasync def echo_loop():\n uri = f\"ws://localhost:8765\"\n async with websockets.connect(uri, ssl=None) as websocket:\n while True:\n await asyncio.gather(recv_msg(websocket),send_msg(websocket))\n\n\nif __name__ == \"__main__\":\n asyncio.get_event_loop().run_until_complete(echo_loop())\n asyncio.get_event_loop().run_forever()\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3152047/" ]
74,468,594
<p>i use the following regex to extract values that appear before certain units:</p> <pre><code>([.\d]+)\s*(?:kg|gr|g) </code></pre> <p>What i want, is to include the unit of that specific value for example from this string :</p> <pre><code>&quot;some text 5kg another text 3 g more text 11.5gr end&quot; </code></pre> <p>i should be getting :</p> <pre><code>[&quot;5kg&quot;, &quot;3 g&quot;, &quot;11.5gr&quot;] </code></pre> <p>can't wrap my head on how to modify the above expression to get the wanted result. Thank you.</p>
[ { "answer_id": 74468635, "author": "Ricardo", "author_id": 16353662, "author_profile": "https://Stackoverflow.com/users/16353662", "pm_score": 3, "selected": true, "text": "import re\n\np = re.compile('(?<!\\d|\\.)\\d+(?:\\.\\d+)?\\s*?(?:gr|kg|g)(?!\\w)')\nprint(p.findall(\"some text 5kg another text 3 g more text 11.5gr end\"))\n" }, { "answer_id": 74468665, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 1, "selected": false, "text": "(?i)\\b\\d+\\.?\\d*\\s*(?:kg|gr?)\\b\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4028670/" ]
74,468,611
<p>I am currently attempting to extend test coverage for a school-based-assignment web application after I came across a completely empty class that extends Exception and contains no coverage according to the coverage report.</p> <p>Normally, I would assume that something like this could be disregarded. However, our overall test coverage factor directly into our individual grading for this course. Because of this and it being near the end of the semester, I am trying to go through the code flagged within the coverage report line-by-line and tidy up anything I can.</p> <p>After going through course content and searches online, I am unsure of how to proceed with writing a test for a class such as this. This server-side class was included in our initial code base that was given to us at the start of the semester by the instructor (we build onto the code base as the semester progresses).</p> <p>The entire code for the Java class:</p> <pre><code>package &lt;package_name&gt;; /* * This is a custom exception that fits our personal * needs and won't collide with existing issues. */ public class BadRequestException extends Exception {} </code></pre> <p>One example of how the class is used (still code that was provided by instructor):</p> <pre><code>private String processHttpRequest(spark.Request httpRequest, spark.Response httpResponse, Type requestType) { setupResponse(httpResponse); String jsonString = httpRequest.body(); try { JSONValidator.validate(jsonString, requestType); Request requestObj = new Gson().fromJson(jsonString, requestType); return buildJSONResponse(requestObj); } catch (IOException | BadRequestException e) { // &lt;---- Here log.info(&quot;Bad Request - {}&quot;, e.getMessage()); // &lt;---- httpResponse.status(HTTP_BAD_REQUEST); } catch (Exception e) { log.info(&quot;Server Error - &quot;, e); httpResponse.status(HTTP_SERVER_ERROR); } return jsonString; } </code></pre> <p>What I have so far (practically nothing):</p> <pre><code>package &lt;package_name&gt;; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.DisplayName; public class TestBadRequestException { @Test @DisplayName(&quot;Test Empty BadRequestException Class&quot;) public void testBadRequestException() { } } </code></pre> <p>Prior to the start of the semester, I had no experience with JUnit. So, any feedback/references/recommendations are greatly appreciated.</p> <h3><strong>EDIT (Solution):</strong></h3> <p>The first comment on this post provided the solution I was looking for. I had not occurred to me that it would be this simple.</p> <p>The solution is in the answer below with proper credit.</p>
[ { "answer_id": 74468940, "author": "Wry S.", "author_id": 11137318, "author_profile": "https://Stackoverflow.com/users/11137318", "pm_score": 0, "selected": false, "text": "new BadRequestException()" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11137318/" ]
74,468,624
<p>Taking into account your past answers, I've changed for the following:</p> <pre><code>n &lt;- 100 B &lt;- 20 S &lt;- 50 alpha &lt;- 0.3 beta &lt;- 1.2 theta &lt;- alpha*beta for (i in 1:S) { ### sim_original_samples &lt;- rgamma(n, alpha, beta) # for each S, we have a sample of 100 observations sim_original_samples_X_bar &lt;- mean(sim_original_samples) # for each dataset, compute the sample mean and input it sim_bs_samples_X_bar &lt;- matrix(0,B,1) # in the same loop we are going to compute the sample mean per bootstrap per original sample i #### #### for (j in 1:B) { sim_bs_samples &lt;- sample(sim_original_samples,n,replace=TRUE) # for each original sample, we are going to draw B times a bootstrap sample sim_bs_samples_X_bar[j] &lt;- mean(sim_bs_samples) # all the elements of this matrix should be the bootstrap sample mean var_sim_bs_samples &lt;- matrix(0,B,1) var_sim_bs_samples[j] &lt;- (sim_bs_samples_X_bar[j] - sim_original_samples_X_bar)^2 se_sim_bs_samples &lt;- sqrt((1/B*sum(var_sim_bs_samples))) } #### #### # now we want to compute the asymptotic CI of i) z &lt;- 1.96 var_gamma &lt;- alpha*beta^2/n CI_sim_asy_norm &lt;- matrix(ncol = 3, nrow = S) # create a vector for the CI names &lt;- c(&quot;Lower bound&quot;, &quot;Upper bound&quot;, &quot;teta covered&quot;) colnames(CI_sim_asy_norm) &lt;- names # CI_sim_asy_norm[i,1] &lt;- theta - z*sqrt(var_gamma) CI_sim_asy_norm[i,2] &lt;- theta + z*sqrt(var_gamma) CI_sim_asy_norm[i,3] &lt;- theta &gt;= CI_sim_asy_norm[i,1] &amp; theta &lt;= CI_sim_asy_norm[i,2] # check whether the true parameter of interest is covered #### #### # do the same for the asymptotic BS CI of ii) CI_sim_asy_bs &lt;- matrix(ncol = 3, nrow = S) colnames(CI_sim_asy_bs) &lt;- names CI_sim_asy_bs[i,1] &lt;- sim_original_samples_X_bar - z*se_sim_bs_samples CI_sim_asy_bs[i,2] &lt;- sim_original_samples_X_bar + z*se_sim_bs_samples CI_sim_asy_bs[i,3] &lt;- theta &gt;= CI_sim_asy_bs[i,1] &amp; theta &lt;= CI_sim_asy_bs[i,2] #### #### # do the same for the percentile BS CI of iii) assuming B = 1000 for simplicity sim_bs_samples_X_bar_sorted &lt;- sort(sim_bs_samples_X_bar, decreasing=FALSE) CI_sim_percentile &lt;- matrix(ncol = 3, nrow = S) colnames(CI_sim_percentile) &lt;- names CI_sim_percentile[i,1] &lt;- sim_bs_samples_X_bar_sorted[1000*(0.05/2)] CI_sim_percentile[i,2] &lt;- sim_bs_samples_X_bar_sorted[1000*((1-0.05)/2)] CI_sim_percentile[i,3] &lt;- theta &gt;= CI_sim_percentile[i,1] &amp; theta &lt;= CI_sim_percentile[i,2] #### } </code></pre> <p>The issue I have now, is that only the last row of the CI is filled (when filled) whereas it should be filled for all rows. Where is the issue ? I cannot see it.</p> <p>That is, for each original sample i, I draw B bootstrap samples. For each, original sample i, I want to construct confidence intervals. For each confidence intervals I want to know whether the true parameter (theta) has been contained in each of the CI.</p> <p>Hence, I'd have 50 confidence intervals. For the bootstrap one it is based on the estimates of the 20 simulations (per original sample).</p> <p>Many thanks</p>
[ { "answer_id": 74468940, "author": "Wry S.", "author_id": 11137318, "author_profile": "https://Stackoverflow.com/users/11137318", "pm_score": 0, "selected": false, "text": "new BadRequestException()" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16161960/" ]
74,468,644
<p>I'm trying to solve a practice problem in JS and the idea of it is to use some methods and to make it the most efficient way as possible.</p> <p><strong>The problem:</strong></p> <p>I have to find how many times I can form the word <em>DOGGY</em> inside a given string of uppercase letters.</p> <p>For examples:</p> <ul> <li>Inside the string 'DHTHTOMMGGSDY' I can form the word <em>DOGGY</em> only 1 time.</li> <li>Inside the string 'DXOXGGYDXOXGGY' I can form the word <em>DOGGY</em> 2 times.</li> <li>Inside the string 'DXOXGXY' I can form the word <em>DOGGY</em> 0 times.</li> </ul> <p>Is there a method I can use to solve it?</p> <p>I was trying to parse the string to an array with spread operator <code>[...string]</code> and then using the method <code>filter()</code> to return a variable with the filtered words but had problems with the 'G's becouse they have to repeat.</p> <p><strong>This is where I've got so far:</strong></p> <pre><code>let result = [...string].filter((char) =&gt; { let word = char !== 'D' &amp;&amp; char !== 'O' &amp;&amp; char !== 'G' &amp;&amp; char !== 'G' &amp;&amp; char !== 'Y'; console.log(word); }); console.log(result); </code></pre>
[ { "answer_id": 74468743, "author": "172d042d", "author_id": 4566840, "author_profile": "https://Stackoverflow.com/users/4566840", "pm_score": 1, "selected": false, "text": " function findPhrase(input, searchedPhrase) {\n const inputWithSearchedPhraseLettersOnly = [...input].filter(letter => searchedPhrase.includes(letter)).join('');\n \n return inputWithSearchedPhraseLettersOnly;\n }\n (() => {\n const input = 'DXOXGGYDXOXGGYXXXDOXXGXXXGYX';\n const searchedPhrase = 'DOGGY';\n const result = findPhrase(input, searchedPhrase).split(searchedPhrase).length - 1;\n console.log(result);\n })();" }, { "answer_id": 74468917, "author": "yaskier_one", "author_id": 15279748, "author_profile": "https://Stackoverflow.com/users/15279748", "pm_score": 2, "selected": false, "text": "let dog = \"DXOXGGYDXOXGGY\";\ndog = dog.split(\"X\").join('');\nconst dogs = dog.match(/DOGGY/g).length;\n\nconsole.log(dogs)" }, { "answer_id": 74469330, "author": "user3425506", "author_id": 3425506, "author_profile": "https://Stackoverflow.com/users/3425506", "pm_score": 2, "selected": true, "text": " const searchString = \"DOGGY\";\n const targetStrings = [\n \"DHTHTOMMGGSDY\",\n \"DXOXGGYDXOXGGY\",\n \"DXOXGXY\"\n ];\n const searchArray = searchString.split(\"\");\n\n console.log(\"searchString\", searchString);\n console.log(\"****************************\");\n\n targetStrings.forEach(function (targetString) {\n const targetArray = targetString.split(\"\");\n console.log(\"targetString\", targetString);\n let occurrences = 0;\n while (true) {\n let allCharsFound = searchArray.every(function (char) {\n const index = targetArray.indexOf(char);\n if (index === -1) {\n return false;\n }\n targetArray.splice(index, 1);\n return true;\n });\n if (allCharsFound) {\n occurrences++;\n } else {\n break;\n }\n }\n \n console.log(\"occurrences\", occurrences);\n console.log(\"----------------------------\");\n\n });" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20524847/" ]
74,468,646
<p>I have a pandas dataframe in python that I want to remove rows that contain letters in a certain column. I have tried a few things, but nothing has worked.</p> <p>Input:</p> <p><code> A B C</code><br /> <code>0 9 1 a</code><br /> <code>1 8 2 b</code><br /> <code>2 7 cat c</code><br /> <code>3 6 4 d</code></p> <p>I would then remove rows that contained letters in column 'B'...</p> <p>Expected Output:</p> <p><code> A B C</code><br /> <code>0 9 1 a</code><br /> <code>1 8 2 b</code><br /> <code>3 6 4 d</code></p> <p>Update: After seeing the replies, I still haven't been able to get this to work. I'm going to just place my entire code here. Maybe I'm not understanding something...</p> <pre><code>import pandas as pd #takes file path from user and removes quotation marks if necessary sysco1file = input(&quot;Input path of FS1 file: &quot;).replace(&quot;\&quot;&quot;,&quot;&quot;) sysco2file = input(&quot;Input path of FS2 file: &quot;).replace(&quot;\&quot;&quot;,&quot;&quot;) sysco3file = input(&quot;Input path of FS3 file: &quot;).replace(&quot;\&quot;&quot;,&quot;&quot;) #tab separated files, all values string sysco_1 = pd.read_csv(sysco1file, sep='\t', dtype=str) sysco_2 = pd.read_csv(sysco2file, sep='\t', dtype=str) sysco_3 = pd.read_csv(sysco3file, sep='\t', dtype=str) #combine all rows from the 3 files into one dataframe sysco_all = pd.concat([sysco_1,sysco_2,sysco_3]) #Also dropping nulls from CompAcctNum column sysco_all.dropna(subset=['CompAcctNum'], inplace=True) #ensure all values are string sysco_all = sysco_all.astype(str) #implemented solution from stackoverflow #I also tried putting &quot;sysco_all = &quot; in front of this sysco_all.loc[~sysco_all['CompanyNumber'].str.isalpha()] #writing dataframe to new csv file sysco_all.to_csv(r&quot;C:\Users\user\Desktop\testcsvfile.csv&quot;) </code></pre> <p>I do not get an error. However, the csv still has rows with letters in this column.</p>
[ { "answer_id": 74468669, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 2, "selected": false, "text": "B" }, { "answer_id": 74468847, "author": "Naveed", "author_id": 3494754, "author_profile": "https://Stackoverflow.com/users/3494754", "pm_score": 1, "selected": false, "text": "# use isalpha to check if value is alphabetic\n# use negation to pick where value is not alphabetic\n\ndf=df.loc[~df['B'].str.isalpha()]\n\ndf\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16140906/" ]
74,468,662
<p>I've cleaned up my code a bit according to some great recommendations from the community. However I still get the error. All of my close disclosing the error message is posted below the error message. Hopefully this is correctly formatted; I greatly appreciate the help of this community.</p> <pre><code>DELETING STUDENT INFORMATION : ENTER STUDENT'S LAST NAME: blow Traceback (most recent call last): File &quot;/Users/jake./PycharmProjects/StudentRecords/StudentRecords.py&quot;, line 281, in &lt;module&gt; SMS.delete_student_information() File &quot;/Users/jake./PycharmProjects/StudentRecords/StudentRecords.py&quot;, line 70, in delete_student_information student_mobile_number.remove(student_mobile_number[LOC]) IndexError: list index out of range Process finished with exit code 1 </code></pre> <pre><code>import sys first_name = [] last_name = [] student_address = [] student_email = [] student_age = [] student_mobile_number = [] student_id = [] class student_management_system: @staticmethod def add_student_information(): print(&quot;ADDING STUDENT INFORMATION : \n&quot;) print(&quot;ENTER STUDENT FIRST NAME :&quot;, end=&quot; &quot;) NAME = input().upper() first_name.append(NAME) print(&quot;ENTER STUDENT LAST NAME :&quot;, end=&quot; &quot;) lname = str(input()) last_name.append(lname) print(&quot;ENTER STUDENT AGE :&quot;, end=&quot; &quot;) AGE = int(input()) student_age.append(AGE) print(&quot;ENTER STUDENT ID :&quot;, end=&quot; &quot;) ID = input().upper() student_id.append(ID) print(&quot;ENTER STUDENT E-MAIL ID :&quot;, end=&quot; &quot;) EMAIL_ID = input().upper() student_email.append(EMAIL_ID) print(&quot;ENTER STUDENT ADDRESS :&quot;, end=&quot; &quot;) ADDRESS = input().upper() student_address.append(ADDRESS) print(&quot;ENTER STUDENT MOBILE NUMBER :&quot;, end=&quot; &quot;) MOBILE_NUMBER = input() MOBILE_NUMBER_LEN = len(MOBILE_NUMBER) if MOBILE_NUMBER_LEN &lt; 10: print(&quot;\t PLEASE ENTER VALID TEN DIGIT MOBILE NUMBER.&quot;) else: student_mobile_number.append(MOBILE_NUMBER) print(&quot;\n&quot;) print(&quot;\t STUDENT INFORMATION ADDED SUCCESSFULLY.&quot;) print(&quot;\n&quot;) @staticmethod # THIS FUNCTION HELP TO 'DELETE' DATA OF STUDENT def delete_student_information(): print(&quot;DELETING STUDENT INFORMATION : \n&quot;) if len(first_name) == 0 and len(last_name) == 0 and len(student_age) == 0 and len( student_id) == 0 and len(student_mobile_number) == 0 and len(student_address) == 0 and len( student_email) == 0: print(&quot;\n&quot;) print(&quot;\t\t\t 'PLEASE FILL SOME INFORMATION DON'T KEEP IT EMPTY&quot;) print(&quot;\n&quot;) else: print(&quot;ENTER STUDENT'S LAST NAME:&quot;, end=&quot; &quot;) l_name = str(input()) LOC = last_name.index(l_name) last_name.remove(last_name[LOC]) first_name.remove(first_name[LOC]) student_mobile_number.remove(student_mobile_number[LOC]) student_age.remove(student_age[LOC]) student_address.remove(student_address[LOC]) student_email.remove(student_email[LOC]) student_id.remove(student_id[LOC]) print(&quot;\n&quot;) print(&quot;\t\t STUDENT INFORMATION DELETED SUCCESSFULLY.&quot;) print(&quot;\n&quot;) @staticmethod # THIS FUNCTION HELP TO 'UPDATE' DATA OF STUDENT. def update_student_information(): print(&quot;UPDATE STUDENT INFORMATION : \n&quot;) if len(first_name) == 0 and len(last_name) == 0 and len(student_age) == 0 and len( student_id) == 0 and len(student_mobile_number) == 0 and len(student_address) == 0 and len( student_email) == 0: print(&quot;\n&quot;) print(&quot;\t\t\t 'PLEASE FILL SOME INFORMATION DON'T KEEP IT EMPTY&quot;) print(&quot;\n&quot;) else: print(&quot;ENTER STUDENT ATTRIBUTE YOU WANT TO DELETE :&quot;, end=&quot;\n&quot;) print(&quot;LIKE 'NAME, ROLL NUMBER, AGE, MOBILE NUMBER, ADDRESS, EMAIL, CLASS.&quot;) print(&quot;ENTER HERE :&quot;, end=&quot; &quot;) ATTRIBUTE = input().upper() if ATTRIBUTE == 'NAME': print(&quot;ENTER 'OLD FIRST NAME' :&quot;, end=&quot; &quot;) OLD_NAME = input() LOC_NAME = first_name.index(OLD_NAME) print(&quot;ENTER 'NEW FIRST NAME' :&quot;, end=&quot; &quot;) NEW_NAME = input() first_name[LOC_NAME] = NEW_NAME print(&quot;\t 'FIRST NAME UPDATED SUCCESSFULLY.&quot;) print(&quot;\n&quot;) elif ATTRIBUTE == 'LAST NAME': print(&quot;ENTER 'OLD LAST NAME' :&quot;, end=&quot; &quot;) old_last_name = str(input()) LOC_ROLL = last_name.index(old_last_name) print(&quot;ENTER 'NEW ROLL NUMBER' :&quot;, end=&quot; &quot;) NEW_NAME = int(input()) last_name[LOC_ROLL] = NEW_NAME print(&quot;\t 'ROLL NUMBER UPDATED SUCCESSFULLY.&quot;) print(&quot;\n&quot;) elif ATTRIBUTE == 'AGE': print(&quot;ENTER 'OLD AGE' :&quot;, end=&quot; &quot;) OLD_AGE = int(input()) LOC_ROLL = student_age.index(OLD_AGE) print(&quot;ENTER 'NEW AGE' :&quot;, end=&quot; &quot;) NEW_AGE = int(input()) student_age[LOC_ROLL] = NEW_AGE print(&quot;\t 'AGE UPDATED SUCCESSFULLY.&quot;) print(&quot;\n&quot;) elif ATTRIBUTE == 'ADDRESS': print(&quot;ENTER 'OLD ADDRESS' :&quot;, end=&quot; &quot;) OLD_ADDRESS = input() LOC_ADDRESS = student_address.index(OLD_ADDRESS) print(&quot;ENTER 'NEW ADDRESS' :&quot;, end=&quot; &quot;) NEW_ADDRESS = input() student_address[LOC_ADDRESS] = NEW_ADDRESS print(&quot;\t 'ADDRESS UPDATED SUCCESSFULLY.&quot;) print(&quot;\n&quot;) elif ATTRIBUTE == 'EMAIL': print(&quot;ENTER 'OLD EMAIL' :&quot;, end=&quot; &quot;) OLD_EMAIL = input() LOC_EMAIL = student_email.index(OLD_EMAIL) print(&quot;ENTER 'NEW EMAIL' :&quot;, end=&quot; &quot;) NEW_EMAIL = input() student_email[LOC_EMAIL] = NEW_EMAIL print(&quot;\t 'EMAIL - ID UPDATED SUCCESSFULLY.&quot;) print(&quot;\n&quot;) elif ATTRIBUTE == 'ID': print(&quot;ENTER 'OLD STUDENT ID' :&quot;, end=&quot; &quot;) OLD_CLASS = input() LOC_CLASS = student_id.index(OLD_CLASS) print(&quot;ENTER 'NEW STUDENT ID' :&quot;, end=&quot; &quot;) NEW_CLASS = input() student_id[LOC_CLASS] = NEW_CLASS print(&quot;\t 'CLASS UPDATED SUCCESSFULLY.&quot;) print(&quot;\n&quot;) elif ATTRIBUTE == 'MOBILE NUMBER': print(&quot;ENTER 'OLD MOBILE NUMBER' :&quot;, end=&quot; &quot;) OLD_MOBILE = input() print(&quot;ENTER 'NEW MOBILE NUMBER' :&quot;, end=&quot; &quot;) NEW_MOBILE = input() MOBILE_NUMBER_LEN = len(OLD_MOBILE) M_N_LEN = len(NEW_MOBILE) if MOBILE_NUMBER_LEN &lt; 10: print(end=&quot;\n&quot;) print(&quot;PLEASE ENTER TEN DIGIT MOBILE NUMBER.&quot;) print(&quot;SYSTEM HAS STOP, PLEASE TRY AGAIN.&quot;) sys.exit() elif M_N_LEN &lt; 10: print(end=&quot;\n&quot;) print(&quot;\t PLEASE ENTER VALID TEN DIGIT MOBILE NUMBER.&quot;) print(&quot;\t SYSTEM WORKING HAS STOP PLEASE TRY AGAIN.&quot;) sys.exit() else: LOC_MOBILE = student_mobile_number.index(OLD_MOBILE) student_mobile_number[LOC_MOBILE] = NEW_MOBILE print(&quot;\t 'MOBILE NUMBER UPDATED SUCCESSFULLY.&quot;) print(&quot;\n&quot;) @staticmethod # THIS FUNCTION HELP TO UPDATE 'DATA' OF STUDENT. def DISPLAY_STUDENT_INFORMATION(): print(&quot;DISPLAYING STUDENTS INFORMATION : \n&quot;) if len(first_name) == 0 and len(last_name) == 0 and len(student_age) == 0 and len( student_id) == 0 and len(student_mobile_number) == 0 and len(student_address) == 0 and len( student_email) == 0: print(&quot;\n&quot;) print(&quot;\t\t\t 'OOPS ! NOTHING TO DISPLAY, BECAUSE NO DATA IS THERE.&quot;) print(&quot;\n&quot;) else: print(&quot;STUDENT'S FIRST NAME : &quot;, end=&quot;\n&quot;) for x in first_name: print(x) print() print(end=&quot;\n&quot;) print(&quot;STUDENT'S LAST NAME :&quot;, end=&quot;\n&quot;) for y in last_name: print(y) print() print(end=&quot;\n&quot;) print(&quot;STUDENT'S AGE :&quot;, end=&quot;\n&quot;) for z in student_age: print(z) print() print(end=&quot;\n&quot;) print(&quot;STUDENT'S MOBILE NUMBER :&quot;, end=&quot;\n&quot;) for x in student_mobile_number: print(x) print() print(end=&quot;\n&quot;) print(&quot;STUDENT'S EMAIL :&quot;, end=&quot;\n&quot;) for y in student_email: print(y) print() print(end=&quot;\n&quot;) print(&quot;STUDENT'S ID :&quot;, end=&quot;\n&quot;) for z in student_id: print(z) print() print(end=&quot;\n&quot;) print(&quot;STUDENT'S ADDRESS :&quot;, end=&quot;\n&quot;) for x in student_address: print(x) print() print(end=&quot;\n&quot;) SMS = student_management_system() if __name__ == '__main__': print(&quot;\n&quot;) print(&quot;' STUDENT RECORDS ' \n&quot;) run = True while run: print(&quot;PRESS FROM THE FOLLOWING OPTION : \n&quot;) print(&quot;PRESS 1 : TO ADD STUDENT INFORMATION.&quot;) print(&quot;PRESS 2 : TO DELETE STUDENT INFORMATION.&quot;) print(&quot;PRESS 3 : TO UPDATE STUDENT INFORMATION.&quot;) print(&quot;PRESS 4 : TO DISPLAY STUDENT INFORMATION.&quot;) print(&quot;PRESS 5 : TO EXIT SYSTEM.&quot;) OPTION = int(input(&quot;ENTER YOUR OPTION : &quot;)) print(&quot;\n&quot;) print(end=&quot;\n&quot;) if OPTION == 1: SMS.add_student_information() elif OPTION == 2: SMS.delete_student_information() elif OPTION == 3: SMS.update_student_information() elif OPTION == 4: SMS.display_student_information() elif OPTION == 5: print(&quot;THANK YOU ! VISIT AGAIN.&quot;) run = False else: print(&quot;PLEASE CHOOSE CORRECT OPTION FROM THE FOLLOWING.&quot;) print(&quot;\n&quot;) </code></pre> <p>Removing multiple instances/bloated code</p>
[ { "answer_id": 74468669, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 2, "selected": false, "text": "B" }, { "answer_id": 74468847, "author": "Naveed", "author_id": 3494754, "author_profile": "https://Stackoverflow.com/users/3494754", "pm_score": 1, "selected": false, "text": "# use isalpha to check if value is alphabetic\n# use negation to pick where value is not alphabetic\n\ndf=df.loc[~df['B'].str.isalpha()]\n\ndf\n" } ]
2022/11/16
[ "https://Stackoverflow.com/questions/74468662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20524919/" ]
74,468,667
<p>I am trying to create a table that would imitate the following table from excel. <a href="https://i.stack.imgur.com/RSdjI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RSdjI.png" alt="enter image description here" /></a></p> <p>My Data is: Col1 Col2 Col3 A Red Cheetah A Red Cheetah A Red Cheetah A Blue Cheetah A Blue Cheetah A Blue Cheetah A Blue Cheetah A Blue Cheetah B Blue Cheetah B Blue Cheetah C Blue Cheetah C Blue Cheetah C Blue Lion C Blue Lion C Orange Lion C Orange Lion A Orange Lion A Orange Lion A Orange Lion A Orange Lion A Red Lion A Red Lion A Red Bear A Red Bear A Red Bear B Red Bear B Green Bear B Green Bear C Green Bear C Green Bear C Green Bear</p> <p>I tried separating the data frame into smaller data frames based on the col3 but I would like it all to still be one table as pictured above</p>
[ { "answer_id": 74469751, "author": "Jason Baker", "author_id": 3249641, "author_profile": "https://Stackoverflow.com/users/3249641", "pm_score": 2, "selected": true, "text": "df = pd.crosstab(\n index=[df.Col1, df.Col3],\n columns=df.Col2,\n rownames=[\"Row Labels\", \"Column Labels\"],\n colnames=[\"Count of Col1\"],\n margins=True,\n margins_name=\"Grand Total\"\n)\n\nprint(df)\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74468667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15684836/" ]
74,468,668
<p>I am new to flask and I was trying to make GET request for url containing &quot;?&quot; symbol but it look like my program is just skipping work with it. I am working with flask-sql alchemy, flask and flask-restful. Some simplified look of my program looks like this:</p> <pre><code>fields_list = ['id'] db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) </code></pre> <pre><code>class Get(Resource): @staticmethod def get(): users = User.query.all() usr_list = Collection.user_to_json(users) return {&quot;Users&quot;: usr_list}, 200 class GetSorted(Resource): @staticmethod def get(field, type): if field not in fields_list or type not in ['acs', 'desc']: return {'Error': 'Wrong field or sort type'}, 400 users = db.session.execute(f&quot;SELECT * FROM USER ORDER BY {field} {type}&quot;) usr_list = Collection.user_to_json(users) return {&quot;Users&quot;: usr_list}, 200 </code></pre> <pre><code>api.add_resource(GetSorted, '/api/customers?sort=&lt;field&gt;&amp;sort_type=&lt;type&gt;') api.add_resource(Get, '/api/customers') </code></pre> <p>Output with url &quot;http://127.0.0.1:5000/api/customers?sort=id&amp;sort_type=desc&quot; looks like this</p> <pre><code>{ &quot;Users&quot;: [ { &quot;Id&quot;: 1 }, { &quot;Id&quot;: 2 }, { &quot;Id&quot;: 3 }, ] } </code></pre> <p>But I expect it to look like this</p> <pre><code>{ &quot;Users&quot;: [ { &quot;Id&quot;: 3 }, { &quot;Id&quot;: 2 }, { &quot;Id&quot;: 1 }, ] } </code></pre> <p>Somehow if I replace &quot;?&quot; with &quot;/&quot; in url everything worked fine, but I want it to work with &quot;?&quot;</p>
[ { "answer_id": 74469751, "author": "Jason Baker", "author_id": 3249641, "author_profile": "https://Stackoverflow.com/users/3249641", "pm_score": 2, "selected": true, "text": "df = pd.crosstab(\n index=[df.Col1, df.Col3],\n columns=df.Col2,\n rownames=[\"Row Labels\", \"Column Labels\"],\n colnames=[\"Count of Col1\"],\n margins=True,\n margins_name=\"Grand Total\"\n)\n\nprint(df)\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74468668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17394781/" ]
74,468,671
<p>Here's my script:</p> <pre><code>using System.Collections; using System.Collections.Generic; using UnityEngine; public class GoToMouse : MonoBehaviour { private Transform tf; private bool Selected = false; // Start is called before the first frame update void Start() { tf = GetComponent&lt;Transform&gt;(); } private void OnMouseDown() { if (Selected == false) { Selected = true; } if (Selected == true) { Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); tf.position = mousePos; } } private void OnMouseUp() { if (Selected == true) { Selected = false; } if (Selected == false) { } } // Update is called once per frame void Update() { } } </code></pre> <p>In this script, I want to do two things. I want an object to become selected when clicked and unselected when you let go of the mouse. When an object is selected I want it to move towards the mouse cursor. Basically, you can drag it around with the mouse cursor and throw it with physics.</p> <p>This script has a couple problems.</p> <ol> <li><p>Whenever I click the object it completely vanishes. I have no background or anything it could be going behind, so I don't know what is causing this. The object also doesn't move anywhere (I checked its transform) So it appears it's sprite just stops rendering</p> </li> <li><p>Whenever I select it and try to move it, it moves less that 1 unit along the X and Y axis and then stops. For some reason, it deselects itself or stops moving before I let go of the mouse. I don't know why this would be since the only way to deselect an object is by letting go of the mouse.</p> </li> </ol> <p>This is a unity2D project BTW, and this script is the backbone of the game I'm making. Please help!</p> <p>thanks.</p>
[ { "answer_id": 74469751, "author": "Jason Baker", "author_id": 3249641, "author_profile": "https://Stackoverflow.com/users/3249641", "pm_score": 2, "selected": true, "text": "df = pd.crosstab(\n index=[df.Col1, df.Col3],\n columns=df.Col2,\n rownames=[\"Row Labels\", \"Column Labels\"],\n colnames=[\"Count of Col1\"],\n margins=True,\n margins_name=\"Grand Total\"\n)\n\nprint(df)\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74468671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20524903/" ]
74,468,681
<p>I am trying to serve a PDF file as a ContentResult in my web API. I have tried to return the PDF payload as an <code>&lt;iframe&gt;</code> and as an <code>&lt;object&gt;</code>. However, the base64 encoded data string is too long I believe and neither one loads the PDF file. I want to return a PDF file without forcing users to download it as a separate file and open it in a PDF viewer and instead user the browser's default PDF viewer, hence the <code>&lt;iframe&gt;</code>.</p> <p>The default from what I gather is 2k characters or 2MB.</p> <p>The following is my code for return the ContentResult:</p> <pre class="lang-cs prettyprint-override"><code>return new ContentResult { ContentType = &quot;text/html&quot;, StatusCode = (int)HttpStatusCode.OK, // &lt;iframe&gt; version Content = $&quot;&lt;iframe title='PDF Viewer Frame' src='{{data:application/pdf;base64,{myFile}}}' height='600px' width='100%'/&gt;&quot; // &lt;object&gt; version Content = $&quot;&lt;object type='application/pdf' data='data:application/pdf;base64,{myFile}' height='600' width='600'&gt;&lt;object/&gt;&quot; }; </code></pre> <p>I am not sure if this is the best approach to serving a PDF by API call or if there is a better way.</p> <p>Thanks for the help!</p>
[ { "answer_id": 74469751, "author": "Jason Baker", "author_id": 3249641, "author_profile": "https://Stackoverflow.com/users/3249641", "pm_score": 2, "selected": true, "text": "df = pd.crosstab(\n index=[df.Col1, df.Col3],\n columns=df.Col2,\n rownames=[\"Row Labels\", \"Column Labels\"],\n colnames=[\"Count of Col1\"],\n margins=True,\n margins_name=\"Grand Total\"\n)\n\nprint(df)\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74468681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19831782/" ]
74,468,702
<h1>Description of Issue</h1> <p>I was reviewing my code for one of my projects when I noticed that one of my function's name is coloured green while all of the other functions are yellow.</p> <p><a href="https://i.stack.imgur.com/mXMT1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mXMT1.png" alt="enter image description here" /></a></p> <p>When I hover over the function in the <code>readButton.addEventListener(&quot;click&quot;, toggleRead);</code> it says: <code>Class toggleRead - function toggleRead(e: any): void</code></p> <p>Also, when I hover over the actual function declaration, it says <code>This constructor function may be converted to a class declaration.ts(80002)</code></p> <h1>Additional Info</h1> <p>I am using the <code>toggleRead</code> function to toggle an attribute. The <code>this</code> keyword refers to the button that calls the function. It doesn't seem to cause any issues in my program and it is working as intended.</p> <h1>Question</h1> <p>Am I breaking some kind of code convention that results in this hint, or am I otherwise doing something wrong? Also, why does visual studio think this function is a constructor?</p> <h1>Similar Issue</h1> <p>I found <a href="https://stackoverflow.com/questions/50257877/vscode-js-this-constructor-function-may-be-converted-to-a-class-declaration">this</a> question on stack overflow but the person asking the question is only interested in turning the hint off. I want to know if I did something wrong.</p> <h1>Code</h1> <pre class="lang-js prettyprint-override"><code>readButton.addEventListener(&quot;click&quot;, toggleRead); </code></pre> <pre class="lang-js prettyprint-override"><code>// Toggle book read function toggleRead(e) { const bookIndex = getBookIndex(this); const bookObject = library.at(bookIndex); if (bookObject.read) { bookObject.read = false; this.setAttribute(&quot;is-read&quot;, &quot;false&quot;); this.innerHTML = &quot;Unread&quot;; } else { bookObject.read = true; this.setAttribute(&quot;is-read&quot;, &quot;true&quot;); this.innerHTML = &quot;Read&quot;; } } </code></pre>
[ { "answer_id": 74468918, "author": "Peter B", "author_id": 1220550, "author_profile": "https://Stackoverflow.com/users/1220550", "pm_score": 1, "selected": false, "text": "const" }, { "answer_id": 74468980, "author": "GeorgeCiesinski", "author_id": 2665812, "author_profile": "https://Stackoverflow.com/users/2665812", "pm_score": 1, "selected": true, "text": "this" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74468702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2665812/" ]
74,468,709
<p><strong>Details:</strong></p> <ol> <li><p>Given a string <code>s</code> that contains <code>words.</code> I am also given <code>spaces</code> which specifies the number of extra spaces to add between words.</p> </li> <li><p>The number of <code>spots</code> will be <code>len(words)-1.</code></p> </li> <li><p>If <code>spaces/spots</code> is an odd number then the left slot gets more spaces.</p> </li> </ol> <p><strong>Example1:</strong></p> <pre><code>s = &quot;This is an&quot; spaces = 6 Ans = &quot;This is an&quot; #Explanation - 3 spaces added after &quot;this&quot; and 3 spaces added after &quot;is&quot; </code></pre> <br> <p><strong>Example2:</strong></p> <pre><code>s = &quot;This is an&quot; spaces = 7 Ans = &quot;This is an&quot; #Explanation - 4 spaces added after &quot;this&quot; and 3 spaces added after &quot;is&quot; </code></pre> <p>Solution:</p> <pre><code>def solution(s, spaces): spots = len(s.split())-1 space_for_every_spot = spaces/spots ... </code></pre>
[ { "answer_id": 74468775, "author": "Nazar Nintendo", "author_id": 20524194, "author_profile": "https://Stackoverflow.com/users/20524194", "pm_score": 1, "selected": false, "text": "def solution(s, spaces):\n words = s.split(\" \")\n spots = len(words) - 1\n n_spaces = spaces // spots\n n_extra_spaces = spaces - n_spaces * spots\n result = words[0] + \" \" * (n_spaces + n_extra_spaces)\n for word in words[1:]:\n result += word + \" \" * n_spaces\n return result\n" }, { "answer_id": 74468807, "author": "Mark Tolonen", "author_id": 235698, "author_profile": "https://Stackoverflow.com/users/235698", "pm_score": 2, "selected": false, "text": "s = 'The quick brown fox jumped over the lazy dog.'\nspaces = 20\n\nwords = s.split()\nspace_count, extra_count = divmod(spaces, len(words) - 1)\nspacing = ' ' * space_count\nextra_spacing = ' ' * (space_count + 1)\nresult = spacing.join(words)\nresult = result.replace(spacing, extra_spacing, extra_count)\nprint(result)\nprint(result.replace(' ', '.')) # for easier counting\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74468709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5632400/" ]
74,468,720
<p>I have a csv file (separated by comma), which contains</p> <pre><code>file1a.extension.extension,file1b.extension.extension file2a.extension.extension,file2b.extension.extension </code></pre> <p>Problem is, these files are name such as file.extension.extension</p> <p>I'm trying to feed both columns to parallel and removing all extesions</p> <p>I tried some variations of:</p> <pre><code>cat /home/filepairs.csv | sed 's/\..*//' | parallel --colsep ',' echo column 1 = {1}.extension.extension column 2 = {2} </code></pre> <p>Which I expected to output</p> <pre><code>column 1 = file1a.extension.extension column 2 = file1b column 1 = file2a.extension.extension column 2 = file2b </code></pre> <p>But outputs:</p> <pre><code>column 1 = file1a.extension.extension column 2 = column 1 = file2a.extension.extension column 2 = </code></pre> <p>The sed command is working but is feeding only column 1 to parallel</p>
[ { "answer_id": 74468775, "author": "Nazar Nintendo", "author_id": 20524194, "author_profile": "https://Stackoverflow.com/users/20524194", "pm_score": 1, "selected": false, "text": "def solution(s, spaces):\n words = s.split(\" \")\n spots = len(words) - 1\n n_spaces = spaces // spots\n n_extra_spaces = spaces - n_spaces * spots\n result = words[0] + \" \" * (n_spaces + n_extra_spaces)\n for word in words[1:]:\n result += word + \" \" * n_spaces\n return result\n" }, { "answer_id": 74468807, "author": "Mark Tolonen", "author_id": 235698, "author_profile": "https://Stackoverflow.com/users/235698", "pm_score": 2, "selected": false, "text": "s = 'The quick brown fox jumped over the lazy dog.'\nspaces = 20\n\nwords = s.split()\nspace_count, extra_count = divmod(spaces, len(words) - 1)\nspacing = ' ' * space_count\nextra_spacing = ' ' * (space_count + 1)\nresult = spacing.join(words)\nresult = result.replace(spacing, extra_spacing, extra_count)\nprint(result)\nprint(result.replace(' ', '.')) # for easier counting\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74468720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11279262/" ]
74,468,730
<p>I would like to get the xml value of an element in ElementTree. For example, if I had the code:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;item&gt; &lt;child&gt;asd&lt;/child&gt; hello world &lt;ch&gt;jkl&lt;/ch&gt; &lt;/item&gt; </code></pre> <p>It would get me</p> <pre class="lang-xml prettyprint-override"><code>&lt;child&gt;asd&lt;/child&gt; hello world &lt;ch&gt;jkl&lt;/ch&gt; </code></pre> <p>Here's what I tried so far:</p> <pre class="lang-py prettyprint-override"><code>import xml.etree.ElementTree as ET root = ET.fromstring(&quot;&quot;&quot;&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;item&gt; &lt;child&gt;asd&lt;/child&gt; hello world &lt;ch&gt;jkl&lt;/ch&gt; &lt;/item&gt;&quot;&quot;&quot;) print(root.text) </code></pre>
[ { "answer_id": 74468775, "author": "Nazar Nintendo", "author_id": 20524194, "author_profile": "https://Stackoverflow.com/users/20524194", "pm_score": 1, "selected": false, "text": "def solution(s, spaces):\n words = s.split(\" \")\n spots = len(words) - 1\n n_spaces = spaces // spots\n n_extra_spaces = spaces - n_spaces * spots\n result = words[0] + \" \" * (n_spaces + n_extra_spaces)\n for word in words[1:]:\n result += word + \" \" * n_spaces\n return result\n" }, { "answer_id": 74468807, "author": "Mark Tolonen", "author_id": 235698, "author_profile": "https://Stackoverflow.com/users/235698", "pm_score": 2, "selected": false, "text": "s = 'The quick brown fox jumped over the lazy dog.'\nspaces = 20\n\nwords = s.split()\nspace_count, extra_count = divmod(spaces, len(words) - 1)\nspacing = ' ' * space_count\nextra_spacing = ' ' * (space_count + 1)\nresult = spacing.join(words)\nresult = result.replace(spacing, extra_spacing, extra_count)\nprint(result)\nprint(result.replace(' ', '.')) # for easier counting\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74468730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14257302/" ]
74,468,752
<p>I'm trying to use the <a href="https://learn.microsoft.com/en-us/microsoftteams/export-teams-content" rel="nofollow noreferrer">Teams Export API</a> to export a single Teams channel. I have my permissions set up properly; if I make a request to <code>https://graph.microsoft.com/v1.0/teams/{TEAM_ID}/channels/getAllMessages</code> (without specifying a filter), I get the paginated results of all of the channel messages on my team. If I copy the sample datetime filters in that documentation, I also get a successful response with the appropriate results.</p> <p>A successful response gives me a list of messages. Each one shows a <code>channelIdentity</code> field, which contains a <code>channelId</code> (fields removed for readability):</p> <pre><code>{ &quot;value&quot;: [ { &quot;channelIdentity&quot;: { &quot;teamId&quot;: &quot;{TEAM ID}&quot;, &quot;channelId&quot;: &quot;{CHANNEL ID}&quot; }, }, ] } </code></pre> <p>What I want is to use this <code>channelIdentity/channelId</code> field as a filter on the results, so that I can export just the messages from a single channel.</p> <p>If I run <code>GET https://graph.microsoft.com/v1.0/teams/{TEAM_ID}/channels/getAllMessages?$filter=channelIdentity/channelId eq '{CHANNEL ID}'</code>, I get an error:</p> <pre><code>{ &quot;error&quot;: { &quot;code&quot;: &quot;BadRequest&quot;, &quot;message&quot;: &quot;The entity property 'channelIdentity/channelId' and operationKind 'Equal' is not allowed in $filter query.&quot;, &quot;innerError&quot;: { &quot;date&quot;: &quot;2022-11-16T23:47:06&quot;, &quot;request-id&quot;: &quot;...&quot;, &quot;client-request-id&quot;: &quot;...&quot; } } } </code></pre> <p>This reads to me like I'm not allowed to use <code>eq</code> with this ID. If I try a 'starts with', I get a different error:</p> <pre><code>GET https://graph.microsoft.com/v1.0/teams/{TEAM_ID}/channels/getAllMessages?$filter=startswith(channelIdentity/teamId, '{CHANNEL ID}') { &quot;error&quot;: { &quot;code&quot;: &quot;BadRequest&quot;, &quot;message&quot;: &quot;Only binary operation expressions are allowed.&quot;, &quot;innerError&quot;: { &quot;date&quot;: &quot;2022-11-17T00:11:26&quot;, &quot;request-id&quot;: &quot;...&quot;, &quot;client-request-id&quot;: &quot;...&quot; } } } </code></pre> <p>I'm unclear on what this is trying to say - either the ID starts with that phrase or it doesn't; it seems like a binary expression to me.</p> <p>Is there some other approach I should use to get these results filtered by channel ID?</p>
[ { "answer_id": 74468775, "author": "Nazar Nintendo", "author_id": 20524194, "author_profile": "https://Stackoverflow.com/users/20524194", "pm_score": 1, "selected": false, "text": "def solution(s, spaces):\n words = s.split(\" \")\n spots = len(words) - 1\n n_spaces = spaces // spots\n n_extra_spaces = spaces - n_spaces * spots\n result = words[0] + \" \" * (n_spaces + n_extra_spaces)\n for word in words[1:]:\n result += word + \" \" * n_spaces\n return result\n" }, { "answer_id": 74468807, "author": "Mark Tolonen", "author_id": 235698, "author_profile": "https://Stackoverflow.com/users/235698", "pm_score": 2, "selected": false, "text": "s = 'The quick brown fox jumped over the lazy dog.'\nspaces = 20\n\nwords = s.split()\nspace_count, extra_count = divmod(spaces, len(words) - 1)\nspacing = ' ' * space_count\nextra_spacing = ' ' * (space_count + 1)\nresult = spacing.join(words)\nresult = result.replace(spacing, extra_spacing, extra_count)\nprint(result)\nprint(result.replace(' ', '.')) # for easier counting\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74468752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3692994/" ]
74,468,759
<p>Turn the four rings so that the sums of each four of the numbers that are located along the same radius are the same. Find what they are equal to? <a href="https://i.stack.imgur.com/q0naU.png" rel="nofollow noreferrer">problem image</a></p> <p>We can do it by <strong>Brute Force</strong> method but it will be dummy cause too many combinations. I had thoughts about <strong>DFS method</strong> but cant imagine how to consume it here truly. I dont need code for this problem, perhaps you can share your thoughts on this issue.</p> <pre><code>input data 1-st ring: 3 9 6 4 3 7 5 2 4 8 3 6 2-nd ring: 8 4 7 5 8 2 9 5 5 8 4 6 3-rd ring: 6 5 8 1 6 6 7 1 3 7 1 9 4-th ring: 9 2 4 6 8 4 3 8 5 2 3 7 </code></pre>
[ { "answer_id": 74469428, "author": "Olafus", "author_id": 20524946, "author_profile": "https://Stackoverflow.com/users/20524946", "pm_score": 2, "selected": true, "text": "def find_radius(*args):\n arr = []\n for i in range(0, len(args[0])):\n sum_radius = args[0][i] + args[1][i] + args[2][i] + args[3][i]\n arr.append(sum_radius)\n\n return list(dict.fromkeys(arr))\n\n\ndef move_ring(arr):\n first_element = arr[0]\n arr.remove(first_element)\n arr.append(first_element)\n return arr\n\n\ndef print_all_rings(*args):\n print(args[0])\n print(args[1])\n print(args[2])\n print(args[3])\n\n\nif __name__ == '__main__':\n # first example\n \n ring_1 = [3, 9, 6, 4, 3, 7, 5, 2, 4, 8, 3, 6]\n ring_2 = [8, 4, 7, 5, 8, 2, 9, 5, 5, 8, 4, 6]\n ring_3 = [6, 5, 8, 1, 6, 6, 7, 1, 3, 7, 1, 9]\n ring_4 = [9, 2, 4, 6, 8, 4, 3, 8, 5, 2, 3, 7]\n\n # second example\n \n # ring_1 = [4, 2]\n # ring_2 = [6, 8]\n # ring_3 = [9, 8]\n # ring_4 = [5, 8]\n\n first_round = 0\n second_round = 0\n\n while True:\n if first_round == len(ring_1):\n first_round = 0\n move_ring(ring_3)\n second_round += 1\n\n if second_round == len(ring_1):\n second_round = 0\n move_ring(ring_4)\n\n if len(find_radius(ring_1, ring_2, ring_3, ring_4)) == 1:\n print(\"200 OK! All subsums in column are the same\")\n break\n else:\n print(\"404 Error!\")\n\n move_ring(ring_2)\n first_round += 1\n\n print(find_radius(ring_1, ring_2, ring_3, ring_4))\n print_all_rings(ring_1, ring_2, ring_3, ring_4)\n\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74468759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20524946/" ]
74,468,784
<p>Hi I have a question about iterating through a list and adding items and their frequency within the list to a dictionary.</p> <pre><code>i = ['apple','pear','red','apple','red','red','pear','pear','pear'] d = {x:i.count(x) for x in i} print (d) </code></pre> <p>outputs</p> <pre><code> {'pear': 4, 'apple': 2, 'red': 3} </code></pre> <p>However</p> <pre><code>i = ['apple','pear','red','apple','red','red','pear', 'pear', 'pear'] d = {} for x in i: d={x:i.count(x)} print(d) </code></pre> <p>outputs</p> <pre><code>{'pear': 4} </code></pre> <p>I need to iterate through the list while adding each iteration within the dictionary to a new list. However I can't understand why the two different codes are giving different results.</p> <p>It's encouraging to seee that the count function works on the second one. But I am confused as to where apple and red dissapeared to.</p> <p>Sorry for bad wording etcetera been working on this hours and is driving me crazy. Thanks so much for taking time to help</p> <p>I am confused as to why the two results are different</p>
[ { "answer_id": 74468804, "author": "Ricardo", "author_id": 16353662, "author_profile": "https://Stackoverflow.com/users/16353662", "pm_score": 0, "selected": false, "text": "i = ['apple','pear','red','apple','red','red','pear', 'pear', 'pear']\nd = {} \nlog = []\nfor x in i: \n log.append({x:i.count(x)})\n" }, { "answer_id": 74468806, "author": "user99999", "author_id": 20070120, "author_profile": "https://Stackoverflow.com/users/20070120", "pm_score": 3, "selected": true, "text": "key:value" }, { "answer_id": 74468822, "author": "Nazar Nintendo", "author_id": 20524194, "author_profile": "https://Stackoverflow.com/users/20524194", "pm_score": 0, "selected": false, "text": "{'apple': 2, 'pear': 4, 'red': 3}\n" }, { "answer_id": 74469041, "author": "Meer Modi", "author_id": 17710122, "author_profile": "https://Stackoverflow.com/users/17710122", "pm_score": -1, "selected": false, "text": "varLs = ['apple','pear','red','apple','red','red','pear','pear','pear']\n\ndef frequency(varLs): \n counters = {}\n\n for item in varLs:\n if item not in counters:\n counters[item] = 1\n else:\n counters[item]+= 1\n return counters\n\nprint(frequency(varLs))\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74468784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20525041/" ]
74,468,789
<p>Let's say I have the following dictionary:</p> <pre><code>full_dic = { 'aa': 1, 'ac': 1, 'ab': 1, 'ba': 2, ... } </code></pre> <p>I normally use standard dictionary comprehension to remove dupes like:</p> <pre><code>t = {val : key for (key, val) in full_dic.items()} cleaned_dic = {val : key for (key, val) in t.items()} </code></pre> <p>Calling <code>print(cleaned_dic)</code> outputs <code>{'ab': 1,'ba': 2, ...}</code></p> <p>With this code, the key that remains seems to always be the final one in the list, but I'm not sure that's even guaranteed as dictionaries are unordered. Instead, I'd like to find a way to ensure that the key I keep is the first alphabetically.</p> <p>So, regardless of the 'order' the dictionary is in, I want the output to be:</p> <pre><code>&gt;&gt; {'aa': 1,'ba': 2, ...} </code></pre> <p>Where 'aa' comes first alphabetically.</p> <hr /> <p>I ran some timer tests on 3 answers below and got the following (dictionary was created with random key/value pairs):</p> <pre><code>dict length: 10 # of loops: 100000 HoliSimo (OrderedDict): 0.0000098405 seconds Ricardo: 0.0000115448 seconds Mark (itertools.groupby): 0.0000111745 seconds dict length: 1000000 # of loops: 10 HoliSimo (OrderedDict): 6.1724137300 seconds Ricardo: 3.3102091300 seconds Mark (itertools.groupby): 6.1338266200 seconds </code></pre> <p>We can see that for smaller dictionary sizes using <code>OrderedDict</code> is fastest but for large dictionary sizes it's slightly better to use Ricardo's answer below.</p>
[ { "answer_id": 74468804, "author": "Ricardo", "author_id": 16353662, "author_profile": "https://Stackoverflow.com/users/16353662", "pm_score": 0, "selected": false, "text": "i = ['apple','pear','red','apple','red','red','pear', 'pear', 'pear']\nd = {} \nlog = []\nfor x in i: \n log.append({x:i.count(x)})\n" }, { "answer_id": 74468806, "author": "user99999", "author_id": 20070120, "author_profile": "https://Stackoverflow.com/users/20070120", "pm_score": 3, "selected": true, "text": "key:value" }, { "answer_id": 74468822, "author": "Nazar Nintendo", "author_id": 20524194, "author_profile": "https://Stackoverflow.com/users/20524194", "pm_score": 0, "selected": false, "text": "{'apple': 2, 'pear': 4, 'red': 3}\n" }, { "answer_id": 74469041, "author": "Meer Modi", "author_id": 17710122, "author_profile": "https://Stackoverflow.com/users/17710122", "pm_score": -1, "selected": false, "text": "varLs = ['apple','pear','red','apple','red','red','pear','pear','pear']\n\ndef frequency(varLs): \n counters = {}\n\n for item in varLs:\n if item not in counters:\n counters[item] = 1\n else:\n counters[item]+= 1\n return counters\n\nprint(frequency(varLs))\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74468789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3894471/" ]
74,468,794
<p>I'm having trouble connecting to my DropBox account via <code>TIdHTTP</code> and I don't know what to do anymore. I want to send a simple text file to DropBox in the first stage.</p> <pre><code>procedure TForm2.btn1Click(Sender: TObject); const API_URL = 'https://content.dropboxapi.com/2/files/upload'; cFile = 'D:\testfile.txt'; var wAccessToken : string; Source: TFileStream; IdHTTP: TIdHTTP; Res : string; Ssl: TIdSSLIOHandlerSocketOpenSSL; begin wAccessToken := 'muj_token'; IdHTTP := TIdHTTP.Create(nil); try (* ShowMessage('Indy version: ' + IdHTTP.Version); RESULT MESSAGE : INDY 10.5.9.0 *) IdHTTP.HandleRedirects := True; ssl := TIdSSLIOHandlerSocketOpenSSL.Create(); ssl.SSLOptions.Method := sslvTLSv1_2; ssl.SSLOptions.Mode := sslmUnassigned; ssl.SSLOptions.VerifyMode := []; ssl.SSLOptions.VerifyDepth := 0; ssl.host := ''; Source := TFileStream.Create(cFile, fmOpenRead); IdHTTP.IOHandler := ssl; IdHTTP.Request.CustomHeaders.Values['Authorization'] := 'Bearer ' + wAccessToken; IdHTTP.Request.CustomHeaders.Values['Dropbox-API-Arg'] := '{ &quot;autorename&quot;: false,&quot;mode&quot;: &quot;add&quot;,&quot;mute&quot;: false,&quot;path&quot;: &quot;/test.txt&quot;,&quot;strict_conflict&quot;: false}'; IdHTTP.Request.CustomHeaders.Values['Content-Type'] := 'application/octet-stream'; Memo1.Lines.Add(IdHTTP.Request.CustomHeaders.Text); Res := IdHTTP.Post(API_URL, Source); finally IdHTTP.Free; end; </code></pre> <p>But, after the <code>POST</code> command, I get the error:</p> <blockquote> <p>Project Project2.exe raised exception class EIdOSSLUnderlyingCryptoError with message &quot;Error connecting with SSL. error:1409442E:SSL routines:SSL3_READ_BYTES:tlsv1 alert protocol version&quot;</p> </blockquote> <p><a href="https://i.stack.imgur.com/VCMjB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VCMjB.jpg" alt="image" /></a></p> <p>I don't know how to proceed, there is a stupid mistake somewhere. I found similar problems on StackOverflow:</p> <p><a href="https://stackoverflow.com/questions/1742900/">TIdHTTP in Indy 10</a></p> <p><a href="https://stackoverflow.com/questions/7762584/">Post problems with Indy TIdHTTP</a></p> <p>And many other forums. Somewhere it says it may be an old Indy (which it is), but DropBox probably has TLS v1.2 required though <code>TIdHTTP</code> enables it:</p> <p><code>ssl.SSLOptions.Method := sslvTLSv1_2</code></p> <p>For the Request track, I stuck to DropBox's API structure:</p> <pre><code>DROPBOX API DOCUMENTATION https://www.dropbox.com/developers/documentation/http/documentation#files-upload Get access token for: ****************************************************** ************** curl -X POST https://content.dropboxapi.com/2/files/upload \ --header &quot;Authorization: Bearer &lt;get access token&gt;&quot; \ --header &quot;Dropbox-API-Arg: {\&quot;autorename\&quot;:false,\&quot;mode\&quot;:\&quot;add\&quot;,\&quot;mute\&quot;:false,\&quot;path\&quot;:\&quot;/Homework/ math/Matrices.txt\&quot;,\&quot;strict_conflict\&quot;:false}&quot; \ --header &quot;Content-Type: application/octet-stream&quot; \ --data-binary @local_file.txt ****************************************************** ************** </code></pre> <p>Even more information:</p> <ul> <li>Delphi XE3</li> <li>Indy 10.5.9.0</li> <li>with the exe I have the OpenSSL files <code>libeay32.dll</code> (1.0.2.17) and <code>ssleay32.dll</code> (1.0.2.17) - but that will not be it. If I throw them away the error is the same.</li> <li>DropBox requires TLS 1.2 since April</li> </ul> <p>On some forums, they wrote the same error with old OpenSSL files, old Indy, sending via TLS, which is not supported by the addressee. But I don't feel either way.</p> <p>I downloaded OpenSSL from <a href="https://github.com/IndySockets/OpenSSL-Binaries" rel="nofollow noreferrer">https://github.com/IndySockets/OpenSSL-Binaries</a></p> <p><code>openssl-1.0.2u-x64_86-win64.zip</code> (I don't know if it's good, there are a bunch of them in the table with differences in the name &quot;r&quot;, &quot;s&quot;, &quot;t&quot;, &quot;u&quot;, I chose the last one).</p>
[ { "answer_id": 74468804, "author": "Ricardo", "author_id": 16353662, "author_profile": "https://Stackoverflow.com/users/16353662", "pm_score": 0, "selected": false, "text": "i = ['apple','pear','red','apple','red','red','pear', 'pear', 'pear']\nd = {} \nlog = []\nfor x in i: \n log.append({x:i.count(x)})\n" }, { "answer_id": 74468806, "author": "user99999", "author_id": 20070120, "author_profile": "https://Stackoverflow.com/users/20070120", "pm_score": 3, "selected": true, "text": "key:value" }, { "answer_id": 74468822, "author": "Nazar Nintendo", "author_id": 20524194, "author_profile": "https://Stackoverflow.com/users/20524194", "pm_score": 0, "selected": false, "text": "{'apple': 2, 'pear': 4, 'red': 3}\n" }, { "answer_id": 74469041, "author": "Meer Modi", "author_id": 17710122, "author_profile": "https://Stackoverflow.com/users/17710122", "pm_score": -1, "selected": false, "text": "varLs = ['apple','pear','red','apple','red','red','pear','pear','pear']\n\ndef frequency(varLs): \n counters = {}\n\n for item in varLs:\n if item not in counters:\n counters[item] = 1\n else:\n counters[item]+= 1\n return counters\n\nprint(frequency(varLs))\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74468794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11147396/" ]
74,468,826
<p>For each unique record ID, return the most recent record of type Y iff there is a more recent record of type X</p> <p>To make explaining easier I will put the records sorted by EventDate descending and look only at specific record ID's. (Most recent at the top.)</p> <p><strong>Case 1</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: right;">ID</th> <th>EventDate</th> <th>Type</th> </tr> </thead> <tbody> <tr> <td style="text-align: right;">1</td> <td>Some Dates</td> <td>Otherstuff (multiple records)</td> </tr> <tr> <td style="text-align: right;">1</td> <td>July 29</td> <td>X</td> </tr> <tr> <td style="text-align: right;">1</td> <td>Feb 23</td> <td>Y</td> </tr> <tr> <td style="text-align: right;">1</td> <td>Jan 3</td> <td>Y</td> </tr> <tr> <td style="text-align: right;">1</td> <td>Some Dates</td> <td>Otherstuff (multiple records)</td> </tr> </tbody> </table> </div> <p>Return record from Feb 23 of Type Y (Feb 23 is a closer date to the Jan 1 date of record with type X)</p> <p><strong>Case 2</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: right;">ID</th> <th>EventDate</th> <th>Type</th> </tr> </thead> <tbody> <tr> <td style="text-align: right;">2</td> <td>Some Dates</td> <td>Otherstuff (multiple records)</td> </tr> <tr> <td style="text-align: right;">2</td> <td>Nov 2</td> <td>X</td> </tr> <tr> <td style="text-align: right;">2</td> <td>Oct 31</td> <td>Y</td> </tr> <tr> <td style="text-align: right;">2</td> <td>Some Dates</td> <td>Otherstuff</td> </tr> <tr> <td style="text-align: right;">2</td> <td>July 2</td> <td>X</td> </tr> <tr> <td style="text-align: right;">2</td> <td>Feb 23</td> <td>Y</td> </tr> <tr> <td style="text-align: right;">2</td> <td>Jan 5</td> <td>Y</td> </tr> <tr> <td style="text-align: right;">2</td> <td>Some Dates</td> <td>Otherstuff</td> </tr> </tbody> </table> </div> <p>Return records from Feb 23 of type Y and Oct 31 of Type Y. These are the records that are the closest to the type X records in terms of date respectively. (Feb 23 Type y is closest to July 2 of type X and Oct 31 type Y is closest to Nov 2 type X)</p> <p><strong>Case 3</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: right;">ID</th> <th style="text-align: right;">EventDate</th> <th>Type</th> </tr> </thead> <tbody> <tr> <td style="text-align: right;">3</td> <td style="text-align: right;">Some Dates</td> <td>Otherstuff (multiple records)</td> </tr> <tr> <td style="text-align: right;">3</td> <td style="text-align: right;">July 2</td> <td>X</td> </tr> <tr> <td style="text-align: right;">3</td> <td style="text-align: right;">Feb 23</td> <td>Y</td> </tr> <tr> <td style="text-align: right;">3</td> <td style="text-align: right;">Some Dates</td> <td>Otherstuff</td> </tr> <tr> <td style="text-align: right;">3</td> <td style="text-align: right;">Jan 5</td> <td>X</td> </tr> <tr> <td style="text-align: right;">3</td> <td style="text-align: right;">Some Dates</td> <td>Otherstuff</td> </tr> </tbody> </table> </div> <p>Return Feb 23 of type Y record</p> <p><strong>Case 4</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: right;">ID</th> <th>EventDate</th> <th>Type</th> </tr> </thead> <tbody> <tr> <td style="text-align: right;">4</td> <td>Some Dates</td> <td>Otherstuff (multiple records)</td> </tr> <tr> <td style="text-align: right;">4</td> <td>Oct 15</td> <td>Y</td> </tr> <tr> <td style="text-align: right;">4</td> <td>July 2</td> <td>X</td> </tr> <tr> <td style="text-align: right;">5</td> <td>Feb 23</td> <td>X</td> </tr> <tr> <td style="text-align: right;">5</td> <td>Some Dates</td> <td>Otherstuff</td> </tr> <tr> <td style="text-align: right;">5</td> <td>Jan 5</td> <td>Y</td> </tr> <tr> <td style="text-align: right;">5</td> <td>Jan 1</td> <td>Y</td> </tr> <tr> <td style="text-align: right;">5</td> <td>Some Dates</td> <td>Otherstuff</td> </tr> </tbody> </table> </div> <p>Return ONLY the Jan 5th of type Y record. It is the closest to record of type X in terms of dates that has happened before the type X</p> <pre class="lang-sql prettyprint-override"><code>SELECT * FROM ( SELECT *, ROW_NUMBER() OVER ( PARTITION BY A.ID ORDER BY EventDate DESC ) AS pc FROM SOMETABLE AS &quot;A&quot; INNER JOIN ( SELECT ID AS 'BID', MIN(EventDate) AS 'OldestDate' FROM SOMETABLE WHERE TYPE = 'X' GROUP BY ID ) AS &quot;B&quot; ON A.ID = B.BID WHERE EventDate &lt; OldestDate AND Type = 'Y' ) AS &quot;FINAL&quot; </code></pre> <p>This fails in cases where there are multiple records of type Y that need to be pulled, as it 'filters out' any records newer than the OLDEST instance of type X.</p>
[ { "answer_id": 74469191, "author": "JHH", "author_id": 20127235, "author_profile": "https://Stackoverflow.com/users/20127235", "pm_score": 0, "selected": false, "text": "create table event (\n id int,\n event_date date,\n type char(1));\n \n\ninsert into event\nvalues\n(1, '2022-01-01', 'X'),\n(1, '2022-01-03', 'X'),\n(1, '2022-01-05', 'Y'),\n(1, '2022-01-07', 'Y'),\n(1, '2022-01-09', 'X'),\n(1, '2022-01-11', 'X'),\n(1, '2022-01-15', 'Y');\n" }, { "answer_id": 74565759, "author": "OPislag", "author_id": 20524948, "author_profile": "https://Stackoverflow.com/users/20524948", "pm_score": 2, "selected": true, "text": "SELECT \n * \n ,ROW_NUMBER() OVER (PARTITION BY ID ORDER BY XDateTime ASC) AS 'Degree'\nFROM\n (SELECT \n *\n ,ROW_NUMBER() OVER (PARTITION BY YDateTime ORDER BY XDateTime ASC) AS 'dc'\n FROM\n (SELECT\n ID\n ,EventDateTime AS 'YDateTime'\n ,B.XDateTime\n ,DATEDIFF(SECOND, EventDateTime, B.XDateTime) AS 'Time'\n ,ROW_NUMBER() OVER (PARTITION BY B.XDateTime ORDER BY EventDateTime DESC) AS 'pc'\n \n FROM vw_A6Productivity AS \"A\"\n\n INNER JOIN\n (SELECT\n ID AS 'BID'\n ,EventDateTime AS 'XDateTime'\n \n FROM TABLE\n \n WHERE TYPE = 'X'\n \n GROUP BY \n ID\n ,EventDateTime\n ) AS \"B\"\n\n ON A.ID= B.BID\n\n WHERE \n EventDateTime < XDateTime -- Inner join filters for Nulls automatically\n AND STATUS = 'Y'\n \n ) AS \"C\"\n\n WHERE\n pc = 1\n \n ) AS \"D\"\n\nWHERE dc = 1;\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74468826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20524948/" ]
74,468,841
<p>I am trying to create a HTML program that can put the selected item from the dropdown created from the <code>&lt;select&gt;</code> and <code>&lt;option&gt;</code> scripts into a .txt file. The file is on Replit, so assume the text file already exists. This is my code, so far:</p> <p>`</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;body&gt; &lt;form action=&quot;cardspicked.txt&quot; method=&quot;get&quot;&gt; &lt;h3&gt;What is your favorite low elixir Clash Royale card?&lt;/h3&gt; &lt;label for=&quot;low_elixir&quot;&gt;Choose a card:&lt;/label&gt; &lt;select name = &quot;low_elixir&quot; id = &quot;low_elixir&quot;&gt; &lt;option&gt;Heal Spirit&lt;/option&gt; &lt;option&gt;Skeletons&lt;/option&gt; &lt;option&gt;Electro Spirit&lt;/option&gt; &lt;option&gt;Fire Spirit&lt;/option&gt; &lt;option&gt;Ice Spirit&lt;/option&gt; &lt;option&gt;Wall Breakers&lt;/option&gt; &lt;option&gt;Bats&lt;/option&gt; &lt;option&gt;Spear Goblins&lt;/option&gt; &lt;option&gt;Bomber&lt;/option&gt; &lt;option&gt;Ice Golem&lt;/option&gt; &lt;option&gt;Goblins&lt;/option&gt; &lt;option&gt;Rage&lt;/option&gt; &lt;option&gt;Giant Snowball&lt;/option&gt; &lt;option&gt;Barbarian Barrel&lt;/option&gt; &lt;option&gt;Zap&lt;/option&gt; &lt;option&gt;The Log&lt;/option&gt; &lt;/select&gt; &lt;hr&gt; &lt;h3&gt;What about medium elixir?&lt;/h3&gt; &lt;label for=&quot;med_elixir&quot;&gt;Choose a card:&lt;/label&gt; &lt;select name = &quot;med_elixir&quot; id = &quot;med_elixir&quot;&gt; &lt;option&gt;Knight&lt;/option&gt; &lt;option&gt;Ice Wizard&lt;/option&gt; &lt;option&gt;Mega Minion&lt;/option&gt; &lt;option&gt;Dart Goblin&lt;/option&gt; &lt;option&gt;Goblin Gang&lt;/option&gt; &lt;option&gt;Miner&lt;/option&gt; &lt;option&gt;Minions&lt;/option&gt; &lt;option&gt;Bandit&lt;/option&gt; &lt;option&gt;Princess&lt;/option&gt; &lt;option&gt;Guards&lt;/option&gt; &lt;option&gt;Archers&lt;/option&gt; &lt;option&gt;Firecracker&lt;/option&gt; &lt;option&gt;Royal Ghost&lt;/option&gt; &lt;option&gt;Elixir Golem&lt;/option&gt; &lt;option&gt;Skeleton Barrel&lt;/option&gt; &lt;option&gt;Fisherman&lt;/option&gt; &lt;option&gt;Skeleton Army&lt;/option&gt; &lt;option&gt;Battle Healer&lt;/option&gt; &lt;option&gt;Zappies&lt;/option&gt; &lt;option&gt;Skeleton King&lt;/option&gt; &lt;option&gt;Hunter&lt;/option&gt; &lt;option&gt;Valkyrie&lt;/option&gt; &lt;option&gt;Flying Machine&lt;/option&gt; &lt;option&gt;Mighty Miner&lt;/option&gt; &lt;option&gt;Electro Wizard&lt;/option&gt; &lt;option&gt;Magic Archer&lt;/option&gt; &lt;option&gt;Night Witch&lt;/option&gt; &lt;option&gt;Inferno Dragon&lt;/option&gt; &lt;option&gt;Battle Ram&lt;/option&gt; &lt;option&gt;Mini P.E.K.K.A&lt;/option&gt; &lt;option&gt;Musketeer&lt;/option&gt; &lt;option&gt;Baby Dragon&lt;/option&gt; &lt;option&gt;Golden Knight&lt;/option&gt; &lt;option&gt;Skeleton Dragons&lt;/option&gt; &lt;option&gt;Dark Prince&lt;/option&gt; &lt;option&gt;Night Witch&lt;/option&gt; &lt;option&gt;Lumberjack&lt;/option&gt; &lt;option&gt;Cannon&lt;/option&gt; &lt;option&gt;Tombstone&lt;/option&gt; &lt;option&gt;Mortar&lt;/option&gt; &lt;option&gt;Bomb Tower&lt;/option&gt; &lt;option&gt;Tesla&lt;/option&gt; &lt;option&gt;Furnace&lt;/option&gt; &lt;option&gt;Goblin Cage&lt;/option&gt; &lt;option&gt;Goblin Drill&lt;/option&gt; &lt;option&gt;Goblin Barrel&lt;/option&gt; &lt;option&gt;Royal Delivery&lt;/option&gt; &lt;option&gt;Tornado&lt;/option&gt; &lt;option&gt;Earthquake&lt;/option&gt; &lt;option&gt;Arrows&lt;/option&gt; &lt;option&gt;Clone&lt;/option&gt; &lt;option&gt;Fireball&lt;/option&gt; &lt;option&gt;Freeze&lt;/option&gt; &lt;option&gt;Poison&lt;/option&gt; &lt;/select&gt; &lt;hr&gt; &lt;h3&gt;High elixir?&lt;/h3&gt; &lt;label for=&quot;high_elixir&quot;&gt;Choose a card:&lt;/label&gt; &lt;select name = &quot;high_elixir&quot; id = &quot;high_elixir&quot;&gt; &lt;option&gt;Barbarians&lt;/option&gt; &lt;option&gt;Royal Hogs&lt;/option&gt; &lt;option&gt;Giant&lt;/option&gt; &lt;option&gt;Prince&lt;/option&gt; &lt;option&gt;Wizard&lt;/option&gt; &lt;option&gt;Ram Rider&lt;/option&gt; &lt;option&gt;Cannon Cart&lt;/option&gt; &lt;option&gt;Rascals&lt;/option&gt; &lt;option&gt;Witch&lt;/option&gt; &lt;option&gt;Minion Horde&lt;/option&gt; &lt;option&gt;Executioner&lt;/option&gt; &lt;option&gt;Balloon&lt;/option&gt; &lt;option&gt;Archer Queen&lt;/option&gt; &lt;option&gt;Bowler&lt;/option&gt; &lt;option&gt;Electro Dragon&lt;/option&gt; &lt;option&gt;Elite Barbarians&lt;/option&gt; &lt;option&gt;Goblin Giant&lt;/option&gt; &lt;option&gt;Sparky&lt;/option&gt; &lt;option&gt;Royal Giant&lt;/option&gt; &lt;option&gt;Giant Skeleton&lt;/option&gt; &lt;option&gt;Mega Knight&lt;/option&gt; &lt;option&gt;P.E.K.K.A&lt;/option&gt; &lt;option&gt;Royal Recruits&lt;/option&gt; &lt;option&gt;Lava Hound&lt;/option&gt; &lt;option&gt;Electro Giant&lt;/option&gt; &lt;option&gt;Golem&lt;/option&gt; &lt;option&gt;Three Musketeers&lt;/option&gt; &lt;option&gt;Goblin Hut&lt;/option&gt; &lt;option&gt;Inferno Tower&lt;/option&gt; &lt;option&gt;Elixir Collector&lt;/option&gt; &lt;option&gt;X-Bow&lt;/option&gt; &lt;option&gt;Barbarian Hut&lt;/option&gt; &lt;option&gt;Graveyard&lt;/option&gt; &lt;option&gt;Lightning&lt;/option&gt; &lt;option&gt;Rocket&lt;/option&gt; &lt;/select&gt; &lt;hr&gt; &lt;button type=&quot;submit&quot; value=&quot;Submit&quot; /&gt;Submit&lt;/button&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>`</p> <p>I have checked many websites, including this one, to find an answer to this question, but none have been able to help me. Try to help, if possible.</p>
[ { "answer_id": 74469191, "author": "JHH", "author_id": 20127235, "author_profile": "https://Stackoverflow.com/users/20127235", "pm_score": 0, "selected": false, "text": "create table event (\n id int,\n event_date date,\n type char(1));\n \n\ninsert into event\nvalues\n(1, '2022-01-01', 'X'),\n(1, '2022-01-03', 'X'),\n(1, '2022-01-05', 'Y'),\n(1, '2022-01-07', 'Y'),\n(1, '2022-01-09', 'X'),\n(1, '2022-01-11', 'X'),\n(1, '2022-01-15', 'Y');\n" }, { "answer_id": 74565759, "author": "OPislag", "author_id": 20524948, "author_profile": "https://Stackoverflow.com/users/20524948", "pm_score": 2, "selected": true, "text": "SELECT \n * \n ,ROW_NUMBER() OVER (PARTITION BY ID ORDER BY XDateTime ASC) AS 'Degree'\nFROM\n (SELECT \n *\n ,ROW_NUMBER() OVER (PARTITION BY YDateTime ORDER BY XDateTime ASC) AS 'dc'\n FROM\n (SELECT\n ID\n ,EventDateTime AS 'YDateTime'\n ,B.XDateTime\n ,DATEDIFF(SECOND, EventDateTime, B.XDateTime) AS 'Time'\n ,ROW_NUMBER() OVER (PARTITION BY B.XDateTime ORDER BY EventDateTime DESC) AS 'pc'\n \n FROM vw_A6Productivity AS \"A\"\n\n INNER JOIN\n (SELECT\n ID AS 'BID'\n ,EventDateTime AS 'XDateTime'\n \n FROM TABLE\n \n WHERE TYPE = 'X'\n \n GROUP BY \n ID\n ,EventDateTime\n ) AS \"B\"\n\n ON A.ID= B.BID\n\n WHERE \n EventDateTime < XDateTime -- Inner join filters for Nulls automatically\n AND STATUS = 'Y'\n \n ) AS \"C\"\n\n WHERE\n pc = 1\n \n ) AS \"D\"\n\nWHERE dc = 1;\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74468841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20413110/" ]
74,468,843
<p>I am doing deploys from specific machines. These are the same machines being used for development. This situation can cause some problems since the environment variables desired for deploys can be different from the ones to be used for development!</p> <p>When the engineer is developing, it is useful to have a <code>.zshrc</code> file with stuff like:</p> <pre><code>export TFR_RELEASE=&quot;my-instance-for-development&quot; export TFR_DEV=&quot;my-instance-for-development&quot; </code></pre> <p>However, the instance for the deploy is a different one!</p> <p>The project already has a <code>makefile</code> to help streamline things. One of the <code>make</code> commands is <code>make clean</code>:</p> <pre class="lang-bash prettyprint-override"><code>clean: rm -rf .shadow-cljs rm -rf node_modules rm -rf target rm -rf public/js </code></pre> <p>In order to make the developer aware on which instance is being used, I decided to add the last two lines:</p> <pre class="lang-bash prettyprint-override"><code>clean: rm -rf .shadow-cljs rm -rf node_modules rm -rf target rm -rf public/js echo &quot;TFR_DEV&quot; &quot;$(TFR_DEV)&quot; echo &quot;TFR_RELEASE&quot; &quot;$(TFR_RELEASE)&quot; </code></pre> <p>After executing <code>$ make clean</code>, the terminal returns:</p> <pre class="lang-bash prettyprint-override"><code>➜ make clean rm -rf .shadow-cljs rm -rf node_modules rm -rf target rm -rf public/js echo &quot;TFR_DEV&quot; &quot;my-instance-for-development&quot; TFR_DEV my-instance-for-development echo &quot;TFR_RELEASE&quot; &quot;my-instance-for-development&quot; TFR_RELEASE my-instance-for-development&quot; </code></pre> <p>If feels a bit repetitive the display of the relevant information... Since the <em>value</em> of the <em>variable</em> is being evaluated on the terminal's &quot;prompt&quot; and on the terminal's &quot;answer&quot;.</p> <p>Is there a better way to &quot;print&quot; it?</p> <p>My approach <strong>does not</strong> feel elegant.</p>
[ { "answer_id": 74469191, "author": "JHH", "author_id": 20127235, "author_profile": "https://Stackoverflow.com/users/20127235", "pm_score": 0, "selected": false, "text": "create table event (\n id int,\n event_date date,\n type char(1));\n \n\ninsert into event\nvalues\n(1, '2022-01-01', 'X'),\n(1, '2022-01-03', 'X'),\n(1, '2022-01-05', 'Y'),\n(1, '2022-01-07', 'Y'),\n(1, '2022-01-09', 'X'),\n(1, '2022-01-11', 'X'),\n(1, '2022-01-15', 'Y');\n" }, { "answer_id": 74565759, "author": "OPislag", "author_id": 20524948, "author_profile": "https://Stackoverflow.com/users/20524948", "pm_score": 2, "selected": true, "text": "SELECT \n * \n ,ROW_NUMBER() OVER (PARTITION BY ID ORDER BY XDateTime ASC) AS 'Degree'\nFROM\n (SELECT \n *\n ,ROW_NUMBER() OVER (PARTITION BY YDateTime ORDER BY XDateTime ASC) AS 'dc'\n FROM\n (SELECT\n ID\n ,EventDateTime AS 'YDateTime'\n ,B.XDateTime\n ,DATEDIFF(SECOND, EventDateTime, B.XDateTime) AS 'Time'\n ,ROW_NUMBER() OVER (PARTITION BY B.XDateTime ORDER BY EventDateTime DESC) AS 'pc'\n \n FROM vw_A6Productivity AS \"A\"\n\n INNER JOIN\n (SELECT\n ID AS 'BID'\n ,EventDateTime AS 'XDateTime'\n \n FROM TABLE\n \n WHERE TYPE = 'X'\n \n GROUP BY \n ID\n ,EventDateTime\n ) AS \"B\"\n\n ON A.ID= B.BID\n\n WHERE \n EventDateTime < XDateTime -- Inner join filters for Nulls automatically\n AND STATUS = 'Y'\n \n ) AS \"C\"\n\n WHERE\n pc = 1\n \n ) AS \"D\"\n\nWHERE dc = 1;\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74468843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9113679/" ]
74,468,869
<p>I have a non-uniform list as follows:</p> <pre><code>[['E', 'A', 'P'], ['E', 'A', 'X', 'P'], ['E', 'A', 'P'], ['P'], ['E', 'A', 'X', 'P'], ['E', 'A', 'P'], ['A', 'X', 'P'], ['E', 'A', 'P'], ['E', 'A', 'P'], ['E', 'A', 'X', 'P'], ['E', 'A', 'P'], ['E', 'A', 'P'], ['A', 'X', 'P'], </code></pre> <p>I would like to create a data frame from this, where each column represents the four possible letters <code>&quot;E&quot;</code>, <code>&quot;A&quot;</code>, <code>&quot;X&quot;</code> and <code>&quot;p&quot;</code> in a one-hot encoded manner - what is the most efficient way to go about this?</p>
[ { "answer_id": 74468901, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 2, "selected": true, "text": "lst = [\n [\"E\", \"A\", \"P\"],\n [\"E\", \"A\", \"X\", \"P\"],\n [\"E\", \"A\", \"P\"],\n [\"P\"],\n [\"E\", \"A\", \"X\", \"P\"],\n [\"E\", \"A\", \"P\"],\n [\"A\", \"X\", \"P\"],\n [\"E\", \"A\", \"P\"],\n [\"E\", \"A\", \"P\"],\n [\"E\", \"A\", \"X\", \"P\"],\n [\"E\", \"A\", \"P\"],\n [\"E\", \"A\", \"P\"],\n [\"A\", \"X\", \"P\"],\n]\n\ndf = pd.DataFrame({v: 1 for v in l} for l in lst).notna().astype(int)\nprint(df)\n" }, { "answer_id": 74468909, "author": "BENY", "author_id": 7964527, "author_profile": "https://Stackoverflow.com/users/7964527", "pm_score": 2, "selected": false, "text": "MultiLabelBinarizer" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74468869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2809834/" ]
74,468,911
<p>I would like to have a piece of JS which loops through a list-item series and for each list-item, it stores a unique attribute value (in this case, the href) and then inserts it as a data attribute to another element within the same list-item (in this case, the button). The JS which I have only applies the desired effect to the first list-item and not the whole series. Can my method be tweaked, or does it require surgery?</p> <pre><code>&lt;li class=&quot;productgrid--item&quot;&gt; &lt;a class=&quot;productitem--image-link&quot; href=&quot;www.link_one.com&quot;&gt;link one&lt;/a&gt; &lt;button class=&quot;atc-button--text&quot;&gt;button one&lt;/button&gt; &lt;/li&gt; &lt;li class=&quot;productgrid--item&quot;&gt; &lt;a class=&quot;productitem--image-link&quot; href=&quot;www.link_two.com&quot;&gt;link two&lt;/a&gt; &lt;button class=&quot;atc-button--text&quot;&gt;button two&lt;/button&gt; &lt;/li&gt; &lt;li class=&quot;productgrid--item&quot;&gt; &lt;a class=&quot;productitem--image-link&quot; href=&quot;www.link_three.com&quot;&gt;link three&lt;/a&gt; &lt;button class=&quot;atc-button--text&quot;&gt;button three&lt;/button&gt; &lt;/li&gt; </code></pre> <pre><code>document.querySelectorAll('.productgrid--item').forEach(function(node) { var anchorHref = document.querySelector('.productitem--image-link').getAttribute('href'); var addToCart = document.querySelector('.atc-button--text'); addToCart.setAttribute('data', anchorHref); }); </code></pre>
[ { "answer_id": 74468973, "author": "nrodic", "author_id": 551322, "author_profile": "https://Stackoverflow.com/users/551322", "pm_score": 3, "selected": true, "text": "forEach()" }, { "answer_id": 74469042, "author": "DCR", "author_id": 4398966, "author_profile": "https://Stackoverflow.com/users/4398966", "pm_score": 0, "selected": false, "text": " document.querySelectorAll('.productgrid--item').forEach(function(node) {\n var anchorHref = node.querySelector('.productitem--image-link').getAttribute('href');\n var addToCart = node.querySelector('.atc-button--text');\n addToCart.setAttribute('data', anchorHref);\n console.log(addToCart)\n});\n \n " } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74468911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15039096/" ]
74,468,931
<p>For example I have enitity Event with fields name, description etc. And then I want to add new field String &quot;photo&quot; that will be reference to a photo. So it is easy to add new field to entity, Hibernate will update the table of entity Event.</p> <p>Also I have POSTmethod saveEvent(Event event) in EventRestController class to save new Entity. Suppose, that I responsible only for backend, and I only need give endpoints to the frontend developers. My method createEvent() returns ReponseEntity. Suppose I changing my method to:</p> <pre><code>public ResponseEntity&lt;Event&gt; createEvent(@RequestBody Event event, @RequestParam(&quot;image&quot;) MultipartFile multipartFile) throws IOException { ... event.setPhoto(StringUtils.cleanPath(multipartFile.getOriginalFilename())); // save event in repo // upload image to directory event-photos/{eventId} // return event with photo field } </code></pre> <p>And then my GET method will be return ReponseEntity with field photo:</p> <pre><code>public ResponseEntity&lt;Event&gt; getEventById(@PathVariable(value = &quot;eventId&quot;) long eventId) { // returns Event with field &quot;photo&quot; } </code></pre> <p><strong>And here is my question. Is this enough to show image of this Event for frontend developers? Is this a good approach to link image reference to the Entity?</strong></p>
[ { "answer_id": 74468973, "author": "nrodic", "author_id": 551322, "author_profile": "https://Stackoverflow.com/users/551322", "pm_score": 3, "selected": true, "text": "forEach()" }, { "answer_id": 74469042, "author": "DCR", "author_id": 4398966, "author_profile": "https://Stackoverflow.com/users/4398966", "pm_score": 0, "selected": false, "text": " document.querySelectorAll('.productgrid--item').forEach(function(node) {\n var anchorHref = node.querySelector('.productitem--image-link').getAttribute('href');\n var addToCart = node.querySelector('.atc-button--text');\n addToCart.setAttribute('data', anchorHref);\n console.log(addToCart)\n});\n \n " } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74468931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17655569/" ]
74,468,933
<p>I have an orleans project with a stateful grain.</p> <p>Orleans seems to not deserialize private properties when hydrating the state for the grain.</p> <p>In the image below UserId gets deserialized but not State.</p> <p>Is there a way to get around this?</p> <p><a href="https://i.stack.imgur.com/uZgf9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uZgf9.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74572992, "author": "Kobus Pelser", "author_id": 9382623, "author_profile": "https://Stackoverflow.com/users/9382623", "pm_score": 3, "selected": true, "text": "public class Order\n{\n [JsonInclude]\n public OrderStates State{ get; private set; }\n}\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74468933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/834815/" ]
74,468,944
<p>t1:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>AccountName</th> <th>Date</th> <th>Amount</th> </tr> </thead> <tbody> <tr> <td>A1</td> <td>2022-06-30</td> <td>2</td> </tr> <tr> <td>A2</td> <td>2022-06-30</td> <td>1</td> </tr> <tr> <td>A3</td> <td>2022-06-30</td> <td></td> </tr> <tr> <td>A1</td> <td>2022-07-31</td> <td>4</td> </tr> <tr> <td>A2</td> <td>2022-07-31</td> <td>5</td> </tr> <tr> <td>A3</td> <td>2022-07-31</td> <td></td> </tr> </tbody> </table> </div> <p>I want to do a transformation on this table such that I fill in the &quot;Amount&quot; column of all rows with account name 'A3' and lets say that for each month group the 'A3' -&quot;Amount&quot; value is equal to (the 'A1' 'Amount' column + the 'A2' 'Amount' column), so the expected result table is:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>AccountName</th> <th>Date</th> <th>Amount</th> </tr> </thead> <tbody> <tr> <td>A1</td> <td>2022-06-30</td> <td>2</td> </tr> <tr> <td>A2</td> <td>2022-06-30</td> <td>1</td> </tr> <tr> <td>A3</td> <td>2022-06-30</td> <td>3</td> </tr> <tr> <td>A1</td> <td>2022-07-31</td> <td>4</td> </tr> <tr> <td>A2</td> <td>2022-07-31</td> <td>5</td> </tr> <tr> <td>A3</td> <td>2022-07-31</td> <td>9</td> </tr> </tbody> </table> </div> <p>The only way I can think of solving this is using multiple CTE's to separate each 'Date' value and using a case statements with multiple selects to get these values the using a union at the end:</p> <pre><code>with d1 as ( select * from t1 WHERE Date = '2022-06-30'), c1 as ( SELECT &quot;AccountName&quot;, &quot;Date&quot;, Case WHEN &quot;AccountName&quot; = 'A3' THEN (SELECT &quot;Amount&quot; FROM t1 WHERE &quot;AccountName&quot; = 'A1') + (SELECT &quot;Amount&quot; FROM t1 WHERE AccountName = 'A2') ELSE &quot;Amount&quot; END AS &quot;Amount&quot; FROM d1), d2 as ( select * from t1 WHERE Date = '2022-07-31'), c2 as ( SELECT &quot;AccountName&quot;, &quot;Date&quot;, Case WHEN &quot;AccountName&quot; = 'A3' THEN (SELECT &quot;Amount&quot; FROM t1 WHERE &quot;AccountName&quot; = 'A1') + (SELECT &quot;Amount&quot; FROM t1 WHERE AccountName = 'A2') ELSE &quot;Amount&quot; END AS &quot;Amount&quot; FROM d2) SELECT * FROM c1 Union SELECT * FROM c2 </code></pre> <p>Is a better way of doing this? As i have multiple row calculations based on other row values and on top of that multiple Distinct 'Date' values (24) for which i would have to create separate CTE's for. This would result in an extremely long sql script for me. Is there maybe a way to group by every 'Date' value in the date column to avoid making multiple CTE's for each 'Date' Value? Additionally is there a better way to construct the sums values for the 'Amount' values for all 'A3' rows rather that using multiple selects in side each 'CASE WHEN'? Thanks!</p>
[ { "answer_id": 74469093, "author": "Gerballi", "author_id": 20358885, "author_profile": "https://Stackoverflow.com/users/20358885", "pm_score": 0, "selected": false, "text": "update t1 t1update\nset amount = (\n select sum(amount) from t1 \n where \n extract(year from t1update.date date) || '-' || extract(month from t1update.date = \n extract(year from t1.date date) || '-' || extract(month from t1.date)\n)\nwhere t1update.amount = '' or t1update.amount is null\n" }, { "answer_id": 74469560, "author": "Bergi", "author_id": 1048572, "author_profile": "https://Stackoverflow.com/users/1048572", "pm_score": 1, "selected": false, "text": "SELECT \n \"AccountName\",\n \"Date\",\n (CASE WHEN \"AccountName\" = 'A3'\n THEN SUM(\"Amount\") FILTER (WHERE \"AccountName\" IN ('A1', 'A2')) OVER (PARTITION BY \"Date\")\n ELSE \"Amount\"\n END) AS \"Amount\"\nFROM t1\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74468944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20524832/" ]
74,468,954
<p>I'm very new to programming, only started learning python ~4 days ago and I'm having trouble figuring out how to print a user input as a string, in between other strings on the same line. Being so new to programming, I feel like the answer is staring me right in the face but I don't have the tools or the knowledge to figure it out lol.</p> <p><strong>what I'm trying to do is:</strong></p> <pre class="lang-none prettyprint-override"><code>Wow (PlayerName) that's cool </code></pre> <p><strong>so far what I have is:</strong></p> <pre class="lang-py prettyprint-override"><code>name = input(&quot;Name? &quot;) print(&quot;Wow&quot;) (print(name)) (print(&quot;that's cool&quot;)) </code></pre> <p>python came back with an error saying object 'NoneType' is not callable, so instead i tried to write it as a function and call that instead:</p> <pre><code>name = input(&quot;Name? &quot;) def name_call(): print(name) print(&quot;Wow&quot;) (name_call()) (print(&quot;that's cool&quot;)) </code></pre> <p>same issue, I tried various similar things, but at this point I'm just throwing darts</p> <p>I'm not 100% sure <strong>why</strong> neither of these worked, but I do know that it <strong>probably</strong> has something to do with me writing it incorrectly. I could just print the name on a new line, but I want to try and put them all on the same line if possible.</p>
[ { "answer_id": 74468983, "author": "Yogesh Thambidurai", "author_id": 18944758, "author_profile": "https://Stackoverflow.com/users/18944758", "pm_score": 0, "selected": false, "text": "name = input(\"Name? \")\n\nprint(\"Wow\")\nprint(name)\nprint(\"that's cool\")\n" }, { "answer_id": 74468988, "author": "Ricardo", "author_id": 16353662, "author_profile": "https://Stackoverflow.com/users/16353662", "pm_score": 0, "selected": false, "text": "val = 'name'\nprint(f\"Wow {val} that's cool.\")\n" }, { "answer_id": 74468989, "author": "Sheldon", "author_id": 6440589, "author_profile": "https://Stackoverflow.com/users/6440589", "pm_score": 0, "selected": false, "text": "format" }, { "answer_id": 74469016, "author": "Meer Modi", "author_id": 17710122, "author_profile": "https://Stackoverflow.com/users/17710122", "pm_score": 0, "selected": false, "text": "x = str(input('Name: '))\nprint('user entered {} as their name'.format(x))\n" }, { "answer_id": 74469019, "author": "Jason Alan Smith", "author_id": 20455489, "author_profile": "https://Stackoverflow.com/users/20455489", "pm_score": 2, "selected": false, "text": "name = input(\"Name? \")\nprint(f\"Wow {name} that's cool\")\n" }, { "answer_id": 74469187, "author": "Nindi", "author_id": 20505208, "author_profile": "https://Stackoverflow.com/users/20505208", "pm_score": 2, "selected": false, "text": "# Python3 code to demonstrate working of\n# Add Phrase in middle of String\n# Using split() + slicing + join()\n \n# initializing string\ntest_str = 'Wow that\\'s cool!'\n \n# printing original string\nprint(\"The original string is : \" + str(test_str))\n \n# initializing mid string\nmid_str = (input('Please input name = '))\n \n# splitting string to list\ntemp = test_str.split()\nmid_pos = len(temp) // 3\n \n# joining and construction using single line\nres = ' '.join(temp[:mid_pos] + [mid_str] + temp[mid_pos:])\n \n# printing result\nprint(\"Formulated String : \" + str(res))\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74468954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20525083/" ]