qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,534,196
<p>I'm learning data structures in C++;</p> <p>I've written a destructor for a linked list as follows:</p> <pre><code> ~List(){ Node* temporary = new Node; Node* node = head; while(node != nullptr){ temporary = node; node = node-&gt;next; delete temporary; } } </code></pre> <p>But then I realized that I can do:</p> <pre><code> ~List(){ Node* node = head; while(node != nullptr){ node = std::move(node-&gt;next); } } </code></pre> <p>Avoiding creating a temporary object, I tried it and worked fine, but I don't know if it is okay, I didn't find a destructor like this in any other place.</p>
[ { "answer_id": 74534365, "author": "Li-yao Xia", "author_id": 6863749, "author_profile": "https://Stackoverflow.com/users/6863749", "pm_score": 2, "selected": false, "text": "data S = S NP VP deriving Show\ndata N = Linguist | Chemist | Anglist | N ADJ N deriving Show\ndata NP = NP DET N deriving Show\ndata ADJ = Curious | Smart deriving Show\ndata DET = The | Some | Every deriving Show\ndata VP = Snores | Dreams | V NP deriving Show\ndata V = Cites | Corrects deriving Show\n" }, { "answer_id": 74534369, "author": "leftaroundabout", "author_id": 745903, "author_profile": "https://Stackoverflow.com/users/745903", "pm_score": 3, "selected": true, "text": "Map show print Map Map Map Show instance Show NP where\n show (NP d n) = \"NP (\"++show d++\") (\"++show n++\")\" -- not recommended\n show data S = S NP VP deriving (Show)\n...\ndata NP = NP DET N deriving (Show)\n...\n Eq Read data S = S NP VP deriving (Eq, Show, Read)\n...\ndata NP = NP DET N deriving (Eq, Show, Read)\n...\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15235825/" ]
74,534,226
<p>How to hide the label &quot;phone number&quot; in onfocus by simple onclick. Or may be ppreciated if can do in css. i tried but need a better solution.Let me know if you can.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="form-row"&gt; &lt;div class="input-data"&gt; &lt;select class="phone-select"&gt; &lt;option&gt;+91&lt;/option&gt; &lt;option&gt;+92&lt;/option&gt; &lt;/select&gt; &lt;input class="phone-input" type="text"&gt; &lt;div class="underline"&gt;&lt;/div&gt; &lt;div class="phone-label"&gt; &lt;label&gt;Phone No.&lt;/label&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74534277, "author": "angel.bonev", "author_id": 3768239, "author_profile": "https://Stackoverflow.com/users/3768239", "pm_score": 1, "selected": false, "text": ".phone-input:focus~div.phone-label label {\n display: none;\n} <div class=\"form-row\">\n <div class=\"input-data\">\n <select class=\"phone-select\">\n <option>+91</option>\n <option>+92</option>\n </select>\n\n <input class=\"phone-input\" type=\"text\">\n <div class=\"underline\"></div>\n <div class=\"phone-label\">\n <label>Phone No.</label>\n </div>\n </div>\n</div>" }, { "answer_id": 74534310, "author": "Szymon Gesele", "author_id": 19757254, "author_profile": "https://Stackoverflow.com/users/19757254", "pm_score": 1, "selected": true, "text": "input.phone-input:focus ~ .phone-label {\n display: none;\n}\n" }, { "answer_id": 74534413, "author": "Moussa Bistami", "author_id": 15628525, "author_profile": "https://Stackoverflow.com/users/15628525", "pm_score": 0, "selected": false, "text": ".field:focus .element-to-style .phone-input:focus + .phone-label {\n opacity: 1;\n}\n.phone-label {\n opacity: 0;\n}\n <div className=\"form-row\">\n <div className=\"input-data\">\n <select className=\"phone-select\">\n <option>+91</option>\n <option>+92</option>\n </select>\n <div>\n <input className=\"phone-input\" type=\"text\" />\n <div className=\"phone-label\">\n <label>Phone No.</label>\n </div>\n </div>\n <div className=\"underline\"></div>\n </div>\n </div>\n<style>\n.phone-input:focus + .phone-label {\n opacity: 1;\n}\n.phone-label {\n opacity: 0;\n}\n</style>\n</div>\n\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19171988/" ]
74,534,247
<pre><code>var password=123; var input; var opp=0; for(var t=0;t&lt;=2;t++){ if(password!=input &amp;&amp; t&lt;=2){ input=prompt(&quot;enter your password&quot;); } else{ opp++; } } if(opp!=0){ alert(&quot;success&quot;); } else if(opp&lt;1){ alert(&quot;fail&quot;); } </code></pre> <p>im expect it to be a password validation which can only try three times. but it will failed even with typing correct password in the third try.</p>
[ { "answer_id": 74534277, "author": "angel.bonev", "author_id": 3768239, "author_profile": "https://Stackoverflow.com/users/3768239", "pm_score": 1, "selected": false, "text": ".phone-input:focus~div.phone-label label {\n display: none;\n} <div class=\"form-row\">\n <div class=\"input-data\">\n <select class=\"phone-select\">\n <option>+91</option>\n <option>+92</option>\n </select>\n\n <input class=\"phone-input\" type=\"text\">\n <div class=\"underline\"></div>\n <div class=\"phone-label\">\n <label>Phone No.</label>\n </div>\n </div>\n</div>" }, { "answer_id": 74534310, "author": "Szymon Gesele", "author_id": 19757254, "author_profile": "https://Stackoverflow.com/users/19757254", "pm_score": 1, "selected": true, "text": "input.phone-input:focus ~ .phone-label {\n display: none;\n}\n" }, { "answer_id": 74534413, "author": "Moussa Bistami", "author_id": 15628525, "author_profile": "https://Stackoverflow.com/users/15628525", "pm_score": 0, "selected": false, "text": ".field:focus .element-to-style .phone-input:focus + .phone-label {\n opacity: 1;\n}\n.phone-label {\n opacity: 0;\n}\n <div className=\"form-row\">\n <div className=\"input-data\">\n <select className=\"phone-select\">\n <option>+91</option>\n <option>+92</option>\n </select>\n <div>\n <input className=\"phone-input\" type=\"text\" />\n <div className=\"phone-label\">\n <label>Phone No.</label>\n </div>\n </div>\n <div className=\"underline\"></div>\n </div>\n </div>\n<style>\n.phone-input:focus + .phone-label {\n opacity: 1;\n}\n.phone-label {\n opacity: 0;\n}\n</style>\n</div>\n\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20328653/" ]
74,534,252
<p><strong>Scenario</strong> I'm sending a request payload to the API that further calls the SMS service provider in the in-sequence flow, I need to share back the response from the SMS service provider as it is. The API works fine and I do receive SMS on phone but I'm unable to share back the response from the service provider in the out sequence flow.</p> <p>The response body from my SMS service provider is actually <strong>text</strong> as shown: <a href="https://i.stack.imgur.com/7gkwv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7gkwv.png" alt="enter image description here" /></a></p> <p>The Response header of SMS Service Provider looks like this: <a href="https://i.stack.imgur.com/yH9ap.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yH9ap.png" alt="enter image description here" /></a></p> <p><strong>API</strong></p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;api context=&quot;/mobilink&quot; name=&quot;MobilinkSmsApi&quot; xmlns=&quot;http://ws.apache.org/ns/synapse&quot;&gt; &lt;resource methods=&quot;POST&quot; uri-template=&quot;/send&quot;&gt; &lt;inSequence&gt; &lt;property action=&quot;remove&quot; name=&quot;TRANSPORT_HEADERS&quot; scope=&quot;axis2&quot;/&gt; &lt;property description=&quot;username&quot; expression=&quot;json-eval($.username)&quot; name=&quot;uri.var.username&quot; scope=&quot;default&quot; type=&quot;STRING&quot;/&gt; &lt;property description=&quot;password&quot; expression=&quot;json-eval($.password)&quot; name=&quot;uri.var.password&quot; scope=&quot;default&quot; type=&quot;STRING&quot;/&gt; &lt;property description=&quot;to&quot; expression=&quot;json-eval($.to)&quot; name=&quot;uri.var.to&quot; scope=&quot;default&quot; type=&quot;STRING&quot;/&gt; &lt;property description=&quot;from&quot; expression=&quot;json-eval($.from)&quot; name=&quot;uri.var.from&quot; scope=&quot;default&quot; type=&quot;STRING&quot;/&gt; &lt;property description=&quot;message&quot; expression=&quot;json-eval($.message)&quot; name=&quot;uri.var.message&quot; scope=&quot;default&quot; type=&quot;STRING&quot;/&gt; &lt;log level=&quot;full&quot;/&gt; &lt;call&gt; &lt;endpoint&gt; &lt;http method=&quot;post&quot; statistics=&quot;enable&quot; trace=&quot;enable&quot; uri-template=&quot;https://coXXXXX.XXXX.com/sendsms_url.html?Username={uri.var.username}&amp;amp;Password={uri.var.password}&amp;amp;From={uri.var.from}&amp;amp;To={uri.var.to}&amp;amp;Message={uri.var.message}&quot;&gt; &lt;suspendOnFailure&gt; &lt;initialDuration&gt;-1&lt;/initialDuration&gt; &lt;progressionFactor&gt;-1&lt;/progressionFactor&gt; &lt;maximumDuration&gt;0&lt;/maximumDuration&gt; &lt;/suspendOnFailure&gt; &lt;markForSuspension&gt; &lt;retriesBeforeSuspension&gt;0&lt;/retriesBeforeSuspension&gt; &lt;/markForSuspension&gt; &lt;/http&gt; &lt;/endpoint&gt; &lt;/call&gt; &lt;/inSequence&gt; &lt;outSequence&gt; &lt;log category=&quot;TRACE&quot; level=&quot;full&quot;/&gt; &lt;property description=&quot;Content-Type&quot; name=&quot;Content-Type&quot; scope=&quot;default&quot; type=&quot;STRING&quot; value=&quot;text/html&quot;/&gt; &lt;property name=&quot;messageType&quot; scope=&quot;axis2&quot; type=&quot;STRING&quot; value=&quot;text/html&quot;/&gt; &lt;respond/&gt; &lt;/outSequence&gt; &lt;faultSequence&gt; &lt;log category=&quot;ERROR&quot; level=&quot;full&quot;/&gt; &lt;/faultSequence&gt; &lt;/resource&gt; &lt;/api&gt; </code></pre> <p><strong>Question</strong> My Question is how to share back the response from the service provider in the out sequence? I tried to use property with value <strong>text/html</strong> and even used content-type as <strong>text/html</strong> but It didn't worked.</p>
[ { "answer_id": 74543270, "author": "Justin", "author_id": 9907182, "author_profile": "https://Stackoverflow.com/users/9907182", "pm_score": 1, "selected": false, "text": "<respond/> <call> <Send> <call> <respond/>" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7454536/" ]
74,534,254
<p>I'm trying to create an animation tween from 0 to 1:</p> <pre><code>final Tween&lt;double&gt; _tween = Tween(begin: 0, end: 1); late AnimationController _controller; late Animation&lt;double&gt; _animation; </code></pre> <p>And for some reason, sometimes I need to call <code>_controller.reverse()</code> or <code>_controller.forward()</code>, and my <code>animation.value</code> runs from 0 to 1 then from 1 to 0.</p> <p>How do I always get <code>animation.value</code> to run from 0 to 1?</p>
[ { "answer_id": 74543270, "author": "Justin", "author_id": 9907182, "author_profile": "https://Stackoverflow.com/users/9907182", "pm_score": 1, "selected": false, "text": "<respond/> <call> <Send> <call> <respond/>" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9618445/" ]
74,534,300
<p>I am new to dbt and in BigQuery I can query partitioned tables in a large dataset by using an asterix. e.g.</p> <pre><code>select * from x.ads_d_* </code></pre> <p>The asterix represents the year and month e.g. 202211. How do I create a source for this in dbt. If I use the code-gen package it creates a table for every month but I do not want to update it every month.</p> <p>I read about incremental datasources but I am not sure if this is what I need? Can somebody point me in the right direction.</p> <p>Adding the asterix in .yml sources definition does not seems to work.</p> <p>schema.yml</p> <pre><code>version: 2 sources: - name: funnel_io_ads tables: - name: ad - schema: ad_d_* </code></pre> <p><a href="https://i.stack.imgur.com/TpzWq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TpzWq.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74534873, "author": "Cylldby", "author_id": 15062605, "author_profile": "https://Stackoverflow.com/users/15062605", "pm_score": 0, "selected": false, "text": "- identifier: ad_d_*\n" }, { "answer_id": 74546156, "author": "Paddy Alton", "author_id": 9044370, "author_profile": "https://Stackoverflow.com/users/9044370", "pm_score": 2, "selected": true, "text": "* YYYYMMDD YYYYMM SELECT * FROM `ad_d_*`\n ad_d ad_d_20180201 ad_d_2018 sources:\n - name: funnel_io_ads\n database: <your GCP project ID>\n schema: funnel_io_ads\n tables:\n - name: ad\n identifier: ad_d_*\n {{ source('funnel_io_ads', 'ad') }}" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2785289/" ]
74,534,304
<p>With the following HTML and CSS I can't seem to be able to change the text color of the hyperlinks in blue or purple? What am I missing?</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>nav ul { /* Navbar unordered */ list-style: none; text-align: center; background-color: #495e57; border-radius: 10px; } nav li { /* Navbar ordered */ display: inline-block; padding: 20px; font-size: 1.5rem; border-radius: 10px; } nav li:hover { /* Navbar on mouse hover */ background-color: #1f2926; color: white; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;nav&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="index.html"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="menu.html"&gt;Menu&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="book.html"&gt;Book&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="about.html"&gt;About&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt;</code></pre> </div> </div> </p> <p>I have tried making using of !important to no avail. The only successful method I found is wrapping it in the HTML code itself as such:</p> <p><code>&lt;li&gt;&lt;a style=&quot;color: white&quot; href=&quot;index.html&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;</code></p>
[ { "answer_id": 74534363, "author": "Cédric", "author_id": 17684809, "author_profile": "https://Stackoverflow.com/users/17684809", "pm_score": 1, "selected": true, "text": "li a a a { \n color: white;\n}\n nav ul {\n list-style: none;\n text-align: center;\n background-color: #495e57;\n border-radius: 10px;\n}\n\nnav li {\n display: inline-block;\n padding: 20px;\n font-size: 1.5rem;\n border-radius: 10px;\n}\n\nnav li:hover {\n background-color: #1f2926;\n}\n\na {\n color: white;\n} <nav>\n <ul>\n <li><a href=\"index.html\">Home</a></li>\n <li><a href=\"menu.html\">Menu</a></li>\n <li><a href=\"book.html\">Book</a></li>\n <li><a href=\"about.html\">About</a></li>\n </ul>\n</nav> li nav li:hover a { \n color: white;\n}\n nav ul {\n list-style: none;\n text-align: center;\n background-color: #495e57;\n border-radius: 10px;\n}\n\nnav li {\n display: inline-block;\n padding: 20px;\n font-size: 1.5rem;\n border-radius: 10px;\n}\n\nnav li:hover {\n background-color: #1f2926;\n}\n\nnav li:hover a {\n color: white;\n} <nav>\n <ul>\n <li><a href=\"index.html\">Home</a></li>\n <li><a href=\"menu.html\">Menu</a></li>\n <li><a href=\"book.html\">Book</a></li>\n <li><a href=\"about.html\">About</a></li>\n </ul>\n</nav>" }, { "answer_id": 74534462, "author": "human bean", "author_id": 17186475, "author_profile": "https://Stackoverflow.com/users/17186475", "pm_score": 2, "selected": false, "text": "a color inherit li nav ul {\n /* Navbar unordered */\n list-style: none;\n text-align: center;\n background-color: #495e57;\n border-radius: 10px;\n}\n\nnav li {\n /* Navbar ordered */\n /* set default color to blue, so that anchor tags inherit this */\n color: blue;\n display: inline-block;\n padding: 20px;\n font-size: 1.5rem;\n border-radius: 10px;\n}\n\nnav li:hover {\n /* Navbar on mouse hover */\n background-color: #1f2926;\n color: white;\n}\n\nnav a {\n /* anchor tags should inherit color of parent */\n color: inherit;\n} <body>\n <nav>\n <ul>\n <li><a href=\"index.html\">Home</a></li>\n <li><a href=\"menu.html\">Menu</a></li>\n <li><a href=\"book.html\">Book</a></li>\n <li><a href=\"about.html\">About</a></li>\n </ul>\n </nav>\n</body>" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20573306/" ]
74,534,359
<p>I still very new using GGPLOT, but ive created the following graphic in which i would like to switch the colors blue and red. Should be simple enough but i cannot figure it out.</p> <pre><code>df &lt;- structure(list(Sex = c(&quot;M&quot;, &quot;M&quot;, &quot;M&quot;, &quot;M&quot;, &quot;M&quot;, &quot;M&quot;, &quot;M&quot;, &quot;W&quot;, &quot;W&quot;, &quot;W&quot;, &quot;W&quot;, &quot;W&quot;, &quot;W&quot;, &quot;W&quot;), age_cat = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L), .Label = c(&quot;&lt;40&quot;, &quot;41-50&quot;, &quot;51-60&quot;, &quot;61-70&quot;, &quot;71-80&quot;, &quot;81-90&quot;, &quot;90+&quot;), class = &quot;factor&quot;), DD = c(42L, 88L, 289L, 558L, 527L, 174L, 22L, 27L, 36L, 206L, 347L, 321L, 160L, 29L), pop = c(36642L, 16327L, 20232L, 18068L, 14025L, 5555L, 1293L, 35887L, 16444L, 20178L, 17965L, 14437L, 7150L, 2300L), proportion = c(0.114622564270509, 0.538984504195504, 1.428430209569, 3.08833296435687, 3.75757575757576, 3.13231323132313, 1.7014694508894, 0.0752361579402012, 0.218924835806373, 1.02091386658737, 1.9315335374339, 2.22345362609961, 2.23776223776224, 1.26086956521739 ), lower = c(0.082621962613957, 0.432499099174075, 1.26946115577044, 2.8408823120445, 3.44891013496043, 2.69000601596679, 1.06929480146528, 0.0495867729368698, 0.153377923598767, 0.886828947142727, 1.73530361873497, 1.98914206124244, 1.90751612365318, 0.846006018532107 ), upper = c(0.154905173671422, 0.663628389658291, 1.6015714811397, 3.35102939015014, 4.08561035940466, 3.6247050150149, 2.56476800800746, 0.10944592449968, 0.302956684874059, 1.16937842460687, 2.14353263545661, 2.47728262910991, 2.60770261266057, 1.80583393021473)), row.names = c(NA, -14L), class = &quot;data.frame&quot;) </code></pre> <p>Below is the script i've used, in which i get (sex = M) in red and (sex = W)in bliue. <a href="https://i.stack.imgur.com/dbp7F.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dbp7F.jpg" alt="enter image description here" /></a></p> <pre><code>ggplot(data = prevalence2021GGPLOT, aes(x = age_cat, y = proportion, color = Sex))+ geom_point()+ labs(title=&quot;Prevalence 2021&quot;, y=&quot;Prevalence (%)&quot;, x=&quot;Age category&quot;) + geom_errorbar(aes(ymin=(lower), ymax=(upper)), width=.2) + theme_bw()+ geom_line(aes(group = unlist(Sex))) </code></pre> <p>How do i make sex = M blue and sex = W red??</p>
[ { "answer_id": 74534363, "author": "Cédric", "author_id": 17684809, "author_profile": "https://Stackoverflow.com/users/17684809", "pm_score": 1, "selected": true, "text": "li a a a { \n color: white;\n}\n nav ul {\n list-style: none;\n text-align: center;\n background-color: #495e57;\n border-radius: 10px;\n}\n\nnav li {\n display: inline-block;\n padding: 20px;\n font-size: 1.5rem;\n border-radius: 10px;\n}\n\nnav li:hover {\n background-color: #1f2926;\n}\n\na {\n color: white;\n} <nav>\n <ul>\n <li><a href=\"index.html\">Home</a></li>\n <li><a href=\"menu.html\">Menu</a></li>\n <li><a href=\"book.html\">Book</a></li>\n <li><a href=\"about.html\">About</a></li>\n </ul>\n</nav> li nav li:hover a { \n color: white;\n}\n nav ul {\n list-style: none;\n text-align: center;\n background-color: #495e57;\n border-radius: 10px;\n}\n\nnav li {\n display: inline-block;\n padding: 20px;\n font-size: 1.5rem;\n border-radius: 10px;\n}\n\nnav li:hover {\n background-color: #1f2926;\n}\n\nnav li:hover a {\n color: white;\n} <nav>\n <ul>\n <li><a href=\"index.html\">Home</a></li>\n <li><a href=\"menu.html\">Menu</a></li>\n <li><a href=\"book.html\">Book</a></li>\n <li><a href=\"about.html\">About</a></li>\n </ul>\n</nav>" }, { "answer_id": 74534462, "author": "human bean", "author_id": 17186475, "author_profile": "https://Stackoverflow.com/users/17186475", "pm_score": 2, "selected": false, "text": "a color inherit li nav ul {\n /* Navbar unordered */\n list-style: none;\n text-align: center;\n background-color: #495e57;\n border-radius: 10px;\n}\n\nnav li {\n /* Navbar ordered */\n /* set default color to blue, so that anchor tags inherit this */\n color: blue;\n display: inline-block;\n padding: 20px;\n font-size: 1.5rem;\n border-radius: 10px;\n}\n\nnav li:hover {\n /* Navbar on mouse hover */\n background-color: #1f2926;\n color: white;\n}\n\nnav a {\n /* anchor tags should inherit color of parent */\n color: inherit;\n} <body>\n <nav>\n <ul>\n <li><a href=\"index.html\">Home</a></li>\n <li><a href=\"menu.html\">Menu</a></li>\n <li><a href=\"book.html\">Book</a></li>\n <li><a href=\"about.html\">About</a></li>\n </ul>\n </nav>\n</body>" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16508809/" ]
74,534,392
<p>what does it means declare variables with the symbol <strong>&quot;#&quot;</strong> in javascript? I am learning about builder pattern and I found it with some examples. Also I saw that the variables are calls with this.#color.</p> <p><strong>#</strong> symbol is different to declare variable with let or var? what is the difference?</p> <p>thanks</p> <pre><code>class Car { #color = null #spoiler = null #fuelType = null #productionDate = null } </code></pre>
[ { "answer_id": 74534430, "author": "Amir Popovich", "author_id": 3213034, "author_profile": "https://Stackoverflow.com/users/3213034", "pm_score": 3, "selected": true, "text": "class ClassWithPrivate {\n #privateField;\n #privateFieldWithInitializer = 42;\n\n #privateMethod() {\n // …\n }\n\n static #privateStaticField;\n static #privateStaticFieldWithInitializer = 42;\n\n static #privateStaticMethod() {\n // …\n }\n}\n" }, { "answer_id": 74534458, "author": "Barkermn01", "author_id": 493804, "author_profile": "https://Stackoverflow.com/users/493804", "pm_score": 0, "selected": false, "text": "class Car{\n #color = \"#FFF\";\n // a getter to read the value\n get color() { return this.color; }\n}\n class Car{\n #color = \"#FFF\";\n // a getter to read the value\n get color() { return this.color; }\n\n #setColor = (color) => {this.#color = color}\n \n passColorSetter = (fn) => {\n fn(this.#setColor); // this is not allowed \n // as the referenced function in fn is not defined in this class\n }\n}\n function Car{\n let color = \"#FFF\";\n this.getColor = function(){ return color; }\n\n let setColor = (c) => {color = c}\n \n passColorSetter = (fn) => {\n fn(setColor); // this would work\n // and allow the fn referenced function to call setColor\n }\n\n}\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18797770/" ]
74,534,434
<pre><code>library IEEE; use IEEE.STD_LOGIC_1164.ALL; entity equation_tb is end equation_tb; architecture Behavioral of equation_tb is signal x, y, z, t, w : std_logic; signal F : std_logic; begin UUT : entity work.equation port map (x, y, z, t, w, F); process begin x &lt;= '0', '1' after 160 ns; y &lt;= '0', '1' after 80 ns, '0' after 160 ns, '1' after 240 ns; z &lt;= '0', '1' after 40 ns, '0' after 80 ns, '1' after 120 ns, '0' after 160 ns, '1' after 200 ns, '0' after 240 ns, '1' after 280 ns; t &lt;= '0', '1' after 20 ns, '0' after 40 ns, '1' after 60 ns, '0' after 80 ns, '1' after 100 ns, '0' after 120 ns, '1' after 140 ns, '0' after 160 ns, '0' after 180 ns, '1' after 200 ns, '0' after 220 ns, '1' after 240 ns, '0' after 260 ns, '1' after 280 ns, '0' after 300 ns; end process; end Behavioral; </code></pre> <p>Hello, is there any way to write this in a simpler way. After &quot;t&quot; I have to write this for &quot;w&quot; and it will change in every 10ns, hence the line will be very long.</p> <p>I tought about using for loop or if, but couldn't know what to do.</p>
[ { "answer_id": 74535802, "author": "the busybee", "author_id": 11294831, "author_profile": "https://Stackoverflow.com/users/11294831", "pm_score": 0, "selected": false, "text": "wait architecture Behavioral of equation_tb is\n signal x : std_logic := '0';\n signal y : std_logic := '0';\n signal z : std_logic := '0';\n signal t : std_logic := '0';\n signal w : std_logic := '0';\n signal F : std_logic;\n \nbegin\n UUT : entity work.equation port map (x, y, z, t, w, F);\n\n process\n begin\n wait for 160 ns;\n x <= not x;\n end process;\n\n process\n begin\n wait for 80 ns;\n y <= not y;\n end process;\n\n process\n begin\n wait for 40 ns;\n z <= not z;\n end process;\n\n process\n begin\n wait for 20 ns;\n t <= not t;\n end process;\n\n process\n begin\n wait for 10 ns;\n w <= not w;\n end process;\n\nend Behavioral;\n t '0' after 160 ns, '0' after 180 ns" }, { "answer_id": 74540195, "author": "user16145658", "author_id": 16145658, "author_profile": "https://Stackoverflow.com/users/16145658", "pm_score": 1, "selected": false, "text": "architecture foo of equation_tb is\n signal x, y, z, t : std_logic := '0';\n signal w, F : std_logic;\n use ieee.numeric_std.all;\n signal counter: unsigned (3 downto 0) := (others => '0');\nbegin\nUUT: entity work.equation port map (x, y, z, t, w, F);\n\nSTIMULI:\n process\n begin\n for i in 0 to 15 loop\n (x, y, z, t) <= std_logic_vector(counter);\n counter <= counter + 1;\n wait for 20 ns;\n end loop;\n wait;\n end process;\nend architecture;\n entity" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18406524/" ]
74,534,441
<p>I was looking for how to disable button using JS and I find this and it works:</p> <pre><code>&lt;button id=&quot;startbtn&quot; onclick=&quot;this.disabled=true; pausebtn.disabled=false; stopbtn.disabled=false;&quot;&gt;Start&lt;/button&gt; </code></pre> <p>but I want to disable it using addEventListener() method instead of doing it directly on the html div, but it is not working, is it posible?</p> <pre><code>let start1 = document.getElementById('startbtn'); start1.addEventListener('click', start); start1.addEventListener('click', this.disabled = true); </code></pre> <p>Obs: the second line in the code above starts the &quot;start&quot; function which is a cronometer.</p>
[ { "answer_id": 74534504, "author": "Moussa Bistami", "author_id": 15628525, "author_profile": "https://Stackoverflow.com/users/15628525", "pm_score": 1, "selected": true, "text": "Element.currentTarget.setAttribute(name, value) let start1 = document.getElementById('startbtn');\nstart1.addEventListener('click', start);\nstart1.addEventListener('click', (e) => e.currentTarget.setAttribute('disabled', true));\n" }, { "answer_id": 74534506, "author": "Brother58697", "author_id": 17804016, "author_profile": "https://Stackoverflow.com/users/17804016", "pm_score": 2, "selected": false, "text": "currentTarget start1.addEventListener('click',() => start1.disabled = true);\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20573325/" ]
74,534,455
<p>I have a problem, I need my Android app to stay active when it's in the background.</p> <p>Application.runInBackground = true;</p>
[ { "answer_id": 74534504, "author": "Moussa Bistami", "author_id": 15628525, "author_profile": "https://Stackoverflow.com/users/15628525", "pm_score": 1, "selected": true, "text": "Element.currentTarget.setAttribute(name, value) let start1 = document.getElementById('startbtn');\nstart1.addEventListener('click', start);\nstart1.addEventListener('click', (e) => e.currentTarget.setAttribute('disabled', true));\n" }, { "answer_id": 74534506, "author": "Brother58697", "author_id": 17804016, "author_profile": "https://Stackoverflow.com/users/17804016", "pm_score": 2, "selected": false, "text": "currentTarget start1.addEventListener('click',() => start1.disabled = true);\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17351668/" ]
74,534,469
<p>I am currently try to have the data like this (The <code>...</code> just means there are more lines, no need to post the entire file here.)</p> <pre><code>376 932 noms sommets 0000 Abbesses 0001 Alexandre Dumas 0002 Alma Marceau ... 0375 Étienne Marcel coord sommets 0000 308 536 0001 472 386 0002 193 404 ... 0375 347 412 arcs values 0 238 41 0 159 46 1 12 36 1 235 44 ... 367 366 120.0 </code></pre> <p>The data should be like this when converted to csv, the data should has three columns</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>nom</th> <th>sommets</th> <th>coord sommets</th> </tr> </thead> <tbody> <tr> <td>0000</td> <td>Abbesses</td> <td>308 536</td> </tr> </tbody> </table> </div> <p>However, everything in the data is a straight line and hard to deal with. What is the solution for this. I try to convert it from txt to csv.</p>
[ { "answer_id": 74534504, "author": "Moussa Bistami", "author_id": 15628525, "author_profile": "https://Stackoverflow.com/users/15628525", "pm_score": 1, "selected": true, "text": "Element.currentTarget.setAttribute(name, value) let start1 = document.getElementById('startbtn');\nstart1.addEventListener('click', start);\nstart1.addEventListener('click', (e) => e.currentTarget.setAttribute('disabled', true));\n" }, { "answer_id": 74534506, "author": "Brother58697", "author_id": 17804016, "author_profile": "https://Stackoverflow.com/users/17804016", "pm_score": 2, "selected": false, "text": "currentTarget start1.addEventListener('click',() => start1.disabled = true);\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11315832/" ]
74,534,513
<p>I am relatively new to Vega Lite and have a question that I'm hoping is fairly straightforward.</p> <p>I have a parameter array called myExtent that I've hard coded to [0, 6]. I'd like to be able to set the upper value of the array based on the data. Here, because the 4th row has &quot;flag&quot; = 1, I'd like to set the upper limit to the &quot;score&quot; for that row, or 6. So,</p> <p>{&quot;name&quot;: &quot;myExtent&quot;, &quot;value&quot;: [0, (value of score for the row in the dataset where flag = 1)]}</p> <p>Is something like this possible, or is there an alternative way I should be thinking about this?</p> <p>`</p> <pre><code>{&quot;$schema&quot;: &quot;https://vega.github.io/schema/vega-lite/v5.json&quot;, &quot;params&quot;: [ {&quot;name&quot;: &quot;myExtent&quot;, &quot;value&quot;: [0, 6]} ], &quot;data&quot;: { &quot;values&quot;: [ {&quot;game&quot;: 1, &quot;score&quot;: 2, &quot;flag&quot;: 0}, {&quot;game&quot;: 2, &quot;score&quot;: 4, &quot;flag&quot;: 0}, {&quot;game&quot;: 3, &quot;score&quot;: 5, &quot;flag&quot;: 0}, {&quot;game&quot;: 4, &quot;score&quot;: 6, &quot;flag&quot;: 1}, {&quot;game&quot;: 5, &quot;score&quot;: 9, &quot;flag&quot;: 0} ] }, &quot;mark&quot;: {&quot;type&quot;: &quot;area&quot;}, &quot;transform&quot;: [ { &quot;density&quot;: &quot;score&quot;, &quot;extent&quot;: {&quot;signal&quot;: &quot;myExtent&quot;} } ], &quot;encoding&quot;: { &quot;x&quot;: {&quot;field&quot;: &quot;value&quot;, &quot;type&quot;: &quot;quantitative&quot;, &quot;scale&quot;: {&quot;domain&quot;: [0, 10]}}, &quot;y&quot;: {&quot;field&quot;: &quot;density&quot;, &quot;type&quot;: &quot;quantitative&quot;} } } </code></pre> <p>`</p> <p>Just to get started, I have tried something like this:</p> <p>`</p> <pre><code> &quot;params&quot;: [ {&quot;name&quot;: &quot;upperLimit&quot;, &quot;value&quot;: 6}, {&quot;name&quot;: &quot;myExtent&quot;, &quot;value&quot;: [0, {&quot;expr&quot;: &quot;upperLimit&quot;}]} ], </code></pre> <p>`</p> <p>However, that (a) doesn't seem to work and (b) doesn't (yet) get at how to set the upperLimit parameter to the score for row 4.</p>
[ { "answer_id": 74534504, "author": "Moussa Bistami", "author_id": 15628525, "author_profile": "https://Stackoverflow.com/users/15628525", "pm_score": 1, "selected": true, "text": "Element.currentTarget.setAttribute(name, value) let start1 = document.getElementById('startbtn');\nstart1.addEventListener('click', start);\nstart1.addEventListener('click', (e) => e.currentTarget.setAttribute('disabled', true));\n" }, { "answer_id": 74534506, "author": "Brother58697", "author_id": 17804016, "author_profile": "https://Stackoverflow.com/users/17804016", "pm_score": 2, "selected": false, "text": "currentTarget start1.addEventListener('click',() => start1.disabled = true);\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20567568/" ]
74,534,517
<p>I would like to create a new column in the data frame that will search for the alphabet in a column. Based on it, it will then search for the next number and copy the alphabet and number into newly extracted column. Example:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Month</th> <th>Sem_Year</th> </tr> </thead> <tbody> <tr> <td>2020-04-01</td> <td>H1 2020</td> </tr> <tr> <td>2020-05-01</td> <td>2020 H1</td> </tr> <tr> <td>2020-06-01</td> <td>H1 2020</td> </tr> <tr> <td>2020-07-01</td> <td>H2 2020</td> </tr> <tr> <td>2020-08-01</td> <td>H2 2020</td> </tr> <tr> <td>2020-09-01</td> <td>2020 H2</td> </tr> <tr> <td>2020-10-01</td> <td>2020 H2</td> </tr> <tr> <td>2020-11-01</td> <td>H2 2020</td> </tr> <tr> <td>2020-12-01</td> <td>H2 2020</td> </tr> <tr> <td>2021-01-01</td> <td>H1 2021</td> </tr> <tr> <td>2021-02-01</td> <td>H1 2021</td> </tr> </tbody> </table> </div> <p>Now I want to search for the alphabet H in the second column and extract the alphabet and number tagged along with it. Example:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Month</th> <th>Sem_Year</th> <th>Sem</th> </tr> </thead> <tbody> <tr> <td>2020-04-01</td> <td>H1 2020</td> <td>H1</td> </tr> <tr> <td>2020-05-01</td> <td>2020 H1</td> <td>H1</td> </tr> <tr> <td>2020-06-01</td> <td>H1 2020</td> <td>H1</td> </tr> <tr> <td>2020-07-01</td> <td>H2 2020</td> <td>H2</td> </tr> <tr> <td>2020-08-01</td> <td>H2 2020</td> <td>H2</td> </tr> <tr> <td>2020-09-01</td> <td>2020 H2</td> <td>H2</td> </tr> <tr> <td>2020-10-01</td> <td>2020 H2</td> <td>H2</td> </tr> <tr> <td>2020-11-01</td> <td>H2 2020</td> <td>H2</td> </tr> <tr> <td>2020-12-01</td> <td>H2 2020</td> <td>H2</td> </tr> <tr> <td>2021-01-01</td> <td>H1 2021</td> <td>H1</td> </tr> <tr> <td>2021-02-01</td> <td>H1 2021</td> <td>H1</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74534662, "author": "user19077881", "author_id": 19077881, "author_profile": "https://Stackoverflow.com/users/19077881", "pm_score": 2, "selected": true, "text": "H\\d df['Sem'] = df['Sem_year'].str.extract(\"(H\\d)\")\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14363224/" ]
74,534,557
<p>I have an in put xml file which contain 20&lt;.entry&gt; element. the value of entry should be convert into word like &quot;Twenty&quot; I want to convert till number 100.</p> <p>Input:</p> <pre><code>&lt;input&gt; &lt;entry&gt;46&lt;/entry&gt; &lt;/input&gt; </code></pre> <p>XSLT:</p> <pre><code>&lt;xsl:stylesheet version=&quot;2.0&quot; xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot;&gt; &lt;xsl:output method=&quot;text&quot; encoding=&quot;UTF-8&quot; /&gt; &lt;xsl:variable name=&quot;numbertoword&quot;&gt; &lt;number Num=&quot;1&quot; Word=&quot;One &quot;/&gt; &lt;number Num=&quot;2&quot; Word=&quot;Two &quot;/&gt; &lt;number Num=&quot;3&quot; Word=&quot;Three &quot;/&gt; &lt;number Num=&quot;4&quot; Word=&quot;Four &quot;/&gt; &lt;number Num=&quot;5&quot; Word=&quot;Five &quot;/&gt; &lt;number Num=&quot;6&quot; Word=&quot;Six &quot;/&gt; &lt;number Num=&quot;7&quot; Word=&quot;Seven &quot;/&gt; &lt;number Num=&quot;8&quot; Word=&quot;Eight &quot;/&gt; &lt;number Num=&quot;9&quot; Word=&quot;Nine &quot;/&gt; &lt;number Num=&quot;11&quot; Word=&quot;Eleven &quot; /&gt; &lt;number Num=&quot;12&quot; Word=&quot;Twelve &quot; /&gt; &lt;number Num=&quot;13&quot; Word=&quot;Thirteen &quot; /&gt; &lt;number Num=&quot;14&quot; Word=&quot;Fourteen &quot; /&gt; &lt;number Num=&quot;15&quot; Word=&quot;Fifteen &quot; /&gt; &lt;number Num=&quot;16&quot; Word=&quot;Sixteen &quot; /&gt; &lt;number Num=&quot;17&quot; Word=&quot;Seventeen &quot; /&gt; &lt;number Num=&quot;18&quot; Word=&quot;Eighteen &quot; /&gt; &lt;number Num=&quot;19&quot; Word=&quot;Nineteen &quot; /&gt; &lt;number Num=&quot;20&quot; Word=&quot;Twenty&quot; /&gt; &lt;number Num=&quot;21&quot; Word=&quot;Twenty one&quot;/&gt; &lt;number Num=&quot;22&quot; Word=&quot;Twenty two&quot;/&gt; &lt;number Num=&quot;23&quot; Word=&quot;Twenty three&quot;/&gt; &lt;number Num=&quot;24&quot; Word=&quot;Twenty four&quot;/&gt; &lt;number Num=&quot;25&quot; Word=&quot;Twenty five&quot;/&gt; &lt;number Num=&quot;26&quot; Word=&quot;Twenty six&quot;/&gt; &lt;number Num=&quot;27&quot; Word=&quot;Twenty seven&quot;/&gt; &lt;number Num=&quot;28&quot; Word=&quot;Twenty eight&quot;/&gt; &lt;number Num=&quot;29&quot; Word=&quot;Twenty nine&quot;/&gt; &lt;number Num=&quot;30&quot; Word=&quot;Thirty &quot; /&gt; &lt;number Num=&quot;31&quot; Word=&quot;Thirty one&quot; /&gt; &lt;number Num=&quot;32&quot; Word=&quot;Thirty two&quot; /&gt; &lt;number Num=&quot;33&quot; Word=&quot;Thirty three&quot; /&gt; &lt;number Num=&quot;34&quot; Word=&quot;Thirty four&quot; /&gt; &lt;number Num=&quot;35&quot; Word=&quot;Thirty five&quot; /&gt; &lt;number Num=&quot;36&quot; Word=&quot;Thirty six&quot; /&gt; &lt;number Num=&quot;37&quot; Word=&quot;Thirty seven&quot; /&gt; &lt;number Num=&quot;38&quot; Word=&quot;Thirty eight&quot; /&gt; &lt;number Num=&quot;39&quot; Word=&quot;Thirty nine&quot; /&gt; &lt;number Num=&quot;40&quot; Word=&quot;Forty &quot; /&gt; &lt;number Num=&quot;41&quot; Word=&quot;Forty one&quot; /&gt; &lt;number Num=&quot;42&quot; Word=&quot;Forty two&quot; /&gt; &lt;number Num=&quot;43&quot; Word=&quot;Forty three&quot; /&gt; &lt;number Num=&quot;44&quot; Word=&quot;Forty four&quot; /&gt; &lt;number Num=&quot;45&quot; Word=&quot;Forty five&quot; /&gt; &lt;number Num=&quot;46&quot; Word=&quot;Forty six&quot; /&gt; &lt;number Num=&quot;47&quot; Word=&quot;Forty seven&quot; /&gt; &lt;number Num=&quot;48&quot; Word=&quot;Forty eight&quot; /&gt; &lt;number Num=&quot;49&quot; Word=&quot;Forty nine&quot; /&gt; &lt;number Num=&quot;50&quot; Word=&quot;Fifty &quot; /&gt; &lt;number Num=&quot;10&quot; Word=&quot;Ten &quot; /&gt; &lt;number Num=&quot;20&quot; Word=&quot;Twenty &quot; /&gt; &lt;number Num=&quot;60&quot; Word=&quot;Sixty &quot; /&gt; &lt;number Num=&quot;70&quot; Word=&quot;Seventy &quot; /&gt; &lt;number Num=&quot;80&quot; Word=&quot;Eighty &quot; /&gt; &lt;number Num=&quot;90&quot; Word=&quot;Ninety &quot; /&gt; &lt;/xsl:variable&gt; &lt;xsl:template match=&quot;/input&quot;&gt; &lt;xsl:for-each select=&quot;entry&quot;&gt; &lt;xsl:value-of select=&quot;$numbertoword/number[@Num = current()]/@Word&quot;/&gt; &lt;/xsl:for-each&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p>Output: Fourty Six</p> <p>I have taken word number into variable from which i comparing number from my input file and behalf of them i am getting right output but I want made my output more dynamic.</p>
[ { "answer_id": 74534662, "author": "user19077881", "author_id": 19077881, "author_profile": "https://Stackoverflow.com/users/19077881", "pm_score": 2, "selected": true, "text": "H\\d df['Sem'] = df['Sem_year'].str.extract(\"(H\\d)\")\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12111629/" ]
74,534,560
<p>This is my code in python whenever I click the start button it automatically stops by the way I am using replit IDE.</p> <pre><code>import discord class MyClient(discord.Client): async def on_ready(self): print(f'Logged on as {self.user}!') async def on_message(self, message): print(f'Message from {message.author}: {message.content}') intents = discord.Intents.default() intents.message_content = True client = MyClient(intents=intents) class MyClient(discord.Client): async def on_ready(self): print(f'Logged on as {self.user}!') async def on_message(self, message): print(f'Message from {message.author}: {message.content}') intents = discord.Intents.default() intents.message_content = True client = MyClient(intents=intents) import asyncio async def client_start(): await client.start('XYZ') </code></pre> <p>I really don't know what to try I expected the application to be started automatically, I am not a python expert my friend asked me this, now I am asking you guys kindly help.</p>
[ { "answer_id": 74535230, "author": "stijndcl", "author_id": 13568999, "author_profile": "https://Stackoverflow.com/users/13568999", "pm_score": 0, "selected": false, "text": "client_start()" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20485629/" ]
74,534,591
<p>I stored my social links data on firebase, and now I want to make a <code>&lt;li&gt;</code> list of my social links but the <code>icon</code> object I have here, is not showing me the icons instead it's showing me the elements like: <code>&lt;BsBehance /&gt;</code>. It should be displayed as icon, how can I do that?</p> <p>Firebase data:-</p> <p><a href="https://i.stack.imgur.com/S2ZKhm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/S2ZKhm.png" alt="enter image description here" /></a></p> <p>Code:-</p> <pre><code>import { useEffect, useState } from &quot;react&quot;; import * as ReactIcons from &quot;react-icons/fa&quot;; import MainWrapper from &quot;./MainWrapper&quot;; import classes from &quot;./pages.module.css&quot;; export default function Footer() { const [socialLinks, setSocialLinks] = useState([]); useEffect(() =&gt; { const fetchSocilLinks = async () =&gt; { const res = await fetch( &quot;https://mohitdevelops-d64e5-default-rtdb.asia-southeast1.firebasedatabase.app/accounts.json&quot; ); const data = await res.json(); let loadedData = []; for (const keys in data) { loadedData.push({ url: data[keys].url, icon: data[keys].icon, id: data[keys].id, }); } setSocialLinks(loadedData); }; fetchSocilLinks().catch((err) =&gt; { console.log(err.message); }); }, [socialLinks]); console.log(socialLinks); return ( &lt;footer className={classes.footer__wrap}&gt; &lt;MainWrapper&gt; &lt;p&gt;Connect with me:&lt;/p&gt; &lt;ul className={classes.social_links}&gt; {socialLinks?.map(({ icon, id, url }) =&gt; { const iconLink = icon.split(/\&lt;|\/&gt;/).filter((e) =&gt; e)[0]; const IconsComponent = ReactIcons[iconLink]; return ( &lt;li key={id}&gt; &lt;a href={url} target=&quot;_blank&quot;&gt; &lt;IconsComponent /&gt; &lt;/a&gt; &lt;/li&gt; ); })} &lt;/ul&gt; &lt;/MainWrapper&gt; &lt;/footer&gt; ); } </code></pre> <p>And its showing me like this:-</p> <p><a href="https://i.stack.imgur.com/v9Fxjl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/v9Fxjl.png" alt="enter image description here" /></a></p> <p>Everything data is coming fine, just need to know how to display an element which is working like an icon.</p>
[ { "answer_id": 74534868, "author": "Miguel Caro", "author_id": 11206583, "author_profile": "https://Stackoverflow.com/users/11206583", "pm_score": 0, "selected": false, "text": "<ul className={classes.social_links}> \n {socialLinks.map((el) => {\n return (\n <li key={el.id}>\n <a href={el.url} target=\"_blank\">\n <span dangerouslySetInnerHTML={{__html: el.icon}} />\n </a>\n </li>\n );\n })}\n</ul>\n" }, { "answer_id": 74623701, "author": "Tejashree Surve", "author_id": 15197074, "author_profile": "https://Stackoverflow.com/users/15197074", "pm_score": 0, "selected": false, "text": "npm install react-icons --save\n import * as ReactIcons from \"react-icons/bs\";\n <ul>\n {socialLinks?.map(({ icon, id, url }) => {\n const iconLink = icon.split(/\\<|\\/>/).filter((e) => e)[0];\n const Compoenent = ReactIcons[iconLink];\n return (\n <li key={id}>\n <a href={url}>\n <Compoenent />\n </a>\n </li>\n );\n })}\n </ul>\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14152125/" ]
74,534,622
<p>I am struggling with the following issue: I would like to write some small code to deisotope mass spec data.</p> <p>For this, I compare, if the difference between two signals is equal the mass of a proton devided by the charge state. So far, so easy.</p> <p>I am struggling now, to find series of more than two peaks.</p> <p>I broke down the problem to having a list of tuples, and a series are n tuples, where the last number of the previous tuple is equal the first tuple of the current tuple.</p> <p>From this:</p> <p>[(1,2), (2,3), (4,5), (7,9), (8,10), (9,11)]</p> <p>To this:</p> <p>[(1,2,3), (4,5), (7,9,11), (8,10)]</p> <p>Simple order will fail, as there might be jumps (7--&gt;9) and an intermediate signal (8,10)</p> <p>Here is some test data:</p> <pre><code>import numpy as np proton = 1.0078250319 data = [ (632.3197631835938, 2244.3374), #0 (632.830322265625, 2938.797), #1 (634.3308715820312, 1567.1385), #2 (639.3309326171875, 80601.41), #3 (640.3339233398438, 23759.367), #4 (641.3328247070312, 4771.9946), #5 (641.8309326171875, 2735.902), #6 (642.3365478515625, 4600.567), #7 (642.84033203125, 1311.657), #8 (650.34521484375, 11952.237), #9 (650.5, 1), #10 (650.84228515625, 10757.939), #11 (651.350341796875, 6324.9023), #12 (651.8455200195312, 1398.8452), #13 (654.296875, 1695.3457)] #14 mz, i = zip(*data) mz = np.array(mz) i = np.array(i) arr = np.triu(mz - mz[:, np.newaxis]) charge = 2 </code></pre> <p>So actually, in the first step, I am just interested in the mz values. I substract all values from all values and isolate the upper triangle.</p> <p>To calculate, if two signals are actually within the correct mass, I then use the following code:</p> <pre><code>&gt;&gt;&gt; pairs = tuple(zip(*np.where(abs(arr - (proton / charge)) &lt; 0.01))) ((0, 1), (5, 6), (6, 7), (7, 8), (9, 11), (11, 12), (12, 13)) </code></pre> <p>Now, to corresponding signals are clear by eye:</p> <p>Peak 1: 0 to 1</p> <p>Peak 2: 5 to 8</p> <p>Peak 3: 9 to 13, without 10.</p> <p>So in principle, I would like compare the 2nd value of each tuple with the first tuple of any other, to identify consequtive sequnces.</p> <p>What I tried, is to flatten the list, remove duplicates and find consequtive counting in this 1D list. But this fails, as a peak from 5-9 is found.</p> <p>I would like to have a vectorized solution, as this calculation is done for 100-500 signals for multiple charge states in 30000+ spectra.</p> <p>I am pretty sure, this had been asked before, but was not able to find a suitable solution.</p> <p>Eventually, these series are than used to check the intensity of the corresponding peaks, sum them and use the biggest initial value to assign the deisotoped peak here.</p> <p>Thx Christian</p> <p>ps. also if there are some suggestion to the already existing code, I am happy to learn. I am pretty new to vectorized calculation, and usually wrote tons of for loops, which take ages to finish.</p>
[ { "answer_id": 74535164, "author": "CodeKorn", "author_id": 10882128, "author_profile": "https://Stackoverflow.com/users/10882128", "pm_score": 3, "selected": true, "text": "d = {}\npairs = [(1,2), (2,3), (4,5), (7,9), (8,10), (9,11)]\nfor t in pairs:\n if t[0] in d:\n d[t[0]].append(t[1])\n d[t[1]] = d.pop(t[0])\n else:\n d[t[1]] = list(t)\nsignals = tuple(tuple(v) for v in d.values())\n" }, { "answer_id": 74535322, "author": "obchardon", "author_id": 4363864, "author_profile": "https://Stackoverflow.com/users/4363864", "pm_score": 3, "selected": false, "text": "networkx import networkx as nx\n# Your tuples become the edges of the graph.\nedge = [(1,2), (2,3), (4,5), (7,9), (8,10), (9,11)]\n\n# We create the graph\nG = nx.Graph()\nG.add_edges_from(edge)\n\n# Use connected_components to detect the subgraphs.\nd = list(nx.connected_components(G)) \n [{1, 2, 3}, {4, 5}, {7, 9, 11}, {8, 10}]\n" }, { "answer_id": 74535389, "author": "msi_gerva", "author_id": 1913367, "author_profile": "https://Stackoverflow.com/users/1913367", "pm_score": 0, "selected": false, "text": "#!/usr/bin/env ipython\n# --------------------\ndatain = [(1,2), (2,3), (4,5), (7,9), (8,10), (9,11)]\ndataout = [];\n# ---------------------------------------------------\nfor ii,val_a in enumerate(datain):\n appendval = set(val_a)\n for jj,val_b in enumerate(datain[ii+1:]):\n # -------------------------------------------\n if len(set(val_a).intersection(set(val_b)))>0:\n appendval = appendval.union(val_b)\n datain.remove(val_b)\n # -------------------------------------------\n dataout.append(tuple(appendval))\n# ---------------------------------------------------\n" }, { "answer_id": 74545208, "author": "Ravnclaw", "author_id": 14571316, "author_profile": "https://Stackoverflow.com/users/14571316", "pm_score": 1, "selected": false, "text": "networkx\nsize: 10\n22.9 µs ± 1.92 µs per loop (mean ± std. dev. of 2 runs, 10 loops each)\nsize: 100\n165 µs ± 4.59 µs per loop (mean ± std. dev. of 2 runs, 10 loops each)\nsize: 1000\n2.08 ms ± 52.4 µs per loop (mean ± std. dev. of 2 runs, 10 loops each)\nsize: 10000\n23.1 ms ± 499 µs per loop (mean ± std. dev. of 2 runs, 10 loops each)\nsize: 100000\n350 ms ± 6.12 ms per loop (mean ± std. dev. of 2 runs, 10 loops each)\nsize: 1000000\n4.82 s ± 120 ms per loop (mean ± std. dev. of 2 runs, 10 loops each)\n\nloop\nsize: 10\n3.31 µs ± 418 ns per loop (mean ± std. dev. of 2 runs, 10 loops each)\nsize: 100\n35.3 µs ± 5.68 µs per loop (mean ± std. dev. of 2 runs, 10 loops each)\nsize: 1000\n350 µs ± 22.2 µs per loop (mean ± std. dev. of 2 runs, 10 loops each)\nsize: 10000\n3.95 ms ± 38.5 µs per loop (mean ± std. dev. of 2 runs, 10 loops each)\nsize: 100000\n71.6 ms ± 278 µs per loop (mean ± std. dev. of 2 runs, 10 loops each)\nsize: 1000000\n1.11 s ± 30.8 ms per loop (mean ± std. dev. of 2 runs, 10 loops each)\n\n import numpy as np\nimport networkx as nx\n\ndef p1(edge):\n # from https://stackoverflow.com/a/74535322/14571316\n \n G = nx.Graph()\n G.add_edges_from(edge)\n\n # Use connected_components to detect the subgraphs.\n d = list(nx.connected_components(G)) \n \n return d\n\ndef p2(pairs):\n # from https://stackoverflow.com/a/74535164/14571316 \n d = {}\n for t in pairs:\n if t[0] in d:\n d[t[0]].append(t[1])\n d[t[1]] = d.pop(t[0])\n else:\n d[t[1]] = list(t)\n signals = tuple(tuple(v) for v in d.values())\n \n return signals\n\nprint(\"networkx\")\nfor size in [10, 100, 1000, 10000, 100000, 1000000]:\n print(f'size: {size}')\n l1 = np.random.randint(0, high=int(size/2), size=size)\n l2 = np.random.randint(0, high=int(size/2), size=size)\n pairs = tuple(zip(l1, l2))\n %timeit -n10 -r2 p1(pairs)\n \nprint(\"loop\")\nfor size in [10, 100, 1000, 10000, 100000, 1000000]:\n print(f'size: {size}')\n l1 = np.random.randint(0, high=int(size/2), size=size)\n l2 = np.random.randint(0, high=int(size/2), size=size)\n pairs = tuple(zip(l1, l2))\n %timeit -n10 -r2 p2(pairs)\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14571316/" ]
74,534,658
<p>I have two arrays of:</p> <pre><code>x=43035000 51065000 67085000 36770000 57165000 54335000 46590000 64410000 39295000 37210000 41800000 y=397 420 349 300 387 417 365 567 321 314 341 </code></pre> <p>I would like to divide the first number in x with the first number in y and the second number in x with the second number in y and so on...</p> <p>I have tried:</p> <pre><code>for i in &quot;${x[@]}&quot;; do for j in &quot;${y[@]}&quot;; do awk &quot;{print $i/$j}&quot;; done; done </code></pre> <p>however it just lists the numbers in x and then the numbers in y:</p> <pre><code>43035000 51065000 67085000 36770000 57165000 54335000 46590000 64410000 39295000 37210000 41800000 397 420 349 300 387 417 365 567 321 314 341 </code></pre>
[ { "answer_id": 74534865, "author": "Adrián Bíro", "author_id": 18172103, "author_profile": "https://Stackoverflow.com/users/18172103", "pm_score": 0, "selected": false, "text": "$ x=(43035000 51065000 67085000 36770000 57165000 54335000 46590000 64410000 39295000 37210000 41800000)\n$ y=(397 420 349 300 387 417 365 567 321 314 341)\n\n$ for (( i=0; i<${#x[@]}; i++ )); \ndo \n awk -v I=${x[$i]} -v J=${y[$i]} 'BEGIN{print I / J}';\ndone\n" }, { "answer_id": 74535120, "author": "M. Nejat Aydin", "author_id": 13809001, "author_profile": "https://Stackoverflow.com/users/13809001", "pm_score": 2, "selected": false, "text": "for bash x=(43035000 51065000 67085000 36770000 57165000 54335000 46590000 64410000 39295000 37210000 41800000)\ny=(397 420 349 300 387 417 365 567 321 314 341)\nfor ((i=0; i<${#x[@]}; ++i)); do echo \"${x[i]} ${y[i]}\"; done |\n awk '{print $1/$2}'\n awk for ((i=0; i<${#x[@]}; ++i)); do echo $((x[i] / y[i])); done\n" }, { "answer_id": 74537261, "author": "Paul Hodges", "author_id": 8656552, "author_profile": "https://Stackoverflow.com/users/8656552", "pm_score": 0, "selected": false, "text": "x=( 43035000 51065000 67085000 36770000 57165000 54335000 46590000 64410000 39295000 37210000 41800000 )\ny=( 397 420 349 300 387 417 365 567 321 314 341 )\n $: for i in ${!x[@]}; do echo \"${x[i]} ${y[i]}\"; done | awk '{print $1/$2}'\n108401\n121583\n192221\n122567\n147713\n130300\n127644\n113598\n122414\n118503\n foo ${!foo[@]} x y $: cat x\n43035000\n51065000\n67085000\n36770000\n57165000\n54335000\n46590000\n64410000\n39295000\n37210000\n41800000\n\n$: cat y\n397\n420\n349\n300\n387\n417\n365\n567\n321\n314\n341\n\n$: awk 'NR==FNR{ dividend[FNR]=$1 } NR>FNR{ print dividend[FNR]/$1 }' x y\n108401\n121583\n192221\n122567\n147713\n130300\n127644\n113598\n122414\n118503\n122581\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20573207/" ]
74,534,666
<p>I am trying to return the objects relating to a through table which counts the number of reactions on a blog post.</p> <p>I have an Article model, Sentiment model and Reactions model. The sentiment is simply a 1 or 2, <code>1</code> representing <code>like</code> and <code>2</code> for <code>dislike</code>. On the frontend users can react to an article and their reactions are stored in a Reactions table.</p> <pre><code>Reactions model class Reaction(models.Model): user_id = models.ForeignKey(User, related_name='user_id', on_delete=models.CASCADE) article_id = models.ForeignKey(Article, related_name='article_id', on_delete=models.CASCADE) sentiment = models.ForeignKey(Sentiment, related_name='sentiment', on_delete=models.CASCADE) </code></pre> <p>I'd like to find the 2 most liked articles so I have written a view to handle the GET request</p> <pre><code>views.py class MostPopularView(generics.RetrieveAPIView): queryset = Reaction.objects.annotate(num_likes = Count('sentiment_id')).order_by('num_likes') serializer_class = MostPopularSerializer </code></pre> <p>and a serializer to transform the data</p> <pre><code>serializers.py class MostPopularSerializer(serializers.Serializer): class Meta: fields = ( 'id', 'title', ) model = Article </code></pre> <p>As the code stands now, I'm getting a response</p> <pre><code>&lt;QuerySet [&lt;Reaction: d745e09b-5685-4592-ab43-766f47c73bef San Francisco Bay 1&gt;, &lt;Reaction: d745e09b-5685-4592-ab43-766f47c73bef The Golden Gate Bridge 1&gt;, &lt;Reaction: dd512e6d-5015-4a70-ac42-3afcb1747050 San Francisco Bay 1&gt;, &lt;Reaction: dd512e6d-5015-4a70-ac42-3afcb1747050 The Golden Gate Bridge 2&gt;]&gt; </code></pre> <p>Showing <code>San Francisco Bay</code> has 2 likes and <code>The Golden Gate Bridge</code> has 1 like and 1 dislike.</p> <p>I've tried multiple methods to get the correct response including filtering by <code>sentiment=1</code> but can't get any further than this. What I'm looking for is a way to count the number of <code>sentiment=1</code> fields which correspond to each article <code>id</code> and order them in descending order, so most liked at the top.</p> <h2>Edit</h2> <p>I've rethought my approach although I have not yet found a solution</p> <ol> <li>Filter Reaction table by <code>sentiment=1</code></li> <li>Order by count of <code>article_id</code></li> <li>Serialize with <code>MostPopularSerializer</code></li> </ol> <p>I changed the <code>View</code> to be a <code>ModelViewSet</code></p> <pre><code>class MostPopularView(viewsets.ModelViewSet): articles = Reaction.objects.filter(sentiment=1).annotate(num_likes = Count('article_id')).order_by('num_likes')[:4] # queryset = Article.objects.filter(id=articles['article_id']) #Doesn't work by hypothetically what I'm thinking for article in articles: queryset = Article.objects.filter(id=article['article_id']) serializer_class = MostPopularSerializer </code></pre> <p>And the serializer to be a <code>ModelSerializer</code></p> <pre><code>class MostPopularSerializer(serializers.ModelSerializer): class Meta: fields = ( 'id', 'title', 'tags', ) model = Article </code></pre> <p>and an updated URL for good measure <code>path('popular', views.MostPopularView.as_view({'get': 'list'}))</code></p> <p>Any tips on achieving these steps would be much appreciated, thank you</p>
[ { "answer_id": 74534865, "author": "Adrián Bíro", "author_id": 18172103, "author_profile": "https://Stackoverflow.com/users/18172103", "pm_score": 0, "selected": false, "text": "$ x=(43035000 51065000 67085000 36770000 57165000 54335000 46590000 64410000 39295000 37210000 41800000)\n$ y=(397 420 349 300 387 417 365 567 321 314 341)\n\n$ for (( i=0; i<${#x[@]}; i++ )); \ndo \n awk -v I=${x[$i]} -v J=${y[$i]} 'BEGIN{print I / J}';\ndone\n" }, { "answer_id": 74535120, "author": "M. Nejat Aydin", "author_id": 13809001, "author_profile": "https://Stackoverflow.com/users/13809001", "pm_score": 2, "selected": false, "text": "for bash x=(43035000 51065000 67085000 36770000 57165000 54335000 46590000 64410000 39295000 37210000 41800000)\ny=(397 420 349 300 387 417 365 567 321 314 341)\nfor ((i=0; i<${#x[@]}; ++i)); do echo \"${x[i]} ${y[i]}\"; done |\n awk '{print $1/$2}'\n awk for ((i=0; i<${#x[@]}; ++i)); do echo $((x[i] / y[i])); done\n" }, { "answer_id": 74537261, "author": "Paul Hodges", "author_id": 8656552, "author_profile": "https://Stackoverflow.com/users/8656552", "pm_score": 0, "selected": false, "text": "x=( 43035000 51065000 67085000 36770000 57165000 54335000 46590000 64410000 39295000 37210000 41800000 )\ny=( 397 420 349 300 387 417 365 567 321 314 341 )\n $: for i in ${!x[@]}; do echo \"${x[i]} ${y[i]}\"; done | awk '{print $1/$2}'\n108401\n121583\n192221\n122567\n147713\n130300\n127644\n113598\n122414\n118503\n foo ${!foo[@]} x y $: cat x\n43035000\n51065000\n67085000\n36770000\n57165000\n54335000\n46590000\n64410000\n39295000\n37210000\n41800000\n\n$: cat y\n397\n420\n349\n300\n387\n417\n365\n567\n321\n314\n341\n\n$: awk 'NR==FNR{ dividend[FNR]=$1 } NR>FNR{ print dividend[FNR]/$1 }' x y\n108401\n121583\n192221\n122567\n147713\n130300\n127644\n113598\n122414\n118503\n122581\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14611431/" ]
74,534,695
<p>I need a query that every time the indicator column turns into zero and there are 3 zeros in a row, I would like to assign them a unique group number.</p> <p>Here is a sample data:</p> <pre><code>select 0 as offset, 1 as indicator, -1 as grp union all select 1, 1, -1 union all select 2, 1, -1 union all select 3, 1, -1 union all select 4, 1, -1 union all select 5, 1, -1 union all select 6, 1, -1 union all select 7, 0, 1 union all select 8, 0, 1 union all select 9, 0, 1 union all select 10, 1, -1 union all select 11, 0, 2 union all select 12, 0, 2 union all select 13, 0, 2 union all select 14, 1, -1 union all select 15, 1, -1 union all select 16, 1, -1 </code></pre> <p>In this example there are two sequences of 3 zeros, indicated as grp=1 and grp=2.</p>
[ { "answer_id": 74534865, "author": "Adrián Bíro", "author_id": 18172103, "author_profile": "https://Stackoverflow.com/users/18172103", "pm_score": 0, "selected": false, "text": "$ x=(43035000 51065000 67085000 36770000 57165000 54335000 46590000 64410000 39295000 37210000 41800000)\n$ y=(397 420 349 300 387 417 365 567 321 314 341)\n\n$ for (( i=0; i<${#x[@]}; i++ )); \ndo \n awk -v I=${x[$i]} -v J=${y[$i]} 'BEGIN{print I / J}';\ndone\n" }, { "answer_id": 74535120, "author": "M. Nejat Aydin", "author_id": 13809001, "author_profile": "https://Stackoverflow.com/users/13809001", "pm_score": 2, "selected": false, "text": "for bash x=(43035000 51065000 67085000 36770000 57165000 54335000 46590000 64410000 39295000 37210000 41800000)\ny=(397 420 349 300 387 417 365 567 321 314 341)\nfor ((i=0; i<${#x[@]}; ++i)); do echo \"${x[i]} ${y[i]}\"; done |\n awk '{print $1/$2}'\n awk for ((i=0; i<${#x[@]}; ++i)); do echo $((x[i] / y[i])); done\n" }, { "answer_id": 74537261, "author": "Paul Hodges", "author_id": 8656552, "author_profile": "https://Stackoverflow.com/users/8656552", "pm_score": 0, "selected": false, "text": "x=( 43035000 51065000 67085000 36770000 57165000 54335000 46590000 64410000 39295000 37210000 41800000 )\ny=( 397 420 349 300 387 417 365 567 321 314 341 )\n $: for i in ${!x[@]}; do echo \"${x[i]} ${y[i]}\"; done | awk '{print $1/$2}'\n108401\n121583\n192221\n122567\n147713\n130300\n127644\n113598\n122414\n118503\n foo ${!foo[@]} x y $: cat x\n43035000\n51065000\n67085000\n36770000\n57165000\n54335000\n46590000\n64410000\n39295000\n37210000\n41800000\n\n$: cat y\n397\n420\n349\n300\n387\n417\n365\n567\n321\n314\n341\n\n$: awk 'NR==FNR{ dividend[FNR]=$1 } NR>FNR{ print dividend[FNR]/$1 }' x y\n108401\n121583\n192221\n122567\n147713\n130300\n127644\n113598\n122414\n118503\n122581\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3972214/" ]
74,534,736
<p>Here is my starting point:</p> <pre><code>#!/usr/bin/env perl use warnings; use strict; my %hash_a = ( &quot;num&quot; =&gt; 7, &quot;date&quot; =&gt; 20221104, &quot;prath&quot; =&gt; &quot;1.1.10&quot;, &quot;antema&quot; =&gt; &quot;1.1.15&quot; ); my %hash_b = ( &quot;num&quot; =&gt; 8, &quot;date&quot; =&gt; 20221105, &quot;prath&quot; =&gt; &quot;1.1.16&quot;, &quot;antema&quot; =&gt; &quot;1.1.19&quot; ); my %hash_c = ( &quot;num&quot; =&gt; 9, &quot;date&quot; =&gt; 20221112, &quot;prath&quot; =&gt; &quot;1.1.20&quot;, &quot;antema&quot; =&gt; &quot;1.1.39&quot; ); </code></pre> <p>from this I want to make these strings using a loop, if possible without using any trick like building variable names through a loop to get 'hash_a', 'hash_b', 'hash_c'. I was used to use multidimensional arrays for such things in python.</p> <pre><code>07_class_date_20221104_-_starting_verse_1.1.10_-_closing_verse_1.1.15.mp4 08_class_date_20221105_-_starting_verse_1.1.16_-_closing_verse_1.1.19.mp4 08_class_date_20221112_-_starting_verse_1.1.20_-_closing_verse_1.1.39.mp4 </code></pre>
[ { "answer_id": 74535129, "author": "Håkon Hægland", "author_id": 2173773, "author_profile": "https://Stackoverflow.com/users/2173773", "pm_score": 0, "selected": false, "text": "use feature qw(say);\nuse strict;\nuse warnings;\nuse experimental qw(declared_refs refaliasing);\n\nmy %hash_a = (\n \"num\" => 7,\n \"date\" => 20221104,\n \"prath\" => \"1.1.10\",\n \"antema\" => \"1.1.15\"\n);\n\n\nmy %hash_b = (\n \"num\" => 8,\n \"date\" => 20221105,\n \"prath\" => \"1.1.16\",\n \"antema\" => \"1.1.19\"\n);\n\nmy %hash_c = (\n \"num\" => 9,\n \"date\" => 20221112,\n \"prath\" => \"1.1.20\",\n \"antema\" => \"1.1.39\"\n);\n\nsub get_str {\n my \\%hash = $_[0];\n\n sprintf \"%02d_class_date_%s_-_starting_verse_%s_-closing_verse_%s.mp4\",\n $hash{num}, $hash{date}, $hash{prath}, $hash{antema};\n}\n\nfor my $ref (\\%hash_a, \\%hash_b, \\%hash_c) {\n my $str = get_str($ref);\n say $str;\n}\n 07_class_date_20221104_-_starting_verse_1.1.10_-closing_verse_1.1.15.mp4\n08_class_date_20221105_-_starting_verse_1.1.16_-closing_verse_1.1.19.mp4\n09_class_date_20221112_-_starting_verse_1.1.20_-closing_verse_1.1.39.mp4\n" }, { "answer_id": 74535531, "author": "TLP", "author_id": 725418, "author_profile": "https://Stackoverflow.com/users/725418", "pm_score": 3, "selected": true, "text": "%hash_a %hash_b my @all = (\n{ \n \"num\" => 7, \n \"date\" => 20221104, \n \"prath\" => \"1.1.10\", \n \"antema\" => \"1.1.15\" \n},\n{\n \"num\" => 8, \n \"date\" => 20221105, \n \"prath\" => \"1.1.16\", \n \"antema\" => \"1.1.19\" \n},\n{\n \"num\" => 9, \n \"date\" => 20221112, \n \"prath\" => \"1.1.20\", \n \"antema\" => \"1.1.39\" \n});\n for my $record (@all) {\n my $num = $record->{num}; # etc...\n sprintf" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1850133/" ]
74,534,742
<p>Given a message (b of type B), nested in another (a of type A); how does one get ‘a’? I was hoping for something like ‘b.getParent()’.</p> <pre class="lang-protobuf prettyprint-override"><code>message B { optional string name = 1; repeated B b = 2; } message A { optional string name = 1; repeated B b = 1; } </code></pre> <p>Here is an example instance of an ‘a’ with textual serialization.</p> <pre class="lang-protobuf prettyprint-override"><code>name: &quot;a&quot; b { name: “foo” b { name: “fred” b { name: “flintstone” }}} b { name: “bar” } b { name: “baz” } </code></pre> <p>The issue is that I am navigating the collection 'a' with a visitor and I need to be able to reconstruct a full name composed of names of all the ancestors.</p> <p>Refs:</p> <ul> <li><a href="https://stackoverflow.com/questions/10998254/get-the-parent-message-of-a-protobuf-message-in-python">Get the parent message of a protobuf message (in python)</a></li> </ul> <p>I am fine with internal representation as I will wrap it in a kotlin extension.</p>
[ { "answer_id": 74536772, "author": "Louis Wasserman", "author_id": 869736, "author_profile": "https://Stackoverflow.com/users/869736", "pm_score": 2, "selected": false, "text": "B A" }, { "answer_id": 74539463, "author": "phreed", "author_id": 345427, "author_profile": "https://Stackoverflow.com/users/345427", "pm_score": 0, "selected": false, "text": "\nfun depthFirstVisitor(root: A, fragFilter: (frag: B) -> Boolean): Sequence<Array<B>> {\n return sequence {\n root.fragmentsList.forEach { child ->\n if (fragFilter(child)) {\n yield(arrayOf(child))\n dfs(emptyArray(), child, fragFilter)\n }\n }\n }\n}\n\nprivate suspend fun SequenceScope<Array<B>>.dfs(\n ancestry: Array<B>,\n base: B,\n fragFilter: (frag: B) -> Boolean\n) {\n val ancestryNew = ancestry + base\n base.fragmentsList.forEach { child ->\n if (fragFilter(child)) {\n yield(ancestryNew + child)\n dfs(ancestryNew, child, fragFilter)\n }\n }\n}\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/345427/" ]
74,534,756
<pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int main(void) { long x, y; printf(&quot;Enter the first number: \n&quot;); scanf(&quot;%ld&quot;, &amp;x); printf(&quot;Enter the second number: \n&quot;); scanf(&quot;%ld&quot;, &amp;y); long z = x + y; printf(&quot;The answer is: %ld \n&quot;, z); return 0; } </code></pre> <p>I can't add more than 4 billion here even though i should since im using 'Long' datatype here.</p> <p><a href="https://i.stack.imgur.com/eEsC1.png" rel="nofollow noreferrer">enter image description here</a></p>
[ { "answer_id": 74534809, "author": "TrebledJ", "author_id": 10239789, "author_profile": "https://Stackoverflow.com/users/10239789", "pm_score": 2, "selected": false, "text": "long long long 2**31 - 1 unsigned long 2**32 - 1 long long unsigned long long %lu %lld %llu" }, { "answer_id": 74535345, "author": "chux - Reinstate Monica", "author_id": 2410359, "author_profile": "https://Stackoverflow.com/users/2410359", "pm_score": 0, "selected": false, "text": "long long long long long long long x, y;\nprintf(\"Enter the first number: \\n\");\nscanf(\"%lld\", &x);\nprintf(\"Enter the second number: \\n\");\nscanf(\"%lld\", &y);\n\nlong long z = x + y;\nprintf(\"The answer is: %lld \\n\", z);\n unsigned long int64_t int_least64_t" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20573579/" ]
74,534,780
<p>I am writing a function to conduct one way anova and was writing the below function</p> <pre><code>fun_aov &lt;- function(sps, param){ ths_data_aov &lt;- ths_data_aov |&gt; filter(Species == sps) |&gt; select(Species, Treatment, param) n_one_way_aov &lt;- aov( param ~ Treatment, data = ths_data_aov) h &lt;- summary(n_one_way_aov) return(h) } </code></pre> <p>for the data frame below</p> <pre><code>Species Treatment num_roots_n lng_long_root_cm dia_long_root_mm &lt;chr&gt; &lt;chr&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; x1 t1 4 7 0.6 x1 t1 4 7 0.6 x1 t1 4 7 0.6 x1 t1 4 7 0.6 x1 t2 4 8 0.7 x1 t2 3 6 0.8 x1 t2 4 8 0.9 x1 t2 5 7 0.3 x1 t3 8 8 0.5 x1 t3 3 5 0.7 x1 t3 4 6 0.3 x1 t3 5 5 0.7 x1 t4 6 4 0.7 x1 t4 9 3 0.8 x1 t4 9 3 0.8 x1 t4 9 3 0.8 </code></pre> <p>but when I execute the function <code>fun_aov(&quot;x1&quot;, lng_long_root_cm)</code> an error shows up saying <code> Error in `select()`: ! object 'lng_long_root_cm' not found</code> how do I rectify it.</p> <p>I am expecting the return of <code>h</code> which gives me an analysis wrt to particular <code>Species</code> and <code>param</code></p>
[ { "answer_id": 74534809, "author": "TrebledJ", "author_id": 10239789, "author_profile": "https://Stackoverflow.com/users/10239789", "pm_score": 2, "selected": false, "text": "long long long 2**31 - 1 unsigned long 2**32 - 1 long long unsigned long long %lu %lld %llu" }, { "answer_id": 74535345, "author": "chux - Reinstate Monica", "author_id": 2410359, "author_profile": "https://Stackoverflow.com/users/2410359", "pm_score": 0, "selected": false, "text": "long long long long long long long x, y;\nprintf(\"Enter the first number: \\n\");\nscanf(\"%lld\", &x);\nprintf(\"Enter the second number: \\n\");\nscanf(\"%lld\", &y);\n\nlong long z = x + y;\nprintf(\"The answer is: %lld \\n\", z);\n unsigned long int64_t int_least64_t" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20121588/" ]
74,534,791
<p>I am currently using SAP CPI to achieve this conversion. I have tried the regular XML to JSON converter available but was not able to achieve this requirement. I then set out to try and see if XSLT can help.</p> <p>I am trying to convert the following XML payload:</p> <pre><code>&lt;root&gt; &lt;ClientID&gt;1&lt;/ClientID&gt; &lt;PackageID&gt;650&lt;/PackageID&gt; &lt;SBUID&gt;2187&lt;/SBUID&gt; &lt;CandidateID&gt;456&lt;/CandidateID&gt; &lt;AssociateId&gt;789&lt;/AssociateId&gt; &lt;FirstName&gt;Meghana&lt;/FirstName&gt; &lt;MiddleName&gt;&lt;/MiddleName&gt; &lt;LastName&gt;Rao&lt;/LastName&gt; &lt;FatherName&gt;Satish&lt;/FatherName&gt; &lt;ContactNo&gt;7530001169&lt;/ContactNo&gt; &lt;EmailID&gt;dummy@sap.com&lt;/EmailID&gt; &lt;AddressHistory&gt; &lt;Address&gt; &lt;SequenceNo&gt;0&lt;/SequenceNo&gt; &lt;AddressLine&gt;Kharghar,navi mumbai&lt;/AddressLine&gt; &lt;City&gt;Maharashtra-Mumbai&lt;/City&gt; &lt;State&gt;Maharashtra&lt;/State&gt; &lt;PinCode&gt;410210&lt;/PinCode&gt; &lt;Country&gt;India&lt;/Country&gt; &lt;Landmark&gt;&lt;/Landmark&gt; &lt;StayFrom&gt;01-08-2013&lt;/StayFrom&gt; &lt;StayTo&gt;06-08-2021&lt;/StayTo&gt; &lt;IsCurrentAddress&gt;false&lt;/IsCurrentAddress&gt; &lt;IsPermanentAddress&gt;false&lt;/IsPermanentAddress&gt; &lt;HouseNo&gt;&lt;/HouseNo&gt; &lt;AddressType&gt;Current&lt;/AddressType&gt; &lt;DocList&gt; &lt;listofdocs&gt; &lt;DocumentName&gt;abc.jpg&lt;/DocumentName&gt; &lt;DocumentPath&gt;base64&lt;/DocumentPath&gt; &lt;/listofdocs&gt; &lt;/DocList&gt; &lt;/Address&gt; &lt;/AddressHistory&gt; &lt;EducationList&gt; &lt;Education&gt; &lt;SequenceNo&gt;0&lt;/SequenceNo&gt; &lt;Qualification&gt;&lt;/Qualification&gt; &lt;Degree&gt;Under Graduate Degree&lt;/Degree&gt; &lt;CollegeName&gt;Amrutvahini College of engineering, Sangamner (Pune University)&lt;/CollegeName&gt; &lt;Location&gt;&lt;/Location&gt; &lt;RollNumber&gt;123123&lt;/RollNumber&gt; &lt;UniversityName&gt;Mumbai University&lt;/UniversityName&gt; &lt;UniversityAddress&gt;&lt;/UniversityAddress&gt; &lt;PeriodFrom&gt;&lt;/PeriodFrom&gt; &lt;PeriodTo&gt;&lt;/PeriodTo&gt; &lt;YearOfPassing&gt;2014&lt;/YearOfPassing&gt; &lt;Zipcode&gt;&lt;/Zipcode&gt; &lt;Percentage&gt;&lt;/Percentage&gt; &lt;AdditionalRemarks&gt;10th/12th/Undergrad etc&lt;/AdditionalRemarks&gt; &lt;International&gt;false&lt;/International&gt; &lt;Country&gt;&lt;/Country&gt; &lt;DocList&gt; &lt;listofdocs&gt; &lt;DocumentName&gt;abc.jpg&lt;/DocumentName&gt; &lt;DocumentPath&gt;base64&lt;/DocumentPath&gt; &lt;/listofdocs&gt; &lt;/DocList&gt; &lt;/Education&gt; &lt;/EducationList&gt; &lt;EmploymentList&gt; &lt;Employment&gt; &lt;SequenceNo&gt;0&lt;/SequenceNo&gt; &lt;EmployerName&gt;Stravis Solutions&lt;/EmployerName&gt; &lt;EmployerAddress&gt;Bangalore&lt;/EmployerAddress&gt; &lt;EmployerContactNo&gt;&lt;/EmployerContactNo&gt; &lt;Designation&gt;SDE&lt;/Designation&gt; &lt;EmployeeID&gt;asdas&lt;/EmployeeID&gt; &lt;FixedSalary&gt;0&lt;/FixedSalary&gt; &lt;IsCurrentEmployment&gt;false&lt;/IsCurrentEmployment&gt; &lt;RelievingDate&gt;15-10-2021&lt;/RelievingDate&gt; &lt;State&gt;&lt;/State&gt; &lt;City&gt;&lt;/City&gt; &lt;Zipcode&gt;&lt;/Zipcode&gt; &lt;International&gt;false&lt;/International&gt; &lt;Country&gt;&lt;/Country&gt; &lt;PFNumber&gt;&lt;/PFNumber&gt; &lt;UANNumber&gt;&lt;/UANNumber&gt; &lt;DocList&gt; &lt;listofdocs&gt; &lt;DocumentName&gt;abc.jpg&lt;/DocumentName&gt; &lt;DocumentPath&gt;base64&lt;/DocumentPath&gt; &lt;/listofdocs&gt; &lt;/DocList&gt; &lt;DateOfJoining&gt;18-03-2015&lt;/DateOfJoining&gt; &lt;/Employment&gt; &lt;Employment&gt; &lt;SequenceNo&gt;0&lt;/SequenceNo&gt; &lt;EmployerName&gt;Stravis Solutions&lt;/EmployerName&gt; &lt;EmployerAddress&gt;Bangalore&lt;/EmployerAddress&gt; &lt;EmployerContactNo&gt;&lt;/EmployerContactNo&gt; &lt;Designation&gt;SDE&lt;/Designation&gt; &lt;EmployeeID&gt;asdas&lt;/EmployeeID&gt; &lt;FixedSalary&gt;0&lt;/FixedSalary&gt; &lt;IsCurrentEmployment&gt;false&lt;/IsCurrentEmployment&gt; &lt;RelievingDate&gt;15-10-2021&lt;/RelievingDate&gt; &lt;International&gt;false&lt;/International&gt; &lt;Country&gt;&lt;/Country&gt; &lt;PFNumber&gt;&lt;/PFNumber&gt; &lt;UANNumber&gt;&lt;/UANNumber&gt; &lt;DocList&gt; &lt;listofdocs&gt; &lt;DocumentName&gt;abc.jpg&lt;/DocumentName&gt; &lt;DocumentPath&gt;base64&lt;/DocumentPath&gt; &lt;/listofdocs&gt; &lt;/DocList&gt; &lt;DateOfJoining&gt;18-03-2015&lt;/DateOfJoining&gt; &lt;/Employment&gt; &lt;/EmploymentList&gt; &lt;AddressReferencesList&gt; &lt;ListofReferences&gt; &lt;OrganizationName&gt;Com 1&lt;/OrganizationName&gt; &lt;AdditionalRemarks&gt;&lt;/AdditionalRemarks&gt; &lt;NameOfReferee&gt;Ref1&lt;/NameOfReferee&gt; &lt;RefereeOccupation&gt;SDE&lt;/RefereeOccupation&gt; &lt;RefereePhoneNumber&gt;123456&lt;/RefereePhoneNumber&gt; &lt;RefereeEmailAddress&gt;Ref1@com1.com&lt;/RefereeEmailAddress&gt; &lt;/ListofReferences&gt; &lt;ListofReferences&gt; &lt;OrganizationName&gt;Com 1&lt;/OrganizationName&gt; &lt;AdditionalRemarks&gt;&lt;/AdditionalRemarks&gt; &lt;NameOfReferee&gt;Ref1&lt;/NameOfReferee&gt; &lt;RefereeOccupation&gt;SDE&lt;/RefereeOccupation&gt; &lt;RefereePhoneNumber&gt;123456&lt;/RefereePhoneNumber&gt; &lt;RefereeEmailAddress&gt;Ref1@com1.com&lt;/RefereeEmailAddress&gt; &lt;/ListofReferences&gt; &lt;/AddressReferencesList&gt; &lt;DOB&gt;03-08-2021&lt;/DOB&gt; &lt;DLDetails&gt; &lt;DOB&gt;03-08-2021&lt;/DOB&gt; &lt;ApplicantName&gt;Test&lt;/ApplicantName&gt; &lt;FatherName&gt;Test&lt;/FatherName&gt; &lt;dl_remarks&gt;&lt;/dl_remarks&gt; &lt;UniqueIDCode&gt;1231231&lt;/UniqueIDCode&gt; &lt;DocList&gt; &lt;listofdocs&gt; &lt;DocumentName&gt;abc.jpg&lt;/DocumentName&gt; &lt;DocumentPath&gt;base64&lt;/DocumentPath&gt; &lt;/listofdocs&gt; &lt;/DocList&gt; &lt;/DLDetails&gt; &lt;PanDetails&gt; &lt;DOB&gt;03-08-2021&lt;/DOB&gt; &lt;ApplicantName&gt;Sunil Kumar Yadav&lt;/ApplicantName&gt; &lt;FatherName&gt;Sunil&lt;/FatherName&gt; &lt;pan_remarks&gt;&lt;/pan_remarks&gt; &lt;UniqueIDCode&gt;23123131&lt;/UniqueIDCode&gt; &lt;DocList&gt; &lt;listofdocs&gt; &lt;DocumentName&gt;abc.jpg&lt;/DocumentName&gt; &lt;DocumentPath&gt;base64&lt;/DocumentPath&gt; &lt;/listofdocs&gt; &lt;/DocList&gt; &lt;/PanDetails&gt; &lt;PVWDetails&gt; &lt;AddressList&gt; &lt;Address&gt; &lt;SequenceNo&gt;0&lt;/SequenceNo&gt; &lt;AddressLine&gt;Kharghar,navi mumbai&lt;/AddressLine&gt; &lt;City&gt;Maharashtra-Mumbai&lt;/City&gt; &lt;State&gt;Maharashtra&lt;/State&gt; &lt;PinCode&gt;410210&lt;/PinCode&gt; &lt;Country&gt;India&lt;/Country&gt; &lt;Landmark&gt;&lt;/Landmark&gt; &lt;StayFrom&gt;01-08-2013&lt;/StayFrom&gt; &lt;StayTo&gt;06-08-2021&lt;/StayTo&gt; &lt;IsCurrentAddress&gt;false&lt;/IsCurrentAddress&gt; &lt;IsPermanentAddress&gt;false&lt;/IsPermanentAddress&gt; &lt;HouseNo&gt;Sai shradha CHS.Sector-11,&lt;/HouseNo&gt; &lt;AddressType&gt;Current&lt;/AddressType&gt; &lt;DocList&gt; &lt;listofdocs&gt; &lt;DocumentName&gt;abc.jpg&lt;/DocumentName&gt; &lt;DocumentPath&gt;base64&lt;/DocumentPath&gt; &lt;/listofdocs&gt; &lt;/DocList&gt; &lt;/Address&gt; &lt;/AddressList&gt; &lt;DOB&gt;03-08-2021&lt;/DOB&gt; &lt;FatherName&gt;Sunil&lt;/FatherName&gt; &lt;ApplicantName&gt;Sunil Kumar Yadav&lt;/ApplicantName&gt; &lt;/PVWDetails&gt; &lt;CreditDetail&gt; &lt;ApplicantName&gt;Test&lt;/ApplicantName&gt; &lt;DOB&gt;03-08-2021&lt;/DOB&gt; &lt;FatherName&gt;Test&lt;/FatherName&gt; &lt;Gender&gt;Male&lt;/Gender&gt; &lt;UniqueIDCode&gt;Pan Number&lt;/UniqueIDCode&gt; &lt;EmailID&gt;asda@gmail.com&lt;/EmailID&gt; &lt;DocList&gt; &lt;listofdocs&gt; &lt;DocumentName&gt;abc.jpg&lt;/DocumentName&gt; &lt;DocumentPath&gt;base64&lt;/DocumentPath&gt; &lt;/listofdocs&gt; &lt;/DocList&gt; &lt;/CreditDetail&gt; &lt;DrugTestPanelCheck&gt; &lt;DrugTestPanel&gt;DrugTestPanel5&lt;/DrugTestPanel&gt; &lt;ApplicantName&gt;Test Candidate&lt;/ApplicantName&gt; &lt;/DrugTestPanelCheck&gt; &lt;GDCDetails&gt; &lt;ApplicantName&gt;Sunil Kumar Yadav&lt;/ApplicantName&gt; &lt;DOB&gt;03-08-2021&lt;/DOB&gt; &lt;FatherName&gt;Sunil&lt;/FatherName&gt; &lt;/GDCDetails&gt; &lt;PassportCheckDetails&gt; &lt;NameInPassport&gt;Sunil Kumar Yadav&lt;/NameInPassport&gt; &lt;PassportNo&gt;1231231&lt;/PassportNo&gt; &lt;MachineReadableZone&gt;&lt;/MachineReadableZone&gt; &lt;CandidateFirstName&gt;Sunil&lt;/CandidateFirstName&gt; &lt;CandidateLastName&gt;Yadav&lt;/CandidateLastName&gt; &lt;DOB&gt;03-08-2021&lt;/DOB&gt; &lt;FatherName&gt;Sunil&lt;/FatherName&gt; &lt;DocList&gt; &lt;listofdocs&gt; &lt;DocumentName&gt;abc.jpg&lt;/DocumentName&gt; &lt;DocumentPath&gt;base64&lt;/DocumentPath&gt; &lt;/listofdocs&gt; &lt;/DocList&gt; &lt;/PassportCheckDetails&gt; &lt;/root&gt; </code></pre> <p>To the below JSON payload, which as you can see has multiple array elements for even single payloads:</p> <pre><code>{ &quot;ClientID&quot;: &quot;1&quot;, &quot;PackageID&quot;: &quot;650&quot;, &quot;SBUID&quot;: &quot;2187&quot;, &quot;CandidateID&quot;: &quot;456&quot;, &quot;AssociateId&quot;: &quot;789&quot;, &quot;FirstName&quot;: &quot;Meghana&quot;, &quot;MiddleName&quot;: &quot;&quot;, &quot;LastName&quot;: &quot;Rao&quot;, &quot;FatherName&quot;: &quot;Satish&quot;, &quot;ContactNo&quot;: &quot;7530001169&quot;, &quot;EmailID&quot;: &quot;dummy@sap.com&quot;, &quot;AddressHistory&quot;: { &quot;Address&quot;: [ { &quot;SequenceNo&quot;: &quot;0&quot;, &quot;AddressLine&quot;: &quot;Kharghar,navi mumbai&quot;, &quot;City&quot;: &quot;Maharashtra-Mumbai&quot;, &quot;State&quot;: &quot;Maharashtra&quot;, &quot;PinCode&quot;: &quot;410210&quot;, &quot;Country&quot;: &quot;India&quot;, &quot;Landmark&quot;: &quot;&quot;, &quot;StayFrom&quot;: &quot;01-08-2013&quot;, &quot;StayTo&quot;: &quot;06-08-2021&quot;, &quot;IsCurrentAddress&quot;: false, &quot;IsPermanentAddress&quot;: false, &quot;HouseNo&quot;: &quot;&quot;, &quot;AddressType&quot;: &quot;Current&quot;, &quot;DocList&quot;: { &quot;listofdocs&quot;: [ { &quot;DocumentName&quot;: &quot;abc.jpg&quot;, &quot;DocumentPath&quot;: &quot;base64&quot; } ] } } ] }, &quot;EducationList&quot;: { &quot;Education&quot;: [ { &quot;SequenceNo&quot;: &quot;0&quot;, &quot;Qualification&quot;: &quot;&quot;, &quot;Degree&quot;: &quot;Under Graduate Degree&quot;, &quot;CollegeName&quot;: &quot;Amrutvahini College of engineering, Sangamner (Pune University)&quot;, &quot;Location&quot;: &quot;&quot;, &quot;RollNumber&quot;: &quot;123123&quot;, &quot;UniversityName&quot;: &quot;Mumbai University&quot;, &quot;UniversityAddress&quot;: &quot;&quot;, &quot;PeriodFrom&quot;: &quot;&quot;, &quot;PeriodTo&quot;: &quot;&quot;, &quot;YearOfPassing&quot;: &quot;2014&quot;, &quot;Zipcode&quot;: &quot;&quot;, &quot;Percentage&quot;: &quot;&quot;, &quot;AdditionalRemarks&quot;: &quot;10th/12th/Undergrad etc&quot;, &quot;International&quot;: false, &quot;Country&quot;: &quot;&quot;, &quot;DocList&quot;: { &quot;listofdocs&quot;: [ { &quot;DocumentName&quot;: &quot;abc.jpg&quot;, &quot;DocumentPath&quot;: &quot;base64&quot; } ] } } ] }, &quot;EmploymentList&quot;: { &quot;Employment&quot;: [ { &quot;SequenceNo&quot;: &quot;0&quot;, &quot;EmployerName&quot;: &quot;Stravis Solutions&quot;, &quot;EmployerAddress&quot;: &quot;Bangalore&quot;, &quot;EmployerContactNo&quot;: &quot;&quot;, &quot;Designation&quot;: &quot;SDE&quot;, &quot;EmployeeID&quot;: &quot;asdas&quot;, &quot;FixedSalary&quot;: &quot;0&quot;, &quot;IsCurrentEmployment&quot;: false, &quot;RelievingDate&quot;: &quot;15-10-2021&quot;, &quot;Zipcode&quot;: &quot;&quot;, &quot;International&quot;: false, &quot;Country&quot;: &quot;&quot;, &quot;PFNumber&quot;: &quot;&quot;, &quot;UANNumber&quot;: &quot;&quot;, &quot;DocList&quot;: { &quot;listofdocs&quot;: [ { &quot;DocumentName&quot;: &quot;abc.jpg&quot;, &quot;DocumentPath&quot;: &quot;base64&quot; } ] }, &quot;DateOfJoining&quot;: &quot;18-03-2015&quot; }, { &quot;SequenceNo&quot;: &quot;0&quot;, &quot;EmployerName&quot;: &quot;Stravis Solutions&quot;, &quot;EmployerAddress&quot;: &quot;Bangalore&quot;, &quot;EmployerContactNo&quot;: &quot;&quot;, &quot;Designation&quot;: &quot;SDE&quot;, &quot;EmployeeID&quot;: &quot;asdas&quot;, &quot;FixedSalary&quot;: &quot;0&quot;, &quot;IsCurrentEmployment&quot;: false, &quot;RelievingDate&quot;: &quot;15-10-2021&quot;, &quot;Zipcode&quot;: &quot;&quot;, &quot;International&quot;: false, &quot;Country&quot;: &quot;&quot;, &quot;PFNumber&quot;: &quot;&quot;, &quot;UANNumber&quot;: &quot;&quot;, &quot;DocList&quot;: { &quot;listofdocs&quot;: [ { &quot;DocumentName&quot;: &quot;abc.jpg&quot;, &quot;DocumentPath&quot;: &quot;base64&quot; } ] }, &quot;DateOfJoining&quot;: &quot;18-03-2015&quot; } ] }, &quot;AddressReferencesList&quot;: { &quot;ListofReferences&quot;: [ { &quot;OrganizationName&quot;: &quot;Com 1&quot;, &quot;AdditionalRemarks&quot;: &quot;&quot;, &quot;NameOfReferee&quot;: &quot;Ref1&quot;, &quot;RefereeOccupation&quot;: &quot;SDE&quot;, &quot;RefereePhoneNumber&quot;: &quot;123456&quot;, &quot;RefereeEmailAddress&quot;: &quot;Ref1@com1.com&quot; }, { &quot;OrganizationName&quot;: &quot;Com 1&quot;, &quot;AdditionalRemarks&quot;: &quot;&quot;, &quot;NameOfReferee&quot;: &quot;Ref2&quot;, &quot;RefereeOccupation&quot;: &quot;SDE&quot;, &quot;RefereePhoneNumber&quot;: &quot;123456&quot;, &quot;RefereeEmailAddress&quot;: &quot;Ref1@com1.com&quot; } ] }, &quot;DOB&quot;: &quot;03-08-2021&quot;, &quot;DLDetails&quot;: { &quot;DOB&quot;: &quot;03-08-2021&quot;, &quot;ApplicantName&quot;: &quot;Test&quot;, &quot;FatherName&quot;: &quot;Test&quot;, &quot;UniqueIDCode&quot;: &quot;1231231&quot;, &quot;DocList&quot;: { &quot;listofdocs&quot;: [ { &quot;DocumentName&quot;: &quot;abc.jpg&quot;, &quot;DocumentPath&quot;: &quot;base64&quot; } ] } }, &quot;PanDetails&quot;: { &quot;DOB&quot;: &quot;03-08-2021&quot;, &quot;ApplicantName&quot;: &quot;Sunil Kumar Yadav&quot;, &quot;FatherName&quot;: &quot;Sunil&quot;, &quot;UniqueIDCode&quot;: &quot;23123131&quot;, &quot;DocList&quot;: { &quot;listofdocs&quot;: [ { &quot;DocumentName&quot;: &quot;abc.jpg&quot;, &quot;DocumentPath&quot;: &quot;base64&quot; } ] } }, &quot;PVWDetails&quot;: { &quot;AddressList&quot;: { &quot;Address&quot;: [ { &quot;SequenceNo&quot;: &quot;0&quot;, &quot;AddressLine&quot;: &quot;Kharghar,navi mumbai&quot;, &quot;City&quot;: &quot;Maharashtra-Mumbai&quot;, &quot;State&quot;: &quot;Maharashtra&quot;, &quot;PinCode&quot;: &quot;410210&quot;, &quot;Country&quot;: &quot;India&quot;, &quot;Landmark&quot;: &quot;&quot;, &quot;StayFrom&quot;: &quot;01-08-2013&quot;, &quot;StayTo&quot;: &quot;06-08-2021&quot;, &quot;IsCurrentAddress&quot;: false, &quot;IsPermanentAddress&quot;: false, &quot;HouseNo&quot;: &quot;Sai shradha CHS.Sector-11,&quot;, &quot;AddressType&quot;: &quot;Current&quot;, &quot;DocList&quot;: { &quot;listofdocs&quot;: [ { &quot;DocumentName&quot;: &quot;abc.jpg&quot;, &quot;DocumentPath&quot;: &quot;base64&quot; } ] } } ] }, &quot;DOB&quot;: &quot;03-08-2021&quot;, &quot;FatherName&quot;: &quot;Sunil&quot;, &quot;ApplicantName&quot;: &quot;Sunil Kumar Yadav&quot; }, &quot;CreditDetail&quot;: { &quot;ApplicantName&quot;: &quot;Test&quot;, &quot;DOB&quot;: &quot;03-08-2021&quot;, &quot;FatherName&quot;: &quot;Test&quot;, &quot;Gender&quot;: &quot;Male&quot;, &quot;UniqueIDCode&quot;: &quot;Pan Number&quot;, &quot;EmailID&quot;: &quot;asda@gmail.com&quot;, &quot;DocList&quot;: { &quot;listofdocs&quot;: [ { &quot;DocumentName&quot;: &quot;abc.jpg&quot;, &quot;DocumentPath&quot;: &quot;base64&quot; } ] } }, &quot;PassportCheckDetails&quot;: { &quot;NameInPassport&quot;: &quot;Sunil Kumar Yadav&quot;, &quot;PassportNo&quot;: &quot;1231231&quot;, &quot;MachineReadableZone&quot;: &quot;&quot;, &quot;CandidateFirstName&quot;: &quot;Sunil&quot;, &quot;CandidateLastName&quot;: &quot;Yadav&quot;, &quot;DOB&quot;: &quot;03-08-2021&quot;, &quot;FatherName&quot;: &quot;Sunil&quot;, &quot;DocList&quot;: { &quot;listofdocs&quot;: [ { &quot;DocumentName&quot;: &quot;abc.jpg&quot;, &quot;DocumentPath&quot;: &quot;base64&quot; } ] } } } </code></pre> <p>As you can see, there is an array created for every part of the data. How can I achieve this with XSLT?</p> <p>Whatever code i have tried with so far, the converted JSON has not had any arrays barring cases where there are multiple records under a root.</p> <p>I have tried variations of the following code:</p> <pre><code> &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;xsl:stylesheet version=&quot;1.0&quot; xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot; xmlns:ns0=&quot;http://use your namespace&quot;&gt; &lt;xsl:output method=&quot;text&quot;/&gt; &lt;xsl:template match=&quot;/ns0:Account_Resp&quot;&gt;{ &lt;xsl:apply-templates select=&quot;*&quot;/&gt; } &lt;/xsl:template&gt; &lt;!-- Object or Element Property--&gt; &lt;xsl:template match=&quot;*&quot;&gt; &quot;&lt;xsl:value-of select=&quot;name()&quot;/&gt;&quot; : &lt;xsl:call-template name=&quot;Properties&quot;/&gt; &lt;/xsl:template&gt; &lt;!-- Array Element --&gt; &lt;xsl:template match=&quot;*&quot; mode=&quot;ArrayElement&quot;&gt; &lt;xsl:call-template name=&quot;Properties&quot;/&gt; &lt;/xsl:template&gt; &lt;!-- Object Properties --&gt; &lt;xsl:template name=&quot;Properties&quot;&gt; &lt;xsl:variable name=&quot;childName&quot; select=&quot;name(*[1])&quot;/&gt; &lt;xsl:choose&gt; &lt;xsl:when test=&quot;not(*|@*)&quot;&gt;&quot;&lt;xsl:value-of select=&quot;.&quot;/&gt;&quot;&lt;/xsl:when&gt; &lt;xsl:when test=&quot;count(*[name()=$childName]) &gt; 1&quot;&gt;{ &quot;&lt;xsl:value-of select=&quot;$childName&quot;/&gt;&quot; :[&lt;xsl:apply-templates select=&quot;*&quot; mode=&quot;ArrayElement&quot;/&gt;] }&lt;/xsl:when&gt; &lt;xsl:otherwise&gt;{ &lt;xsl:apply-templates select=&quot;@*&quot;/&gt; &lt;xsl:apply-templates select=&quot;*&quot;/&gt; }&lt;/xsl:otherwise&gt; &lt;/xsl:choose&gt; &lt;xsl:if test=&quot;following-sibling::*&quot;&gt;,&lt;/xsl:if&gt; &lt;/xsl:template&gt; &lt;!-- Attribute Property --&gt; &lt;xsl:template `enter code here`match=&quot;@*&quot;&gt;&quot;&lt;xsl:value-of select=&quot;name()&quot;/&gt;&quot; : &quot;&lt;xsl:value-of select=&quot;.&quot;/&gt;&quot;, &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p>And received the following output - in which you can see that for single payloads, an array is not getting created:</p> <pre><code>{ &quot;ClientID&quot; : &quot;1&quot;, &quot;PackageID&quot; : &quot;650&quot;, &quot;SBUID&quot; : &quot;2187&quot;, &quot;CandidateID&quot; : &quot;456&quot;, &quot;AssociateId&quot; : &quot;789&quot;, &quot;FirstName&quot; : &quot;Meghana&quot;, &quot;MiddleName&quot; : &quot;&quot;, &quot;LastName&quot; : &quot;Rao&quot;, &quot;FatherName&quot; : &quot;Satish&quot;, &quot;ContactNo&quot; : &quot;7530001169&quot;, &quot;EmailID&quot; : &quot;dummy@sap.com&quot;, &quot;AddressHistory&quot; : { &quot;Address&quot; :[{ &quot;SequenceNo&quot; : &quot;0&quot;, &quot;AddressLine&quot; : &quot;Kharghar,navi mumbai&quot;, &quot;City&quot; : &quot;Maharashtra-Mumbai&quot;, &quot;State&quot; : &quot;Maharashtra&quot;, &quot;PinCode&quot; : &quot;410210&quot;, &quot;Country&quot; : &quot;India&quot;, &quot;Landmark&quot; : &quot;&quot;, &quot;StayFrom&quot; : &quot;01-08-2013&quot;, &quot;StayTo&quot; : &quot;06-08-2021&quot;, &quot;IsCurrentAddress&quot; : &quot;false&quot;, &quot;IsPermanentAddress&quot; : &quot;false&quot;, &quot;HouseNo&quot; : &quot;&quot;, &quot;AddressType&quot; : &quot;Current&quot;, &quot;DocList&quot; : { &quot;listofdocs&quot; :[{ &quot;DocumentName&quot; : &quot;abc.jpg&quot;, &quot;DocumentPath&quot; : &quot;base64&quot; }] } },{ &quot;SequenceNo&quot; : &quot;1&quot;, &quot;AddressLine&quot; : &quot;Kharghar,navi mumbai&quot;, &quot;City&quot; : &quot;Maharashtra-Mumbai&quot;, &quot;State&quot; : &quot;Maharashtra&quot;, &quot;PinCode&quot; : &quot;410210&quot;, &quot;Country&quot; : &quot;India&quot;, &quot;Landmark&quot; : &quot;&quot;, &quot;StayFrom&quot; : &quot;01-08-2013&quot;, &quot;StayTo&quot; : &quot;06-08-2021&quot;, &quot;IsCurrentAddress&quot; : &quot;false&quot;, &quot;IsPermanentAddress&quot; : &quot;false&quot;, &quot;HouseNo&quot; : &quot;&quot;, &quot;AddressType&quot; : &quot;Current&quot;, &quot;DocList&quot; : { &quot;listofdocs&quot; :[{ &quot;DocumentName&quot; : &quot;def.jpg&quot;, &quot;DocumentPath&quot; : &quot;base64&quot; }] } }] }, &quot;EducationList&quot; : { &quot;Education&quot; : { &quot;SequenceNo&quot; : &quot;0&quot;, &quot;Qualification&quot; : &quot;&quot;, &quot;Degree&quot; : &quot;Under Graduate Degree&quot;, &quot;CollegeName&quot; : &quot;Amrutvahini College of engineering, Sangamner (Pune University)&quot;, &quot;Location&quot; : &quot;&quot;, &quot;RollNumber&quot; : &quot;123123&quot;, &quot;UniversityName&quot; : &quot;Mumbai University&quot;, &quot;UniversityAddress&quot; : &quot;&quot;, &quot;PeriodFrom&quot; : &quot;&quot;, &quot;PeriodTo&quot; : &quot;&quot;, &quot;YearOfPassing&quot; : &quot;2014&quot;, &quot;Percentage&quot; : &quot;&quot;, &quot;AdditionalRemarks&quot; : &quot;10th/12th/Undergrad etc&quot;, &quot;International&quot; : &quot;false&quot;, &quot;Country&quot; : &quot;&quot;, &quot;DocList&quot; : { &quot;listofdocs&quot; :[{ &quot;DocumentName&quot; : &quot;def.jpg&quot;, &quot;DocumentPath&quot; : &quot;base64&quot; }] } } }, &quot;EmploymentList&quot; : { &quot;Employment&quot; :[{ &quot;SequenceNo&quot; : &quot;0&quot;, &quot;EmployerName&quot; : &quot;Stravis Solutions&quot;, &quot;EmployerAddress&quot; : &quot;Bangalore&quot;, &quot;EmployerContactNo&quot; : &quot;&quot;, &quot;Designation&quot; : &quot;SDE&quot;, &quot;EmployeeID&quot; : &quot;asdas&quot;, &quot;FixedSalary&quot; : &quot;0&quot;, &quot;IsCurrentEmployment&quot; : &quot;false&quot;, &quot;RelievingDate&quot; : &quot;15-10-2021&quot;, &quot;Zipcode&quot; : &quot;&quot;, &quot;International&quot; : &quot;false&quot;, &quot;Country&quot; : &quot;&quot;, &quot;PFNumber&quot; : &quot;&quot;, &quot;UANNumber&quot; : &quot;&quot;, &quot;DocList&quot; : { &quot;listofdocs&quot; : { &quot;DocumentName&quot; : &quot;abc.jpg&quot;, &quot;DocumentPath&quot; : &quot;base64&quot; } }, &quot;DateOfJoining&quot; : &quot;18-03-2015&quot; },{ &quot;SequenceNo&quot; : &quot;1&quot;, &quot;EmployerName&quot; : &quot;Stravis Solutions&quot;, &quot;EmployerAddress&quot; : &quot;Bangalore&quot;, &quot;EmployerContactNo&quot; : &quot;&quot;, &quot;Designation&quot; : &quot;SDE&quot;, &quot;EmployeeID&quot; : &quot;asdas&quot;, &quot;FixedSalary&quot; : &quot;0&quot;, &quot;IsCurrentEmployment&quot; : &quot;false&quot;, &quot;RelievingDate&quot; : &quot;15-10-2021&quot;, &quot;Zipcode&quot; : &quot;&quot;, &quot;International&quot; : &quot;false&quot;, &quot;Country&quot; : &quot;&quot;, &quot;PFNumber&quot; : &quot;&quot;, &quot;UANNumber&quot; : &quot;&quot;, &quot;DocList&quot; : { &quot;listofdocs&quot; : { &quot;DocumentName&quot; : &quot;def.jpg&quot;, &quot;DocumentPath&quot; : &quot;base64&quot; } }, &quot;DateOfJoining&quot; : &quot;18-03-2015&quot; }] }, &quot;AddressReferencesList&quot; : { &quot;ListofReferences&quot; :[{ &quot;OrganizationName&quot; : &quot;Com 1&quot;, &quot;AdditionalRemarks&quot; : &quot;&quot;, &quot;NameOfReferee&quot; : &quot;Ref1&quot;, &quot;RefereeOccupation&quot; : &quot;SDE&quot;, &quot;RefereePhoneNumber&quot; : &quot;123456&quot;, &quot;RefereeEmailAddress&quot; : &quot;Ref1@com1.com&quot; },{ &quot;OrganizationName&quot; : &quot;Com 1&quot;, &quot;AdditionalRemarks&quot; : &quot;&quot;, &quot;NameOfReferee&quot; : &quot;Ref2&quot;, &quot;RefereeOccupation&quot; : &quot;SDE&quot;, &quot;RefereePhoneNumber&quot; : &quot;123456&quot;, &quot;RefereeEmailAddress&quot; : &quot;Ref1@com1.com&quot; }] }, &quot;DOB&quot; : &quot;03-08-2021&quot;, &quot;DLDetails&quot; : { &quot;DOB&quot; : &quot;03-08-2021&quot;, &quot;ApplicantName&quot; : &quot;Test&quot;, &quot;FatherName&quot; : &quot;Test&quot;, &quot;UniqueIDCode&quot; : &quot;1231231&quot;, &quot;DocList&quot; : { &quot;listofdocs&quot; : { &quot;DocumentName&quot; : &quot;abc.jpg&quot;, &quot;DocumentPath&quot; : &quot;base64&quot; } } }, &quot;PanDetails&quot; : { &quot;DOB&quot; : &quot;03-08-2021&quot;, &quot;ApplicantName&quot; : &quot;Sunil Kumar Yadav&quot;, &quot;FatherName&quot; : &quot;Sunil&quot;, &quot;UniqueIDCode&quot; : &quot;23123131&quot;, &quot;DocList&quot; : { &quot;listofdocs&quot; : { &quot;DocumentName&quot; : &quot;abc.jpg&quot;, &quot;DocumentPath&quot; : &quot;base64&quot; } } }, &quot;PVWDetails&quot; : { &quot;AddressList&quot; : { &quot;Address&quot; : { &quot;SequenceNo&quot; : &quot;0&quot;, &quot;AddressLine&quot; : &quot;Kharghar,navi mumbai&quot;, &quot;City&quot; : &quot;Maharashtra-Mumbai&quot;, &quot;State&quot; : &quot;Maharashtra&quot;, &quot;PinCode&quot; : &quot;410210&quot;, &quot;Country&quot; : &quot;India&quot;, &quot;Landmark&quot; : &quot;&quot;, &quot;StayFrom&quot; : &quot;01-08-2013&quot;, &quot;StayTo&quot; : &quot;06-08-2021&quot;, &quot;IsCurrentAddress&quot; : &quot;false&quot;, &quot;IsPermanentAddress&quot; : &quot;false&quot;, &quot;HouseNo&quot; : &quot;Sai shradha CHS.Sector-11,&quot;, &quot;AddressType&quot; : &quot;Current&quot; } }, &quot;DOB&quot; : &quot;03-08-2021&quot;, &quot;FatherName&quot; : &quot;Sunil&quot;, &quot;ApplicantName&quot; : &quot;Sunil Kumar Yadav&quot; }, &quot;CreditDetail&quot; : { &quot;ApplicantName&quot; : &quot;Test&quot;, &quot;DOB&quot; : &quot;03-08-2021&quot;, &quot;FatherName&quot; : &quot;Test&quot;, &quot;Gender&quot; : &quot;Male&quot;, &quot;UniqueIDCode&quot; : &quot;Pan Number&quot;, &quot;EmailID&quot; : &quot;asda@gmail.com&quot;, &quot;DocList&quot; : { &quot;listofdocs&quot; : { &quot;DocumentName&quot; : &quot;abc.jpg&quot;, &quot;DocumentPath&quot; : &quot;base64&quot; } } }, &quot;DrugTestPanelCheck&quot; : { &quot;DrugTestPanel&quot; : &quot;DrugTestPanel5&quot;, &quot;ApplicantName&quot; : &quot;Test Candidate&quot; }, &quot;GDCDetails&quot; : { &quot;ApplicantName&quot; : &quot;Sunil Kumar Yadav&quot;, &quot;DOB&quot; : &quot;03-08-2021&quot;, &quot;FatherName&quot; : &quot;Sunil&quot; }, &quot;PassportCheckDetails&quot; : { &quot;NameInPassport&quot; : &quot;Sunil Kumar Yadav&quot;, &quot;PassportNo&quot; : &quot;1231231&quot;, &quot;MachineReadableZone&quot; : &quot;&quot;, &quot;CandidateFirstName&quot; : &quot;Sunil&quot;, &quot;CandidateLastName&quot; : &quot;Yadav&quot;, &quot;DOB&quot; : &quot;03-08-2021&quot;, &quot;FatherName&quot; : &quot;Sunil&quot;, &quot;DocList&quot; : { &quot;listofdocs&quot; : { &quot;DocumentName&quot; : &quot;abc.jpg&quot;, &quot;DocumentPath&quot; : &quot;base64&quot; } } } } </code></pre> <p>Really need some help on this. Thanks</p>
[ { "answer_id": 74535938, "author": "Heiko Theißen", "author_id": 16462950, "author_profile": "https://Stackoverflow.com/users/16462950", "pm_score": 1, "selected": false, "text": "count(*[name()=$childName]) > 1 <EducationList> <Education> List count(*[name()=$childName]) > 1 substring(name(), string-length(name()) - 3, 4) = 'List'\n" }, { "answer_id": 74536504, "author": "jpseng", "author_id": 16332641, "author_profile": "https://Stackoverflow.com/users/16332641", "pm_score": 0, "selected": false, "text": "yq --input-format xml --output-format json '\nwith(.root;\n .AddressHistory.Address |= select(type == \"!!map\") |= [.] |\n .EducationList.Education |= select(type == \"!!map\") |= [.] |\n .EmploymentList.Employment |= select(type == \"!!map\") |= [.] |\n .AddressReferencesList.ListofReferences |= select(type == \"!!map\") |= [.] |\n .PVWDetails.AddressList.Address |= select(type == \"!!map\") |= [.]\n )\n ' input.xml\n |= select(type == \"!!map\") [.] ARRAY_PATHS='\n[\n \"root.AddressHistory.Address\",\n \"root.EducationList.Education\",\n \"root.EmploymentList.Employment\",\n \"root.AddressReferencesList.ListofReferences\",\n \"root.PVWDetails.AddressList.Address\"\n]\n'\n\nxq --argjson paths \"$ARRAY_PATHS\" '\n . as $input\n | reduce ($paths\n | map(split(\".\") # split given paths by \".\"\n | . as $p\n | select($input | getpath($p) | type == \"object\")))[] # process only objects at the given paths (ignore arrays)\n as $path\n (.; setpath($path; [getpath($path)])) # wrap objects at the given paths in an array\n ' input.xml\n select($input | getpath($p) | type == \"object\") setpath($path; [getpath($path)]) {\n \"root\": {\n \"ClientID\": \"1\",\n \"PackageID\": \"650\",\n \"SBUID\": \"2187\",\n \"CandidateID\": \"456\",\n \"AssociateId\": \"789\",\n \"FirstName\": \"Meghana\",\n \"MiddleName\": null,\n \"LastName\": \"Rao\",\n \"FatherName\": \"Satish\",\n \"ContactNo\": \"7530001169\",\n \"EmailID\": \"dummy@sap.com\",\n \"AddressHistory\": {\n \"Address\": [\n {\n \"SequenceNo\": \"0\",\n \"AddressLine\": \"Kharghar,navi mumbai\",\n \"City\": \"Maharashtra-Mumbai\",\n \"State\": \"Maharashtra\",\n \"PinCode\": \"410210\",\n \"Country\": \"India\",\n \"Landmark\": null,\n \"StayFrom\": \"01-08-2013\",\n \"StayTo\": \"06-08-2021\",\n \"IsCurrentAddress\": \"false\",\n \"IsPermanentAddress\": \"false\",\n \"HouseNo\": null,\n \"AddressType\": \"Current\",\n \"DocList\": {\n \"listofdocs\": {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n }\n }\n ]\n },\n \"EducationList\": {\n \"Education\": [\n {\n \"SequenceNo\": \"0\",\n \"Qualification\": null,\n \"Degree\": \"Under Graduate Degree\",\n \"CollegeName\": \"Amrutvahini College of engineering, Sangamner (Pune University)\",\n \"Location\": null,\n \"RollNumber\": \"123123\",\n \"UniversityName\": \"Mumbai University\",\n \"UniversityAddress\": null,\n \"PeriodFrom\": null,\n \"PeriodTo\": null,\n \"YearOfPassing\": \"2014\",\n \"Zipcode\": null,\n \"Percentage\": null,\n \"AdditionalRemarks\": \"10th/12th/Undergrad etc\",\n \"International\": \"false\",\n \"Country\": null,\n \"DocList\": {\n \"listofdocs\": {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n }\n }\n ]\n },\n \"EmploymentList\": {\n \"Employment\": [\n {\n \"SequenceNo\": \"0\",\n \"EmployerName\": \"Stravis Solutions\",\n \"EmployerAddress\": \"Bangalore\",\n \"EmployerContactNo\": null,\n \"Designation\": \"SDE\",\n \"EmployeeID\": \"asdas\",\n \"FixedSalary\": \"0\",\n \"IsCurrentEmployment\": \"false\",\n \"RelievingDate\": \"15-10-2021\",\n \"State\": null,\n \"City\": null,\n \"Zipcode\": null,\n \"International\": \"false\",\n \"Country\": null,\n \"PFNumber\": null,\n \"UANNumber\": null,\n \"DocList\": {\n \"listofdocs\": {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n },\n \"DateOfJoining\": \"18-03-2015\"\n },\n {\n \"SequenceNo\": \"0\",\n \"EmployerName\": \"Stravis Solutions\",\n \"EmployerAddress\": \"Bangalore\",\n \"EmployerContactNo\": null,\n \"Designation\": \"SDE\",\n \"EmployeeID\": \"asdas\",\n \"FixedSalary\": \"0\",\n \"IsCurrentEmployment\": \"false\",\n \"RelievingDate\": \"15-10-2021\",\n \"International\": \"false\",\n \"Country\": null,\n \"PFNumber\": null,\n \"UANNumber\": null,\n \"DocList\": {\n \"listofdocs\": {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n },\n \"DateOfJoining\": \"18-03-2015\"\n }\n ]\n },\n \"AddressReferencesList\": {\n \"ListofReferences\": [\n {\n \"OrganizationName\": \"Com 1\",\n \"AdditionalRemarks\": null,\n \"NameOfReferee\": \"Ref1\",\n \"RefereeOccupation\": \"SDE\",\n \"RefereePhoneNumber\": \"123456\",\n \"RefereeEmailAddress\": \"Ref1@com1.com\"\n },\n {\n \"OrganizationName\": \"Com 1\",\n \"AdditionalRemarks\": null,\n \"NameOfReferee\": \"Ref1\",\n \"RefereeOccupation\": \"SDE\",\n \"RefereePhoneNumber\": \"123456\",\n \"RefereeEmailAddress\": \"Ref1@com1.com\"\n }\n ]\n },\n \"DOB\": \"03-08-2021\",\n \"DLDetails\": {\n \"DOB\": \"03-08-2021\",\n \"ApplicantName\": \"Test\",\n \"FatherName\": \"Test\",\n \"dl_remarks\": null,\n \"UniqueIDCode\": \"1231231\",\n \"DocList\": {\n \"listofdocs\": {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n }\n },\n \"PanDetails\": {\n \"DOB\": \"03-08-2021\",\n \"ApplicantName\": \"Sunil Kumar Yadav\",\n \"FatherName\": \"Sunil\",\n \"pan_remarks\": null,\n \"UniqueIDCode\": \"23123131\",\n \"DocList\": {\n \"listofdocs\": {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n }\n },\n \"PVWDetails\": {\n \"AddressList\": {\n \"Address\": [\n {\n \"SequenceNo\": \"0\",\n \"AddressLine\": \"Kharghar,navi mumbai\",\n \"City\": \"Maharashtra-Mumbai\",\n \"State\": \"Maharashtra\",\n \"PinCode\": \"410210\",\n \"Country\": \"India\",\n \"Landmark\": null,\n \"StayFrom\": \"01-08-2013\",\n \"StayTo\": \"06-08-2021\",\n \"IsCurrentAddress\": \"false\",\n \"IsPermanentAddress\": \"false\",\n \"HouseNo\": \"Sai shradha CHS.Sector-11,\",\n \"AddressType\": \"Current\",\n \"DocList\": {\n \"listofdocs\": {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n }\n }\n ]\n },\n \"DOB\": \"03-08-2021\",\n \"FatherName\": \"Sunil\",\n \"ApplicantName\": \"Sunil Kumar Yadav\"\n },\n \"CreditDetail\": {\n \"ApplicantName\": \"Test\",\n \"DOB\": \"03-08-2021\",\n \"FatherName\": \"Test\",\n \"Gender\": \"Male\",\n \"UniqueIDCode\": \"Pan Number\",\n \"EmailID\": \"asda@gmail.com\",\n \"DocList\": {\n \"listofdocs\": {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n }\n },\n \"DrugTestPanelCheck\": {\n \"DrugTestPanel\": \"DrugTestPanel5\",\n \"ApplicantName\": \"Test Candidate\"\n },\n \"GDCDetails\": {\n \"ApplicantName\": \"Sunil Kumar Yadav\",\n \"DOB\": \"03-08-2021\",\n \"FatherName\": \"Sunil\"\n },\n \"PassportCheckDetails\": {\n \"NameInPassport\": \"Sunil Kumar Yadav\",\n \"PassportNo\": \"1231231\",\n \"MachineReadableZone\": null,\n \"CandidateFirstName\": \"Sunil\",\n \"CandidateLastName\": \"Yadav\",\n \"DOB\": \"03-08-2021\",\n \"FatherName\": \"Sunil\",\n \"DocList\": {\n \"listofdocs\": {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n }\n }\n }\n}\n" }, { "answer_id": 74582325, "author": "pgfearo", "author_id": 63965, "author_profile": "https://Stackoverflow.com/users/63965", "pm_score": 0, "selected": false, "text": "xml-to-json xsl:template <xsl:template match=\"*[*]\" mode=\"outer\">\n<xsl:param name=\"key\" as=\"xs:string?\"/>\n<xsl:variable name=\"distinctChildNames\" as=\"xs:string*\" select=\"*!name() => distinct-values()\"/>\n<xsl:choose>\n <xsl:when test=\"count($distinctChildNames) gt 1 and exists($key)\">\n <array>\n <xsl:sequence select=\"fn:keyAttribute(name())\"/>\n <map>\n <xsl:apply-templates select=\"*\" mode=\"outer\">\n <xsl:with-param name=\"key\" select=\"name()\"/>\n </xsl:apply-templates>\n </map>\n </array>\n </xsl:when>\n <xsl:when test=\"count(*) gt 1 and count($distinctChildNames) eq 1\">\n <map>\n <xsl:sequence select=\"fn:keyAttribute(name())\"/>\n <array key=\"{name(*[1])}\">\n <xsl:for-each select=\"*\">\n <map>\n <xsl:apply-templates select=\"*\" mode=\"outer\"/>\n </map>\n </xsl:for-each>\n </array>\n </map>\n </xsl:when>\n <xsl:otherwise>\n <map>\n <xsl:sequence select=\"fn:keyAttribute(name())\"/> \n <xsl:apply-templates select=\"*\" mode=\"outer\">\n <xsl:with-param name=\"key\" select=\"name()\"/>\n </xsl:apply-templates> \n </map>\n </xsl:otherwise>\n</xsl:choose>\n</xsl:template>\n {\n \"ClientID\": \"1\",\n \"PackageID\": \"650\",\n \"SBUID\": \"2187\",\n \"CandidateID\": \"456\",\n \"AssociateId\": \"789\",\n \"FirstName\": \"Meghana\",\n \"MiddleName\": \"\",\n \"LastName\": \"Rao\",\n \"FatherName\": \"Satish\",\n \"ContactNo\": \"7530001169\",\n \"EmailID\": \"dummy@sap.com\",\n \"AddressHistory\": {\n \"Address\": [\n {\n \"SequenceNo\": \"0\",\n \"AddressLine\": \"Kharghar,navi mumbai\",\n \"City\": \"Maharashtra-Mumbai\",\n \"State\": \"Maharashtra\",\n \"PinCode\": \"410210\",\n \"Country\": \"India\",\n \"Landmark\": \"\",\n \"StayFrom\": \"01-08-2013\",\n \"StayTo\": \"06-08-2021\",\n \"IsCurrentAddress\": false,\n \"IsPermanentAddress\": false,\n \"HouseNo\": \"\",\n \"AddressType\": \"Current\",\n \"DocList\": {\n \"listofdocs\": [\n {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n ]\n }\n }\n ]\n },\n \"EducationList\": {\n \"Education\": [\n {\n \"SequenceNo\": \"0\",\n \"Qualification\": \"\",\n \"Degree\": \"Under Graduate Degree\",\n \"CollegeName\": \"Amrutvahini College of engineering, Sangamner (Pune University)\",\n \"Location\": \"\",\n \"RollNumber\": \"123123\",\n \"UniversityName\": \"Mumbai University\",\n \"UniversityAddress\": \"\",\n \"PeriodFrom\": \"\",\n \"PeriodTo\": \"\",\n \"YearOfPassing\": \"2014\",\n \"Zipcode\": \"\",\n \"Percentage\": \"\",\n \"AdditionalRemarks\": \"10th\\/12th\\/Undergrad etc\",\n \"International\": false,\n \"Country\": \"\",\n \"DocList\": {\n \"listofdocs\": [\n {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n ]\n }\n }\n ]\n },\n \"EmploymentList\": {\n \"Employment\": [\n {\n \"SequenceNo\": \"0\",\n \"EmployerName\": \"Stravis Solutions\",\n \"EmployerAddress\": \"Bangalore\",\n \"EmployerContactNo\": \"\",\n \"Designation\": \"SDE\",\n \"EmployeeID\": \"asdas\",\n \"FixedSalary\": \"0\",\n \"IsCurrentEmployment\": false,\n \"RelievingDate\": \"15-10-2021\",\n \"State\": \"\",\n \"City\": \"\",\n \"Zipcode\": \"\",\n \"International\": false,\n \"Country\": \"\",\n \"PFNumber\": \"\",\n \"UANNumber\": \"\",\n \"DocList\": {\n \"listofdocs\": [\n {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n ]\n },\n \"DateOfJoining\": \"18-03-2015\"\n },\n {\n \"SequenceNo\": \"0\",\n \"EmployerName\": \"Stravis Solutions\",\n \"EmployerAddress\": \"Bangalore\",\n \"EmployerContactNo\": \"\",\n \"Designation\": \"SDE\",\n \"EmployeeID\": \"asdas\",\n \"FixedSalary\": \"0\",\n \"IsCurrentEmployment\": false,\n \"RelievingDate\": \"15-10-2021\",\n \"International\": false,\n \"Country\": \"\",\n \"PFNumber\": \"\",\n \"UANNumber\": \"\",\n \"DocList\": {\n \"listofdocs\": [\n {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n ]\n },\n \"DateOfJoining\": \"18-03-2015\"\n }\n ]\n },\n \"AddressReferencesList\": {\n \"ListofReferences\": [\n {\n \"OrganizationName\": \"Com 1\",\n \"AdditionalRemarks\": \"\",\n \"NameOfReferee\": \"Ref1\",\n \"RefereeOccupation\": \"SDE\",\n \"RefereePhoneNumber\": \"123456\",\n \"RefereeEmailAddress\": \"Ref1@com1.com\"\n },\n {\n \"OrganizationName\": \"Com 1\",\n \"AdditionalRemarks\": \"\",\n \"NameOfReferee\": \"Ref1\",\n \"RefereeOccupation\": \"SDE\",\n \"RefereePhoneNumber\": \"123456\",\n \"RefereeEmailAddress\": \"Ref1@com1.com\"\n }\n ]\n },\n \"DOB\": \"03-08-2021\",\n \"DLDetails\": {\n \"DOB\": \"03-08-2021\",\n \"ApplicantName\": \"Test\",\n \"FatherName\": \"Test\",\n \"dl_remarks\": \"\",\n \"UniqueIDCode\": \"1231231\",\n \"DocList\": {\n \"listofdocs\": [\n {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n ]\n }\n },\n \"PanDetails\": {\n \"DOB\": \"03-08-2021\",\n \"ApplicantName\": \"Sunil Kumar Yadav\",\n \"FatherName\": \"Sunil\",\n \"pan_remarks\": \"\",\n \"UniqueIDCode\": \"23123131\",\n \"DocList\": {\n \"listofdocs\": [\n {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n ]\n }\n },\n \"PVWDetails\": {\n \"AddressList\": {\n \"Address\": [\n {\n \"SequenceNo\": \"0\",\n \"AddressLine\": \"Kharghar,navi mumbai\",\n \"City\": \"Maharashtra-Mumbai\",\n \"State\": \"Maharashtra\",\n \"PinCode\": \"410210\",\n \"Country\": \"India\",\n \"Landmark\": \"\",\n \"StayFrom\": \"01-08-2013\",\n \"StayTo\": \"06-08-2021\",\n \"IsCurrentAddress\": false,\n \"IsPermanentAddress\": false,\n \"HouseNo\": \"Sai shradha CHS.Sector-11,\",\n \"AddressType\": \"Current\",\n \"DocList\": {\n \"listofdocs\": [\n {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n ]\n }\n }\n ]\n },\n \"DOB\": \"03-08-2021\",\n \"FatherName\": \"Sunil\",\n \"ApplicantName\": \"Sunil Kumar Yadav\"\n },\n \"CreditDetail\": {\n \"ApplicantName\": \"Test\",\n \"DOB\": \"03-08-2021\",\n \"FatherName\": \"Test\",\n \"Gender\": \"Male\",\n \"UniqueIDCode\": \"Pan Number\",\n \"EmailID\": \"asda@gmail.com\",\n \"DocList\": {\n \"listofdocs\": [\n {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n ]\n }\n },\n \"DrugTestPanelCheck\": {\n \"DrugTestPanel\": \"DrugTestPanel5\",\n \"ApplicantName\": \"Test Candidate\"\n },\n \"GDCDetails\": {\n \"ApplicantName\": \"Sunil Kumar Yadav\",\n \"DOB\": \"03-08-2021\",\n \"FatherName\": \"Sunil\"\n },\n \"PassportCheckDetails\": {\n \"NameInPassport\": \"Sunil Kumar Yadav\",\n \"PassportNo\": \"1231231\",\n \"MachineReadableZone\": \"\",\n \"CandidateFirstName\": \"Sunil\",\n \"CandidateLastName\": \"Yadav\",\n \"DOB\": \"03-08-2021\",\n \"FatherName\": \"Sunil\",\n \"DocList\": {\n \"listofdocs\": [\n {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n ]\n }\n }\n}\n \\/ <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n xmlns:fn=\"com.example.functions\"\n xmlns=\"http://www.w3.org/2005/xpath-functions\"\n expand-text=\"yes\"\n version=\"3.0\">\n \n <xsl:output method=\"text\" indent=\"yes\"/>\n <xsl:mode on-no-match=\"shallow-copy\"/>\n <xsl:mode name=\"outer\" on-no-match=\"shallow-copy\"/>\n \n <xsl:template match=\"/*\">\n <xsl:variable name=\"result\" as=\"node()*\">\n <map>\n <xsl:apply-templates select=\"*\" mode=\"outer\"/>\n </map>\n </xsl:variable>\n <xsl:sequence select=\"xml-to-json($result)\"/>\n </xsl:template>\n \n <xsl:template match=\"*[*]\" mode=\"outer\">\n <xsl:param name=\"key\" as=\"xs:string?\"/>\n <xsl:variable name=\"distinctChildNames\" as=\"xs:string*\" select=\"*!name() => distinct-values()\"/>\n <xsl:choose>\n <xsl:when test=\"count($distinctChildNames) gt 1 and exists($key)\">\n <array>\n <xsl:sequence select=\"fn:keyAttribute(name())\"/>\n <map>\n <xsl:apply-templates select=\"*\" mode=\"outer\">\n <xsl:with-param name=\"key\" select=\"name()\"/>\n </xsl:apply-templates>\n </map>\n </array>\n </xsl:when>\n <xsl:when test=\"count(*) gt 1 and count($distinctChildNames) eq 1\">\n <map>\n <xsl:sequence select=\"fn:keyAttribute(name())\"/>\n <array key=\"{name(*[1])}\">\n <xsl:for-each select=\"*\">\n <map>\n <xsl:apply-templates select=\"*\" mode=\"outer\"/>\n </map>\n </xsl:for-each>\n </array>\n </map>\n </xsl:when>\n <xsl:otherwise>\n <map>\n <xsl:sequence select=\"fn:keyAttribute(name())\"/> \n <xsl:apply-templates select=\"*\" mode=\"outer\">\n <xsl:with-param name=\"key\" select=\"name()\"/>\n </xsl:apply-templates> \n </map>\n </xsl:otherwise>\n </xsl:choose>\n </xsl:template>\n \n <xsl:template match=\"*[empty(*) and exists(text())]\" mode=\"outer\">\n <xsl:apply-templates select=\"node()\" mode=\"outer\">\n <xsl:with-param name=\"key\" select=\"name()\"/>\n </xsl:apply-templates>\n </xsl:template>\n \n <xsl:template match=\"*[empty(*) and empty(text())]\" mode=\"outer\">\n <string key=\"{name()}\"/>\n </xsl:template>\n \n <xsl:template match=\"text()[. = ('true', 'false')]\" mode=\"outer\">\n <xsl:param name=\"key\" as=\"xs:string?\"/>\n <boolean key=\"{$key}\">{.}</boolean>\n </xsl:template>\n \n <xsl:template match=\"text()\" mode=\"outer\">\n <xsl:param name=\"key\" as=\"xs:string?\"/>\n <xsl:if test=\"exists($key)\">\n <string key=\"{$key}\">{.}</string>\n </xsl:if>\n </xsl:template>\n \n <xsl:function name=\"fn:keyAttribute\" as=\"attribute()?\">\n <xsl:param name=\"key\" as=\"xs:string?\"/>\n <xsl:if test=\"$key\">\n <xsl:attribute name=\"key\" select=\"$key\"/>\n </xsl:if>\n </xsl:function>\n \n</xsl:stylesheet>\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20573341/" ]
74,534,794
<p>This question applies only for HTTPS requests.</p> <p>Lets divide the problem in 3 areas.</p> <ol> <li>The origin. This is the user sending an HTTPS request.</li> <li>The proxy. This will handle the request, forward it to the remote and vice-versa.</li> <li>The remote. This is the server where the request is supposed to arrive.</li> </ol> <p>When you make an HTTPS request through a proxy, this is what happens:</p> <ol> <li><p>Origin sends with HTTP (this is not encrypted):</p> <p>CONNECT remote.url:443 HTTP/1.1 ...</p> </li> <li><p>Proxy replies:</p> <p>HTTP/1.1 200 Connection established</p> </li> <li><p>Origin sends the request to the proxy, totally encrypted:</p> <p>Cᆭᅯi ᄃJ￁,タᆵH;ホUᆲ*ネᄋ#cR{gリ ᄋ�ᅣ゙WuᅠY&lt;u#1ナ￳#j￴iᅲH뮤k...</p> </li> <li><p>Proxy takes it as it is, and it forwards it to remote:</p> <p>Cᆭᅯi ᄃJ￁,タᆵH;ホUᆲ*ネᄋ#cR{gリ ᄋ�ᅣ゙WuᅠY&lt;u#1ナ￳#j￴iᅲH뮤k...</p> </li> <li><p>Remote replies, it is also totally encrypted:</p> <p>cR{gリ ᄋ�ᅣ゙WuᅠY&lt;u#1...</p> </li> <li><p>Proxy passes this to the origin:</p> <p>cR{gリ ᄋ�ᅣ゙WuᅠY&lt;u#1...</p> </li> <li><p>Origin knows how to decrypt this and it is happy to receive the response.</p> </li> </ol> <p>The question is, how does the proxy knows that the response is terminated?. The proxy is just reading streams, and cannot know the end of it. Moreover, it cannot read HTTP headers to know the length because they are encrypted.</p> <p>I am facing this issue in Java and I don't know how to deal with that.</p>
[ { "answer_id": 74535938, "author": "Heiko Theißen", "author_id": 16462950, "author_profile": "https://Stackoverflow.com/users/16462950", "pm_score": 1, "selected": false, "text": "count(*[name()=$childName]) > 1 <EducationList> <Education> List count(*[name()=$childName]) > 1 substring(name(), string-length(name()) - 3, 4) = 'List'\n" }, { "answer_id": 74536504, "author": "jpseng", "author_id": 16332641, "author_profile": "https://Stackoverflow.com/users/16332641", "pm_score": 0, "selected": false, "text": "yq --input-format xml --output-format json '\nwith(.root;\n .AddressHistory.Address |= select(type == \"!!map\") |= [.] |\n .EducationList.Education |= select(type == \"!!map\") |= [.] |\n .EmploymentList.Employment |= select(type == \"!!map\") |= [.] |\n .AddressReferencesList.ListofReferences |= select(type == \"!!map\") |= [.] |\n .PVWDetails.AddressList.Address |= select(type == \"!!map\") |= [.]\n )\n ' input.xml\n |= select(type == \"!!map\") [.] ARRAY_PATHS='\n[\n \"root.AddressHistory.Address\",\n \"root.EducationList.Education\",\n \"root.EmploymentList.Employment\",\n \"root.AddressReferencesList.ListofReferences\",\n \"root.PVWDetails.AddressList.Address\"\n]\n'\n\nxq --argjson paths \"$ARRAY_PATHS\" '\n . as $input\n | reduce ($paths\n | map(split(\".\") # split given paths by \".\"\n | . as $p\n | select($input | getpath($p) | type == \"object\")))[] # process only objects at the given paths (ignore arrays)\n as $path\n (.; setpath($path; [getpath($path)])) # wrap objects at the given paths in an array\n ' input.xml\n select($input | getpath($p) | type == \"object\") setpath($path; [getpath($path)]) {\n \"root\": {\n \"ClientID\": \"1\",\n \"PackageID\": \"650\",\n \"SBUID\": \"2187\",\n \"CandidateID\": \"456\",\n \"AssociateId\": \"789\",\n \"FirstName\": \"Meghana\",\n \"MiddleName\": null,\n \"LastName\": \"Rao\",\n \"FatherName\": \"Satish\",\n \"ContactNo\": \"7530001169\",\n \"EmailID\": \"dummy@sap.com\",\n \"AddressHistory\": {\n \"Address\": [\n {\n \"SequenceNo\": \"0\",\n \"AddressLine\": \"Kharghar,navi mumbai\",\n \"City\": \"Maharashtra-Mumbai\",\n \"State\": \"Maharashtra\",\n \"PinCode\": \"410210\",\n \"Country\": \"India\",\n \"Landmark\": null,\n \"StayFrom\": \"01-08-2013\",\n \"StayTo\": \"06-08-2021\",\n \"IsCurrentAddress\": \"false\",\n \"IsPermanentAddress\": \"false\",\n \"HouseNo\": null,\n \"AddressType\": \"Current\",\n \"DocList\": {\n \"listofdocs\": {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n }\n }\n ]\n },\n \"EducationList\": {\n \"Education\": [\n {\n \"SequenceNo\": \"0\",\n \"Qualification\": null,\n \"Degree\": \"Under Graduate Degree\",\n \"CollegeName\": \"Amrutvahini College of engineering, Sangamner (Pune University)\",\n \"Location\": null,\n \"RollNumber\": \"123123\",\n \"UniversityName\": \"Mumbai University\",\n \"UniversityAddress\": null,\n \"PeriodFrom\": null,\n \"PeriodTo\": null,\n \"YearOfPassing\": \"2014\",\n \"Zipcode\": null,\n \"Percentage\": null,\n \"AdditionalRemarks\": \"10th/12th/Undergrad etc\",\n \"International\": \"false\",\n \"Country\": null,\n \"DocList\": {\n \"listofdocs\": {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n }\n }\n ]\n },\n \"EmploymentList\": {\n \"Employment\": [\n {\n \"SequenceNo\": \"0\",\n \"EmployerName\": \"Stravis Solutions\",\n \"EmployerAddress\": \"Bangalore\",\n \"EmployerContactNo\": null,\n \"Designation\": \"SDE\",\n \"EmployeeID\": \"asdas\",\n \"FixedSalary\": \"0\",\n \"IsCurrentEmployment\": \"false\",\n \"RelievingDate\": \"15-10-2021\",\n \"State\": null,\n \"City\": null,\n \"Zipcode\": null,\n \"International\": \"false\",\n \"Country\": null,\n \"PFNumber\": null,\n \"UANNumber\": null,\n \"DocList\": {\n \"listofdocs\": {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n },\n \"DateOfJoining\": \"18-03-2015\"\n },\n {\n \"SequenceNo\": \"0\",\n \"EmployerName\": \"Stravis Solutions\",\n \"EmployerAddress\": \"Bangalore\",\n \"EmployerContactNo\": null,\n \"Designation\": \"SDE\",\n \"EmployeeID\": \"asdas\",\n \"FixedSalary\": \"0\",\n \"IsCurrentEmployment\": \"false\",\n \"RelievingDate\": \"15-10-2021\",\n \"International\": \"false\",\n \"Country\": null,\n \"PFNumber\": null,\n \"UANNumber\": null,\n \"DocList\": {\n \"listofdocs\": {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n },\n \"DateOfJoining\": \"18-03-2015\"\n }\n ]\n },\n \"AddressReferencesList\": {\n \"ListofReferences\": [\n {\n \"OrganizationName\": \"Com 1\",\n \"AdditionalRemarks\": null,\n \"NameOfReferee\": \"Ref1\",\n \"RefereeOccupation\": \"SDE\",\n \"RefereePhoneNumber\": \"123456\",\n \"RefereeEmailAddress\": \"Ref1@com1.com\"\n },\n {\n \"OrganizationName\": \"Com 1\",\n \"AdditionalRemarks\": null,\n \"NameOfReferee\": \"Ref1\",\n \"RefereeOccupation\": \"SDE\",\n \"RefereePhoneNumber\": \"123456\",\n \"RefereeEmailAddress\": \"Ref1@com1.com\"\n }\n ]\n },\n \"DOB\": \"03-08-2021\",\n \"DLDetails\": {\n \"DOB\": \"03-08-2021\",\n \"ApplicantName\": \"Test\",\n \"FatherName\": \"Test\",\n \"dl_remarks\": null,\n \"UniqueIDCode\": \"1231231\",\n \"DocList\": {\n \"listofdocs\": {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n }\n },\n \"PanDetails\": {\n \"DOB\": \"03-08-2021\",\n \"ApplicantName\": \"Sunil Kumar Yadav\",\n \"FatherName\": \"Sunil\",\n \"pan_remarks\": null,\n \"UniqueIDCode\": \"23123131\",\n \"DocList\": {\n \"listofdocs\": {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n }\n },\n \"PVWDetails\": {\n \"AddressList\": {\n \"Address\": [\n {\n \"SequenceNo\": \"0\",\n \"AddressLine\": \"Kharghar,navi mumbai\",\n \"City\": \"Maharashtra-Mumbai\",\n \"State\": \"Maharashtra\",\n \"PinCode\": \"410210\",\n \"Country\": \"India\",\n \"Landmark\": null,\n \"StayFrom\": \"01-08-2013\",\n \"StayTo\": \"06-08-2021\",\n \"IsCurrentAddress\": \"false\",\n \"IsPermanentAddress\": \"false\",\n \"HouseNo\": \"Sai shradha CHS.Sector-11,\",\n \"AddressType\": \"Current\",\n \"DocList\": {\n \"listofdocs\": {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n }\n }\n ]\n },\n \"DOB\": \"03-08-2021\",\n \"FatherName\": \"Sunil\",\n \"ApplicantName\": \"Sunil Kumar Yadav\"\n },\n \"CreditDetail\": {\n \"ApplicantName\": \"Test\",\n \"DOB\": \"03-08-2021\",\n \"FatherName\": \"Test\",\n \"Gender\": \"Male\",\n \"UniqueIDCode\": \"Pan Number\",\n \"EmailID\": \"asda@gmail.com\",\n \"DocList\": {\n \"listofdocs\": {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n }\n },\n \"DrugTestPanelCheck\": {\n \"DrugTestPanel\": \"DrugTestPanel5\",\n \"ApplicantName\": \"Test Candidate\"\n },\n \"GDCDetails\": {\n \"ApplicantName\": \"Sunil Kumar Yadav\",\n \"DOB\": \"03-08-2021\",\n \"FatherName\": \"Sunil\"\n },\n \"PassportCheckDetails\": {\n \"NameInPassport\": \"Sunil Kumar Yadav\",\n \"PassportNo\": \"1231231\",\n \"MachineReadableZone\": null,\n \"CandidateFirstName\": \"Sunil\",\n \"CandidateLastName\": \"Yadav\",\n \"DOB\": \"03-08-2021\",\n \"FatherName\": \"Sunil\",\n \"DocList\": {\n \"listofdocs\": {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n }\n }\n }\n}\n" }, { "answer_id": 74582325, "author": "pgfearo", "author_id": 63965, "author_profile": "https://Stackoverflow.com/users/63965", "pm_score": 0, "selected": false, "text": "xml-to-json xsl:template <xsl:template match=\"*[*]\" mode=\"outer\">\n<xsl:param name=\"key\" as=\"xs:string?\"/>\n<xsl:variable name=\"distinctChildNames\" as=\"xs:string*\" select=\"*!name() => distinct-values()\"/>\n<xsl:choose>\n <xsl:when test=\"count($distinctChildNames) gt 1 and exists($key)\">\n <array>\n <xsl:sequence select=\"fn:keyAttribute(name())\"/>\n <map>\n <xsl:apply-templates select=\"*\" mode=\"outer\">\n <xsl:with-param name=\"key\" select=\"name()\"/>\n </xsl:apply-templates>\n </map>\n </array>\n </xsl:when>\n <xsl:when test=\"count(*) gt 1 and count($distinctChildNames) eq 1\">\n <map>\n <xsl:sequence select=\"fn:keyAttribute(name())\"/>\n <array key=\"{name(*[1])}\">\n <xsl:for-each select=\"*\">\n <map>\n <xsl:apply-templates select=\"*\" mode=\"outer\"/>\n </map>\n </xsl:for-each>\n </array>\n </map>\n </xsl:when>\n <xsl:otherwise>\n <map>\n <xsl:sequence select=\"fn:keyAttribute(name())\"/> \n <xsl:apply-templates select=\"*\" mode=\"outer\">\n <xsl:with-param name=\"key\" select=\"name()\"/>\n </xsl:apply-templates> \n </map>\n </xsl:otherwise>\n</xsl:choose>\n</xsl:template>\n {\n \"ClientID\": \"1\",\n \"PackageID\": \"650\",\n \"SBUID\": \"2187\",\n \"CandidateID\": \"456\",\n \"AssociateId\": \"789\",\n \"FirstName\": \"Meghana\",\n \"MiddleName\": \"\",\n \"LastName\": \"Rao\",\n \"FatherName\": \"Satish\",\n \"ContactNo\": \"7530001169\",\n \"EmailID\": \"dummy@sap.com\",\n \"AddressHistory\": {\n \"Address\": [\n {\n \"SequenceNo\": \"0\",\n \"AddressLine\": \"Kharghar,navi mumbai\",\n \"City\": \"Maharashtra-Mumbai\",\n \"State\": \"Maharashtra\",\n \"PinCode\": \"410210\",\n \"Country\": \"India\",\n \"Landmark\": \"\",\n \"StayFrom\": \"01-08-2013\",\n \"StayTo\": \"06-08-2021\",\n \"IsCurrentAddress\": false,\n \"IsPermanentAddress\": false,\n \"HouseNo\": \"\",\n \"AddressType\": \"Current\",\n \"DocList\": {\n \"listofdocs\": [\n {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n ]\n }\n }\n ]\n },\n \"EducationList\": {\n \"Education\": [\n {\n \"SequenceNo\": \"0\",\n \"Qualification\": \"\",\n \"Degree\": \"Under Graduate Degree\",\n \"CollegeName\": \"Amrutvahini College of engineering, Sangamner (Pune University)\",\n \"Location\": \"\",\n \"RollNumber\": \"123123\",\n \"UniversityName\": \"Mumbai University\",\n \"UniversityAddress\": \"\",\n \"PeriodFrom\": \"\",\n \"PeriodTo\": \"\",\n \"YearOfPassing\": \"2014\",\n \"Zipcode\": \"\",\n \"Percentage\": \"\",\n \"AdditionalRemarks\": \"10th\\/12th\\/Undergrad etc\",\n \"International\": false,\n \"Country\": \"\",\n \"DocList\": {\n \"listofdocs\": [\n {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n ]\n }\n }\n ]\n },\n \"EmploymentList\": {\n \"Employment\": [\n {\n \"SequenceNo\": \"0\",\n \"EmployerName\": \"Stravis Solutions\",\n \"EmployerAddress\": \"Bangalore\",\n \"EmployerContactNo\": \"\",\n \"Designation\": \"SDE\",\n \"EmployeeID\": \"asdas\",\n \"FixedSalary\": \"0\",\n \"IsCurrentEmployment\": false,\n \"RelievingDate\": \"15-10-2021\",\n \"State\": \"\",\n \"City\": \"\",\n \"Zipcode\": \"\",\n \"International\": false,\n \"Country\": \"\",\n \"PFNumber\": \"\",\n \"UANNumber\": \"\",\n \"DocList\": {\n \"listofdocs\": [\n {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n ]\n },\n \"DateOfJoining\": \"18-03-2015\"\n },\n {\n \"SequenceNo\": \"0\",\n \"EmployerName\": \"Stravis Solutions\",\n \"EmployerAddress\": \"Bangalore\",\n \"EmployerContactNo\": \"\",\n \"Designation\": \"SDE\",\n \"EmployeeID\": \"asdas\",\n \"FixedSalary\": \"0\",\n \"IsCurrentEmployment\": false,\n \"RelievingDate\": \"15-10-2021\",\n \"International\": false,\n \"Country\": \"\",\n \"PFNumber\": \"\",\n \"UANNumber\": \"\",\n \"DocList\": {\n \"listofdocs\": [\n {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n ]\n },\n \"DateOfJoining\": \"18-03-2015\"\n }\n ]\n },\n \"AddressReferencesList\": {\n \"ListofReferences\": [\n {\n \"OrganizationName\": \"Com 1\",\n \"AdditionalRemarks\": \"\",\n \"NameOfReferee\": \"Ref1\",\n \"RefereeOccupation\": \"SDE\",\n \"RefereePhoneNumber\": \"123456\",\n \"RefereeEmailAddress\": \"Ref1@com1.com\"\n },\n {\n \"OrganizationName\": \"Com 1\",\n \"AdditionalRemarks\": \"\",\n \"NameOfReferee\": \"Ref1\",\n \"RefereeOccupation\": \"SDE\",\n \"RefereePhoneNumber\": \"123456\",\n \"RefereeEmailAddress\": \"Ref1@com1.com\"\n }\n ]\n },\n \"DOB\": \"03-08-2021\",\n \"DLDetails\": {\n \"DOB\": \"03-08-2021\",\n \"ApplicantName\": \"Test\",\n \"FatherName\": \"Test\",\n \"dl_remarks\": \"\",\n \"UniqueIDCode\": \"1231231\",\n \"DocList\": {\n \"listofdocs\": [\n {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n ]\n }\n },\n \"PanDetails\": {\n \"DOB\": \"03-08-2021\",\n \"ApplicantName\": \"Sunil Kumar Yadav\",\n \"FatherName\": \"Sunil\",\n \"pan_remarks\": \"\",\n \"UniqueIDCode\": \"23123131\",\n \"DocList\": {\n \"listofdocs\": [\n {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n ]\n }\n },\n \"PVWDetails\": {\n \"AddressList\": {\n \"Address\": [\n {\n \"SequenceNo\": \"0\",\n \"AddressLine\": \"Kharghar,navi mumbai\",\n \"City\": \"Maharashtra-Mumbai\",\n \"State\": \"Maharashtra\",\n \"PinCode\": \"410210\",\n \"Country\": \"India\",\n \"Landmark\": \"\",\n \"StayFrom\": \"01-08-2013\",\n \"StayTo\": \"06-08-2021\",\n \"IsCurrentAddress\": false,\n \"IsPermanentAddress\": false,\n \"HouseNo\": \"Sai shradha CHS.Sector-11,\",\n \"AddressType\": \"Current\",\n \"DocList\": {\n \"listofdocs\": [\n {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n ]\n }\n }\n ]\n },\n \"DOB\": \"03-08-2021\",\n \"FatherName\": \"Sunil\",\n \"ApplicantName\": \"Sunil Kumar Yadav\"\n },\n \"CreditDetail\": {\n \"ApplicantName\": \"Test\",\n \"DOB\": \"03-08-2021\",\n \"FatherName\": \"Test\",\n \"Gender\": \"Male\",\n \"UniqueIDCode\": \"Pan Number\",\n \"EmailID\": \"asda@gmail.com\",\n \"DocList\": {\n \"listofdocs\": [\n {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n ]\n }\n },\n \"DrugTestPanelCheck\": {\n \"DrugTestPanel\": \"DrugTestPanel5\",\n \"ApplicantName\": \"Test Candidate\"\n },\n \"GDCDetails\": {\n \"ApplicantName\": \"Sunil Kumar Yadav\",\n \"DOB\": \"03-08-2021\",\n \"FatherName\": \"Sunil\"\n },\n \"PassportCheckDetails\": {\n \"NameInPassport\": \"Sunil Kumar Yadav\",\n \"PassportNo\": \"1231231\",\n \"MachineReadableZone\": \"\",\n \"CandidateFirstName\": \"Sunil\",\n \"CandidateLastName\": \"Yadav\",\n \"DOB\": \"03-08-2021\",\n \"FatherName\": \"Sunil\",\n \"DocList\": {\n \"listofdocs\": [\n {\n \"DocumentName\": \"abc.jpg\",\n \"DocumentPath\": \"base64\"\n }\n ]\n }\n }\n}\n \\/ <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n xmlns:fn=\"com.example.functions\"\n xmlns=\"http://www.w3.org/2005/xpath-functions\"\n expand-text=\"yes\"\n version=\"3.0\">\n \n <xsl:output method=\"text\" indent=\"yes\"/>\n <xsl:mode on-no-match=\"shallow-copy\"/>\n <xsl:mode name=\"outer\" on-no-match=\"shallow-copy\"/>\n \n <xsl:template match=\"/*\">\n <xsl:variable name=\"result\" as=\"node()*\">\n <map>\n <xsl:apply-templates select=\"*\" mode=\"outer\"/>\n </map>\n </xsl:variable>\n <xsl:sequence select=\"xml-to-json($result)\"/>\n </xsl:template>\n \n <xsl:template match=\"*[*]\" mode=\"outer\">\n <xsl:param name=\"key\" as=\"xs:string?\"/>\n <xsl:variable name=\"distinctChildNames\" as=\"xs:string*\" select=\"*!name() => distinct-values()\"/>\n <xsl:choose>\n <xsl:when test=\"count($distinctChildNames) gt 1 and exists($key)\">\n <array>\n <xsl:sequence select=\"fn:keyAttribute(name())\"/>\n <map>\n <xsl:apply-templates select=\"*\" mode=\"outer\">\n <xsl:with-param name=\"key\" select=\"name()\"/>\n </xsl:apply-templates>\n </map>\n </array>\n </xsl:when>\n <xsl:when test=\"count(*) gt 1 and count($distinctChildNames) eq 1\">\n <map>\n <xsl:sequence select=\"fn:keyAttribute(name())\"/>\n <array key=\"{name(*[1])}\">\n <xsl:for-each select=\"*\">\n <map>\n <xsl:apply-templates select=\"*\" mode=\"outer\"/>\n </map>\n </xsl:for-each>\n </array>\n </map>\n </xsl:when>\n <xsl:otherwise>\n <map>\n <xsl:sequence select=\"fn:keyAttribute(name())\"/> \n <xsl:apply-templates select=\"*\" mode=\"outer\">\n <xsl:with-param name=\"key\" select=\"name()\"/>\n </xsl:apply-templates> \n </map>\n </xsl:otherwise>\n </xsl:choose>\n </xsl:template>\n \n <xsl:template match=\"*[empty(*) and exists(text())]\" mode=\"outer\">\n <xsl:apply-templates select=\"node()\" mode=\"outer\">\n <xsl:with-param name=\"key\" select=\"name()\"/>\n </xsl:apply-templates>\n </xsl:template>\n \n <xsl:template match=\"*[empty(*) and empty(text())]\" mode=\"outer\">\n <string key=\"{name()}\"/>\n </xsl:template>\n \n <xsl:template match=\"text()[. = ('true', 'false')]\" mode=\"outer\">\n <xsl:param name=\"key\" as=\"xs:string?\"/>\n <boolean key=\"{$key}\">{.}</boolean>\n </xsl:template>\n \n <xsl:template match=\"text()\" mode=\"outer\">\n <xsl:param name=\"key\" as=\"xs:string?\"/>\n <xsl:if test=\"exists($key)\">\n <string key=\"{$key}\">{.}</string>\n </xsl:if>\n </xsl:template>\n \n <xsl:function name=\"fn:keyAttribute\" as=\"attribute()?\">\n <xsl:param name=\"key\" as=\"xs:string?\"/>\n <xsl:if test=\"$key\">\n <xsl:attribute name=\"key\" select=\"$key\"/>\n </xsl:if>\n </xsl:function>\n \n</xsl:stylesheet>\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1976997/" ]
74,534,798
<p>Good day to you.</p> <p>I have a question.. i am using report builder to build some reports. And i got stuck in this place where i want to sum all the results of one month to be in one cell.</p> <p><a href="https://i.stack.imgur.com/3yjI6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3yjI6.png" alt="enter image description here" /></a></p> <p>For example, in this picture you see that under the country1 i have 2 &quot;1&quot; i want them to be in one line and the sum/total will be 2</p> <p>I tried to group by country... but it didn't make any difference in the view.</p> <p>How can i do that? Is there a way to do it via the report builder or through my SQL query?</p> <p>Thank you</p> <p>NOTE: I used this code to get the days field in the report builder</p> <pre><code>=iif(Fields!Date_WEEKDAY__NUMBER_.Value=1,&quot;Sunday&quot;, iif(Fields!Date_WEEKDAY__NUMBER_.Value=2,&quot;Monday&quot;, iif(Fields!Date_WEEKDAY__NUMBER_.Value=3,&quot;Tuesday&quot;, iif(Fields!Date_WEEKDAY__NUMBER_.Value=4,&quot;Wednesday&quot;, iif(Fields!Date_WEEKDAY__NUMBER_.Value=5,&quot;Thrusday&quot;, iif(Fields!Date_WEEKDAY__NUMBER_.Value=6,&quot;Friday&quot;, iif(Fields!Date_WEEKDAY__NUMBER_.Value=7,&quot;Saturday&quot;,&quot;Null&quot;))))))) </code></pre> <p><a href="https://i.stack.imgur.com/Xps2b.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Xps2b.png" alt="1" /></a></p> <p><a href="https://i.stack.imgur.com/0QVkS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0QVkS.png" alt="" /></a></p> <p><a href="https://i.stack.imgur.com/QubpH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QubpH.png" alt="" /></a></p> <p>And this is my main quarry in SQL:</p> <pre><code>SELECT COUNT([Patient ID]) AS ID, Activity,Date, [Interaction Type], [Adverse Event Occured], [Product Compaint Occured], [Cancelation Reason], Created, Status, [Interaction Reason], Country, Drug, [Registered Nurse], [Created by], YEAR(Date) AS [Date Year], DATENAME(MONTH, Date) AS [Date Month], DATENAME(WEEK, Date) AS [Date WEEK], DATENAME(WEEKDAY, Date) AS [Date WEEKDAY], DATEPART(WEEKDAY, Date) AS [Date WEEKDAY (NUMBER)] FROM MNZL_Patient_Activities GROUP BY ID, Activity, Date, [Interaction Type], [Adverse Event Occured], [Product Compaint Occured], [Cancelation Reason], Created, Status, [Interaction Reason], Country, Drug, [Registered Nurse], [Created by], YEAR(Date), DATENAME(MONTH, Date), DATENAME(WEEK, Date), DATENAME(WEEKDAY, Date) HAVING ([Interaction Reason] = N'Medication Administration') order by DATENAME(WEEK, Date) </code></pre>
[ { "answer_id": 74535666, "author": "Zakaria Matlaoui", "author_id": 20167795, "author_profile": "https://Stackoverflow.com/users/20167795", "pm_score": 1, "selected": false, "text": "SELECT MT.[YEAR],\n MT.[ENROLMENT DATE],\n MT.[ENROLMENT DATE WEEK],\n MT.[COUNTRY],\n ISNULL(MT.SUNDAY,0)+\n ISNULL(MT.MONDAY,0)+\n ISNULL(MT.TUESDAY,0)+\n ISNULL(MT.WEDNESDAY,0)+\n ISNULL(MT.THRUSDAY,0)+\n ISNULL(MT.FRIDAY,0)+\n ISNULL(MT.SATURDAY,0) AS TOTAL\nFROM MyTable MT\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15265191/" ]
74,534,813
<p>I ask for your help for a problem that I encounter with IONIC 1. When I change the API level from 30 to 31 in the config.xml file:</p> <p>this code is not working</p> <pre><code>$http.get($scope.url) .then(function (success) { ... }, function (error) { $scope.errTXT = JSON.stringify(error); }); </code></pre> <p>returns a status of 0.</p> <blockquote> <p>{ &quot;data&quot;: null, &quot;status&quot;: 0, &quot;config&quot;: { &quot;method&quot;: &quot;GET&quot;, &quot;transformRequest&quot;: [ null ], &quot;transformResponse&quot;: [ null ], &quot;url&quot;: &quot;https://xxxxxxxxxxxxxxxxxx&quot;, headers: { &quot;Accept&quot;: &quot;application/json, text/plain, <em>/</em>&quot; } }, &quot;statusText&quot;: &quot;&quot; }</p> </blockquote> <p>I don't understand why the result of http is null</p> <blockquote> <p>Just for information, when i change back to API 30, everything is working well. I do not think is a server problem. I start thinking that the $http.get is not supported in API 31? My server is running on HTTPS://.......</p> </blockquote> <pre><code> Ionic CLI : 5.4.16 (C:xxxxxxxx\AppData\Roaming\npm\node_modules\ionic) Ionic Framework : ionic1 1.3.1 @ionic/v1-toolkit : not installed Cordova: Cordova CLI : 11.0.0 Cordova Platforms : android 9.1.0 Cordova Plugins : cordova-plugin-ionic-webview 1.2.1, (and 16 other plugins) Utility: cordova-res : not installed native-run : not installed System: Android SDK Tools : 26.1.1 (xxxxxxxx \AppData\Local\Android\Sdk\) NodeJS : v14.16.1 (C:\Program Files\nodejs\node.exe) npm : 7.24.2 OS : Windows 10 </code></pre>
[ { "answer_id": 74535666, "author": "Zakaria Matlaoui", "author_id": 20167795, "author_profile": "https://Stackoverflow.com/users/20167795", "pm_score": 1, "selected": false, "text": "SELECT MT.[YEAR],\n MT.[ENROLMENT DATE],\n MT.[ENROLMENT DATE WEEK],\n MT.[COUNTRY],\n ISNULL(MT.SUNDAY,0)+\n ISNULL(MT.MONDAY,0)+\n ISNULL(MT.TUESDAY,0)+\n ISNULL(MT.WEDNESDAY,0)+\n ISNULL(MT.THRUSDAY,0)+\n ISNULL(MT.FRIDAY,0)+\n ISNULL(MT.SATURDAY,0) AS TOTAL\nFROM MyTable MT\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20573004/" ]
74,534,816
<p>I'm beginer in C#. Now I have next task: In method I get template and arguments and I have to return formated string.</p> <p>For example:</p> <pre><code>template = &quot;Hello, {name}!&quot; name = &quot;Bob&quot; </code></pre> <p>So result must be a string -&gt; Hello, Bob!</p> <pre><code>public static string GetHelloGreeting(string template, string name) { return string.Format(template, name); } </code></pre>
[ { "answer_id": 74535000, "author": "Mong Zhu", "author_id": 5174469, "author_profile": "https://Stackoverflow.com/users/5174469", "pm_score": 0, "selected": false, "text": "string template = \"Hello, {0}!\"\n public static string Format (string format, params object?[] args);\n" }, { "answer_id": 74535004, "author": "frankM_DN", "author_id": 20034020, "author_profile": "https://Stackoverflow.com/users/20034020", "pm_score": 0, "selected": false, "text": "template template = $\"Hello, {name}\"; String.Format name template String.Format(template, name); template = \"Hello, {0}!\"; 0 String.Format" }, { "answer_id": 74535021, "author": "Tim Schmelter", "author_id": 284240, "author_profile": "https://Stackoverflow.com/users/284240", "pm_score": 3, "selected": true, "text": "String.Format String.Replace public static string GetHelloGreeting(string template, string name)\n{\n return template.Replace(\"{name}\", name);\n}\n public static string ReplaceAll(string template, params (string key, string value)[] replacements)\n{\n foreach (var kv in replacements)\n {\n template = template.Replace(\"{\"+ kv.key + \"}\", kv.value);\n }\n\n return template;\n}\n string res = ReplaceAll(\"Hello, {name}!\", (\"name\", \"Bob\"));\n string res = ReplaceAll(\"Hello, {name}! Now it's {time}\", (\"name\", \"Bob\"), (\"time\", DateTime.Now.ToString(\"HH:mm\")));\n" }, { "answer_id": 74535097, "author": "hossein sabziani", "author_id": 4301195, "author_profile": "https://Stackoverflow.com/users/4301195", "pm_score": 0, "selected": false, "text": "string.Format() template $ template string name = \"Bob\";\n string template = $\"Hello, {name}!\";\n\n Console.WriteLine(GetHelloGreeting(template, name)); // Hello, Bob!\n \n public static string GetHelloGreeting(string template, string name)\n {\n return string.Format(template, name);\n }\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20395904/" ]
74,534,817
<p>I've just started learning <code>malloc()</code> and <code>realloc()</code> and when testing them, I came across this issue with reallocating the size of an int array.</p> <p>the program is supposed to make an array, initially of size two, but it's supposed to increase its size and add values to it ten times. However it doesn't increase its size and the output ends up being <code>array = {0,1}</code> when it should be <code>array = {0,1,2,3,4,5,6,7,8,9}</code></p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; int main(void) { int *array= malloc(sizeof(int)*2); for (int x = 0; x &lt; 10; x++) { array = realloc(array, sizeof(int)*(2+x)); array[x] = x; } for (int i = 0; i&lt;(sizeof(array)/sizeof(array[0])); i++) { printf(&quot;%d\n&quot;,array[i]); } free(array); } </code></pre> <p>could someone explain why it doesn't work?? I've tried looking for answers but none of this makes sense to me lol.</p>
[ { "answer_id": 74535030, "author": "Vlad from Moscow", "author_id": 2877241, "author_profile": "https://Stackoverflow.com/users/2877241", "pm_score": 1, "selected": false, "text": "sizeof(array)/sizeof(array[0])\n sizeof( int * )/sizeof( int )\n (2+x) array = realloc(array, sizeof(int)*(2+x));\n enum { N = 10 };\nsize_t n = 2;\n\nint *array = malloc( n * sizeof( int ) );\nfor ( int x = 0; x < N; x++ ) {\n if ( n <= x )\n {\n n += 2;\n array = realloc( array, n * sizeof( int ) );\n }\n array[x] = x;\n}\n\nfor ( int i = 0; i < N; i++ ) {\n printf(\"%d\\n\",array[i]);\n}\n\nfree(array);\n realloc int *tmp = realloc( array, n * sizeof( int ) );\nif ( tmp != NULL ) array = tmp;\n realloc" }, { "answer_id": 74535109, "author": "Anthony Kelly", "author_id": 20410405, "author_profile": "https://Stackoverflow.com/users/20410405", "pm_score": 0, "selected": false, "text": "sizeof(array) #include <stdlib.h>\n#include <stdio.h>\n\nint main(void) {\n int *array= malloc(sizeof(int));\n int size;\n for (size = 0; size < 10; size++) {\n array = realloc(array, sizeof(int)*(1+size));\n array[size] = size;\n }\n for (int i = 0; i<size; i++) {\n printf(\"%d\\n\",array[i]);\n }\n printf(\"array size: %ld\\n\",size*sizeof(int));\n free(array);\n}\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18623170/" ]
74,534,831
<p>I want to drop columns if the values inside of them are the same as other columns. From DF, it should yields DF_new:</p> <pre><code>DF = pd.DataFrame(index=[1,2,3,4], columns = ['col1', 'col2','col3','col4','col5']) x = np.random.uniform(size=4) DF['col1'] = x DF['col2'] = x+2 DF['col3'] = x DF ['col4'] = x+2 DF['col5'] = [5,6,7,8] display(DF) DF_new = DF[['col1', 'col2', 'col5']] display(DF_new) </code></pre> <p><a href="https://i.stack.imgur.com/rbMCP.jpg" rel="nofollow noreferrer">Simple example of what I can't manage to do:</a></p> <p>Note that the column names are not the same, so I can't use:</p> <pre><code>DF_new = DF.loc[:,~DF.columns.duplicated()].copy() </code></pre> <p>, which drop columns based on their names.</p>
[ { "answer_id": 74535313, "author": "jack23456", "author_id": 20247353, "author_profile": "https://Stackoverflow.com/users/20247353", "pm_score": 0, "selected": false, "text": "df = df.loc[:,~df.apply(lambda x: x.duplicated(),axis=1).all()].copy()\n" }, { "answer_id": 74536197, "author": "Bushmaster", "author_id": 15415267, "author_profile": "https://Stackoverflow.com/users/15415267", "pm_score": 2, "selected": false, "text": "df = df.T.drop_duplicates().T\n\n df2 = df.T # T = transpose (convert rows to columns)\n\n 1 2 3 4\ncol1 0.67075 0.707864 0.206923 0.168023\ncol2 2.67075 2.707864 2.206923 2.168023\ncol3 0.67075 0.707864 0.206923 0.168023\ncol4 2.67075 2.707864 2.206923 2.168023\ncol5 5.00000 6.000000 7.000000 8.000000\n\n#now we can use drop duplicates\n\ndf2=df2.drop_duplicates()\n'''\n 1 2 3 4\ncol1 0.67075 0.707864 0.206923 0.168023\ncol2 2.67075 2.707864 2.206923 2.168023\ncol5 5.00000 6.000000 7.000000 8.000000\n'''\n\n#then use transpose again.\ndf2=df2.T\n'''\n col1 col2 col5\n1 0.670750 2.670750 5.0\n2 0.707864 2.707864 6.0\n3 0.206923 2.206923 7.0\n4 0.168023 2.168023 8.0\n'''\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20198320/" ]
74,534,840
<p>I have some pdfs with data about machine parts and i am trying to extract sizes. I extracted the text from a pdf via pypdfium2.</p> <pre><code>import pypdfium2 as pdfium pdf = pdfium.PdfDocument(&quot;myfile.pdf&quot;) page=pdf[1] textpage = page.get_textpage() </code></pre> <p>Most of the text is readable but for some reason the important data is not readable when extracted. In the extracted string the relevant part is like this</p> <pre><code>Readable text \r\n\x13\x0c\x10 \x18\x0c\x18 \x0b\x10\x0e\x10\x15\x18\x0f\x10 \x15\x0c\x10 \x14\x0c\x10 \x14\x0c\x15 readable text </code></pre> <p>I tried also with tika and PyMuPDF. They only give me the questionmarkcharacter for those parts.</p> <p>I know the mangled part (<code>\r\n\x13\x0c\x10 \x18\x0c\x18 \x0b\x10\x0e\x10\x15\x18\x0f\x10 \x15\x0c\x10 \x14\x0c\x10 \x14\x0c\x15</code>) should be <code>3,0 8,8 +0,058/0 5,0 4,0 4,5</code>. My current idea is to make my own encoding table but i wanted to ask if there is a better method and if this looks familiar to someone. I have about 52 files whith around 200 occurences each. While the pdfs are not confidential i dont want to post links because it is not my intelectual property.</p> <p>Update------------------------------</p> <p>I tried to find out more about the fonts.</p> <pre><code>from pdfreader import PDFDocument fd = open(&quot;myfile&quot;, &quot;rb&quot;) doc = PDFDocument(fd) page = next(doc.pages()) font_keys=sorted(page.Resources.Font.keys()) for font_key in font_keys: font = page.Resources.Font[font_key] print(f&quot;{font_key}: {font.Subtype}, {font.BaseFont}, {font.Encoding}&quot;) </code></pre> <p>gives:</p> <pre><code>R13: Type0, UHIIUQ+MetaPlusBold-Roman-Identity-H, Identity-H R17: Type0, EWGLNL+MetaPlusBold-Caps-Identity-H, Identity-H R20: Type1, NRVKIY+Meta-LightLF, {'Type': 'Encoding', 'BaseEncoding': 'WinAnsiEncoding', 'Differences': [33, 'agrave', 'degree', 39, 'quoteright', 177, 'endash']} R24: Type0, IKRCND+MetaPlusBold-Italic-Identity-H, Identity-H </code></pre> <p>-Edit------ I am not interested in help tranlating it manually. I can do that by myself. i am interested in a solution that works by script. For example a script that extracts fonts with codemaps from the pdf and then uses those to translate the unreadable parts</p>
[ { "answer_id": 74536064, "author": "K J", "author_id": 10802527, "author_profile": "https://Stackoverflow.com/users/10802527", "pm_score": 1, "selected": false, "text": "UHIIUQ+ 3,0 8,8 +0,058/0 5,0 4,0 4,5 \\r\\n\\ = cR Nl (windows line feed \\x0d\\x0a)\n\\x13 has been mapped to 3\n\\x0c has been mapped to ,\n\\x10 has been mapped to 0\n (literal nbsp)\n\\x18 = 8\n\\x0c = ,\n\\x18 = 8\n (literal nbsp)\n\\x0b has been mapped to +\n\\x10 = 0\n\\x0e has been mapped to , (very odd see \\x0c)\n\\x10 = 0\n\\x15 = 5\n\\x18 = 8\n\\x0f has been mapped to /\n\\x10 = 0\n (literal nbsp)\n\\x15 etc......................\n\\x0c\n\\x10\n \n\\x14\n\\x0c\n\\x10\n \n\\x14\n\\x0c\n\\x15\n \\x0e has been mapped to , (very odd see \\x0c) dot" }, { "answer_id": 74581885, "author": "Jorj McKie", "author_id": 4474869, "author_profile": "https://Stackoverflow.com/users/4474869", "pm_score": 0, "selected": false, "text": "import fitz\ndoc = fitz.open(\"some.pdf\")\n# assume that we know a font's xref already\n# extract the xref of its CMAP:\ncmap_xref = doc.xref_get_key(xref, \"ToUnicode\")[1] # second string is 'nnn 0 R'\nif cmap_xref.endswith(\"0 R\"): # check if a CMAP exists at all\n cxref = int(cmap_xref.split()[0])\nelse:\n raise ValueError(\"no CMAP found\")\nprint(doc.xref_stream(cxref).decode()) # convert bytes to string\n/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CMapType 2 def\n/CMapName/R63 def\n1 begincodespacerange\n<00><ff>\nendcodespacerange\n12 beginbfrange\n<20><20><0020>\n<2e><2e><002e>\n<30><31><0030>\n<43><46><0043>\n<49><49><0049>\n<4c><4d><004c>\n<4f><50><004f>\n<61><61><0061>\n<63><69><0063>\n<6b><70><006b>\n<72><76><0072>\n<78><79><0078>\nendbfrange\nendcmap\nCMapName currentdict /CMap defineresource pop\nend end\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9764940/" ]
74,534,850
<p>I'm trying to iterate this block of code for displaying data in table. I want object arrays of equal length.</p> <p>Hence, need to fill undefined values for respective keys to make array of objects uniform (same length)</p> <p><strong>Original Json</strong></p> <pre><code>[ { &quot;toolName&quot;: &quot;Alteryx&quot;, &quot;contacts&quot;: [ { &quot;contactPerson&quot;: &quot;James clear&quot;, &quot;email&quot;: &quot;james@google.com&quot; }, { &quot;contactPerson&quot;: &quot;Paul Unger&quot;, &quot;email&quot;: &quot;paulunger@twitter.com&quot; } ] }, { &quot;toolName&quot;: &quot;Processes&quot;, &quot;contacts&quot;: [ { &quot;contactPerson&quot;: &quot;naomi Unger&quot;, &quot;email&quot;: &quot;naomiunger@twitter.com&quot; } ] }, { &quot;toolName&quot;: &quot;Alteryx Server&quot;, &quot;contacts&quot;: [ { &quot;contactPerson&quot;: &quot;Avinash&quot;, &quot;email&quot;: &quot;avinash@meta.com&quot; }, { &quot;contactPerson&quot;: &quot;Sowmia&quot;, &quot;email&quot;: &quot;sowmia@energy.com&quot; } ] } ] </code></pre> <p><strong>Expectation json</strong></p> <pre><code>[ { &quot;toolName&quot;: &quot;Alteryx&quot;, &quot;contacts&quot;: [ { &quot;contactPerson&quot;: &quot;James clear&quot;, &quot;email&quot;: &quot;james@google.com&quot; }, { &quot;contactPerson&quot;: &quot;Paul Unger&quot;, &quot;email&quot;: &quot;paulunger@twitter.com&quot; } ] }, { &quot;toolName&quot;: &quot;Processes&quot;, &quot;contacts&quot;: [ { &quot;contactPerson&quot;: &quot;naomi Unger&quot;, &quot;email&quot;: &quot;naomiunger@twitter.com&quot; }, { &quot;contactPerson&quot;: null, &quot;email&quot;: null } ] }, { &quot;toolName&quot;: &quot;Alteryx Server&quot;, &quot;contacts&quot;: [ { &quot;contactPerson&quot;: &quot;Avinash&quot;, &quot;email&quot;: &quot;avinash@meta.com&quot; }, { &quot;contactPerson&quot;: &quot;Sowmia&quot;, &quot;email&quot;: &quot;sowmia@energy.com&quot; } ] } ] </code></pre> <h2>Tried this, but not working</h2> <pre><code>let max = 0; const masterArray = res?.data?.tools?.map((obj) =&gt; { obj.contacts.forEach((ele, ind) =&gt; { if(max &lt;= ind){ max = ind; } for(let i = 0 ; i&lt; max; i++){ if (ele !== undefined) return ele; return { ...ele, contactPerson: '', email: '', } } }); }); </code></pre> <hr /> <p>How to fill null/undefined values to handle error.</p>
[ { "answer_id": 74534947, "author": "Moussa Bistami", "author_id": 15628525, "author_profile": "https://Stackoverflow.com/users/15628525", "pm_score": 0, "selected": false, "text": "var s = [\n {\n \"toolName\": \"Alteryx\",\n \"contacts\": [\n {\n \"contactPerson\": \"James clear\",\n \"email\": \"james@google.com\"\n },\n {\n \"contactPerson\": \"Paul Unger\",\n \"email\": \"paulunger@twitter.com\"\n }\n ]\n },\n {\n \"toolName\": \"Processes\",\n \"contacts\": [\n {\n \"contactPerson\": \"naomi Unger\",\n \"email\": \"naomiunger@twitter.com\"\n },\n {\n \"contactPerson\": null,\n \"email\": null\n }\n ]\n },\n {\n \"toolName\": \"Alteryx Server\",\n \"contacts\": [\n {\n \"contactPerson\": \"Avinash\",\n \"email\": \"avinash@meta.com\"\n },\n {\n \"contactPerson\": \"Sowmia\",\n \"email\": \"sowmia@energy.com\"\n }\n ]\n }\n]\nconst handleNullContacts = (obj) => {\nobj.map(e=>e?.contacts.map(contact=>{\n if (!contact?.contactPerson)\n contact[\"contactPerson\"] = '';\n if (!contact?.email)\n contact[\"email\"] = ''\n }))\n return obj;\n}\n\ns = handleNullContacts(s)\nconsole.log(s) undefined null ''" }, { "answer_id": 74535061, "author": "Trevor Dixon", "author_id": 711902, "author_profile": "https://Stackoverflow.com/users/711902", "pm_score": 1, "selected": false, "text": "function fillMissingContacts(arr) {\n const max = arr.reduce((max, el) =>\n Math.max(max, el.contacts.length), 0);\n return arr.map(el => {\n const contacts = [...el.contacts];\n for (let i = contacts.length; i < max; i++) {\n contacts[i] = {contactPerson: null, email: null};\n }\n return {...el, contacts};\n });\n}\n function fillMissingContacts(arr) {\n const max = arr.reduce((max, el) =>\n Math.max(max, el.contacts.length), 0);\n for (const el of arr) {\n for (let i = el.contacts.length; i < max; i++) {\n el.contacts[i] = {contactPerson: null, email: null};\n }\n }\n}\n" }, { "answer_id": 74535161, "author": "Tim Nimets", "author_id": 9311283, "author_profile": "https://Stackoverflow.com/users/9311283", "pm_score": 1, "selected": false, "text": "const array = res?.data?.tools;\n// Finding max count of contacts\nconst max = array ? Math.max(...array.map?.(obj => obj.contacts.length)) : 0;\n// Filling master array\nconst masterArray = (array || []).map(obj => {\n const emptyContact = () => ({ contactPerson: null, email: null });\n // creating contact array; max - contacts.length is the lengths of missing contacts; emptyContact will be called that many times\n const contacts = [ ...obj.contacts, ...Array.from({ length: max - obj.contacts.length }, emptyContact)];\n // Creating new object with new contacts, so we do not overwrite the original\n return { ...obj, contacts };\n});\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8478108/" ]
74,534,852
<p>I'm trying to pass a <code>shared_ptr</code> to an object around, which may or may not be null:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;memory&gt; struct MyObject { int i = 0; MyObject(const int i_) : i(i_) {} }; struct Command { std::shared_ptr&lt;MyObject&gt; cmdObj; Command(std::shared_ptr&lt;MyObject&gt;&amp; obj) : cmdObj(obj) { std::cout &lt;&lt; &quot;Store and use this address: &quot; &lt;&lt; &amp;obj &lt;&lt; std::endl; // [1] } void execute() { if (cmdObj == nullptr) { cmdObj = std::make_shared&lt;MyObject&gt;(42); } else { cmdObj-&gt;i = 7; } } }; struct CommandManager { std::shared_ptr&lt;MyObject&gt; globalObj; // [1] CommandManager() { globalObj = nullptr; } void runCommand() { Command cmd(globalObj); cmd.execute(); } }; int main() { CommandManager cm; std::cout &lt;&lt; &quot;cm.globalObj address: &quot; &lt;&lt; &amp;cm.globalObj &lt;&lt; std::endl; // [1] cm.runCommand(); if (cm.globalObj == nullptr) { std::cout &lt;&lt; &quot;globalObj is null&quot; &lt;&lt; std::endl; } else { std::cout &lt;&lt; &quot;globalObj is &quot; &lt;&lt; cm.globalObj-&gt;i &lt;&lt; std::endl; } } </code></pre> <p>As you can see, I'm trying to manipulate or create <code>globalObj</code> from within <code>Command</code>. However, despite passing the address in the constructor (<code>[1]</code>), I'm not storing it correctly so that the new object is usable in the <code>CommandManager</code>.</p> <p>How do I make it so I can store and use the address of the <code>shared_ptr&lt;MyObject&gt;</code> correctly?</p> <p>Thank you in advance.</p>
[ { "answer_id": 74535116, "author": "Nelfeal", "author_id": 3854570, "author_profile": "https://Stackoverflow.com/users/3854570", "pm_score": 3, "selected": true, "text": "struct Command {\n std::shared_ptr<MyObject>* cmdObj;\n\n Command(std::shared_ptr<MyObject>& obj) : cmdObj(&obj) {\n std::cout << \"Store and use this address: \" << &obj << std::endl; // [1]\n }\n\n void execute() {\n if (*cmdObj == nullptr) {\n *cmdObj = std::make_shared<MyObject>(42);\n } else {\n (*cmdObj)->i = 7;\n }\n }\n};\n Command struct Command {\n std::shared_ptr<MyObject>& cmdObj;\n\n Command(std::shared_ptr<MyObject>& obj) : cmdObj(obj) {\n std::cout << \"Store and use this address: \" << &obj << std::endl; // [1]\n }\n\n void execute() {\n if (cmdObj == nullptr) {\n cmdObj = std::make_shared<MyObject>(42);\n } else {\n cmdObj->i = 7;\n }\n }\n};\n std::shared_ptr struct Command {\n MyObject* cmdObj;\n\n Command(MyObject* obj) : cmdObj(obj) {\n std::cout << \"Store and use this address: \" << obj << std::endl; // [1]\n }\n\n void execute() {\n cmdObj->i = 7;\n }\n};\n\nstruct CommandManager {\n MyObject globalObj = 42; // [1]\n\n void runCommand() {\n Command cmd(&globalObj);\n cmd.execute();\n }\n};\n\nint main() {\n CommandManager cm;\n std::cout << \"cm.globalObj address: \" << &cm.globalObj << std::endl; // [1]\n cm.runCommand();\n std::cout << \"globalObj is \" << cm.globalObj.i << std::endl;\n}\n MyObject std::shared_ptr struct Command {\n std::shared_ptr<MyObject> cmdObj;\n\n Command(std::shared_ptr<MyObject>& obj) : cmdObj(obj) {\n }\n\n void execute() {\n cmdObj->i = 7;\n }\n};\n\nstruct CommandManager {\n std::shared_ptr<MyObject> globalObj; // [1]\n\n CommandManager() { globalObj = std::make_shared<MyObject>(42); }\n\n void runCommand() {\n Command cmd(globalObj);\n cmd.execute();\n }\n};\n Command CommandManager struct Command {\n std::shared_ptr<MyObject> cmdObj;\n\n Command(std::shared_ptr<MyObject>& obj) {\n if (obj == nullptr) {\n obj = std::make_shared<MyObject>(42);\n }\n cmdObj = obj;\n }\n\n void execute() {\n cmdObj->i = 7;\n }\n};\n std::unique_ptr MyObject Command struct Command {\n std::shared_ptr<std::unique_ptr<MyObject>> cmdObj;\n\n Command(std::shared_ptr<std::unique_ptr<MyObject>> obj) : cmdObj(obj) {\n }\n\n void execute() {\n if (*cmdObj == nullptr) {\n *cmdObj = std::make_unique<MyObject>(42);\n } else {\n (*cmdObj)->i = 7;\n }\n }\n};\n\nstruct CommandManager {\n std::shared_ptr<std::unique_ptr<MyObject>> globalObj; // [1]\n\n CommandManager() { globalObj = std::make_shared<std::unique_ptr<MyObject>>(nullptr); }\n\n void runCommand() {\n Command cmd(globalObj);\n cmd.execute();\n }\n};\n" }, { "answer_id": 74535356, "author": "Cedric", "author_id": 8224596, "author_profile": "https://Stackoverflow.com/users/8224596", "pm_score": 0, "selected": false, "text": "shared_ptr #include <iostream>\n#include <memory>\n\nint main() {\n\n // Create an integer, give shared ownership to sp_1\n std::shared_ptr<int> sp_1 = std::make_shared<int>(2);\n\n // sp_2 points to same integer now, so sp_2.get() == sp_1.get().\n // Reference count is increased to 2.\n // Note that sp_1 and sp_2 are still different objects, i.e. &sp_2 != &sp_1 \n std::shared_ptr<int> sp_2 = sp_1;\n\n // Value of int is changed (both sp_1 and sp_2 point to it)\n *sp_2 = 4;\n\n // Replace shared_ptr object sp_2. It now points to another integer object.\n // sp_1 is not affected by it, the reference count to the first integer is back down to 1.\n sp_2 = std::make_shared<int>(6);\n\n std::cout << *sp_1 << \" is still 4!\" << std::endl;\n std::cout << *sp_2 << \" is 6!\" << std::endl;\n\n // \"Destroy\" first integer object\n sp_1.reset();\n\n // This is perfectly valid since sp_2 is pointing to a different integer\n *sp_2 = 8;\n std::cout << *sp_2 << \" is 8!\" << std::endl;\n\n return 0;\n}\n" }, { "answer_id": 74535532, "author": "n. m.", "author_id": 775806, "author_profile": "https://Stackoverflow.com/users/775806", "pm_score": 1, "selected": false, "text": "& globalObj obj obj globalObj cmdObj obj cmdObj cmdObj globalObj if (cmdObj == nullptr) { \n // Before the assignment, globalObj was nullptr.\n cmdObj = std::make_shared<MyObject>(42);\n // And it still is after the assignment to cmdObj.\n cmdObj Mystd::shared_ptr<MyObject>Object*& cmdObj;\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/547768/" ]
74,534,857
<p>I know this question has been asked multiple times in different ways, but I can't find a solution where I would replace the text between some &quot;borders&quot; while keeping the borders.</p> <pre><code>input &lt;- &quot;this is my 'example'&quot; change &lt;- &quot;test&quot; </code></pre> <p>And now I want to replace everything between teh single quotes with the value in <code>change</code>.</p> <p>Expected output would be <code>&quot;this is my 'test'</code></p> <p>I tried different variants of:</p> <pre><code>stringr::str_replace(input, &quot;['].*&quot;, change) </code></pre> <p>But it doesn't work. E.g. the one above gives <code>&quot;this is my test&quot;</code>, so it doesn't have the single quotes anymore.</p> <p>Any ideas?</p>
[ { "answer_id": 74535116, "author": "Nelfeal", "author_id": 3854570, "author_profile": "https://Stackoverflow.com/users/3854570", "pm_score": 3, "selected": true, "text": "struct Command {\n std::shared_ptr<MyObject>* cmdObj;\n\n Command(std::shared_ptr<MyObject>& obj) : cmdObj(&obj) {\n std::cout << \"Store and use this address: \" << &obj << std::endl; // [1]\n }\n\n void execute() {\n if (*cmdObj == nullptr) {\n *cmdObj = std::make_shared<MyObject>(42);\n } else {\n (*cmdObj)->i = 7;\n }\n }\n};\n Command struct Command {\n std::shared_ptr<MyObject>& cmdObj;\n\n Command(std::shared_ptr<MyObject>& obj) : cmdObj(obj) {\n std::cout << \"Store and use this address: \" << &obj << std::endl; // [1]\n }\n\n void execute() {\n if (cmdObj == nullptr) {\n cmdObj = std::make_shared<MyObject>(42);\n } else {\n cmdObj->i = 7;\n }\n }\n};\n std::shared_ptr struct Command {\n MyObject* cmdObj;\n\n Command(MyObject* obj) : cmdObj(obj) {\n std::cout << \"Store and use this address: \" << obj << std::endl; // [1]\n }\n\n void execute() {\n cmdObj->i = 7;\n }\n};\n\nstruct CommandManager {\n MyObject globalObj = 42; // [1]\n\n void runCommand() {\n Command cmd(&globalObj);\n cmd.execute();\n }\n};\n\nint main() {\n CommandManager cm;\n std::cout << \"cm.globalObj address: \" << &cm.globalObj << std::endl; // [1]\n cm.runCommand();\n std::cout << \"globalObj is \" << cm.globalObj.i << std::endl;\n}\n MyObject std::shared_ptr struct Command {\n std::shared_ptr<MyObject> cmdObj;\n\n Command(std::shared_ptr<MyObject>& obj) : cmdObj(obj) {\n }\n\n void execute() {\n cmdObj->i = 7;\n }\n};\n\nstruct CommandManager {\n std::shared_ptr<MyObject> globalObj; // [1]\n\n CommandManager() { globalObj = std::make_shared<MyObject>(42); }\n\n void runCommand() {\n Command cmd(globalObj);\n cmd.execute();\n }\n};\n Command CommandManager struct Command {\n std::shared_ptr<MyObject> cmdObj;\n\n Command(std::shared_ptr<MyObject>& obj) {\n if (obj == nullptr) {\n obj = std::make_shared<MyObject>(42);\n }\n cmdObj = obj;\n }\n\n void execute() {\n cmdObj->i = 7;\n }\n};\n std::unique_ptr MyObject Command struct Command {\n std::shared_ptr<std::unique_ptr<MyObject>> cmdObj;\n\n Command(std::shared_ptr<std::unique_ptr<MyObject>> obj) : cmdObj(obj) {\n }\n\n void execute() {\n if (*cmdObj == nullptr) {\n *cmdObj = std::make_unique<MyObject>(42);\n } else {\n (*cmdObj)->i = 7;\n }\n }\n};\n\nstruct CommandManager {\n std::shared_ptr<std::unique_ptr<MyObject>> globalObj; // [1]\n\n CommandManager() { globalObj = std::make_shared<std::unique_ptr<MyObject>>(nullptr); }\n\n void runCommand() {\n Command cmd(globalObj);\n cmd.execute();\n }\n};\n" }, { "answer_id": 74535356, "author": "Cedric", "author_id": 8224596, "author_profile": "https://Stackoverflow.com/users/8224596", "pm_score": 0, "selected": false, "text": "shared_ptr #include <iostream>\n#include <memory>\n\nint main() {\n\n // Create an integer, give shared ownership to sp_1\n std::shared_ptr<int> sp_1 = std::make_shared<int>(2);\n\n // sp_2 points to same integer now, so sp_2.get() == sp_1.get().\n // Reference count is increased to 2.\n // Note that sp_1 and sp_2 are still different objects, i.e. &sp_2 != &sp_1 \n std::shared_ptr<int> sp_2 = sp_1;\n\n // Value of int is changed (both sp_1 and sp_2 point to it)\n *sp_2 = 4;\n\n // Replace shared_ptr object sp_2. It now points to another integer object.\n // sp_1 is not affected by it, the reference count to the first integer is back down to 1.\n sp_2 = std::make_shared<int>(6);\n\n std::cout << *sp_1 << \" is still 4!\" << std::endl;\n std::cout << *sp_2 << \" is 6!\" << std::endl;\n\n // \"Destroy\" first integer object\n sp_1.reset();\n\n // This is perfectly valid since sp_2 is pointing to a different integer\n *sp_2 = 8;\n std::cout << *sp_2 << \" is 8!\" << std::endl;\n\n return 0;\n}\n" }, { "answer_id": 74535532, "author": "n. m.", "author_id": 775806, "author_profile": "https://Stackoverflow.com/users/775806", "pm_score": 1, "selected": false, "text": "& globalObj obj obj globalObj cmdObj obj cmdObj cmdObj globalObj if (cmdObj == nullptr) { \n // Before the assignment, globalObj was nullptr.\n cmdObj = std::make_shared<MyObject>(42);\n // And it still is after the assignment to cmdObj.\n cmdObj Mystd::shared_ptr<MyObject>Object*& cmdObj;\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2725773/" ]
74,534,869
<p>I don't know why I'm having so much trouble with this. I need to get the average of the sum that is outputted from def main():. I have tried to put the average within the def main and tried to use a separate def. both ways do not come out as expected.</p> <p>Below is where I am at currently.</p> <pre><code>def main(): totalMiles = 0 dayTotal = 0 mileageGoal = eval( input(&quot;How many miles would you like to run this week? &quot;)) while totalMiles != mileageGoal: dailyTotal = eval( input(f&quot;How many miles did you run on day {dayTotal + 1}? &quot;)) totalMiles = totalMiles + dailyTotal dayTotal = dayTotal + 1 if totalMiles &gt;= mileageGoal: print(&quot;You hit your goal! Keep going!&quot;) print(f&quot;You ran {totalMiles} miles!&quot;) print(f&quot;You completed your goal in {dayTotal} days! Congratulations!&quot;) break main() def average(): average = totalMiles / dayTotal return average print('the average miles you ran was:', average) </code></pre>
[ { "answer_id": 74535116, "author": "Nelfeal", "author_id": 3854570, "author_profile": "https://Stackoverflow.com/users/3854570", "pm_score": 3, "selected": true, "text": "struct Command {\n std::shared_ptr<MyObject>* cmdObj;\n\n Command(std::shared_ptr<MyObject>& obj) : cmdObj(&obj) {\n std::cout << \"Store and use this address: \" << &obj << std::endl; // [1]\n }\n\n void execute() {\n if (*cmdObj == nullptr) {\n *cmdObj = std::make_shared<MyObject>(42);\n } else {\n (*cmdObj)->i = 7;\n }\n }\n};\n Command struct Command {\n std::shared_ptr<MyObject>& cmdObj;\n\n Command(std::shared_ptr<MyObject>& obj) : cmdObj(obj) {\n std::cout << \"Store and use this address: \" << &obj << std::endl; // [1]\n }\n\n void execute() {\n if (cmdObj == nullptr) {\n cmdObj = std::make_shared<MyObject>(42);\n } else {\n cmdObj->i = 7;\n }\n }\n};\n std::shared_ptr struct Command {\n MyObject* cmdObj;\n\n Command(MyObject* obj) : cmdObj(obj) {\n std::cout << \"Store and use this address: \" << obj << std::endl; // [1]\n }\n\n void execute() {\n cmdObj->i = 7;\n }\n};\n\nstruct CommandManager {\n MyObject globalObj = 42; // [1]\n\n void runCommand() {\n Command cmd(&globalObj);\n cmd.execute();\n }\n};\n\nint main() {\n CommandManager cm;\n std::cout << \"cm.globalObj address: \" << &cm.globalObj << std::endl; // [1]\n cm.runCommand();\n std::cout << \"globalObj is \" << cm.globalObj.i << std::endl;\n}\n MyObject std::shared_ptr struct Command {\n std::shared_ptr<MyObject> cmdObj;\n\n Command(std::shared_ptr<MyObject>& obj) : cmdObj(obj) {\n }\n\n void execute() {\n cmdObj->i = 7;\n }\n};\n\nstruct CommandManager {\n std::shared_ptr<MyObject> globalObj; // [1]\n\n CommandManager() { globalObj = std::make_shared<MyObject>(42); }\n\n void runCommand() {\n Command cmd(globalObj);\n cmd.execute();\n }\n};\n Command CommandManager struct Command {\n std::shared_ptr<MyObject> cmdObj;\n\n Command(std::shared_ptr<MyObject>& obj) {\n if (obj == nullptr) {\n obj = std::make_shared<MyObject>(42);\n }\n cmdObj = obj;\n }\n\n void execute() {\n cmdObj->i = 7;\n }\n};\n std::unique_ptr MyObject Command struct Command {\n std::shared_ptr<std::unique_ptr<MyObject>> cmdObj;\n\n Command(std::shared_ptr<std::unique_ptr<MyObject>> obj) : cmdObj(obj) {\n }\n\n void execute() {\n if (*cmdObj == nullptr) {\n *cmdObj = std::make_unique<MyObject>(42);\n } else {\n (*cmdObj)->i = 7;\n }\n }\n};\n\nstruct CommandManager {\n std::shared_ptr<std::unique_ptr<MyObject>> globalObj; // [1]\n\n CommandManager() { globalObj = std::make_shared<std::unique_ptr<MyObject>>(nullptr); }\n\n void runCommand() {\n Command cmd(globalObj);\n cmd.execute();\n }\n};\n" }, { "answer_id": 74535356, "author": "Cedric", "author_id": 8224596, "author_profile": "https://Stackoverflow.com/users/8224596", "pm_score": 0, "selected": false, "text": "shared_ptr #include <iostream>\n#include <memory>\n\nint main() {\n\n // Create an integer, give shared ownership to sp_1\n std::shared_ptr<int> sp_1 = std::make_shared<int>(2);\n\n // sp_2 points to same integer now, so sp_2.get() == sp_1.get().\n // Reference count is increased to 2.\n // Note that sp_1 and sp_2 are still different objects, i.e. &sp_2 != &sp_1 \n std::shared_ptr<int> sp_2 = sp_1;\n\n // Value of int is changed (both sp_1 and sp_2 point to it)\n *sp_2 = 4;\n\n // Replace shared_ptr object sp_2. It now points to another integer object.\n // sp_1 is not affected by it, the reference count to the first integer is back down to 1.\n sp_2 = std::make_shared<int>(6);\n\n std::cout << *sp_1 << \" is still 4!\" << std::endl;\n std::cout << *sp_2 << \" is 6!\" << std::endl;\n\n // \"Destroy\" first integer object\n sp_1.reset();\n\n // This is perfectly valid since sp_2 is pointing to a different integer\n *sp_2 = 8;\n std::cout << *sp_2 << \" is 8!\" << std::endl;\n\n return 0;\n}\n" }, { "answer_id": 74535532, "author": "n. m.", "author_id": 775806, "author_profile": "https://Stackoverflow.com/users/775806", "pm_score": 1, "selected": false, "text": "& globalObj obj obj globalObj cmdObj obj cmdObj cmdObj globalObj if (cmdObj == nullptr) { \n // Before the assignment, globalObj was nullptr.\n cmdObj = std::make_shared<MyObject>(42);\n // And it still is after the assignment to cmdObj.\n cmdObj Mystd::shared_ptr<MyObject>Object*& cmdObj;\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20034972/" ]
74,534,896
<p>I have this rust method error message:</p> <pre><code>error[E0277]: the `?` operator can only be used on `Option`s, not `Result`s, in an async function that returns `Option` </code></pre> <p>I must admit, I often encounter Rust error messages which appear confusing to me, while to most other coders they make absolute sense.</p> <p>So, I apologize in advance for posting this question.</p> <p>First of all: what does that second comma in the error message mean? Should I read it as the following:</p> <p>&quot;If an async function call [within another function] returns an enum of the type <code>Result</code> then the <code>?</code> operator can only be applied <em>if</em>, and only if, the respective [other] function also returns an enum of type <code>Result</code> and not an enum of type <code>Option</code>&quot;</p> <p>Pardon my verbose language. I hope I got my point across.</p> <p>What also got me confused was the error message with that very same Reference i.e. <em>error[E0277]</em> , which is listed in the <a href="https://doc.rust-lang.org/error_codes/E0277.html" rel="nofollow noreferrer">official rust error codes index</a>, states:</p> <p>&quot;You tried to use a type which doesn't implement some trait in a place which expected that trait.&quot;</p> <p>In which universe do these two error messages have anything in common, except for the identical reference number?</p> <p>And here's the entire error block, which Rust produced:</p> <pre><code>error[E0277]: the `?` operator can only be used on `Option`s, not `Result`s, in an async function that returns `Option` --&gt; src/utils/tokenizer.rs:72:73 | 70 | pub async fn clear(&amp;self) -&gt; Option&lt;String&gt; { | _________________________________________________- 71 | | let mut conn = self.pool.get().await.unwrap(); 72 | | let mut iter: redis::AsyncIter&lt;i32&gt; = conn.sscan(&quot;my_set&quot;).await?; | | ^ use `.ok()?` if you want to discard the `Result&lt;Infallible, Red Error&gt;` error information 73 | | while let Some(element) = iter.next_item().await { ... | 79 | | Some(String::from(&quot;A&quot;)) 80 | | } | |_____- this function returns an `Option` | = help: the trait `FromResidual&lt;Result&lt;Infallible, RedisError&gt;&gt;` is not implemented for `std::option::Option&lt;std::string::String&gt;` = help: the following other types implement trait `FromResidual&lt;R&gt;`: &lt;std::option::Option&lt;T&gt; as FromResidual&lt;Yeet&lt;()&gt;&gt;&gt; &lt;std::option::Option&lt;T&gt; as FromResidual&gt; For more information about this error, try `rustc --explain E0277`. </code></pre> <p>What is the canonical error message, the one from the error code index page or the one, the compiler produces?</p>
[ { "answer_id": 74534975, "author": "etchesketch", "author_id": 4066795, "author_profile": "https://Stackoverflow.com/users/4066795", "pm_score": 2, "selected": false, "text": "clear Option<String> conn.sscan(\"my_set\").await?; ? clear(&self) -> Option<String> Result Option<String> .ok()? ?" }, { "answer_id": 74535140, "author": "Chayim Friedman", "author_id": 7884305, "author_profile": "https://Stackoverflow.com/users/7884305", "pm_score": 3, "selected": true, "text": "Option Option Result ? Try ? ?" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/716568/" ]
74,534,904
<p>I'm trying to better understand Futures in Flutter. In this example, my app makes an API call to get some information of type <code>Future&lt;String&gt;</code>. I'd like to display this information in a <code>Text()</code> widget. However, because my <code>String</code> is wrapped in a <code>Future</code> I'm unable to put this information in my <code>Text()</code> widget, and I'm not sure how to handle this without resorting to a <code>FutureBuilder</code> to create the small widget tree.</p> <p>The following example uses a <code>FutureBuilder</code> and it works fine. Note that I've commented out the following line near the bottom:</p> <p><code>Future&lt;String&gt; category = getData();</code></p> <p>Is it possible to turn <code>category</code> into a <code>String</code> and simply drop this in my <code>Text()</code> widget?</p> <pre><code>import 'package:flutter/material.dart'; import 'cocktails.dart'; class CocktailScreen extends StatefulWidget { const CocktailScreen({super.key}); @override State&lt;CocktailScreen&gt; createState() =&gt; _CocktailScreenState(); } class _CocktailScreenState extends State&lt;CocktailScreen&gt; { @override Widget build(BuildContext context) { Cocktails cocktails = Cocktails(); Future&lt;String&gt; getData() async { var data = await cocktails.getCocktailByName('margarita'); String category = data['drinks'][0]['strCategory']; print('Category: ${data[&quot;drinks&quot;][0][&quot;strCategory&quot;]}'); return category; } FutureBuilder categoryText = FutureBuilder( initialData: '', future: getData(), builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasData) { return Text(snapshot.data); } else if (snapshot.hasError) { return Text(snapshot.error.toString()); } } return const CircularProgressIndicator(); }, ); //Future&lt;String&gt; category = getData(); return Center( child: categoryText, ); } } </code></pre> <p>Here's my <code>Cocktails</code> class:</p> <pre><code>import 'networking.dart'; const apiKey = '1'; const apiUrl = 'https://www.thecocktaildb.com/api/json/v1/1/search.php'; class Cocktails { Future&lt;dynamic&gt; getCocktailByName(String cocktailName) async { NetworkHelper networkHelper = NetworkHelper('$apiUrl?s=$cocktailName&amp;apikey=$apiKey'); dynamic cocktailData = await networkHelper.getData(); return cocktailData; } } </code></pre> <p>And here's my <code>NetworkHelper</code> class:</p> <pre><code>import 'package:http/http.dart' as http; import 'dart:convert'; class NetworkHelper { NetworkHelper(this.url); final String url; Future&lt;dynamic&gt; getData() async { http.Response response = await http.get(Uri.parse(url)); if (response.statusCode == 200) { String data = response.body; var decodedData = jsonDecode(data); return decodedData; } else { //print('Error: ${response.statusCode}'); throw 'Sorry, there\'s a problem with the request'; } } } </code></pre>
[ { "answer_id": 74534976, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 2, "selected": true, "text": "FutureBuilder FutureBuilder categoryText = FutureBuilder<String>(\n future: getData(),\n builder: (BuildContext context, AsyncSnapshot snapshot) {\n switch (snapshot.connectionState) {\n case ConnectionState.waiting:\n return Text('Loading....');\n default:\n if (snapshot.hasError) {\n return Text('Error: ${snapshot.error}');\n } else {\n var data = snapshot.data ?? '';\n\n return Text(data);\n }\n }\n },\n ),\n FutureBuilder String category = '';\n\nFuture<void> getData() async {\n var data = await cocktails.getCocktailByName('margarita');\n setState(() {\n category = data['drinks'][0]['strCategory'];\n });\n}\n @override\n void initState() {\n super.initState();\n getData();\n }\n @override\n Widget build(BuildContext context) {\n return Center(\n child: Text(category),\n );\n }\n category getData cocktails" }, { "answer_id": 74535911, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 2, "selected": false, "text": "Future FutureBuilder Future initState() then class StatefuleWidget extends StatefulWidget {\n const StatefuleWidget({super.key});\n\n @override\n State<StatefuleWidget> createState() => _StatefuleWidgetState();\n}\n\nclass _StatefuleWidgetState extends State<StatefuleWidget> {\n String? text;\n\n Future<String> getData() async {\n var data = await cocktails.getCocktailByName('margarita');\n String category = data['drinks'][0]['strCategory'];\n print('Category: ${data[\"drinks\"][0][\"strCategory\"]}');\n return category;\n }\n\n @override\n void initState() {\n super.initState();\n getData().then((value) {\n setState(() {\n text = value;\n });\n });\n }\n\n @override\n Widget build(BuildContext context) {\n return Text(text ?? 'Loading');\n }\n}\n text Text() Future" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6483841/" ]
74,534,939
<p>i have an array like this</p> <pre><code>const arr = [1,2,3,4,5,6,7]; </code></pre> <p>i am trying to make sub arrays from this main array so that it will look something like this</p> <pre><code>const splitArray = [[1,4], [2,5], [3,6], [7]]; </code></pre> <p>what i have tried so far is</p> <pre><code>const convertToSubArray = (array, chunkSize = 2) =&gt; { let i, j, accum = []; for (i=0, j=array.length; i&lt;j; i+=chunkSize) { accum = [...accum, array.slice(i, i+chunkSize)]; } return accum; } </code></pre> <p>But getting this as the output</p> <pre><code>[ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7 ] ] </code></pre> <p>How can i achieve this, any help is appreciated</p>
[ { "answer_id": 74535182, "author": "Anshu", "author_id": 18638118, "author_profile": "https://Stackoverflow.com/users/18638118", "pm_score": -1, "selected": false, "text": "const arr = [1, 2, 3, 4, 5, 6, 7]\nconst splitArray = [];\n\nfor (i = 0; i < arr.length; i++) {\n if (arr[i + 3] != undefined) {\n splitArray.push([arr[i], arr[i + 3]])\n }\n}\n\nconsole.log(splitArray);" }, { "answer_id": 74535247, "author": "Nina Scholz", "author_id": 1447675, "author_profile": "https://Stackoverflow.com/users/1447675", "pm_score": 2, "selected": true, "text": "offset p p indices grouping comment\n--- ------------- -------------------------- --------------\n 3 0 1 2 3 4 5 [[0, 3], [1, 4], [2, 5]]\n 3 0 1 2 3 4 [[0, 3], [1, 4], [2]]\n 2 0 1 2 3 [[0, 2], [1, 3]]\n 2 0 1 2 [[0, 1, 2]] special case\n 1 0 1 [[0, 1]] \"\n 1 0 [[0]] \"\n const\n chunk = array => {\n const result = [];\n\n for (let offset = 0; offset < array.length; offset += 6) {\n const l = Math.min(array.length - offset, 6);\n\n if (l <= 3) {\n result.push(array.slice(offset, offset + 3));\n break;\n }\n\n for (let i = 0, p = Math.ceil(l / 2); i < p; i++) {\n result.push(i + 1 === p && l & 1\n ? [array[offset + i]]\n : [array[offset + i], array[offset + i + p]]\n );\n }\n }\n\n return result;\n };\n\nconsole.log(chunk([1]));\nconsole.log(chunk([1, 2]));\nconsole.log(chunk([1, 2, 3]));\nconsole.log(chunk([1, 2, 3, 4]));\nconsole.log(chunk([1, 2, 3, 4, 5]));\nconsole.log(chunk([1, 2, 3, 4, 5, 6]));\nconsole.log(chunk([1, 2, 3, 4, 5, 6, 7]));\nconsole.log(chunk([1, 2, 3, 4, 5, 6, 7, 8]));\nconsole.log(chunk([1, 2, 3, 4, 5, 6, 7, 8, 9])); .as-console-wrapper { max-height: 100% !important; top: 0; }" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10829671/" ]
74,534,952
<p>I have table data after doing all joins and restrictions like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> <th>Type</th> <th>Path</th> </tr> </thead> <tbody> <tr> <td>Item 1</td> <td>mobile</td> <td>/mobile/image1.jpg</td> </tr> <tr> <td>Item 1</td> <td>desktop</td> <td>/desktop/image1.jpg</td> </tr> <tr> <td>Item 2</td> <td>mobile</td> <td>/mobile/image2.jpg</td> </tr> <tr> <td>Item 2</td> <td>desktop</td> <td>/desktop/image2.jpg</td> </tr> </tbody> </table> </div> <p>I want the result table to look like this in the end:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> <th>Path mobile</th> <th>Path desktop</th> </tr> </thead> <tbody> <tr> <td>Item 1</td> <td>/mobile/image1.jpg</td> <td>/desktop/image1.jpg</td> </tr> <tr> <td>Item 2</td> <td>/mobile/image2.jpg</td> <td>/desktop/image2.jpg</td> </tr> </tbody> </table> </div> <p>What SQL (mySQL) feature can be used to get such a result?</p> <p>So far, I've had to do data processing (mapping) in the code that calls this request.</p>
[ { "answer_id": 74535015, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 2, "selected": false, "text": "SELECT\n Name,\n MAX(CASE WHEN Type = 'mobile' THEN Path END) AS Path_Mobile,\n MAX(CASE WHEN Type = 'desktop' THEN Path END) AS Path_Desktop\nFROM yourTable\nGROUP BY Name\nORDER BY Name;\n" }, { "answer_id": 74536002, "author": "Zakaria Matlaoui", "author_id": 20167795, "author_profile": "https://Stackoverflow.com/users/20167795", "pm_score": 0, "selected": false, "text": "SELECT DISTINCT(MT.[Name]),\n MT2.[Path] AS DesktopPath,\n MT3.[Path] AS MobilePath\nFROM MyTable MT\nINNER JOIN MyTable MT2\n ON MT2.[Name] = MT.[Name] AND MT2.[Type] = 'DESKTOP'\nINNER JOIN MyTable MT3\n ON MT3.[Name] = MT.[Name] AND MT3.[Type] = 'MOBILE'\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9300894/" ]
74,534,955
<p>My previous question was not understood, so I rephrase and post this one. I have a list of tuple for <code>(class, n_class_examples)</code> like this:</p> <pre class="lang-py prettyprint-override"><code>my_list = (0, 126), (1, 192), (2, 330), (3, 952) ] </code></pre> <p>So I am interested in generating a function, that takes in such a list, compare each tuple against all others, and in each case reports which class has smaller number of samples (<code>min_class</code>), and which has the larger number of samples (<code>max_class</code>).</p> <pre class="lang-py prettyprint-override"><code>def get_min_max_class(current_list): for tn, tn+1: # tn -&gt; 1-tuple, tn+1 any other tuple not tn if tn[1] &lt; tn+1[1] smaller_class = tn[0] larger_class = tn+1[0] smaller_class = tn+1[0] larger_class = tn[0] return # smaller, larger of the 2 compared in each case </code></pre> <p>So that:</p> <pre class="lang-py prettyprint-override"><code>get_min_max_class(my_list) # would perform the comparison like so: (0, 126) v (1, 192) -&gt; min_class = 0, max_class = 1 # in this case (0, 126) v (2, 330) -&gt; min_class = 0, max_class = 2 # and in this case (0, 126) v (3, 952) -&gt; min_class = 0, max_class = 3 # and here .. (1, 192) v (2, 330) -&gt; min_class = 1, max_class = 2 # ... (1, 192) v (3, 952) -&gt; min_class = 1, max_class = 3 (2, 330) v (3, 952) -&gt; min_class = 2, max_class = 3 </code></pre> <p>Forgive my definition of function, but I want the function to iteratively compare those items, each time, report which is larger and which is smaller.</p>
[ { "answer_id": 74535100, "author": "whatf0xx", "author_id": 19625920, "author_profile": "https://Stackoverflow.com/users/19625920", "pm_score": 0, "selected": false, "text": "max_class = max(my_list, key=lambda x: x[1])[-1]\n" }, { "answer_id": 74535325, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 2, "selected": true, "text": "itertools.combintions min max from itertools import combinations\nfrom operator import itemgetter\n\nfirst = itemgetter(0)\nsecond = itemgetter(1)\n\ndef get_min_max_class(current_list):\n for pair in combinations(current_list, 2):\n p0, p1 = pair\n min_class = first(min(pair, key=second))\n max_class = first(max(pair, key=second))\n print(f'{p0} v {p1} -> min_class = {min_class}, max_class = {max_class}')\n\nget_min_max_class(my_list)\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17487457/" ]
74,534,956
<p>Why std::transform doesn't work this way:</p> <pre><code>std::string tmp = &quot;WELCOME&quot;; std::string out = &quot;&quot;; std::transform(tmp.begin(), tmp.end(), out.begin(), ::tolower); </code></pre> <p>out is empty!</p> <p>But this works:</p> <pre><code>std::transform(tmp.begin(), tmp.end(), tmp.begin(), ::tolower); </code></pre> <p>I don't want the transformation to happen in-place.</p>
[ { "answer_id": 74535009, "author": "Stack Danny", "author_id": 6039995, "author_profile": "https://Stackoverflow.com/users/6039995", "pm_score": 4, "selected": true, "text": "out tmp out std::back_inserter std::tolower std::transform(tmp.begin(), tmp.end(), std::back_inserter(out), [](auto c) {\n return std::tolower(static_cast<unsigned char>(c));\n});\n" }, { "answer_id": 74535040, "author": "TrebledJ", "author_id": 10239789, "author_profile": "https://Stackoverflow.com/users/10239789", "pm_score": 2, "selected": false, "text": "std::transform out.resize(tmp.size()); // <---\nstd::transform(tmp.begin(), tmp.end(), out.begin(), ::tolower);\n std::back_inserter out.reserve out.reserve(tmp.size()); // (optional) Smol optimisation.\nstd::transform(tmp.begin(), tmp.end(), std::back_inserter(out), ::tolower);\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4195836/" ]
74,534,961
<p>Need to make a password program, where the user sets a password at the beginning and the password can be entered 3 times before the program is stopped. The program can not be case sensitive.</p> <pre class="lang-java prettyprint-override"><code> public static void main(String[] args) { Scanner sc = new Scanner(System.in); int attempts = 3; String password = &quot;&quot;; System.out.println(&quot;Please input your password.&quot;); Scanner stringScanner = new Scanner(System.in); String PASSWORD = stringScanner.next(); while (attempts-- &gt; 0 &amp;&amp; !PASSWORD.equals(password)) //compares and then decrements { System.out.print(&quot;Enter your password: &quot;); password = sc.nextLine(); if (password.equals(PASSWORD)) System.out.println(&quot;Access Granted&quot;); else System.out.println(&quot;Incorrect. Number of attempts remaining: &quot; + attempts); } if (attempts &lt; 1) { System.out.println(&quot;You have entered too many incorrect passwords, please try again later.&quot;); } else { System.out.println(&quot;Secret: Water is not Wet.&quot;); } } } </code></pre> <p>Program prints as expected, but is not case sensitive</p>
[ { "answer_id": 74535031, "author": "anqit", "author_id": 4234254, "author_profile": "https://Stackoverflow.com/users/4234254", "pm_score": 2, "selected": false, "text": "The program can not be case sensitive Program prints as expected, but is not case sensitive String#equalsIgnoreCase !PASSWORD.equalsIgnoresCase(password)" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20436933/" ]
74,534,974
<p>my Https header is in this format in Mule http requester</p> <pre><code>%dw 2.0 output application/java { &quot;Content-Transfer-Encoding&quot; :&quot;base64&quot;, &quot;X-do-Authentication&quot; : {&quot;Username&quot;: &quot;xxx@yyy.org&quot;,&quot;Password&quot;: &quot;xxxyyy&quot;,&quot;IntegratorKey&quot;: &quot;4xzzzz&quot;} } </code></pre> <p>whem trying to send header in this format I am getting this error</p> <pre><code>Message : &quot;java.lang.IllegalStateException - No read or write handler for Username java.lang.IllegalStateException: No read or write handler for Username at org.mule.weave.v2.module.pojo.reader.PropertyDefinition._type$lzycompute(PropertyDefinition.scala:44) at org.mule.weave.v2.module.pojo.reader.PropertyDefinition._type(PropertyDefinition.scala:35) at org.mule.weave.v2.module.pojo.reader.PropertyDefinition.classType(PropertyDefinition.scala:70) </code></pre> <p>I tried setting output to text/plain but this is still not working how can I proceed on this. I am using Mule 4</p>
[ { "answer_id": 74535429, "author": "Harshank Bansal", "author_id": 10946202, "author_profile": "https://Stackoverflow.com/users/10946202", "pm_score": 2, "selected": false, "text": "write %dw 2.0 \noutput application/java\n---\n{ \"Content-Transfer-Encoding\" :\"base64\",\n \"X-do-Authentication\" : write({\"Username\": \"xxx@yyy.org\",\"Password\": \"xxxyyy\",\"IntegratorKey\": \"4xzzzz\"}, \"application/json\", {indent: false})\n}\n" }, { "answer_id": 74541459, "author": "Nampd", "author_id": 6388664, "author_profile": "https://Stackoverflow.com/users/6388664", "pm_score": -1, "selected": true, "text": "{\"Username\": \"xxx@yyy.org\",\"Password\": \"xxxyyy\",\"IntegratorKey\": \"4xzzzz\"} write({\"Username\": \"xxx@yyy.org\",\"Password\": \"xxxyyy\",\"IntegratorKey\": \"4xzzzz\"}, \"application/json\")" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9557351/" ]
74,534,991
<p>I got a dataset and I want to drop a few unusable rows. I used a filter to the specific condition in which i want the rows to be dropped</p> <p><code>filter = df.groupby(['Bairro'], group_keys=False, sort=True).size() &gt; 1 print(filter.to_string())</code></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Bairro</th> <th></th> </tr> </thead> <tbody> <tr> <td>01</td> <td>True</td> </tr> <tr> <td>02</td> <td>False</td> </tr> </tbody> </table> </div> <p>All the data in which the condition is false is useless. I've tried a few things, none of them work.</p> <p>So, I'd like the dataframe to maintain only the values where the condition is true:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Bairro</th> <th></th> </tr> </thead> <tbody> <tr> <td>01</td> <td>True</td> </tr> </tbody> </table> </div> <p><code>df2 = ((df.groupby(['Bairro']).size()) != 1)</code></p> <p>I was even planning to dropping value by value, but it didn't work as well</p> <p><code>df2 = df[~df.isin(['02']).any(axis=1)]</code></p> <p>Tried passing the filter as a condition:</p> <p><code>df.drop(df[df.groupby(['Bairro'], group_keys=False, sort=True).size() &gt; 1], inplace = True)</code></p>
[ { "answer_id": 74535263, "author": "Sam Donnermeyer", "author_id": 13778703, "author_profile": "https://Stackoverflow.com/users/13778703", "pm_score": 2, "selected": false, "text": "new_df = df.loc[df['col2'] == \"True\"]\n new_df = df.loc[(df['col1'] == \"True\") & (df['col2'] == \"True\")]\n" }, { "answer_id": 74535720, "author": "psychicesp", "author_id": 13741789, "author_profile": "https://Stackoverflow.com/users/13741789", "pm_score": 2, "selected": true, "text": "import pandas as pd\ndf = pd.DataFrame({\n 'numbers': [0,1,2,3,4],\n 'letters': ['a','b','c','d','e'],\n 'colors': ['red', 'blue', 'yellow', 'green', 'purple']\n})\ndf\n boolean_list = [True, True, False, True, False]\nfiltered_df = df[boolean_list]\nfiltered_df\n df['numbers']>2\n 0 False\n1 False\n2 False\n3 True\n4 True\nName: numbers, dtype: bool\n df[df['numbers']>2]\n def letter_in_color(row):\n return row['letters'] in row['colors']\nboolean_arr = df.apply(letter_in_color, axis = 1)\nprint(boolean_arr)\n\n0 False\n1 True\n2 False\n3 False\n4 True\ndtype: bool\n\nletter_in_color_df = df[boolean_array]\nletter_in_color_df\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74534991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16443121/" ]
74,535,008
<p>I want to apply padding to the right of this input field but its not working this is how it look like I want to add a margin like on the left side to the right side <a href="https://i.stack.imgur.com/VeBPN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VeBPN.png" alt="This is the how it look like after style and the right margin is not displaying " /></a></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>body { margin: 0; padding: 10px; } input { width: 100%; box-sizing: border-box; padding: 10px; margin-top: 10px; margin-left: 10px; margin-right: 10px; border: solid #5f9341 1px; border-radius: 30px; } #save { width: 100px; padding: 10px; margin-top: 4px; margin-left: 10px; border: none; background-color: #5f9341; font-weight: bold; color: white; text-transform: uppercase; border-radius: 30px; } #save:active { transform: scale(0.98); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt; &lt;body&gt; &lt;input type="text" id="input" /&gt; &lt;button id="save"&gt;Save input&lt;/button&gt; &lt;button id="save"&gt;Save input&lt;/button&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74535191, "author": "Cédric", "author_id": 17684809, "author_profile": "https://Stackoverflow.com/users/17684809", "pm_score": 0, "selected": false, "text": "width: 100% calc() :root {\n --input-margin: 10px;\n}\n\nbody {\n margin: 0;\n padding: 10px;\n}\n\ninput {\n width: calc(100% - 2 * var(--input-margin));\n box-sizing: border-box;\n padding: 10px;\n margin-top: var(--input-margin);\n margin-left: var(--input-margin);\n margin-right: var(--input-margin);\n border: solid #5f9341 1px;\n border-radius: 30px;\n}\n\n#save {\n width: 100px;\n padding: 10px;\n margin-top: 4px;\n margin-left: 10px;\n border: none;\n background-color: #5f9341;\n font-weight: bold;\n color: white;\n text-transform: uppercase;\n border-radius: 30px;\n}\n\n#save:active {\n transform: scale(0.98);\n} <input type=\"text\" id=\"input\" />\n<button id=\"save\">Save input</button>\n<button id=\"save\">Save input</button>" }, { "answer_id": 74535210, "author": "disinfor", "author_id": 1172189, "author_profile": "https://Stackoverflow.com/users/1172189", "pm_score": 2, "selected": false, "text": "margin width: calc(100% - 10px) body {\n margin: 0;\n padding: 10px;\n}\n\ninput {\n width: calc(100% - 10px);\n box-sizing: border-box;\n padding: 10px;\n margin-top: 10px;\n margin-left: 10px;\n border: solid #5f9341 1px;\n border-radius: 30px;\n}\n\n#save {\n width: 100px;\n padding: 10px;\n margin-top: 4px;\n margin-left: 10px;\n border: none;\n background-color: #5f9341;\n font-weight: bold;\n color: white;\n text-transform: uppercase;\n border-radius: 30px;\n}\n\n#save:active {\n transform: scale(0.98);\n} <body>\n <input type=\"text\" id=\"input\" placeholder=\"not wrapped\" />\n <div class=\"input-wrap\">\n <input type=\"text\" id=\"input-wrapped\" placeholder=\"wrapped\" />\n </div>\n <button id=\"save\">Save input</button>\n <button id=\"save\">Save input</button>\n</body>" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20370427/" ]
74,535,010
<p>Been struggling with this problem, can't figure it out. My simplified table schemas are:</p> <ol> <li>SalesOrderHeader(SalesOrderID int, ShipToAddressID int),</li> <li>SalesOrderDetails(SalesOrderID int, ProductID int),</li> <li>Address(ShipToAddressID int, City nvarchar),</li> <li>Product(ProductID int, ProductCategory int)</li> <li>ProductCategory(ProductCategoryID int, Name nvarchar).</li> </ol> <p>I tried to find the 3 most popular cities(the ones which have the most orders delivered to) and the most popular product categories in these cities, but unfortunately, can't make it work properly.</p> <pre><code>select count(*) as OrderNum, ProductCategory.Name, City from SalesLT.SalesOrderDetail left join SalesLT.SalesOrderHeader on SalesLT.SalesOrderDetail.SalesOrderID = SalesLT.SalesOrderHeader.SalesOrderID left join SalesLT.Address on SalesLT.Address.AddressID = SalesOrderHeader.ShipToAddressID left join SalesLT.Product on SalesOrderDetail.ProductID = Product.ProductID left join SalesLT.ProductCategory on ProductCategory.ProductCategoryID = Product.ProductCategoryID where City in (select top(3) City from SalesLT.SalesOrderHeader left join SalesLT.Address on SalesLT.Address.AddressID = SalesOrderHeader.ShipToAddressID group by City order by Count(*) desc) group by City, ProductCategory.Name order by count(*) desc </code></pre> <p>I tried to change the query to make it return only 1 position for each city, but it didn't work. Would be grateful to hear an advice, thank you.</p> <p><a href="https://i.stack.imgur.com/hxpwN.jpg" rel="nofollow noreferrer">Query returns following result</a></p>
[ { "answer_id": 74535191, "author": "Cédric", "author_id": 17684809, "author_profile": "https://Stackoverflow.com/users/17684809", "pm_score": 0, "selected": false, "text": "width: 100% calc() :root {\n --input-margin: 10px;\n}\n\nbody {\n margin: 0;\n padding: 10px;\n}\n\ninput {\n width: calc(100% - 2 * var(--input-margin));\n box-sizing: border-box;\n padding: 10px;\n margin-top: var(--input-margin);\n margin-left: var(--input-margin);\n margin-right: var(--input-margin);\n border: solid #5f9341 1px;\n border-radius: 30px;\n}\n\n#save {\n width: 100px;\n padding: 10px;\n margin-top: 4px;\n margin-left: 10px;\n border: none;\n background-color: #5f9341;\n font-weight: bold;\n color: white;\n text-transform: uppercase;\n border-radius: 30px;\n}\n\n#save:active {\n transform: scale(0.98);\n} <input type=\"text\" id=\"input\" />\n<button id=\"save\">Save input</button>\n<button id=\"save\">Save input</button>" }, { "answer_id": 74535210, "author": "disinfor", "author_id": 1172189, "author_profile": "https://Stackoverflow.com/users/1172189", "pm_score": 2, "selected": false, "text": "margin width: calc(100% - 10px) body {\n margin: 0;\n padding: 10px;\n}\n\ninput {\n width: calc(100% - 10px);\n box-sizing: border-box;\n padding: 10px;\n margin-top: 10px;\n margin-left: 10px;\n border: solid #5f9341 1px;\n border-radius: 30px;\n}\n\n#save {\n width: 100px;\n padding: 10px;\n margin-top: 4px;\n margin-left: 10px;\n border: none;\n background-color: #5f9341;\n font-weight: bold;\n color: white;\n text-transform: uppercase;\n border-radius: 30px;\n}\n\n#save:active {\n transform: scale(0.98);\n} <body>\n <input type=\"text\" id=\"input\" placeholder=\"not wrapped\" />\n <div class=\"input-wrap\">\n <input type=\"text\" id=\"input-wrapped\" placeholder=\"wrapped\" />\n </div>\n <button id=\"save\">Save input</button>\n <button id=\"save\">Save input</button>\n</body>" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19036367/" ]
74,535,025
<p><code>Concurrency::task.wait()</code> throws <code>invalid_operation</code> exception: <strong>&quot;Illegal to wait on a task in a Windows Runtime STA.&quot;</strong></p> <p>This exception occurs since ~14th November 2022 and seems to be Microsoft update related.</p> <p>The exception does not occur, when building in <strong>Debug</strong> mode. <em><strong>Edit</strong>: it was true only for some Visual Studio versions. The latest release do throw the exception regardless of Debug or Release modes.</em></p> <p>The code runs in a C++ application as managed-C++.</p> <p>Any known Microsoft issues in this direction? <em><strong>Edit</strong>: the exception seems to be correct but it never showed up until some updates.</em></p>
[ { "answer_id": 74557519, "author": "user2279376", "author_id": 2279376, "author_profile": "https://Stackoverflow.com/users/2279376", "pm_score": 1, "selected": false, "text": "try {\n response = client.request(request).get();\n} catch (...) {\n}\n" }, { "answer_id": 74655944, "author": "Viktor Be", "author_id": 11440276, "author_profile": "https://Stackoverflow.com/users/11440276", "pm_score": 1, "selected": true, "text": "COM CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); CoInitialize(NULL); Concurrency::task.wait() COM CoInitializeEx(NULL, COINIT_MULTITHREADED); Windows::Foundation::Initialize(RO_INIT_MULTITHREADED); Concurrency::task.wait() COINIT_APARTMENTTHREADED std::thread" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11440276/" ]
74,535,066
<p>The powerset of {1, 2, 3} is:</p> <p>{{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}}</p> <p>I have a String array in java,</p> <pre><code> String elements={&quot;apple&quot;,&quot;mango&quot;,&quot;banana&quot;}; String set[]=elements.split(&quot;[ ,]+&quot;); </code></pre> <p>How do I print the power set of this array in the Mathematical order? (I have tried bit manipulation method, it does not gives the solution in that order! )</p> <p>My bit manipulation method! Did not give the required result!</p> <pre><code>static void printPowerSet(String[] set) { long pset = (long) Math.pow(2, set.length); System.out.print(&quot;Power Set is \n{&quot;); for (int i = 0; i &lt; pset; i++) { System.out.print(&quot;{&quot;); for (int j = 0; j &lt; set.length; j++) { if ((i &amp; (1 &lt;&lt; j)) &gt; 0){ System.out.print(set[j] + &quot; &quot;); } if (i == 0 &amp;&amp; j==0 ) System.out.print(&quot; &quot;); } System.out.println(&quot;}&quot;); } System.out.println(&quot; } \n&quot;); } </code></pre>
[ { "answer_id": 74557519, "author": "user2279376", "author_id": 2279376, "author_profile": "https://Stackoverflow.com/users/2279376", "pm_score": 1, "selected": false, "text": "try {\n response = client.request(request).get();\n} catch (...) {\n}\n" }, { "answer_id": 74655944, "author": "Viktor Be", "author_id": 11440276, "author_profile": "https://Stackoverflow.com/users/11440276", "pm_score": 1, "selected": true, "text": "COM CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); CoInitialize(NULL); Concurrency::task.wait() COM CoInitializeEx(NULL, COINIT_MULTITHREADED); Windows::Foundation::Initialize(RO_INIT_MULTITHREADED); Concurrency::task.wait() COINIT_APARTMENTTHREADED std::thread" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17017229/" ]
74,535,138
<p>In Julia, some amazing packages like <code>ProgressMeter</code> provide an easy API for displaying progress bars in the REPL. However, it seems like they only work with regular for loops, comprehensions and map/reduce. So, e.g., these work:</p> <pre><code>using ProgressMeter function sleepyAdd(arg::Int64) sleep(1) return arg + 1000 end nums = [1, 2, 3, 4] # Progress bar with for loop @showprogress for num in nums sleepyAdd(num) end # Progress bar with comprehension @showprogress [sleepyAdd(num) for num in nums] </code></pre> <p>Howeve, you can't just use that with broadcast notation (so <code>@showprogress sleepyAdd.(nums)</code> doesn't work), which is a shame because brodcasting functions is one of the best features of Julia's syntax: elegant, simple and concise.</p> <p><strong>Is there any way around this limitation?</strong></p>
[ { "answer_id": 74538890, "author": "Dan Getz", "author_id": 3580870, "author_profile": "https://Stackoverflow.com/users/3580870", "pm_score": 3, "selected": false, "text": "@showprogress @macroexpand @showprogress... let t_nums = nums, \n t_meter = ProgressMeter.Progress(ProgressMeter.length(t_nums)),\n t_wrapper = ProgressMeter.ProgressWrapper(t_nums, t_meter)\n # now comes the comprehension\n [sleepyAdd(num) for num in t_wrapper]\nend\n for" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12104222/" ]
74,535,156
<p>I am using Elementor Anywhere to create a specific display for my WooCommerce products.</p> <p>I have a filter and for the filter works I need to use Post blocks Adv.</p> <p>There I ask to display current archive.</p> <p>I have the possibility to put a query filter, but I can't exclude products from a certain category.</p> <p>I have this, but it doesn't work with current archives.</p> <pre><code>function filtrer_produit_sans_crea( $query_args ) { $query_args['meta_query'] = array( array( 'key' =&gt; '_stock_status', 'value' =&gt; 'instock', ), ); $query_args['tax_query'][] = array( 'taxonomy' =&gt; 'product_cat', 'field' =&gt; 'slug', 'terms' =&gt; 'coin-des-creatrices', 'operator' =&gt; 'NOT IN', ); return $query_args; } add_filter( 'filtre_zero_dechet', 'filtrer_produit_sans_crea' ); </code></pre> <p>Has anyone ever tried something like this? Or do you have a clue?</p>
[ { "answer_id": 74538890, "author": "Dan Getz", "author_id": 3580870, "author_profile": "https://Stackoverflow.com/users/3580870", "pm_score": 3, "selected": false, "text": "@showprogress @macroexpand @showprogress... let t_nums = nums, \n t_meter = ProgressMeter.Progress(ProgressMeter.length(t_nums)),\n t_wrapper = ProgressMeter.ProgressWrapper(t_nums, t_meter)\n # now comes the comprehension\n [sleepyAdd(num) for num in t_wrapper]\nend\n for" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20573761/" ]
74,535,179
<p>Firstly I'm using C language. I want a variable that I refer to as a parameter to change outside the function when it is changed inside the function. But the problem is that the variable is of type linked list and I want to add to the linked list.</p> <p>So what I'm trying to do is add the linked list outside the function with the save function.</p> <p>Is this possible? If possible how can I do it? Sorry for the English, I used a translator.</p> <p>My codes:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; typedef struct NS { char * name; char * value; struct NS * next; } n_t; void save(char * name, char * value, n_t ** item) { n_t * link = malloc(sizeof(struct NS)); link-&gt;name = name; link-&gt;value = value; link-&gt;next = NULL; n_t ** pointer = NULL; if (*item == NULL) *item = link; pointer = &amp;(*item); while ((*pointer)-&gt;next != NULL) *pointer = (*pointer)-&gt;next; (*pointer)-&gt;next = link; } int main() { n_t * mem = NULL; save(&quot;hello&quot;, &quot;val123&quot;, &amp;mem); printf(&quot;-&gt; %s\n&quot;, mem-&gt;value); save(&quot;abc&quot;, &quot;hello&quot;, &amp;mem); printf(&quot;-&gt; %s\n&quot;, mem-&gt;value); printf(&quot;-&gt; %s\n&quot;, mem-&gt;next-&gt;value); return 0; } </code></pre> <p>The output for the first arrow (-&gt;) should be &quot;val123&quot;</p> <p>The result that should also appear in the second arrow output is &quot;val123&quot;</p> <p>The result that should appear in the third arrow output is &quot;hello&quot;</p>
[ { "answer_id": 74538890, "author": "Dan Getz", "author_id": 3580870, "author_profile": "https://Stackoverflow.com/users/3580870", "pm_score": 3, "selected": false, "text": "@showprogress @macroexpand @showprogress... let t_nums = nums, \n t_meter = ProgressMeter.Progress(ProgressMeter.length(t_nums)),\n t_wrapper = ProgressMeter.ProgressWrapper(t_nums, t_meter)\n # now comes the comprehension\n [sleepyAdd(num) for num in t_wrapper]\nend\n for" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19912998/" ]
74,535,211
<p>I have a pandas df like this:</p> <pre><code>MEMBERSHIP [2022_K_, EWREW_NK] [333_NFK_,2022_K_, EWREW_NK, 000] </code></pre> <p>And I have a list of keys:</p> <pre><code>list_k = [&quot;_K_&quot;,&quot;_NK_&quot;,&quot;_NKF_&quot;,&quot;_KF_&quot;] </code></pre> <p>I want to add and create a column that count if any of that element is in the column. The desired output is:</p> <pre><code>MEMBERSHIP | COUNT [2022_K_, EWREW_NK] | 2 [333_NFK_,2022_K_, EWREW_NK, 000] | 3 </code></pre> <p>Can you help me?</p>
[ { "answer_id": 74535624, "author": "coelidonum", "author_id": 12430846, "author_profile": "https://Stackoverflow.com/users/12430846", "pm_score": 0, "selected": false, "text": "count_row=0\ndf['Count']= None\nfor i in df['MEMBERSHIP_SPLIT']:\n count_element=0\n\n for sub in i:\n for e in list_k:\n if e in sub:\n count_element+=1\n df['Count'][count_row]=count_element\n count_row += 1 \n" }, { "answer_id": 74535647, "author": "Bushmaster", "author_id": 15415267, "author_profile": "https://Stackoverflow.com/users/15415267", "pm_score": 1, "selected": false, "text": "def check(x):\n total=0\n for i in x:\n if type(i) != str: #if value is not string pass.\n pass\n else:\n for j in list_k:\n if j in i:\n total+=1\n return total\n \ndf['count']=df['MEMBERSHIP'].apply(lambda x: check(x))\n" }, { "answer_id": 74535726, "author": "Scott Boston", "author_id": 6361531, "author_profile": "https://Stackoverflow.com/users/6361531", "pm_score": 2, "selected": true, "text": "import pandas as pd\ndf = pd.DataFrame({'MEMBERSHIP':[['2022_K_', 'EWREW_NK'],\n ['333_NFK_','2022_K_', 'EWREW_NK', '000']]})\n\nlist_k = [\"_K_\",\"_NK\",\"_NFK_\",\"_KF_\"] #I changed this list a little\nreg = '|'.join(list_k)\ndf['count'] = df['MEMBERSHIP'].explode().str.contains(reg).groupby(level=0).sum()\nprint(df)\n MEMBERSHIP count\n0 [2022_K_, EWREW_NK] 2\n1 [333_NFK_, 2022_K_, EWREW_NK, 000] 3\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12430846/" ]
74,535,282
<p>After upgrading in the backend by clicking on update button, I'm getting <em>&quot;Our website is currently undergoing maintenance.&quot;</em> both on front- and backend. Deleted update-assets folder, nothing changed. When I go to <em>mydomain/recovery/update/index.php</em> I'm getting:</p> <blockquote> <p>Slim Application Error</p> </blockquote> <blockquote> <p>The application could not run because of the following error:</p> </blockquote> <blockquote> <p>Details</p> </blockquote> <blockquote> <p>Type: TypeError</p> </blockquote> <blockquote> <p>Message: trim() expects parameter 1 to be string, bool given</p> </blockquote> <blockquote> <p>File: .../shop/vendor/shopware/recovery/Update/src/DependencyInjection/Container.php</p> </blockquote> <blockquote> <p>Line: 41</p> </blockquote> <p>What can I do?</p>
[ { "answer_id": 74537238, "author": "dneustadt", "author_id": 8556259, "author_profile": "https://Stackoverflow.com/users/8556259", "pm_score": 1, "selected": false, "text": "{shopwareRoot}/files/backup/auto_update/dummy" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2511599/" ]
74,535,285
<p>I've been trying to get the switch statement to work without having to be nested, but it won't work because it's linked to the if statement I've made.</p> <p>Does anybody know how i can move the boardType switch statement outside of the duration switch statement with the if statement still working? Thank you</p> <pre><code>int duration = input.nextInt(); switch (duration) { default -&gt; System.out.println(&quot;You have not entered a valid number of nights.&quot;); case 2, 7, 14 -&gt; { System.out.print(&quot;How many guests are in your party? &quot;); int guestAmount = input.nextInt(); if (guestAmount &gt;= 1 &amp;&amp; guestAmount &lt;= 10) { System.out.print(&quot;What type of board would you like (full, half, or self-catering)? &quot;); String boardType = input.next(); switch (boardType) { case &quot;full&quot;, &quot;half&quot;, &quot;self-catering&quot; -&gt; System.out.println(&quot;Valid details entered - booking may proceed&quot;); default -&gt; System.out.println(&quot;Sorry, we do not cater that type of board.&quot;); } } else { System.out.println(&quot;Sorry, you are only allowed 1 to 10 guests.&quot;); </code></pre>
[ { "answer_id": 74537238, "author": "dneustadt", "author_id": 8556259, "author_profile": "https://Stackoverflow.com/users/8556259", "pm_score": 1, "selected": false, "text": "{shopwareRoot}/files/backup/auto_update/dummy" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17145420/" ]
74,535,292
<p>I using <a href="https://github.com/dsherret/ts-morph" rel="nofollow noreferrer">ts-morph</a> to analyze my code and I want to get the parent <code>CallExpression</code> from <code>Identifier</code> location. So I use <code>.getParentWhileKind(SyntaxKind.CallExpression)</code>, but the function returns <code>null</code>.</p> <p>Why? I do have <code>CallExpression</code>, which is the parent of <code>Identifier</code> (<code>foo</code>)</p> <p>What am I missing? and how to solve it? (other than use <code>getParent().getParent()..</code>)</p> <pre><code>import { Identifier, Project, SyntaxKind } from &quot;ts-morph&quot;; console.clear(); const project = new Project(); const sourceFile = project.createSourceFile( &quot;test.ts&quot;, ` const fn = () =&gt; { chain.foo.bar('arg'); } ` ); const a = sourceFile.getDescendants().find((d) =&gt; d.getText() === &quot;foo&quot;); console.log({ a: a?.getParentWhileKind(SyntaxKind.CallExpression) }); </code></pre> <p><a href="https://codesandbox.io/s/magical-wildflower-ufwvep?file=/src/index.ts" rel="nofollow noreferrer">codesandbox.io</a></p>
[ { "answer_id": 74537238, "author": "dneustadt", "author_id": 8556259, "author_profile": "https://Stackoverflow.com/users/8556259", "pm_score": 1, "selected": false, "text": "{shopwareRoot}/files/backup/auto_update/dummy" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10932853/" ]
74,535,293
<p>After starting the program (launching TomCat) there are no tables created in the schema, but the table &quot;player&quot; has to be created automatically.</p> <p>I checked hibernate config, but can't find where is the problem. I've tried changing hbm2ddl.auto to hibernate.hbm2ddl.auto (also create, create-drop etc.) but it didn't help.</p> <p>If there are any ideas, please let me know. Thanks.</p> <p><strong>Entity class:</strong></p> <pre><code>package com.game.entity; import javax.persistence.*; import java.util.Date; @Entity @Table(schema = &quot;rpg&quot;, name = &quot;player&quot;) public class Player { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = &quot;id&quot;) private Long id; @Column(name = &quot;name&quot;, length = 12, nullable = false) private String name; @Column(name = &quot;title&quot;, length = 30, nullable = false) private String title; @Column(name = &quot;race&quot;, nullable = false) @Enumerated(EnumType.ORDINAL) private Race race; @Column(name = &quot;profession&quot;, nullable = false) @Enumerated(EnumType.ORDINAL) private Profession profession; @Column(name = &quot;birthday&quot;, nullable = false) private Date birthday; @Column(name = &quot;banned&quot;, nullable = false) private Boolean banned; @Column(name = &quot;level&quot;, nullable = false) private Integer level; public Player() { } public Player(Long id, String name, String title, Race race, Profession profession, Date birthday, Boolean banned, Integer level) { this.id = id; this.name = name; this.title = title; this.race = race; this.profession = profession; this.birthday = birthday; this.banned = banned; this.level = level; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Race getRace() { return race; } public void setRace(Race race) { this.race = race; } public Profession getProfession() { return profession; } public void setProfession(Profession profession) { this.profession = profession; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public Boolean getBanned() { return banned; } public void setBanned(Boolean banned) { this.banned = banned; } public Integer getLevel() { return level; } public void setLevel(Integer level) { this.level = level; } } </code></pre> <p><strong>Repository class:</strong></p> <pre><code>package com.game.repository; import com.game.entity.Player; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.query.NativeQuery; import org.springframework.stereotype.Repository; import javax.annotation.PreDestroy; import java.util.List; import java.util.Optional; @Repository(value = &quot;db&quot;) public class PlayerRepositoryDB implements IPlayerRepository { private final SessionFactory sessionFactory; public PlayerRepositoryDB() { Configuration configuration = new Configuration().configure().addAnnotatedClass(Player.class); StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()).build(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } @Override public List&lt;Player&gt; getAll(int pageNumber, int pageSize) { try(Session session = sessionFactory.openSession()){ NativeQuery&lt;Player&gt; nativeQuery = session.createNativeQuery(&quot;SELECT * FROM rpg.player&quot;, Player.class); nativeQuery.setFirstResult(pageNumber * pageSize); nativeQuery.setMaxResults(pageSize); return nativeQuery.list(); } } </code></pre> <p><strong>Hibernate configuration:</strong></p> <pre><code>&lt;?xml version='1.0' encoding='utf-8'?&gt; &lt;!DOCTYPE hibernate-configuration PUBLIC &quot;-//Hibernate/Hibernate Configuration DTD//EN&quot; &quot;http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd&quot;&gt; &lt;hibernate-configuration&gt; &lt;session-factory&gt; &lt;property name=&quot;connection.url&quot;&gt;jdbc:mysql://localhost:3306/rpg&lt;/property&gt; &lt;property name=&quot;connection.driver_class&quot;&gt;com.mysql.cj.jdbc.Driver&lt;/property&gt; &lt;property name=&quot;connection.username&quot;&gt;root&lt;/property&gt; &lt;property name=&quot;connection.password&quot;&gt;1234&lt;/property&gt; &lt;property name=&quot;hbm2ddl.auto&quot;&gt;update&lt;/property&gt; &lt;property name=&quot;dialect&quot;&gt;org.hibernate.dialect.MySQL8Dialect&lt;/property&gt; &lt;property name=&quot;show_sql&quot;&gt;true&lt;/property&gt; &lt;property name=&quot;hibernate.current_session_context_class&quot;&gt;thread&lt;/property&gt; &lt;/session-factory&gt; &lt;/hibernate-configuration&gt; </code></pre> <p><strong>Full project code with pom.xml is available by link:</strong> <a href="https://github.com/gamlethot/project-hibernate-1" rel="nofollow noreferrer">https://github.com/gamlethot/project-hibernate-1</a></p>
[ { "answer_id": 74537238, "author": "dneustadt", "author_id": 8556259, "author_profile": "https://Stackoverflow.com/users/8556259", "pm_score": 1, "selected": false, "text": "{shopwareRoot}/files/backup/auto_update/dummy" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18504667/" ]
74,535,305
<p>I have dataframe, and I would like to merge the rows that has the same value in reversed columns. An example as below:</p> <pre><code>Column1 Column2 A B B A C D D C E F </code></pre> <p>Expected results:</p> <pre><code>Column1 Column2 A B C D E F </code></pre> <p>As the file has less than 50 lines (though I have 1000 files), I tried some codes use <code>iterrows</code> as followed:</p> <pre><code>for index, row in df.iterrows(): output = [] row_rev = df[(df['Column1'] == row['Column2']) &amp; (df['Column2'] == row['Column1'])] row_rev_index = df[(df['Column1'] == row['Column2']) &amp; (df['Column2'] == row['Column1'])].index() if row_rev.any(): print(df[min([index, row_rev_index])]) output.append(df[min([index, row_rev_index])]) # always print out the first line of the reciprocal lines </code></pre> <p>but it complains that <code>row_rev_index = df[(df['Column1'] == row['Column2']) &amp; (df['Column2'] == row['Column1'])].index()</code> <code>TypeError: 'Int64Index' object is not callable</code></p>
[ { "answer_id": 74537238, "author": "dneustadt", "author_id": 8556259, "author_profile": "https://Stackoverflow.com/users/8556259", "pm_score": 1, "selected": false, "text": "{shopwareRoot}/files/backup/auto_update/dummy" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14633866/" ]
74,535,309
<p>I'm trying to make an exercise app and when a user finishes a set of exercises, I want them to be able to press a button to go back into the home screen.</p> <p>There are 5 exercises in total, so I made 5 exercise views that shows the 5 different exercises and each exercise view has a navigation link at the bottom to lead to the next exercise. When a user reaches the last exercise, I want the button at the bottom to bring them back to the home screen but when I did that, there would be a back button at the top. Is there any way to go back to the home screen from that view without the back button?</p> <p>Code for the last exercise screen:</p> <pre><code>import SwiftUI import AVKit struct ExerciseScreen5View: View { var countdownTimer = 300 @State var player = AVPlayer() var exercisePlan: ExercisePlan var body: some View { VStack { Text(exercisePlan.exercise5.title) .font(.system(size: 35, weight: .medium)) .padding(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)) VideoPlayer(player: exercisePlan.exercise5.video) .scaledToFit() .frame(alignment: .center) .cornerRadius(10) .padding(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)) Text(exercisePlan.exercise5.steps) .font(.system(size: 20, weight: .regular)) .padding() .frame(alignment: .center) TimerView() .padding(EdgeInsets(top: 0, leading: 0, bottom: 35, trailing: 0)) NavigationLink(destination: ContentView()) { Text(&quot;Return to Home Screen&quot;) .padding() .background((Color(red: 184/255, green: 243/255, blue: 255/255))) .foregroundColor(.black) .cornerRadius(10) } } } } struct ExerciseScreen5View_Previews: PreviewProvider { static var previews: some View { ExerciseScreen5View(exercisePlan: ExercisePlan(title: &quot;Exercise Plan 1&quot;, details: &quot;Choose this plan for a more basic workout&quot;, exercise: Exercise(title: &quot;Tricep Stretch&quot;, duration: 5, steps: &quot;Lift your left elbow straight up while bending your arm. Grab your left elbow with your right hand and pull your left elbow towards your head or slightly behind your head with light pressure. (We recommend doing 10 seconds per rep)&quot;, video: AVPlayer(url: Bundle.main.url(forResource: &quot;TricepStretch&quot; , withExtension: &quot;MOV&quot;)!)), exercise2: Exercise(title: &quot;Toe Touches&quot;, duration: 5, steps: &quot;Sit with your legs closed and toes pointing up. Keep your knees straight while stretching your arms forward to touch your toes. (We recommend doing 20 seconds per rep)&quot;, video: AVPlayer(url: Bundle.main.url(forResource: &quot;ToeTouches&quot; , withExtension: &quot;MOV&quot;)!)), exercise3: Exercise(title: &quot;Arm Circles&quot;, duration: 5, steps: &quot;Hold your arms straight out to your sides, then swing them forwards or backwards in circles. Try to keep your shoulders down while doing this exercise. (We recommend doing 20 seconds per rep then changing sides)&quot;, video: AVPlayer(url: Bundle.main.url(forResource: &quot;ArmCircles&quot; , withExtension: &quot;MOV&quot;)!)), exercise4: Exercise(title: &quot;Elbow Stretch&quot;, duration: 5, steps: &quot;Lift your left arm up while pushing it towards your chest, with your elbow pointing forward. (We recommend doing 10 seconds per rep)&quot;, video: AVPlayer(url: Bundle.main.url(forResource: &quot;ElbowStretch&quot; , withExtension: &quot;MOV&quot;)!)), exercise5: Exercise(title: &quot;Calf Raises&quot;, duration: 5, steps: &quot;Raise your heels off the floor and return to the starting position, by slowly lowering your heels. (We recommend doing 20 seconds per rep)&quot;, video: AVPlayer(url: Bundle.main.url(forResource: &quot;CalfRaises&quot; , withExtension: &quot;MOV&quot;)!)) )) } } </code></pre> <p><a href="https://i.stack.imgur.com/LUCUS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LUCUS.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74537238, "author": "dneustadt", "author_id": 8556259, "author_profile": "https://Stackoverflow.com/users/8556259", "pm_score": 1, "selected": false, "text": "{shopwareRoot}/files/backup/auto_update/dummy" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18810574/" ]
74,535,331
<p>Is there a way to print a specified character of a string in a certain position?</p> <p>For example:</p> <pre><code>char str[]=&quot;Hello&quot;; Output: o </code></pre> <p>I have to print the letter &quot;o&quot; in the position indicated by its index (in this case &quot;4&quot;);</p>
[ { "answer_id": 74537238, "author": "dneustadt", "author_id": 8556259, "author_profile": "https://Stackoverflow.com/users/8556259", "pm_score": 1, "selected": false, "text": "{shopwareRoot}/files/backup/auto_update/dummy" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20523849/" ]
74,535,332
<p>I have a df like this:</p> <pre><code>data &lt;- tribble(~id, ~othervar, ~it_1, ~it_2, ~it_3, ~it_4, ~it_5, ~it_6, &quot;k01&quot;, &quot;lum&quot;, &quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;a&quot;, NA, NA, &quot;k01&quot;, &quot;lum&quot;, NA, NA, NA, NA, &quot;a&quot;, &quot;d&quot;, &quot;k02&quot;, &quot;nar&quot;, &quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;b&quot;, NA, NA, &quot;k03&quot;, &quot;lum&quot;, &quot;a&quot;, &quot;b&quot;, &quot;a&quot;, &quot;c&quot;, NA, NA, &quot;k03&quot;, &quot;lum&quot;, &quot;b&quot;, &quot;b&quot;, &quot;a&quot;, NA, &quot;d&quot;, &quot;e&quot;) </code></pre> <p>I want to merge rows with duplicated IDs in only one row where NAs are replaced with the information available in the other row. But where there are no-NA in both rows, the problem is to preserve any one. I´ve tried pivoting the table, but have no resources to deal with this.</p> <p>i expect somthing like this:</p> <pre><code>id othervar it_1 it_2 it_3 it_4 it_5 it_6 k01 lum a b c a a d k02 nar a b c b NA NA k03 lum a b a c d e </code></pre>
[ { "answer_id": 74535435, "author": "Maël", "author_id": 13460602, "author_profile": "https://Stackoverflow.com/users/13460602", "pm_score": 1, "selected": false, "text": "ifelse summarise library(dplyr)\ndata %>% \n group_by(id) %>% \n summarise(across(everything(), ~ ifelse(any(complete.cases(.x)),\n first(.x[!is.na(.x)]),\n NA)))\n\n# A tibble: 3 × 8\n id othervar it_1 it_2 it_3 it_4 it_5 it_6 \n <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>\n1 k01 lum a b c a a d \n2 k02 nar a b c b NA NA \n3 k03 lum a b a c d e \n" }, { "answer_id": 74537284, "author": "asd-tm", "author_id": 5043424, "author_profile": "https://Stackoverflow.com/users/5043424", "pm_score": 0, "selected": false, "text": "ifelse data %>%\ngroup_by(id) %>%\nsummarise(across(everything(), \n~coalesce(.x) %>% \n`[`(!is.na(.)) %>% \n`[`(1) ))\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14119277/" ]
74,535,347
<p>I try to implement a method to segment image with seed points, and assign each pixel to nearest point.</p> <p>for example, if the pixel close to 1, then set to 1.</p> <p>input:</p> <pre><code>0 0 0 0 0 3 0 0 1 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 </code></pre> <p>output:</p> <pre><code>1 1 1 3 3 3 3 1 1 1 2 2 3 3 1 1 1 2 2 2 2 1 1 1 2 2 2 2 </code></pre> <p>current the method take too long time and calculate (width * height * numPoints) times, is there any algorithm can be faster?</p> <hr /> <p>7 seconds to process 5 9478 * 1868 images, numPoints = 8</p> <pre><code> for (int i = 0; i &lt; height; i++) { for (int j = 0; j &lt; width; j++) { byte index = 0; double distance = double.MaxValue; for (int m = 0; m &lt; elements.Count; m++) { CircleROI circle = roiResized[m]; double currentDistance = Math.Abs(i - circle.Center.Y) + Math.Abs(j - circle.Center.X); if (currentDistance &lt; distance) { distance = currentDistance; index = (byte)m; } } *data++ = index; } } </code></pre>
[ { "answer_id": 74536942, "author": "Mark Setchell", "author_id": 2836621, "author_profile": "https://Stackoverflow.com/users/2836621", "pm_score": 3, "selected": true, "text": "magick -size 60x30 xc: \\\n -sparse-color Voronoi '10,10 red 40,20 lime 50,0 blue' \\\n result.png\n magick -size 60x30- xc: \\\n -sparse-color Voronoi '10,10 black 40,20 gray 50,0 white' result.png\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7364454/" ]
74,535,353
<p>I'm using Laravel 9 with php 8.1 in a pretty advanced project. In this project I have a parent form which allows a purchase order document to be created. The po document has at least one child row which is added by clicking an add button using livewire. However when this is saved the document it belongs to has not been created and thus no id i can use. So how would you guys handle such a form?</p> <p>I'm considering a temporary id which I think is my best option. I had considered using the user id here but if I as the user have 2 such forms on the go then I wouldn't know which are the correct rows to amend with the document id, worse if I've added rows and get logged out these rows will be unattached.</p> <p>Another option would be to create the document but as it stands it would fail validation due to there being no associated rows.</p> <p>I'm struggling to find a strategy to deal with this scenario. In a previous project I used an is_draft flag for a similar scenario but it left orphaned items if the process was not fully completed.</p> <p>thanks</p>
[ { "answer_id": 74536942, "author": "Mark Setchell", "author_id": 2836621, "author_profile": "https://Stackoverflow.com/users/2836621", "pm_score": 3, "selected": true, "text": "magick -size 60x30 xc: \\\n -sparse-color Voronoi '10,10 red 40,20 lime 50,0 blue' \\\n result.png\n magick -size 60x30- xc: \\\n -sparse-color Voronoi '10,10 black 40,20 gray 50,0 white' result.png\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6236430/" ]
74,535,367
<p>I've written down this following &quot;Design source&quot; code (on Xilinx Vivado) The code is written in System Verilog, and it is the Hamming 7,4 encoder</p> <p><a href="https://en.wikipedia.org/wiki/Hamming(7,4)" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Hamming(7,4)</a></p> <pre><code> module eccproj( input logic [3:0] data_in, output logic [6:0] hamcode); logic p1,p2,p4; always @(*) begin p1 = data_in[0] + data_in[1] + data_in[3]; p2 = data_in[0] + data_in[2] + data_in[3]; p4 = data_in[1] + data_in[2] + data_in[3]; // Input : d3 d2 d1 d0 //Output : d7 d6 d5 p4 d3 d2 d1 assign hamcode = {data_in[3:1] , p4 , data_in[0] , p2 , p1}; // Error on this line end endmodule </code></pre> <p>I am getting error in the line with the comment, and the error reads as follows :</p> <blockquote> <p><em>[Synth 8-27] procedural assign not supported</em></p> </blockquote> <p>I know that, in Verilog the above assignment works, but how to work it using System Verilog.</p> <ul> <li><strong>The above error line, must concatenate the input bits and parity bits at their corresponding positions</strong>*</li> </ul> <p>It would be great if someone could suggest a way to get rid of the error.</p>
[ { "answer_id": 74535456, "author": "toolic", "author_id": 197758, "author_profile": "https://Stackoverflow.com/users/197758", "pm_score": 3, "selected": true, "text": "assign always assign always always @(*) begin\n p1 = data_in[0] + data_in[1] + data_in[3];\n p2 = data_in[0] + data_in[2] + data_in[3];\n p4 = data_in[1] + data_in[2] + data_in[3];\n\n // Input : d3 d2 d1 d0\n //Output : d7 d6 d5 p4 d3 d2 d1 \nend\n\nassign hamcode = {data_in[3:1] , p4 , data_in[0] , p2 , p1};\n" }, { "answer_id": 74535876, "author": "dave_59", "author_id": 2755607, "author_profile": "https://Stackoverflow.com/users/2755607", "pm_score": 1, "selected": false, "text": "assign module eccproj(\ninput logic [3:0] data_in,\noutput logic [6:0] hamcode);\n\n\nlogic p1,p2,p4;\n \nalways_comb begin\n p1 = data_in[0] + data_in[1] + data_in[3];\n p2 = data_in[0] + data_in[2] + data_in[3];\n p4 = data_in[1] + data_in[2] + data_in[3];\n\n // Input : d3 d2 d1 d0\n //Output : d7 d6 d5 p4 d3 d2 d1 \n \n hamcode = {data_in[3:1] , p4 , data_in[0] , p2 , p1}; \nend\n\nendmodule\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17773379/" ]
74,535,370
<p>This is my <code>pubspec.yaml</code></p> <pre><code>flutter: # The following line ensures that the Material Icons font is # included with your application, so that you can use the icons in # the material Icons class. uses-material-design: true # To add assets to your application, add an assets section, like this: assets: - images/img_rectangle1.jpg </code></pre> <p>I have established an assets folder and included it with my.png picture; but, I am experiencing difficulty with the widgets.</p> <pre><code>@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text(&quot;Korean vocabulary related to traits&quot;), centerTitle: false, backgroundColor: const Color(0xFFEC74C8), ), body: Row( children: [ Expanded( child: ListView.builder( itemCount: koreanNameList.length, itemBuilder: (context, index) { KoreanItem item = koreanNameList[index]; return Draggable&lt;KoreanItem&gt;( data: item, dragAnchorStrategy: pointerDragAnchorStrategy, feedback: KoreanNameCard(item: item), child: KoreanNameCard(item: item)); }, )), Expanded( child: ListView.builder( itemCount: englishanswers.length, itemBuilder: (context, index) { return buildEnglishanswerColumn(englishanswers[index]); }, )), ], ), ); } </code></pre> <p>Where exactly should the container that holds the background picture be placed, then?</p> <p>I have tried to use</p> <pre><code>AssetImage </code></pre> <p>but it is not showing on my app.</p>
[ { "answer_id": 74535456, "author": "toolic", "author_id": 197758, "author_profile": "https://Stackoverflow.com/users/197758", "pm_score": 3, "selected": true, "text": "assign always assign always always @(*) begin\n p1 = data_in[0] + data_in[1] + data_in[3];\n p2 = data_in[0] + data_in[2] + data_in[3];\n p4 = data_in[1] + data_in[2] + data_in[3];\n\n // Input : d3 d2 d1 d0\n //Output : d7 d6 d5 p4 d3 d2 d1 \nend\n\nassign hamcode = {data_in[3:1] , p4 , data_in[0] , p2 , p1};\n" }, { "answer_id": 74535876, "author": "dave_59", "author_id": 2755607, "author_profile": "https://Stackoverflow.com/users/2755607", "pm_score": 1, "selected": false, "text": "assign module eccproj(\ninput logic [3:0] data_in,\noutput logic [6:0] hamcode);\n\n\nlogic p1,p2,p4;\n \nalways_comb begin\n p1 = data_in[0] + data_in[1] + data_in[3];\n p2 = data_in[0] + data_in[2] + data_in[3];\n p4 = data_in[1] + data_in[2] + data_in[3];\n\n // Input : d3 d2 d1 d0\n //Output : d7 d6 d5 p4 d3 d2 d1 \n \n hamcode = {data_in[3:1] , p4 , data_in[0] , p2 , p1}; \nend\n\nendmodule\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17902196/" ]
74,535,375
<p>I have two dataframes:</p> <pre><code>df1 = pd.DataFrame({&quot;product&quot;:['apples', 'bananas', 'oranges', 'kiwi']}) df2 = pd.Dataframe({&quot;product&quot;:['apples', 'aples', 'appples', 'banans', 'oranges', 'kiwki'], &quot;key&quot;: [1, 2, 3, 4, 5, 6]}) </code></pre> <p>I want to use something like a set(df2).difference(df1) to find the difference between the product columns but I want to keep the indexes. So ideally the output would look like this</p> <p>result =['aples', 'appples', 'banans', 'kiwki'][2 3 4 6]</p> <p>Whenever I use the set.difference() I get the list of the different values but I lose the key index.</p>
[ { "answer_id": 74535456, "author": "toolic", "author_id": 197758, "author_profile": "https://Stackoverflow.com/users/197758", "pm_score": 3, "selected": true, "text": "assign always assign always always @(*) begin\n p1 = data_in[0] + data_in[1] + data_in[3];\n p2 = data_in[0] + data_in[2] + data_in[3];\n p4 = data_in[1] + data_in[2] + data_in[3];\n\n // Input : d3 d2 d1 d0\n //Output : d7 d6 d5 p4 d3 d2 d1 \nend\n\nassign hamcode = {data_in[3:1] , p4 , data_in[0] , p2 , p1};\n" }, { "answer_id": 74535876, "author": "dave_59", "author_id": 2755607, "author_profile": "https://Stackoverflow.com/users/2755607", "pm_score": 1, "selected": false, "text": "assign module eccproj(\ninput logic [3:0] data_in,\noutput logic [6:0] hamcode);\n\n\nlogic p1,p2,p4;\n \nalways_comb begin\n p1 = data_in[0] + data_in[1] + data_in[3];\n p2 = data_in[0] + data_in[2] + data_in[3];\n p4 = data_in[1] + data_in[2] + data_in[3];\n\n // Input : d3 d2 d1 d0\n //Output : d7 d6 d5 p4 d3 d2 d1 \n \n hamcode = {data_in[3:1] , p4 , data_in[0] , p2 , p1}; \nend\n\nendmodule\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20573915/" ]
74,535,376
<p>Should I need to Global everything Global? Considering scope?</p> <p>I keep randomly running into this problem, Im gonna assume its some how a syntax problem on myside. But variables out side of a scope in python seems to be inconsistent... my situation is</p> <pre><code>libFound=False def Setup(): _setup_import() print('booting:',libFound) #--Here I get False? if libFound: _boot() else:print('Did not Boot') def _setup_import(): sys.path.append(PATH) try: import libwrapper global libwrapper except: #Critical Exception else: #found libFound=True print(libFound)#--Here I get True </code></pre> <p>I assume this is garbage collection but I would think it would match gloval before local variables, should I have to global everything global? Scope is scope, I seem to get this often in python. I would like to include it seems to happen most when initiateing with None or it being Bool</p> <p>Makeing variables global,checking syntax, I've tried researching this but I don't understand if its my syntax possibly or my lack or understanding of how python is actually handleing variable</p>
[ { "answer_id": 74535456, "author": "toolic", "author_id": 197758, "author_profile": "https://Stackoverflow.com/users/197758", "pm_score": 3, "selected": true, "text": "assign always assign always always @(*) begin\n p1 = data_in[0] + data_in[1] + data_in[3];\n p2 = data_in[0] + data_in[2] + data_in[3];\n p4 = data_in[1] + data_in[2] + data_in[3];\n\n // Input : d3 d2 d1 d0\n //Output : d7 d6 d5 p4 d3 d2 d1 \nend\n\nassign hamcode = {data_in[3:1] , p4 , data_in[0] , p2 , p1};\n" }, { "answer_id": 74535876, "author": "dave_59", "author_id": 2755607, "author_profile": "https://Stackoverflow.com/users/2755607", "pm_score": 1, "selected": false, "text": "assign module eccproj(\ninput logic [3:0] data_in,\noutput logic [6:0] hamcode);\n\n\nlogic p1,p2,p4;\n \nalways_comb begin\n p1 = data_in[0] + data_in[1] + data_in[3];\n p2 = data_in[0] + data_in[2] + data_in[3];\n p4 = data_in[1] + data_in[2] + data_in[3];\n\n // Input : d3 d2 d1 d0\n //Output : d7 d6 d5 p4 d3 d2 d1 \n \n hamcode = {data_in[3:1] , p4 , data_in[0] , p2 , p1}; \nend\n\nendmodule\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20494804/" ]
74,535,377
<p><a href="https://i.stack.imgur.com/xnq3G.png" rel="nofollow noreferrer">Errors for this code</a>I don't understand how the code under the docstring is running. I am trying to make a main menu. I also keep getting errors under the comments</p> <pre><code>def main_menu(): # Function for the interface where the user is presented with a menu and given the options requiring the user's input choice = input(&quot;&quot;&quot; MainName R - Reporting I - Intelligence M - Monitoring A - About Q - Quit Choose an option: &quot;&quot;&quot;) if choice == &quot;R&quot; or choice == &quot;r&quot;: reporting() elif choice == &quot;I&quot; or choice == &quot;i&quot;: intelligence() elif choice == &quot;M&quot; or choice == &quot;m&quot;: monitoring() elif choice == &quot;A&quot; or choice == &quot;a&quot;: about() elif choice == &quot;Q&quot; or choice == &quot;q&quot;: quit() else: print(&quot; &quot;) print(&quot;Please try again&quot;) main_menu() </code></pre> <p>Is this a correct way to making a menu? The program runs with no error messages but I keep getting problems highlighted.</p>
[ { "answer_id": 74535456, "author": "toolic", "author_id": 197758, "author_profile": "https://Stackoverflow.com/users/197758", "pm_score": 3, "selected": true, "text": "assign always assign always always @(*) begin\n p1 = data_in[0] + data_in[1] + data_in[3];\n p2 = data_in[0] + data_in[2] + data_in[3];\n p4 = data_in[1] + data_in[2] + data_in[3];\n\n // Input : d3 d2 d1 d0\n //Output : d7 d6 d5 p4 d3 d2 d1 \nend\n\nassign hamcode = {data_in[3:1] , p4 , data_in[0] , p2 , p1};\n" }, { "answer_id": 74535876, "author": "dave_59", "author_id": 2755607, "author_profile": "https://Stackoverflow.com/users/2755607", "pm_score": 1, "selected": false, "text": "assign module eccproj(\ninput logic [3:0] data_in,\noutput logic [6:0] hamcode);\n\n\nlogic p1,p2,p4;\n \nalways_comb begin\n p1 = data_in[0] + data_in[1] + data_in[3];\n p2 = data_in[0] + data_in[2] + data_in[3];\n p4 = data_in[1] + data_in[2] + data_in[3];\n\n // Input : d3 d2 d1 d0\n //Output : d7 d6 d5 p4 d3 d2 d1 \n \n hamcode = {data_in[3:1] , p4 , data_in[0] , p2 , p1}; \nend\n\nendmodule\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20573938/" ]
74,535,378
<p>I have two models:</p> <pre><code>class Student(models.Model): first_name = models.CharField() last_name = models.CharField() class Group(models.Model): name = models.CharField() students = models.ManyToManyField(Student) </code></pre> <p>Some data (<code>first_name</code> and <code>last_name</code> concatenated):</p> <pre><code>Group #1 | Blak Coleman Group #1 | Miguel Scott Group #2 | Jordan Barnes Group #2 | Jordan Gustman Group #2 | Jekson Barnes Group #3 | Jordan Smith </code></pre> <p>As you can see theres three students by name <code>Jordan</code>. So I need to return groups which in <code>students</code> queryset has only students by name <code>Jordan</code>.</p> <p>I tried this:</p> <pre><code>groups = Group.objects.filter(students__first_name='Jordan') </code></pre> <p>But <code>group.first().students.all()</code> contains all the students not only Jordan. Expected result:</p> <pre><code>Group #2 | Jordan Barnes Group #2 | Jordan Gustman Group #3 | Jordan Smith </code></pre> <p>How could I do this?</p>
[ { "answer_id": 74535641, "author": "Sunderam Dubey", "author_id": 17562044, "author_profile": "https://Stackoverflow.com/users/17562044", "pm_score": 0, "selected": false, "text": "groups = Group.objects.filter(students__first_name__in=['Jordan'])\n" }, { "answer_id": 74561823, "author": "Альберт Александров", "author_id": 9112151, "author_profile": "https://Stackoverflow.com/users/9112151", "pm_score": 1, "selected": false, "text": "from django.db.models import Prefetch\n\nstudents = Student.objects.filter(first_name='Jordan')\nprefetch = Prefetch('students', queryset=students)\ngroups = Group.objects.prefetch_related(prefetch)\ngroups = [group for group in groups if len(group.students.all())]\n" }, { "answer_id": 74564473, "author": "Mahammadhusain kadiwala", "author_id": 19205926, "author_profile": "https://Stackoverflow.com/users/19205926", "pm_score": 0, "selected": false, "text": "groups = Group.objects.filter(students__id__in=[i.id for i in Students.objects.all()])\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9112151/" ]
74,535,394
<p>Apologies if this doesn't make sense! Fairly new to WinForms and this is for a uni assessment. My main form is as below with the method I want to call in another class. I've renamed from Form1 to LoginPage.</p> <pre><code>public partial class LoginPage : Form { public LoginPage() { InitializeComponent(); Customer.LoadCustomerDB(); } public string PinText { get { return PINNumTxt.Text; } set { PINNumTxt.Text = value; } } } </code></pre> <p>My other class looks to verify the PinText which I've made accessible with the function above.</p> <pre><code> class BankCard { // Attributes private Customer customer; private int pinAttempts = 0; private bool cardUnusable = false; // Member functions public void VerifyPIN() { LoginPage loginPage = new LoginPage(); foreach (Customer c in Customer.customers) { if (c.GetID().ToString() == loginPage.AccountNum()) { customer = c; } } if (cardUnusable == true) { MessageBox.Show(&quot;This card is currently blocked. Please contact your bank.&quot;); Environment.Exit(0); } else if (loginPage.PinText == customer.GetPIN()) { MessageBox.Show(&quot;Success!&quot;); } else if (pinAttempts &lt; 2) { MessageBox.Show(&quot;Incorrect PIN attempt &quot; + (pinAttempts + 1) + &quot;/3&quot;); loginPage.PinText = &quot;&quot;; pinAttempts += 1; } else { MessageBox.Show(&quot;3 failed PIN attempts. Please contact your bank.&quot;); cardUnusable = true; Environment.Exit(0); } } } </code></pre> <p>My issue is that where I have the following:</p> <pre><code>LoginPage loginPage = new LoginPage(); </code></pre> <p>This creates a new instance of the main page, doubles up the CustomerDB being loaded in and causes errors in my VerifyPin() function.</p> <p>Is the issue that I need to somehow have LoginPage loginPage = current instance of LoginPage? And if so, how would I code that?</p> <p>Thanks for any help</p>
[ { "answer_id": 74535576, "author": "frankM_DN", "author_id": 20034020, "author_profile": "https://Stackoverflow.com/users/20034020", "pm_score": -1, "selected": false, "text": "Program Application.Run(new Form1()); LoginPage Program public static LoginPage loginPage; Main static void Main()\n{\n loginPage = new LoginPage();\n Application.Run(loginPage);\n}\n loginPage Program.loginPage" }, { "answer_id": 74535862, "author": "JordanChester", "author_id": 17516619, "author_profile": "https://Stackoverflow.com/users/17516619", "pm_score": 0, "selected": false, "text": "LoginPage loginPage = Application.OpenForms.OfType<LoginPage>().FirstOrDefault();\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17516619/" ]
74,535,405
<p>My method doesn't deliver the &quot;expect&quot; string that I expect to get from my input string. It should close the parenthesis after the list of words.</p> <pre><code>public static string Dostuff(string st) { String s = &quot;&quot;; String pattern = @&quot;[^($]&quot;; if (st.Contains(&quot;create view&quot;)) { s = st.Replace(&quot;create view&quot;, &quot;CSQL_CREATE_VIEW (&quot;); } if (s.Contains(&quot;CSQL_CREATE_VIEW (&quot;) /*&amp;&amp; Regex.IsMatch(st,pattern)*/ ) { s = s + &quot;)&quot;; } return s; } static void Main(string[] args) { //Test input = &quot;create view etwas.viewiges()&quot;; expect = &quot;CSQL_CREATE_VIEW ( etwas.viewiges)()&quot;; output = Dostuff(input); if (expect != output) throw new Exception(); } </code></pre>
[ { "answer_id": 74535576, "author": "frankM_DN", "author_id": 20034020, "author_profile": "https://Stackoverflow.com/users/20034020", "pm_score": -1, "selected": false, "text": "Program Application.Run(new Form1()); LoginPage Program public static LoginPage loginPage; Main static void Main()\n{\n loginPage = new LoginPage();\n Application.Run(loginPage);\n}\n loginPage Program.loginPage" }, { "answer_id": 74535862, "author": "JordanChester", "author_id": 17516619, "author_profile": "https://Stackoverflow.com/users/17516619", "pm_score": 0, "selected": false, "text": "LoginPage loginPage = Application.OpenForms.OfType<LoginPage>().FirstOrDefault();\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18659251/" ]
74,535,526
<p>So suppose I have a function in my code like this:</p> <pre><code>const getAccountName = account =&gt; `${account.name} ${account.lastName}`; </code></pre> <p>Now, in the function I'm not doing something like <code>${account?.name ?? ''}</code> because in this particular case I'm 100% sure that account will always have a <code>name</code> and <code>lastName</code>.</p> <p>Now in the unit test for the <code>getAccountName</code>, should I still test with an empty object, or without passing any arguments, etc?</p>
[ { "answer_id": 74535576, "author": "frankM_DN", "author_id": 20034020, "author_profile": "https://Stackoverflow.com/users/20034020", "pm_score": -1, "selected": false, "text": "Program Application.Run(new Form1()); LoginPage Program public static LoginPage loginPage; Main static void Main()\n{\n loginPage = new LoginPage();\n Application.Run(loginPage);\n}\n loginPage Program.loginPage" }, { "answer_id": 74535862, "author": "JordanChester", "author_id": 17516619, "author_profile": "https://Stackoverflow.com/users/17516619", "pm_score": 0, "selected": false, "text": "LoginPage loginPage = Application.OpenForms.OfType<LoginPage>().FirstOrDefault();\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3549177/" ]
74,535,597
<p>I've made a histogram for the different age groups in my data:</p> <pre><code>&gt; dput(Agedata[1:20,]) structure(list(samples = c(&quot;Pt1&quot;, &quot;Pt10&quot;, &quot;Pt101&quot;, &quot;Pt103&quot;, &quot;Pt106&quot;, &quot;Pt11&quot;, &quot;Pt17&quot;, &quot;Pt18&quot;, &quot;Pt2&quot;, &quot;Pt24&quot;, &quot;Pt26&quot;, &quot;Pt27&quot;, &quot;Pt28&quot;, &quot;Pt29&quot;, &quot;Pt3&quot;, &quot;Pt30&quot;, &quot;Pt31&quot;, &quot;Pt34&quot;, &quot;Pt36&quot;, &quot;Pt37&quot;), resp = c(&quot;NoResponse&quot;, &quot;NoResponse&quot;, &quot;Response&quot;, &quot;NoResponse&quot;, &quot;NoResponse&quot;, &quot;NoResponse&quot;, &quot;NoResponse&quot;, &quot;Response&quot;, &quot;NoResponse&quot;, &quot;NoResponse&quot;, &quot;NoResponse&quot;, &quot;NoResponse&quot;, &quot;NoResponse&quot;, &quot;NoResponse&quot;, &quot;Response&quot;, &quot;Response&quot;, &quot;NoResponse&quot;, &quot;Response&quot;, &quot;NoResponse&quot;, &quot;NoResponse&quot;), age = c(58, 53, 61, 57, 57, 62, 51, 59, 58, 60, 61, 49, 52, 57, 61, 61, 60, 56, 55, 61), age_group = structure(c(6L, 6L, 7L, 6L, 6L, 7L, 6L, 6L, 6L, 7L, 7L, 5L, 6L, 6L, 7L, 7L, 7L, 6L, 6L, 7L), levels = c(&quot;0-9&quot;, &quot;10-19&quot;, &quot;20-29&quot;, &quot;30-39&quot;, &quot;40-49&quot;, &quot;50-59&quot;, &quot;60-69&quot;, &quot;70-79&quot;, &quot;80-89&quot;, &quot;90-99&quot;), class = &quot;factor&quot;)), row.names = c(NA, 20L), class = &quot;data.frame&quot;) </code></pre> <p>Like this:</p> <pre><code>library(ggpubr) gghistogram(Agedata, x = &quot;age_group&quot;, bins = 8, rug = TRUE, color = &quot;resp&quot;, fill = &quot;resp&quot;, stat = 'count', palette = c(&quot;red&quot;, &quot;green&quot;), main = 'Age ~ Outcome') + ylim(c(0,500)) + theme_bw() </code></pre> <p><a href="https://i.stack.imgur.com/3QPPi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3QPPi.png" alt="enter image description here" /></a></p> <p>Now how do I add the count values on top of each bin? including the red bins and the green bins?</p>
[ { "answer_id": 74535752, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 3, "selected": true, "text": "geom_bar gghistogram gghistogram geom_text gghistogram ggplot(Agedata, aes(age_group, color = resp)) +\n geom_bar(aes(fill = after_scale(alpha(colour, 0.4)))) +\n geom_text(stat = 'count', position = position_stack(vjust = 1),\n vjust = -0.2,\n aes(label = after_stat(count), group = resp), color = 'black') +\n scale_color_manual(values = c('red2', 'green3')) +\n theme_bw()\n" }, { "answer_id": 74536437, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 2, "selected": false, "text": "library(tidyverse)\nAgedata %>% \n count(resp, age_group) %>% \n ggplot(aes(x = age_group,y = n, fill = resp, label = n)) +\n geom_col() +\n geom_text(size = 6, position = position_stack(vjust = 0.5))+\n scale_fill_manual(values = alpha(c(\"red\", \"green\"), 0.5)) +\n ylim(c(0,15)) +\n theme_bw()\n" }, { "answer_id": 74537525, "author": "Quinten", "author_id": 14282714, "author_profile": "https://Stackoverflow.com/users/14282714", "pm_score": 2, "selected": false, "text": "ggbarplot ggpubr n label = TRUE library(ggpubr)\nlibrary(dplyr)\n\ndata <- Agedata %>%\n group_by(age_group, resp) %>%\n summarise(n = n())\n#> `summarise()` has grouped output by 'age_group'. You can override using the\n#> `.groups` argument.\n\nggbarplot(data, \n x = \"age_group\", y = 'n', \n color = \"resp\", fill = \"resp\", \n palette = c(\"red\", \"green\"), \n main = 'Age ~ Outcome',\n label = TRUE) + \n ylim(c(0,12)) + \n theme_bw()\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17945841/" ]
74,535,599
<p>I have a class like this:</p> <pre><code>class ErrorMessages(object): &quot;&quot;&quot;a class that holds all error messages and then presents them to the user)&quot;&quot;&quot; messages= [] userStrMessages= &quot;&quot; def newError(self, Error): self.userStrMessages+= Error def __str__(self): if self.messages.count() != 0: i=0 for thing in self.messages: self.userStrMessages += self.messages[i] + &quot;\n&quot; i+=1 return self.userStrMessages </code></pre> <p>this doesn't work when I call on it like this and wants 2 input variables, but that is just self and what i put into it?:</p> <pre><code> ErrorMessages.newError(errormessage) </code></pre> <p>errormessage is a string</p> <p>i have a (what i think is) a static class? (new to this and learned in swedish which makes this harder) it looks like this</p> <pre><code>class EZSwitch(object): fileway= &quot;G:/Other computers/Stationär Dator/Files/Pyhton Program/Scheman&quot; fileway2= &quot;Kolmården.txt&quot; numberSchedules= 30 </code></pre> <p>I thought i could make my errormessagclass like this but it also does things with methods. Like adds things to the list messages on newError. It doesnt seem to be possible or how would I do this?</p>
[ { "answer_id": 74535655, "author": "John Carter", "author_id": 459082, "author_profile": "https://Stackoverflow.com/users/459082", "pm_score": -1, "selected": false, "text": "myMessage = ErrorMessage()\nmyMessage.newError(\"important error message\")\n" }, { "answer_id": 74535690, "author": "Adheesh", "author_id": 6499990, "author_profile": "https://Stackoverflow.com/users/6499990", "pm_score": -1, "selected": true, "text": "newError() @classmethod\ndef newError(self, Error): \n self.userStrMessages+= Error\n\nErrorMessages.newError(errormessage)\n err_object = ErrorMessage()\nerr_object.newError(errormessage)\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20148636/" ]
74,535,615
<p>I'm trying to figure why/how can I make the button text update before the &quot;each&quot; loop, so I can provide feedback to the users while it's running... but it only seems to update after the &quot;each&quot; has completed.</p> <p>In my example, the button will go &quot;Updating please wait...&quot; after the each has run. So if it take 10s, the button stay enable and with the text &quot;Update&quot; (original value). I want it to be disable and display &quot;Updating please wait ...&quot; while the Loop (each) is running.</p> <p>Got an idea why?</p> <pre><code> $(&quot;#UpdateRFID&quot;).click(function() { $('#UpdateRFID').prop(&quot;disabled&quot;, true).prop(&quot;value&quot;, &quot;Updating please wait...&quot;); UpdateRFID(); //$('#UpdateRFID').prop(&quot;disabled&quot;, false).prop(&quot;value&quot;, &quot;Update&quot;); }); function UpdateRFID() { $('.skurow[submitted=&quot;0&quot;]').each(function() { sku = $(this).attr('sku'); $.ajax({ url: 'class.action.php', type: 'post', async: false, dataType: 'JSON', data: { &quot;action&quot;: &quot;GetDataFromTagID&quot;, &quot;tagid&quot;: sku }, success: function(response) { console.log('ok'); }, error: function(response) { console.log(response.responseText); } }); }); } </code></pre> <p>Button :</p> <pre><code>&lt;input class=&quot;MenuButton&quot; name=&quot;UpdateRFID&quot; id=&quot;UpdateRFID&quot; value=&quot;Update&quot; type=&quot;button&quot; /&gt; </code></pre> <hr /> <p>Here's another test I did. In this Example, when I click the button, I get an alert &quot;Start&quot;, then it wait for about 3 secondes (sleep in the PHP Code for testing), then I get the alert &quot;Done&quot;, then the button is disable and change to &quot;Recherche ...&quot;. I'm not sure why... I want it to be disable before the &quot;each&quot; start.</p> <pre><code> function UpdateRFID() { $(&quot;#UpdateRFID&quot;).prop(&quot;disabled&quot;, true).prop(&quot;value&quot;, &quot;Recherche ...&quot;); alert(&quot;Start&quot;); $('.skurow[submitted=&quot;0&quot;]').each(function () { sku = $(this).attr(&quot;sku&quot;); $.ajax({ url: &quot;class.action.php&quot;, type: &quot;post&quot;, async: false, dataType: &quot;JSON&quot;, data: { action: &quot;GetDataFromTagID&quot;, tagid: sku, }, success: function (response) { console.log(&quot;ok&quot;); }, error: function (response) { console.log(response.responseText); }, }); }); alert(&quot;Done&quot;); //$('#UpdateRFID').prop(&quot;disabled&quot;, false).prop(&quot;value&quot;, &quot;Mise a jour nom RFID&quot;); } </code></pre> <hr /> <p>Here's the full code standalone code to reproduce the problem: jQuery is 2.2.1 PHP is 5.4 (but I don't think it's relevant)</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;script src=&quot;includes/jquery.min.js&quot;&gt;&lt;/script&gt; &lt;title&gt;Document&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;p class=&quot;ScanText&quot;&gt;SKU&lt;/p&gt; &lt;input class=&quot;FullSizeBox&quot; type=&quot;text&quot; id=&quot;SKU&quot; name=&quot;SKU&quot; onclick=&quot;BoxSelect(this.id);&quot; /&gt; &lt;script type=&quot;text/javascript&quot;&gt; $('#SKU').focus(); &lt;/script&gt; &lt;br&gt;&lt;input class=&quot;MenuButton&quot; name=&quot;UpdateRFID&quot; id=&quot;UpdateRFID&quot; value=&quot;Mise a jour nom RFID&quot; type=&quot;button&quot; /&gt; &lt;div id=&quot;qtsku&quot; style=&quot;margin-left:5px&quot;&gt;-&lt;/div&gt; &lt;div id=&quot;divSKUScanned&quot;&gt; &lt;table id=&quot;ScannedSKU&quot;&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;&lt;/th&gt; &lt;th&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;!-- updated by JavaScript --&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;div class=&quot;ScanSubmit&quot;&gt;&lt;input class=&quot;MenuButton&quot; id=&quot;btnsubmit&quot; type=&quot;button&quot; value=&quot;Soumettre&quot; onclick=&quot;SubmitVE();&quot; disabled&gt;&lt;/div&gt; &lt;script&gt; function SkuCount() { skucount = $('#ScannedSKU tr').length - 1; stritem = 'item'; if (skucount &gt; 1) { stritem = 'items'; } $('#qtsku').html('Total ' + stritem + ': ' + skucount); if (skucount == 0) { $('#qtsku').html(''); } } SkuCount(); $(document.body).on('click', '.delButton', function() { sku = $(this).closest(&quot;tr&quot;).find('.skudesc').text(); r = confirm('Effacer ' + sku + ' ?'); if (r == true) { $(this).closest(&quot;tr&quot;).remove(); } SkuCount(); $('#SKU').focus(); //TODO: That Focus dosent work... }); $('#SKU').keypress(function(event) { keycode = (event.keyCode ? event.keyCode : event.which); if (keycode == '13') { sku = this.value; sku.trim(); this.value = &quot;&quot;; if (sku != &quot;&quot;) { if (!($('.skurow[sku=&quot;' + sku + '&quot;').length)) { delBtn = '&lt;input name=&quot;delButton&quot; id=&quot;delButton&quot; class=&quot;delButton&quot; type=&quot;button&quot; value=&quot;X&quot; style=&quot;background-color:gray; color:black&quot;&gt;'; $('#ScannedSKU &gt; tbody:last-child').append('&lt;tr class=&quot;skurow&quot; submitted=&quot;0&quot; sku=&quot;' + sku + '&quot;&gt;&lt;td class=&quot;delbtn&quot;&gt;' + delBtn + '&lt;/td&gt;&lt;td class=&quot;skudesc&quot;&gt;' + sku + '&lt;/td&gt;&lt;/tr&gt;'); $(&quot;#btnsubmit&quot;).prop(&quot;disabled&quot;, true); SkuCount(); } } } }); $(&quot;#UpdateRFID&quot;).click(function() { UpdateRFID(); }); function UpdateRFID() { $('#UpdateRFID').prop(&quot;disabled&quot;, true).prop(&quot;value&quot;, &quot;Recherche ...&quot;); alert('Start'); $('.skurow[submitted=&quot;0&quot;]').each(function() { sku = $(this).attr('sku'); $.ajax({ url: 'class.action.php', type: 'post', async: false, dataType: 'JSON', data: { &quot;action&quot;: &quot;GetDataFromTagID&quot;, &quot;tagid&quot;: sku }, success: function(response) { console.log('ok'); }, error: function(response) { console.log(response.responseText); } }); }); alert('Done'); //$('#UpdateRFID').prop(&quot;disabled&quot;, false).prop(&quot;value&quot;, &quot;Mise a jour nom RFID&quot;); } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>and this is the php page section for class.action.php</p> <pre><code>&lt;?php if ($_POST[&quot;action&quot;] == &quot;GetDataFromTagID&quot;) { sleep(3); } ?&gt; </code></pre>
[ { "answer_id": 74537998, "author": "nka", "author_id": 10946618, "author_profile": "https://Stackoverflow.com/users/10946618", "pm_score": 0, "selected": false, "text": " $(\"#UpdateRFID\").click(function() {\n $('#UpdateRFID').prop(\"disabled\", true).prop(\"value\", \"Recherche ...\");\n setTimeout(UpdateRFID, 100);\n });\n setTimeout(UpdateRFID(), 100);" }, { "answer_id": 74540162, "author": "Mark Schultheiss", "author_id": 125981, "author_profile": "https://Stackoverflow.com/users/125981", "pm_score": 1, "selected": false, "text": "Promise UpdateRFID onclick=\"BoxSelect(this.id);\" $('#SKU').on('click',function(){BoxSelect(this.id);}); $('#SKU').focus();\n\nfunction SkuCount() {\n let skucount = $('#ScannedSKU').find('.skurow').length - 1;\n let stritem = 'item' + !!skucount ? 's' : '';\n let updateText = skucount == 0 ? '' : 'Total ' + stritem + ': ' + skucount;\n $('#qtsku').html(updateText);\n}\n\n$('#ScannedSKU').on('click', '.delButton', function() {\n let sku = $(this).closest(\"tr\").find('.skudesc').text();\n let r = confirm('Effacer ' + sku + ' ?');\n if (!!r) {\n $(this).closest(\"tr\").remove();\n }\n SkuCount();\n $('#SKU').focus();\n});\n\n$(document.body).on('keypress', function(event) {\n let keycode = event.keyCode ? event.keyCode : event.which;\n if (keycode == '13') {\n const skuContainer = $('#ScannedSKU').find('.sku-container');\n const skuList = skuContainer.find('.skurow');\n let sku = this.value.trim(); //?????\n this.value = \"\";\n if (!!sku && !skuList.filter('[data-sku=\"' + sku + '\"]').length) {\n let newtr = $('#newrows').find('.skurow').first().clone();\n newtr.data('sku', sku);\n newtr.find('skudesc').html(skudesc);\n skuContainer.append(newtr);\n $(\"#btnsubmit\").prop(\"disabled\", true);\n SkuCount();\n }\n }\n});\n\nfunction UpdateRFID() {\n $('#UpdateRFID').trigger(\"disable-me\");\n alert('Start');\n const myPromise = new Promise((resolve, reject) => {\n $('.skurow[submitted=\"0\"]')\n .each(function() {\n let sku = $(this).data('sku');\n const skuData = {\n \"action\": \"GetDataFromTagID\",\n \"tagid\": sku\n };\n $.ajax({\n url: 'class.action.php',\n type: 'post',\n dataType: 'JSON',\n data: skuData\n })\n .done(function(response) {\n console.log('ok');\n })\n .fail(function(response) {\n console.log(response.responseText);\n });\n });\n resolve(\"looperdone\");\n });\n\n myPromise\n .then(function() {\n alert('Done');\n })\n .then(function() {\n $('#UpdateRFID').trigger(\"enable-me\");\n });\n}\n\n// this was missing so this is just an empty function\nfunction SubmitVE() {}\n$('#btnsubmit').on('click', SubmitVE);\n\n$(\"#UpdateRFID\")\n .on('click', UpdateRFID)\n .on('enable-me', function() {\n $(this).prop(\"disabled\", false).prop(\"value\", \"Mise a jour nom RFID\");\n }).on('disable-me', function() {\n $(this).prop(\"disabled\", true).prop(\"value\", \"Recherche ...\");\n });\n\nSkuCount(); .delButton {\n background-color: gray;\n color: black;\n}\n\n.element-container {\n display: none;\n} <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<p class=\"ScanText\">SKU</p>\n<input class=\"FullSizeBox\" type=\"text\" id=\"SKU\" name=\"SKU\" />\n<input class=\"MenuButton\" name=\"UpdateRFID\" id=\"UpdateRFID\" value=\"Mise a jour nom RFID\" type=\"button\" />\n<div id=\"qtsku\" style=\"margin-left:5px\">-</div>\n<div id=\"divSKUScanned\">\n <table id=\"ScannedSKU\">\n <thead>\n <tr>\n <th></th>\n <th></th>\n </tr>\n </thead>\n <tbody class='sku-container'>\n <!-- updated by JavaScript -->\n </tbody>\n </table>\n</div>\n<div class=\"ScanSubmit\"><input class=\"MenuButton\" id=\"btnsubmit\" type=\"button\" value=\"Soumettre\" disabled></div>\n\n<div class=\"element-container\">\n <table id=\"newrows\">\n <tbody>\n <tr class=\"skurow\" submitted=\"0\" sku=\"\">\n <td class=\"delbtn\"><button name=\"delButton\" class=\"delButton\" type=\"button\">X</button></td>\n <td class=\"skudesc\"></td>\n </tr>\n <tbody>\n </table>\n</div>" }, { "answer_id": 74549974, "author": "nka", "author_id": 10946618, "author_profile": "https://Stackoverflow.com/users/10946618", "pm_score": 1, "selected": true, "text": "$.when async: false function UpdateRFID() {\n $('#UpdateRFID').trigger(\"disable-me\");\n\n const UpdateRFIDajaxes = [];\n\n $('.skurow[submitted=\"0\"]')\n .each(function() {\n sku = $(this).attr('sku');\n const skuData = {\n \"action\": \"GetDataFromTagID\",\n \"tagid\": sku\n };\n UpdateRFIDajaxes.push(\n $.ajax({\n url: 'class.action.php',\n type: 'post',\n dataType: 'JSON',\n data: skuData\n })\n .done(function(response) {\n //do ok stuff.\n console.log('ok')\n })\n .fail(function(response) {\n //do failed stuff.\n console.log('failed');\n })\n );\n });\n $.when.apply($, UpdateRFIDajaxes)\n .always(function() {\n $('#UpdateRFID').trigger(\"enable-me\");\n EnableSubmit();\n $('#SKU').focus();\n }).done(function() {\n //console.log('Done.');\n })\n .fail(function() {\n alert('Erreur, ca ne fonctionne pas, etes vous sur le WiFi?');\n });\n }\n\n\n $(\"#UpdateRFID\")\n .on('click', function() {\n UpdateRFID();\n })\n .on('enable-me', function() {\n $(this).prop(\"disabled\", false).prop(\"value\", \"Mise a jour nom RFID\");\n }).on('disable-me', function() {\n $(this).prop(\"disabled\", true).prop(\"value\", \"Recherche ...\");\n });\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10946618/" ]
74,535,625
<p>Help please! I have installed for view class permission_class which allow GET-requests, but when i send GET-request i get messege: GET method is not allowed</p> <p>i have <strong>views.py</strong> file:</p> <pre><code>class WomenAPIList(generics.ListCreateAPIView): queryset = Women.objects.all() serializer_class = WomenSerializer permission_classes = (IsAuthenticatedOrReadOnly, ) class WomenAPIUpdate(generics.UpdateAPIView): queryset = Women.objects.all() serializer_class = WomenSerializer permission_classes = (IsAuthenticated, ) # authentication_classes = (TokenAuthentication, ) class WomenAPIDestroy(generics.RetrieveDestroyAPIView): queryset = Women.objects.all() serializer_class = WomenSerializer permission_classes = (IsAdminOrReadOnly, ) </code></pre> <p>In <strong>views.py</strong> file i use basic integrated <strong>IsAuthenticated</strong> class for <strong>WomenAPIUpdate</strong>:</p> <pre><code>class WomenAPIUpdate(generics.UpdateAPIView): queryset = Women.objects.all() serializer_class = WomenSerializer permission_classes = (IsAuthenticated, ) # authentication_classes = (TokenAuthentication, ) </code></pre> <p>My <strong>urls.py</strong> file looks like:</p> <pre><code>urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/drf-auth/', include('rest_framework.urls')), path('api/v1/women/', WomenAPIList.as_view()), path('api/v1/women/&lt;int:pk&gt;/', WomenAPIUpdate.as_view()), path('api/v1/womendelete/&lt;int:pk&gt;/', WomenAPIDestroy.as_view()), path('api/v1/auth/', include('djoser.urls')), re_path(r'^auth/', include('djoser.urls.authtoken')), path('api/v1/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/v1/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/v1/token/verify/', TokenVerifyView.as_view(), name='token_verify'), ] </code></pre> <p>And for <strong>WomenAPIUpdate</strong> class i have installed next url:</p> <pre><code>path('api/v1/women/&lt;int:pk&gt;/', WomenAPIUpdate.as_view()), </code></pre> <p>But when i make GET-request to this url i get messege: <strong>&quot;GET method is not allowed&quot;</strong> (i get same messege during using Postaman and Browser).</p> <p>Here is my <strong>models.py</strong> file:</p> <pre><code>class Women(models.Model): title = models.CharField(max_length=255) content = models.TextField(blank=True) time_create = models.DateTimeField(auto_now_add=True) time_update = models.DateTimeField(auto_now=True) is_published = models.BooleanField(default=True) cat_id = models.ForeignKey('Category', on_delete=models.PROTECT, null=True) car_id = models.BooleanField(default=True) user = models.ForeignKey(User, verbose_name='Пользователь', on_delete=models.CASCADE) def __str__(self): return self.title class Category(models.Model): name = models.CharField(max_length=100, db_index=True) def __str__(self): return self.name </code></pre> <p>I tried create own permission classes where i allowed GET method during using integrated tuple <strong>SAFE_METHODS</strong> and installed them to <strong>WomenAPIUpdate class</strong>, but it did'nt work:</p> <pre><code>class IsAdminOrReadOnly(BasePermission): def has_permission(self, request, view): if request.method in permissions.SAFE_METHODS: return True return bool(request.user and request.user.is_staff) class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.user == request.user </code></pre> <p><strong>SAFE_METHOD</strong> tuple:</p> <pre><code>SAFE_METHODS = ('GET', 'HEAD', 'OPTIONS') </code></pre> <p>It worrked until i created Authentication settings and instelled them in <strong>settings.py</strong> file:</p> <pre><code>REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ] } </code></pre>
[ { "answer_id": 74537998, "author": "nka", "author_id": 10946618, "author_profile": "https://Stackoverflow.com/users/10946618", "pm_score": 0, "selected": false, "text": " $(\"#UpdateRFID\").click(function() {\n $('#UpdateRFID').prop(\"disabled\", true).prop(\"value\", \"Recherche ...\");\n setTimeout(UpdateRFID, 100);\n });\n setTimeout(UpdateRFID(), 100);" }, { "answer_id": 74540162, "author": "Mark Schultheiss", "author_id": 125981, "author_profile": "https://Stackoverflow.com/users/125981", "pm_score": 1, "selected": false, "text": "Promise UpdateRFID onclick=\"BoxSelect(this.id);\" $('#SKU').on('click',function(){BoxSelect(this.id);}); $('#SKU').focus();\n\nfunction SkuCount() {\n let skucount = $('#ScannedSKU').find('.skurow').length - 1;\n let stritem = 'item' + !!skucount ? 's' : '';\n let updateText = skucount == 0 ? '' : 'Total ' + stritem + ': ' + skucount;\n $('#qtsku').html(updateText);\n}\n\n$('#ScannedSKU').on('click', '.delButton', function() {\n let sku = $(this).closest(\"tr\").find('.skudesc').text();\n let r = confirm('Effacer ' + sku + ' ?');\n if (!!r) {\n $(this).closest(\"tr\").remove();\n }\n SkuCount();\n $('#SKU').focus();\n});\n\n$(document.body).on('keypress', function(event) {\n let keycode = event.keyCode ? event.keyCode : event.which;\n if (keycode == '13') {\n const skuContainer = $('#ScannedSKU').find('.sku-container');\n const skuList = skuContainer.find('.skurow');\n let sku = this.value.trim(); //?????\n this.value = \"\";\n if (!!sku && !skuList.filter('[data-sku=\"' + sku + '\"]').length) {\n let newtr = $('#newrows').find('.skurow').first().clone();\n newtr.data('sku', sku);\n newtr.find('skudesc').html(skudesc);\n skuContainer.append(newtr);\n $(\"#btnsubmit\").prop(\"disabled\", true);\n SkuCount();\n }\n }\n});\n\nfunction UpdateRFID() {\n $('#UpdateRFID').trigger(\"disable-me\");\n alert('Start');\n const myPromise = new Promise((resolve, reject) => {\n $('.skurow[submitted=\"0\"]')\n .each(function() {\n let sku = $(this).data('sku');\n const skuData = {\n \"action\": \"GetDataFromTagID\",\n \"tagid\": sku\n };\n $.ajax({\n url: 'class.action.php',\n type: 'post',\n dataType: 'JSON',\n data: skuData\n })\n .done(function(response) {\n console.log('ok');\n })\n .fail(function(response) {\n console.log(response.responseText);\n });\n });\n resolve(\"looperdone\");\n });\n\n myPromise\n .then(function() {\n alert('Done');\n })\n .then(function() {\n $('#UpdateRFID').trigger(\"enable-me\");\n });\n}\n\n// this was missing so this is just an empty function\nfunction SubmitVE() {}\n$('#btnsubmit').on('click', SubmitVE);\n\n$(\"#UpdateRFID\")\n .on('click', UpdateRFID)\n .on('enable-me', function() {\n $(this).prop(\"disabled\", false).prop(\"value\", \"Mise a jour nom RFID\");\n }).on('disable-me', function() {\n $(this).prop(\"disabled\", true).prop(\"value\", \"Recherche ...\");\n });\n\nSkuCount(); .delButton {\n background-color: gray;\n color: black;\n}\n\n.element-container {\n display: none;\n} <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<p class=\"ScanText\">SKU</p>\n<input class=\"FullSizeBox\" type=\"text\" id=\"SKU\" name=\"SKU\" />\n<input class=\"MenuButton\" name=\"UpdateRFID\" id=\"UpdateRFID\" value=\"Mise a jour nom RFID\" type=\"button\" />\n<div id=\"qtsku\" style=\"margin-left:5px\">-</div>\n<div id=\"divSKUScanned\">\n <table id=\"ScannedSKU\">\n <thead>\n <tr>\n <th></th>\n <th></th>\n </tr>\n </thead>\n <tbody class='sku-container'>\n <!-- updated by JavaScript -->\n </tbody>\n </table>\n</div>\n<div class=\"ScanSubmit\"><input class=\"MenuButton\" id=\"btnsubmit\" type=\"button\" value=\"Soumettre\" disabled></div>\n\n<div class=\"element-container\">\n <table id=\"newrows\">\n <tbody>\n <tr class=\"skurow\" submitted=\"0\" sku=\"\">\n <td class=\"delbtn\"><button name=\"delButton\" class=\"delButton\" type=\"button\">X</button></td>\n <td class=\"skudesc\"></td>\n </tr>\n <tbody>\n </table>\n</div>" }, { "answer_id": 74549974, "author": "nka", "author_id": 10946618, "author_profile": "https://Stackoverflow.com/users/10946618", "pm_score": 1, "selected": true, "text": "$.when async: false function UpdateRFID() {\n $('#UpdateRFID').trigger(\"disable-me\");\n\n const UpdateRFIDajaxes = [];\n\n $('.skurow[submitted=\"0\"]')\n .each(function() {\n sku = $(this).attr('sku');\n const skuData = {\n \"action\": \"GetDataFromTagID\",\n \"tagid\": sku\n };\n UpdateRFIDajaxes.push(\n $.ajax({\n url: 'class.action.php',\n type: 'post',\n dataType: 'JSON',\n data: skuData\n })\n .done(function(response) {\n //do ok stuff.\n console.log('ok')\n })\n .fail(function(response) {\n //do failed stuff.\n console.log('failed');\n })\n );\n });\n $.when.apply($, UpdateRFIDajaxes)\n .always(function() {\n $('#UpdateRFID').trigger(\"enable-me\");\n EnableSubmit();\n $('#SKU').focus();\n }).done(function() {\n //console.log('Done.');\n })\n .fail(function() {\n alert('Erreur, ca ne fonctionne pas, etes vous sur le WiFi?');\n });\n }\n\n\n $(\"#UpdateRFID\")\n .on('click', function() {\n UpdateRFID();\n })\n .on('enable-me', function() {\n $(this).prop(\"disabled\", false).prop(\"value\", \"Mise a jour nom RFID\");\n }).on('disable-me', function() {\n $(this).prop(\"disabled\", true).prop(\"value\", \"Recherche ...\");\n });\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20461872/" ]
74,535,646
<p>I want to randomize the popping of the list of the baby variable, but it's only popping the baby[1].</p> <pre><code>&lt;body&gt; &lt;h1 id=&quot;1&quot;&gt;bebe&lt;/h1&gt; &lt;h1 id=&quot;2&quot;&gt;tae&lt;/h1&gt; &lt;script&gt; var baby = [document.getElementById('1').innerText, document.getElementById('2').innerText] bot = Math.floor(Math.random() * baby.length) if (bot == 0) { baby.pop(0) } if (bot == 1) { baby.pop(1) } console.log(baby) &lt;/script&gt; &lt;/body&gt; </code></pre>
[ { "answer_id": 74537998, "author": "nka", "author_id": 10946618, "author_profile": "https://Stackoverflow.com/users/10946618", "pm_score": 0, "selected": false, "text": " $(\"#UpdateRFID\").click(function() {\n $('#UpdateRFID').prop(\"disabled\", true).prop(\"value\", \"Recherche ...\");\n setTimeout(UpdateRFID, 100);\n });\n setTimeout(UpdateRFID(), 100);" }, { "answer_id": 74540162, "author": "Mark Schultheiss", "author_id": 125981, "author_profile": "https://Stackoverflow.com/users/125981", "pm_score": 1, "selected": false, "text": "Promise UpdateRFID onclick=\"BoxSelect(this.id);\" $('#SKU').on('click',function(){BoxSelect(this.id);}); $('#SKU').focus();\n\nfunction SkuCount() {\n let skucount = $('#ScannedSKU').find('.skurow').length - 1;\n let stritem = 'item' + !!skucount ? 's' : '';\n let updateText = skucount == 0 ? '' : 'Total ' + stritem + ': ' + skucount;\n $('#qtsku').html(updateText);\n}\n\n$('#ScannedSKU').on('click', '.delButton', function() {\n let sku = $(this).closest(\"tr\").find('.skudesc').text();\n let r = confirm('Effacer ' + sku + ' ?');\n if (!!r) {\n $(this).closest(\"tr\").remove();\n }\n SkuCount();\n $('#SKU').focus();\n});\n\n$(document.body).on('keypress', function(event) {\n let keycode = event.keyCode ? event.keyCode : event.which;\n if (keycode == '13') {\n const skuContainer = $('#ScannedSKU').find('.sku-container');\n const skuList = skuContainer.find('.skurow');\n let sku = this.value.trim(); //?????\n this.value = \"\";\n if (!!sku && !skuList.filter('[data-sku=\"' + sku + '\"]').length) {\n let newtr = $('#newrows').find('.skurow').first().clone();\n newtr.data('sku', sku);\n newtr.find('skudesc').html(skudesc);\n skuContainer.append(newtr);\n $(\"#btnsubmit\").prop(\"disabled\", true);\n SkuCount();\n }\n }\n});\n\nfunction UpdateRFID() {\n $('#UpdateRFID').trigger(\"disable-me\");\n alert('Start');\n const myPromise = new Promise((resolve, reject) => {\n $('.skurow[submitted=\"0\"]')\n .each(function() {\n let sku = $(this).data('sku');\n const skuData = {\n \"action\": \"GetDataFromTagID\",\n \"tagid\": sku\n };\n $.ajax({\n url: 'class.action.php',\n type: 'post',\n dataType: 'JSON',\n data: skuData\n })\n .done(function(response) {\n console.log('ok');\n })\n .fail(function(response) {\n console.log(response.responseText);\n });\n });\n resolve(\"looperdone\");\n });\n\n myPromise\n .then(function() {\n alert('Done');\n })\n .then(function() {\n $('#UpdateRFID').trigger(\"enable-me\");\n });\n}\n\n// this was missing so this is just an empty function\nfunction SubmitVE() {}\n$('#btnsubmit').on('click', SubmitVE);\n\n$(\"#UpdateRFID\")\n .on('click', UpdateRFID)\n .on('enable-me', function() {\n $(this).prop(\"disabled\", false).prop(\"value\", \"Mise a jour nom RFID\");\n }).on('disable-me', function() {\n $(this).prop(\"disabled\", true).prop(\"value\", \"Recherche ...\");\n });\n\nSkuCount(); .delButton {\n background-color: gray;\n color: black;\n}\n\n.element-container {\n display: none;\n} <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<p class=\"ScanText\">SKU</p>\n<input class=\"FullSizeBox\" type=\"text\" id=\"SKU\" name=\"SKU\" />\n<input class=\"MenuButton\" name=\"UpdateRFID\" id=\"UpdateRFID\" value=\"Mise a jour nom RFID\" type=\"button\" />\n<div id=\"qtsku\" style=\"margin-left:5px\">-</div>\n<div id=\"divSKUScanned\">\n <table id=\"ScannedSKU\">\n <thead>\n <tr>\n <th></th>\n <th></th>\n </tr>\n </thead>\n <tbody class='sku-container'>\n <!-- updated by JavaScript -->\n </tbody>\n </table>\n</div>\n<div class=\"ScanSubmit\"><input class=\"MenuButton\" id=\"btnsubmit\" type=\"button\" value=\"Soumettre\" disabled></div>\n\n<div class=\"element-container\">\n <table id=\"newrows\">\n <tbody>\n <tr class=\"skurow\" submitted=\"0\" sku=\"\">\n <td class=\"delbtn\"><button name=\"delButton\" class=\"delButton\" type=\"button\">X</button></td>\n <td class=\"skudesc\"></td>\n </tr>\n <tbody>\n </table>\n</div>" }, { "answer_id": 74549974, "author": "nka", "author_id": 10946618, "author_profile": "https://Stackoverflow.com/users/10946618", "pm_score": 1, "selected": true, "text": "$.when async: false function UpdateRFID() {\n $('#UpdateRFID').trigger(\"disable-me\");\n\n const UpdateRFIDajaxes = [];\n\n $('.skurow[submitted=\"0\"]')\n .each(function() {\n sku = $(this).attr('sku');\n const skuData = {\n \"action\": \"GetDataFromTagID\",\n \"tagid\": sku\n };\n UpdateRFIDajaxes.push(\n $.ajax({\n url: 'class.action.php',\n type: 'post',\n dataType: 'JSON',\n data: skuData\n })\n .done(function(response) {\n //do ok stuff.\n console.log('ok')\n })\n .fail(function(response) {\n //do failed stuff.\n console.log('failed');\n })\n );\n });\n $.when.apply($, UpdateRFIDajaxes)\n .always(function() {\n $('#UpdateRFID').trigger(\"enable-me\");\n EnableSubmit();\n $('#SKU').focus();\n }).done(function() {\n //console.log('Done.');\n })\n .fail(function() {\n alert('Erreur, ca ne fonctionne pas, etes vous sur le WiFi?');\n });\n }\n\n\n $(\"#UpdateRFID\")\n .on('click', function() {\n UpdateRFID();\n })\n .on('enable-me', function() {\n $(this).prop(\"disabled\", false).prop(\"value\", \"Mise a jour nom RFID\");\n }).on('disable-me', function() {\n $(this).prop(\"disabled\", true).prop(\"value\", \"Recherche ...\");\n });\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17085102/" ]
74,535,682
<p>i have this problem programming in Next.js 13. I really appreciate any help or suggestion =), here are the files:</p> <h1>typingtext.tsx</h1> <pre><code>import React from &quot;react&quot;; export function useTypedText(text: string, speed: number, delayTime?: number) { const [textState, setTextState] = React.useState(&quot;&quot;) const chars = text.split(&quot;&quot;) let interval = speed if(textState.length === 0 &amp;&amp; delayTime) interval = speed + delayTime React.useEffect(() =&gt; { const timer = setTimeout(() =&gt; { setTextState((prevText) =&gt; { if (prevText.length !== chars.length) { const newText = prevText.concat(chars[prevText.length]) return newText } return prevText }) }, interval) return () =&gt; clearTimeout(timer) }) return textState } </code></pre> <h1>mainheader.tsx:</h1> <pre><code>import React from 'react'; import { useTypedText } from '../typingtext'; export function VMainHeader() { return ( &lt;div&gt; &lt;h1&gt; {useTypedText(&quot;Hello everyone!&quot;, 50)} &lt;br/&gt; {useTypedText(&quot;I'm Diego.&quot;, 50, 200)} &lt;/h1&gt; &lt;h2&gt; {useTypedText(&quot;Welcome&quot;, 30, 350)} &lt;/h2&gt; &lt;/div&gt; ) } </code></pre> <h1>home.tsx</h1> <pre><code>import React from &quot;react&quot; import { VMainHeader } from &quot;./mainheader&quot; export default function VHome(){ return( &lt;div&gt; &lt;VMainHeader /&gt; &lt;/div&gt; ) } </code></pre> <p>Im expecting know what happening, because i already try with</p> <pre><code>import { useState, useEffect } from &quot;react&quot;; </code></pre> <p>in the typingtext.tsx file but it doesn't work</p>
[ { "answer_id": 74537998, "author": "nka", "author_id": 10946618, "author_profile": "https://Stackoverflow.com/users/10946618", "pm_score": 0, "selected": false, "text": " $(\"#UpdateRFID\").click(function() {\n $('#UpdateRFID').prop(\"disabled\", true).prop(\"value\", \"Recherche ...\");\n setTimeout(UpdateRFID, 100);\n });\n setTimeout(UpdateRFID(), 100);" }, { "answer_id": 74540162, "author": "Mark Schultheiss", "author_id": 125981, "author_profile": "https://Stackoverflow.com/users/125981", "pm_score": 1, "selected": false, "text": "Promise UpdateRFID onclick=\"BoxSelect(this.id);\" $('#SKU').on('click',function(){BoxSelect(this.id);}); $('#SKU').focus();\n\nfunction SkuCount() {\n let skucount = $('#ScannedSKU').find('.skurow').length - 1;\n let stritem = 'item' + !!skucount ? 's' : '';\n let updateText = skucount == 0 ? '' : 'Total ' + stritem + ': ' + skucount;\n $('#qtsku').html(updateText);\n}\n\n$('#ScannedSKU').on('click', '.delButton', function() {\n let sku = $(this).closest(\"tr\").find('.skudesc').text();\n let r = confirm('Effacer ' + sku + ' ?');\n if (!!r) {\n $(this).closest(\"tr\").remove();\n }\n SkuCount();\n $('#SKU').focus();\n});\n\n$(document.body).on('keypress', function(event) {\n let keycode = event.keyCode ? event.keyCode : event.which;\n if (keycode == '13') {\n const skuContainer = $('#ScannedSKU').find('.sku-container');\n const skuList = skuContainer.find('.skurow');\n let sku = this.value.trim(); //?????\n this.value = \"\";\n if (!!sku && !skuList.filter('[data-sku=\"' + sku + '\"]').length) {\n let newtr = $('#newrows').find('.skurow').first().clone();\n newtr.data('sku', sku);\n newtr.find('skudesc').html(skudesc);\n skuContainer.append(newtr);\n $(\"#btnsubmit\").prop(\"disabled\", true);\n SkuCount();\n }\n }\n});\n\nfunction UpdateRFID() {\n $('#UpdateRFID').trigger(\"disable-me\");\n alert('Start');\n const myPromise = new Promise((resolve, reject) => {\n $('.skurow[submitted=\"0\"]')\n .each(function() {\n let sku = $(this).data('sku');\n const skuData = {\n \"action\": \"GetDataFromTagID\",\n \"tagid\": sku\n };\n $.ajax({\n url: 'class.action.php',\n type: 'post',\n dataType: 'JSON',\n data: skuData\n })\n .done(function(response) {\n console.log('ok');\n })\n .fail(function(response) {\n console.log(response.responseText);\n });\n });\n resolve(\"looperdone\");\n });\n\n myPromise\n .then(function() {\n alert('Done');\n })\n .then(function() {\n $('#UpdateRFID').trigger(\"enable-me\");\n });\n}\n\n// this was missing so this is just an empty function\nfunction SubmitVE() {}\n$('#btnsubmit').on('click', SubmitVE);\n\n$(\"#UpdateRFID\")\n .on('click', UpdateRFID)\n .on('enable-me', function() {\n $(this).prop(\"disabled\", false).prop(\"value\", \"Mise a jour nom RFID\");\n }).on('disable-me', function() {\n $(this).prop(\"disabled\", true).prop(\"value\", \"Recherche ...\");\n });\n\nSkuCount(); .delButton {\n background-color: gray;\n color: black;\n}\n\n.element-container {\n display: none;\n} <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<p class=\"ScanText\">SKU</p>\n<input class=\"FullSizeBox\" type=\"text\" id=\"SKU\" name=\"SKU\" />\n<input class=\"MenuButton\" name=\"UpdateRFID\" id=\"UpdateRFID\" value=\"Mise a jour nom RFID\" type=\"button\" />\n<div id=\"qtsku\" style=\"margin-left:5px\">-</div>\n<div id=\"divSKUScanned\">\n <table id=\"ScannedSKU\">\n <thead>\n <tr>\n <th></th>\n <th></th>\n </tr>\n </thead>\n <tbody class='sku-container'>\n <!-- updated by JavaScript -->\n </tbody>\n </table>\n</div>\n<div class=\"ScanSubmit\"><input class=\"MenuButton\" id=\"btnsubmit\" type=\"button\" value=\"Soumettre\" disabled></div>\n\n<div class=\"element-container\">\n <table id=\"newrows\">\n <tbody>\n <tr class=\"skurow\" submitted=\"0\" sku=\"\">\n <td class=\"delbtn\"><button name=\"delButton\" class=\"delButton\" type=\"button\">X</button></td>\n <td class=\"skudesc\"></td>\n </tr>\n <tbody>\n </table>\n</div>" }, { "answer_id": 74549974, "author": "nka", "author_id": 10946618, "author_profile": "https://Stackoverflow.com/users/10946618", "pm_score": 1, "selected": true, "text": "$.when async: false function UpdateRFID() {\n $('#UpdateRFID').trigger(\"disable-me\");\n\n const UpdateRFIDajaxes = [];\n\n $('.skurow[submitted=\"0\"]')\n .each(function() {\n sku = $(this).attr('sku');\n const skuData = {\n \"action\": \"GetDataFromTagID\",\n \"tagid\": sku\n };\n UpdateRFIDajaxes.push(\n $.ajax({\n url: 'class.action.php',\n type: 'post',\n dataType: 'JSON',\n data: skuData\n })\n .done(function(response) {\n //do ok stuff.\n console.log('ok')\n })\n .fail(function(response) {\n //do failed stuff.\n console.log('failed');\n })\n );\n });\n $.when.apply($, UpdateRFIDajaxes)\n .always(function() {\n $('#UpdateRFID').trigger(\"enable-me\");\n EnableSubmit();\n $('#SKU').focus();\n }).done(function() {\n //console.log('Done.');\n })\n .fail(function() {\n alert('Erreur, ca ne fonctionne pas, etes vous sur le WiFi?');\n });\n }\n\n\n $(\"#UpdateRFID\")\n .on('click', function() {\n UpdateRFID();\n })\n .on('enable-me', function() {\n $(this).prop(\"disabled\", false).prop(\"value\", \"Mise a jour nom RFID\");\n }).on('disable-me', function() {\n $(this).prop(\"disabled\", true).prop(\"value\", \"Recherche ...\");\n });\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17903717/" ]
74,535,707
<p>I am getting the following errors in Intellij whilst trying to connect to a H2 database.</p> <p><code>Hibernate: create table user (id bigint not null, email varchar(255), name varchar(255), primary key (id))</code></p> <p><code>2022-11-22 15:53:11.743 WARN 13376 --- [ main] o.h.t.s.i.ExceptionHandlerLoggedImpl : GenerationTarget encountered exception accepting command : Error executing DDL &quot;create table user (id bigint not null, email varchar(255), name varchar(255), primary key (id))&quot; via JDBC Statement</code></p> <p><code>org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL &quot;create table user (id bigint not null, email varchar(255), name varchar(255), primary key (id))&quot; via JDBC Statement</code></p> <p><code>Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Syntax error in SQL statement &quot;create table [*]user (id bigint not null, email varchar(255), name varchar(255), primary key (id))&quot;; expected &quot;identifier&quot;; SQL statement:</code></p> <p><code>create table user (id bigint not null, email varchar(255), name varchar(255), primary key (id)) [42001-214]</code></p> <p><code>could not prepare statement; SQL [insert into user (email, name, id) values (?, ?, ?)]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement</code></p> <p>My Code:</p> <p>Application.java</p> <pre><code>@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean CommandLineRunner init(UserRepository userRepository) { return args -&gt; { Stream.of(&quot;John&quot;, &quot;Julie&quot;, &quot;Jennifer&quot;, &quot;Helen&quot;, &quot;Rachel&quot;).forEach(name -&gt; { User user = new User(name, name.toLowerCase() + &quot;@domain.com&quot;); userRepository.save(user); }); userRepository.findAll().forEach(System.out::println); }; } //* for reference } </code></pre> <p>The code from &quot;@Bean&quot; to the &quot;//*&quot; seems to be causing the error, as when deleted it has no errors when running. However unsure how to word it in order to not receive the error. <a href="https://www.baeldung.com/spring-boot-angular-web#:%7E:text=Spring%20Boot%20and%20Angular%20form,creating%20a%20JavaScript-based%20frontend." rel="nofollow noreferrer">Following this tutorial.</a></p> <p>UserController.java</p> <pre><code>@RestController @CrossOrigin(origins = &quot;http://localhost:4200&quot;) public class UserController { private final UserRepository userRepository; public UserController(UserRepository userRepository) { this.userRepository = userRepository; } @GetMapping(&quot;/users&quot;) public List&lt;User&gt; getUsers() { return (List&lt;User&gt;) userRepository.findAll(); } @PostMapping(&quot;/users&quot;) void addUser(@RequestBody User user) { userRepository.save(user); } } </code></pre> <p>User.java</p> <pre><code>@Entity public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private final String name; private final String email; public User() { this.name = &quot;&quot;; this.email = &quot;&quot;; } public User(String name, String email) { this.name = name; this.email = email; } public long getId() { return id; } public String getName() { return name; } public String getEmail() { return email; } @Override public String toString() { return &quot;User{&quot; + &quot;id=&quot; + id + &quot;, name=&quot; + name + &quot;, email=&quot; + email + '}'; } </code></pre> <p>application.properties</p> <pre><code>spring.jpa.show-sql = true spring.jpa.hibernate.ddl-auto = update spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect </code></pre> <p>**What I have tried **</p> <p>I have read gone through some previous questions <a href="https://stackoverflow.com/questions/33626089/hibernate-schema-is-automatically-dropped-on-deploy">here</a> and adjusted the application.properties to include the dialect as most places have mention this as the issue.</p> <p>As stated I have removed the marked code in Application.java and the it seems to be fine once that has been done so that area I feel is the issue.</p>
[ { "answer_id": 74536398, "author": "abidinberkay", "author_id": 1261764, "author_profile": "https://Stackoverflow.com/users/1261764", "pm_score": 0, "selected": false, "text": "int long @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n GenerationType.AUTO CrudRepository<User, Integer> javax.persistence.Id\n" }, { "answer_id": 74537705, "author": "StackVeryOverFlowed", "author_id": 20110547, "author_profile": "https://Stackoverflow.com/users/20110547", "pm_score": 1, "selected": false, "text": "spring.jpa.show-sql = true\nspring.jpa.hibernate.ddl-auto = update\nspring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect spring.jpa.properties.hibernate.globally_quoted_identifiers=true\nspring.jpa.properties.hibernate.globally_quoted_identifiers_skip_column_definitions = true " } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20110547/" ]
74,535,727
<p>I have a strange bug, I am able to receive two different values from the server successfully and when I do Math calculations for them the returned value is always zero.</p> <p>My code is very simple</p> <pre><code> val achievedViews = campaign.achievedViews val totalViews = campaign.totalViews val percentage = (achievedViews.div(totalViews)).times(100) </code></pre> <p>By logging my code I can see I got the value of both achievedViews and totalViews, but percentage is always zero even though I didn't initiate its value by anything.</p> <p><a href="https://i.stack.imgur.com/OlYwS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OlYwS.png" alt="enter image description here" /></a></p> <p>I cant figure out what is the reason for this strange behavior and why the returned value is always zero?</p>
[ { "answer_id": 74535933, "author": "undermark5", "author_id": 3251429, "author_profile": "https://Stackoverflow.com/users/3251429", "pm_score": 1, "selected": true, "text": "achievedViews totalViews Int div 0 Float Double Int" }, { "answer_id": 74536642, "author": "ba1", "author_id": 18776657, "author_profile": "https://Stackoverflow.com/users/18776657", "pm_score": 1, "selected": false, "text": "2(int) / 4(int) = 0(int) (rounded down)\n2(double) / 4(double) = 0.5(double)\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8415711/" ]
74,535,746
<p>so here's my collection. This consists of users and their data</p> <pre><code>{ userId: 6udg, data: [ { date: 22-09-2022 hits: 98 }, { date: 23-09-2022 hits: 88 }, { date: 24-09-2022 hits: 100 }, { date: 24-11-2022 hits: 145 }, { date: 25-11-2022 hits: 75 } ] }, { userId: 7tu5, data: [ { date: 22-09-2022 hits: 98 }, { date: 23-09-2022 hits: 88 }, { date: 24-09-2022 hits: 100 }, { date: 24-11-2022 hits: 18 }, { date: 25-11-2022 hits: 65 } ] } </code></pre> <p>Here's how I'm creating an aggregate with objects for hits filtered by week, month and year. First I match the user whose data we want to fetch. Then I use projection to get the custom fields that I want.</p> <pre><code>Users.aggregate([ { $match: { userId: req.params.userId } }, { $project: { _id: 0, last_seven_days: { $filter: { input: &quot;$data&quot;, as: &quot;index&quot;, cond: { $and: [ { $gte: [ &quot;$$index.date&quot;, new Date(moment().utc().startOf(&quot;week&quot;)) ] }, { $lte: [ &quot;$$index.date&quot;, new Date(moment().utc().endOf(&quot;week&quot;)) ] } ] } }, }, last_month: { $filter: { input: &quot;$data&quot;, as: &quot;index&quot;, cond: { $and: [ { $gte: [ &quot;$$index.date&quot;, new Date(moment().utc().startOf(&quot;month&quot;)) ] }, { $lte: [ &quot;$$index.date&quot;, new Date(moment().utc().endOf(&quot;month&quot;)) ] } ] } } }, last_year: { $filter: { input: &quot;$data&quot;, as: &quot;index&quot;, cond: { $and: [ { $gte: [ &quot;$$index.date&quot;, new Date(moment().utc().startOf(&quot;year&quot;)) ] }, { $lte: [ &quot;$$index.date&quot;, new Date(moment().utc().endOf(&quot;month&quot;)) ] } ] } } } } } ]) </code></pre> <p>what I want to do is add a key called 'average' in each <strong>last_seven_days</strong> , <strong>last_month</strong>, and <strong>last_year</strong> - containing the average hits for week, month and year respectively</p> <p>Expected output:</p> <pre><code>{ userId: 6udg last_seven_day:[ avg: &lt;avg&gt; data:[ { date: 24-11-2022, hits: 145, }, { date: 25-11-2022, hits: 75, } ] ] } </code></pre>
[ { "answer_id": 74535933, "author": "undermark5", "author_id": 3251429, "author_profile": "https://Stackoverflow.com/users/3251429", "pm_score": 1, "selected": true, "text": "achievedViews totalViews Int div 0 Float Double Int" }, { "answer_id": 74536642, "author": "ba1", "author_id": 18776657, "author_profile": "https://Stackoverflow.com/users/18776657", "pm_score": 1, "selected": false, "text": "2(int) / 4(int) = 0(int) (rounded down)\n2(double) / 4(double) = 0.5(double)\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7599905/" ]
74,535,766
<p>Given the following task. We have an <code>Employee</code> and a <code>Company</code> classes. Each instance of <code>Employee</code> class is stored in array <code>Employee[] employees</code> in the <code>Company</code> class. I need a method which removes an instance of <code>Employee</code> in the array <code>Employee[] employees</code> by <code>id</code>.</p> <p>I managed to write the following code:</p> <pre><code>public class Employee { protected final int id; protected String name; public Employee(int id, String name) { this.id = id; this.name= name; } public int getId() { return id; } } public class Company { private Employee[] employees; private int size; private static final int defaultCapacity = 5; public Company() { this(defaultCapacity); } public Company(int capacity) { if (capacity &lt;= 0) throw new RuntimeException(&quot;capacity is required&quot;); employees = new Employee[capacity]; } public Employee removeEmployee(int id) { Collection&lt;Employee&gt; employeeList = Arrays.asList(employees) .stream() .filter(Objects::nonNull) .collect(Collectors.toList()); Employee[] employeeArray = employeeList.toArray(Employee[]::new); for (int i = 0; i &lt; size; i++) { if(employeeArray[i].getId() == id) { Employee removedEmployee = employees[i]; employeeList.remove(employeeArray[i]); employees = employeeList .stream() .filter(Objects::nonNull) .toArray(Employee[]::new); return removedEmployee; } } return null; } } </code></pre> <p>The problem is that my method <code>public Employee removeEmployee(int id)</code> throws <code>NullPointerException</code> if an element for removal is not found.</p> <p><strong>Question:</strong></p> <ol> <li>How can I rewrite the method <code>public Employee removeEmployee(int id)</code> using, for instance, Streams API and Optional in oder to get rid of NullPointerException in the method <code>public Employee removeEmployee(int id)</code>?</li> </ol> <p><strong>N.B.:</strong> The length of the array <code>Employee[] employees</code> declared in the class <code>Company</code> must be reduced after the element has been successfully removed.</p>
[ { "answer_id": 74536059, "author": "Lorenz Hetterich", "author_id": 20473701, "author_profile": "https://Stackoverflow.com/users/20473701", "pm_score": 3, "selected": true, "text": "public Employee removeEmployee(int id) {\n Optional<Employee> employee = Arrays.stream(employees)\n .filter(Objects::nonNull)\n .filter(x -> x.getId() == id).\n .findAny();\n if(employee.isEmpty())\n return null;\n employees = Arrays.stream(employees).filter(x -> x != employee.get()).toArray(Employee[]::new);\n return employee.get();\n}\n employees public Employee removeEmployee(int id){\n Optional<Employee> toRemove = employees.stream().filter(x -> x.getId() == id).findAny();\n if(toRemove.isEmpty())\n return null;\n employees.remove(toRemove.get());\n return toRemove.get();\n\n}\n public Employee removeEmployee(int id){\n int idx;\n for(idx = 0; idx < employees.length; idx++){\n if(employees[idx] != null && employees[idx].getId() == id)\n break;\n }\n if(idx == employees.length)\n return null;\n\n Employee value = employees[idx];\n \n Employee[] newArr = new Employee[employees.length - 1];\n\n // the parameters here are left as an exercise to the reader :P\n System.arraycopy(newArr, ...);\n System.arraycopy(newArr, ...);\n\n employees = newArr;\n\n return value;\n\n}\n" }, { "answer_id": 74536406, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 1, "selected": false, "text": "Employee[] Company id 1 employees System.arraycopy() for public Employee removeEmployee(int id) {\n Employee result = null;\n int index = -1;\n \n for (int i = 0; i < employees.length; i++) {\n if (employees[i] != null && employees[i].getId() == id) {\n result = employees[i];\n employees[i] = null;\n break;\n }\n }\n if (result != null) {\n reduceLength(index);\n }\n return result;\n}\n\npublic void reduceLength(int i) {\n Employee[] newEmployees = new Employee[employees.length - 1];\n System.arraycopy(employees, 0, newEmployees, 0, i);\n System.arraycopy(employees, i + 1, newEmployees, i, employees.length - (i + 1));\n employees = newEmployees;\n}\n public Optional<Employee> removeEmployee(int id) {\n Optional<Integer> index = IntStream.range(0, employees.length)\n .filter(i -> employees[i] != null)\n .filter(i -> employees[i].getId() == id)\n .boxed() // otherwise will get OptionalInt which lacks map() method\n .findFirst();\n \n Optional<Employee> result = index.map(i -> employees[i]);\n index.ifPresent(this::reduceLength);\n \n return result;\n}\n" }, { "answer_id": 74544905, "author": "Chaosfire", "author_id": 17795888, "author_profile": "https://Stackoverflow.com/users/17795888", "pm_score": 0, "selected": false, "text": "public class Company {\n\n private Employee[] employees;\n private int size;\n\n public Employee removeEmployee(int id) {\n int index = -1;\n //find the index of employee with required id, you have mostly done that\n if (index == -1) {\n return null;\n }\n //save found employee to variable\n //remove from array\n //shift array to the left\n\n //do not forget to use and reassign size variable where appropriate\n }\n\n //some extra\n public void addEmployee(Employee employee) {\n //resize array if necessary\n //add employee at correct position in array\n\n //do not forget to use and reassign size variable where appropriate\n }\n}\n ArrayList" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16561343/" ]
74,535,815
<p>Hey I am making a telegram bot and I need it to be able to run the same command multiple times at once.</p> <pre><code>dispatcher.add_handler(CommandHandler(&quot;send&quot;, send)) </code></pre> <p>This is the command ^</p> <p>And inside the command it starts a function:</p> <pre><code>sendmail(email, amount, update, context) </code></pre> <p>This function takes around 5seconds to finish. I want it so I can run it multiple times at once without needing to wait for it to finish. I tried the following:</p> <pre><code>Thread(target=sendmail(email, amount, update, context)).start() </code></pre> <p>This would give me no errors but It waits for function to finish then proceeds. I also tried this</p> <pre><code>with ThreadPoolExecutor(max_workers=100) as executor: executor.submit(sendmail, email, amount, update, context).result() </code></pre> <p>but it gave me the following error:</p> <pre><code>No error handlers are registered, logging exception. Traceback (most recent call last): File &quot;C:\Users\seal\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\ext\dispatcher.py&quot;, line 557, in process_update handler.handle_update(update, self, check, context) File &quot;C:\Users\seal\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\ext\handler.py&quot;, line 199, in handle_update return self.callback(update, context) File &quot;c:\Users\seal\Downloads\telegrambot\main.py&quot;, line 382, in sendmailcmd executor.submit(sendmail, email, amount, update, context).result() File &quot;C:\Users\main\AppData\Local\Programs\Python\Python310\lib\concurrent\futures\thread.py&quot;, line 169, in submit raise RuntimeError('cannot schedule new futures after ' RuntimeError: cannot schedule new futures after interpreter shutdown </code></pre>
[ { "answer_id": 74536037, "author": "Hunter", "author_id": 15076691, "author_profile": "https://Stackoverflow.com/users/15076691", "pm_score": 1, "selected": false, "text": "import threading\nx1 = threading.Thread(target=sendmail, args=(email, amount, update, context))\nx1.start()\n x1 = threading... x1.start()" }, { "answer_id": 74536105, "author": "Januka samaranyake", "author_id": 5266998, "author_profile": "https://Stackoverflow.com/users/5266998", "pm_score": 0, "selected": false, "text": "def async_send_email(emails_to_send):\n with ThreadPoolExecutor(max_workers=32) as executor:\n futures = [\n executor.submit(\n send_email,\n email=email_to_send.email,\n amount=email_to_send.amount,\n update=email_to_send.update,\n context=email_to_send.context\n )\n for email_to_send in emails_to_send\n ]\n\n for future, email_to_send in zip(futures, emails_to_send):\n try:\n future.result()\n except Exception as e:\n # Handle the exceptions.\n continue\n\ndef send_email(email, amount, update, context):\n # do what you want here.\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20494538/" ]
74,535,821
<p>I am trying to enable touchdrag and mousedrag only for mobile devices.</p> <pre><code>customOptions: OwlOptions = { loop: true, mouseDrag: false, touchDrag: false, pullDrag: false, dots: false, navText: ['', ''], items: 4, responsive: { 0: { touchDrag: true, mouseDrag: true }, 768: { touchDrag: false, mouseDrag: false } }, nav: true } </code></pre> <p>Somewhere I read, carousel should be refreshed for changes to happen when resized. But everywhere they used jquery</p> <pre><code>$('owl-carousel').trigger('refresh.owl.carousel') </code></pre> <p>But I want to do it without using jquery as I am using owl-carousel-o tag and also owloptions. If there is some other way also please suggest.</p>
[ { "answer_id": 74536037, "author": "Hunter", "author_id": 15076691, "author_profile": "https://Stackoverflow.com/users/15076691", "pm_score": 1, "selected": false, "text": "import threading\nx1 = threading.Thread(target=sendmail, args=(email, amount, update, context))\nx1.start()\n x1 = threading... x1.start()" }, { "answer_id": 74536105, "author": "Januka samaranyake", "author_id": 5266998, "author_profile": "https://Stackoverflow.com/users/5266998", "pm_score": 0, "selected": false, "text": "def async_send_email(emails_to_send):\n with ThreadPoolExecutor(max_workers=32) as executor:\n futures = [\n executor.submit(\n send_email,\n email=email_to_send.email,\n amount=email_to_send.amount,\n update=email_to_send.update,\n context=email_to_send.context\n )\n for email_to_send in emails_to_send\n ]\n\n for future, email_to_send in zip(futures, emails_to_send):\n try:\n future.result()\n except Exception as e:\n # Handle the exceptions.\n continue\n\ndef send_email(email, amount, update, context):\n # do what you want here.\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18660674/" ]
74,535,834
<p>I would like to use the corr.test function from the psych package in order to calculate the correlation and the significance between corresponding columns of two dataframes. A simplified example of the dataframes <code>Df1</code> and <code>Df2</code> I am working with is this:</p> <pre><code>set.seed(42) Df1 &lt;- data.frame(matrix(runif(50), 10, 5)) Df2 &lt;- data.frame(matrix(runif(50), 10, 5)) </code></pre> <p>Please note that this question has been already answered here:</p> <p><a href="https://stackoverflow.com/questions/68694054/column-by-column-correlation-between-two-data-sets-with-r">Column by column correlation between two data sets with R?</a></p> <p>but only for the the correlation part, i.e., it lacks the significance I am looking for, since it uses the cor function and not the corr.test one.</p> <p>Any help would be greatly appreciated.</p>
[ { "answer_id": 74536169, "author": "Armel Soubeiga", "author_id": 11368978, "author_profile": "https://Stackoverflow.com/users/11368978", "pm_score": 0, "selected": false, "text": "rcorr() Hmisc library(\"Hmisc\")\nres2 <- rcorr(as.matrix(cbind(Df1, Df2)))\nres2\n P\n X1 X2 X3 X4 X5 X1 X2 X3 X4 X5 \nX1 0.8552 0.3306 0.2765 0.6174 0.4885 0.8445 0.3510 0.4739 0.8592\nX2 0.8552 0.4264 0.9639 0.7081 0.2472 0.2417 0.7335 0.9291 0.1414\nX3 0.3306 0.4264 0.6919 0.7151 0.4481 0.6139 0.9188 0.9900 0.7766\nX4 0.2765 0.9639 0.6919 0.5230 0.4341 0.8599 0.2467 0.7841 0.9047\nX5 0.6174 0.7081 0.7151 0.5230 0.1280 0.1076 0.1151 0.8081 0.1744\nX1 0.4885 0.2472 0.4481 0.4341 0.1280 0.0130 0.5283 0.6915 0.9308\nX2 0.8445 0.2417 0.6139 0.8599 0.1076 0.0130 0.8044 0.7331 0.4809\nX3 0.3510 0.7335 0.9188 0.2467 0.1151 0.5283 0.8044 0.8020 0.2286\nX4 0.4739 0.9291 0.9900 0.7841 0.8081 0.6915 0.7331 0.8020 0.0595\nX5 0.8592 0.1414 0.7766 0.9047 0.1744 0.9308 0.4809 0.2286 0.0595\n" }, { "answer_id": 74536587, "author": "AndS.", "author_id": 9778513, "author_profile": "https://Stackoverflow.com/users/9778513", "pm_score": 1, "selected": false, "text": "library(tidyverse)\n\nmap_dfr(1:ncol(Df1), \\(i) {\n cr_tst <- cor.test(Df1[, i], Df2[, i])\n tibble(var = colnames(Df1)[i],\n cor = cr_tst$estimate,\n p.value = cr_tst$p.value)\n})\n#> # A tibble: 5 x 3\n#> var cor p.value\n#> <chr> <dbl> <dbl>\n#> 1 X1 0.249 0.488\n#> 2 X2 -0.408 0.242\n#> 3 X3 0.0372 0.919\n#> 4 X4 -0.0997 0.784\n#> 5 X5 0.466 0.174\n" }, { "answer_id": 74537978, "author": "jay.sf", "author_id": 6574038, "author_profile": "https://Stackoverflow.com/users/6574038", "pm_score": 1, "selected": true, "text": "cor.test mapply mapply(\\(x, y) cor.test(x, y)[c('estimate', 'p.value')], Df1, Df2)\n# X1 X2 X3 X4 X5 \n# estimate 0.2486405 -0.408098 0.03718413 -0.09967868 0.4662738\n# p.value 0.4884952 0.2416943 0.9187721 0.7841065 0.1743502\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7025817/" ]
74,535,852
<p>My custom post type &quot;references&quot; has a custom field called &quot;references_count&quot;. It has a numeric value.</p> <p>I have an custom taxonomy called &quot;country&quot; with a custom field called &quot;country_count&quot; for the terms.</p> <p><strong>Background:</strong> The custom post type &quot;references&quot; saves <em>cities</em> with a number of <em>clients in this city</em>. This value is saved in the field &quot;references_count&quot;. In the custom taxonomy there are countries. For each country, there is a <em>total number of references</em>.</p> <p><strong>Example:</strong> In the city of &quot;Berlin&quot; there are 3 clients. In the city of &quot;Munich&quot; there are 2 clients. The taxonomy term &quot;Germany&quot; includes the sum of all cities in this country. So the value of &quot;country_count&quot; in this example for the taxonomy term &quot;Germany&quot; is 5, being the sum of the references of each city.</p> <p>I wrote this code which is working, if I'm saving each individual taxonomy term.</p> <pre><code>add_action( 'edited_country', 'update_counter_for_countries', 10, 2 ); function update_counter_for_countries( $term_id ) { // Get posts with term $args = array( 'post_type' =&gt; 'reference', 'posts_per_page' =&gt; -1, 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'country', 'field' =&gt; 'term_id', 'terms' =&gt; $term_id ) ) ); $the_query = new WP_Query( $args ); // sum values in posts $sumTerm = 0; if ( $the_query-&gt;have_posts() ) { while ( $the_query-&gt;have_posts() ) { $the_query-&gt;the_post(); $number = get_field( 'references_count', get_the_ID() ); $sumTerm = $sumTerm + $number; } } wp_reset_postdata(); // update field in term update_field( 'country_count', $sumTerm, 'country'.'_'.$term_id ); } </code></pre> <p><strong>Problem:</strong> I have more than 100 countries (taxonomy terms), so I have to save each term individually to get things going.</p> <p><strong>What I am looking for:</strong> Is there a way to update / save all custom taxonomy terms at once, so I don't have to update each term seperately? I checked out a lot of plugins, but couldn't find any plugin which gives the possibility of &quot;bulk edit&quot; or &quot;bulk save&quot; taxonomy terms. I would prefer a solution without plugin if possible. I am very grateful for any hint, thank you very much.</p>
[ { "answer_id": 74537879, "author": "Rizwan Ahmad", "author_id": 20133382, "author_profile": "https://Stackoverflow.com/users/20133382", "pm_score": 1, "selected": false, "text": "if($_SERVER[\"REMOTE_ADDR\"]=='111.111.111.111'){\n//run only my ip\n add_action(\"init\",\"update_all_terms_in_one_go\");\n}\n\nfunction update_all_terms_in_one_go(){\n session_start();\n if(isset($_SESSION['all_terms_updated']) && $_SESSION['all_terms_updated'] == \"done\"){\n return;\n }\n $taxonomy = \"country\";\n $terms = get_terms([\n 'taxonomy' => $taxonomy,\n 'hide_empty' => false,\n ]);\n foreach ($terms as $term) {\n update_counter_for_countries( $term->term_id );\n }\n $_SESSION['all_terms_updated'] = \"done\";\n echo \"ALL TAXONOMY TERMS UPDATED\";\n die();\n\n}\n\nfunction update_counter_for_countries( $term_id ) {\n// Get posts with term\n $args = array(\n 'post_type' => 'reference',\n 'posts_per_page' => -1,\n 'tax_query' => array(\n array(\n 'taxonomy' => 'country',\n 'field' => 'term_id',\n 'terms' => $term_id\n )\n )\n );\n $the_query = new WP_Query( $args );\n\n// sum values in posts\n $sumTerm = 0;\n if ( $the_query->have_posts() ) {\n while ( $the_query->have_posts() ) {\n $the_query->the_post();\n $number = get_field( 'references_count', get_the_ID() );\n $sumTerm = $sumTerm + $number;\n }\n }\n wp_reset_postdata();\n// update field in term\n update_field( 'country_count', $sumTerm, 'country'.'_'.$term_id );\n}\n" }, { "answer_id": 74662008, "author": "rank", "author_id": 12405298, "author_profile": "https://Stackoverflow.com/users/12405298", "pm_score": 1, "selected": true, "text": "add_action( 'admin_menu', array( $this, 'my_admin_page' ) );\n\nfunction my_admin_page() {\n add_menu_page(\n __('Bulk Terms'), // page title\n __('Bulk Terms'), // menu title\n 'manage_options', // user capabilities\n 'options-page', // menu slug\n 'my_output_function', // output function\n 'dashicons-admin-generic', // menu icon\n 77 // menu position\n );\n}\n function my_output_function() {\n echo '<div class=\"wrap\">';\n echo '<form action=\"admin.php?page=options-page\" method=\"post\">';\n wp_nonce_field( 'ajax_validation', 'nonce' ); // security feature\n submit_button('Update Terms', 'primary', 'submitOptions', false);\n echo '</form>';\n echo '<div id=\"processing\" style=\"display:none;\">Please wait</div>';\n echo '<div id=\"error\" style=\"display:none;\">Something went wrong</div>';\n echo '<div id=\"success\" style=\"display:none;\">Done!</div>';\n echo '</div>';\n}\n add_action( 'admin_enqueue_scripts', 'my_ajax_scripts' );\n\nfunction my_ajax_scripts() {\n // Check if on specific admin page\n global $pagenow;\n if (( $pagenow == 'admin.php' ) && ($_GET['page'] == 'options-page')):\n wp_enqueue_script( 'ajaxcalls', plugin_dir_url( __FILE__ ).'/js/ajax-calls.js', array('jquery'), '1.0.0', true );\n\n wp_localize_script( 'ajaxcalls', 'ajax_object', array(\n 'ajaxurl' => admin_url( 'admin-ajax.php' ),\n 'ajaxnonce' => wp_create_nonce( 'ajax_validation' )\n ) );\n endif;\n}\n function options_page_action() {\n $taxonomy = \"country\";\n $terms = get_terms([\n 'taxonomy' => $taxonomy,\n 'hide_empty' => false,\n ]);\n foreach ($terms as $term) {\n $term_id = $term->term_id;\n // Get posts with term\n $args = array(\n 'post_type' => 'reference',\n 'posts_per_page' => -1,\n 'tax_query' => array(\n array(\n 'taxonomy' => 'country',\n 'field' => 'term_id',\n 'terms' => $term_id\n )\n )\n );\n $the_query = new WP_Query( $args );\n\n // sum values in posts\n $sumTerm = 0;\n if ( $the_query->have_posts() ) {\n while ( $the_query->have_posts() ) {\n $the_query->the_post();\n $number = get_field( 'references_count', get_the_ID() );\n $sumTerm = $sumTerm + $number;\n }\n }\n wp_reset_postdata();\n // update field in term\n update_field( 'country_count', $sumTerm, 'country'.'_'.$term_id );\n }\n $result = array( 'status' => 'success' ); // create response\n wp_send_json_success( $result ); // send response\n wp_die(); // close ajax request\n}\n $( '#submitOptions' ).click( function(event) {\n event.preventDefault();\n $('#submitOptions').css('cssText','display:none;');\n $('#processing').css('cssText','display: block;');\n $.ajax({\n type: 'POST',\n url: ajax_object.ajaxurl,\n data: {\n action: 'options_page_action',\n nonce: ajax_object.ajaxnonce\n },\n success: function( response ) {\n if( response['data']['status'] == 'success' ) {\n $('#processing').css('cssText','display:none;');\n $('#success').css('cssText','display:block;');\n }\n },\n error: function() {\n $('#processing').css('cssText','display:none;');\n $('#error').css('cssText','display:block;');\n }\n });\n});\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12405298/" ]
74,535,858
<p>I'm struggling with expression trees and Entity Framework Core.</p> <p>I have a method that returns an expression tree that I will use for filtering, something like:</p> <pre><code>public Expression&lt;Func&lt;E, bool&gt;&gt; GetWherePredicate&lt;E&gt;(Func&lt;E, NpgsqlTsVector&gt; selector, string queryText) { return entity =&gt; selector(entity).Matches(queryText); } </code></pre> <p>And then I'd like to invoke this method with something like:</p> <pre><code> query = query.Where(GetWherePredicate&lt;MyEntity&gt;(i =&gt; i.MySearchField, &quot;the_query&quot;)); </code></pre> <p>This produces an error, something like:</p> <blockquote> <p>System.InvalidOperationException: The LINQ expression 'DbSet()<br /> .Where(i =&gt; Invoke(__selector_0, i)<br /> .Matches(__queryText_1))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See <a href="https://go.microsoft.com/fwlink/?linkid=2101038" rel="nofollow noreferrer">https://go.microsoft.com/fwlink/?linkid=2101038</a> for more information.</p> </blockquote> <p>While I understand why this doesn't work, I am not sure how to solve this, but suspect it has to do with using expression trees. I thought of creating a new function that has the following signature, something like:</p> <pre><code>Expression&lt;Func&lt;E, bool&gt;&gt; GetWherePredicate&lt;E&gt;(MemberExpression selectorForSearchField, string queryText); </code></pre> <p>But I am not able to figure out how to take that expression and apply the <code>Matches</code> function.</p> <p>Any help is appreciated.</p> <p>Thanks, Eric</p>
[ { "answer_id": 74537879, "author": "Rizwan Ahmad", "author_id": 20133382, "author_profile": "https://Stackoverflow.com/users/20133382", "pm_score": 1, "selected": false, "text": "if($_SERVER[\"REMOTE_ADDR\"]=='111.111.111.111'){\n//run only my ip\n add_action(\"init\",\"update_all_terms_in_one_go\");\n}\n\nfunction update_all_terms_in_one_go(){\n session_start();\n if(isset($_SESSION['all_terms_updated']) && $_SESSION['all_terms_updated'] == \"done\"){\n return;\n }\n $taxonomy = \"country\";\n $terms = get_terms([\n 'taxonomy' => $taxonomy,\n 'hide_empty' => false,\n ]);\n foreach ($terms as $term) {\n update_counter_for_countries( $term->term_id );\n }\n $_SESSION['all_terms_updated'] = \"done\";\n echo \"ALL TAXONOMY TERMS UPDATED\";\n die();\n\n}\n\nfunction update_counter_for_countries( $term_id ) {\n// Get posts with term\n $args = array(\n 'post_type' => 'reference',\n 'posts_per_page' => -1,\n 'tax_query' => array(\n array(\n 'taxonomy' => 'country',\n 'field' => 'term_id',\n 'terms' => $term_id\n )\n )\n );\n $the_query = new WP_Query( $args );\n\n// sum values in posts\n $sumTerm = 0;\n if ( $the_query->have_posts() ) {\n while ( $the_query->have_posts() ) {\n $the_query->the_post();\n $number = get_field( 'references_count', get_the_ID() );\n $sumTerm = $sumTerm + $number;\n }\n }\n wp_reset_postdata();\n// update field in term\n update_field( 'country_count', $sumTerm, 'country'.'_'.$term_id );\n}\n" }, { "answer_id": 74662008, "author": "rank", "author_id": 12405298, "author_profile": "https://Stackoverflow.com/users/12405298", "pm_score": 1, "selected": true, "text": "add_action( 'admin_menu', array( $this, 'my_admin_page' ) );\n\nfunction my_admin_page() {\n add_menu_page(\n __('Bulk Terms'), // page title\n __('Bulk Terms'), // menu title\n 'manage_options', // user capabilities\n 'options-page', // menu slug\n 'my_output_function', // output function\n 'dashicons-admin-generic', // menu icon\n 77 // menu position\n );\n}\n function my_output_function() {\n echo '<div class=\"wrap\">';\n echo '<form action=\"admin.php?page=options-page\" method=\"post\">';\n wp_nonce_field( 'ajax_validation', 'nonce' ); // security feature\n submit_button('Update Terms', 'primary', 'submitOptions', false);\n echo '</form>';\n echo '<div id=\"processing\" style=\"display:none;\">Please wait</div>';\n echo '<div id=\"error\" style=\"display:none;\">Something went wrong</div>';\n echo '<div id=\"success\" style=\"display:none;\">Done!</div>';\n echo '</div>';\n}\n add_action( 'admin_enqueue_scripts', 'my_ajax_scripts' );\n\nfunction my_ajax_scripts() {\n // Check if on specific admin page\n global $pagenow;\n if (( $pagenow == 'admin.php' ) && ($_GET['page'] == 'options-page')):\n wp_enqueue_script( 'ajaxcalls', plugin_dir_url( __FILE__ ).'/js/ajax-calls.js', array('jquery'), '1.0.0', true );\n\n wp_localize_script( 'ajaxcalls', 'ajax_object', array(\n 'ajaxurl' => admin_url( 'admin-ajax.php' ),\n 'ajaxnonce' => wp_create_nonce( 'ajax_validation' )\n ) );\n endif;\n}\n function options_page_action() {\n $taxonomy = \"country\";\n $terms = get_terms([\n 'taxonomy' => $taxonomy,\n 'hide_empty' => false,\n ]);\n foreach ($terms as $term) {\n $term_id = $term->term_id;\n // Get posts with term\n $args = array(\n 'post_type' => 'reference',\n 'posts_per_page' => -1,\n 'tax_query' => array(\n array(\n 'taxonomy' => 'country',\n 'field' => 'term_id',\n 'terms' => $term_id\n )\n )\n );\n $the_query = new WP_Query( $args );\n\n // sum values in posts\n $sumTerm = 0;\n if ( $the_query->have_posts() ) {\n while ( $the_query->have_posts() ) {\n $the_query->the_post();\n $number = get_field( 'references_count', get_the_ID() );\n $sumTerm = $sumTerm + $number;\n }\n }\n wp_reset_postdata();\n // update field in term\n update_field( 'country_count', $sumTerm, 'country'.'_'.$term_id );\n }\n $result = array( 'status' => 'success' ); // create response\n wp_send_json_success( $result ); // send response\n wp_die(); // close ajax request\n}\n $( '#submitOptions' ).click( function(event) {\n event.preventDefault();\n $('#submitOptions').css('cssText','display:none;');\n $('#processing').css('cssText','display: block;');\n $.ajax({\n type: 'POST',\n url: ajax_object.ajaxurl,\n data: {\n action: 'options_page_action',\n nonce: ajax_object.ajaxnonce\n },\n success: function( response ) {\n if( response['data']['status'] == 'success' ) {\n $('#processing').css('cssText','display:none;');\n $('#success').css('cssText','display:block;');\n }\n },\n error: function() {\n $('#processing').css('cssText','display:none;');\n $('#error').css('cssText','display:block;');\n }\n });\n});\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/726411/" ]
74,535,875
<p>I am trying to get the scroll position of a div in React. I tried getting the window the scroll values the values are always 0.</p> <pre><code> handleScrollPosition(e){ sessionStorage.setItem(&quot;scrollPosition&quot;, this.myRef.current!.scrollTop.toString()); }; &lt;SearchListWrapper className=&quot;TestSL&quot; ref={this.myRef} onScroll={this.handleScrollPosition} &gt; &lt;StyledLink onClick={ () =&gt;{ this.onClickResult(); } } &gt; &lt;/StyledLink&gt; &lt;/SearchListWrapper&gt; </code></pre> <p>On click of StyledLink the new page is loaded. When I go back(with browser's back button) from the newly loaded page, I want to restore the position of scroll on SearchListWrapper .</p>
[ { "answer_id": 74536220, "author": "MalwareMoon", "author_id": 20241005, "author_profile": "https://Stackoverflow.com/users/20241005", "pm_score": 1, "selected": true, "text": "getBoundingClientRect().top document.getElementById(element).getBoundingClientRect().top;\n useRef yourRef.current.getBoundingClientRect().top\n export default function App() {\n const divRef = React.useRef();\n if (divRef) {\n console.log(divRef.current.getBoundingClientRect().top);\n }\n return (\n <div className=\"App\">\n <h1>Hello CodeSandbox</h1>\n <h2> Start editing to see some magic happen!</h2>\n <div ref={divRef}>Text</div>\n </div>\n );\n}\n" }, { "answer_id": 74536236, "author": "codinn.dev", "author_id": 15755662, "author_profile": "https://Stackoverflow.com/users/15755662", "pm_score": -1, "selected": false, "text": "handleScrollPosition(e){\n const scrollTop = document.getElementById(\"TestSL\").scrollTop;\n //use scrollTop here\n}\n <SearchListWrapper id=\"TestSL\" onScroll={this.handleScrollPosition} >\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20574172/" ]
74,535,878
<p>I have the following folder structure</p> <p><a href="https://i.stack.imgur.com/GFOYv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GFOYv.png" alt="enter image description here" /></a></p> <p>I want to import both MessageList.tsx and MessageSent.tsx inside my Chat.tsx</p> <pre><code>// Chat.tsx import React from 'react' import {MessageList, MessageSent} from &quot;./components/&quot; type Props = {} const Chat= (props: Props) =\&gt; { return ( &lt;div\&gt;Chat&lt;/div&gt; ) } export default Chat` // MessageSent.tsx import React from 'react' type Props = {} const MessageList = (props: Props) =&gt; { return ( &lt;div&gt;MessageList&lt;/div&gt; ) } export default MessageList </code></pre> <p>MessageList.tsx is similar to MessageSent,tsx, only the name of the components is different</p> <p>However, when I try to do the import of these two components {MessageList, MessageSent} I get the following error:</p> <p>** Cannot find module './components/' or its corresponding type declarations.**</p> <p>Why is that?</p> <p>Tried different paths besides &quot;./components/&quot;, even with full path.</p>
[ { "answer_id": 74536009, "author": "Art Bauer", "author_id": 8350191, "author_profile": "https://Stackoverflow.com/users/8350191", "pm_score": 0, "selected": false, "text": "// index.ts\nexport * from './MessageList';\nexport * from './MessageSent';\n" }, { "answer_id": 74536013, "author": "Moussa Bistami", "author_id": 15628525, "author_profile": "https://Stackoverflow.com/users/15628525", "pm_score": 0, "selected": false, "text": "index.ts index.ts export * from './MessageList.tsx';\nexport * from './MessageSent.tsx';\n" }, { "answer_id": 74536043, "author": "DanH", "author_id": 15197189, "author_profile": "https://Stackoverflow.com/users/15197189", "pm_score": 1, "selected": false, "text": "import MessageSent from \"./components/MessageSent\"\nimport MessageList from \"./components/MessageList\"\n import MessageSent from './MessageSent'\nimport MessageList from './MessageList'\nexport { MessageSent, MessageList }\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12695692/" ]
74,535,917
<pre><code>async function change_status(object_id:number){ const response = await fetch('/api/db', { method: 'POST', body: JSON.parse(`{&quot;id&quot;:${object_id}}`) }); if (!response.ok){ throw new Error(response.statusText); } return await response.json(); } </code></pre> <p><strong>I want this button to change an int in mysql</strong></p> <pre><code>&lt;button onClick={() =&gt; change_status(object.id)}&gt; change Status &lt;/button&gt; </code></pre> <p><strong>/api/db.ts</strong></p> <pre><code>export default async function handler(req: NextApiRequest,res: NextApiResponse) { const data = JSON.parse(req.body); const object_id = data.id; const find_object = await prisma.objects.findFirstOrThrow({ where: {id:object_id} }); if (find_object.status == 0){ var change = await prisma.objects.update({ where: { id: object_id }, data: { status:1 }, }) } else { var change = await prisma.objects.update({ where: { id: object_id }, data: { status:0 }, }) } res.json(change); } </code></pre> <p><strong>I get this error <code>SyntaxError: Unexpected token o in JSON at position 1</code></strong></p> <p>Is there any better way to code the button or pass object_id without a JSON</p>
[ { "answer_id": 74536009, "author": "Art Bauer", "author_id": 8350191, "author_profile": "https://Stackoverflow.com/users/8350191", "pm_score": 0, "selected": false, "text": "// index.ts\nexport * from './MessageList';\nexport * from './MessageSent';\n" }, { "answer_id": 74536013, "author": "Moussa Bistami", "author_id": 15628525, "author_profile": "https://Stackoverflow.com/users/15628525", "pm_score": 0, "selected": false, "text": "index.ts index.ts export * from './MessageList.tsx';\nexport * from './MessageSent.tsx';\n" }, { "answer_id": 74536043, "author": "DanH", "author_id": 15197189, "author_profile": "https://Stackoverflow.com/users/15197189", "pm_score": 1, "selected": false, "text": "import MessageSent from \"./components/MessageSent\"\nimport MessageList from \"./components/MessageList\"\n import MessageSent from './MessageSent'\nimport MessageList from './MessageList'\nexport { MessageSent, MessageList }\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12618447/" ]
74,535,921
<p>Here is my data:</p> <pre><code>df1 &lt;- fread(' id , date1 , date2 id_0001 , 2017-01-01, 2017-01-05 id_0002 , 2017-01-02, 2017-01-08 id_0003 , 2017-01-04, 2017-01-07 ') df2&lt;- fread(' date , value 2017-01-01, 1 2017-01-02, 2 2017-01-03, 5 2017-01-04, 5 2017-01-05, 5 2017-01-06, 3 2017-01-07, 4 2017-01-08, 7 2017-01-09, 5 2017-01-10, 1 2017-01-11, 5 ') </code></pre> <p>I want to summarize (get mean) the <code>value</code> from <code>df2</code> by each <code>id</code> from <code>df1</code> witinin the range between rowwise <code>date1</code> and <code>date2</code>.</p> <p>The result is like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>date1</th> <th>date2</th> <th>value</th> </tr> </thead> <tbody> <tr> <td>id_0001</td> <td>2017-01-01</td> <td>2017-01-05</td> <td><code>mean(c(1,2,5,5,5))</code></td> </tr> <tr> <td>id_0002</td> <td>2017-01-02</td> <td>2017-01-08</td> <td><code>mean(c(2,5,5,5,3,4,7))</code></td> </tr> <tr> <td>id_0003</td> <td>2017-01-04</td> <td>2017-01-07</td> <td><code>mean(c(5,5,3,4))</code></td> </tr> </tbody> </table> </div> <p>I know that I can extend <code>id</code> by <code>date1</code> and <code>date2</code> in <code>df1</code> and perform <code>left_join</code> by <code>dates</code> to <code>df2</code> and then <code>summarize</code>. However, as data volume increases, r cannot handle vectors of a certain size when further analysis is needed. Is there a <code>data.table</code> way of doing this inter-dataframe summary?</p>
[ { "answer_id": 74536218, "author": "Maël", "author_id": 13460602, "author_profile": "https://Stackoverflow.com/users/13460602", "pm_score": 2, "selected": false, "text": "pmap between library(purrr)\nlibrary(dplyr)\ndf1 %>% \n mutate(mean = pmap(across(date1:date2), ~ mean(df2$value[between(df2$date, ..1, ..2)])))\n\n# id date1 date2 mean\n#1: id_0001 2017-01-01 2017-01-05 3.6\n#2: id_0002 2017-01-02 2017-01-08 4.428571\n#3: id_0003 2017-01-04 2017-01-07 4.25\n" }, { "answer_id": 74536219, "author": "arg0naut91", "author_id": 8389003, "author_profile": "https://Stackoverflow.com/users/8389003", "pm_score": 4, "selected": true, "text": "library(data.table)\n\ndf1[, value := df2[.SD, on = .(date >= date1, date <= date2), mean(value), by = .EACHI]$V1]\n df1\n\n id date1 date2 value\n1: id_0001 2017-01-01 2017-01-05 3.600000\n2: id_0002 2017-01-02 2017-01-08 4.428571\n3: id_0003 2017-01-04 2017-01-07 4.250000\n" }, { "answer_id": 74536227, "author": "zephryl", "author_id": 17303805, "author_profile": "https://Stackoverflow.com/users/17303805", "pm_score": 2, "selected": false, "text": "library(dplyr)\n\ndf1 %>% \n group_by(id) %>% \n mutate(value = mean(df2$value[df2$date >= date1 & df2$date <= date2])) %>% \n ungroup()\n # A tibble: 3 × 4\n id date1 date2 value\n <chr> <date> <date> <dbl>\n1 id_0001 2017-01-01 2017-01-05 3.6 \n2 id_0002 2017-01-02 2017-01-08 4.43\n3 id_0003 2017-01-04 2017-01-07 4.25\n sapply() id df1$value <- sapply(\n seq(nrow(df1)),\n \\(i) mean(df2$value[df2$date >= df1$date1[[i]] & df2$date <= df1$date2[[i]]])\n)\n id date1 date2 value\n1: id_0001 2017-01-01 2017-01-05 3.600000\n2: id_0002 2017-01-02 2017-01-08 4.428571\n3: id_0003 2017-01-04 2017-01-07 4.250000\n" }, { "answer_id": 74537878, "author": "B. Christian Kamgang", "author_id": 10848898, "author_profile": "https://Stackoverflow.com/users/10848898", "pm_score": 1, "selected": false, "text": "# Method 1\ndf1[, value := df2[date>=date1 & date<=date2, mean(value)], by=.(date1, date2)]\n\n# Method 2\ndf1[, value := df2[.BY, mean(value), on=.(date>=date1, date<=date2)], by=.(date1, date2)]\n\n\n id date1 date2 value\n <char> <IDat> <IDat> <num>\n1: id_0001 2017-01-01 2017-01-05 3.600000\n2: id_0002 2017-01-02 2017-01-08 4.428571\n3: id_0003 2017-01-04 2017-01-07 4.250000\n" }, { "answer_id": 74538300, "author": "ThomasIsCoding", "author_id": 12158757, "author_profile": "https://Stackoverflow.com/users/12158757", "pm_score": 0, "selected": false, "text": "non-equi join data.table df2[df1,\n on = .(date >= date1, date <= date2)\n][\n ,\n .(value = mean(value)), \n .(id, date1 = date, date2 = date.1)\n]\n id date1 date2 value\n1: id_0001 2017-01-01 2017-01-05 3.600000\n2: id_0002 2017-01-02 2017-01-08 4.428571\n3: id_0003 2017-01-04 2017-01-07 4.250000\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8188773/" ]
74,535,953
<p>I want to get count of form fields.</p> <p>Total count of fields and valid and invalid form fields. So I try with this function but getting this below error.</p> <p>Error I am getting below :</p> <pre><code>Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'AbstractControl&lt;any, any&gt;'. No index signature with a parameter of type 'string' was found on type 'AbstractControl&lt;any, any&gt;' </code></pre> <pre><code>const firstFormGroup = this.allFormGroup.controls['firstFormGroup']; const invalidArr = []; const validArr = []; for (const name in firstFormGroup) { if (firstFormGroup[name].status === 'INVALID') { // I am getting error on this line invalidArr.push(name); } else { validArr.push(name); } } console.log(`valid count : ${validArr.length}`) console.log(`invalid count : ${invalidArr.length}`) </code></pre>
[ { "answer_id": 74536158, "author": "RenokK", "author_id": 2377357, "author_profile": "https://Stackoverflow.com/users/2377357", "pm_score": 0, "selected": false, "text": "[key: string]: T keyof firstFormGroup[name as keyof AbstractControl].status === 'INVALID'\n keyof typeof T const firstFormGroup = this.allFormGroup.controls['firstFormGroup']; // this is your object\n\n[...]\nfirstFormGroup[name as keyof typeof firstFormGroup].status === 'INVALID'\n[...]\n" }, { "answer_id": 74536707, "author": "Louis-Eric Simard", "author_id": 715613, "author_profile": "https://Stackoverflow.com/users/715613", "pm_score": 2, "selected": true, "text": "const firstFormGroup = this.contactForm.controls['firstFormGroup'] as FormGroup;\n for (const name in firstFormGroup.controls)\n let item = firstFormGroup.get(name);\n const firstFormGroup = this.contactForm.controls['firstFormGroup'] as FormGroup;\nconst invalidArr = [];\nconst validArr = [];\nfor (const name in firstFormGroup.controls) {\n let item = firstFormGroup.get(name);\n if (item !== null) {\n if (item.status === 'INVALID') {\n invalidArr.push(name);\n } else {\n validArr.push(name);\n }\n }\n}\nconsole.log(`valid count : ${validArr.length}`)\nconsole.log(`invalid count : ${invalidArr.length}`)\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20200307/" ]
74,535,967
<p>So I have the following composable function:</p> <pre class="lang-kotlin prettyprint-override"><code>@Composable fun SearchResult() { if (searchInput.isNotEmpty()) { Column() { Text(&quot;Search Result!&quot;) } } } </code></pre> <p>Then I called the function from here:</p> <pre class="lang-kotlin prettyprint-override"><code>private fun updateContent() { setContent { ChemistryAssistantTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Column() { Title(&quot; Chemistry Assistant &quot;, &quot; Made by Saket Tamrakar &quot;) Column() { SearchElements() SearchResult() // Here //Options() } } } } } } </code></pre> <p>The issue here is that the function gets correctly called in the beginning, when I invoke <code>updateContent()</code> here:</p> <pre class="lang-kotlin prettyprint-override"><code>OutlinedTextField(value = input, placeholder = { Text(&quot;Search for any element!&quot;) }, onValueChange = { input = it searchInput = it.text updateContent() }) </code></pre> <p>Control does reach the function (at least according to what the debugger tells me), but still fails to execute the function body. <br><br> <strong>Any ideas?</strong></p>
[ { "answer_id": 74536068, "author": "Solved Games", "author_id": 18081244, "author_profile": "https://Stackoverflow.com/users/18081244", "pm_score": 0, "selected": false, "text": "searchInput @Composable\nfun SearchResult() {\n if (/*this one*/searchInput.isNotEmpty()) {\n Column() {\n Text(\"Search Result!\")\n }\n }\n}\n MainActivity" }, { "answer_id": 74546410, "author": "Hyzam", "author_id": 16102475, "author_profile": "https://Stackoverflow.com/users/16102475", "pm_score": 1, "selected": false, "text": "searchInput val searchInput by mutableStateOf(\"\")" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18081244/" ]
74,535,973
<p>I have a dataframe with price quotes for a variety of parts and makers. ~10k parts and 10 makers, so my dataset contains up to 100k rows, looking roughly like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Part</th> <th>Maker</th> <th>Price</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Alpha</td> <td>1.00</td> </tr> <tr> <td>2</td> <td>Alpha</td> <td>1.30</td> </tr> <tr> <td>3</td> <td>Alpha</td> <td>1.25</td> </tr> <tr> <td>1</td> <td>Bravo</td> <td>1.10</td> </tr> <tr> <td>2</td> <td>Bravo</td> <td>1.02</td> </tr> <tr> <td>3</td> <td>Bravo</td> <td>1.15</td> </tr> <tr> <td>4</td> <td>Bravo</td> <td>1.19</td> </tr> <tr> <td>1</td> <td>Charlie</td> <td>.99</td> </tr> <tr> <td>2</td> <td>Charlie</td> <td>1.10</td> </tr> <tr> <td>3</td> <td>Charlie</td> <td>1.12</td> </tr> <tr> <td>4</td> <td>Charlie</td> <td>1.19</td> </tr> </tbody> </table> </div> <p>I am wanting to return two dictionaries based on the best price, Part/Maker and Part/Price. My main issue is when two makers have the same best price.</p> <p>I want my result to end up like this:</p> <p>1:.99</p> <p>2:1.1</p> <p>3: 1.02</p> <p>4:1.19</p> <p>and the second one to be:</p> <p>1:Charlie</p> <p>2: Charlie</p> <p>3: Bravo</p> <p>4: [Bravo, Charlie]</p> <p>The first dictionary is easy. Second one is what I'm stuck on. Here's what I have so far:</p> <pre><code>winning_price_dict={} winning_mfg_dict={} for index, row in quote_df.iterrows(): if row['Part'] not in winning_price_dict: winning_price_dict[row['Part']] = row['Proposed Quote'] winning_mfg_dict[row['Part']] = list(row['Maker']) if winning_price_dict[row['Part']]&gt;row['Proposed Quote']: winning_price_dict[row['Part']] = row['Proposed Quote'] winning_mfg_dict[row['Part']] = row['Maker'] if winning_price_dict[row['Part']]==row['Proposed Quote']: winning_price_dict[row['Part']] = row['Proposed Quote'] winning_mfg_dict[row['Part']] = winning_mfg_dict[row['Part']].append(row['Maker']) #this is the only line that I don't believe works </code></pre> <p>When I run it as is, it says 'str' object has no attribute 'append'. However, I thought that it should be a list because of the list(row['Maker']) command.</p> <p>When I change the relevant lines to this:</p> <pre><code>for index, row in quote_df.iterrows(): if row['Part'] not in winning_price_dict: winning_mfg_dict[row['Part']] = list(row['Mfg']) if winning_price_dict[row['Part']]&gt;row['Proposed Quote']: winning_mfg_dict[row['Part']] = list(row[['Mfg']]) if winning_price_dict[row['Part']]==row['Proposed Quote']: winning_mfg_dict[row['Part']] = list(winning_mfg_dict[row['Part']]).append(row['Mfg']) </code></pre> <p>The winning_mfg_dict is all the part numbers and NoneType values, not the maker names.</p> <p>What do I need to change to get it to return the list of suitable makers?</p> <p>Thanks!</p>
[ { "answer_id": 74536068, "author": "Solved Games", "author_id": 18081244, "author_profile": "https://Stackoverflow.com/users/18081244", "pm_score": 0, "selected": false, "text": "searchInput @Composable\nfun SearchResult() {\n if (/*this one*/searchInput.isNotEmpty()) {\n Column() {\n Text(\"Search Result!\")\n }\n }\n}\n MainActivity" }, { "answer_id": 74546410, "author": "Hyzam", "author_id": 16102475, "author_profile": "https://Stackoverflow.com/users/16102475", "pm_score": 1, "selected": false, "text": "searchInput val searchInput by mutableStateOf(\"\")" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74535973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4039994/" ]
74,536,025
<p>I am trying to pull info from a log file but can not figure out how to limit the entries to include brackets and two digits in the bracket.</p> <p>The log file has entries similar to:</p> <pre><code>11/22/22 11:25:26 RandomUselessData12453: 053, Clen 24, Flen 25, Data: [00] Data: [00 01 23 45 03 15] </code></pre> <p>I need to pull only the section of <code>Data: [00]</code></p> <p>currently using <code>(?:^|\W)data:(.{5})</code></p> <p>it is pulling</p> <p>Data: [00]</p> <p>Data: [00]</p> <p>Data: [00 0</p> <p>Data: [00 0</p> <p>Full Code currently:</p> <pre><code>$LogRegexe = '(?:^|\W)data:(.{5})' $LogLocation = get-content &quot;C:\blah\log.log&quot; -Tail 80 $LogLocation | select-string $LogRegexe | foreach-object { $_.Matches.Value } | set-content &quot;C:\blah\log.log&quot; </code></pre>
[ { "answer_id": 74536120, "author": "Abraham Zinala", "author_id": 14903754, "author_profile": "https://Stackoverflow.com/users/14903754", "pm_score": 2, "selected": false, "text": "Data: [00] 'Data: \\[\\d{2}\\]' Select-String -Path \"C:\\blah\\log.log\" -Pattern 'Data: \\[\\d{2}\\]'| \n ForEach-Object -Process {\n $_.Matches.Value\n }\n Data: [00]\nData: [12]\n" }, { "answer_id": 74536811, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 3, "selected": true, "text": "\\bdata:\\s*\\[(\\d{2})]\n \\b (?:^|\\W) data: \\s* \\[ [ (\\d{2}) ] ]" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20531556/" ]
74,536,077
<p>I want to show error message like required error message for max input limit but using below code it work for required but not for maxlength . I also not to use ts file . Is there any way to achieve this. Thanks</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;form #featureForm="ngForm"&gt; &lt;mat-form-field class="featureInputForm" appearance="fill"&gt; &lt;mat-label&gt;Feature Namre&lt;/mat-label&gt; &lt;input matInput [(ngModel)]="featureName" required name="featureName" maxlength="64" (ngModelChange)="moduleNameChange($event)" /&gt; &lt;mat-error *ngIf="featureForm.controls['featureName']?.errors?.required"&gt;Feature Name is required.&lt;/mat-error&gt; &lt;mat-error *ngIf="featureForm.controls['featureName']?.errors?.maxlength"&gt;Maximum limit exceed.&lt;/mat-error&gt; &lt;/mat-form-field&gt; &lt;/form&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74536120, "author": "Abraham Zinala", "author_id": 14903754, "author_profile": "https://Stackoverflow.com/users/14903754", "pm_score": 2, "selected": false, "text": "Data: [00] 'Data: \\[\\d{2}\\]' Select-String -Path \"C:\\blah\\log.log\" -Pattern 'Data: \\[\\d{2}\\]'| \n ForEach-Object -Process {\n $_.Matches.Value\n }\n Data: [00]\nData: [12]\n" }, { "answer_id": 74536811, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 3, "selected": true, "text": "\\bdata:\\s*\\[(\\d{2})]\n \\b (?:^|\\W) data: \\s* \\[ [ (\\d{2}) ] ]" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20122571/" ]
74,536,093
<p>How can I schedule a task with Umbraco Cms. I would like to create scheduled emails with Umbraco 9.</p> <p>I have tried unsuccessfully to get a documentation that could help. Could you please help or refer me to a documentation</p>
[ { "answer_id": 74536120, "author": "Abraham Zinala", "author_id": 14903754, "author_profile": "https://Stackoverflow.com/users/14903754", "pm_score": 2, "selected": false, "text": "Data: [00] 'Data: \\[\\d{2}\\]' Select-String -Path \"C:\\blah\\log.log\" -Pattern 'Data: \\[\\d{2}\\]'| \n ForEach-Object -Process {\n $_.Matches.Value\n }\n Data: [00]\nData: [12]\n" }, { "answer_id": 74536811, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 3, "selected": true, "text": "\\bdata:\\s*\\[(\\d{2})]\n \\b (?:^|\\W) data: \\s* \\[ [ (\\d{2}) ] ]" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20281160/" ]
74,536,098
<p>I'm trying to write a PowerShell script to update a file inside of a zip file, as I need to automate this for a number of zips. My issue is that the file I need to update is inside a few directories inside the zip, such as:</p> <p>myZip.zip -&gt; dir1/dir2/file.txt</p> <p>I'm trying to use the command such as</p> <pre><code>Compress-Archive -Path .\file.txt -Update -DestinationPath .\myZip.zip </code></pre> <p>But when I run that, the file gets added to the root of the zip file, rather than into the dir1/dir2/ directory as I need it to.</p> <p>Is this possible?</p>
[ { "answer_id": 74547816, "author": "tboyle3", "author_id": 20574212, "author_profile": "https://Stackoverflow.com/users/20574212", "pm_score": 1, "selected": false, "text": "myZip.zip\n-> dir1\n-> -> dir2\n-> -> -> dir3\n-> -> -> -> myFile.txt\n dir1\n-> dir2\n-> -> dir3\n-> -> -> myFile.txt\n Compress-Archive -Path .\\dir1 -DestinationPath .\\myZip.zip -Update" }, { "answer_id": 74548151, "author": "Santiago Squarzon", "author_id": 15339544, "author_profile": "https://Stackoverflow.com/users/15339544", "pm_score": 0, "selected": false, "text": "ZipArchiveEntry Compress-Archive dir1/dir2/dir3/myFile.txt .GetEntry(..) using namespace System.IO\nusing namespace System.IO.Compression\n\nAdd-Type -AssemblyName System.IO.Compression\n\n$filestream = (Get-Item .\\myZip.zip).Open([FileMode]::Open)\n$ziparchive = [ZipArchive]::new($filestream, [ZipArchiveMode]::Update)\n# relative path of the ZipEntry must be precise here\n# ZipEntry path is relative, note the forward slashes are important\n$zipentry = $ziparchive.GetEntry('dir1/dir2/dir3/myFile.txt')\n$wrappedstream = $zipentry.Open()\n# this is the source file, used to replace the ZipEntry\n$copyStream = (Get-Item .\\file.txt).OpenRead()\n$copyStream.CopyTo($wrappedstream)\n$wrappedstream, $copyStream, $ziparchive, $filestream | ForEach-Object Dispose\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20574212/" ]